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 <chapter><para> 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 <?xml> prolog -def minixml_4(): +def test_minixml_4(): xml = """<?xml encoding="utf-8"?>\n<foo />\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 = ( ('<a></A>', '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 = '<a>' * 10001 xml_str += '</a>' * 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 = """<?xml version="2.0"?> <TestXML>Value</TestXML> """ - 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 = """<?xml version="2.0"?> <TestXML>Value</TestXML> """ - 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("""<PAMDataset> @@ -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('<HistCounts>6000000000|') < 0: - gdaltest.post_reason('fail') - print(aux_xml) - return 'fail' - - return 'success' + assert hist1 == hist2 + assert hist1[0] == 6000000000 + assert aux_xml.find('<HistCounts>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 = """<VRTDataset rasterXSize="20" rasterYSize="20"> <VRTRasterBand dataType="Byte" band="1" subClass="VRTDerivedRasterBand"> @@ -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') != ['<abc />\n']: - print(ds.GetMetadata('xml:ESRI')) - gdaltest.post_reason('did not get expected xml:ESRI metadata.') - return 'fail' + assert ds.GetMetadata('xml:ESRI') == ['<abc />\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') != ['<abc />\n']: - print(ds.GetMetadata('xml:ESRI')) - gdaltest.post_reason('did not get expected xml:ESRI metadata (cc).') - return 'fail' + assert ds.GetMetadata('xml:ESRI') == ['<abc />\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('<foo/>', '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] != '<foo/>': - print(md) - return 'fail' - - return 'success' + assert len(md) == 1 + assert md[0] == '<foo/>' ############################################################################### # 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("""<VRTDataset rasterXSize="20" rasterYSize="20"> @@ -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(""" <VRTDataset rasterXSize="20" rasterYSize="20"> @@ -641,9 +475,7 @@ def transformer_12(): </VRTDataset>""") 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(""" <VRTDataset rasterXSize="20" rasterYSize="20"> @@ -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(""" <VRTDataset rasterXSize="20" rasterYSize="20"> @@ -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('<MaxErrorForward>6.05</MaxErrorForward>') < 0 or \ - content.find('<MaxErrorReverse>0.1</MaxErrorReverse>') < 0 or \ - content.find('<MaxErrorForward>0.0001</MaxErrorForward>') < 0 or \ - content.find('<MaxErrorReverse>6.1</MaxErrorReverse>') < 0: - gdaltest.post_reason('fail') - print(content) - return 'fail' + assert (content.find('<MaxErrorForward>6.05</MaxErrorForward>') >= 0 and \ + content.find('<MaxErrorReverse>0.1</MaxErrorReverse>') >= 0 and \ + content.find('<MaxErrorForward>0.0001</MaxErrorForward>') >= 0 and \ + content.find('<MaxErrorReverse>6.1</MaxErrorReverse>') >= 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('<Histograms>') < 0: - gdaltest.post_reason('fail') - print(content) - return 'fail' + assert content.find('<Histograms>') >= 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('<Histograms>') < 0: - gdaltest.post_reason('fail') - print(content) - return 'fail' + assert content.find('<Histograms>') >= 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('<Histograms>') < 0: - gdaltest.post_reason('fail') - print(content) - return 'fail' + assert content.find('<Histograms>') >= 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("""<VRTDataset rasterXSize="9" rasterYSize="9"> <VRTRasterBand dataType="Byte" band="1"> @@ -630,17 +543,13 @@ def vrt_read_15(): </VRTDataset>""") 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("""<VRTDataset rasterXSize="9" rasterYSize="9"> <VRTRasterBand dataType="Byte" band="1"> @@ -662,17 +571,13 @@ def vrt_read_16(): </VRTDataset>""") 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("""<VRTDataset rasterXSize="9" rasterYSize="9"> <VRTRasterBand dataType="Byte" band="1"> @@ -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("""<VRTDataset rasterXSize="20" rasterYSize="20"> <VRTRasterBand dataType="Byte" band="1"> @@ -735,25 +632,19 @@ def vrt_read_19(): </VRTDataset>""") 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(): </VRTRasterBand> </VRTDataset>""") 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(): </VRTRasterBand> </VRTDataset>""") 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(): </VRTRasterBand> </VRTDataset>""") 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(): </SimpleSource> </VRTRasterBand> </VRTDataset>""") - 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("""<VRTDataset rasterXSize="20" rasterYSize="20"> <VRTRasterBand dataType="Byte" band="1"> @@ -983,22 +827,13 @@ def vrt_read_22(): </ComplexSource> </VRTRasterBand> </VRTDataset>""") - 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("""<VRTDataset rasterXSize="20" rasterYSize="20"> <VRTRasterBand dataType="Byte" band="1"> @@ -1012,42 +847,30 @@ def vrt_read_22(): </ComplexSource> </VRTRasterBand> </VRTDataset>""") - 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(): </VRTRasterBand> </VRTDataset>""") 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(): </VRTRasterBand> </VRTDataset>""") 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("""<VRTDataset rasterXSize="2000" rasterYSize="200"> <VRTRasterBand dataType="Byte" band="1"> @@ -1158,41 +964,23 @@ def vrt_read_25(): </VRTDataset>""") (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("""<VRTDataset rasterXSize="22" rasterYSize="22"> <VRTRasterBand dataType="Byte" band="1"> @@ -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('<VRTDataset rasterXSize="1 "rasterYSize="1"><VRTRasterBand band="-2147483648"><SimpleSource></SimpleSource></VRTRasterBand></VRTDataset>') - 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(): </VRTRasterBand> </VRTDataset>""" + 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("""<VRTDataset rasterXSize="2" rasterYSize="2"> <VRTRasterBand dataType="Byte" band="1"> @@ -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 <SrcMin> <SrcMax> in VRT file) -def vrtmisc_3(): +def test_vrtmisc_3(): ds = gdal.Open("""<VRTDataset rasterXSize="20" rasterYSize="20"> <VRTRasterBand dataType="Byte" band="1"> @@ -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", """<VRTDataset rasterXSize="1" rasterYSize="1"> @@ -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] != '<some_xml />\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] == '<some_xml />\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] != '<some_xml />\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] == '<some_xml />\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('<SourceFilename relativeToVRT="1">../data/byte.tif</SourceFilename>') < 0: - gdaltest.post_reason('fail') - return 'fail' - - return "success" + assert data.find('<SourceFilename relativeToVRT="1">../data/byte.tif</SourceFilename>') >= 0 ############################################################################### # Test set/delete nodata -def vrtmisc_12(): +def test_vrtmisc_12(): gdal.FileFromMemBuffer("/vsimem/vrtmisc_12.vrt", """<VRTDataset rasterXSize="1" rasterYSize="1"> @@ -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('<SrcRect xOff="0" yOff="0" xSize="123456789" ySize="1"') < 0 or \ - content.find('<DstRect xOff="0" yOff="0" xSize="123456789" ySize="1"') < 0: - gdaltest.post_reason('fail') - print(content) - return 'fail' + assert (content.find('<SrcRect xOff="0" yOff="0" xSize="123456789" ySize="1"') >= 0 and \ + content.find('<DstRect xOff="0" yOff="0" xSize="123456789" ySize="1"') >= 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('<SrcRect xOff="0" yOff="0" xSize="1" ySize="123456789"') < 0 or \ - content.find('<DstRect xOff="0" yOff="0" xSize="1" ySize="123456789"') < 0: - gdaltest.post_reason('fail') - print(content) - return 'fail' - - return "success" + assert (content.find('<SrcRect xOff="0" yOff="0" xSize="1" ySize="123456789"') >= 0 and \ + content.find('<DstRect xOff="0" yOff="0" xSize="1" ySize="123456789"') >= 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('<SrcRect xOff="0" yOff="0" xSize="952" ySize="1189"') < 0: - gdaltest.post_reason('fail') - print(content) - return 'fail' - if content.find('<DstRect xOff="0" yOff="0" xSize="952" ySize="1189"') < 0: - gdaltest.post_reason('fail') - print(content) - return 'fail' - if content.find('<SrcRect xOff="0" yOff="0" xSize="494" ySize="893"') < 0: - gdaltest.post_reason('fail') - print(content) - return 'fail' - if content.find('<DstRect xOff="1680" yOff="5922" xSize="494" ySize="893"') < 0: - gdaltest.post_reason('fail') - print(content) - return 'fail' + assert content.find('<SrcRect xOff="0" yOff="0" xSize="952" ySize="1189"') >= 0 + assert content.find('<DstRect xOff="0" yOff="0" xSize="952" ySize="1189"') >= 0 + assert content.find('<SrcRect xOff="0" yOff="0" xSize="494" ySize="893"') >= 0 + assert content.find('<DstRect xOff="1680" yOff="5922" xSize="494" ySize="893"') >= 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('<SourceFilename relativeToVRT="1">data/byte.tif</SourceFilename>') < 0 and \ - xml_vrt.find('<SourceFilename relativeToVRT="1">data\\byte.tif</SourceFilename>') < 0: - gdaltest.post_reason('fail') - print(xml_vrt) - return 'fail' - - return "success" + assert (xml_vrt.find('<SourceFilename relativeToVRT="1">data/byte.tif</SourceFilename>') >= 0 or \ + xml_vrt.find('<SourceFilename relativeToVRT="1">data\\byte.tif</SourceFilename>') >= 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('<GDALRasterAttributeTable tableType="thematic">') < 0: - gdaltest.post_reason('fail') - print(xml_vrt) - return 'fail' + assert xml_vrt.find('<GDALRasterAttributeTable tableType="thematic">') >= 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('<GDALRasterAttributeTable tableType="thematic">') < 0: - gdaltest.post_reason('fail') - print(xml_vrt) - return 'fail' + assert xml_vrt.find('<GDALRasterAttributeTable tableType="thematic">') >= 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, {}, """<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN"> @@ -500,31 +437,23 @@ def vsicurl_test_parse_html_filelist_apache(): </body></html>""") with webserver.install_http_handler(handler): fl = gdal.ReadDir('/vsicurl/http://localhost:%d/mydir' % gdaltest.webserver_port) - if fl != ['foo.tif', 'foo%20with%20space.tif']: - gdaltest.post_reason('fail') - print(fl) - return 'fail' + assert fl == ['foo.tif', 'foo%20with%20space.tif'] - if gdal.VSIStatL('/vsicurl/http://localhost:%d/mydir/foo%%20with%%20space.tif' % gdaltest.webserver_port, gdal.VSI_STAT_EXISTS_FLAG) is None: - gdaltest.post_reason('fail') - return 'fail' + assert gdal.VSIStatL('/vsicurl/http://localhost:%d/mydir/foo%%20with%%20space.tif' % gdaltest.webserver_port, gdal.VSI_STAT_EXISTS_FLAG) is not None handler = webserver.SequentialHandler() handler.add('HEAD', '/mydir/i_dont_exist', 404, {}) with webserver.install_http_handler(handler): - if gdal.VSIStatL('/vsicurl/http://localhost:%d/mydir/i_dont_exist' % gdaltest.webserver_port, gdal.VSI_STAT_EXISTS_FLAG) is not None: - gdaltest.post_reason('fail') - return 'fail' - - return 'success' + assert gdal.VSIStatL('/vsicurl/http://localhost:%d/mydir/i_dont_exist' % gdaltest.webserver_port, gdal.VSI_STAT_EXISTS_FLAG) is None + ############################################################################### -def vsicurl_stop_webserver(): +def test_vsicurl_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 @@ -532,36 +461,5 @@ def vsicurl_stop_webserver(): webserver.server_stop(gdaltest.webserver_process, gdaltest.webserver_port) - return 'success' - - -gdaltest_list = [vsicurl_1, - # vsicurl_2, - # vsicurl_3, - vsicurl_4, - vsicurl_5, - #vsicurl_6_disabled, - vsicurl_7, - # vsicurl_8, - vsicurl_9, - vsicurl_10, - vsicurl_11, - vsicurl_start_webserver, - vsicurl_test_redirect, - vsicurl_test_clear_cache, - vsicurl_test_retry, - vsicurl_test_fallback_from_head_to_get, - vsicurl_test_parse_html_filelist_apache, - vsicurl_stop_webserver] - -if __name__ == '__main__': - - if gdal.GetConfigOption('GDAL_RUN_SLOW_TESTS', '').upper() != 'NO': - print('Enabling slow tests as GDAL_RUN_SLOW_TESTS is not defined') - gdal.SetConfigOption('GDAL_RUN_SLOW_TESTS', 'YES') - - gdaltest.setup_run('vsicurl') - gdaltest.run_tests(gdaltest_list) - sys.exit(gdaltest.summarize()) diff --git a/autotest/gcore/vsicurl_streaming.py b/autotest/gcore/vsicurl_streaming.py index f5e2c0a759f4..089b5a138ccc 100755 --- a/autotest/gcore/vsicurl_streaming.py +++ b/autotest/gcore/vsicurl_streaming.py @@ -28,126 +28,95 @@ # DEALINGS IN THE SOFTWARE. ############################################################################### -import sys import time from osgeo import gdal -sys.path.append('../pymod') import gdaltest +import pytest ############################################################################### # -def vsicurl_streaming_1(): +def test_vsicurl_streaming_1(): drv = gdal.GetDriverByName('HTTP') if drv is None: - return 'skip' + pytest.skip() gdal.SetConfigOption('GDAL_HTTP_CONNECTTIMEOUT', '5') fp = gdal.VSIFOpenL('/vsicurl_streaming/http://download.osgeo.org/gdal/data/usgsdem/cded/114p01_0100_deme.dem', 'rb') gdal.SetConfigOption('GDAL_HTTP_CONNECTTIMEOUT', None) if fp is None: if gdaltest.gdalurlopen('http://download.osgeo.org/gdal/data/usgsdem/cded/114p01_0100_deme.dem', timeout=4) is None: - print('cannot open URL') - return 'skip' - gdaltest.post_reason('fail') - return 'fail' + pytest.skip('cannot open URL') + pytest.fail() if gdal.VSIFTellL(fp) != 0: - gdaltest.post_reason('fail') gdal.VSIFCloseL(fp) - return 'fail' + pytest.fail() data = gdal.VSIFReadL(1, 50, fp) if data.decode('ascii') != ' 114p01DEMe Base Ma': - gdaltest.post_reason('fail') gdal.VSIFCloseL(fp) - return 'fail' + pytest.fail() if gdal.VSIFTellL(fp) != 50: - gdaltest.post_reason('fail') gdal.VSIFCloseL(fp) - return 'fail' + pytest.fail() gdal.VSIFSeekL(fp, 0, 0) if gdal.VSIFTellL(fp) != 0: - gdaltest.post_reason('fail') gdal.VSIFCloseL(fp) - return 'fail' + pytest.fail() data = gdal.VSIFReadL(1, 50, fp) if data.decode('ascii') != ' 114p01DEMe Base Ma': - gdaltest.post_reason('fail') gdal.VSIFCloseL(fp) - return 'fail' + pytest.fail() if gdal.VSIFTellL(fp) != 50: - gdaltest.post_reason('fail') gdal.VSIFCloseL(fp) - return 'fail' + pytest.fail() time.sleep(0.5) gdal.VSIFSeekL(fp, 2001, 0) data_2001 = gdal.VSIFReadL(1, 20, fp) if data_2001.decode('ascii') != '7-32767-32767-32767-': - print(data_2001) - gdaltest.post_reason('fail') gdal.VSIFCloseL(fp) - return 'fail' + pytest.fail(data_2001) if gdal.VSIFTellL(fp) != 2001 + 20: - gdaltest.post_reason('fail') gdal.VSIFCloseL(fp) - return 'fail' + pytest.fail() gdal.VSIFSeekL(fp, 0, 2) if gdal.VSIFTellL(fp) != 9839616: - gdaltest.post_reason('fail') gdal.VSIFCloseL(fp) - return 'fail' + pytest.fail() nRet = len(gdal.VSIFReadL(1, 10, fp)) if nRet != 0: - gdaltest.post_reason('fail') gdal.VSIFCloseL(fp) - return 'fail' + pytest.fail() gdal.VSIFSeekL(fp, 2001, 0) data_2001_2 = gdal.VSIFReadL(1, 20, fp) if gdal.VSIFTellL(fp) != 2001 + 20: - gdaltest.post_reason('fail') gdal.VSIFCloseL(fp) - return 'fail' + pytest.fail() if data_2001 != data_2001_2: - gdaltest.post_reason('fail') gdal.VSIFCloseL(fp) - return 'fail' + pytest.fail() gdal.VSIFSeekL(fp, 1024 * 1024 + 100, 0) data = gdal.VSIFReadL(1, 20, fp) if data.decode('ascii') != '67-32767-32767-32767': - print(data) - gdaltest.post_reason('fail') gdal.VSIFCloseL(fp) - return 'fail' + pytest.fail(data) if gdal.VSIFTellL(fp) != 1024 * 1024 + 100 + 20: - gdaltest.post_reason('fail') gdal.VSIFCloseL(fp) - return 'fail' + pytest.fail() gdal.VSIFCloseL(fp) - return 'success' -gdaltest_list = [vsicurl_streaming_1] - -if __name__ == '__main__': - - gdal.SetConfigOption('GDAL_RUN_SLOW_TESTS', 'YES') - - gdaltest.setup_run('vsicurl_streaming') - - gdaltest.run_tests(gdaltest_list) - - sys.exit(gdaltest.summarize()) diff --git a/autotest/gcore/vsifile.py b/autotest/gcore/vsifile.py index 62e46fe7ed94..e202c856885d 100755 --- a/autotest/gcore/vsifile.py +++ b/autotest/gcore/vsifile.py @@ -33,9 +33,9 @@ import time from osgeo import gdal -sys.path.append('../pymod') import gdaltest +import pytest ############################################################################### # Generic test @@ -46,69 +46,38 @@ def vsifile_generic(filename): start_time = time.time() fp = gdal.VSIFOpenL(filename, 'wb+') - if fp is None: - gdaltest.post_reason('failure') - return 'fail' + assert fp is not None - if gdal.VSIFWriteL('0123456789', 1, 10, fp) != 10: - gdaltest.post_reason('failure') - return 'fail' + assert gdal.VSIFWriteL('0123456789', 1, 10, fp) == 10 - if gdal.VSIFFlushL(fp) != 0: - gdaltest.post_reason('failure') - return 'fail' + assert gdal.VSIFFlushL(fp) == 0 - if gdal.VSIFTruncateL(fp, 20) != 0: - gdaltest.post_reason('failure') - return 'fail' + assert gdal.VSIFTruncateL(fp, 20) == 0 - if gdal.VSIFTellL(fp) != 10: - gdaltest.post_reason('failure') - return 'fail' + assert gdal.VSIFTellL(fp) == 10 - if gdal.VSIFTruncateL(fp, 5) != 0: - gdaltest.post_reason('failure') - return 'fail' + assert gdal.VSIFTruncateL(fp, 5) == 0 - if gdal.VSIFTellL(fp) != 10: - gdaltest.post_reason('failure') - return 'fail' + assert gdal.VSIFTellL(fp) == 10 - if gdal.VSIFSeekL(fp, 0, 2) != 0: - gdaltest.post_reason('failure') - return 'fail' + assert gdal.VSIFSeekL(fp, 0, 2) == 0 - if gdal.VSIFTellL(fp) != 5: - gdaltest.post_reason('failure') - return 'fail' + assert gdal.VSIFTellL(fp) == 5 gdal.VSIFWriteL('XX', 1, 2, fp) gdal.VSIFCloseL(fp) statBuf = gdal.VSIStatL(filename, gdal.VSI_STAT_EXISTS_FLAG | gdal.VSI_STAT_NATURE_FLAG | gdal.VSI_STAT_SIZE_FLAG) - if statBuf.size != 7: - gdaltest.post_reason('failure') - print(statBuf.size) - return 'fail' - if abs(start_time - statBuf.mtime) > 2: - gdaltest.post_reason('failure') - print(statBuf.mtime) - return 'fail' + assert statBuf.size == 7 + assert abs(start_time - statBuf.mtime) <= 2 fp = gdal.VSIFOpenL(filename, 'rb') buf = gdal.VSIFReadL(1, 7, fp) - if gdal.VSIFWriteL('a', 1, 1, fp) != 0: - gdaltest.post_reason('fail') - return 'fail' - if gdal.VSIFTruncateL(fp, 0) == 0: - gdaltest.post_reason('fail') - return 'fail' + assert gdal.VSIFWriteL('a', 1, 1, fp) == 0 + assert gdal.VSIFTruncateL(fp, 0) != 0 gdal.VSIFCloseL(fp) - if buf.decode('ascii') != '01234XX': - gdaltest.post_reason('failure') - print(buf.decode('ascii')) - return 'fail' + assert buf.decode('ascii') == '01234XX' # Test append mode on existing file fp = gdal.VSIFOpenL(filename, 'ab') @@ -116,19 +85,12 @@ def vsifile_generic(filename): gdal.VSIFCloseL(fp) statBuf = gdal.VSIStatL(filename, gdal.VSI_STAT_EXISTS_FLAG | gdal.VSI_STAT_NATURE_FLAG | gdal.VSI_STAT_SIZE_FLAG) - if statBuf.size != 9: - gdaltest.post_reason('failure') - print(statBuf.size) - return 'fail' + assert statBuf.size == 9 - if gdal.Unlink(filename) != 0: - gdaltest.post_reason('failure') - return 'fail' + assert gdal.Unlink(filename) == 0 statBuf = gdal.VSIStatL(filename, gdal.VSI_STAT_EXISTS_FLAG) - if statBuf is not None: - gdaltest.post_reason('failure') - return 'fail' + assert statBuf is None # Test append mode on non existing file fp = gdal.VSIFOpenL(filename, 'ab') @@ -136,46 +98,39 @@ def vsifile_generic(filename): gdal.VSIFCloseL(fp) statBuf = gdal.VSIStatL(filename, gdal.VSI_STAT_EXISTS_FLAG | gdal.VSI_STAT_NATURE_FLAG | gdal.VSI_STAT_SIZE_FLAG) - if statBuf.size != 2: - gdaltest.post_reason('failure') - print(statBuf.size) - return 'fail' + assert statBuf.size == 2 - if gdal.Unlink(filename) != 0: - gdaltest.post_reason('failure') - return 'fail' - - return 'success' + assert gdal.Unlink(filename) == 0 ############################################################################### # Test /vsimem -def vsifile_1(): +def test_vsifile_1(): return vsifile_generic('/vsimem/vsifile_1.bin') ############################################################################### # Test regular file system -def vsifile_2(): +def test_vsifile_2(): ret = vsifile_generic('tmp/vsifile_2.bin') if ret != 'success' and gdaltest.skip_on_travis(): # FIXME # Fails on Travis with 17592186044423 (which is 0x10 00 00 00 00 07 instead of 7) at line 63 # Looks like a 32/64bit issue with Python bindings of VSIStatL() - return 'skip' + pytest.skip() return ret ############################################################################### # Test ftruncate >= 32 bit -def vsifile_3(): +def test_vsifile_3(): if not gdaltest.filesystem_supports_sparse_files('tmp'): - return 'skip' + pytest.skip() filename = 'tmp/vsifile_3' @@ -184,55 +139,43 @@ def vsifile_3(): gdal.VSIFSeekL(fp, 0, 2) pos = gdal.VSIFTellL(fp) if pos != 10 * 1024 * 1024 * 1024: - gdaltest.post_reason('failure') gdal.VSIFCloseL(fp) gdal.Unlink(filename) - print(pos) - return 'fail' + pytest.fail(pos) gdal.VSIFSeekL(fp, 0, 0) gdal.VSIFSeekL(fp, pos, 0) pos = gdal.VSIFTellL(fp) if pos != 10 * 1024 * 1024 * 1024: - gdaltest.post_reason('failure') gdal.VSIFCloseL(fp) gdal.Unlink(filename) - print(pos) - return 'fail' + pytest.fail(pos) gdal.VSIFCloseL(fp) statBuf = gdal.VSIStatL(filename, gdal.VSI_STAT_EXISTS_FLAG | gdal.VSI_STAT_NATURE_FLAG | gdal.VSI_STAT_SIZE_FLAG) gdal.Unlink(filename) - if statBuf.size != 10 * 1024 * 1024 * 1024: - gdaltest.post_reason('failure') - print(statBuf.size) - return 'fail' - - return 'success' + assert statBuf.size == 10 * 1024 * 1024 * 1024 ############################################################################### # Test fix for #4583 (short reads) -def vsifile_4(): +def test_vsifile_4(): fp = gdal.VSIFOpenL('vsifile.py', 'rb') data = gdal.VSIFReadL(1000000, 1, fp) # print(len(data)) gdal.VSIFSeekL(fp, 0, 0) data = gdal.VSIFReadL(1, 1000000, fp) - if not data: - return 'fail' + assert data gdal.VSIFCloseL(fp) - return 'success' - ############################################################################### # Test vsicache -def vsifile_5(): +def test_vsifile_5(): fp = gdal.VSIFOpenL('tmp/vsifile_5.bin', 'wb') ref_data = ''.join(['%08X' % i for i in range(5 * 32768)]) @@ -253,48 +196,42 @@ def vsifile_5(): gdal.VSIFSeekL(fp, 50000, 0) if gdal.VSIFTellL(fp) != 50000: - gdaltest.post_reason('fail') gdal.SetConfigOption('VSI_CACHE_SIZE', None) gdal.SetConfigOption('VSI_CACHE', None) - return 'fail' + pytest.fail() gdal.VSIFSeekL(fp, 50000, 1) if gdal.VSIFTellL(fp) != 100000: - gdaltest.post_reason('fail') gdal.SetConfigOption('VSI_CACHE_SIZE', None) gdal.SetConfigOption('VSI_CACHE', None) - return 'fail' + pytest.fail() gdal.VSIFSeekL(fp, 0, 2) if gdal.VSIFTellL(fp) != 5 * 32768 * 8: - gdaltest.post_reason('fail') gdal.SetConfigOption('VSI_CACHE_SIZE', None) gdal.SetConfigOption('VSI_CACHE', None) - return 'fail' + pytest.fail() gdal.VSIFReadL(1, 1, fp) gdal.VSIFSeekL(fp, 0, 0) data = gdal.VSIFReadL(1, 3 * 32768, fp) if data.decode('ascii') != ref_data[0:3 * 32768]: - gdaltest.post_reason('fail') gdal.SetConfigOption('VSI_CACHE_SIZE', None) gdal.SetConfigOption('VSI_CACHE', None) - return 'fail' + pytest.fail() gdal.VSIFSeekL(fp, 16384, 0) data = gdal.VSIFReadL(1, 5 * 32768, fp) if data.decode('ascii') != ref_data[16384:16384 + 5 * 32768]: - gdaltest.post_reason('fail') gdal.SetConfigOption('VSI_CACHE_SIZE', None) gdal.SetConfigOption('VSI_CACHE', None) - return 'fail' + pytest.fail() data = gdal.VSIFReadL(1, 50 * 32768, fp) if data[0:1130496].decode('ascii') != ref_data[16384 + 5 * 32768:]: - gdaltest.post_reason('fail') gdal.SetConfigOption('VSI_CACHE_SIZE', None) gdal.SetConfigOption('VSI_CACHE', None) - return 'fail' + pytest.fail() gdal.VSIFCloseL(fp) @@ -302,16 +239,14 @@ def vsifile_5(): gdal.SetConfigOption('VSI_CACHE', None) gdal.Unlink('tmp/vsifile_5.bin') - return 'success' - ############################################################################### # Test vsicache above 2 GB -def vsifile_6(): +def test_vsifile_6(): if not gdaltest.filesystem_supports_sparse_files('tmp'): - return 'skip' + pytest.skip() offset = 4 * 1024 * 1024 * 1024 @@ -327,9 +262,7 @@ def vsifile_6(): got_data = gdal.VSIFReadL(1, len(ref_data), fp) gdal.VSIFCloseL(fp) - if ref_data != got_data: - print(got_data) - return 'fail' + assert ref_data == got_data # Real test now gdal.SetConfigOption('VSI_CACHE', 'YES') @@ -339,102 +272,68 @@ def vsifile_6(): got_data = gdal.VSIFReadL(1, len(ref_data), fp) gdal.VSIFCloseL(fp) - if ref_data != got_data: - print(got_data) - return 'fail' + assert ref_data == got_data gdal.Unlink('tmp/vsifile_6.bin') - return 'success' - ############################################################################### # Test limit cases on /vsimem -def vsifile_7(): +def test_vsifile_7(): if gdal.GetConfigOption('SKIP_MEM_INTENSIVE_TEST') is not None: - return 'skip' + pytest.skip() # Test extending file beyond reasonable limits in write mode fp = gdal.VSIFOpenL('/vsimem/vsifile_7.bin', 'wb') - if gdal.VSIFSeekL(fp, 0x7FFFFFFFFFFFFFFF, 0) != 0: - gdaltest.post_reason('fail') - return 'fail' - if gdal.VSIStatL('/vsimem/vsifile_7.bin').size != 0: - gdaltest.post_reason('fail') - return 'fail' + assert gdal.VSIFSeekL(fp, 0x7FFFFFFFFFFFFFFF, 0) == 0 + assert gdal.VSIStatL('/vsimem/vsifile_7.bin').size == 0 gdal.PushErrorHandler() ret = gdal.VSIFWriteL('a', 1, 1, fp) gdal.PopErrorHandler() - if ret != 0: - gdaltest.post_reason('fail') - return 'fail' - if gdal.VSIStatL('/vsimem/vsifile_7.bin').size != 0: - gdaltest.post_reason('fail') - return 'fail' + assert ret == 0 + assert gdal.VSIStatL('/vsimem/vsifile_7.bin').size == 0 gdal.VSIFCloseL(fp) # Test seeking beyond file size in read-only mode fp = gdal.VSIFOpenL('/vsimem/vsifile_7.bin', 'rb') - if gdal.VSIFSeekL(fp, 0x7FFFFFFFFFFFFFFF, 0) != 0: - gdaltest.post_reason('fail') - return 'fail' - if gdal.VSIFEofL(fp) != 0: - gdaltest.post_reason('fail') - return 'fail' - if gdal.VSIFTellL(fp) != 0x7FFFFFFFFFFFFFFF: - gdaltest.post_reason('fail') - return 'fail' - if gdal.VSIFReadL(1, 1, fp): - gdaltest.post_reason('fail') - return 'fail' - if gdal.VSIFEofL(fp) != 1: - gdaltest.post_reason('fail') - return 'fail' + assert gdal.VSIFSeekL(fp, 0x7FFFFFFFFFFFFFFF, 0) == 0 + assert gdal.VSIFEofL(fp) == 0 + assert gdal.VSIFTellL(fp) == 0x7FFFFFFFFFFFFFFF + assert not gdal.VSIFReadL(1, 1, fp) + assert gdal.VSIFEofL(fp) == 1 gdal.VSIFCloseL(fp) gdal.Unlink('/vsimem/vsifile_7.bin') - return 'success' - ############################################################################### # Test renaming directory in /vsimem -def vsifile_8(): +def test_vsifile_8(): # octal 0666 = decimal 438 gdal.Mkdir('/vsimem/mydir', 438) fp = gdal.VSIFOpenL('/vsimem/mydir/a', 'wb') gdal.VSIFCloseL(fp) gdal.Rename('/vsimem/mydir', '/vsimem/newdir'.encode('ascii').decode('ascii')) - if gdal.VSIStatL('/vsimem/newdir') is None: - gdaltest.post_reason('fail') - return 'fail' - if gdal.VSIStatL('/vsimem/newdir/a') is None: - gdaltest.post_reason('fail') - return 'fail' + assert gdal.VSIStatL('/vsimem/newdir') is not None + assert gdal.VSIStatL('/vsimem/newdir/a') is not None gdal.Unlink('/vsimem/newdir/a') gdal.Rmdir('/vsimem/newdir') - return 'success' - ############################################################################### # Test ReadDir() -def vsifile_9(): +def test_vsifile_9(): lst = gdal.ReadDir('.') - if len(lst) < 4: - gdaltest.post_reason('fail') - return 'fail' + assert len(lst) >= 4 # Test truncation lst_truncated = gdal.ReadDir('.', int(len(lst) / 2)) - if len(lst_truncated) <= int(len(lst) / 2): - gdaltest.post_reason('fail') - return 'fail' + assert len(lst_truncated) > int(len(lst) / 2) gdal.Mkdir('/vsimem/mydir', 438) for i in range(10): @@ -442,26 +341,20 @@ def vsifile_9(): gdal.VSIFCloseL(fp) lst = gdal.ReadDir('/vsimem/mydir') - if len(lst) < 4: - gdaltest.post_reason('fail') - return 'fail' + assert len(lst) >= 4 # Test truncation lst_truncated = gdal.ReadDir('/vsimem/mydir', int(len(lst) / 2)) - if len(lst_truncated) <= int(len(lst) / 2): - gdaltest.post_reason('fail') - return 'fail' + assert len(lst_truncated) > int(len(lst) / 2) for i in range(10): gdal.Unlink('/vsimem/mydir/%d' % i) gdal.Rmdir('/vsimem/mydir') - return 'success' - ############################################################################### # Test fuzzer friendly archive -def vsifile_10(): +def test_vsifile_10(): gdal.FileFromMemBuffer('/vsimem/vsifile_10.tar', """FUZZER_FRIENDLY_ARCHIVE @@ -520,67 +413,41 @@ def vsifile_10(): contents = gdal.ReadDir('/vsitar//vsimem/vsifile_10.tar') if contents is None: gdal.Unlink('/vsimem/vsifile_10.tar') - return 'skip' - if contents != ['test.txt', 'huge.txt', 'small.txt']: - gdaltest.post_reason('fail') - print(contents) - return 'fail' - if gdal.VSIStatL('/vsitar//vsimem/vsifile_10.tar/test.txt').size != 3: - gdaltest.post_reason('fail') - print(gdal.VSIStatL('/vsitar//vsimem/vsifile_10.tar/test.txt').size) - return 'fail' - if gdal.VSIStatL('/vsitar//vsimem/vsifile_10.tar/huge.txt').size != 3888: - gdaltest.post_reason('fail') - print(gdal.VSIStatL('/vsitar//vsimem/vsifile_10.tar/huge.txt').size) - return 'fail' - if gdal.VSIStatL('/vsitar//vsimem/vsifile_10.tar/small.txt').size != 1: - gdaltest.post_reason('fail') - print(gdal.VSIStatL('/vsitar//vsimem/vsifile_10.tar/small.txt').size) - return 'fail' + pytest.skip() + assert contents == ['test.txt', 'huge.txt', 'small.txt'] + assert gdal.VSIStatL('/vsitar//vsimem/vsifile_10.tar/test.txt').size == 3 + assert gdal.VSIStatL('/vsitar//vsimem/vsifile_10.tar/huge.txt').size == 3888 + assert gdal.VSIStatL('/vsitar//vsimem/vsifile_10.tar/small.txt').size == 1 gdal.FileFromMemBuffer('/vsimem/vsifile_10.tar', """FUZZER_FRIENDLY_ARCHIVE ***NEWFILE***:x abc""") contents = gdal.ReadDir('/vsitar//vsimem/vsifile_10.tar') - if contents != ['x']: - gdaltest.post_reason('fail') - print(contents) - return 'fail' + assert contents == ['x'] gdal.FileFromMemBuffer('/vsimem/vsifile_10.tar', """FUZZER_FRIENDLY_ARCHIVE ***NEWFILE***:x abc***NEWFILE***:""") contents = gdal.ReadDir('/vsitar//vsimem/vsifile_10.tar') - if contents != ['x']: - gdaltest.post_reason('fail') - print(contents) - return 'fail' + assert contents == ['x'] gdal.Unlink('/vsimem/vsifile_10.tar') - return 'success' - ############################################################################### # Test generic Truncate implementation for file extension -def vsifile_11(): +def test_vsifile_11(): f = gdal.VSIFOpenL('/vsimem/vsifile_11', 'wb') gdal.VSIFCloseL(f) f = gdal.VSIFOpenL('/vsisubfile/0_,/vsimem/vsifile_11', 'wb') gdal.VSIFWriteL('0123456789', 1, 10, f) - if gdal.VSIFTruncateL(f, 10 + 4096 + 2) != 0: - gdaltest.post_reason('fail') - return 'fail' - if gdal.VSIFTellL(f) != 10: - gdaltest.post_reason('fail') - return 'fail' - if gdal.VSIFTruncateL(f, 0) != -1: - gdaltest.post_reason('fail') - return 'fail' + assert gdal.VSIFTruncateL(f, 10 + 4096 + 2) == 0 + assert gdal.VSIFTellL(f) == 10 + assert gdal.VSIFTruncateL(f, 0) == -1 gdal.VSIFCloseL(f) f = gdal.VSIFOpenL('/vsimem/vsifile_11', 'rb') @@ -588,58 +455,43 @@ def vsifile_11(): gdal.VSIFCloseL(f) import struct data = struct.unpack('B' * len(data), data) - if data[0] != 48 or data[9] != 57 or data[10] != 0 or data[10 + 4096 + 2 - 1] != 0: - gdaltest.post_reason('fail') - print(data) - return 'fail' + assert data[0] == 48 and data[9] == 57 and data[10] == 0 and data[10 + 4096 + 2 - 1] == 0 gdal.Unlink('/vsimem/vsifile_11') - return 'success' - ############################################################################### # Test regular file system sparse file support -def vsifile_12(): +def test_vsifile_12(): target_dir = 'tmp' if gdal.VSISupportsSparseFiles(target_dir) == 0: - return 'skip' + pytest.skip() # Minimum value to make it work on NTFS block_size = 65536 f = gdal.VSIFOpenL(target_dir + '/vsifile_12', 'wb') gdal.VSIFWriteL('a', 1, 1, f) - if gdal.VSIFTruncateL(f, block_size * 2) != 0: - gdaltest.post_reason('fail') - return 'fail' + assert gdal.VSIFTruncateL(f, block_size * 2) == 0 ret = gdal.VSIFGetRangeStatusL(f, 0, 1) # We could get unknown on nfs if ret == gdal.VSI_RANGE_STATUS_UNKNOWN: print('Range status unknown') else: - if ret != gdal.VSI_RANGE_STATUS_DATA: - gdaltest.post_reason('fail') - print(ret) - return 'fail' + assert ret == gdal.VSI_RANGE_STATUS_DATA ret = gdal.VSIFGetRangeStatusL(f, block_size * 2 - 1, 1) - if ret != gdal.VSI_RANGE_STATUS_HOLE: - gdaltest.post_reason('fail') - print(ret) - return 'fail' + assert ret == gdal.VSI_RANGE_STATUS_HOLE gdal.VSIFCloseL(f) gdal.Unlink(target_dir + '/vsifile_12') - return 'success' - ############################################################################### # Test reading filename with prefixes without terminating slash -def vsifile_13(): +def test_vsifile_13(): gdal.VSIFOpenL('/vsigzip', 'rb') gdal.VSIFOpenL('/vsizip', 'rb') @@ -670,65 +522,48 @@ def vsifile_13(): gdal.VSIStatL('/vsistdin') gdal.VSIStatL('/vsistdout') - return 'success' - ############################################################################### # Check performance issue (https://bugs.chromium.org/p/oss-fuzz/issues/detail?id=1673) -def vsifile_14(): +def test_vsifile_14(): with gdaltest.error_handler(): gdal.VSIFOpenL('/vsitar//vsitar//vsitar//vsitar//vsitar//vsitar//vsitar//vsitar/a.tgzb.tgzc.tgzd.tgze.tgzf.tgz.h.tgz.i.tgz', 'rb') - return 'success' - + ############################################################################### # Test issue with Eof() not detecting end of corrupted gzip stream (#6944) -def vsifile_15(): +def test_vsifile_15(): fp = gdal.VSIFOpenL('/vsigzip/data/corrupted_z_buf_error.gz', 'rb') - if fp is None: - return 'fail' + assert fp is not None file_len = 0 while not gdal.VSIFEofL(fp): with gdaltest.error_handler(): file_len += len(gdal.VSIFReadL(1, 4, fp)) - if file_len != 6469: - gdaltest.post_reason('fail') - return 'fail' + assert file_len == 6469 with gdaltest.error_handler(): file_len += len(gdal.VSIFReadL(1, 4, fp)) - if file_len != 6469: - gdaltest.post_reason('fail') - return 'fail' + assert file_len == 6469 with gdaltest.error_handler(): - if gdal.VSIFSeekL(fp, 0, 2) == 0: - gdaltest.post_reason('fail') - return 'fail' + assert gdal.VSIFSeekL(fp, 0, 2) != 0 - if gdal.VSIFSeekL(fp, 0, 0) != 0: - gdaltest.post_reason('fail') - return 'fail' + assert gdal.VSIFSeekL(fp, 0, 0) == 0 len_read = len(gdal.VSIFReadL(1, file_len, fp)) - if len_read != file_len: - gdaltest.post_reason('fail') - print(len_read) - return 'fail' + assert len_read == file_len gdal.VSIFCloseL(fp) - return 'success' - ############################################################################### # Test failed gdal.Rename() with exceptions enabled -def vsifile_16(): +def test_vsifile_16(): old_val = gdal.GetUseExceptions() gdal.UseExceptions() @@ -745,75 +580,60 @@ def vsifile_16(): # Test gdal.GetActualURL() on a non-network based filesystem -def vsifile_17(): +def test_vsifile_17(): - if gdal.GetActualURL('foo') is not None: - gdaltest.post_reason('fail') - return 'fail' + assert gdal.GetActualURL('foo') is None - if gdal.GetSignedURL('foo') is not None: - gdaltest.post_reason('fail') - return 'fail' - - return 'success' + assert gdal.GetSignedURL('foo') is None ############################################################################### # Test gdal.GetFileSystemsPrefixes() -def vsifile_18(): +def test_vsifile_18(): prefixes = gdal.GetFileSystemsPrefixes() - if '/vsimem/' not in prefixes: - print(prefixes) - return 'fail' - - return 'success' + assert '/vsimem/' in prefixes ############################################################################### # Test gdal.GetFileSystemOptions() -def vsifile_19(): +def test_vsifile_19(): for prefix in gdal.GetFileSystemsPrefixes(): options = gdal.GetFileSystemOptions(prefix) # Check that the options is XML correct if options is not None: ret = gdal.ParseXMLString(options) - if ret is None: - gdaltest.post_reason('fail') - print(prefix, options) - return 'fail' - - return 'success' + assert ret is not None, (prefix, options) + ############################################################################### # Test gdal.VSIFReadL with None fp -def vsifile_20(): +def test_vsifile_20(): try: gdal.VSIFReadL(1, 1, None) except ValueError: - return 'success' + return - return 'fail' + pytest.fail() ############################################################################### # Test gdal.VSIGetMemFileBuffer_unsafe() and gdal.VSIFWriteL() reading buffers -def vsifile_21(): +def test_vsifile_21(): filename = '/vsimem/read.tif' filename_write = '/vsimem/write.tif' data = 'This is some data' vsifile = gdal.VSIFOpenL(filename, 'wb') - if gdal.VSIFWriteL(data, 1, len(data), vsifile) != len(data): - return 'fail' + assert gdal.VSIFWriteL(data, 1, len(data), vsifile) == len(data) gdal.VSIFCloseL(vsifile) vsifile = gdal.VSIFOpenL(filename, 'rb') @@ -822,74 +642,55 @@ def vsifile_21(): gdal.VSIFSeekL(vsifile, 0, 0) data_read = gdal.VSIFReadL(1, vsilen, vsifile) data_mem = gdal.VSIGetMemFileBuffer_unsafe(filename) - if data_read != data_mem[:]: - return 'fail' + assert data_read == data_mem[:] gdal.VSIFCloseL(vsifile) vsifile_write = gdal.VSIFOpenL(filename_write, 'wb') - if gdal.VSIFWriteL(data_mem, 1, len(data_mem), vsifile_write) != len(data_mem): - return 'fail' + assert gdal.VSIFWriteL(data_mem, 1, len(data_mem), vsifile_write) == len(data_mem) gdal.VSIFCloseL(vsifile_write) gdal.Unlink(filename) gdal.Unlink(filename_write) with gdaltest.error_handler(): data3 = gdal.VSIGetMemFileBuffer_unsafe(filename) - if data3 != None: - return 'fail' - - return 'success' + assert data3 == None + -def vsifile_22(): +def test_vsifile_22(): # VSIOpenL doesn't set errorno gdal.VSIErrorReset() - if gdal.VSIGetLastErrorNo() != 0: - gdaltest.post_reason("Expected Err=0 after VSIErrorReset(), got %d" % gdal.VSIGetLastErrorNo()) - return 'fail' + assert gdal.VSIGetLastErrorNo() == 0, \ + ("Expected Err=0 after VSIErrorReset(), got %d" % gdal.VSIGetLastErrorNo()) fp = gdal.VSIFOpenL('tmp/not-existing', 'r') - if fp is not None: - gdaltest.post_reason("Expected None from VSIFOpenL") - return 'fail' - if gdal.VSIGetLastErrorNo() != 0: - gdaltest.post_reason("Expected Err=0 from VSIFOpenL, got %d" % gdal.VSIGetLastErrorNo()) - return 'fail' + assert fp is None, "Expected None from VSIFOpenL" + assert gdal.VSIGetLastErrorNo() == 0, \ + ("Expected Err=0 from VSIFOpenL, got %d" % gdal.VSIGetLastErrorNo()) # VSIOpenExL does fp = gdal.VSIFOpenExL('tmp/not-existing', 'r', 1) - if fp is not None: - gdaltest.post_reason("Expected None from VSIFOpenExL") - return 'fail' - if gdal.VSIGetLastErrorNo() != 1: - gdaltest.post_reason("Expected Err=1 from VSIFOpenExL, got %d" % gdal.VSIGetLastErrorNo()) - return 'fail' - if len(gdal.VSIGetLastErrorMsg()) == 0: - gdaltest.post_reason("Expected a VSI error message") - return 'fail' + assert fp is None, "Expected None from VSIFOpenExL" + assert gdal.VSIGetLastErrorNo() == 1, \ + ("Expected Err=1 from VSIFOpenExL, got %d" % gdal.VSIGetLastErrorNo()) + assert len(gdal.VSIGetLastErrorMsg()) != 0, "Expected a VSI error message" gdal.VSIErrorReset() - if gdal.VSIGetLastErrorNo() != 0: - gdaltest.post_reason("Expected Err=0 after VSIErrorReset(), got %d" % gdal.VSIGetLastErrorNo()) - return 'fail' - - return 'success' + assert gdal.VSIGetLastErrorNo() == 0, \ + ("Expected Err=0 after VSIErrorReset(), got %d" % gdal.VSIGetLastErrorNo()) ############################################################################### # Test bugfix for https://github.com/OSGeo/gdal/issues/675 -def vsitar_bug_675(): +def test_vsitar_bug_675(): content = gdal.ReadDir('/vsitar/data/tar_with_star_base256_fields.tar') - if len(content) != 1: - print(content) - return 'fail' - return 'success' + assert len(content) == 1 ############################################################################### # Test multithreaded compression -def vsigzip_multi_thread(): +def test_vsigzip_multi_thread(): with gdaltest.config_options({'GDAL_NUM_THREADS': 'ALL_CPUS', 'CPL_VSIL_DEFLATE_CHUNK_SIZE': '32K'}): @@ -905,41 +706,30 @@ def vsigzip_multi_thread(): gdal.Unlink('/vsimem/vsigzip_multi_thread.gz') if data != 'hello' * 100000: - gdaltest.post_reason('fail') - for i in range(10000): if data[i*5:i*5+5] != 'hello': print(i*5, data[i*5:i*5+5], data[i*5-5:i*5+5-5]) break - return 'fail' - - return 'success' + pytest.fail() + ############################################################################### # Test vsisync() -def vsisync(): +def test_vsisync(): with gdaltest.error_handler(): - if gdal.Sync('/i_do/not/exist', '/vsimem/'): - gdaltest.post_reason('fail') - return 'fail' + assert not gdal.Sync('/i_do/not/exist', '/vsimem/') with gdaltest.error_handler(): - if gdal.Sync('vsifile.py', '/i_do/not/exist'): - gdaltest.post_reason('fail') - return 'fail' + assert not gdal.Sync('vsifile.py', '/i_do/not/exist') # Test copying a file for i in range(2): - if not gdal.Sync('vsifile.py', '/vsimem/'): - gdaltest.post_reason('fail') - return 'fail' - if gdal.VSIStatL('/vsimem/vsifile.py').size != gdal.VSIStatL('vsifile.py').size: - gdaltest.post_reason('fail') - return 'fail' + assert gdal.Sync('vsifile.py', '/vsimem/') + assert gdal.VSIStatL('/vsimem/vsifile.py').size == gdal.VSIStatL('vsifile.py').size gdal.Unlink('/vsimem/vsifile.py') # Test copying the content of a directory @@ -950,25 +740,13 @@ def vsisync(): if sys.platform != 'win32': with gdaltest.error_handler(): - if gdal.Sync('/vsimem/test_sync/', '/i_do_not/exist'): - gdaltest.post_reason('fail') - return 'fail' - - if not gdal.Sync('/vsimem/test_sync/', '/vsimem/out'): - gdaltest.post_reason('fail') - return 'fail' - if gdal.ReadDir('/vsimem/out') != [ 'foo.txt', 'subdir' ]: - gdaltest.post_reason('fail') - print(gdal.ReadDir('/vsimem/out')) - return 'fail' - if gdal.ReadDir('/vsimem/out/subdir') != [ 'bar.txt' ]: - gdaltest.post_reason('fail') - print(gdal.ReadDir('/vsimem/out/subdir')) - return 'fail' + assert not gdal.Sync('/vsimem/test_sync/', '/i_do_not/exist') + + assert gdal.Sync('/vsimem/test_sync/', '/vsimem/out') + assert gdal.ReadDir('/vsimem/out') == [ 'foo.txt', 'subdir' ] + assert gdal.ReadDir('/vsimem/out/subdir') == [ 'bar.txt' ] # Again - if not gdal.Sync('/vsimem/test_sync/', '/vsimem/out'): - gdaltest.post_reason('fail') - return 'fail' + assert gdal.Sync('/vsimem/test_sync/', '/vsimem/out') gdal.RmdirRecursive('/vsimem/out') @@ -977,51 +755,32 @@ def vsisync(): def my_progress(pct, message, user_data): pct_values.append(pct) - if not gdal.Sync('/vsimem/test_sync', '/vsimem/out', callback = my_progress): - gdaltest.post_reason('fail') - return 'fail' + assert gdal.Sync('/vsimem/test_sync', '/vsimem/out', callback = my_progress) - if pct_values != [0.5, 1.0]: - gdaltest.post_reason('fail') - print(pct_values) - return 'fail' + assert pct_values == [0.5, 1.0] - if gdal.ReadDir('/vsimem/out') != [ 'test_sync' ]: - gdaltest.post_reason('fail') - print(gdal.ReadDir('/vsimem/out')) - return 'fail' - if gdal.ReadDir('/vsimem/out/test_sync') != [ 'foo.txt', 'subdir' ]: - gdaltest.post_reason('fail') - print(gdal.ReadDir('/vsimem/out/test_sync')) - return 'fail' + assert gdal.ReadDir('/vsimem/out') == [ 'test_sync' ] + assert gdal.ReadDir('/vsimem/out/test_sync') == [ 'foo.txt', 'subdir' ] gdal.RmdirRecursive('/vsimem/test_sync') gdal.RmdirRecursive('/vsimem/out') - return 'success' - ############################################################################### # Test gdal.OpenDir() -def vsifile_opendir(): +def test_vsifile_opendir(): # Non existing dir d = gdal.OpenDir('/vsimem/i_dont_exist') - if d: - gdaltest.post_reason('fail') - return 'fail' + assert not d gdal.Mkdir('/vsimem/vsifile_opendir', 0o755) # Empty dir d = gdal.OpenDir('/vsimem/vsifile_opendir') - if not d: - gdaltest.post_reason('fail') - return 'fail' + assert d entry = gdal.GetNextDirEntry(d) - if entry: - gdaltest.post_reason('fail') - return 'fail' + assert not entry gdal.CloseDir(d) gdal.FileFromMemBuffer('/vsimem/vsifile_opendir/test', 'foo') @@ -1033,130 +792,46 @@ def vsifile_opendir(): d = gdal.OpenDir('/vsimem/vsifile_opendir') entry = gdal.GetNextDirEntry(d) - if entry.name != 'subdir': - gdaltest.post_reason('fail') - print(entry.name) - return 'fail' - if entry.mode != 16384: - gdaltest.post_reason('fail') - print(entry.mode) - return 'fail' + assert entry.name == 'subdir' + assert entry.mode == 16384 entry = gdal.GetNextDirEntry(d) - if entry.name != 'subdir/subdir2': - gdaltest.post_reason('fail') - print(entry.name) - return 'fail' - if entry.mode != 16384: - gdaltest.post_reason('fail') - print(entry.mode) - return 'fail' + assert entry.name == 'subdir/subdir2' + assert entry.mode == 16384 entry = gdal.GetNextDirEntry(d) - if entry.name != 'subdir/subdir2/test2': - gdaltest.post_reason('fail') - print(entry.name) - return 'fail' - if entry.mode != 32768: - gdaltest.post_reason('fail') - print(entry.mode) - return 'fail' + assert entry.name == 'subdir/subdir2/test2' + assert entry.mode == 32768 entry = gdal.GetNextDirEntry(d) - if entry.name != 'test': - gdaltest.post_reason('fail') - print(entry.name) - return 'fail' - if entry.mode != 32768: - gdaltest.post_reason('fail') - print(entry.mode) - return 'fail' - if not entry.modeKnown: - gdaltest.post_reason('fail') - return 'fail' - if entry.size != 3: - gdaltest.post_reason('fail') - return 'fail' - if not entry.sizeKnown: - gdaltest.post_reason('fail') - return 'fail' - if entry.mtime == 0: - gdaltest.post_reason('fail') - return 'fail' - if not entry.mtimeKnown: - gdaltest.post_reason('fail') - return 'fail' - if entry.extra: - gdaltest.post_reason('fail') - return 'fail' + assert entry.name == 'test' + assert entry.mode == 32768 + assert entry.modeKnown + assert entry.size == 3 + assert entry.sizeKnown + assert entry.mtime != 0 + assert entry.mtimeKnown + assert not entry.extra entry = gdal.GetNextDirEntry(d) - if entry: - gdaltest.post_reason('fail') - return 'fail' + assert not entry gdal.CloseDir(d) # Only top level d = gdal.OpenDir('/vsimem/vsifile_opendir', 0) entry = gdal.GetNextDirEntry(d) - if entry.name != 'subdir': - gdaltest.post_reason('fail') - print(entry.name) - return 'fail' + assert entry.name == 'subdir' entry = gdal.GetNextDirEntry(d) - if entry.name != 'test': - gdaltest.post_reason('fail') - print(entry.name) - return 'fail' + assert entry.name == 'test' entry = gdal.GetNextDirEntry(d) - if entry: - gdaltest.post_reason('fail') - return 'fail' + assert not entry gdal.CloseDir(d) # Depth 1 files = [l_entry.name for l_entry in gdal.listdir('/vsimem/vsifile_opendir', 1)] - if files != ['subdir', 'subdir/subdir2', 'test']: - gdaltest.post_reason('fail') - print(files) - return 'fail' + assert files == ['subdir', 'subdir/subdir2', 'test'] gdal.RmdirRecursive('/vsimem/vsifile_opendir') - return 'success' - - -gdaltest_list = [vsifile_1, - vsifile_2, - vsifile_3, - vsifile_4, - vsifile_5, - vsifile_6, - vsifile_7, - vsifile_8, - vsifile_9, - vsifile_10, - vsifile_11, - vsifile_12, - vsifile_13, - vsifile_14, - vsifile_15, - vsifile_16, - vsifile_17, - vsifile_18, - vsifile_19, - vsifile_20, - vsifile_21, - vsifile_22, - vsitar_bug_675, - vsigzip_multi_thread, - vsifile_opendir, - vsisync] - -if __name__ == '__main__': - - gdaltest.setup_run('vsifile') - - gdaltest.run_tests(gdaltest_list) - - sys.exit(gdaltest.summarize()) + + diff --git a/autotest/gcore/vsigs.py b/autotest/gcore/vsigs.py index 2580f3142702..e59b7fff022a 100755 --- a/autotest/gcore/vsigs.py +++ b/autotest/gcore/vsigs.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 vsigs_init(): +def test_vsigs_init(): gdaltest.gs_vars = {} for var in ('GS_SECRET_ACCESS_KEY', 'GS_ACCESS_KEY_ID', @@ -68,20 +68,17 @@ def vsigs_init(): gdal.SetConfigOption('GOOGLE_APPLICATION_CREDENTIALS', '') with gdaltest.config_option('CPL_GCE_SKIP', 'YES'): - if gdal.GetSignedURL('/vsigs/foo/bar') is not None: - gdaltest.post_reason('fail') - return 'fail' - - return 'success' + assert gdal.GetSignedURL('/vsigs/foo/bar') is None + ############################################################################### # Error cases -def vsigs_1(): +def test_vsigs_1(): if not gdaltest.built_against_curl(): - return 'skip' + pytest.skip() # Invalid header filename gdal.ErrorReset() @@ -90,42 +87,31 @@ def vsigs_1(): with gdaltest.error_handler(): f = open_for_read('/vsigs/foo/bar') if f is not None: - gdaltest.post_reason('fail') gdal.VSIFCloseL(f) - return 'fail' + pytest.fail() last_err = gdal.GetLastErrorMsg() - if last_err.find('Cannot read') < 0: - gdaltest.post_reason('fail') - print(last_err) - return 'fail' + assert last_err.find('Cannot read') >= 0 # Invalid content for header file with gdaltest.config_option('GDAL_HTTP_HEADER_FILE', 'vsigs.py'): with gdaltest.config_option('CPL_GCE_SKIP', 'YES'): f = open_for_read('/vsigs/foo/bar') if f is not None: - gdaltest.post_reason('fail') gdal.VSIFCloseL(f) - return 'fail' + pytest.fail() # Missing GS_SECRET_ACCESS_KEY gdal.ErrorReset() with gdaltest.config_option('CPL_GCE_SKIP', 'YES'): with gdaltest.error_handler(): f = open_for_read('/vsigs/foo/bar') - if f is not None or gdal.VSIGetLastErrorMsg().find('GS_SECRET_ACCESS_KEY') < 0: - gdaltest.post_reason('fail') - print(gdal.VSIGetLastErrorMsg()) - return 'fail' + assert f is None and gdal.VSIGetLastErrorMsg().find('GS_SECRET_ACCESS_KEY') >= 0 gdal.ErrorReset() with gdaltest.config_option('CPL_GCE_SKIP', 'YES'): with gdaltest.error_handler(): f = open_for_read('/vsigs_streaming/foo/bar') - if f is not None or gdal.VSIGetLastErrorMsg().find('GS_SECRET_ACCESS_KEY') < 0: - gdaltest.post_reason('fail') - print(gdal.VSIGetLastErrorMsg()) - return 'fail' + assert f is None and gdal.VSIGetLastErrorMsg().find('GS_SECRET_ACCESS_KEY') >= 0 gdal.SetConfigOption('GS_SECRET_ACCESS_KEY', 'GS_SECRET_ACCESS_KEY') @@ -133,10 +119,7 @@ def vsigs_1(): gdal.ErrorReset() with gdaltest.error_handler(): f = open_for_read('/vsigs/foo/bar') - if f is not None or gdal.VSIGetLastErrorMsg().find('GS_ACCESS_KEY_ID') < 0: - gdaltest.post_reason('fail') - print(gdal.VSIGetLastErrorMsg()) - return 'fail' + assert f is None and gdal.VSIGetLastErrorMsg().find('GS_ACCESS_KEY_ID') >= 0 gdal.SetConfigOption('GS_ACCESS_KEY_ID', 'GS_ACCESS_KEY_ID') @@ -148,50 +131,41 @@ def vsigs_1(): 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('/vsigs_streaming/foo/bar.baz') - if f is not None or gdal.VSIGetLastErrorMsg() == '': - gdaltest.post_reason('fail') - print(gdal.VSIGetLastErrorMsg()) - return 'fail' - - return 'success' + assert f is None and gdal.VSIGetLastErrorMsg() != '' ############################################################################### -def vsigs_start_webserver(): +def test_vsigs_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('CPL_GS_ENDPOINT', 'http://127.0.0.1:%d/' % gdaltest.webserver_port) gdal.SetConfigOption('GS_SECRET_ACCESS_KEY', 'GS_SECRET_ACCESS_KEY') gdal.SetConfigOption('GS_ACCESS_KEY_ID', 'GS_ACCESS_KEY_ID') - return 'success' - ############################################################################### # Test with a fake Google Cloud Storage server -def vsigs_2(): +def test_vsigs_2(): if gdaltest.webserver_port == 0: - return 'skip' + pytest.skip() # header file gdal.FileFromMemBuffer('/vsimem/my_headers.txt', 'foo: bar') @@ -203,14 +177,10 @@ def vsigs_2(): with webserver.install_http_handler(handler): with gdaltest.config_option('GDAL_HTTP_HEADER_FILE', '/vsimem/my_headers.txt'): f = open_for_read('/vsigs/gs_fake_bucket_http_header_file/resource') - if f is None: - gdaltest.post_reason('fail') - return 'fail' + assert f is not None data = gdal.VSIFReadL(1, 1, f) gdal.VSIFCloseL(f) - if len(data) != 1: - gdaltest.post_reason('fail') - return 'fail' + assert len(data) == 1 gdal.Unlink('/vsimem/my_headers.txt') gdal.SetConfigOption('GS_SECRET_ACCESS_KEY', 'GS_SECRET_ACCESS_KEY') @@ -219,11 +189,8 @@ def vsigs_2(): signed_url = gdal.GetSignedURL('/vsigs/gs_fake_bucket/resource', ['START_DATE=20180212T123456Z']) - if signed_url not in ('http://127.0.0.1:8080/gs_fake_bucket/resource?Expires=1518442496&GoogleAccessId=GS_ACCESS_KEY_ID&Signature=xTphUyMqtKA6UmAX3PEr5VL3EOg%3D', - 'http://127.0.0.1:8081/gs_fake_bucket/resource?Expires=1518442496&GoogleAccessId=GS_ACCESS_KEY_ID&Signature=xTphUyMqtKA6UmAX3PEr5VL3EOg%3D'): - gdaltest.post_reason('fail') - print(signed_url) - return 'fail' + assert (signed_url in ('http://127.0.0.1:8080/gs_fake_bucket/resource?Expires=1518442496&GoogleAccessId=GS_ACCESS_KEY_ID&Signature=xTphUyMqtKA6UmAX3PEr5VL3EOg%3D', + 'http://127.0.0.1:8081/gs_fake_bucket/resource?Expires=1518442496&GoogleAccessId=GS_ACCESS_KEY_ID&Signature=xTphUyMqtKA6UmAX3PEr5VL3EOg%3D')) handler = webserver.SequentialHandler() handler.add('GET', '/gs_fake_bucket/resource', 200, @@ -231,16 +198,11 @@ def vsigs_2(): expected_headers={'Authorization': 'GOOG1 GS_ACCESS_KEY_ID:8tndu9//BfmN+Kg4AFLdUMZMBDQ='}) with webserver.install_http_handler(handler): f = open_for_read('/vsigs/gs_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('GET', '/gs_fake_bucket/resource', 200, @@ -248,16 +210,11 @@ def vsigs_2(): expected_headers={'Authorization': 'GOOG1 GS_ACCESS_KEY_ID:8tndu9//BfmN+Kg4AFLdUMZMBDQ='}) with webserver.install_http_handler(handler): f = open_for_read('/vsigs_streaming/gs_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('GET', '/gs_fake_bucket/resource2.bin', 206, @@ -265,12 +222,11 @@ def vsigs_2(): with webserver.install_http_handler(handler): stat_res = gdal.VSIStatL('/vsigs/gs_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', '/gs_fake_bucket/resource2.bin', 200, @@ -278,23 +234,21 @@ def vsigs_2(): with webserver.install_http_handler(handler): stat_res = gdal.VSIStatL('/vsigs_streaming/gs_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 Google Cloud Storage server -def vsigs_readdir(): +def test_vsigs_readdir(): if gdaltest.webserver_port == 0: - return 'skip' + pytest.skip() handler = webserver.SequentialHandler() handler.add('GET', '/gs_fake_bucket2/?delimiter=%2F&prefix=a_dir%2F', 200, @@ -331,30 +285,19 @@ def vsigs_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('/vsigs/gs_fake_bucket2/a_dir') - if dir_contents != ['resource3.bin', 'resource4.bin', 'subdir']: - gdaltest.post_reason('fail') - print(dir_contents) - return 'fail' - if gdal.VSIStatL('/vsigs/gs_fake_bucket2/a_dir/resource3.bin').size != 123456: - gdaltest.post_reason('fail') - return 'fail' - if gdal.VSIStatL('/vsigs/gs_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('/vsigs/gs_fake_bucket2/a_dir/resource3.bin').size == 123456 + assert gdal.VSIStatL('/vsigs/gs_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('/vsigs/gs_fake_bucket2/a_dir/resource3.bin') - if dir_contents is not None: - gdaltest.post_reason('fail') - return 'fail' + assert dir_contents is None # List buckets handler = webserver.SequentialHandler() @@ -370,28 +313,21 @@ def vsigs_readdir(): """) with webserver.install_http_handler(handler): dir_contents = gdal.ReadDir('/vsigs/') - if dir_contents != ['mybucket']: - gdaltest.post_reason('fail') - print(dir_contents) - return 'fail' - - return 'success' + assert dir_contents == ['mybucket'] ############################################################################### # Test write -def vsigs_write(): +def test_vsigs_write(): if gdaltest.webserver_port == 0: - return 'skip' + pytest.skip() gdal.VSICurlClearCache() f = gdal.VSIFOpenL('/vsigs/test_copy/file.bin', 'wb') - if f is None: - gdaltest.post_reason('fail') - return 'fail' + assert f is not None handler = webserver.SequentialHandler() @@ -420,17 +356,13 @@ 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 failure while transmitting f = gdal.VSIFOpenL('/vsigs/test_copy/file.bin', 'wb') - if f is None: - gdaltest.post_reason('fail') - return 'fail' + assert f is not None handler = webserver.SequentialHandler() @@ -445,17 +377,13 @@ def method(request): with gdaltest.error_handler(): ret = gdal.VSIFWriteL('x' * 35000, 1, 35000, f) if ret != 0: - gdaltest.post_reason('fail') - print(ret) gdal.VSIFCloseL(f) - return 'fail' + pytest.fail(ret) gdal.VSIFCloseL(f) # Simulate failure at end of transfer f = gdal.VSIFOpenL('/vsigs/test_copy/file.bin', 'wb') - if f is None: - gdaltest.post_reason('fail') - return 'fail' + assert f is not None handler = webserver.SequentialHandler() @@ -477,26 +405,21 @@ def method(request): with webserver.install_http_handler(handler): ret = gdal.VSIFWriteL('x' * 35000, 1, 35000, f) if ret != 35000: - gdaltest.post_reason('fail') - print(ret) gdal.VSIFCloseL(f) - return 'fail' + pytest.fail(ret) with gdaltest.error_handler(): ret = gdal.VSIFCloseL(f) - if ret == 0: - gdaltest.post_reason('fail') - return 'fail' - - return 'success' + assert ret != 0 + ############################################################################### # Read credentials with OAuth2 refresh_token -def vsigs_read_credentials_refresh_token_default_gdal_app(): +def test_vsigs_read_credentials_refresh_token_default_gdal_app(): if gdaltest.webserver_port == 0: - return 'skip' + pytest.skip() gdal.SetConfigOption('GS_SECRET_ACCESS_KEY', '') gdal.SetConfigOption('GS_ACCESS_KEY_ID', '') @@ -507,9 +430,7 @@ def vsigs_read_credentials_refresh_token_default_gdal_app(): gdal.SetConfigOption('GS_OAUTH2_REFRESH_TOKEN', 'REFRESH_TOKEN') with gdaltest.error_handler(): - if gdal.GetSignedURL('/vsigs/foo/bar') is not None: - gdaltest.post_reason('fail') - return 'fail' + assert gdal.GetSignedURL('/vsigs/foo/bar') is None gdal.VSICurlClearCache() @@ -555,30 +476,23 @@ def method(request): handler.add('GET', '/gs_fake_bucket/resource', custom_method=method) with webserver.install_http_handler(handler): f = open_for_read('/vsigs/gs_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' gdal.SetConfigOption('GOA2_AUTH_URL_TOKEN', None) gdal.SetConfigOption('GS_OAUTH2_REFRESH_TOKEN', '') - return 'success' - ############################################################################### # Read credentials with OAuth2 refresh_token -def vsigs_read_credentials_refresh_token_custom_app(): +def test_vsigs_read_credentials_refresh_token_custom_app(): if gdaltest.webserver_port == 0: - return 'skip' + pytest.skip() gdal.SetConfigOption('GS_SECRET_ACCESS_KEY', '') gdal.SetConfigOption('GS_ACCESS_KEY_ID', '') @@ -634,32 +548,25 @@ def method(request): handler.add('GET', '/gs_fake_bucket/resource', custom_method=method) with webserver.install_http_handler(handler): f = open_for_read('/vsigs/gs_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' gdal.SetConfigOption('GOA2_AUTH_URL_TOKEN', None) gdal.SetConfigOption('GS_OAUTH2_REFRESH_TOKEN', '') gdal.SetConfigOption('GS_OAUTH2_CLIENT_ID', '') gdal.SetConfigOption('GS_OAUTH2_CLIENT_SECRET', '') - return 'success' - ############################################################################### # Read credentials with OAuth2 service account -def vsigs_read_credentials_oauth2_service_account(): +def test_vsigs_read_credentials_oauth2_service_account(): if gdaltest.webserver_port == 0: - return 'skip' + pytest.skip() gdal.SetConfigOption('GS_SECRET_ACCESS_KEY', '') gdal.SetConfigOption('GS_ACCESS_KEY_ID', '') @@ -746,14 +653,12 @@ def method(request): try: with webserver.install_http_handler(handler): f = open_for_read('/vsigs/gs_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) except: if gdal.GetLastErrorMsg().find('CPLRSASHA256Sign() not implemented') >= 0: - return 'skip' + pytest.skip() finally: gdal.SetConfigOption('GO2A_AUD', None) gdal.SetConfigOption('GO2A_NOW', None) @@ -761,23 +666,18 @@ def method(request): gdal.SetConfigOption('GS_OAUTH2_PRIVATE_KEY_FILE', '') gdal.SetConfigOption('GS_OAUTH2_CLIENT_EMAIL', '') - if data != 'foo': - gdaltest.post_reason('fail') - print(data) - return 'fail' + assert data == 'foo' gdal.Unlink('/vsimem/pkey') - return 'success' - ############################################################################### # Read credentials with OAuth2 service account through a json configuration file -def vsigs_read_credentials_oauth2_service_account_json_file(): +def test_vsigs_read_credentials_oauth2_service_account_json_file(): if gdaltest.webserver_port == 0: - return 'skip' + pytest.skip() gdal.SetConfigOption('GS_SECRET_ACCESS_KEY', '') gdal.SetConfigOption('GS_ACCESS_KEY_ID', '') @@ -841,9 +741,8 @@ def method(request): with webserver.install_http_handler(handler): f = open_for_read('/vsigs/gs_fake_bucket/resource') if f is None: - gdaltest.post_reason('fail') gdal.Unlink('/vsimem/service_account.json') - return 'fail' + pytest.fail() data = gdal.VSIFReadL(1, 4, f).decode('ascii') gdal.VSIFCloseL(f) @@ -851,14 +750,12 @@ def method(request): ['START_DATE=20180212T123456Z']) if signed_url not in ('http://127.0.0.1:8080/gs_fake_bucket/resource?Expires=1518442496&GoogleAccessId=CLIENT_EMAIL&Signature=b19I62KdqV51DpWGxhxGXLGJIA8MHvSJofwOygoeQuIxkM6PmmQFvJYTNWRt9zUVTUoVC0UHVB7ee5Z35NqDC8K4i0quu1hb8Js2B4h0W6OAupvyF3nSQ5D0OJmiSbomGMq0Ehyro5cqJ%2FU%2Fd8oAaKrGKVQScKfXoFrSJBbWkNs%3D', 'http://127.0.0.1:8081/gs_fake_bucket/resource?Expires=1518442496&GoogleAccessId=CLIENT_EMAIL&Signature=b19I62KdqV51DpWGxhxGXLGJIA8MHvSJofwOygoeQuIxkM6PmmQFvJYTNWRt9zUVTUoVC0UHVB7ee5Z35NqDC8K4i0quu1hb8Js2B4h0W6OAupvyF3nSQ5D0OJmiSbomGMq0Ehyro5cqJ%2FU%2Fd8oAaKrGKVQScKfXoFrSJBbWkNs%3D'): - gdaltest.post_reason('fail') - print(signed_url) gdal.Unlink('/vsimem/service_account.json') - return 'fail' + pytest.fail(signed_url) except: if gdal.GetLastErrorMsg().find('CPLRSASHA256Sign() not implemented') >= 0: - return 'skip' + pytest.skip() finally: gdal.SetConfigOption('GO2A_AUD', None) gdal.SetConfigOption('GO2A_NOW', None) @@ -866,21 +763,16 @@ def method(request): gdal.Unlink('/vsimem/service_account.json') - if data != 'foo': - gdaltest.post_reason('fail') - print(data) - return 'fail' - - return 'success' + assert data == 'foo' ############################################################################### # Read credentials from simulated ~/.boto -def vsigs_read_credentials_file(): +def test_vsigs_read_credentials_file(): if gdaltest.webserver_port == 0: - return 'skip' + pytest.skip() gdal.SetConfigOption('GS_SECRET_ACCESS_KEY', '') gdal.SetConfigOption('GS_ACCESS_KEY_ID', '') @@ -922,30 +814,23 @@ def method(request): handler.add('GET', '/gs_fake_bucket/resource', custom_method=method) with webserver.install_http_handler(handler): f = open_for_read('/vsigs/gs_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' gdal.SetConfigOption('CPL_GS_CREDENTIALS_FILE', '') gdal.Unlink('/vsimem/.boto') - return 'success' - ############################################################################### # Read credentials from simulated ~/.boto -def vsigs_read_credentials_file_refresh_token(): +def test_vsigs_read_credentials_file_refresh_token(): if gdaltest.webserver_port == 0: - return 'skip' + pytest.skip() gdal.SetConfigOption('GS_SECRET_ACCESS_KEY', '') gdal.SetConfigOption('GS_ACCESS_KEY_ID', '') @@ -1006,34 +891,27 @@ def method(request): handler.add('GET', '/gs_fake_bucket/resource', custom_method=method) with webserver.install_http_handler(handler): f = open_for_read('/vsigs/gs_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' gdal.SetConfigOption('CPL_GS_CREDENTIALS_FILE', '') gdal.SetConfigOption('GOA2_AUTH_URL_TOKEN', None) gdal.Unlink('/vsimem/.boto') - return 'success' - ############################################################################### # Read credentials from simulated GCE instance -def vsigs_read_credentials_gce(): +def test_vsigs_read_credentials_gce(): if gdaltest.webserver_port == 0: - return 'skip' + pytest.skip() if sys.platform not in ('linux', 'linux2', 'win32'): - return 'skip' + pytest.skip() gdal.SetConfigOption('CPL_GS_CREDENTIALS_FILE', '') gdal.SetConfigOption('GS_SECRET_ACCESS_KEY', '') @@ -1073,16 +951,11 @@ def method(request): handler.add('GET', '/gs_fake_bucket/resource', custom_method=method) with webserver.install_http_handler(handler): f = open_for_read('/vsigs/gs_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' # Set a fake URL to check that credentials re-use works gdal.SetConfigOption('CPL_GCE_CREDENTIALS_URL', '') @@ -1091,39 +964,30 @@ def method(request): handler.add('GET', '/gs_fake_bucket/bar', 200, {}, 'bar') with webserver.install_http_handler(handler): f = open_for_read('/vsigs/gs_fake_bucket/bar') - 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 != 'bar': - gdaltest.post_reason('fail') - print(data) - return 'fail' + assert data == 'bar' with gdaltest.error_handler(): - if gdal.GetSignedURL('/vsigs/foo/bar') is not None: - gdaltest.post_reason('fail') - return 'fail' + assert gdal.GetSignedURL('/vsigs/foo/bar') is None gdal.SetConfigOption('CPL_GCE_CREDENTIALS_URL', '') gdal.SetConfigOption('CPL_GCE_CHECK_LOCAL_FILES', None) - return 'success' - ############################################################################### # Read credentials from simulated GCE instance with expiration of the # cached credentials -def vsigs_read_credentials_gce_expiration(): +def test_vsigs_read_credentials_gce_expiration(): if gdaltest.webserver_port == 0: - return 'skip' + pytest.skip() if sys.platform not in ('linux', 'linux2', 'win32'): - return 'skip' + pytest.skip() gdal.SetConfigOption('CPL_GS_CREDENTIALS_FILE', '') gdal.SetConfigOption('GS_SECRET_ACCESS_KEY', '') @@ -1171,29 +1035,22 @@ def method(request): handler.add('GET', '/gs_fake_bucket/resource', custom_method=method) with webserver.install_http_handler(handler): f = open_for_read('/vsigs/gs_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' gdal.SetConfigOption('CPL_GCE_CREDENTIALS_URL', '') gdal.SetConfigOption('CPL_GCE_CHECK_LOCAL_FILES', None) - return 'success' - ############################################################################### -def vsigs_stop_webserver(): +def test_vsigs_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 @@ -1201,158 +1058,103 @@ def vsigs_stop_webserver(): webserver.server_stop(gdaltest.webserver_process, gdaltest.webserver_port) - return 'success' - ############################################################################### # Nominal cases (require valid credentials) -def vsigs_extra_1(): +def test_vsigs_extra_1(): if not gdaltest.built_against_curl(): - return 'skip' + pytest.skip() # if gdal.GetConfigOption('GS_SECRET_ACCESS_KEY') is None: - # print('Missing GS_SECRET_ACCESS_KEY for running gdaltest_list_extra') - # return 'skip' + # print('Missing GS_SECRET_ACCESS_KEY') + # pytest.skip() # elif gdal.GetConfigOption('GS_ACCESS_KEY_ID') is None: - # print('Missing GS_ACCESS_KEY_ID for running gdaltest_list_extra') - # return 'skip' + # print('Missing GS_ACCESS_KEY_ID') + # pytest.skip() gs_resource = gdal.GetConfigOption('GS_RESOURCE') if gs_resource is None: - print('Missing GS_RESOURCE for running gdaltest_list_extra') - return 'skip' + pytest.skip('Missing GS_RESOURCE') if gs_resource.find('/') < 0: path = '/vsigs/' + gs_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 = 'vsigs_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('/vsigs/' + gs_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 /vsigs_streaming/ f = open_for_read('/vsigs_streaming/' + gs_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 @@ -1362,74 +1164,26 @@ def vsigs_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('/vsigs_streaming/' + gs_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('/vsigs/' + gs_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 vsigs_cleanup(): +def test_vsigs_cleanup(): for var in gdaltest.gs_vars: gdal.SetConfigOption(var, gdaltest.gs_vars[var]) - - return 'success' - - -gdaltest_list = [vsigs_init, - vsigs_1, - vsigs_start_webserver, - vsigs_2, - vsigs_readdir, - vsigs_write, - vsigs_read_credentials_refresh_token_default_gdal_app, - vsigs_read_credentials_refresh_token_custom_app, - vsigs_read_credentials_oauth2_service_account, - vsigs_read_credentials_oauth2_service_account_json_file, - vsigs_read_credentials_file, - vsigs_read_credentials_file_refresh_token, - vsigs_read_credentials_gce, - vsigs_read_credentials_gce_expiration, - vsigs_stop_webserver, - vsigs_cleanup] - -# gdaltest_list = [ vsigs_init, vsigs_start_webserver, vsigs_write, vsigs_stop_webserver, vsigs_cleanup ] - -gdaltest_list_extra = [vsigs_extra_1] - -if __name__ == '__main__': - - gdaltest.setup_run('vsigs') - - if gdal.GetConfigOption('RUN_MANUAL_ONLY', None): - gdaltest.run_tests(gdaltest_list_extra) - else: - gdaltest.run_tests(gdaltest_list + gdaltest_list_extra + [vsigs_cleanup]) - - sys.exit(gdaltest.summarize()) diff --git a/autotest/gcore/vsihdfs.py b/autotest/gcore/vsihdfs.py index 7c938f7681a2..369e4896401e 100755 --- a/autotest/gcore/vsihdfs.py +++ b/autotest/gcore/vsihdfs.py @@ -30,164 +30,124 @@ # DEALINGS IN THE SOFTWARE. ############################################################################### -import sys import os from osgeo import gdal -sys.path.append('../pymod') import gdaltest +import pytest # Read test -def vsihdfs_1(): +def test_vsihdfs_1(): filename = '/vsihdfs/file:' + os.getcwd() + '/data/text.txt' fp = gdal.VSIFOpenL(filename, 'rb') if fp is None: gdaltest.have_vsihdfs = False - return 'skip' + pytest.skip() gdaltest.have_vsihdfs = True data = gdal.VSIFReadL(5, 1, fp) - if not data or data.decode('ascii') != 'Lorem': - return 'fail' + assert data and data.decode('ascii') == 'Lorem' data = gdal.VSIFReadL(1, 6, fp) - if not data or data.decode('ascii') != ' ipsum': - return 'fail' + assert data and data.decode('ascii') == ' ipsum' gdal.VSIFCloseL(fp) - return 'success' # Seek test -def vsihdfs_2(): +def test_vsihdfs_2(): if gdaltest.have_vsihdfs == False: - return 'skip' + pytest.skip() filename = '/vsihdfs/file:' + os.getcwd() + '/data/text.txt' fp = gdal.VSIFOpenL(filename, 'rb') - if fp is None: - return 'fail' + assert fp is not None gdal.VSIFSeekL(fp, 2, 0) # From beginning gdal.VSIFSeekL(fp, 5, 0) data = gdal.VSIFReadL(6, 1, fp) - if not data or data.decode('ascii') != ' ipsum': - return 'fail' + assert data and data.decode('ascii') == ' ipsum' gdal.VSIFSeekL(fp, 7, 1) # From current data = gdal.VSIFReadL(3, 1, fp) - if not data or data.decode('ascii') != 'sit': - return 'fail' + assert data and data.decode('ascii') == 'sit' gdal.VSIFSeekL(fp, 9, 2) # From end data = gdal.VSIFReadL(7, 1, fp) - if not data or data.decode('ascii') != 'laborum': - return 'fail' + assert data and data.decode('ascii') == 'laborum' gdal.VSIFCloseL(fp) - return 'success' # Tell test -def vsihdfs_3(): +def test_vsihdfs_3(): if gdaltest.have_vsihdfs == False: - return 'skip' + pytest.skip() filename = '/vsihdfs/file:' + os.getcwd() + '/data/text.txt' fp = gdal.VSIFOpenL(filename, 'rb') - if fp is None: - return 'fail' + assert fp is not None data = gdal.VSIFReadL(5, 1, fp) - if not data or data.decode('ascii') != 'Lorem': - return 'fail' + assert data and data.decode('ascii') == 'Lorem' offset = gdal.VSIFTellL(fp) - if offset != 5: - return 'fail' + assert offset == 5 gdal.VSIFCloseL(fp) - return 'success' # Write test -def vsihdfs_4(): - return 'skip' +def test_vsihdfs_4(): + pytest.skip() # EOF test -def vsihdfs_5(): +def test_vsihdfs_5(): if gdaltest.have_vsihdfs == False: - return 'skip' + pytest.skip() filename = '/vsihdfs/file:' + os.getcwd() + '/data/text.txt' fp = gdal.VSIFOpenL(filename, 'rb') - if fp is None: - return 'fail' + assert fp is not None gdal.VSIFReadL(5, 1, fp) eof = gdal.VSIFEofL(fp) - if eof != 0: - return 'fail' + assert eof == 0 gdal.VSIFReadL(1000000, 1, fp) eof = gdal.VSIFEofL(fp) - if eof != 0: - return 'fail' + assert eof == 0 gdal.VSIFReadL(1, 1, fp) eof = gdal.VSIFEofL(fp) - if eof != 1: - return 'fail' + assert eof == 1 gdal.VSIFSeekL(fp, 0, 0) eof = gdal.VSIFEofL(fp) - if eof != 0: - return 'fail' + assert eof == 0 gdal.VSIFCloseL(fp) - return 'success' # Stat test -def vsihdfs_6(): +def test_vsihdfs_6(): if gdaltest.have_vsihdfs == False: - return 'skip' + pytest.skip() filename = '/vsihdfs/file:' + os.getcwd() + '/data/text.txt' statBuf = gdal.VSIStatL(filename, 0) - if not statBuf: - return 'fail' + assert statBuf filename = '/vsihdfs/file:' + os.getcwd() + '/data/no-such-file.txt' statBuf = gdal.VSIStatL(filename, 0) - if statBuf: - return 'fail' - - return 'success' + assert not statBuf # ReadDir test -def vsihdfs_7(): +def test_vsihdfs_7(): if gdaltest.have_vsihdfs == False: - return 'skip' + pytest.skip() dirname = '/vsihdfs/file:' + os.getcwd() + '/data/' lst = gdal.ReadDir(dirname) - if len(lst) < 360: - return 'fail' - - return 'success' - - -gdaltest_list = [vsihdfs_1, - vsihdfs_2, - vsihdfs_3, - vsihdfs_4, - vsihdfs_5, - vsihdfs_6, - vsihdfs_7] - -if __name__ == '__main__': + assert len(lst) >= 360 - gdaltest.setup_run('vsihdfs') - gdaltest.run_tests(gdaltest_list) - sys.exit(gdaltest.summarize()) diff --git a/autotest/gcore/vsioss.py b/autotest/gcore/vsioss.py index db5362d67164..877bf2f13ec4 100755 --- a/autotest/gcore/vsioss.py +++ b/autotest/gcore/vsioss.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 visoss_init(): +def test_visoss_init(): gdaltest.oss_vars = {} for var in ('OSS_SECRET_ACCESS_KEY', 'OSS_ACCESS_KEY_ID', 'OSS_TIMESTAMP', 'OSS_HTTPS', 'OSS_VIRTUAL_HOSTING', 'OSS_ENDPOINT'): @@ -55,37 +55,27 @@ def visoss_init(): if gdaltest.oss_vars[var] is not None: gdal.SetConfigOption(var, "") - if gdal.GetSignedURL('/vsioss/foo/bar') is not None: - gdaltest.post_reason('fail') - return 'fail' - - return 'success' + assert gdal.GetSignedURL('/vsioss/foo/bar') is None ############################################################################### # Error cases -def visoss_1(): +def test_visoss_1(): if not gdaltest.built_against_curl(): - return 'skip' + pytest.skip() # Missing OSS_SECRET_ACCESS_KEY gdal.ErrorReset() with gdaltest.error_handler(): f = open_for_read('/vsioss/foo/bar') - if f is not None or gdal.VSIGetLastErrorMsg().find('OSS_SECRET_ACCESS_KEY') < 0: - gdaltest.post_reason('fail') - print(gdal.VSIGetLastErrorMsg()) - return 'fail' + assert f is None and gdal.VSIGetLastErrorMsg().find('OSS_SECRET_ACCESS_KEY') >= 0 gdal.ErrorReset() with gdaltest.error_handler(): f = open_for_read('/vsioss_streaming/foo/bar') - if f is not None or gdal.VSIGetLastErrorMsg().find('OSS_SECRET_ACCESS_KEY') < 0: - gdaltest.post_reason('fail') - print(gdal.VSIGetLastErrorMsg()) - return 'fail' + assert f is None and gdal.VSIGetLastErrorMsg().find('OSS_SECRET_ACCESS_KEY') >= 0 gdal.SetConfigOption('OSS_SECRET_ACCESS_KEY', 'OSS_SECRET_ACCESS_KEY') @@ -93,23 +83,18 @@ def visoss_1(): gdal.ErrorReset() with gdaltest.error_handler(): f = open_for_read('/vsioss/foo/bar') - if f is not None or gdal.VSIGetLastErrorMsg().find('OSS_ACCESS_KEY_ID') < 0: - gdaltest.post_reason('fail') - print(gdal.VSIGetLastErrorMsg()) - return 'fail' + assert f is None and gdal.VSIGetLastErrorMsg().find('OSS_ACCESS_KEY_ID') >= 0 gdal.SetConfigOption('OSS_ACCESS_KEY_ID', 'OSS_ACCESS_KEY_ID') - return 'success' - -def visoss_real_test(): +def test_visoss_real_test(): if not gdaltest.built_against_curl(): - return 'skip' + pytest.skip() if gdaltest.skip_on_travis(): - return 'skip' + pytest.skip() # ERROR 1: The OSS Access Key Id you provided does not exist in our records. gdal.ErrorReset() @@ -119,35 +104,28 @@ def visoss_real_test(): 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('/vsioss_streaming/foo/bar.baz') - if f is not None or gdal.VSIGetLastErrorMsg() == '': - gdaltest.post_reason('fail') - print(gdal.VSIGetLastErrorMsg()) - return 'fail' - - return 'success' + assert f is None and gdal.VSIGetLastErrorMsg() != '' ############################################################################### -def visoss_start_webserver(): +def test_visoss_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('OSS_SECRET_ACCESS_KEY', 'OSS_SECRET_ACCESS_KEY') gdal.SetConfigOption('OSS_ACCESS_KEY_ID', 'OSS_ACCESS_KEY_ID') @@ -156,8 +134,6 @@ def visoss_start_webserver(): gdal.SetConfigOption('OSS_VIRTUAL_HOSTING', 'NO') gdal.SetConfigOption('OSS_ENDPOINT', '127.0.0.1:%d' % gdaltest.webserver_port) - return 'success' - ############################################################################### @@ -185,49 +161,36 @@ def get_oss_fake_bucket_resource_method(request): # Test with a fake OSS server -def visoss_2(): +def test_visoss_2(): if gdaltest.webserver_port == 0: - return 'skip' + pytest.skip() signed_url = gdal.GetSignedURL('/vsioss/oss_fake_bucket/resource', ['START_DATE=20180212T123456Z']) - if signed_url not in ('http://127.0.0.1:8080/oss_fake_bucket/resource?Expires=1518442496&OSSAccessKeyId=OSS_ACCESS_KEY_ID&Signature=bpFqur6tQMNN7Xe7UHVFFrugmgs%3D', - 'http://127.0.0.1:8081/oss_fake_bucket/resource?Expires=1518442496&OSSAccessKeyId=OSS_ACCESS_KEY_ID&Signature=bpFqur6tQMNN7Xe7UHVFFrugmgs%3D'): - gdaltest.post_reason('fail') - print(signed_url) - return 'fail' + assert (signed_url in ('http://127.0.0.1:8080/oss_fake_bucket/resource?Expires=1518442496&OSSAccessKeyId=OSS_ACCESS_KEY_ID&Signature=bpFqur6tQMNN7Xe7UHVFFrugmgs%3D', + 'http://127.0.0.1:8081/oss_fake_bucket/resource?Expires=1518442496&OSSAccessKeyId=OSS_ACCESS_KEY_ID&Signature=bpFqur6tQMNN7Xe7UHVFFrugmgs%3D')) handler = webserver.SequentialHandler() handler.add('GET', '/oss_fake_bucket/resource', custom_method=get_oss_fake_bucket_resource_method) with webserver.install_http_handler(handler): f = open_for_read('/vsioss/oss_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('GET', '/oss_fake_bucket/resource', custom_method=get_oss_fake_bucket_resource_method) with webserver.install_http_handler(handler): f = open_for_read('/vsioss_streaming/oss_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() @@ -269,36 +232,26 @@ def method(request): # Test region and endpoint 'redirects' with webserver.install_http_handler(handler): f = open_for_read('/vsioss/oss_fake_bucket/redirect') - 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': 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') - print(data) - return 'fail' + pytest.fail(data) # Test region and endpoint 'redirects' handler.req_count = 0 with webserver.install_http_handler(handler): f = open_for_read('/vsioss_streaming/oss_fake_bucket/redirect') - 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() @@ -324,10 +277,7 @@ def method(request): with webserver.install_http_handler(handler): with gdaltest.error_handler(): f = open_for_read('/vsioss_streaming/oss_fake_bucket/non_xml_error') - if f is not None or gdal.VSIGetLastErrorMsg().find('bla') < 0: - gdaltest.post_reason('fail') - print(gdal.VSIGetLastErrorMsg()) - return 'fail' + assert f is None and gdal.VSIGetLastErrorMsg().find('bla') >= 0 handler = webserver.SequentialHandler() response = '<?xml version="1.0" encoding="UTF-8"?><oops>' @@ -340,10 +290,7 @@ def method(request): with webserver.install_http_handler(handler): with gdaltest.error_handler(): f = open_for_read('/vsioss_streaming/oss_fake_bucket/invalid_xml_error') - if f is not None or gdal.VSIGetLastErrorMsg().find('<oops>') < 0: - gdaltest.post_reason('fail') - print(gdal.VSIGetLastErrorMsg()) - return 'fail' + assert f is None and gdal.VSIGetLastErrorMsg().find('<oops>') >= 0 handler = webserver.SequentialHandler() response = '<?xml version="1.0" encoding="UTF-8"?><Error/>' @@ -356,10 +303,7 @@ def method(request): with webserver.install_http_handler(handler): with gdaltest.error_handler(): f = open_for_read('/vsioss_streaming/oss_fake_bucket/no_code_in_error') - if f is not None or gdal.VSIGetLastErrorMsg().find('<Error/>') < 0: - gdaltest.post_reason('fail') - print(gdal.VSIGetLastErrorMsg()) - return 'fail' + assert f is None and gdal.VSIGetLastErrorMsg().find('<Error/>') >= 0 handler = webserver.SequentialHandler() response = '<?xml version="1.0" encoding="UTF-8"?><Error><Code>AuthorizationHeaderMalformed</Code></Error>' @@ -372,10 +316,7 @@ def method(request): with webserver.install_http_handler(handler): with gdaltest.error_handler(): f = open_for_read('/vsioss_streaming/oss_fake_bucket/no_region_in_AuthorizationHeaderMalformed_error') - if f is not None or gdal.VSIGetLastErrorMsg().find('<Error>') < 0: - gdaltest.post_reason('fail') - print(gdal.VSIGetLastErrorMsg()) - return 'fail' + assert f is None and gdal.VSIGetLastErrorMsg().find('<Error>') >= 0 handler = webserver.SequentialHandler() response = '<?xml version="1.0" encoding="UTF-8"?><Error><Code>PermanentRedirect</Code></Error>' @@ -388,10 +329,7 @@ def method(request): with webserver.install_http_handler(handler): with gdaltest.error_handler(): f = open_for_read('/vsioss_streaming/oss_fake_bucket/no_endpoint_in_PermanentRedirect_error') - if f is not None or gdal.VSIGetLastErrorMsg().find('<Error>') < 0: - gdaltest.post_reason('fail') - print(gdal.VSIGetLastErrorMsg()) - return 'fail' + assert f is None and gdal.VSIGetLastErrorMsg().find('<Error>') >= 0 handler = webserver.SequentialHandler() response = '<?xml version="1.0" encoding="UTF-8"?><Error><Code>bla</Code></Error>' @@ -404,21 +342,16 @@ def method(request): with webserver.install_http_handler(handler): with gdaltest.error_handler(): f = open_for_read('/vsioss_streaming/oss_fake_bucket/no_message_in_error') - if f is not None or gdal.VSIGetLastErrorMsg().find('<Error>') < 0: - gdaltest.post_reason('fail') - print(gdal.VSIGetLastErrorMsg()) - return 'fail' - - return 'success' + assert f is None and gdal.VSIGetLastErrorMsg().find('<Error>') >= 0 ############################################################################### # Test ReadDir() with a fake OSS server -def visoss_3(): +def test_visoss_3(): if gdaltest.webserver_port == 0: - return 'skip' + pytest.skip() handler = webserver.SequentialHandler() @@ -471,31 +404,20 @@ def method(request): 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) with webserver.install_http_handler(webserver.SequentialHandler()): dir_contents = gdal.ReadDir('/vsioss/oss_fake_bucket2/a_dir') - if dir_contents != ['resource3.bin', 'resource4.bin', 'subdir']: - gdaltest.post_reason('fail') - print(dir_contents) - return 'fail' - if gdal.VSIStatL('/vsioss/oss_fake_bucket2/a_dir/resource3.bin').size != 123456: - gdaltest.post_reason('fail') - return 'fail' - if gdal.VSIStatL('/vsioss/oss_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('/vsioss/oss_fake_bucket2/a_dir/resource3.bin').size == 123456 + assert gdal.VSIStatL('/vsioss/oss_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('/vsioss/oss_fake_bucket2/a_dir/resource3.bin') - if dir_contents is not None: - gdaltest.post_reason('fail') - return 'fail' + assert dir_contents is None # Test CPL_VSIL_CURL_NON_CACHED for config_option_value in ['/vsioss/oss_non_cached/test.txt', @@ -510,28 +432,17 @@ def method(request): with webserver.install_http_handler(handler): f = open_for_read('/vsioss/oss_non_cached/test.txt') - if f is None: - gdaltest.post_reason('fail') - print(config_option_value) - return 'fail' + assert f is not None, config_option_value data = gdal.VSIFReadL(1, 3, f).decode('ascii') gdal.VSIFCloseL(f) - if data != 'foo': - gdaltest.post_reason('fail') - print(config_option_value) - print(data) - return 'fail' + assert data == 'foo', config_option_value handler = webserver.SequentialHandler() handler.add('GET', '/oss_non_cached/test.txt', 200, {}, 'bar2') with webserver.install_http_handler(handler): size = gdal.VSIStatL('/vsioss/oss_non_cached/test.txt').size - if size != 4: - gdaltest.post_reason('fail') - print(config_option_value) - print(size) - return 'fail' + assert size == 4, config_option_value handler = webserver.SequentialHandler() handler.add('GET', '/oss_non_cached/test.txt', 200, {}, 'foo') @@ -539,27 +450,18 @@ def method(request): with webserver.install_http_handler(handler): size = gdal.VSIStatL('/vsioss/oss_non_cached/test.txt').size if size != 3: - gdaltest.post_reason('fail') print(config_option_value) - print(data) - return 'fail' + pytest.fail(data) handler = webserver.SequentialHandler() handler.add('GET', '/oss_non_cached/test.txt', 200, {}, 'bar2') with webserver.install_http_handler(handler): f = open_for_read('/vsioss/oss_non_cached/test.txt') - if f is None: - gdaltest.post_reason('fail') - print(config_option_value) - return 'fail' + assert f is not None, config_option_value data = gdal.VSIFReadL(1, 4, f).decode('ascii') gdal.VSIFCloseL(f) - if data != 'bar2': - gdaltest.post_reason('fail') - print(config_option_value) - print(data) - return 'fail' + assert data == 'bar2', config_option_value # Retry without option for config_option_value in [None, @@ -588,33 +490,19 @@ def method(request): with webserver.install_http_handler(handler): f = open_for_read('/vsioss/oss_non_cached/test.txt') - if f is None: - gdaltest.post_reason('fail') - print(config_option_value) - return 'fail' + assert f is not None, config_option_value data = gdal.VSIFReadL(1, 3, f).decode('ascii') gdal.VSIFCloseL(f) - if data != 'foo': - gdaltest.post_reason('fail') - print(config_option_value) - print(data) - return 'fail' + assert data == 'foo', config_option_value handler = webserver.SequentialHandler() with webserver.install_http_handler(handler): f = open_for_read('/vsioss/oss_non_cached/test.txt') - if f is None: - gdaltest.post_reason('fail') - print(config_option_value) - return 'fail' + assert f is not None, config_option_value data = gdal.VSIFReadL(1, 4, f).decode('ascii') gdal.VSIFCloseL(f) # We should still get foo because of caching - if data != 'foo': - gdaltest.post_reason('fail') - print(config_option_value) - print(data) - return 'fail' + assert data == 'foo', config_option_value # List buckets (empty result) handler = webserver.SequentialHandler() @@ -627,10 +515,7 @@ def method(request): """) with webserver.install_http_handler(handler): dir_contents = gdal.ReadDir('/vsioss/') - if dir_contents != ['.']: - gdaltest.post_reason('fail') - print(dir_contents) - return 'fail' + assert dir_contents == ['.'] gdal.VSICurlClearCache() @@ -648,35 +533,26 @@ def method(request): """) with webserver.install_http_handler(handler): dir_contents = gdal.ReadDir('/vsioss/') - if dir_contents != ['mybucket']: - gdaltest.post_reason('fail') - print(dir_contents) - return 'fail' - - return 'success' + assert dir_contents == ['mybucket'] ############################################################################### # Test simple PUT support with a fake OSS server -def visoss_4(): +def test_visoss_4(): if gdaltest.webserver_port == 0: - return 'skip' + pytest.skip() with webserver.install_http_handler(webserver.SequentialHandler()): with gdaltest.error_handler(): f = gdal.VSIFOpenL('/vsioss/oss_fake_bucket3', 'wb') - if f is not None: - gdaltest.post_reason('fail') - return 'fail' + assert f is None handler = webserver.SequentialHandler() handler.add('GET', '/oss_fake_bucket3/empty_file.bin', 200, {'Connection': 'close'}, 'foo') with webserver.install_http_handler(handler): - if gdal.VSIStatL('/vsioss/oss_fake_bucket3/empty_file.bin').size != 3: - gdaltest.post_reason('fail') - return 'fail' + assert gdal.VSIStatL('/vsioss/oss_fake_bucket3/empty_file.bin').size == 3 # Empty file handler = webserver.SequentialHandler() @@ -695,48 +571,34 @@ def method(request): with webserver.install_http_handler(handler): f = gdal.VSIFOpenL('/vsioss/oss_fake_bucket3/empty_file.bin', 'wb') - if f is None: - gdaltest.post_reason('fail') - return 'fail' + assert f is not None gdal.ErrorReset() gdal.VSIFCloseL(f) - if gdal.GetLastErrorMsg() != '': - gdaltest.post_reason('fail') - return 'fail' + assert gdal.GetLastErrorMsg() == '' handler = webserver.SequentialHandler() handler.add('GET', '/oss_fake_bucket3/empty_file.bin', 200, {'Connection': 'close'}, '') with webserver.install_http_handler(handler): - if gdal.VSIStatL('/vsioss/oss_fake_bucket3/empty_file.bin').size != 0: - gdaltest.post_reason('fail') - return 'fail' + assert gdal.VSIStatL('/vsioss/oss_fake_bucket3/empty_file.bin').size == 0 # Invalid seek handler = webserver.SequentialHandler() with webserver.install_http_handler(handler): f = gdal.VSIFOpenL('/vsioss/oss_fake_bucket3/empty_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) # Invalid read handler = webserver.SequentialHandler() with webserver.install_http_handler(handler): f = gdal.VSIFOpenL('/vsioss/oss_fake_bucket3/empty_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') - return 'fail' + assert not ret gdal.VSIFCloseL(f) # Error case @@ -744,40 +606,22 @@ def method(request): handler.add('PUT', '/oss_fake_bucket3/empty_file_error.bin', 403) with webserver.install_http_handler(handler): f = gdal.VSIFOpenL('/vsioss/oss_fake_bucket3/empty_file_error.bin', 'wb') - if f is None: - gdaltest.post_reason('fail') - return 'fail' + assert f is not None gdal.ErrorReset() with gdaltest.error_handler(): gdal.VSIFCloseL(f) - if gdal.GetLastErrorMsg() == '': - gdaltest.post_reason('fail') - return 'fail' + assert gdal.GetLastErrorMsg() != '' # Nominal case with webserver.install_http_handler(webserver.SequentialHandler()): f = gdal.VSIFOpenL('/vsioss/oss_fake_bucket3/another_file.bin', 'wb') - if f is None: - gdaltest.post_reason('fail') - return 'fail' - if gdal.VSIFSeekL(f, gdal.VSIFTellL(f), 0) != 0: - gdaltest.post_reason('fail') - return 'fail' - if gdal.VSIFSeekL(f, 0, 1) != 0: - gdaltest.post_reason('fail') - return 'fail' - if gdal.VSIFSeekL(f, 0, 2) != 0: - gdaltest.post_reason('fail') - return 'fail' - if gdal.VSIFWriteL('foo', 1, 3, f) != 3: - gdaltest.post_reason('fail') - return 'fail' - if gdal.VSIFSeekL(f, gdal.VSIFTellL(f), 0) != 0: - gdaltest.post_reason('fail') - return 'fail' - if gdal.VSIFWriteL('bar', 1, 3, f) != 3: - gdaltest.post_reason('fail') - return 'fail' + assert f is not None + assert gdal.VSIFSeekL(f, gdal.VSIFTellL(f), 0) == 0 + assert gdal.VSIFSeekL(f, 0, 1) == 0 + assert gdal.VSIFSeekL(f, 0, 2) == 0 + assert gdal.VSIFWriteL('foo', 1, 3, f) == 3 + assert gdal.VSIFSeekL(f, gdal.VSIFTellL(f), 0) == 0 + assert gdal.VSIFWriteL('bar', 1, 3, f) == 3 handler = webserver.SequentialHandler() @@ -808,55 +652,41 @@ def method(request): gdal.ErrorReset() with webserver.install_http_handler(handler): gdal.VSIFCloseL(f) - if gdal.GetLastErrorMsg() != '': - gdaltest.post_reason('fail') - return 'fail' - - return 'success' + assert gdal.GetLastErrorMsg() == '' ############################################################################### # Test simple DELETE support with a fake OSS server -def visoss_5(): +def test_visoss_5(): if gdaltest.webserver_port == 0: - return 'skip' + pytest.skip() with webserver.install_http_handler(webserver.SequentialHandler()): with gdaltest.error_handler(): ret = gdal.Unlink('/vsioss/foo') - if ret == 0: - gdaltest.post_reason('fail') - return 'fail' + assert ret != 0 handler = webserver.SequentialHandler() handler.add('GET', '/oss_delete_bucket/delete_file', 200, {'Connection': 'close'}, 'foo') with webserver.install_http_handler(handler): - if gdal.VSIStatL('/vsioss/oss_delete_bucket/delete_file').size != 3: - gdaltest.post_reason('fail') - return 'fail' + assert gdal.VSIStatL('/vsioss/oss_delete_bucket/delete_file').size == 3 with webserver.install_http_handler(webserver.SequentialHandler()): - if gdal.VSIStatL('/vsioss/oss_delete_bucket/delete_file').size != 3: - gdaltest.post_reason('fail') - return 'fail' + assert gdal.VSIStatL('/vsioss/oss_delete_bucket/delete_file').size == 3 handler = webserver.SequentialHandler() handler.add('DELETE', '/oss_delete_bucket/delete_file', 204) with webserver.install_http_handler(handler): ret = gdal.Unlink('/vsioss/oss_delete_bucket/delete_file') - if ret != 0: - gdaltest.post_reason('fail') - return 'fail' + assert ret == 0 handler = webserver.SequentialHandler() handler.add('GET', '/oss_delete_bucket/delete_file', 404, {'Connection': 'close'}, 'foo') handler.add('GET', '/oss_delete_bucket/?delimiter=%2F&max-keys=100&prefix=delete_file%2F', 404, {'Connection': 'close'}, 'foo') with webserver.install_http_handler(handler): - if gdal.VSIStatL('/vsioss/oss_delete_bucket/delete_file') is not None: - gdaltest.post_reason('fail') - return 'fail' + assert gdal.VSIStatL('/vsioss/oss_delete_bucket/delete_file') is None handler = webserver.SequentialHandler() handler.add('GET', '/oss_delete_bucket/delete_file_error', 200) @@ -864,27 +694,21 @@ def visoss_5(): with webserver.install_http_handler(handler): with gdaltest.error_handler(): ret = gdal.Unlink('/vsioss/oss_delete_bucket/delete_file_error') - if ret == 0: - gdaltest.post_reason('fail') - return 'fail' - - return 'success' + assert ret != 0 ############################################################################### # Test multipart upload with a fake OSS server -def visoss_6(): +def test_visoss_6(): if gdaltest.webserver_port == 0: - return 'skip' + pytest.skip() with gdaltest.config_option('VSIOSS_CHUNK_SIZE', '1'): # 1 MB with webserver.install_http_handler(webserver.SequentialHandler()): f = gdal.VSIFOpenL('/vsioss/oss_fake_bucket4/large_file.bin', 'wb') - if f is None: - gdaltest.post_reason('fail') - return 'fail' + assert f is not None size = 1024 * 1024 + 1 big_buffer = 'a' * size @@ -917,9 +741,7 @@ def method(request): with webserver.install_http_handler(handler): ret = gdal.VSIFWriteL(big_buffer, 1, size, f) - if ret != size: - gdaltest.post_reason('fail') - return 'fail' + assert ret == size handler = webserver.SequentialHandler() def method(request): @@ -966,9 +788,7 @@ def method(request): gdal.ErrorReset() with webserver.install_http_handler(handler): gdal.VSIFCloseL(f) - if gdal.GetLastErrorMsg() != '': - gdaltest.post_reason('fail') - return 'fail' + assert gdal.GetLastErrorMsg() == '' handler = webserver.SequentialHandler() handler.add('POST', '/oss_fake_bucket4/large_file_initiate_403_error.bin?uploads', 403) @@ -982,20 +802,13 @@ def method(request): '/vsioss/oss_fake_bucket4/large_file_initiate_no_uploadId.bin']: with gdaltest.config_option('VSIOSS_CHUNK_SIZE', '1'): # 1 MB f = gdal.VSIFOpenL(filename, 'wb') - if f is None: - gdaltest.post_reason('fail') - return 'fail' + assert f is not None with gdaltest.error_handler(): ret = gdal.VSIFWriteL(big_buffer, 1, size, f) - if ret != 0: - gdaltest.post_reason('fail') - print(ret) - return 'fail' + assert ret == 0 gdal.ErrorReset() gdal.VSIFCloseL(f) - if gdal.GetLastErrorMsg() != '': - gdaltest.post_reason('fail') - return 'fail' + assert gdal.GetLastErrorMsg() == '' handler = webserver.SequentialHandler() handler.add('POST', '/oss_fake_bucket4/large_file_upload_part_403_error.bin?uploads', 200, {}, @@ -1013,23 +826,13 @@ def method(request): '/vsioss/oss_fake_bucket4/large_file_upload_part_no_etag.bin']: with gdaltest.config_option('VSIOSS_CHUNK_SIZE', '1'): # 1 MB f = gdal.VSIFOpenL(filename, 'wb') - if f is None: - gdaltest.post_reason('fail') - print(filename) - return 'fail' + assert f is not None, filename with gdaltest.error_handler(): ret = gdal.VSIFWriteL(big_buffer, 1, size, f) - if ret != 0: - gdaltest.post_reason('fail') - print(filename) - print(ret) - return 'fail' + assert ret == 0, filename gdal.ErrorReset() gdal.VSIFCloseL(f) - if gdal.GetLastErrorMsg() != '': - gdaltest.post_reason('fail') - print(filename) - return 'fail' + assert gdal.GetLastErrorMsg() == '', filename # Simulate failure in AbortMultipart stage handler = webserver.SequentialHandler() @@ -1042,24 +845,14 @@ def method(request): with webserver.install_http_handler(handler): with gdaltest.config_option('VSIOSS_CHUNK_SIZE', '1'): # 1 MB f = gdal.VSIFOpenL(filename, 'wb') - if f is None: - gdaltest.post_reason('fail') - print(filename) - return 'fail' + assert f is not None, filename with gdaltest.error_handler(): ret = gdal.VSIFWriteL(big_buffer, 1, size, f) - if ret != 0: - gdaltest.post_reason('fail') - print(filename) - print(ret) - return 'fail' + assert ret == 0, filename gdal.ErrorReset() with gdaltest.error_handler(): gdal.VSIFCloseL(f) - if gdal.GetLastErrorMsg() == '': - gdaltest.post_reason('fail') - print(filename) - return 'fail' + assert gdal.GetLastErrorMsg() != '', filename # Simulate failure in CompleteMultipartUpload stage handler = webserver.SequentialHandler() @@ -1074,34 +867,23 @@ def method(request): with webserver.install_http_handler(handler): with gdaltest.config_option('VSIOSS_CHUNK_SIZE', '1'): # 1 MB f = gdal.VSIFOpenL(filename, 'wb') - if f is None: - gdaltest.post_reason('fail') - print(filename) - return 'fail' + assert f is not None, filename ret = gdal.VSIFWriteL(big_buffer, 1, size, f) - if ret != size: - gdaltest.post_reason('fail') - print(filename) - print(ret) - return 'fail' + assert ret == size, filename gdal.ErrorReset() with gdaltest.error_handler(): gdal.VSIFCloseL(f) - if gdal.GetLastErrorMsg() == '': - gdaltest.post_reason('fail') - print(filename) - return 'fail' - - return 'success' + assert gdal.GetLastErrorMsg() != '', filename + ############################################################################### # Test Mkdir() / Rmdir() -def visoss_7(): +def test_visoss_7(): if gdaltest.webserver_port == 0: - return 'skip' + pytest.skip() handler = webserver.SequentialHandler() handler.add('GET', '/oss_bucket_test_mkdir/dir/', 404, {'Connection': 'close'}) @@ -1109,26 +891,20 @@ def visoss_7(): handler.add('PUT', '/oss_bucket_test_mkdir/dir/', 200) with webserver.install_http_handler(handler): ret = gdal.Mkdir('/vsioss/oss_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() handler.add('GET', '/oss_bucket_test_mkdir/dir/', 416) with webserver.install_http_handler(handler): ret = gdal.Mkdir('/vsioss/oss_bucket_test_mkdir/dir', 0) - if ret == 0: - gdaltest.post_reason('fail') - return 'fail' + assert ret != 0 handler = webserver.SequentialHandler() handler.add('DELETE', '/oss_bucket_test_mkdir/dir/', 204) with webserver.install_http_handler(handler): ret = gdal.Rmdir('/vsioss/oss_bucket_test_mkdir/dir') - if ret != 0: - gdaltest.post_reason('fail') - return 'fail' + assert ret == 0 # Try deleting already deleted directory handler = webserver.SequentialHandler() @@ -1136,9 +912,7 @@ def visoss_7(): handler.add('GET', '/oss_bucket_test_mkdir/?delimiter=%2F&max-keys=100&prefix=dir%2F', 404, {'Connection': 'close'}) with webserver.install_http_handler(handler): ret = gdal.Rmdir('/vsioss/oss_bucket_test_mkdir/dir') - if ret == 0: - gdaltest.post_reason('fail') - return 'fail' + assert ret != 0 # Try deleting non-empty directory handler = webserver.SequentialHandler() @@ -1157,20 +931,16 @@ def visoss_7(): """) with webserver.install_http_handler(handler): ret = gdal.Rmdir('/vsioss/oss_bucket_test_mkdir/dir_nonempty') - if ret == 0: - gdaltest.post_reason('fail') - return 'fail' - - return 'success' + assert ret != 0 ############################################################################### # Test handling of file and directory with same name -def visoss_8(): +def test_visoss_8(): if gdaltest.webserver_port == 0: - return 'skip' + pytest.skip() handler = webserver.SequentialHandler() handler.add('GET', '/visoss_8/?delimiter=%2F', 200, @@ -1191,32 +961,24 @@ def visoss_8(): with webserver.install_http_handler(handler): listdir = gdal.ReadDir('/vsioss/visoss_8', 0) - if listdir != ['test', 'test/']: - gdaltest.post_reason('fail') - print(listdir) - return 'fail' + assert listdir == ['test', 'test/'] handler = webserver.SequentialHandler() with webserver.install_http_handler(handler): - if stat.S_ISDIR(gdal.VSIStatL('/vsioss/visoss_8/test').mode): - gdaltest.post_reason('fail') - return 'fail' + assert not stat.S_ISDIR(gdal.VSIStatL('/vsioss/visoss_8/test').mode) handler = webserver.SequentialHandler() with webserver.install_http_handler(handler): - if not stat.S_ISDIR(gdal.VSIStatL('/vsioss/visoss_8/test/').mode): - gdaltest.post_reason('fail') - return 'fail' - - return 'success' + assert stat.S_ISDIR(gdal.VSIStatL('/vsioss/visoss_8/test/').mode) + ############################################################################### -def visoss_stop_webserver(): +def test_visoss_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 @@ -1224,160 +986,102 @@ def visoss_stop_webserver(): webserver.server_stop(gdaltest.webserver_process, gdaltest.webserver_port) - return 'success' - ############################################################################### # Nominal cases (require valid credentials) -def visoss_extra_1(): +def test_visoss_extra_1(): if not gdaltest.built_against_curl(): - return 'skip' + pytest.skip() # Either a bucket name or bucket/filename OSS_RESOURCE = gdal.GetConfigOption('OSS_RESOURCE') if gdal.GetConfigOption('OSS_SECRET_ACCESS_KEY') is None: - print('Missing OSS_SECRET_ACCESS_KEY for running gdaltest_list_extra') - return 'skip' + pytest.skip('Missing OSS_SECRET_ACCESS_KEY') elif gdal.GetConfigOption('OSS_ACCESS_KEY_ID') is None: - print('Missing OSS_ACCESS_KEY_ID for running gdaltest_list_extra') - return 'skip' + pytest.skip('Missing OSS_ACCESS_KEY_ID') elif OSS_RESOURCE is None: - print('Missing OSS_RESOURCE for running gdaltest_list_extra') - return 'skip' + pytest.skip('Missing OSS_RESOURCE') if OSS_RESOURCE.find('/') < 0: path = '/vsioss/' + OSS_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 = 'visoss_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('/vsioss/' + OSS_RESOURCE) - if f is None: - gdaltest.post_reason('fail') - print('cannot open %s' % ('/vsioss/' + OSS_RESOURCE)) - return 'fail' + assert f is not None, ('cannot open %s' % ('/vsioss/' + OSS_RESOURCE)) 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 /vsioss_streaming/ f = open_for_read('/vsioss_streaming/' + OSS_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: @@ -1387,71 +1091,26 @@ def visoss_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('/vsioss_streaming/' + OSS_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('/vsioss/' + OSS_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 visoss_cleanup(): +def test_visoss_cleanup(): for var in gdaltest.oss_vars: gdal.SetConfigOption(var, gdaltest.oss_vars[var]) - - return 'success' - - -gdaltest_list = [visoss_init, - visoss_1, - visoss_real_test, - visoss_start_webserver, - visoss_2, - visoss_3, - visoss_4, - visoss_5, - visoss_6, - visoss_7, - visoss_8, - visoss_stop_webserver, - visoss_cleanup] - -# gdaltest_list = [ visoss_init, visoss_start_webserver, visoss_8, visoss_stop_webserver, visoss_cleanup ] - -gdaltest_list_extra = [visoss_extra_1] - -if __name__ == '__main__': - - gdaltest.setup_run('vsioss') - - if gdal.GetConfigOption('RUN_MANUAL_ONLY', None): - gdaltest.run_tests(gdaltest_list_extra) - else: - gdaltest.run_tests(gdaltest_list + gdaltest_list_extra + [visoss_cleanup]) - - sys.exit(gdaltest.summarize()) diff --git a/autotest/gcore/vsis3.py b/autotest/gcore/vsis3.py index d187199ec2d8..f10f39328122 100755 --- a/autotest/gcore/vsis3.py +++ b/autotest/gcore/vsis3.py @@ -33,10 +33,10 @@ import sys from osgeo import gdal -sys.path.append('../pymod') import gdaltest import webserver +import pytest def open_for_read(uri): @@ -48,7 +48,7 @@ def open_for_read(uri): ############################################################################### -def vsis3_init(): +def test_vsis3_init(): gdaltest.aws_vars = {} for var in ('AWS_SECRET_ACCESS_KEY', 'AWS_ACCESS_KEY_ID', 'AWS_TIMESTAMP', 'AWS_HTTPS', 'AWS_VIRTUAL_HOSTING', 'AWS_S3_ENDPOINT', 'AWS_REQUEST_PAYER', 'AWS_DEFAULT_REGION', 'AWS_DEFAULT_PROFILE', 'AWS_NO_SIGN_REQUEST'): @@ -62,69 +62,51 @@ def vsis3_init(): gdal.SetConfigOption('AWS_CONFIG_FILE', '') gdal.SetConfigOption('CPL_AWS_EC2_CREDENTIALS_URL', '') - if gdal.GetSignedURL('/vsis3/foo/bar') is not None: - gdaltest.post_reason('fail') - return 'fail' - - return 'success' + assert gdal.GetSignedURL('/vsis3/foo/bar') is None ############################################################################### # Test AWS_NO_SIGN_REQUEST=YES -def vsis3_no_sign_request(): +def test_vsis3_no_sign_request(): if not gdaltest.built_against_curl(): - return 'skip' + pytest.skip() with gdaltest.config_option('AWS_NO_SIGN_REQUEST', 'YES'): actual_url = gdal.GetActualURL('/vsis3/landsat-pds/L8/001/002/LC80010022016230LGN00/LC80010022016230LGN00_B1.TIF') - if actual_url != 'https://landsat-pds.s3.amazonaws.com/L8/001/002/LC80010022016230LGN00/LC80010022016230LGN00_B1.TIF': - gdaltest.post_reason('fail') - print(actual_url) - return 'fail' + assert actual_url == 'https://landsat-pds.s3.amazonaws.com/L8/001/002/LC80010022016230LGN00/LC80010022016230LGN00_B1.TIF' actual_url = gdal.GetActualURL('/vsis3_streaming/landsat-pds/L8/001/002/LC80010022016230LGN00/LC80010022016230LGN00_B1.TIF') - if actual_url != 'https://landsat-pds.s3.amazonaws.com/L8/001/002/LC80010022016230LGN00/LC80010022016230LGN00_B1.TIF': - gdaltest.post_reason('fail') - print(actual_url) - return 'fail' + assert actual_url == 'https://landsat-pds.s3.amazonaws.com/L8/001/002/LC80010022016230LGN00/LC80010022016230LGN00_B1.TIF' f = open_for_read('/vsis3/landsat-pds/L8/001/002/LC80010022016230LGN00/LC80010022016230LGN00_B1.TIF') if f is None: if gdaltest.gdalurlopen('https://landsat-pds.s3.amazonaws.com/L8/001/002/LC80010022016230LGN00/LC80010022016230LGN00_B1.TIF') is None: - print('cannot open URL') - return 'skip' - return 'fail' + pytest.skip('cannot open URL') + pytest.fail() gdal.VSIFCloseL(f) - return 'success' ############################################################################### # Error cases -def vsis3_1(): +def test_vsis3_1(): if not gdaltest.built_against_curl(): - return 'skip' + pytest.skip() # Missing AWS_SECRET_ACCESS_KEY gdal.ErrorReset() with gdaltest.error_handler(): f = open_for_read('/vsis3/foo/bar') - if f is not None or gdal.VSIGetLastErrorMsg().find('AWS_SECRET_ACCESS_KEY') < 0: - gdaltest.post_reason('fail') - print(gdal.VSIGetLastErrorMsg()) - return 'fail' + assert f is None and gdal.VSIGetLastErrorMsg().find('AWS_SECRET_ACCESS_KEY') >= 0 gdal.ErrorReset() with gdaltest.error_handler(): f = open_for_read('/vsis3_streaming/foo/bar') - if f is not None or gdal.VSIGetLastErrorMsg().find('AWS_SECRET_ACCESS_KEY') < 0: - gdaltest.post_reason('fail') - print(gdal.VSIGetLastErrorMsg()) - return 'fail' + assert f is None and gdal.VSIGetLastErrorMsg().find('AWS_SECRET_ACCESS_KEY') >= 0 gdal.SetConfigOption('AWS_SECRET_ACCESS_KEY', 'AWS_SECRET_ACCESS_KEY') @@ -132,10 +114,7 @@ def vsis3_1(): gdal.ErrorReset() with gdaltest.error_handler(): f = open_for_read('/vsis3/foo/bar') - if f is not None or gdal.VSIGetLastErrorMsg().find('AWS_ACCESS_KEY_ID') < 0: - gdaltest.post_reason('fail') - print(gdal.VSIGetLastErrorMsg()) - return 'fail' + assert f is None and gdal.VSIGetLastErrorMsg().find('AWS_ACCESS_KEY_ID') >= 0 gdal.SetConfigOption('AWS_ACCESS_KEY_ID', 'AWS_ACCESS_KEY_ID') @@ -147,35 +126,28 @@ def vsis3_1(): 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('/vsis3_streaming/foo/bar.baz') - if f is not None or gdal.VSIGetLastErrorMsg() == '': - gdaltest.post_reason('fail') - print(gdal.VSIGetLastErrorMsg()) - return 'fail' - - return 'success' + assert f is None and gdal.VSIGetLastErrorMsg() != '' ############################################################################### -def vsis3_start_webserver(): +def test_vsis3_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('AWS_SECRET_ACCESS_KEY', 'AWS_SECRET_ACCESS_KEY') gdal.SetConfigOption('AWS_ACCESS_KEY_ID', 'AWS_ACCESS_KEY_ID') @@ -184,8 +156,6 @@ def vsis3_start_webserver(): gdal.SetConfigOption('AWS_VIRTUAL_HOSTING', 'NO') gdal.SetConfigOption('AWS_S3_ENDPOINT', '127.0.0.1:%d' % gdaltest.webserver_port) - return 'success' - def get_s3_fake_bucket_resource_method(request): request.protocol_version = 'HTTP/1.1' @@ -212,49 +182,36 @@ def get_s3_fake_bucket_resource_method(request): # Test with a fake AWS server -def vsis3_2(): +def test_vsis3_2(): if gdaltest.webserver_port == 0: - return 'skip' + pytest.skip() signed_url = gdal.GetSignedURL('/vsis3/s3_fake_bucket/resource') expected_url_8080 = 'http://127.0.0.1:8080/s3_fake_bucket/resource?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=AWS_ACCESS_KEY_ID%2F20150101%2Fus-east-1%2Fs3%2Faws4_request&X-Amz-Date=20150101T000000Z&X-Amz-Expires=3600&X-Amz-Signature=dca239dd95f72ff8c37c15c840afc54cd19bdb07f7aaee2223108b5b0ad35da8&X-Amz-SignedHeaders=host' expected_url_8081 = 'http://127.0.0.1:8081/s3_fake_bucket/resource?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=AWS_ACCESS_KEY_ID%2F20150101%2Fus-east-1%2Fs3%2Faws4_request&X-Amz-Date=20150101T000000Z&X-Amz-Expires=3600&X-Amz-Signature=ef5216bc5971863414c69f6ca095276c0d62c0da97fa4f6ab80c30bd7fc146ac&X-Amz-SignedHeaders=host' - if signed_url not in (expected_url_8080, expected_url_8081): - gdaltest.post_reason('fail') - print(signed_url) - return 'fail' + assert signed_url in (expected_url_8080, expected_url_8081) handler = webserver.SequentialHandler() handler.add('GET', '/s3_fake_bucket/resource', custom_method=get_s3_fake_bucket_resource_method) with webserver.install_http_handler(handler): f = open_for_read('/vsis3/s3_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('GET', '/s3_fake_bucket/resource', custom_method=get_s3_fake_bucket_resource_method) with webserver.install_http_handler(handler): f = open_for_read('/vsis3_streaming/s3_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() @@ -284,9 +241,7 @@ def method(request): with gdaltest.config_option('AWS_SESSION_TOKEN', 'AWS_SESSION_TOKEN'): with webserver.install_http_handler(handler): f = open_for_read('/vsis3/s3_fake_bucket_with_session_token/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) @@ -322,12 +277,11 @@ def method(request): stat_res = gdal.VSIStatL('/vsis3/s3_fake_bucket/resource2.bin') # gdal.SetConfigOption('GDAL_DISABLE_READDIR_ON_OPEN', old_val) 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', '/s3_fake_bucket/resource2.bin', 200, @@ -337,12 +291,11 @@ def method(request): with webserver.install_http_handler(handler): stat_res = gdal.VSIStatL('/vsis3_streaming/s3_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() @@ -398,36 +351,26 @@ def method(request): # Test region and endpoint 'redirects' with webserver.install_http_handler(handler): f = open_for_read('/vsis3/s3_fake_bucket/redirect') - 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': 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') - print(data) - return 'fail' + pytest.fail(data) # Test region and endpoint 'redirects' handler.req_count = 0 with webserver.install_http_handler(handler): f = open_for_read('/vsis3_streaming/s3_fake_bucket/redirect') - 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() @@ -454,10 +397,7 @@ def method(request): with webserver.install_http_handler(handler): with gdaltest.error_handler(): f = open_for_read('/vsis3_streaming/s3_fake_bucket/non_xml_error') - if f is not None or gdal.VSIGetLastErrorMsg().find('bla') < 0: - gdaltest.post_reason('fail') - print(gdal.VSIGetLastErrorMsg()) - return 'fail' + assert f is None and gdal.VSIGetLastErrorMsg().find('bla') >= 0 handler = webserver.SequentialHandler() response = '<?xml version="1.0" encoding="UTF-8"?><oops>' @@ -470,10 +410,7 @@ def method(request): with webserver.install_http_handler(handler): with gdaltest.error_handler(): f = open_for_read('/vsis3_streaming/s3_fake_bucket/invalid_xml_error') - if f is not None or gdal.VSIGetLastErrorMsg().find('<oops>') < 0: - gdaltest.post_reason('fail') - print(gdal.VSIGetLastErrorMsg()) - return 'fail' + assert f is None and gdal.VSIGetLastErrorMsg().find('<oops>') >= 0 handler = webserver.SequentialHandler() response = '<?xml version="1.0" encoding="UTF-8"?><Error/>' @@ -486,10 +423,7 @@ def method(request): with webserver.install_http_handler(handler): with gdaltest.error_handler(): f = open_for_read('/vsis3_streaming/s3_fake_bucket/no_code_in_error') - if f is not None or gdal.VSIGetLastErrorMsg().find('<Error/>') < 0: - gdaltest.post_reason('fail') - print(gdal.VSIGetLastErrorMsg()) - return 'fail' + assert f is None and gdal.VSIGetLastErrorMsg().find('<Error/>') >= 0 handler = webserver.SequentialHandler() response = '<?xml version="1.0" encoding="UTF-8"?><Error><Code>AuthorizationHeaderMalformed</Code></Error>' @@ -502,10 +436,7 @@ def method(request): with webserver.install_http_handler(handler): with gdaltest.error_handler(): f = open_for_read('/vsis3_streaming/s3_fake_bucket/no_region_in_AuthorizationHeaderMalformed_error') - if f is not None or gdal.VSIGetLastErrorMsg().find('<Error>') < 0: - gdaltest.post_reason('fail') - print(gdal.VSIGetLastErrorMsg()) - return 'fail' + assert f is None and gdal.VSIGetLastErrorMsg().find('<Error>') >= 0 handler = webserver.SequentialHandler() response = '<?xml version="1.0" encoding="UTF-8"?><Error><Code>PermanentRedirect</Code></Error>' @@ -518,10 +449,7 @@ def method(request): with webserver.install_http_handler(handler): with gdaltest.error_handler(): f = open_for_read('/vsis3_streaming/s3_fake_bucket/no_endpoint_in_PermanentRedirect_error') - if f is not None or gdal.VSIGetLastErrorMsg().find('<Error>') < 0: - gdaltest.post_reason('fail') - print(gdal.VSIGetLastErrorMsg()) - return 'fail' + assert f is None and gdal.VSIGetLastErrorMsg().find('<Error>') >= 0 handler = webserver.SequentialHandler() response = '<?xml version="1.0" encoding="UTF-8"?><Error><Code>bla</Code></Error>' @@ -534,10 +462,7 @@ def method(request): with webserver.install_http_handler(handler): with gdaltest.error_handler(): f = open_for_read('/vsis3_streaming/s3_fake_bucket/no_message_in_error') - if f is not None or gdal.VSIGetLastErrorMsg().find('<Error>') < 0: - gdaltest.post_reason('fail') - print(gdal.VSIGetLastErrorMsg()) - return 'fail' + assert f is None and gdal.VSIGetLastErrorMsg().find('<Error>') >= 0 # Test with requester pays handler = webserver.SequentialHandler() @@ -571,15 +496,11 @@ def method(request): with webserver.install_http_handler(handler): with gdaltest.error_handler(): f = open_for_read('/vsis3/s3_fake_bucket_with_requester_pays/resource') - if f is None: - gdaltest.post_reason('fail') - return 'fail' + assert f is not None data = gdal.VSIFReadL(1, 3, f).decode('ascii') gdal.VSIFCloseL(f) - if data != 'foo': - gdaltest.post_reason('fail') - return 'fail' + assert data == 'foo' # Test temporary redirect handler = webserver.SequentialHandler() @@ -626,16 +547,11 @@ def method_req_2(self, request): with webserver.install_http_handler(handler): f = open_for_read('/vsis3/s3_test_temporary_redirect_read/resource') - if f is None: - gdaltest.post_reason('fail') - return 'fail' + assert f is not None data = gdal.VSIFReadL(1, 3, f).decode('ascii') gdal.VSIFCloseL(f) - if data != 'foo': - gdaltest.post_reason('fail') - print(data) - return 'fail' + assert data == 'foo' # Retry on the same bucket and check that the redirection was indeed temporary handler = webserver.SequentialHandler() @@ -646,27 +562,20 @@ def method_req_2(self, request): with webserver.install_http_handler(handler): f = open_for_read('/vsis3/s3_test_temporary_redirect_read/resource2') - if f is None: - gdaltest.post_reason('fail') - return 'fail' + assert f is not None data = gdal.VSIFReadL(1, 3, f).decode('ascii') gdal.VSIFCloseL(f) - if data != 'bar': - gdaltest.post_reason('fail') - print(data) - return 'fail' - - return 'success' + assert data == 'bar' ############################################################################### # Test ReadDir() with a fake AWS server -def vsis3_readdir(): +def test_vsis3_readdir(): if gdaltest.webserver_port == 0: - return 'skip' + pytest.skip() handler = webserver.SequentialHandler() @@ -757,52 +666,33 @@ def method(request): 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) with webserver.install_http_handler(webserver.SequentialHandler()): dir_contents = gdal.ReadDir('/vsis3/s3_fake_bucket2/a_dir') - if dir_contents != ['resource3.bin', 'resource4.bin', 'subdir']: - gdaltest.post_reason('fail') - print(dir_contents) - return 'fail' - - if gdal.VSIStatL('/vsis3/s3_fake_bucket2/a_dir/resource3.bin').size != 123456: - gdaltest.post_reason('fail') - return 'fail' - if gdal.VSIStatL('/vsis3/s3_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('/vsis3/s3_fake_bucket2/a_dir/resource3.bin').size == 123456 + assert gdal.VSIStatL('/vsis3/s3_fake_bucket2/a_dir/resource3.bin').mtime == 1 # Same as above: cached dir_contents = gdal.ReadDir('/vsis3/s3_fake_bucket2/a_dir') - if dir_contents != ['resource3.bin', 'resource4.bin', 'subdir']: - gdaltest.post_reason('fail') - print(dir_contents) - return 'fail' + assert dir_contents == ['resource3.bin', 'resource4.bin', 'subdir'] # ReadDir on something known to be a file shouldn't cause network access dir_contents = gdal.ReadDir('/vsis3/s3_fake_bucket2/a_dir/resource3.bin') - if dir_contents is not None: - gdaltest.post_reason('fail') - return 'fail' + assert dir_contents is None # Test unrelated partial clear of the cache gdal.VSICurlPartialClearCache('/vsis3/s3_fake_bucket_unrelated') - if gdal.VSIStatL('/vsis3/s3_fake_bucket2/a_dir/resource3.bin').size != 123456: - gdaltest.post_reason('fail') - return 'fail' + assert gdal.VSIStatL('/vsis3/s3_fake_bucket2/a_dir/resource3.bin').size == 123456 dir_contents = gdal.ReadDir('/vsis3/s3_fake_bucket2/a_dir') - if dir_contents != ['resource3.bin', 'resource4.bin', 'subdir']: - gdaltest.post_reason('fail') - print(dir_contents) - return 'fail' + assert dir_contents == ['resource3.bin', 'resource4.bin', 'subdir'] # Test partial clear of the cache gdal.VSICurlPartialClearCache('/vsis3/s3_fake_bucket2/a_dir') @@ -827,10 +717,7 @@ def method(request): """) with webserver.install_http_handler(handler): dir_contents = gdal.ReadDir('/vsis3/s3_fake_bucket2/a_dir') - if dir_contents != ['test.txt']: - gdaltest.post_reason('fail') - print(dir_contents) - return 'fail' + assert dir_contents == ['test.txt'] gdal.VSICurlClearCache() handler = webserver.SequentialHandler() @@ -857,10 +744,7 @@ def method(request): with gdaltest.config_option('CPL_VSIL_CURL_IGNORE_GLACIER_STORAGE', 'NO'): with webserver.install_http_handler(handler): dir_contents = gdal.ReadDir('/vsis3/s3_fake_bucket2/a_dir') - if dir_contents != ['resource4.bin', 'i_am_a_glacier_file', 'subdir']: - gdaltest.post_reason('fail') - print(dir_contents) - return 'fail' + assert dir_contents == ['resource4.bin', 'i_am_a_glacier_file', 'subdir'] # Test CPL_VSIL_CURL_NON_CACHED @@ -876,28 +760,17 @@ def method(request): with webserver.install_http_handler(handler): f = open_for_read('/vsis3/s3_non_cached/test.txt') - if f is None: - gdaltest.post_reason('fail') - print(config_option_value) - return 'fail' + assert f is not None, config_option_value data = gdal.VSIFReadL(1, 3, f).decode('ascii') gdal.VSIFCloseL(f) - if data != 'foo': - gdaltest.post_reason('fail') - print(config_option_value) - print(data) - return 'fail' + assert data == 'foo', config_option_value handler = webserver.SequentialHandler() handler.add('GET', '/s3_non_cached/test.txt', 200, {}, 'bar2') with webserver.install_http_handler(handler): size = gdal.VSIStatL('/vsis3/s3_non_cached/test.txt').size - if size != 4: - gdaltest.post_reason('fail') - print(config_option_value) - print(size) - return 'fail' + assert size == 4, config_option_value handler = webserver.SequentialHandler() handler.add('GET', '/s3_non_cached/test.txt', 200, {}, 'foo') @@ -905,27 +778,18 @@ def method(request): with webserver.install_http_handler(handler): size = gdal.VSIStatL('/vsis3/s3_non_cached/test.txt').size if size != 3: - gdaltest.post_reason('fail') print(config_option_value) - print(data) - return 'fail' + pytest.fail(data) handler = webserver.SequentialHandler() handler.add('GET', '/s3_non_cached/test.txt', 200, {}, 'bar2') with webserver.install_http_handler(handler): f = open_for_read('/vsis3/s3_non_cached/test.txt') - if f is None: - gdaltest.post_reason('fail') - print(config_option_value) - return 'fail' + assert f is not None, config_option_value data = gdal.VSIFReadL(1, 4, f).decode('ascii') gdal.VSIFCloseL(f) - if data != 'bar2': - gdaltest.post_reason('fail') - print(config_option_value) - print(data) - return 'fail' + assert data == 'bar2', config_option_value # Retry without option for config_option_value in [None, @@ -954,33 +818,19 @@ def method(request): with webserver.install_http_handler(handler): f = open_for_read('/vsis3/s3_non_cached/test.txt') - if f is None: - gdaltest.post_reason('fail') - print(config_option_value) - return 'fail' + assert f is not None, config_option_value data = gdal.VSIFReadL(1, 3, f).decode('ascii') gdal.VSIFCloseL(f) - if data != 'foo': - gdaltest.post_reason('fail') - print(config_option_value) - print(data) - return 'fail' + assert data == 'foo', config_option_value handler = webserver.SequentialHandler() with webserver.install_http_handler(handler): f = open_for_read('/vsis3/s3_non_cached/test.txt') - if f is None: - gdaltest.post_reason('fail') - print(config_option_value) - return 'fail' + assert f is not None, config_option_value data = gdal.VSIFReadL(1, 4, f).decode('ascii') gdal.VSIFCloseL(f) # We should still get foo because of caching - if data != 'foo': - gdaltest.post_reason('fail') - print(config_option_value) - print(data) - return 'fail' + assert data == 'foo', config_option_value # List buckets (empty result) handler = webserver.SequentialHandler() @@ -993,10 +843,7 @@ def method(request): """) with webserver.install_http_handler(handler): dir_contents = gdal.ReadDir('/vsis3/') - if dir_contents != ['.']: - gdaltest.post_reason('fail') - print(dir_contents) - return 'fail' + assert dir_contents == ['.'] gdal.VSICurlClearCache() @@ -1014,10 +861,7 @@ def method(request): """) with webserver.install_http_handler(handler): dir_contents = gdal.ReadDir('/vsis3/') - if dir_contents != ['mybucket']: - gdaltest.post_reason('fail') - print(dir_contents) - return 'fail' + assert dir_contents == ['mybucket'] # Test temporary redirect handler = webserver.SequentialHandler() @@ -1072,10 +916,7 @@ def method_req_2(self, request): with webserver.install_http_handler(handler): dir_contents = gdal.ReadDir('/vsis3/s3_test_temporary_redirect_read_dir') - if dir_contents != ['test']: - gdaltest.post_reason('fail') - print(dir_contents) - return 'fail' + assert dir_contents == ['test'] # Retry on the same bucket and check that the redirection was indeed temporary handler = webserver.SequentialHandler() @@ -1093,21 +934,16 @@ def method_req_2(self, request): with webserver.install_http_handler(handler): dir_contents = gdal.ReadDir('/vsis3/s3_test_temporary_redirect_read_dir/test') - if dir_contents != ['test2']: - gdaltest.post_reason('fail') - print(dir_contents) - return 'fail' - - return 'success' + assert dir_contents == ['test2'] ############################################################################### # Test OpenDir() with a fake AWS server -def vsis3_opendir(): +def test_vsis3_opendir(): if gdaltest.webserver_port == 0: - return 'skip' + pytest.skip() # Unlimited depth handler = webserver.SequentialHandler() @@ -1135,48 +971,23 @@ def vsis3_opendir(): """) with webserver.install_http_handler(handler): d = gdal.OpenDir('/vsis3/vsis3_opendir') - if d is None: - gdaltest.post_reason('fail') - return 'fail' + assert d is not None entry = gdal.GetNextDirEntry(d) - if entry.name != 'test.txt': - gdaltest.post_reason('fail') - print(entry.name) - return 'fail' - if entry.size != 40: - gdaltest.post_reason('fail') - print(entry.size) - return 'fail' - if entry.mode != 32768: - gdaltest.post_reason('fail') - print(entry.mode) - return 'fail' - if entry.mtime != 1: - gdaltest.post_reason('fail') - print(entry.mtime) - return 'fail' + assert entry.name == 'test.txt' + assert entry.size == 40 + assert entry.mode == 32768 + assert entry.mtime == 1 entry = gdal.GetNextDirEntry(d) - if entry.name != 'subdir': - gdaltest.post_reason('fail') - print(entry.name) - return 'fail' - if entry.mode != 16384: - gdaltest.post_reason('fail') - print(entry.mode) - return 'fail' + assert entry.name == 'subdir' + assert entry.mode == 16384 entry = gdal.GetNextDirEntry(d) - if entry.name != 'subdir/test.txt': - gdaltest.post_reason('fail') - print(entry.name) - return 'fail' + assert entry.name == 'subdir/test.txt' entry = gdal.GetNextDirEntry(d) - if entry is not None: - gdaltest.post_reason('fail') - return 'fail' + assert entry is None gdal.CloseDir(d) @@ -1199,42 +1010,20 @@ def vsis3_opendir(): """) with webserver.install_http_handler(handler): d = gdal.OpenDir('/vsis3/vsis3_opendir', 0) - if d is None: - gdaltest.post_reason('fail') - return 'fail' + assert d is not None entry = gdal.GetNextDirEntry(d) - if entry.name != 'test.txt': - gdaltest.post_reason('fail') - print(entry.name) - return 'fail' - if entry.size != 40: - gdaltest.post_reason('fail') - print(entry.size) - return 'fail' - if entry.mode != 32768: - gdaltest.post_reason('fail') - print(entry.mode) - return 'fail' - if entry.mtime != 1: - gdaltest.post_reason('fail') - print(entry.mtime) - return 'fail' + assert entry.name == 'test.txt' + assert entry.size == 40 + assert entry.mode == 32768 + assert entry.mtime == 1 entry = gdal.GetNextDirEntry(d) - if entry.name != 'subdir': - gdaltest.post_reason('fail') - print(entry.name) - return 'fail' - if entry.mode != 16384: - gdaltest.post_reason('fail') - print(entry.mode) - return 'fail' + assert entry.name == 'subdir' + assert entry.mode == 16384 entry = gdal.GetNextDirEntry(d) - if entry is not None: - gdaltest.post_reason('fail') - return 'fail' + assert entry is None gdal.CloseDir(d) @@ -1257,37 +1046,17 @@ def vsis3_opendir(): """) with webserver.install_http_handler(handler): d = gdal.OpenDir('/vsis3/vsis3_opendir', 1) - if d is None: - gdaltest.post_reason('fail') - return 'fail' + assert d is not None entry = gdal.GetNextDirEntry(d) - if entry.name != 'test.txt': - gdaltest.post_reason('fail') - print(entry.name) - return 'fail' - if entry.size != 40: - gdaltest.post_reason('fail') - print(entry.size) - return 'fail' - if entry.mode != 32768: - gdaltest.post_reason('fail') - print(entry.mode) - return 'fail' - if entry.mtime != 1: - gdaltest.post_reason('fail') - print(entry.mtime) - return 'fail' + assert entry.name == 'test.txt' + assert entry.size == 40 + assert entry.mode == 32768 + assert entry.mtime == 1 entry = gdal.GetNextDirEntry(d) - if entry.name != 'subdir': - gdaltest.post_reason('fail') - print(entry.name) - return 'fail' - if entry.mode != 16384: - gdaltest.post_reason('fail') - print(entry.mode) - return 'fail' + assert entry.name == 'subdir' + assert entry.mode == 16384 handler = webserver.SequentialHandler() handler.add('GET', '/vsis3_opendir/?delimiter=%2F&prefix=subdir%2F', 200, {'Content-type': 'application/xml'}, @@ -1304,44 +1073,31 @@ def vsis3_opendir(): """) with webserver.install_http_handler(handler): entry = gdal.GetNextDirEntry(d) - if entry.name != 'subdir/test.txt': - gdaltest.post_reason('fail') - print(entry.name) - return 'fail' + assert entry.name == 'subdir/test.txt' entry = gdal.GetNextDirEntry(d) - if entry is not None: - gdaltest.post_reason('fail') - return 'fail' + assert entry is None gdal.CloseDir(d) - - - return 'success' - ############################################################################### # Test simple PUT support with a fake AWS server -def vsis3_4(): +def test_vsis3_4(): if gdaltest.webserver_port == 0: - return 'skip' + pytest.skip() with webserver.install_http_handler(webserver.SequentialHandler()): with gdaltest.error_handler(): f = gdal.VSIFOpenL('/vsis3/s3_fake_bucket3', 'wb') - if f is not None: - gdaltest.post_reason('fail') - return 'fail' + assert f is None handler = webserver.SequentialHandler() handler.add('GET', '/s3_fake_bucket3/empty_file.bin', 200, {'Connection': 'close'}, 'foo') with webserver.install_http_handler(handler): - if gdal.VSIStatL('/vsis3/s3_fake_bucket3/empty_file.bin').size != 3: - gdaltest.post_reason('fail') - return 'fail' + assert gdal.VSIStatL('/vsis3/s3_fake_bucket3/empty_file.bin').size == 3 # Empty file handler = webserver.SequentialHandler() @@ -1360,48 +1116,34 @@ def method(request): with webserver.install_http_handler(handler): f = gdal.VSIFOpenL('/vsis3/s3_fake_bucket3/empty_file.bin', 'wb') - if f is None: - gdaltest.post_reason('fail') - return 'fail' + assert f is not None gdal.ErrorReset() gdal.VSIFCloseL(f) - if gdal.GetLastErrorMsg() != '': - gdaltest.post_reason('fail') - return 'fail' + assert gdal.GetLastErrorMsg() == '' handler = webserver.SequentialHandler() handler.add('GET', '/s3_fake_bucket3/empty_file.bin', 200, {'Connection': 'close'}, '') with webserver.install_http_handler(handler): - if gdal.VSIStatL('/vsis3/s3_fake_bucket3/empty_file.bin').size != 0: - gdaltest.post_reason('fail') - return 'fail' + assert gdal.VSIStatL('/vsis3/s3_fake_bucket3/empty_file.bin').size == 0 # Invalid seek handler = webserver.SequentialHandler() with webserver.install_http_handler(handler): f = gdal.VSIFOpenL('/vsis3/s3_fake_bucket3/empty_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) # Invalid read handler = webserver.SequentialHandler() with webserver.install_http_handler(handler): f = gdal.VSIFOpenL('/vsis3/s3_fake_bucket3/empty_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') - return 'fail' + assert not ret gdal.VSIFCloseL(f) # Error case @@ -1409,40 +1151,22 @@ def method(request): handler.add('PUT', '/s3_fake_bucket3/empty_file_error.bin', 403) with webserver.install_http_handler(handler): f = gdal.VSIFOpenL('/vsis3/s3_fake_bucket3/empty_file_error.bin', 'wb') - if f is None: - gdaltest.post_reason('fail') - return 'fail' + assert f is not None gdal.ErrorReset() with gdaltest.error_handler(): gdal.VSIFCloseL(f) - if gdal.GetLastErrorMsg() == '': - gdaltest.post_reason('fail') - return 'fail' + assert gdal.GetLastErrorMsg() != '' # Nominal case with webserver.install_http_handler(webserver.SequentialHandler()): f = gdal.VSIFOpenL('/vsis3/s3_fake_bucket3/another_file.bin', 'wb') - if f is None: - gdaltest.post_reason('fail') - return 'fail' - if gdal.VSIFSeekL(f, gdal.VSIFTellL(f), 0) != 0: - gdaltest.post_reason('fail') - return 'fail' - if gdal.VSIFSeekL(f, 0, 1) != 0: - gdaltest.post_reason('fail') - return 'fail' - if gdal.VSIFSeekL(f, 0, 2) != 0: - gdaltest.post_reason('fail') - return 'fail' - if gdal.VSIFWriteL('foo', 1, 3, f) != 3: - gdaltest.post_reason('fail') - return 'fail' - if gdal.VSIFSeekL(f, gdal.VSIFTellL(f), 0) != 0: - gdaltest.post_reason('fail') - return 'fail' - if gdal.VSIFWriteL('bar', 1, 3, f) != 3: - gdaltest.post_reason('fail') - return 'fail' + assert f is not None + assert gdal.VSIFSeekL(f, gdal.VSIFTellL(f), 0) == 0 + assert gdal.VSIFSeekL(f, 0, 1) == 0 + assert gdal.VSIFSeekL(f, 0, 2) == 0 + assert gdal.VSIFWriteL('foo', 1, 3, f) == 3 + assert gdal.VSIFSeekL(f, gdal.VSIFTellL(f), 0) == 0 + assert gdal.VSIFWriteL('bar', 1, 3, f) == 3 handler = webserver.SequentialHandler() @@ -1473,19 +1197,13 @@ def method(request): gdal.ErrorReset() with webserver.install_http_handler(handler): gdal.VSIFCloseL(f) - if gdal.GetLastErrorMsg() != '': - gdaltest.post_reason('fail') - return 'fail' + assert gdal.GetLastErrorMsg() == '' # Redirect case with webserver.install_http_handler(webserver.SequentialHandler()): f = gdal.VSIFOpenL('/vsis3/s3_fake_bucket3/redirect', 'wb') - if f is None: - gdaltest.post_reason('fail') - return 'fail' - if gdal.VSIFWriteL('foobar', 1, 6, f) != 6: - gdaltest.post_reason('fail') - return 'fail' + assert f is not None + assert gdal.VSIFWriteL('foobar', 1, 6, f) == 6 handler = webserver.SequentialHandler() @@ -1529,56 +1247,42 @@ def method(request): gdal.ErrorReset() with webserver.install_http_handler(handler): gdal.VSIFCloseL(f) - if gdal.GetLastErrorMsg() != '': - gdaltest.post_reason('fail') - return 'fail' - - return 'success' + assert gdal.GetLastErrorMsg() == '' ############################################################################### # Test simple DELETE support with a fake AWS server -def vsis3_5(): +def test_vsis3_5(): if gdaltest.webserver_port == 0: - return 'skip' + pytest.skip() with webserver.install_http_handler(webserver.SequentialHandler()): with gdaltest.error_handler(): ret = gdal.Unlink('/vsis3/foo') - if ret == 0: - gdaltest.post_reason('fail') - return 'fail' + assert ret != 0 handler = webserver.SequentialHandler() handler.add('GET', '/s3_delete_bucket/delete_file', 200, {'Connection': 'close'}, 'foo') with webserver.install_http_handler(handler): - if gdal.VSIStatL('/vsis3/s3_delete_bucket/delete_file').size != 3: - gdaltest.post_reason('fail') - return 'fail' + assert gdal.VSIStatL('/vsis3/s3_delete_bucket/delete_file').size == 3 handler = webserver.SequentialHandler() with webserver.install_http_handler(handler): - if gdal.VSIStatL('/vsis3/s3_delete_bucket/delete_file').size != 3: - gdaltest.post_reason('fail') - return 'fail' + assert gdal.VSIStatL('/vsis3/s3_delete_bucket/delete_file').size == 3 handler = webserver.SequentialHandler() handler.add('DELETE', '/s3_delete_bucket/delete_file', 204) with webserver.install_http_handler(handler): ret = gdal.Unlink('/vsis3/s3_delete_bucket/delete_file') - if ret != 0: - gdaltest.post_reason('fail') - return 'fail' + assert ret == 0 handler = webserver.SequentialHandler() handler.add('GET', '/s3_delete_bucket/delete_file', 404, {'Connection': 'close'}) handler.add('GET', '/s3_delete_bucket/?delimiter=%2F&max-keys=100&prefix=delete_file%2F', 404, {'Connection': 'close'}) with webserver.install_http_handler(handler): - if gdal.VSIStatL('/vsis3/s3_delete_bucket/delete_file') is not None: - gdaltest.post_reason('fail') - return 'fail' + assert gdal.VSIStatL('/vsis3/s3_delete_bucket/delete_file') is None handler = webserver.SequentialHandler() handler.add('GET', '/s3_delete_bucket/delete_file_error', 200) @@ -1586,9 +1290,7 @@ def vsis3_5(): with webserver.install_http_handler(handler): with gdaltest.error_handler(): ret = gdal.Unlink('/vsis3/s3_delete_bucket/delete_file_error') - if ret == 0: - gdaltest.post_reason('fail') - return 'fail' + assert ret != 0 handler = webserver.SequentialHandler() @@ -1619,27 +1321,21 @@ def method(request): with webserver.install_http_handler(handler): ret = gdal.Unlink('/vsis3/s3_delete_bucket/redirect') - if ret != 0: - gdaltest.post_reason('fail') - return 'fail' - - return 'success' + assert ret == 0 ############################################################################### # Test multipart upload with a fake AWS server -def vsis3_6(): +def test_vsis3_6(): if gdaltest.webserver_port == 0: - return 'skip' + pytest.skip() with gdaltest.config_option('VSIS3_CHUNK_SIZE', '1'): # 1 MB with webserver.install_http_handler(webserver.SequentialHandler()): f = gdal.VSIFOpenL('/vsis3/s3_fake_bucket4/large_file.bin', 'wb') - if f is None: - gdaltest.post_reason('fail') - return 'fail' + assert f is not None size = 1024 * 1024 + 1 big_buffer = 'a' * size @@ -1687,9 +1383,7 @@ def method(request): with webserver.install_http_handler(handler): ret = gdal.VSIFWriteL(big_buffer, 1, size, f) - if ret != size: - gdaltest.post_reason('fail') - return 'fail' + assert ret == size handler = webserver.SequentialHandler() def method(request): @@ -1736,9 +1430,7 @@ def method(request): gdal.ErrorReset() with webserver.install_http_handler(handler): gdal.VSIFCloseL(f) - if gdal.GetLastErrorMsg() != '': - gdaltest.post_reason('fail') - return 'fail' + assert gdal.GetLastErrorMsg() == '' handler = webserver.SequentialHandler() handler.add('POST', '/s3_fake_bucket4/large_file_initiate_403_error.bin?uploads', 403) @@ -1752,20 +1444,13 @@ def method(request): '/vsis3/s3_fake_bucket4/large_file_initiate_no_uploadId.bin']: with gdaltest.config_option('VSIS3_CHUNK_SIZE', '1'): # 1 MB f = gdal.VSIFOpenL(filename, 'wb') - if f is None: - gdaltest.post_reason('fail') - return 'fail' + assert f is not None with gdaltest.error_handler(): ret = gdal.VSIFWriteL(big_buffer, 1, size, f) - if ret != 0: - gdaltest.post_reason('fail') - print(ret) - return 'fail' + assert ret == 0 gdal.ErrorReset() gdal.VSIFCloseL(f) - if gdal.GetLastErrorMsg() != '': - gdaltest.post_reason('fail') - return 'fail' + assert gdal.GetLastErrorMsg() == '' handler = webserver.SequentialHandler() handler.add('POST', '/s3_fake_bucket4/large_file_upload_part_403_error.bin?uploads', 200, {}, @@ -1783,23 +1468,13 @@ def method(request): '/vsis3/s3_fake_bucket4/large_file_upload_part_no_etag.bin']: with gdaltest.config_option('VSIS3_CHUNK_SIZE', '1'): # 1 MB f = gdal.VSIFOpenL(filename, 'wb') - if f is None: - gdaltest.post_reason('fail') - print(filename) - return 'fail' + assert f is not None, filename with gdaltest.error_handler(): ret = gdal.VSIFWriteL(big_buffer, 1, size, f) - if ret != 0: - gdaltest.post_reason('fail') - print(filename) - print(ret) - return 'fail' + assert ret == 0, filename gdal.ErrorReset() gdal.VSIFCloseL(f) - if gdal.GetLastErrorMsg() != '': - gdaltest.post_reason('fail') - print(filename) - return 'fail' + assert gdal.GetLastErrorMsg() == '', filename # Simulate failure in AbortMultipart stage handler = webserver.SequentialHandler() @@ -1812,24 +1487,14 @@ def method(request): with webserver.install_http_handler(handler): with gdaltest.config_option('VSIS3_CHUNK_SIZE', '1'): # 1 MB f = gdal.VSIFOpenL(filename, 'wb') - if f is None: - gdaltest.post_reason('fail') - print(filename) - return 'fail' + assert f is not None, filename with gdaltest.error_handler(): ret = gdal.VSIFWriteL(big_buffer, 1, size, f) - if ret != 0: - gdaltest.post_reason('fail') - print(filename) - print(ret) - return 'fail' + assert ret == 0, filename gdal.ErrorReset() with gdaltest.error_handler(): gdal.VSIFCloseL(f) - if gdal.GetLastErrorMsg() == '': - gdaltest.post_reason('fail') - print(filename) - return 'fail' + assert gdal.GetLastErrorMsg() != '', filename # Simulate failure in CompleteMultipartUpload stage handler = webserver.SequentialHandler() @@ -1844,34 +1509,23 @@ def method(request): with webserver.install_http_handler(handler): with gdaltest.config_option('VSIS3_CHUNK_SIZE', '1'): # 1 MB f = gdal.VSIFOpenL(filename, 'wb') - if f is None: - gdaltest.post_reason('fail') - print(filename) - return 'fail' + assert f is not None, filename ret = gdal.VSIFWriteL(big_buffer, 1, size, f) - if ret != size: - gdaltest.post_reason('fail') - print(filename) - print(ret) - return 'fail' + assert ret == size, filename gdal.ErrorReset() with gdaltest.error_handler(): gdal.VSIFCloseL(f) - if gdal.GetLastErrorMsg() == '': - gdaltest.post_reason('fail') - print(filename) - return 'fail' - - return 'success' + assert gdal.GetLastErrorMsg() != '', filename + ############################################################################### # Test Mkdir() / Rmdir() -def vsis3_7(): +def test_vsis3_7(): if gdaltest.webserver_port == 0: - return 'skip' + pytest.skip() handler = webserver.SequentialHandler() handler.add('GET', '/s3_bucket_test_mkdir/dir/', 404, {'Connection': 'close'}) @@ -1879,36 +1533,25 @@ def vsis3_7(): handler.add('PUT', '/s3_bucket_test_mkdir/dir/', 200) with webserver.install_http_handler(handler): ret = gdal.Mkdir('/vsis3/s3_bucket_test_mkdir/dir', 0) - if ret != 0: - gdaltest.post_reason('fail') - return 'fail' + assert ret == 0 - if not stat.S_ISDIR(gdal.VSIStatL('/vsis3/s3_bucket_test_mkdir/dir').mode): - gdaltest.post_reason('fail') - return 'fail' + assert stat.S_ISDIR(gdal.VSIStatL('/vsis3/s3_bucket_test_mkdir/dir').mode) dir_content = gdal.ReadDir('/vsis3/s3_bucket_test_mkdir/dir') - if dir_content != ['.']: - gdaltest.post_reason('fail') - print(dir_content) - return 'fail' + assert dir_content == ['.'] # Try creating already existing directory handler = webserver.SequentialHandler() handler.add('GET', '/s3_bucket_test_mkdir/dir/', 416, {'Connection': 'close'}) with webserver.install_http_handler(handler): ret = gdal.Mkdir('/vsis3/s3_bucket_test_mkdir/dir', 0) - if ret == 0: - gdaltest.post_reason('fail') - return 'fail' + assert ret != 0 handler = webserver.SequentialHandler() handler.add('DELETE', '/s3_bucket_test_mkdir/dir/', 204) with webserver.install_http_handler(handler): ret = gdal.Rmdir('/vsis3/s3_bucket_test_mkdir/dir') - if ret != 0: - gdaltest.post_reason('fail') - return 'fail' + assert ret == 0 # Try deleting already deleted directory handler = webserver.SequentialHandler() @@ -1916,9 +1559,7 @@ def vsis3_7(): handler.add('GET', '/s3_bucket_test_mkdir/?delimiter=%2F&max-keys=100&prefix=dir%2F', 404, {'Connection': 'close'}) with webserver.install_http_handler(handler): ret = gdal.Rmdir('/vsis3/s3_bucket_test_mkdir/dir') - if ret == 0: - gdaltest.post_reason('fail') - return 'fail' + assert ret != 0 # Try deleting non-empty directory handler = webserver.SequentialHandler() @@ -1937,9 +1578,7 @@ def vsis3_7(): """) with webserver.install_http_handler(handler): ret = gdal.Rmdir('/vsis3/s3_bucket_test_mkdir/dir_nonempty') - if ret == 0: - gdaltest.post_reason('fail') - return 'fail' + assert ret != 0 # Try stat'ing a directory not ending with slash handler = webserver.SequentialHandler() @@ -1957,9 +1596,7 @@ def vsis3_7(): </ListBucketResult> """) with webserver.install_http_handler(handler): - if not stat.S_ISDIR(gdal.VSIStatL('/vsis3/s3_bucket_test_dir_stat/test_dir_stat').mode): - gdaltest.post_reason('fail') - return 'fail' + assert stat.S_ISDIR(gdal.VSIStatL('/vsis3/s3_bucket_test_dir_stat/test_dir_stat').mode) # Try ReadDi'ing a directory not ending with slash handler = webserver.SequentialHandler() @@ -1976,9 +1613,7 @@ def vsis3_7(): </ListBucketResult> """) with webserver.install_http_handler(handler): - if gdal.ReadDir('/vsis3/s3_bucket_test_readdir/test_dirread') is None: - gdaltest.post_reason('fail') - return 'fail' + assert gdal.ReadDir('/vsis3/s3_bucket_test_readdir/test_dirread') is not None # Try stat'ing a directory ending with slash handler = webserver.SequentialHandler() @@ -1996,9 +1631,7 @@ def vsis3_7(): </ListBucketResult> """) with webserver.install_http_handler(handler): - if not stat.S_ISDIR(gdal.VSIStatL('/vsis3/s3_bucket_test_dir_stat_2/test_dir_stat/').mode): - gdaltest.post_reason('fail') - return 'fail' + assert stat.S_ISDIR(gdal.VSIStatL('/vsis3/s3_bucket_test_dir_stat_2/test_dir_stat/').mode) # Try ReadDi'ing a directory ending with slash handler = webserver.SequentialHandler() @@ -2015,20 +1648,17 @@ def vsis3_7(): </ListBucketResult> """) with webserver.install_http_handler(handler): - if gdal.ReadDir('/vsis3/s3_bucket_test_readdir2/test_dirread') is None: - gdaltest.post_reason('fail') - return 'fail' - - return 'success' + assert gdal.ReadDir('/vsis3/s3_bucket_test_readdir2/test_dirread') is not None + ############################################################################### # Test handling of file and directory with same name -def vsis3_8(): +def test_vsis3_8(): if gdaltest.webserver_port == 0: - return 'skip' + pytest.skip() handler = webserver.SequentialHandler() handler.add('GET', '/vsis3_8/?delimiter=%2F', 200, @@ -2049,33 +1679,25 @@ def vsis3_8(): with webserver.install_http_handler(handler): listdir = gdal.ReadDir('/vsis3/vsis3_8', 0) - if listdir != ['test', 'test/']: - gdaltest.post_reason('fail') - print(listdir) - return 'fail' + assert listdir == ['test', 'test/'] handler = webserver.SequentialHandler() with webserver.install_http_handler(handler): - if stat.S_ISDIR(gdal.VSIStatL('/vsis3/vsis3_8/test').mode): - gdaltest.post_reason('fail') - return 'fail' + assert not stat.S_ISDIR(gdal.VSIStatL('/vsis3/vsis3_8/test').mode) handler = webserver.SequentialHandler() with webserver.install_http_handler(handler): - if not stat.S_ISDIR(gdal.VSIStatL('/vsis3/vsis3_8/test/').mode): - gdaltest.post_reason('fail') - return 'fail' - - return 'success' + assert stat.S_ISDIR(gdal.VSIStatL('/vsis3/vsis3_8/test/').mode) + ############################################################################### # Test vsisync() with SYNC_STRATEGY=ETAG -def vsis3_sync_etag(): +def test_vsis3_sync_etag(): if gdaltest.webserver_port == 0: - return 'skip' + pytest.skip() gdal.VSICurlClearCache() @@ -2084,9 +1706,7 @@ def vsis3_sync_etag(): with gdaltest.error_handler(): handler = webserver.SequentialHandler() with webserver.install_http_handler(handler): - if gdal.Sync('/i_do/not/exist', '/vsis3/', options=options): - gdaltest.post_reason('fail') - return 'fail' + assert not gdal.Sync('/i_do/not/exist', '/vsis3/', options=options) with gdaltest.error_handler(): handler = webserver.SequentialHandler() @@ -2094,9 +1714,7 @@ def vsis3_sync_etag(): handler.add('GET', '/do_not/?delimiter=%2F&max-keys=100&prefix=exist%2F', 404) handler.add('PUT', '/do_not/exist', 404) with webserver.install_http_handler(handler): - if gdal.Sync('vsifile.py', '/vsis3/do_not/exist', options=options): - gdaltest.post_reason('fail') - return 'fail' + assert not gdal.Sync('vsifile.py', '/vsis3/do_not/exist', options=options) handler = webserver.SequentialHandler() handler.add('GET', '/out/', 200) @@ -2130,16 +1748,12 @@ def method(request): gdal.FileFromMemBuffer('/vsimem/testsync.txt', 'foo') with webserver.install_http_handler(handler): - if not gdal.Sync('/vsimem/testsync.txt', '/vsis3/out', options=options): - gdaltest.post_reason('fail') - return 'fail' + assert gdal.Sync('/vsimem/testsync.txt', '/vsis3/out', options=options) # Re-try with cached ETag. Should generate no network access handler = webserver.SequentialHandler() with webserver.install_http_handler(handler): - if not gdal.Sync('/vsimem/testsync.txt', '/vsis3/out', options=options): - gdaltest.post_reason('fail') - return 'fail' + assert gdal.Sync('/vsimem/testsync.txt', '/vsis3/out', options=options) gdal.VSICurlClearCache() @@ -2150,15 +1764,11 @@ def method(request): 'Content-Range': 'bytes 0-2/3', 'ETag' : '"acbd18db4cc2f85cedef654fccc4a4d8"' }, "foo") with webserver.install_http_handler(handler): - if not gdal.Sync( '/vsis3/out/testsync.txt', '/vsimem/', options=options): - gdaltest.post_reason('fail') - return 'fail' + assert gdal.Sync( '/vsis3/out/testsync.txt', '/vsimem/', options=options) # Shouldn't do any copy, but hard to verify with webserver.install_http_handler(webserver.SequentialHandler()): - if not gdal.Sync( '/vsis3/out/testsync.txt', '/vsimem/', options=options): - gdaltest.post_reason('fail') - return 'fail' + assert gdal.Sync( '/vsis3/out/testsync.txt', '/vsimem/', options=options) # Modify target file, and redo synchronization gdal.FileFromMemBuffer('/vsimem/testsync.txt', 'bar') @@ -2181,16 +1791,12 @@ def method(request): 'Content-Range': 'bytes 0-2/3', 'ETag' : '"acbd18db4cc2f85cedef654fccc4a4d8"' }, "foo") with webserver.install_http_handler(handler): - if not gdal.Sync( '/vsis3/out/testsync.txt', '/vsimem/', options=options): - gdaltest.post_reason('fail') - return 'fail' + assert gdal.Sync( '/vsis3/out/testsync.txt', '/vsimem/', options=options) f = gdal.VSIFOpenL('/vsimem/testsync.txt', 'rb') data = gdal.VSIFReadL(1, 3, f).decode('ascii') gdal.VSIFCloseL(f) - if data != 'foo': - gdaltest.post_reason('fail') - return 'fail' + assert data == 'foo' # /vsimem to S3, but after cleaning the cache gdal.VSICurlClearCache() @@ -2202,9 +1808,7 @@ def method(request): 'Content-Range': 'bytes 0-2/3', 'ETag' : '"acbd18db4cc2f85cedef654fccc4a4d8"' }, "foo") with webserver.install_http_handler(handler): - if not gdal.Sync('/vsimem/testsync.txt', '/vsis3/out', options=options): - gdaltest.post_reason('fail') - return 'fail' + assert gdal.Sync('/vsimem/testsync.txt', '/vsis3/out', options=options) gdal.Unlink('/vsimem/testsync.txt') @@ -2227,21 +1831,17 @@ def method(request): </ListBucketResult> """) with webserver.install_http_handler(handler): - if not gdal.Sync('/vsimem/subdir/', '/vsis3/out', options=options): - gdaltest.post_reason('fail') - return 'fail' + assert gdal.Sync('/vsimem/subdir/', '/vsis3/out', options=options) gdal.RmdirRecursive('/vsimem/subdir') - return 'success' - ############################################################################### # Test vsisync() with SYNC_STRATEGY=TIMESTAMP -def vsis3_sync_timestamp(): +def test_vsis3_sync_timestamp(): if gdaltest.webserver_port == 0: - return 'skip' + pytest.skip() options = ['SYNC_STRATEGY=TIMESTAMP'] @@ -2260,10 +1860,8 @@ def vsis3_sync_timestamp(): 'Content-Range': 'bytes 0-2/3', 'Last-Modified': 'Mon, 01 Jan 1970 00:00:01 GMT' }, "foo") with webserver.install_http_handler(handler): - if not gdal.Sync( '/vsis3/out/testsync.txt', '/vsimem/', - options=options): - gdaltest.post_reason('fail') - return 'fail' + assert gdal.Sync( '/vsis3/out/testsync.txt', '/vsimem/', + options=options) # S3 to local: S3 file is newer -> do nothing gdal.VSICurlClearCache() @@ -2273,10 +1871,8 @@ def vsis3_sync_timestamp(): 'Content-Range': 'bytes 0-2/3', 'Last-Modified': 'Mon, 01 Jan 2037 00:00:01 GMT' }, "foo") with webserver.install_http_handler(handler): - if not gdal.Sync( '/vsis3/out/testsync.txt', '/vsimem/', - options=options): - gdaltest.post_reason('fail') - return 'fail' + assert gdal.Sync( '/vsis3/out/testsync.txt', '/vsimem/', + options=options) # Local to S3: S3 file is older -> upload gdal.VSICurlClearCache() @@ -2287,10 +1883,8 @@ def vsis3_sync_timestamp(): 'Last-Modified': 'Mon, 01 Jan 1970 00:00:01 GMT' }, "foo") handler.add('PUT', '/out/testsync.txt', 200) with webserver.install_http_handler(handler): - if not gdal.Sync( '/vsimem/testsync.txt', '/vsis3/out/testsync.txt', - options=options): - gdaltest.post_reason('fail') - return 'fail' + assert gdal.Sync( '/vsimem/testsync.txt', '/vsis3/out/testsync.txt', + options=options) # Local to S3: S3 file is newer -> do nothgin gdal.VSICurlClearCache() @@ -2300,23 +1894,19 @@ def vsis3_sync_timestamp(): 'Content-Range': 'bytes 0-2/3', 'Last-Modified': 'Mon, 01 Jan 2037 00:00:01 GMT' }, "foo") with webserver.install_http_handler(handler): - if not gdal.Sync( '/vsimem/testsync.txt', '/vsis3/out/testsync.txt', - options=options): - gdaltest.post_reason('fail') - return 'fail' + assert gdal.Sync( '/vsimem/testsync.txt', '/vsis3/out/testsync.txt', + options=options) gdal.Unlink('/vsimem/testsync.txt') - return 'success' - ############################################################################### # Read credentials from simulated ~/.aws/credentials -def vsis3_read_credentials_file(): +def test_vsis3_read_credentials_file(): if gdaltest.webserver_port == 0: - return 'skip' + pytest.skip() gdal.SetConfigOption('AWS_SECRET_ACCESS_KEY', '') gdal.SetConfigOption('AWS_ACCESS_KEY_ID', '') @@ -2341,30 +1931,23 @@ def vsis3_read_credentials_file(): handler.add('GET', '/s3_fake_bucket/resource', custom_method=get_s3_fake_bucket_resource_method) with webserver.install_http_handler(handler): f = open_for_read('/vsis3/s3_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' gdal.SetConfigOption('CPL_AWS_CREDENTIALS_FILE', '') gdal.Unlink('/vsimem/aws_credentials') - return 'success' - ############################################################################### # Read credentials from simulated ~/.aws/config -def vsis3_read_config_file(): +def test_vsis3_read_config_file(): if gdaltest.webserver_port == 0: - return 'skip' + pytest.skip() gdal.SetConfigOption('AWS_SECRET_ACCESS_KEY', '') gdal.SetConfigOption('AWS_ACCESS_KEY_ID', '') @@ -2390,30 +1973,23 @@ def vsis3_read_config_file(): handler.add('GET', '/s3_fake_bucket/resource', custom_method=get_s3_fake_bucket_resource_method) with webserver.install_http_handler(handler): f = open_for_read('/vsis3/s3_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' gdal.SetConfigOption('AWS_CONFIG_FILE', '') gdal.Unlink('/vsimem/aws_config') - return 'success' - ############################################################################### # Read credentials from simulated ~/.aws/credentials and ~/.aws/config -def vsis3_read_credentials_config_file(): +def test_vsis3_read_credentials_config_file(): if gdaltest.webserver_port == 0: - return 'skip' + pytest.skip() gdal.SetConfigOption('AWS_SECRET_ACCESS_KEY', '') gdal.SetConfigOption('AWS_ACCESS_KEY_ID', '') @@ -2452,33 +2028,26 @@ def vsis3_read_credentials_config_file(): handler.add('GET', '/s3_fake_bucket/resource', custom_method=get_s3_fake_bucket_resource_method) with webserver.install_http_handler(handler): f = open_for_read('/vsis3/s3_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' gdal.SetConfigOption('CPL_AWS_CREDENTIALS_FILE', '') gdal.Unlink('/vsimem/aws_credentials') gdal.SetConfigOption('AWS_CONFIG_FILE', '') gdal.Unlink('/vsimem/aws_config') - return 'success' - ############################################################################### # Read credentials from simulated ~/.aws/credentials and ~/.aws/config with # a non default profile -def vsis3_read_credentials_config_file_non_default(): +def test_vsis3_read_credentials_config_file_non_default(): if gdaltest.webserver_port == 0: - return 'skip' + pytest.skip() gdal.SetConfigOption('AWS_SECRET_ACCESS_KEY', '') gdal.SetConfigOption('AWS_ACCESS_KEY_ID', '') @@ -2516,16 +2085,11 @@ def vsis3_read_credentials_config_file_non_default(): handler.add('GET', '/s3_fake_bucket/resource', custom_method=get_s3_fake_bucket_resource_method) with webserver.install_http_handler(handler): f = open_for_read('/vsis3/s3_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' gdal.SetConfigOption('CPL_AWS_CREDENTIALS_FILE', '') gdal.Unlink('/vsimem/aws_credentials') @@ -2533,16 +2097,14 @@ def vsis3_read_credentials_config_file_non_default(): gdal.Unlink('/vsimem/aws_config') gdal.SetConfigOption('AWS_DEFAULT_PROFILE', '') - return 'success' - ############################################################################### # Read credentials from simulated ~/.aws/credentials and ~/.aws/config -def vsis3_read_credentials_config_file_inconsistent(): +def test_vsis3_read_credentials_config_file_inconsistent(): if gdaltest.webserver_port == 0: - return 'skip' + pytest.skip() gdal.SetConfigOption('AWS_SECRET_ACCESS_KEY', '') gdal.SetConfigOption('AWS_ACCESS_KEY_ID', '') @@ -2583,39 +2145,29 @@ def vsis3_read_credentials_config_file_inconsistent(): with webserver.install_http_handler(handler): with gdaltest.error_handler(): f = open_for_read('/vsis3/s3_fake_bucket/resource') - if f is None: - gdaltest.post_reason('fail') - return 'fail' - if gdal.GetLastErrorMsg() == '': - # Expected 'aws_access_key_id defined in both /vsimem/aws_credentials and /vsimem/aws_config' - gdaltest.post_reason('fail') - return 'fail' + assert f is not None + assert gdal.GetLastErrorMsg() != '' 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' gdal.SetConfigOption('CPL_AWS_CREDENTIALS_FILE', '') gdal.Unlink('/vsimem/aws_credentials') gdal.SetConfigOption('AWS_CONFIG_FILE', '') gdal.Unlink('/vsimem/aws_config') - return 'success' - ############################################################################### # Read credentials from simulated EC2 instance -def vsis3_read_credentials_ec2(): +def test_vsis3_read_credentials_ec2(): if gdaltest.webserver_port == 0: - return 'skip' + pytest.skip() if sys.platform not in ('linux', 'linux2', 'win32'): - return 'skip' + pytest.skip() gdal.SetConfigOption('CPL_AWS_CREDENTIALS_FILE', '') gdal.SetConfigOption('AWS_CONFIG_FILE', '') @@ -2640,16 +2192,11 @@ def vsis3_read_credentials_ec2(): handler.add('GET', '/s3_fake_bucket/resource', custom_method=get_s3_fake_bucket_resource_method) with webserver.install_http_handler(handler): f = open_for_read('/vsis3/s3_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' # Set a fake URL to check that credentials re-use works gdal.SetConfigOption('CPL_AWS_EC2_CREDENTIALS_URL', '') @@ -2658,34 +2205,27 @@ def vsis3_read_credentials_ec2(): handler.add('GET', '/s3_fake_bucket/bar', 200, {}, 'bar') with webserver.install_http_handler(handler): f = open_for_read('/vsis3/s3_fake_bucket/bar') - 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 != 'bar': - gdaltest.post_reason('fail') - print(data) - return 'fail' + assert data == 'bar' gdal.SetConfigOption('CPL_AWS_EC2_CREDENTIALS_URL', '') gdal.SetConfigOption('CPL_AWS_AUTODETECT_EC2', None) - return 'success' - ############################################################################### # Read credentials from simulated EC2 instance with expiration of the # cached credentials -def vsis3_read_credentials_ec2_expiration(): +def test_vsis3_read_credentials_ec2_expiration(): if gdaltest.webserver_port == 0: - return 'skip' + pytest.skip() if sys.platform not in ('linux', 'linux2', 'win32'): - return 'skip' + pytest.skip() gdal.SetConfigOption('CPL_AWS_CREDENTIALS_FILE', '') gdal.SetConfigOption('AWS_CONFIG_FILE', '') @@ -2710,38 +2250,29 @@ def vsis3_read_credentials_ec2_expiration(): handler.add('GET', '/s3_fake_bucket/resource', custom_method=get_s3_fake_bucket_resource_method) with webserver.install_http_handler(handler): f = open_for_read('/vsis3/s3_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' # Set a fake URL to demonstrate we try to re-fetch credentials gdal.SetConfigOption('CPL_AWS_EC2_CREDENTIALS_URL', '') with gdaltest.error_handler(): f = open_for_read('/vsis3/s3_fake_bucket/bar') - if f is not None: - gdaltest.post_reason('fail') - return 'fail' + assert f is None gdal.SetConfigOption('CPL_AWS_EC2_CREDENTIALS_URL', '') gdal.SetConfigOption('CPL_AWS_AUTODETECT_EC2', None) - return 'success' - ############################################################################### -def vsis3_stop_webserver(): +def test_vsis3_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 @@ -2749,16 +2280,14 @@ def vsis3_stop_webserver(): webserver.server_stop(gdaltest.webserver_process, gdaltest.webserver_port) - return 'success' - ############################################################################### # Nominal cases (require valid credentials) -def vsis3_extra_1(): +def test_vsis3_extra_1(): if not gdaltest.built_against_curl(): - return 'skip' + pytest.skip() credentials_filename = gdal.GetConfigOption('HOME', gdal.GetConfigOption('USERPROFILE', '')) + '/.aws/credentials' @@ -2768,145 +2297,90 @@ def vsis3_extra_1(): if not os.path.exists(credentials_filename): if gdal.GetConfigOption('AWS_SECRET_ACCESS_KEY') is None: - print('Missing AWS_SECRET_ACCESS_KEY for running gdaltest_list_extra') - return 'skip' + pytest.skip('Missing AWS_SECRET_ACCESS_KEY') elif gdal.GetConfigOption('AWS_ACCESS_KEY_ID') is None: - print('Missing AWS_ACCESS_KEY_ID for running gdaltest_list_extra') - return 'skip' - elif s3_resource is None: - print('Missing S3_RESOURCE for running gdaltest_list_extra') - return 'skip' + pytest.skip('Missing AWS_ACCESS_KEY_ID') + + if s3_resource is None: + pytest.skip('Missing S3_RESOURCE') if s3_resource.find('/') < 0: path = '/vsis3/' + s3_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 = 'vsis3_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('/vsis3/' + s3_resource) - if f is None: - gdaltest.post_reason('fail') - print('cannot open %s' % ('/vsis3/' + s3_resource)) - return 'fail' + assert f is not None, ('cannot open %s' % ('/vsis3/' + s3_resource)) 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 /vsis3_streaming/ f = open_for_read('/vsis3_streaming/' + s3_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 @@ -2916,39 +2390,26 @@ def vsis3_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('/vsis3_streaming/' + gdal.GetConfigOption('S3_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('/vsis3/' + s3_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 vsis3_cleanup(): +def test_vsis3_cleanup(): for var in gdaltest.aws_vars: gdal.SetConfigOption(var, gdaltest.aws_vars[var]) @@ -2956,45 +2417,3 @@ def vsis3_cleanup(): gdal.SetConfigOption('CPL_AWS_CREDENTIALS_FILE', None) gdal.SetConfigOption('AWS_CONFIG_FILE', None) gdal.SetConfigOption('CPL_AWS_EC2_CREDENTIALS_URL', None) - - return 'success' - - -gdaltest_list = [vsis3_init, - vsis3_no_sign_request, - vsis3_1, - vsis3_start_webserver, - vsis3_2, - vsis3_readdir, - vsis3_opendir, - vsis3_4, - vsis3_5, - vsis3_6, - vsis3_7, - vsis3_8, - vsis3_sync_etag, - vsis3_sync_timestamp, - vsis3_read_credentials_file, - vsis3_read_config_file, - vsis3_read_credentials_config_file, - vsis3_read_credentials_config_file_non_default, - vsis3_read_credentials_config_file_inconsistent, - vsis3_read_credentials_ec2, - vsis3_read_credentials_ec2_expiration, - vsis3_stop_webserver, - vsis3_cleanup] - -# gdaltest_list = [ vsis3_init, vsis3_start_webserver, vsis3_opendir, vsis3_stop_webserver, vsis3_cleanup ] - -gdaltest_list_extra = [vsis3_extra_1] - -if __name__ == '__main__': - - gdaltest.setup_run('vsis3') - - if gdal.GetConfigOption('RUN_MANUAL_ONLY', None): - gdaltest.run_tests(gdaltest_list_extra) - else: - gdaltest.run_tests(gdaltest_list + gdaltest_list_extra + [vsis3_cleanup]) - - sys.exit(gdaltest.summarize()) diff --git a/autotest/gcore/vsistdin.py b/autotest/gcore/vsistdin.py index 3e8ca62cf16b..aefa24aa442b 100755 --- a/autotest/gcore/vsistdin.py +++ b/autotest/gcore/vsistdin.py @@ -29,21 +29,19 @@ ############################################################################### import os -import sys -sys.path.append('../pymod') -import gdaltest from osgeo import gdal import test_cli_utilities +import pytest ############################################################################### # Test on a small file -def vsistdin_1(): +def test_vsistdin_1(): if test_cli_utilities.get_gdal_translate_path() is None: - return 'skip' + pytest.skip() src_ds = gdal.Open('data/byte.tif') ds = gdal.GetDriverByName('GTiff').CreateCopy('tmp/vsistdin_1_src.tif', src_ds) @@ -57,24 +55,18 @@ def vsistdin_1(): gdal.Unlink("tmp/vsistdin_1_src.tif") ds = gdal.Open("tmp/vsistdin_1_out.tif") - if ds is None: - gdaltest.post_reason('fail') - return 'fail' - if ds.GetRasterBand(1).Checksum() != cs: - gdaltest.post_reason('fail') - return 'fail' + assert ds is not None + assert ds.GetRasterBand(1).Checksum() == cs gdal.Unlink("tmp/vsistdin_1_out.tif") - return 'success' - ############################################################################### # Test on a bigger file (> 1 MB) -def vsistdin_2(): +def test_vsistdin_2(): if test_cli_utilities.get_gdal_translate_path() is None: - return 'skip' + pytest.skip() ds = gdal.GetDriverByName('GTiff').Create('tmp/vsistdin_2_src.tif', 2048, 2048) ds = None @@ -85,35 +77,29 @@ def vsistdin_2(): gdal.Unlink("tmp/vsistdin_2_src.tif") ds = gdal.Open("tmp/vsistdin_2_out.tif") - if ds is None: - return 'fail' + assert ds is not None ds = None gdal.Unlink("tmp/vsistdin_2_out.tif") - return 'success' - ############################################################################### # Test opening /vsistdin/ in write mode (failure expected) -def vsistdin_3(): +def test_vsistdin_3(): gdal.PushErrorHandler('CPLQuietErrorHandler') f = gdal.VSIFOpenL('/vsistdin/', 'wb') gdal.PopErrorHandler() - if f is not None: - return 'fail' - - return 'success' + assert f is None ############################################################################### # Test fix for #6061 -def vsistdin_4(): +def test_vsistdin_4(): if test_cli_utilities.get_gdal_translate_path() is None: - return 'skip' + pytest.skip() f = open('tmp/vsistdin_4_src.vrt', 'wt') f.write("""<VRTDataset rasterXSize="20" rasterYSize="20"> @@ -136,22 +122,11 @@ def vsistdin_4(): gdal.Unlink("tmp/vsistdin_4_src.vrt") ds = gdal.Open("tmp/vsistdin_4_out.tif") - if ds is None: - return 'fail' + assert ds is not None ds = None gdal.Unlink("tmp/vsistdin_4_out.tif") - return 'success' - - -gdaltest_list = [vsistdin_1, vsistdin_2, vsistdin_3, vsistdin_4] - - -if __name__ == '__main__': - gdaltest.setup_run('vsistdin') - gdaltest.run_tests(gdaltest_list) - sys.exit(gdaltest.summarize()) diff --git a/autotest/gcore/vsiswift.py b/autotest/gcore/vsiswift.py index de3ac7be99c9..5cb0c55600a9 100644 --- a/autotest/gcore/vsiswift.py +++ b/autotest/gcore/vsiswift.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 vsiswift_init(): +def test_vsiswift_init(): gdaltest.swift_vars = {} for var in ('SWIFT_STORAGE_URL', 'SWIFT_AUTH_TOKEN', @@ -56,33 +56,26 @@ def vsiswift_init(): if gdaltest.swift_vars[var] is not None: gdal.SetConfigOption(var, "") - return 'success' - + ############################################################################### # Error cases -def vsiswift_real_server_errors(): +def test_vsiswift_real_server_errors(): if not gdaltest.built_against_curl(): - return 'skip' + pytest.skip() # Nothing set gdal.ErrorReset() with gdaltest.error_handler(): f = open_for_read('/vsiswift/foo/bar') - if f is not None or gdal.VSIGetLastErrorMsg().find('SWIFT_STORAGE_URL') < 0: - gdaltest.post_reason('fail') - print(gdal.VSIGetLastErrorMsg()) - return 'fail' + assert f is None and gdal.VSIGetLastErrorMsg().find('SWIFT_STORAGE_URL') >= 0 gdal.ErrorReset() with gdaltest.error_handler(): f = open_for_read('/vsiswift_streaming/foo/bar') - if f is not None or gdal.VSIGetLastErrorMsg().find('SWIFT_STORAGE_URL') < 0: - gdaltest.post_reason('fail') - print(gdal.VSIGetLastErrorMsg()) - return 'fail' + assert f is None and gdal.VSIGetLastErrorMsg().find('SWIFT_STORAGE_URL') >= 0 gdal.SetConfigOption('SWIFT_STORAGE_URL', 'http://0.0.0.0') @@ -90,10 +83,7 @@ def vsiswift_real_server_errors(): gdal.ErrorReset() with gdaltest.error_handler(): f = open_for_read('/vsiswift/foo/bar') - if f is not None or gdal.VSIGetLastErrorMsg().find('SWIFT_AUTH_TOKEN') < 0: - gdaltest.post_reason('fail') - print(gdal.VSIGetLastErrorMsg()) - return 'fail' + assert f is None and gdal.VSIGetLastErrorMsg().find('SWIFT_AUTH_TOKEN') >= 0 gdal.SetConfigOption('SWIFT_AUTH_TOKEN', 'SWIFT_AUTH_TOKEN') @@ -103,45 +93,37 @@ def vsiswift_real_server_errors(): if f is not None: if f is not None: gdal.VSIFCloseL(f) - gdaltest.post_reason('fail') - print(gdal.VSIGetLastErrorMsg()) - return 'fail' + pytest.fail(gdal.VSIGetLastErrorMsg()) gdal.ErrorReset() with gdaltest.error_handler(): f = open_for_read('/vsiswift_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 vsiswift_start_webserver(): +def test_vsiswift_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() + ############################################################################### # Test authentication with SWIFT_AUTH_V1_URL + SWIFT_USER + SWIFT_KEY -def vsiswift_fake_auth_v1_url(): +def test_vsiswift_fake_auth_v1_url(): if gdaltest.webserver_port == 0: - return 'skip' + pytest.skip() gdal.VSICurlClearCache() gdal.SetConfigOption('SWIFT_AUTH_V1_URL', 'http://127.0.0.1:%d/auth/1.0' % gdaltest.webserver_port) @@ -190,16 +172,11 @@ def method(request): handler.add('GET', '/v1/AUTH_something/foo/bar', custom_method=method) with webserver.install_http_handler(handler): f = open_for_read('/vsiswift/foo/bar') - 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' # authentication is reused @@ -223,27 +200,20 @@ def method(request): with webserver.install_http_handler(handler): f = open_for_read('/vsiswift/foo/baz') - 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 != 'bar': - gdaltest.post_reason('fail') - print(data) - return 'fail' - - return 'success' + assert data == 'bar' ############################################################################### # Test authentication with SWIFT_STORAGE_URL + SWIFT_AUTH_TOKEN -def vsiswift_fake_auth_storage_url_and_auth_token(): +def test_vsiswift_fake_auth_storage_url_and_auth_token(): if gdaltest.webserver_port == 0: - return 'skip' + pytest.skip() gdal.VSICurlClearCache() gdal.SetConfigOption('SWIFT_AUTH_V1_URL', '') @@ -257,9 +227,7 @@ def vsiswift_fake_auth_storage_url_and_auth_token(): handler.add('GET', '/v1/AUTH_something/foo/bar', 501) with webserver.install_http_handler(handler): f = open_for_read('/vsiswift/foo/bar') - if f is None: - gdaltest.post_reason('fail') - return 'fail' + assert f is not None gdal.VSIFReadL(1, 4, f).decode('ascii') gdal.VSIFCloseL(f) @@ -286,27 +254,20 @@ def method(request): handler.add('GET', '/v1/AUTH_something/foo/bar', custom_method=method) with webserver.install_http_handler(handler): f = open_for_read('/vsiswift/foo/bar') - 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' - - return 'success' + assert data == 'foo' ############################################################################### # Test VSIStatL() -def vsiswift_stat(): +def test_vsiswift_stat(): if gdaltest.webserver_port == 0: - return 'skip' + pytest.skip() gdal.VSICurlClearCache() @@ -316,24 +277,22 @@ def vsiswift_stat(): with webserver.install_http_handler(handler): stat_res = gdal.VSIStatL('/vsiswift/foo/bar') 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', '/v1/AUTH_something/foo/bar', 200, {'Content-Length': '1000000'}) with webserver.install_http_handler(handler): stat_res = gdal.VSIStatL('/vsiswift_streaming/foo/bar') 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() # Test stat on container handler = webserver.SequentialHandler() @@ -342,20 +301,17 @@ def vsiswift_stat(): handler.add('GET', '/v1/AUTH_something/foo', 200, {}, "blabla") with webserver.install_http_handler(handler): stat_res = gdal.VSIStatL('/vsiswift/foo') - if stat_res is None or not stat.S_ISDIR(stat_res.mode): - gdaltest.post_reason('fail') - return 'fail' - - return 'success' + assert stat_res is not None and stat.S_ISDIR(stat_res.mode) + ############################################################################### # Test ReadDir() -def vsiswift_fake_readdir(): +def test_vsiswift_fake_readdir(): if gdaltest.webserver_port == 0: - return 'skip' + pytest.skip() gdal.VSICurlClearCache() @@ -386,40 +342,25 @@ def vsiswift_fake_readdir(): with gdaltest.config_option('SWIFT_MAX_KEYS', '1'): with webserver.install_http_handler(handler): f = open_for_read('/vsiswift/foo/bar.baz') - if f is None: - gdaltest.post_reason('fail') - return 'fail' + assert f is not None gdal.VSIFCloseL(f) dir_contents = gdal.ReadDir('/vsiswift/foo') - if dir_contents != ['bar.baz', 'mysubdir']: - gdaltest.post_reason('fail') - print(dir_contents) - return 'fail' + assert dir_contents == ['bar.baz', 'mysubdir'] stat_res = gdal.VSIStatL('/vsiswift/foo/bar.baz') - if stat_res.size != 123456: - gdaltest.post_reason('fail') - print(stat_res.size) - return 'fail' - if stat_res.mtime != 1: - gdaltest.post_reason('fail') - return 'fail' + assert stat_res.size == 123456 + assert stat_res.mtime == 1 # ReadDir on something known to be a file shouldn't cause network access dir_contents = gdal.ReadDir('/vsiswift/foo/bar.baz') - 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', '/v1/AUTH_something/foo?delimiter=%2F&limit=10000&prefix=error_test%2F', 500) with webserver.install_http_handler(handler): dir_contents = gdal.ReadDir('/vsiswift/foo/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() @@ -428,10 +369,7 @@ def vsiswift_fake_readdir(): """) with webserver.install_http_handler(handler): dir_contents = gdal.ReadDir('/vsiswift/') - if dir_contents != ['.']: - gdaltest.post_reason('fail') - print(dir_contents) - return 'fail' + assert dir_contents == ['.'] # List containers gdal.VSICurlClearCache() @@ -443,10 +381,7 @@ def vsiswift_fake_readdir(): ] """) with webserver.install_http_handler(handler): dir_contents = gdal.ReadDir('/vsiswift/') - if dir_contents != ['mycontainer1', 'mycontainer2']: - gdaltest.post_reason('fail') - print(dir_contents) - return 'fail' + assert dir_contents == ['mycontainer1', 'mycontainer2'] # ReadDir() with a file and directory of same names gdal.VSICurlClearCache() @@ -461,39 +396,29 @@ def vsiswift_fake_readdir(): { "subdir": "foo/"} ] """) with webserver.install_http_handler(handler): dir_contents = gdal.ReadDir('/vsiswift/') - if dir_contents != ['foo', 'foo/']: - gdaltest.post_reason('fail') - print(dir_contents) - return 'fail' + assert dir_contents == ['foo', 'foo/'] handler = webserver.SequentialHandler() handler.add('GET', '/v1/AUTH_something/foo?delimiter=%2F&limit=10000', 200, {'Content-type': 'application/json'}, "[]") with webserver.install_http_handler(handler): dir_contents = gdal.ReadDir('/vsiswift/foo/') - if dir_contents != ['.']: - gdaltest.post_reason('fail') - print(dir_contents) - return 'fail' - - return 'success' + assert dir_contents == ['.'] ############################################################################### # Test write -def vsiswift_fake_write(): +def test_vsiswift_fake_write(): if gdaltest.webserver_port == 0: - return 'skip' + pytest.skip() gdal.VSICurlClearCache() # Test creation of BlockBob f = gdal.VSIFOpenL('/vsiswift/test_copy/file.bin', 'wb') - if f is None: - gdaltest.post_reason('fail') - return 'fail' + assert f is not None handler = webserver.SequentialHandler() @@ -530,22 +455,19 @@ 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) - return 'success' - + ############################################################################### # Test Unlink() -def vsiswift_fake_unlink(): +def test_vsiswift_fake_unlink(): if gdaltest.webserver_port == 0: - return 'skip' + pytest.skip() gdal.VSICurlClearCache() @@ -556,9 +478,7 @@ def vsiswift_fake_unlink(): handler.add('DELETE', '/v1/AUTH_something/foo/bar', 202, {'Connection': 'close'}) with webserver.install_http_handler(handler): ret = gdal.Unlink('/vsiswift/foo/bar') - if ret != 0: - gdaltest.post_reason('fail') - return 'fail' + assert ret == 0 # Failure handler = webserver.SequentialHandler() @@ -568,28 +488,22 @@ def vsiswift_fake_unlink(): with webserver.install_http_handler(handler): with gdaltest.error_handler(): ret = gdal.Unlink('/vsiswift/foo/bar') - if ret != -1: - gdaltest.post_reason('fail') - return 'fail' - - return 'success' + assert ret == -1 ############################################################################### # Test Mkdir() / Rmdir() -def vsiswift_fake_mkdir_rmdir(): +def test_vsiswift_fake_mkdir_rmdir(): if gdaltest.webserver_port == 0: - return 'skip' + pytest.skip() gdal.VSICurlClearCache() # Invalid name ret = gdal.Mkdir('/vsiswift', 0) - if ret == 0: - gdaltest.post_reason('fail') - return 'fail' + assert ret != 0 handler = webserver.SequentialHandler() handler.add('GET', '/v1/AUTH_something/foo/dir/', 404, {'Connection': 'close'}) @@ -597,9 +511,7 @@ def vsiswift_fake_mkdir_rmdir(): handler.add('PUT', '/v1/AUTH_something/foo/dir/', 201) with webserver.install_http_handler(handler): ret = gdal.Mkdir('/vsiswift/foo/dir', 0) - if ret != 0: - gdaltest.post_reason('fail') - return 'fail' + assert ret == 0 # Try creating already existing directory handler = webserver.SequentialHandler() @@ -610,15 +522,11 @@ def vsiswift_fake_mkdir_rmdir(): """[ { "subdir": "dir/" } ]""") with webserver.install_http_handler(handler): ret = gdal.Mkdir('/vsiswift/foo/dir', 0) - if ret == 0: - gdaltest.post_reason('fail') - return 'fail' + assert ret != 0 # Invalid name ret = gdal.Rmdir('/vsiswift') - if ret == 0: - gdaltest.post_reason('fail') - return 'fail' + assert ret != 0 gdal.VSICurlClearCache() @@ -631,9 +539,7 @@ def vsiswift_fake_mkdir_rmdir(): """[ { "name": "it_is_a_file/", "bytes": 0, "last_modified": "1970-01-01T00:00:01" } ]""") with webserver.install_http_handler(handler): ret = gdal.Rmdir('/vsiswift/foo/it_is_a_file') - if ret == 0: - gdaltest.post_reason('fail') - return 'fail' + assert ret != 0 # Valid handler = webserver.SequentialHandler() @@ -646,9 +552,7 @@ def vsiswift_fake_mkdir_rmdir(): handler.add('DELETE', '/v1/AUTH_something/foo/dir/', 204) with webserver.install_http_handler(handler): ret = gdal.Rmdir('/vsiswift/foo/dir') - if ret != 0: - gdaltest.post_reason('fail') - return 'fail' + assert ret == 0 # Try deleting already deleted directory handler = webserver.SequentialHandler() @@ -656,9 +560,7 @@ def vsiswift_fake_mkdir_rmdir(): handler.add('GET', '/v1/AUTH_something/foo?delimiter=%2F&limit=10000', 200) with webserver.install_http_handler(handler): ret = gdal.Rmdir('/vsiswift/foo/dir') - if ret == 0: - gdaltest.post_reason('fail') - return 'fail' + assert ret != 0 gdal.VSICurlClearCache() @@ -675,19 +577,15 @@ def vsiswift_fake_mkdir_rmdir(): """[ { "name": "dir_nonempty/some_file", "bytes": 0, "last_modified": "1970-01-01T00:00:01" } ]""") with webserver.install_http_handler(handler): ret = gdal.Rmdir('/vsiswift/foo/dir_nonempty') - if ret == 0: - gdaltest.post_reason('fail') - return 'fail' - - return 'success' + assert ret != 0 ############################################################################### -def vsiswift_stop_webserver(): +def test_vsiswift_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 @@ -695,197 +593,106 @@ def vsiswift_stop_webserver(): webserver.server_stop(gdaltest.webserver_process, gdaltest.webserver_port) - return 'success' - ############################################################################### # Nominal cases (require valid credentials) -def vsiswift_extra_1(): +def test_vsiswift_extra_1(): if not gdaltest.built_against_curl(): - return 'skip' + pytest.skip() swift_resource = gdal.GetConfigOption('SWIFT_RESOURCE') if swift_resource is None: - print('Missing SWIFT_RESOURCE for running gdaltest_list_extra') - return 'skip' + pytest.skip('Missing SWIFT_RESOURCE') if swift_resource.find('/') < 0: path = '/vsiswift/' + swift_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 = 'vsiswift_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('/vsiswift/' + swift_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 /vsiswift_streaming/ f = open_for_read('/vsiswift_streaming/' + swift_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 # Invalid resource gdal.ErrorReset() f = open_for_read('/vsiswift_streaming/' + swift_resource + '/invalid_resource.baz') - if f is not None: - gdaltest.post_reason('fail') - print(gdal.VSIGetLastErrorMsg()) - return 'fail' - - return 'success' + assert f is None, gdal.VSIGetLastErrorMsg() ############################################################################### -def vsiswift_cleanup(): +def test_vsiswift_cleanup(): for var in gdaltest.swift_vars: gdal.SetConfigOption(var, gdaltest.swift_vars[var]) - - return 'success' - - -gdaltest_list = [vsiswift_init, - vsiswift_real_server_errors, - vsiswift_start_webserver, - vsiswift_fake_auth_v1_url, - vsiswift_fake_auth_storage_url_and_auth_token, - vsiswift_stat, - vsiswift_fake_readdir, - vsiswift_fake_write, - vsiswift_fake_unlink, - vsiswift_fake_mkdir_rmdir, - vsiswift_stop_webserver, - vsiswift_cleanup] - -# gdaltest_list = [ vsiswift_init, vsiswift_start_webserver, vsiswift_fake_mkdir_rmdir, vsiswift_stop_webserver, vsiswift_cleanup ] - -gdaltest_list_extra = [vsiswift_extra_1] - -if __name__ == '__main__': - - gdaltest.setup_run('vsiswift') - - if gdal.GetConfigOption('RUN_MANUAL_ONLY', None): - gdaltest.run_tests(gdaltest_list_extra) - else: - gdaltest.run_tests(gdaltest_list + gdaltest_list_extra + [vsiswift_cleanup]) - - sys.exit(gdaltest.summarize()) diff --git a/autotest/gcore/vsiwebhdfs.py b/autotest/gcore/vsiwebhdfs.py index 55a2c2cb2533..2789283aac1a 100644 --- a/autotest/gcore/vsiwebhdfs.py +++ b/autotest/gcore/vsiwebhdfs.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 vsiwebhdfs_init(): +def test_vsiwebhdfs_init(): gdaltest.webhdfs_vars = {} for var in ('WEBHDFS_USERNAME', 'WEBHDFS_DELEGATION'): @@ -55,39 +55,36 @@ def vsiwebhdfs_init(): if gdaltest.webhdfs_vars[var] is not None: gdal.SetConfigOption(var, "") - return 'success' - + ############################################################################### -def vsiwebhdfs_start_webserver(): +def test_vsiwebhdfs_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() gdaltest.webhdfs_base_connection = '/vsiwebhdfs/http://localhost:' + \ str(gdaltest.webserver_port) + '/webhdfs/v1' gdaltest.webhdfs_redirected_url = 'http://non_existing_host:' + \ str(gdaltest.webserver_port) + '/redirected' - return 'success' - ############################################################################### # Test VSIFOpenL() -def vsiwebhdfs_open(): +def test_vsiwebhdfs_open(): if gdaltest.webserver_port == 0: - return 'skip' + pytest.skip() gdal.VSICurlClearCache() @@ -97,13 +94,9 @@ def vsiwebhdfs_open(): {}, '0123456789data') with webserver.install_http_handler(handler): f = open_for_read(gdaltest.webhdfs_base_connection + '/foo/bar') - if f is None: - gdaltest.post_reason('fail') - return 'fail' + assert f is not None gdal.VSIFSeekL(f, 9999990784 + 10, 0) - if gdal.VSIFReadL(1, 4, f).decode('ascii') != 'data': - gdaltest.post_reason('fail') - return 'fail' + assert gdal.VSIFReadL(1, 4, f).decode('ascii') == 'data' gdal.VSIFCloseL(f) # Download with redirect (nominal) and permissions @@ -120,12 +113,8 @@ def vsiwebhdfs_open(): 'WEBHDFS_DATANODE_HOST': 'localhost'}): with webserver.install_http_handler(handler): f = open_for_read(gdaltest.webhdfs_base_connection + '/foo/bar') - if f is None: - gdaltest.post_reason('fail') - return 'fail' - if gdal.VSIFReadL(1, 4, f).decode('ascii') != 'yeah': - gdaltest.post_reason('fail') - return 'fail' + assert f is not None + assert gdal.VSIFReadL(1, 4, f).decode('ascii') == 'yeah' gdal.VSIFCloseL(f) # Test error @@ -133,34 +122,26 @@ def vsiwebhdfs_open(): gdal.VSICurlClearCache() f = open_for_read(gdaltest.webhdfs_base_connection + '/foo/bar') - if f is None: - gdaltest.post_reason('fail') - return 'fail' + assert f is not None handler = webserver.SequentialHandler() handler.add('GET', '/webhdfs/v1/foo/bar?op=OPEN&offset=0&length=16384', 404) with webserver.install_http_handler(handler): - if len(gdal.VSIFReadL(1, 4, f)) != 0: - gdaltest.post_reason('fail') - return 'fail' + assert len(gdal.VSIFReadL(1, 4, f)) == 0 # Retry: shouldn't not cause network access - if len(gdal.VSIFReadL(1, 4, f)) != 0: - gdaltest.post_reason('fail') - return 'fail' + assert len(gdal.VSIFReadL(1, 4, f)) == 0 gdal.VSIFCloseL(f) - return 'success' - ############################################################################### # Test VSIStatL() -def vsiwebhdfs_stat(): +def test_vsiwebhdfs_stat(): if gdaltest.webserver_port == 0: - return 'skip' + pytest.skip() gdal.VSICurlClearCache() @@ -170,18 +151,15 @@ def vsiwebhdfs_stat(): with webserver.install_http_handler(handler): stat_res = gdal.VSIStatL(gdaltest.webhdfs_base_connection + '/foo/bar') 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() # Test caching stat_res = gdal.VSIStatL(gdaltest.webhdfs_base_connection + '/foo/bar') - if stat_res.size != 1000000: - gdaltest.post_reason('fail') - return 'fail' + assert stat_res.size == 1000000 # Test missing file handler = webserver.SequentialHandler() @@ -190,20 +168,16 @@ def vsiwebhdfs_stat(): with webserver.install_http_handler(handler): stat_res = gdal.VSIStatL( gdaltest.webhdfs_base_connection + '/unexisting') - if stat_res is not None: - gdaltest.post_reason('fail') - return 'fail' - - return 'success' + assert stat_res is None ############################################################################### # Test ReadDir() -def vsiwebhdfs_readdir(): +def test_vsiwebhdfs_readdir(): if gdaltest.webserver_port == 0: - return 'skip' + pytest.skip() gdal.VSICurlClearCache() @@ -212,25 +186,15 @@ def vsiwebhdfs_readdir(): {}, '{"FileStatuses":{"FileStatus":[{"type":"FILE","modificationTime":1000,"pathSuffix":"bar.baz","length":123456},{"type":"DIRECTORY","pathSuffix":"mysubdir","length":0}]}}') with webserver.install_http_handler(handler): dir_contents = gdal.ReadDir(gdaltest.webhdfs_base_connection + '/foo') - if dir_contents != ['bar.baz', 'mysubdir']: - gdaltest.post_reason('fail') - print(dir_contents) - return 'fail' + assert dir_contents == ['bar.baz', 'mysubdir'] stat_res = gdal.VSIStatL(gdaltest.webhdfs_base_connection + '/foo/bar.baz') - if stat_res.size != 123456: - gdaltest.post_reason('fail') - print(stat_res.size) - return 'fail' - if stat_res.mtime != 1: - gdaltest.post_reason('fail') - return 'fail' + assert stat_res.size == 123456 + assert stat_res.mtime == 1 # ReadDir on something known to be a file shouldn't cause network access dir_contents = gdal.ReadDir( gdaltest.webhdfs_base_connection + '/foo/bar.baz') - if dir_contents is not None: - gdaltest.post_reason('fail') - return 'fail' + assert dir_contents is None # Test error on ReadDir() handler = webserver.SequentialHandler() @@ -238,21 +202,16 @@ def vsiwebhdfs_readdir(): with webserver.install_http_handler(handler): dir_contents = gdal.ReadDir( gdaltest.webhdfs_base_connection + 'foo/error_test/') - if dir_contents is not None: - gdaltest.post_reason('fail') - print(dir_contents) - return 'fail' - - return 'success' + assert dir_contents is None ############################################################################### # Test write -def vsiwebhdfs_write(): +def test_vsiwebhdfs_write(): if gdaltest.webserver_port == 0: - return 'skip' + pytest.skip() gdal.VSICurlClearCache() @@ -263,9 +222,7 @@ def vsiwebhdfs_write(): with gdaltest.error_handler(): f = gdal.VSIFOpenL( gdaltest.webhdfs_base_connection + '/foo/bar', 'wb') - if f is not None: - gdaltest.post_reason('fail') - return 'fail' + assert f is None handler = webserver.SequentialHandler() handler.add('PUT', '/webhdfs/v1/foo/bar?op=CREATE&overwrite=true&user.name=root', 307, @@ -277,12 +234,8 @@ def vsiwebhdfs_write(): with webserver.install_http_handler(handler): f = gdal.VSIFOpenL( gdaltest.webhdfs_base_connection + '/foo/bar', 'wb') - if f is None: - gdaltest.post_reason('fail') - return 'fail' - if gdal.VSIFCloseL(f) != 0: - gdaltest.post_reason('fail') - return 'fail' + assert f is not None + assert gdal.VSIFCloseL(f) == 0 # Non-empty file @@ -298,13 +251,9 @@ def vsiwebhdfs_write(): with webserver.install_http_handler(handler): f = gdal.VSIFOpenL( gdaltest.webhdfs_base_connection + '/foo/bar', 'wb') - if f is None: - gdaltest.post_reason('fail') - return 'fail' + assert f is not None - if gdal.VSIFWriteL('foobar', 1, 6, f) != 6: - gdaltest.post_reason('fail') - return 'fail' + assert gdal.VSIFWriteL('foobar', 1, 6, f) == 6 handler = webserver.SequentialHandler() @@ -328,9 +277,7 @@ def method(request): 200, expected_body='foobar'.encode('ascii')) with webserver.install_http_handler(handler): - if gdal.VSIFCloseL(f) != 0: - gdaltest.post_reason('fail') - return 'fail' + assert gdal.VSIFCloseL(f) == 0 # Errors during file creation @@ -344,9 +291,7 @@ def method(request): with gdaltest.error_handler(): f = gdal.VSIFOpenL( gdaltest.webhdfs_base_connection + '/foo/bar', 'wb') - if f is not None: - gdaltest.post_reason('fail') - return 'fail' + assert f is None handler = webserver.SequentialHandler() handler.add('PUT', '/webhdfs/v1/foo/bar?op=CREATE&overwrite=true&user.name=root', 307, @@ -356,9 +301,7 @@ def method(request): with gdaltest.error_handler(): f = gdal.VSIFOpenL( gdaltest.webhdfs_base_connection + '/foo/bar', 'wb') - if f is not None: - gdaltest.post_reason('fail') - return 'fail' + assert f is None # Errors during POST @@ -374,13 +317,9 @@ def method(request): with webserver.install_http_handler(handler): f = gdal.VSIFOpenL( gdaltest.webhdfs_base_connection + '/foo/bar', 'wb') - if f is None: - gdaltest.post_reason('fail') - return 'fail' + assert f is not None - if gdal.VSIFWriteL('foobar', 1, 6, f) != 6: - gdaltest.post_reason('fail') - return 'fail' + assert gdal.VSIFWriteL('foobar', 1, 6, f) == 6 handler = webserver.SequentialHandler() handler.add('POST', '/webhdfs/v1/foo/bar?op=APPEND&user.name=root', 307, @@ -390,20 +329,17 @@ def method(request): with gdaltest.error_handler(): with webserver.install_http_handler(handler): - if gdal.VSIFCloseL(f) == 0: - gdaltest.post_reason('fail') - return 'fail' - - return 'success' + assert gdal.VSIFCloseL(f) != 0 + ############################################################################### # Test Unlink() -def vsiwebhdfs_unlink(): +def test_vsiwebhdfs_unlink(): if gdaltest.webserver_port == 0: - return 'skip' + pytest.skip() gdal.VSICurlClearCache() @@ -413,9 +349,7 @@ def vsiwebhdfs_unlink(): {}, '{"boolean":true}') with webserver.install_http_handler(handler): ret = gdal.Unlink(gdaltest.webhdfs_base_connection + '/foo/bar') - if ret != 0: - gdaltest.post_reason('fail') - return 'fail' + assert ret == 0 gdal.VSICurlClearCache() @@ -431,9 +365,7 @@ def vsiwebhdfs_unlink(): 'WEBHDFS_DELEGATION': 'token'}): with webserver.install_http_handler(handler): ret = gdal.Unlink(gdaltest.webhdfs_base_connection + '/foo/bar') - if ret != 0: - gdaltest.post_reason('fail') - return 'fail' + assert ret == 0 # Failure handler = webserver.SequentialHandler() @@ -442,9 +374,7 @@ def vsiwebhdfs_unlink(): with webserver.install_http_handler(handler): with gdaltest.error_handler(): ret = gdal.Unlink(gdaltest.webhdfs_base_connection + '/foo/bar') - if ret != -1: - gdaltest.post_reason('fail') - return 'fail' + assert ret == -1 gdal.VSICurlClearCache() @@ -455,28 +385,22 @@ def vsiwebhdfs_unlink(): with webserver.install_http_handler(handler): with gdaltest.error_handler(): ret = gdal.Unlink(gdaltest.webhdfs_base_connection + '/foo/bar') - if ret != -1: - gdaltest.post_reason('fail') - return 'fail' - - return 'success' + assert ret == -1 ############################################################################### # Test Mkdir() / Rmdir() -def vsiwebhdfs_mkdir_rmdir(): +def test_vsiwebhdfs_mkdir_rmdir(): if gdaltest.webserver_port == 0: - return 'skip' + pytest.skip() gdal.VSICurlClearCache() # Invalid name ret = gdal.Mkdir('/vsiwebhdfs', 0) - if ret == 0: - gdaltest.post_reason('fail') - return 'fail' + assert ret != 0 # Valid handler = webserver.SequentialHandler() @@ -484,9 +408,7 @@ def vsiwebhdfs_mkdir_rmdir(): {}, '{"boolean":true}') with webserver.install_http_handler(handler): ret = gdal.Mkdir(gdaltest.webhdfs_base_connection + '/foo/dir', 0) - if ret != 0: - gdaltest.post_reason('fail') - return 'fail' + assert ret == 0 # Valid with all options handler = webserver.SequentialHandler() @@ -496,9 +418,7 @@ def vsiwebhdfs_mkdir_rmdir(): with webserver.install_http_handler(handler): ret = gdal.Mkdir(gdaltest.webhdfs_base_connection + '/foo/dir/', 493) # 0755 - if ret != 0: - gdaltest.post_reason('fail') - return 'fail' + assert ret == 0 # Error handler = webserver.SequentialHandler() @@ -506,21 +426,15 @@ def vsiwebhdfs_mkdir_rmdir(): with webserver.install_http_handler(handler): ret = gdal.Mkdir(gdaltest.webhdfs_base_connection + '/foo/dir_error', 0) - if ret == 0: - gdaltest.post_reason('fail') - return 'fail' + assert ret != 0 # Root name is invalid ret = gdal.Mkdir(gdaltest.webhdfs_base_connection + '/', 0) - if ret == 0: - gdaltest.post_reason('fail') - return 'fail' + assert ret != 0 # Invalid name ret = gdal.Rmdir('/vsiwebhdfs') - if ret == 0: - gdaltest.post_reason('fail') - return 'fail' + assert ret != 0 gdal.VSICurlClearCache() @@ -530,28 +444,22 @@ def vsiwebhdfs_mkdir_rmdir(): {}, '{"boolean":true}') with webserver.install_http_handler(handler): ret = gdal.Rmdir(gdaltest.webhdfs_base_connection + '/foo/dir') - if ret != 0: - gdaltest.post_reason('fail') - return 'fail' + assert ret == 0 # Error handler = webserver.SequentialHandler() handler.add('DELETE', '/webhdfs/v1/foo/dir_error?op=DELETE', 404) with webserver.install_http_handler(handler): ret = gdal.Rmdir(gdaltest.webhdfs_base_connection + '/foo/dir_error') - if ret == 0: - gdaltest.post_reason('fail') - return 'fail' - - return 'success' + assert ret != 0 ############################################################################### -def vsiwebhdfs_stop_webserver(): +def test_vsiwebhdfs_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 @@ -559,57 +467,41 @@ def vsiwebhdfs_stop_webserver(): webserver.server_stop(gdaltest.webserver_process, gdaltest.webserver_port) - return 'success' - ############################################################################### # Nominal cases (require valid credentials) -def vsiwebhdfs_extra_1(): +def test_vsiwebhdfs_extra_1(): if not gdaltest.built_against_curl(): - return 'skip' + pytest.skip() webhdfs_url = gdal.GetConfigOption('WEBHDFS_URL') if webhdfs_url is None: - print('Missing WEBHDFS_URL for running gdaltest_list_extra') - return 'skip' + pytest.skip('Missing WEBHDFS_URL') if webhdfs_url.endswith('/webhdfs/v1') or webhdfs_url.endswith('/webhdfs/v1/'): path = '/vsiwebhdfs/' + webhdfs_url 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 = 'vsiwebhdfs_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: @@ -618,115 +510,53 @@ def vsiwebhdfs_extra_1(): # return 'fail' 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' % + assert ret >= 0, ('Unlink(%s) should not return an error' % (subpath + '/test.txt')) - return 'fail' 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('/vsiwebhdfs/' + webhdfs_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 vsiwebhdfs_cleanup(): +def test_vsiwebhdfs_cleanup(): for var in gdaltest.webhdfs_vars: gdal.SetConfigOption(var, gdaltest.webhdfs_vars[var]) - - return 'success' - - -gdaltest_list = [vsiwebhdfs_init, - vsiwebhdfs_start_webserver, - vsiwebhdfs_open, - vsiwebhdfs_stat, - vsiwebhdfs_readdir, - vsiwebhdfs_write, - vsiwebhdfs_unlink, - vsiwebhdfs_mkdir_rmdir, - vsiwebhdfs_stop_webserver, - vsiwebhdfs_cleanup] - -gdaltest_list_extra = [vsiwebhdfs_extra_1] - -if __name__ == '__main__': - - gdaltest.setup_run('vsiwebhdfs') - - if gdal.GetConfigOption('RUN_MANUAL_ONLY', None): - gdaltest.run_tests(gdaltest_list_extra) - else: - gdaltest.run_tests( - gdaltest_list + gdaltest_list_extra + [vsiwebhdfs_cleanup]) - - sys.exit(gdaltest.summarize()) diff --git a/autotest/gcore/vsizip.py b/autotest/gcore/vsizip.py index 82cb1e4e2218..e96d0a7b7f87 100755 --- a/autotest/gcore/vsizip.py +++ b/autotest/gcore/vsizip.py @@ -30,30 +30,25 @@ ############################################################################### import random -import sys -sys.path.append('../pymod') import gdaltest from osgeo import gdal +import pytest ############################################################################### # Test writing a ZIP with multiple files and directories -def vsizip_1(): +def test_vsizip_1(): # We can keep the handle open during all the ZIP writing hZIP = gdal.VSIFOpenL("/vsizip/vsimem/test.zip", "wb") - if hZIP is None: - gdaltest.post_reason('fail 1') - return 'fail' + assert hZIP is not None, 'fail 1' # One way to create a directory f = gdal.VSIFOpenL("/vsizip/vsimem/test.zip/subdir2/", "wb") - if f is None: - gdaltest.post_reason('fail 2') - return 'fail' + assert f is not None, 'fail 2' gdal.VSIFCloseL(f) # A more natural one @@ -61,9 +56,7 @@ def vsizip_1(): # Create 1st file f2 = gdal.VSIFOpenL("/vsizip/vsimem/test.zip/subdir3/abcd", "wb") - if f2 is None: - gdaltest.post_reason('fail 3') - return 'fail' + assert f2 is not None, 'fail 3' gdal.VSIFWriteL("abcd", 1, 4, f2) gdal.VSIFCloseL(f2) @@ -72,19 +65,13 @@ def vsizip_1(): gdal.PushErrorHandler('CPLQuietErrorHandler') f = gdal.VSIFOpenL("/vsizip/vsimem/test.zip/subdir3/abcd", "rb") gdal.PopErrorHandler() - if gdal.GetLastErrorMsg() != 'Cannot read a zip file being written': - gdaltest.post_reason('expected error') - print(gdal.GetLastErrorMsg()) - return 'fail' - if f is not None: - gdaltest.post_reason('should not have been successful 1') - return 'fail' + assert gdal.GetLastErrorMsg() == 'Cannot read a zip file being written', \ + 'expected error' + assert f is None, 'should not have been successful 1' # Create 2nd file f3 = gdal.VSIFOpenL("/vsizip/vsimem/test.zip/subdir3/efghi", "wb") - if f3 is None: - gdaltest.post_reason('fail 4') - return 'fail' + assert f3 is not None, 'fail 4' gdal.VSIFWriteL("efghi", 1, 5, f3) # Try creating a 3d file @@ -92,13 +79,9 @@ def vsizip_1(): gdal.PushErrorHandler('CPLQuietErrorHandler') f4 = gdal.VSIFOpenL("/vsizip/vsimem/test.zip/that_wont_work", "wb") gdal.PopErrorHandler() - if gdal.GetLastErrorMsg() != 'Cannot create that_wont_work while another file is being written in the .zip': - gdaltest.post_reason('expected error') - print(gdal.GetLastErrorMsg()) - return 'fail' - if f4 is not None: - gdaltest.post_reason('should not have been successful 2') - return 'fail' + assert gdal.GetLastErrorMsg() == 'Cannot create that_wont_work while another file is being written in the .zip', \ + 'expected error' + assert f4 is None, 'should not have been successful 2' gdal.VSIFCloseL(f3) @@ -111,79 +94,51 @@ def vsizip_1(): f = gdal.VSIFOpenL('/vsizip/vsimem/test.zip', 'rb') if f is not None: gdal.VSIFCloseL(f) - if gdal.GetLastErrorMsg() == '': - gdaltest.post_reason('expected error') - print(gdal.GetLastErrorMsg()) - return 'fail' + assert gdal.GetLastErrorMsg() != '', 'expected error' f = gdal.VSIFOpenL("/vsizip/vsimem/test.zip/subdir3/abcd", "rb") - if f is None: - gdaltest.post_reason('fail 5') - return 'fail' + assert f is not None, 'fail 5' data = gdal.VSIFReadL(1, 4, f) gdal.VSIFCloseL(f) - if data.decode('ASCII') != 'abcd': - gdaltest.post_reason('fail') - print(data) - return 'fail' + assert data.decode('ASCII') == 'abcd' # Test alternate uri syntax gdal.Rename("/vsimem/test.zip", "/vsimem/test.xxx") f = gdal.VSIFOpenL("/vsizip/{/vsimem/test.xxx}/subdir3/abcd", "rb") - if f is None: - gdaltest.post_reason('fail') - return 'fail' + assert f is not None data = gdal.VSIFReadL(1, 4, f) gdal.VSIFCloseL(f) - if data.decode('ASCII') != 'abcd': - gdaltest.post_reason('fail') - print(data) - return 'fail' + assert data.decode('ASCII') == 'abcd' # With a trailing slash f = gdal.VSIFOpenL("/vsizip/{/vsimem/test.xxx}/subdir3/abcd/", "rb") - if f is None: - gdaltest.post_reason('fail') - return 'fail' + assert f is not None gdal.VSIFCloseL(f) # Test ReadDir() - if len(gdal.ReadDir("/vsizip/{/vsimem/test.xxx}")) != 3: - gdaltest.post_reason('fail') - print(gdal.ReadDir("/vsizip/{/vsimem/test.xxx}")) - return 'fail' + assert len(gdal.ReadDir("/vsizip/{/vsimem/test.xxx}")) == 3 # Unbalanced curls f = gdal.VSIFOpenL("/vsizip/{/vsimem/test.xxx", "rb") - if f is not None: - gdaltest.post_reason('fail') - return 'fail' + assert f is None # Non existing mainfile f = gdal.VSIFOpenL("/vsizip/{/vsimem/test.xxx}/bla", "rb") - if f is not None: - gdaltest.post_reason('fail') - return 'fail' + assert f is None # Non existing subfile f = gdal.VSIFOpenL("/vsizip/{/vsimem/test.zzz}/bla", "rb") - if f is not None: - gdaltest.post_reason('fail') - return 'fail' + assert f is None # Wrong syntax f = gdal.VSIFOpenL("/vsizip/{/vsimem/test.xxx}.aux.xml", "rb") - if f is not None: - gdaltest.post_reason('fail') - return 'fail' + assert f is None # Test nested { { } } hZIP = gdal.VSIFOpenL("/vsizip/{/vsimem/zipinzip.yyy}", "wb") - if hZIP is None: - gdaltest.post_reason('fail 1') - return 'fail' + assert hZIP is not None, 'fail 1' f = gdal.VSIFOpenL("/vsizip/{/vsimem/zipinzip.yyy}/test.xxx", "wb") f_src = gdal.VSIFOpenL("/vsimem/test.xxx", "rb") data = gdal.VSIFReadL(1, 10000, f_src) @@ -193,112 +148,76 @@ def vsizip_1(): gdal.VSIFCloseL(hZIP) f = gdal.VSIFOpenL("/vsizip/{/vsizip/{/vsimem/zipinzip.yyy}/test.xxx}/subdir3/abcd/", "rb") - if f is None: - gdaltest.post_reason('fail') - return 'fail' + assert f is not None data = gdal.VSIFReadL(1, 4, f) gdal.VSIFCloseL(f) - if data.decode('ASCII') != 'abcd': - gdaltest.post_reason('fail') - print(data) - return 'fail' + assert data.decode('ASCII') == 'abcd' gdal.Unlink("/vsimem/test.xxx") gdal.Unlink("/vsimem/zipinzip.yyy") # Test VSIStatL on a non existing file - if gdal.VSIStatL('/vsizip//vsimem/foo.zip') is not None: - gdaltest.post_reason('fail') - return 'fail' + assert gdal.VSIStatL('/vsizip//vsimem/foo.zip') is None # Test ReadDir on a non existing file - if gdal.ReadDir('/vsizip//vsimem/foo.zip') is not None: - gdaltest.post_reason('fail') - return 'fail' - - return 'success' + assert gdal.ReadDir('/vsizip//vsimem/foo.zip') is None ############################################################################### # Test writing 2 files in the ZIP by closing it completely between the 2 -def vsizip_2(): +def test_vsizip_2(): zip_name = '/vsimem/test2.zip' fmain = gdal.VSIFOpenL("/vsizip/" + zip_name + "/foo.bar", "wb") - if fmain is None: - gdaltest.post_reason('fail 1') - return 'fail' + assert fmain is not None, 'fail 1' gdal.VSIFWriteL("12345", 1, 5, fmain) gdal.VSIFCloseL(fmain) content = gdal.ReadDir("/vsizip/" + zip_name) - if content != ['foo.bar']: - gdaltest.post_reason('bad content 1') - print(content) - return 'fail' + assert content == ['foo.bar'], 'bad content 1' # Now append a second file fmain = gdal.VSIFOpenL("/vsizip/" + zip_name + "/bar.baz", "wb") - if fmain is None: - gdaltest.post_reason('fail 2') - return 'fail' + assert fmain is not None, 'fail 2' gdal.VSIFWriteL("67890", 1, 5, fmain) gdal.ErrorReset() gdal.PushErrorHandler('CPLQuietErrorHandler') content = gdal.ReadDir("/vsizip/" + zip_name) gdal.PopErrorHandler() - if gdal.GetLastErrorMsg() != 'Cannot read a zip file being written': - gdaltest.post_reason('expected error') - print(gdal.GetLastErrorMsg()) - return 'fail' - if content is not None: - gdaltest.post_reason('bad content 2') - print(content) - return 'fail' + assert gdal.GetLastErrorMsg() == 'Cannot read a zip file being written', \ + 'expected error' + assert content is None, 'bad content 2' gdal.VSIFCloseL(fmain) content = gdal.ReadDir("/vsizip/" + zip_name) - if content != ['foo.bar', 'bar.baz']: - gdaltest.post_reason('bad content 3') - print(content) - return 'fail' + assert content == ['foo.bar', 'bar.baz'], 'bad content 3' fmain = gdal.VSIFOpenL("/vsizip/" + zip_name + "/foo.bar", "rb") - if fmain is None: - gdaltest.post_reason('fail 3') - return 'fail' + assert fmain is not None, 'fail 3' data = gdal.VSIFReadL(1, 5, fmain) gdal.VSIFCloseL(fmain) - if data.decode('ASCII') != '12345': - print(data) - return 'fail' + assert data.decode('ASCII') == '12345' fmain = gdal.VSIFOpenL("/vsizip/" + zip_name + "/bar.baz", "rb") - if fmain is None: - gdaltest.post_reason('fail 4') - return 'fail' + assert fmain is not None, 'fail 4' data = gdal.VSIFReadL(1, 5, fmain) gdal.VSIFCloseL(fmain) - if data.decode('ASCII') != '67890': - print(data) - return 'fail' + assert data.decode('ASCII') == '67890' gdal.Unlink(zip_name) - return 'success' - ############################################################################### # Test opening in write mode a file inside a zip archive whose content has been listed before (testcase for fix of r22625) -def vsizip_3(): +def test_vsizip_3(): fmain = gdal.VSIFOpenL("/vsizip/vsimem/test3.zip", "wb") @@ -321,80 +240,55 @@ def vsizip_3(): gdal.Unlink("/vsimem/test3.zip") - if res != ['foo', 'bar', 'baz']: - print(res) - return 'fail' - - return 'success' + assert res == ['foo', 'bar', 'baz'] ############################################################################### # Test ReadRecursive on valid zip -def vsizip_4(): +def test_vsizip_4(): # read recursive and validate content res = gdal.ReadDirRecursive("/vsizip/data/testzip.zip") - if res is None: - gdaltest.post_reason('fail read') - return 'fail' - if res != ['subdir/', 'subdir/subdir/', 'subdir/subdir/uint16.tif', + assert res is not None, 'fail read' + assert (res == ['subdir/', 'subdir/subdir/', 'subdir/subdir/uint16.tif', 'subdir/subdir/test_rpc.txt', 'subdir/test_rpc.txt', - 'test_rpc.txt', 'uint16.tif']: - gdaltest.post_reason('bad content') - print(res) - return 'fail' - - return 'success' + 'test_rpc.txt', 'uint16.tif']), 'bad content' ############################################################################### # Test ReadRecursive on deep zip -def vsizip_5(): +def test_vsizip_5(): # make file in memory fmain = gdal.VSIFOpenL('/vsizip/vsimem/bigdepthzip.zip', 'wb') - if fmain is None: - gdaltest.post_reason('fail') - return 'fail' + assert fmain is not None filename = "a" + "/a" * 1000 finside = gdal.VSIFOpenL('/vsizip/vsimem/bigdepthzip.zip/' + filename, 'wb') - if finside is None: - gdaltest.post_reason('fail') - return 'fail' + assert finside is not None gdal.VSIFCloseL(finside) gdal.VSIFCloseL(fmain) # read recursive and validate content res = gdal.ReadDirRecursive("/vsizip/vsimem/bigdepthzip.zip") - if res is None: - gdaltest.post_reason('fail read') - return 'fail' - if len(res) != 1001: - gdaltest.post_reason('wrong size: ' + str(len(res))) - return 'fail' - if res[10] != 'a/a/a/a/a/a/a/a/a/a/a/': - gdaltest.post_reason('bad content: ' + res[10]) - return 'fail' + assert res is not None, 'fail read' + assert len(res) == 1001, ('wrong size: ' + str(len(res))) + assert res[10] == 'a/a/a/a/a/a/a/a/a/a/a/', ('bad content: ' + res[10]) gdal.Unlink("/vsimem/bigdepthzip.zip") - return 'success' - ############################################################################### # Test writing 2 files with same name in a ZIP (#4785) -def vsizip_6(): +def test_vsizip_6(): # Maintain ZIP file opened fmain = gdal.VSIFOpenL("/vsizip/vsimem/test6.zip", "wb") f = gdal.VSIFOpenL("/vsizip/vsimem/test6.zip/foo.bar", "wb") - if f is None: - gdaltest.post_reason('fail') - return 'fail' + assert f is not None gdal.VSIFWriteL("12345", 1, 5, f) gdal.VSIFCloseL(f) f = None @@ -403,9 +297,8 @@ def vsizip_6(): f = gdal.VSIFOpenL("/vsizip/vsimem/test6.zip/foo.bar", "wb") gdal.PopErrorHandler() if f is not None: - gdaltest.post_reason('fail') gdal.VSIFCloseL(f) - return 'fail' + pytest.fail() gdal.VSIFCloseL(fmain) fmain = None @@ -413,9 +306,7 @@ def vsizip_6(): # Now close it each time f = gdal.VSIFOpenL("/vsizip/vsimem/test6.zip/foo.bar", "wb") - if f is None: - gdaltest.post_reason('fail') - return 'fail' + assert f is not None gdal.VSIFWriteL("12345", 1, 5, f) gdal.VSIFCloseL(f) f = None @@ -424,19 +315,16 @@ def vsizip_6(): f = gdal.VSIFOpenL("/vsizip/vsimem/test6.zip/foo.bar", "wb") gdal.PopErrorHandler() if f is not None: - gdaltest.post_reason('fail') gdal.VSIFCloseL(f) - return 'fail' + pytest.fail() gdal.Unlink("/vsimem/test6.zip") - return 'success' - ############################################################################### # Test that we use the extended field for UTF-8 filenames (#5361). -def vsizip_7(): +def test_vsizip_7(): content = gdal.ReadDir("/vsizip/data/cp866_plus_utf8.zip") ok = 0 @@ -449,60 +337,44 @@ def vsizip_7(): ok = 1 if ok == 0: - gdaltest.post_reason('bad content') print(content) - return 'fail' - - return 'success' + pytest.fail('bad content') + ############################################################################### # Basic test for ZIP64 support (5 GB file that compresses in less than 4 GB) -def vsizip_8(): - - if gdal.VSIStatL('/vsizip/vsizip/data/zero.bin.zip.zip/zero.bin.zip').size != 5000 * 1000 * 1000 + 1: - return 'fail' +def test_vsizip_8(): - return 'success' + assert gdal.VSIStatL('/vsizip/vsizip/data/zero.bin.zip.zip/zero.bin.zip').size == 5000 * 1000 * 1000 + 1 ############################################################################### # Basic test for ZIP64 support (5 GB file that is stored) -def vsizip_9(): +def test_vsizip_9(): - if gdal.VSIStatL('/vsizip//vsisparse/data/zero_stored.bin.xml.zip/zero.bin').size != 5000 * 1000 * 1000 + 1: - gdaltest.post_reason('fail') - return 'fail' + assert gdal.VSIStatL('/vsizip//vsisparse/data/zero_stored.bin.xml.zip/zero.bin').size == 5000 * 1000 * 1000 + 1 - if gdal.VSIStatL('/vsizip//vsisparse/data/zero_stored.bin.xml.zip/hello.txt').size != 6: - gdaltest.post_reason('fail') - return 'fail' + assert gdal.VSIStatL('/vsizip//vsisparse/data/zero_stored.bin.xml.zip/hello.txt').size == 6 f = gdal.VSIFOpenL('/vsizip//vsisparse/data/zero_stored.bin.xml.zip/zero.bin', 'rb') gdal.VSIFSeekL(f, 5000 * 1000 * 1000, 0) data = gdal.VSIFReadL(1, 1, f) gdal.VSIFCloseL(f) - if data.decode('ascii') != '\x03': - gdaltest.post_reason('fail') - return 'fail' + assert data.decode('ascii') == '\x03' f = gdal.VSIFOpenL('/vsizip//vsisparse/data/zero_stored.bin.xml.zip/hello.txt', 'rb') data = gdal.VSIFReadL(1, 6, f) gdal.VSIFCloseL(f) - if data.decode('ascii') != 'HELLO\n': - print(data) - gdaltest.post_reason('fail') - return 'fail' - - return 'success' + assert data.decode('ascii') == 'HELLO\n' ############################################################################### # Test that we recode filenames in ZIP (#5361) -def vsizip_10(): +def test_vsizip_10(): gdal.SetConfigOption('CPL_ZIP_ENCODING', 'CP866') content = gdal.ReadDir("/vsizip/data/cp866.zip") @@ -518,19 +390,17 @@ def vsizip_10(): if ok == 0: if gdal.GetLastErrorMsg().find('Recode from CP866 to UTF-8 not supported') >= 0: - return 'skip' + pytest.skip() - gdaltest.post_reason('bad content') print(content) - return 'fail' - - return 'success' + pytest.fail('bad content') + ############################################################################### # Test that we don't do anything with ZIP with filenames in UTF-8 already (#5361) -def vsizip_11(): +def test_vsizip_11(): content = gdal.ReadDir("/vsizip/data/utf8.zip") ok = 0 @@ -543,17 +413,15 @@ def vsizip_11(): ok = 1 if ok == 0: - gdaltest.post_reason('bad content') print(content) - return 'fail' - - return 'success' + pytest.fail('bad content') + ############################################################################### # Test changing the content of a zip file (#6005) -def vsizip_12(): +def test_vsizip_12(): fmain = gdal.VSIFOpenL("/vsizip/vsimem/vsizip_12_src1.zip", "wb") f = gdal.VSIFOpenL("/vsizip/vsimem/vsizip_12_src1.zip/foo.bar", "wb") @@ -595,18 +463,13 @@ def vsizip_12(): gdal.Unlink('/vsimem/vsizip_12_src2.zip') gdal.Unlink('/vsimem/vsizip_12.zip') - if content != ['bar.baz']: - gdaltest.post_reason('fail') - print(content) - return 'fail' - - return 'success' + assert content == ['bar.baz'] ############################################################################### # Test ReadDir() truncation -def vsizip_13(): +def test_vsizip_13(): fmain = gdal.VSIFOpenL("/vsizip/vsimem/vsizip_13.zip", "wb") for i in range(10): @@ -615,24 +478,18 @@ def vsizip_13(): gdal.VSIFCloseL(fmain) lst = gdal.ReadDir('/vsizip/vsimem/vsizip_13.zip') - if len(lst) < 4: - gdaltest.post_reason('fail') - return 'fail' + assert len(lst) >= 4 # Test truncation lst_truncated = gdal.ReadDir('/vsizip/vsimem/vsizip_13.zip', int(len(lst) / 2)) - if len(lst_truncated) <= int(len(lst) / 2): - gdaltest.post_reason('fail') - return 'fail' + assert len(lst_truncated) > int(len(lst) / 2) gdal.Unlink('/vsimem/vsizip_13.zip') - return 'success' - ############################################################################### # Test that we can recode filenames in ZIP when writing (#6631) -def vsizip_14(): +def test_vsizip_14(): fmain = gdal.VSIFOpenL('/vsizip//vsimem/vsizip_14.zip', 'wb') try: @@ -647,27 +504,22 @@ def vsizip_14(): if f is None: gdal.VSIFCloseL(fmain) gdal.Unlink('/vsimem/vsizip_14.zip') - return 'skip' + pytest.skip() gdal.VSIFWriteL('hello', 1, 5, f) gdal.VSIFCloseL(f) gdal.VSIFCloseL(fmain) content = gdal.ReadDir("/vsizip//vsimem/vsizip_14.zip") - if content != [cp866_filename]: - gdaltest.post_reason('bad content') - print(content) - return 'fail' + assert content == [cp866_filename], 'bad content' gdal.Unlink('/vsimem/vsizip_14.zip') - return 'success' - ############################################################################### # Test multithreaded compression -def vsizip_multi_thread(): +def test_vsizip_multi_thread(): with gdaltest.config_options({'GDAL_NUM_THREADS': 'ALL_CPUS', 'CPL_VSIL_DEFLATE_CHUNK_SIZE': '32K'}): @@ -685,22 +537,19 @@ def vsizip_multi_thread(): gdal.Unlink('/vsimem/vsizip_multi_thread.zip') if data != 'hello' * 100000: - gdaltest.post_reason('fail') - for i in range(10000): if data[i*5:i*5+5] != 'hello': print(i*5, data[i*5:i*5+5], data[i*5-5:i*5+5-5]) break - return 'fail' - - return 'success' + pytest.fail() + ############################################################################### # Test multithreaded compression, below the threshold where it triggers -def vsizip_multi_thread_below_threshold(): +def test_vsizip_multi_thread_below_threshold(): with gdaltest.config_options({'GDAL_NUM_THREADS': 'ALL_CPUS'}): fmain = gdal.VSIFOpenL('/vsizip//vsimem/vsizip_multi_thread.zip', 'wb') @@ -715,22 +564,17 @@ def vsizip_multi_thread_below_threshold(): gdal.Unlink('/vsimem/vsizip_multi_thread.zip') - if data != 'hello': - gdaltest.post_reason('fail') - print(data) - return 'fail' - - return 'success' + assert data == 'hello' ############################################################################### # Test creating ZIP64 file: uncompressed larger than 4GB, but compressed # data stream < 4 GB -def vsizip_create_zip64(): +def test_vsizip_create_zip64(): if not gdaltest.run_slow_tests(): - return 'skip' + pytest.skip() niters = 1000 s = 'hello' * 1000 * 1000 @@ -744,36 +588,26 @@ def vsizip_create_zip64(): gdal.VSIFCloseL(fmain) size = gdal.VSIStatL(zip_name).size - if size > 0xFFFFFFFF: - gdaltest.post_reason('fail') - print(size) - return 'fail' + assert size <= 0xFFFFFFFF size = gdal.VSIStatL('/vsizip/' + zip_name + '/test').size - if size != len(s) * niters: - gdaltest.post_reason('fail') - print(size) - return 'fail' + assert size == len(s) * niters f = gdal.VSIFOpenL('/vsizip/' + zip_name + '/test', 'rb') data = gdal.VSIFReadL(1, len(s), f).decode('ascii') gdal.VSIFCloseL(f) - if data != s: - gdaltest.post_reason('fail') - return 'fail' + assert data == s gdal.Unlink(zip_name) - return 'success' - ############################################################################### # Test creating ZIP64 file: compressed data stream > 4 GB -def vsizip_create_zip64_stream_larger_than_4G(): +def test_vsizip_create_zip64_stream_larger_than_4G(): if not gdaltest.run_slow_tests(): - return 'skip' + pytest.skip() zip_name = 'tmp/vsizip_create_zip64_stream_larger_than_4G.zip' @@ -788,66 +622,24 @@ def vsizip_create_zip64_stream_larger_than_4G(): gdal.VSIFCloseL(f) size = gdal.VSIStatL(zip_name).size - if size <= 0xFFFFFFFF: - gdaltest.post_reason('fail') - print(size) - return 'fail' + assert size > 0xFFFFFFFF size = gdal.VSIStatL('/vsizip/' + zip_name + '/test2').size - if size != len(s) * niters: - gdaltest.post_reason('fail') - print(size) - return 'fail' + assert size == len(s) * niters f = gdal.VSIFOpenL('/vsizip/' + zip_name + '/test2', 'rb') data = gdal.VSIFReadL(1, len(s), f).decode('ascii') gdal.VSIFCloseL(f) - if data != s: - gdaltest.post_reason('fail') - return 'fail' + assert data == s gdal.Unlink(zip_name) - return 'success' - ############################################################################### -def vsizip_byte_zip64_local_header_zeroed(): +def test_vsizip_byte_zip64_local_header_zeroed(): size = gdal.VSIStatL('/vsizip/data/byte_zip64_local_header_zeroed.zip/byte.tif').size - if size != 736: - gdaltest.post_reason('fail') - print(size) - return 'fail' - - return 'success' - -gdaltest_list = [vsizip_1, - vsizip_2, - vsizip_3, - vsizip_4, - vsizip_5, - vsizip_6, - vsizip_7, - vsizip_8, - vsizip_9, - vsizip_10, - vsizip_11, - vsizip_12, - vsizip_13, - vsizip_14, - vsizip_multi_thread, - vsizip_multi_thread_below_threshold, - vsizip_create_zip64, - vsizip_create_zip64_stream_larger_than_4G, - vsizip_byte_zip64_local_header_zeroed, - ] - - -if __name__ == '__main__': - - gdaltest.setup_run('vsizip') - - gdaltest.run_tests(gdaltest_list) - - sys.exit(gdaltest.summarize()) + assert size == 736 + + + diff --git a/autotest/gdrivers/__init__.py b/autotest/gdrivers/__init__.py new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/autotest/gdrivers/aaigrid.py b/autotest/gdrivers/aaigrid.py index 6061156549ef..8527940054a2 100755 --- a/autotest/gdrivers/aaigrid.py +++ b/autotest/gdrivers/aaigrid.py @@ -32,18 +32,17 @@ ############################################################################### import os -import sys from osgeo import gdal -sys.path.append('../pymod') import gdaltest +import pytest ############################################################################### # Perform simple read test. -def aaigrid_1(): +def test_aaigrid_1(): tst = gdaltest.GDALTest('aaigrid', 'pixel_per_line.asc', 1, 1123) return tst.testOpen() @@ -52,68 +51,49 @@ def aaigrid_1(): # Verify some auxiliary data. -def aaigrid_2(): +def test_aaigrid_2(): ds = gdal.Open('data/pixel_per_line.asc') gt = ds.GetGeoTransform() - if gt[0] != 100000.0 or gt[1] != 50 or gt[2] != 0 \ - or gt[3] != 650600.0 or gt[4] != 0 or gt[5] != -50: - gdaltest.post_reason('Aaigrid geotransform wrong.') - return 'fail' + assert gt[0] == 100000.0 and gt[1] == 50 and gt[2] == 0 and gt[3] == 650600.0 and gt[4] == 0 and gt[5] == -50, \ + 'Aaigrid geotransform wrong.' prj = ds.GetProjection() - if prj != 'PROJCS["unnamed",GEOGCS["NAD83",DATUM["North_American_Datum_1983",SPHEROID["GRS 1980",6378137,298.257222101,AUTHORITY["EPSG","7019"]],TOWGS84[0,0,0,0,0,0,0],AUTHORITY["EPSG","6269"]],PRIMEM["Greenwich",0,AUTHORITY["EPSG","8901"]],UNIT["degree",0.0174532925199433,AUTHORITY["EPSG","9122"]],AUTHORITY["EPSG","4269"]],PROJECTION["Albers_Conic_Equal_Area"],PARAMETER["standard_parallel_1",61.66666666666666],PARAMETER["standard_parallel_2",68],PARAMETER["latitude_of_center",59],PARAMETER["longitude_of_center",-132.5],PARAMETER["false_easting",500000],PARAMETER["false_northing",500000],UNIT["METERS",1]]': - gdaltest.post_reason('Projection does not match expected:\n%s' % prj) - return 'fail' + assert prj == 'PROJCS["unnamed",GEOGCS["NAD83",DATUM["North_American_Datum_1983",SPHEROID["GRS 1980",6378137,298.257222101,AUTHORITY["EPSG","7019"]],TOWGS84[0,0,0,0,0,0,0],AUTHORITY["EPSG","6269"]],PRIMEM["Greenwich",0,AUTHORITY["EPSG","8901"]],UNIT["degree",0.0174532925199433,AUTHORITY["EPSG","9122"]],AUTHORITY["EPSG","4269"]],PROJECTION["Albers_Conic_Equal_Area"],PARAMETER["standard_parallel_1",61.66666666666666],PARAMETER["standard_parallel_2",68],PARAMETER["latitude_of_center",59],PARAMETER["longitude_of_center",-132.5],PARAMETER["false_easting",500000],PARAMETER["false_northing",500000],UNIT["METERS",1]]', \ + ('Projection does not match expected:\n%s' % prj) band1 = ds.GetRasterBand(1) - if band1.GetNoDataValue() != -99999: - gdaltest.post_reason('Grid NODATA value wrong or missing.') - return 'fail' + assert band1.GetNoDataValue() == -99999, 'Grid NODATA value wrong or missing.' - if band1.DataType != gdal.GDT_Float32: - gdaltest.post_reason('Data type is not Float32!') - return 'fail' - - return 'success' + assert band1.DataType == gdal.GDT_Float32, 'Data type is not Float32!' ############################################################################### # Test reading a file where decimal separator is comma (#3668) -def aaigrid_comma(): +def test_aaigrid_comma(): ds = gdal.Open('data/pixel_per_line_comma.asc') gt = ds.GetGeoTransform() - if gt[0] != 100000.0 or gt[1] != 50 or gt[2] != 0 \ - or gt[3] != 650600.0 or gt[4] != 0 or gt[5] != -50: - gdaltest.post_reason('Aaigrid geotransform wrong.') - return 'fail' + assert gt[0] == 100000.0 and gt[1] == 50 and gt[2] == 0 and gt[3] == 650600.0 and gt[4] == 0 and gt[5] == -50, \ + 'Aaigrid geotransform wrong.' band1 = ds.GetRasterBand(1) - if band1.Checksum() != 1123: - gdaltest.post_reason('Did not get expected nodata value.') - return 'fail' - - if band1.GetNoDataValue() != -99999: - gdaltest.post_reason('Grid NODATA value wrong or missing.') - return 'fail' + assert band1.Checksum() == 1123, 'Did not get expected nodata value.' - if band1.DataType != gdal.GDT_Float32: - gdaltest.post_reason('Data type is not Float32!') - return 'fail' + assert band1.GetNoDataValue() == -99999, 'Grid NODATA value wrong or missing.' - return 'success' + assert band1.DataType == gdal.GDT_Float32, 'Data type is not Float32!' ############################################################################### # Create simple copy and check. -def aaigrid_3(): +def test_aaigrid_3(): tst = gdaltest.GDALTest('AAIGRID', 'byte.tif', 1, 4672) @@ -125,7 +105,7 @@ def aaigrid_3(): # Read subwindow. Tests the tail recursion problem. -def aaigrid_4(): +def test_aaigrid_4(): tst = gdaltest.GDALTest('aaigrid', 'pixel_per_line.asc', 1, 187, 5, 5, 5, 5) @@ -135,7 +115,7 @@ def aaigrid_4(): # Perform simple read test on mixed-case .PRJ filename -def aaigrid_5(): +def test_aaigrid_5(): # Mixed-case files pair used in the test: # - case_sensitive.ASC @@ -171,45 +151,33 @@ def aaigrid_5(): # Verify data type determination from type of nodata -def aaigrid_6(): +def test_aaigrid_6(): ds = gdal.Open('data/nodata_float.asc') b = ds.GetRasterBand(1) - if b.GetNoDataValue() != -99999: - gdaltest.post_reason('Grid NODATA value wrong or missing.') - return 'fail' + assert b.GetNoDataValue() == -99999, 'Grid NODATA value wrong or missing.' - if b.DataType != gdal.GDT_Float32: - gdaltest.post_reason('Data type is not Float32!') - return 'fail' - - return 'success' + assert b.DataType == gdal.GDT_Float32, 'Data type is not Float32!' ############################################################################### # Verify data type determination from type of nodata -def aaigrid_6bis(): +def test_aaigrid_6bis(): ds = gdal.Open('data/nodata_int.asc') b = ds.GetRasterBand(1) - if b.GetNoDataValue() != -99999: - gdaltest.post_reason('Grid NODATA value wrong or missing.') - return 'fail' - - if b.DataType != gdal.GDT_Int32: - gdaltest.post_reason('Data type is not Int32!') - return 'fail' + assert b.GetNoDataValue() == -99999, 'Grid NODATA value wrong or missing.' - return 'success' + assert b.DataType == gdal.GDT_Int32, 'Data type is not Int32!' ############################################################################### # Verify writing files with non-square pixels. -def aaigrid_7(): +def test_aaigrid_7(): tst = gdaltest.GDALTest('AAIGRID', 'nonsquare.vrt', 1, 12481) @@ -219,7 +187,7 @@ def aaigrid_7(): ############################################################################### # Test creating an in memory copy. -def aaigrid_8(): +def test_aaigrid_8(): tst = gdaltest.GDALTest('AAIGRID', 'byte.tif', 1, 4672) @@ -229,7 +197,7 @@ def aaigrid_8(): ############################################################################### # Test DECIMAL_PRECISION creation option -def aaigrid_9(): +def test_aaigrid_9(): ds = gdal.Open('data/float32.bil') ds2 = gdal.GetDriverByName('AAIGRID').CreateCopy('tmp/aaigrid.tmp', ds, options=['DECIMAL_PRECISION=2']) @@ -239,20 +207,18 @@ def aaigrid_9(): gdal.GetDriverByName('AAIGRID').Delete('tmp/aaigrid.tmp') if abs(got_minmax[0] - -0.84) < 1e-7: - return 'success' - return 'fail' + return + pytest.fail() ############################################################################### # Test AAIGRID_DATATYPE configuration option and DATATYPE open options -def aaigrid_10(): +def test_aaigrid_10(): # By default detected as 32bit float ds = gdal.Open('data/float64.asc') - if ds.GetRasterBand(1).DataType != gdal.GDT_Float32: - gdaltest.post_reason('Data type is not Float32!') - return 'fail' + assert ds.GetRasterBand(1).DataType == gdal.GDT_Float32, 'Data type is not Float32!' for i in range(2): @@ -268,35 +234,28 @@ def aaigrid_10(): else: ds = gdal.OpenEx('data/float64.asc', open_options=['DATATYPE=Float64']) - if ds.GetRasterBand(1).DataType != gdal.GDT_Float64: - gdaltest.post_reason('Data type is not Float64!') - return 'fail' + assert ds.GetRasterBand(1).DataType == gdal.GDT_Float64, 'Data type is not Float64!' nv = ds.GetRasterBand(1).GetNoDataValue() - if abs(nv - -1.234567890123) > 1e-16: - gdaltest.post_reason('did not get expected nodata value') - return 'fail' + assert abs(nv - -1.234567890123) <= 1e-16, 'did not get expected nodata value' got_minmax = ds.GetRasterBand(1).ComputeRasterMinMax() - if abs(got_minmax[0] - 1.234567890123) > 1e-16: - gdaltest.post_reason('did not get expected min value') - return 'fail' - if abs(got_minmax[1] - 1.234567890123) > 1e-16: - gdaltest.post_reason('did not get expected max value') - return 'fail' + assert abs(got_minmax[0] - 1.234567890123) <= 1e-16, \ + 'did not get expected min value' + assert abs(got_minmax[1] - 1.234567890123) <= 1e-16, \ + 'did not get expected max value' try: os.remove('data/float64.asc.aux.xml') except OSError: pass - return 'success' - + ############################################################################### # Test SIGNIFICANT_DIGITS creation option (same as DECIMAL_PRECISION test) -def aaigrid_11(): +def test_aaigrid_11(): ds = gdal.Open('data/float32.bil') ds2 = gdal.GetDriverByName('AAIGRID').CreateCopy('tmp/aaigrid.tmp', ds, options=['SIGNIFICANT_DIGITS=2']) @@ -306,14 +265,14 @@ def aaigrid_11(): gdal.GetDriverByName('AAIGRID').Delete('tmp/aaigrid.tmp') if abs(got_minmax[0] - -0.84) < 1e-7: - return 'success' - return 'fail' + return + pytest.fail() ############################################################################### # Test no data is written to correct precision with DECIMAL_PRECISION. -def aaigrid_12(): +def test_aaigrid_12(): ds = gdal.Open('data/nodata_float.asc') ds2 = gdal.GetDriverByName('AAIGRID').CreateCopy('tmp/aaigrid.tmp', ds, @@ -321,28 +280,20 @@ def aaigrid_12(): del ds2 aai = open('tmp/aaigrid.tmp') - if not aai: - return 'fail' + assert aai for _ in range(5): aai.readline() ndv = aai.readline().strip().lower() aai.close() gdal.GetDriverByName('AAIGRID').Delete('tmp/aaigrid.tmp') - if not ndv.startswith('nodata_value'): - gdaltest.post_reason('fail') - print(ndv) - return 'fail' - if not ndv.endswith('-99999.000'): - gdaltest.post_reason('fail') - print(ndv) - return 'fail' - return 'success' + assert ndv.startswith('nodata_value') + assert ndv.endswith('-99999.000') ############################################################################### # Test no data is written to correct precision WITH SIGNIFICANT_DIGITS. -def aaigrid_13(): +def test_aaigrid_13(): ds = gdal.Open('data/nodata_float.asc') ds2 = gdal.GetDriverByName('AAIGRID').CreateCopy('tmp/aaigrid.tmp', ds, @@ -350,28 +301,20 @@ def aaigrid_13(): del ds2 aai = open('tmp/aaigrid.tmp') - if not aai: - return 'fail' + assert aai for _ in range(5): aai.readline() ndv = aai.readline().strip().lower() aai.close() gdal.GetDriverByName('AAIGRID').Delete('tmp/aaigrid.tmp') - if not ndv.startswith('nodata_value'): - gdaltest.post_reason('fail') - print(ndv) - return 'fail' - if not ndv.endswith('-1e+05') and not ndv.endswith('-1e+005'): - gdaltest.post_reason('fail') - print(ndv) - return 'fail' - return 'success' + assert ndv.startswith('nodata_value') + assert ndv.endswith('-1e+05') or ndv.endswith('-1e+005') ############################################################################### # Test fix for #6060 -def aaigrid_14(): +def test_aaigrid_14(): ds = gdal.Open('data/byte.tif') mem_ds = gdal.GetDriverByName('MEM').Create('', 20, 20, 1, gdal.GDT_Float32) @@ -385,18 +328,13 @@ def aaigrid_14(): gdal.GetDriverByName('AAIGRID').Delete('/vsimem/aaigrid_14.asc') - if data.find('107.0 123') < 0: - gdaltest.post_reason('fail') - print(data) - return 'fail' - - return 'success' + assert data.find('107.0 123') >= 0 ############################################################################### # Test Float64 detection when nodata = DBL_MIN -def aaigrid_15(): +def test_aaigrid_15(): gdal.FileFromMemBuffer('/vsimem/aaigrid_15.asc', """ncols 4 nrows 1 @@ -408,41 +346,12 @@ def aaigrid_15(): """) ds = gdal.Open('/vsimem/aaigrid_15.asc') - if ds.GetRasterBand(1).DataType != gdal.GDT_Float64: - gdaltest.post_reason('fail') - return 'fail' + assert ds.GetRasterBand(1).DataType == gdal.GDT_Float64 ds = None gdal.Unlink('/vsimem/aaigrid_15.asc') - return 'success' - ############################################################################### -gdaltest_list = [ - aaigrid_1, - aaigrid_2, - aaigrid_comma, - aaigrid_3, - aaigrid_4, - aaigrid_5, - aaigrid_6, - aaigrid_6bis, - aaigrid_7, - aaigrid_8, - aaigrid_9, - aaigrid_10, - aaigrid_11, - aaigrid_12, - aaigrid_13, - aaigrid_14, - aaigrid_15] - -if __name__ == '__main__': - - gdaltest.setup_run('aaigrid') - - gdaltest.run_tests(gdaltest_list) - - sys.exit(gdaltest.summarize()) + diff --git a/autotest/gdrivers/ace2.py b/autotest/gdrivers/ace2.py index abd1301dd9b9..b0c22425203a 100755 --- a/autotest/gdrivers/ace2.py +++ b/autotest/gdrivers/ace2.py @@ -28,10 +28,8 @@ # DEALINGS IN THE SOFTWARE. ############################################################################### -import sys from osgeo import gdal -sys.path.append('../pymod') import gdaltest @@ -39,7 +37,7 @@ # Test a fake ACE2 dataset -def ace2_1(): +def test_ace2_1(): f = gdal.VSIFOpenL('/vsimem/45N015E_5M.ACE2', 'wb') gdal.VSIFSeekL(f, 180 * 180 * 4 - 1, 0) @@ -66,13 +64,4 @@ def ace2_1(): return ret -gdaltest_list = [ - ace2_1] -if __name__ == '__main__': - - gdaltest.setup_run('ace2') - - gdaltest.run_tests(gdaltest_list) - - sys.exit(gdaltest.summarize()) diff --git a/autotest/gdrivers/adrg.py b/autotest/gdrivers/adrg.py index 801e17cd4398..7eaaa7de946f 100755 --- a/autotest/gdrivers/adrg.py +++ b/autotest/gdrivers/adrg.py @@ -30,11 +30,9 @@ ############################################################################### import os -import sys import shutil from osgeo import gdal -sys.path.append('../pymod') import gdaltest @@ -42,7 +40,7 @@ # Read test of simple byte reference data. -def adrg_read_gen(): +def test_adrg_read_gen(): tst = gdaltest.GDALTest('ADRG', 'SMALL_ADRG/ABCDEF01.GEN', 1, 62833) return tst.testOpen() @@ -51,7 +49,7 @@ def adrg_read_gen(): # Read test of simple byte reference data by the TRANSH01.THF file . -def adrg_read_transh(): +def test_adrg_read_transh(): tst = gdaltest.GDALTest('ADRG', 'SMALL_ADRG/TRANSH01.THF', 1, 62833) return tst.testOpen() @@ -60,7 +58,7 @@ def adrg_read_transh(): # Read test of simple byte reference data by a subdataset file -def adrg_read_subdataset_img(): +def test_adrg_read_subdataset_img(): tst = gdaltest.GDALTest('ADRG', 'ADRG:data/SMALL_ADRG/ABCDEF01.GEN,data/SMALL_ADRG/ABCDEF01.IMG', 1, 62833, filename_absolute=1) return tst.testOpen() @@ -69,7 +67,7 @@ def adrg_read_subdataset_img(): # Test copying. -def adrg_copy(): +def test_adrg_copy(): drv = gdal.GetDriverByName('ADRG') srcds = gdal.Open('data/SMALL_ADRG/ABCDEF01.GEN') @@ -78,21 +76,17 @@ def adrg_copy(): chksum = dstds.GetRasterBand(1).Checksum() - if chksum != 62833: - gdaltest.post_reason('Wrong checksum') - return 'fail' + assert chksum == 62833, 'Wrong checksum' dstds = None drv.Delete('tmp/ABCDEF01.GEN') - return 'success' - ############################################################################### # Test creating a fake 2 subdataset image and reading it. -def adrg_2subdatasets(): +def test_adrg_2subdatasets(): drv = gdal.GetDriverByName('ADRG') srcds = gdal.Open('data/SMALL_ADRG/ABCDEF01.GEN') @@ -105,22 +99,16 @@ def adrg_2subdatasets(): shutil.copy('tmp/XXXXXX01.IMG', 'tmp/XXXXXX02.IMG') ds = gdal.Open('tmp/TRANSH01.THF') - if ds.RasterCount != 0: - gdaltest.post_reason('did not expected non 0 RasterCount') - return 'fail' + assert ds.RasterCount == 0, 'did not expected non 0 RasterCount' ds = None ds = gdal.Open('ADRG:tmp/XXXXXX01.GEN,tmp/XXXXXX02.IMG') chksum = ds.GetRasterBand(1).Checksum() - if chksum != 62833: - gdaltest.post_reason('Wrong checksum') - return 'fail' + assert chksum == 62833, 'Wrong checksum' md = ds.GetMetadata('') - if md['ADRG_NAM'] != 'XXXXXX02': - gdaltest.post_reason('metadata wrong.') - return 'fail' + assert md['ADRG_NAM'] == 'XXXXXX02', 'metadata wrong.' ds = None @@ -130,13 +118,11 @@ def adrg_2subdatasets(): os.remove('tmp/XXXXXX02.IMG') os.remove('tmp/TRANSH01.THF') - return 'success' - ############################################################################### # Test creating an in memory copy. -def adrg_copy_vsimem(): +def test_adrg_copy_vsimem(): drv = gdal.GetDriverByName('ADRG') srcds = gdal.Open('data/SMALL_ADRG/ABCDEF01.GEN') @@ -145,9 +131,7 @@ def adrg_copy_vsimem(): chksum = dstds.GetRasterBand(1).Checksum() - if chksum != 62833: - gdaltest.post_reason('Wrong checksum') - return 'fail' + assert chksum == 62833, 'Wrong checksum' dstds = None @@ -155,75 +139,43 @@ def adrg_copy_vsimem(): ds = gdal.Open('/vsimem/ABCDEF01.GEN') chksum = ds.GetRasterBand(1).Checksum() - if chksum != 62833: - gdaltest.post_reason('Wrong checksum') - return 'fail' + assert chksum == 62833, 'Wrong checksum' ds = None drv.Delete('/vsimem/ABCDEF01.GEN') gdal.Unlink('/vsimem/TRANSH01.THF') - return 'success' - ############################################################################### # Test reading a fake North Polar dataset (#6560) -def adrg_zna_9(): +def test_adrg_zna_9(): ds = gdal.Open('data/SMALL_ADRG_ZNA9/ABCDEF01.GEN') expected_gt = (-307675.73602473765, 100.09145391818853, 0.0, -179477.5051066006, 0.0, -100.09145391818853) gt = ds.GetGeoTransform() - if max(abs(gt[i] - expected_gt[i]) for i in range(6)) > 1e-5: - gdaltest.post_reason('Wrong geotransfsorm') - print(gt) - return 'fail' + assert max(abs(gt[i] - expected_gt[i]) for i in range(6)) <= 1e-5, \ + 'Wrong geotransfsorm' wkt = ds.GetProjectionRef() - if wkt != """PROJCS["ARC_System_Zone_09",GEOGCS["GCS_Sphere",DATUM["D_Sphere",SPHEROID["Sphere",6378137.0,0.0]],PRIMEM["Greenwich",0],UNIT["degree",0.0174532925199433]],PROJECTION["Azimuthal_Equidistant"],PARAMETER["latitude_of_center",90],PARAMETER["longitude_of_center",0],PARAMETER["false_easting",0],PARAMETER["false_northing",0]]""": - gdaltest.post_reason('Wrong WKT') - print(wkt) - return 'fail' - - return 'success' + assert wkt == """PROJCS["ARC_System_Zone_09",GEOGCS["GCS_Sphere",DATUM["D_Sphere",SPHEROID["Sphere",6378137.0,0.0]],PRIMEM["Greenwich",0],UNIT["degree",0.0174532925199433]],PROJECTION["Azimuthal_Equidistant"],PARAMETER["latitude_of_center",90],PARAMETER["longitude_of_center",0],PARAMETER["false_easting",0],PARAMETER["false_northing",0]]""", \ + 'Wrong WKT' ############################################################################### # Test reading a fake South Polar dataset (#6560) -def adrg_zna_18(): +def test_adrg_zna_18(): ds = gdal.Open('data/SMALL_ADRG_ZNA18/ABCDEF01.GEN') expected_gt = (-307675.73602473765, 100.09145391818853, 0.0, 179477.5051066006, 0.0, -100.09145391818853) gt = ds.GetGeoTransform() - if max(abs(gt[i] - expected_gt[i]) for i in range(6)) > 1e-5: - gdaltest.post_reason('Wrong geotransfsorm') - print(gt) - return 'fail' + assert max(abs(gt[i] - expected_gt[i]) for i in range(6)) <= 1e-5, \ + 'Wrong geotransfsorm' wkt = ds.GetProjectionRef() - if wkt != """PROJCS["ARC_System_Zone_18",GEOGCS["GCS_Sphere",DATUM["D_Sphere",SPHEROID["Sphere",6378137.0,0.0]],PRIMEM["Greenwich",0],UNIT["degree",0.0174532925199433]],PROJECTION["Azimuthal_Equidistant"],PARAMETER["latitude_of_center",-90],PARAMETER["longitude_of_center",0],PARAMETER["false_easting",0],PARAMETER["false_northing",0]]""": - gdaltest.post_reason('Wrong WKT') - print(wkt) - return 'fail' - - return 'success' + assert wkt == """PROJCS["ARC_System_Zone_18",GEOGCS["GCS_Sphere",DATUM["D_Sphere",SPHEROID["Sphere",6378137.0,0.0]],PRIMEM["Greenwich",0],UNIT["degree",0.0174532925199433]],PROJECTION["Azimuthal_Equidistant"],PARAMETER["latitude_of_center",-90],PARAMETER["longitude_of_center",0],PARAMETER["false_easting",0],PARAMETER["false_northing",0]]""", \ + 'Wrong WKT' ############################################################################### -gdaltest_list = [ - adrg_read_gen, - adrg_read_transh, - adrg_read_subdataset_img, - adrg_copy, - adrg_2subdatasets, - adrg_copy_vsimem, - adrg_zna_9, - adrg_zna_18] - -if __name__ == '__main__': - - gdaltest.setup_run('adrg') - - gdaltest.run_tests(gdaltest_list) - sys.exit(gdaltest.summarize()) diff --git a/autotest/gdrivers/aigrid.py b/autotest/gdrivers/aigrid.py index 4563f388f36d..008986f0074a 100755 --- a/autotest/gdrivers/aigrid.py +++ b/autotest/gdrivers/aigrid.py @@ -30,18 +30,17 @@ ############################################################################### import os -import sys from osgeo import gdal -sys.path.append('../pymod') import gdaltest +import pytest ############################################################################### # Read test of simple byte reference data. -def aigrid_1(): +def test_aigrid_1(): tst = gdaltest.GDALTest('AIG', 'abc3x1', 1, 3) return tst.testOpen() @@ -50,59 +49,43 @@ def aigrid_1(): # Verify some auxiliary data. -def aigrid_2(): +def test_aigrid_2(): ds = gdal.Open('data/abc3x1/prj.adf') gt = ds.GetGeoTransform() - if gt[0] != -0.5 or gt[1] != 1.0 or gt[2] != 0.0 \ - or gt[3] != 0.5 or gt[4] != 0.0 or gt[5] != -1.0: - gdaltest.post_reason('Aigrid geotransform wrong.') - return 'fail' + assert gt[0] == -0.5 and gt[1] == 1.0 and gt[2] == 0.0 and gt[3] == 0.5 and gt[4] == 0.0 and gt[5] == -1.0, \ + 'Aigrid geotransform wrong.' prj = ds.GetProjection() - if prj.find('PROJCS["UTM Zone 55, Southern Hemisphere",GEOGCS["GDA94",DATUM["Geocentric_Datum_of_Australia_1994"') == -1: - gdaltest.post_reason('Projection does not match expected:\n%s' % prj) - return 'fail' + assert prj.find('PROJCS["UTM Zone 55, Southern Hemisphere",GEOGCS["GDA94",DATUM["Geocentric_Datum_of_Australia_1994"') != -1, \ + ('Projection does not match expected:\n%s' % prj) band1 = ds.GetRasterBand(1) - if band1.GetNoDataValue() != 255: - gdaltest.post_reason('Grid NODATA value wrong or missing.') - return 'fail' + assert band1.GetNoDataValue() == 255, 'Grid NODATA value wrong or missing.' - if band1.DataType != gdal.GDT_Byte: - gdaltest.post_reason('Data type is not Byte!') - return 'fail' - - return 'success' + assert band1.DataType == gdal.GDT_Byte, 'Data type is not Byte!' ############################################################################### # Verify the colormap, and nodata setting for test file. -def aigrid_3(): +def test_aigrid_3(): ds = gdal.Open('data/abc3x1') cm = ds.GetRasterBand(1).GetRasterColorTable() - if cm.GetCount() != 256 \ - or cm.GetColorEntry(0) != (95, 113, 150, 255)\ - or cm.GetColorEntry(1) != (95, 57, 29, 255): - gdaltest.post_reason('Wrong colormap entries') - return 'fail' + assert cm.GetCount() == 256 and cm.GetColorEntry(0) == (95, 113, 150, 255) and cm.GetColorEntry(1) == (95, 57, 29, 255), \ + 'Wrong colormap entries' cm = None - if ds.GetRasterBand(1).GetNoDataValue() != 255.0: - gdaltest.post_reason('Wrong nodata value.') - return 'fail' - - return 'success' + assert ds.GetRasterBand(1).GetNoDataValue() == 255.0, 'Wrong nodata value.' ############################################################################### # Read test of simple byte reference data with data directory name in all uppercase -def aigrid_4(): +def test_aigrid_4(): tst = gdaltest.GDALTest('AIG', 'ABC3X1UC', 1, 3) return tst.testOpen() @@ -111,47 +94,34 @@ def aigrid_4(): # Verify the colormap, and nodata setting for test file with names of coverage directory and all files in it in all uppercase. Additionally also test for case where clr file resides in parent directory of coverage. -def aigrid_5(): +def test_aigrid_5(): ds = gdal.Open('data/ABC3X1UC') cm = ds.GetRasterBand(1).GetRasterColorTable() - if cm.GetCount() != 256 \ - or cm.GetColorEntry(0) != (95, 113, 150, 255)\ - or cm.GetColorEntry(1) != (95, 57, 29, 255): - gdaltest.post_reason('Wrong colormap entries') - return 'fail' + assert cm.GetCount() == 256 and cm.GetColorEntry(0) == (95, 113, 150, 255) and cm.GetColorEntry(1) == (95, 57, 29, 255), \ + 'Wrong colormap entries' cm = None - if ds.GetRasterBand(1).GetNoDataValue() != 255.0: - gdaltest.post_reason('Wrong nodata value.') - return 'fail' - - return 'success' + assert ds.GetRasterBand(1).GetNoDataValue() == 255.0, 'Wrong nodata value.' ############################################################################### # Verify dataset whose sta.adf is 24 bytes -def aigrid_6(): +def test_aigrid_6(): ds = gdal.Open('data/aigrid_sta_24bytes/teststa') - if ds.GetRasterBand(1).GetMinimum() != 0.0: - gdaltest.post_reason('Wrong minimum') - return 'fail' - - if ds.GetRasterBand(1).GetMaximum() != 2.0: - gdaltest.post_reason('Wrong maximum') - return 'fail' + assert ds.GetRasterBand(1).GetMinimum() == 0.0, 'Wrong minimum' - return 'success' + assert ds.GetRasterBand(1).GetMaximum() == 2.0, 'Wrong maximum' ############################################################################### # Test on real dataset downloaded from http://download.osgeo.org/gdal/data/aig/nzdem -def aigrid_online_1(): +def test_aigrid_online_1(): list_files = ['info/arc.dir', 'info/arc0000.dat', @@ -178,12 +148,10 @@ def aigrid_online_1(): for filename in list_files: if not gdaltest.download_file('http://download.osgeo.org/gdal/data/aig/nzdem/' + filename, 'nzdem/' + filename): - return 'skip' + pytest.skip() tst = gdaltest.GDALTest('AIG', 'tmp/cache/nzdem/nzdem500/hdr.adf', 1, 45334, filename_absolute=1) - ret = tst.testOpen() - if ret != 'success': - return ret + tst.testOpen() ds = gdal.Open('tmp/cache/nzdem/nzdem500/hdr.adf') @@ -191,66 +159,40 @@ def aigrid_online_1(): rat = ds.GetRasterBand(1).GetDefaultRAT() except: print('Skipping RAT checking... OG Python bindings have no RAT API') - return 'success' + return - if rat is None: - gdaltest.post_reason('No RAT found') - return 'fail' + assert rat is not None, 'No RAT found' - if rat.GetRowCount() != 2642: - gdaltest.post_reason('Wrong row count in RAT') - return 'fail' + assert rat.GetRowCount() == 2642, 'Wrong row count in RAT' - if rat.GetColumnCount() != 2: - gdaltest.post_reason('Wrong column count in RAT') - return 'fail' + assert rat.GetColumnCount() == 2, 'Wrong column count in RAT' - if rat.GetNameOfCol(0) != 'VALUE': - gdaltest.post_reason('Wrong name of col 0') - return 'fail' + assert rat.GetNameOfCol(0) == 'VALUE', 'Wrong name of col 0' - if rat.GetTypeOfCol(0) != gdal.GFT_Integer: - gdaltest.post_reason('Wrong type of col 0') - return 'fail' + assert rat.GetTypeOfCol(0) == gdal.GFT_Integer, 'Wrong type of col 0' - if rat.GetUsageOfCol(0) != gdal.GFU_MinMax: - gdaltest.post_reason('Wrong usage of col 0') - return 'fail' + assert rat.GetUsageOfCol(0) == gdal.GFU_MinMax, 'Wrong usage of col 0' - if rat.GetNameOfCol(1) != 'COUNT': - gdaltest.post_reason('Wrong name of col 1') - return 'fail' + assert rat.GetNameOfCol(1) == 'COUNT', 'Wrong name of col 1' - if rat.GetTypeOfCol(1) != gdal.GFT_Integer: - gdaltest.post_reason('Wrong type of col 1') - return 'fail' + assert rat.GetTypeOfCol(1) == gdal.GFT_Integer, 'Wrong type of col 1' - if rat.GetUsageOfCol(1) != gdal.GFU_PixelCount: - gdaltest.post_reason('Wrong usage of col 1') - return 'fail' + assert rat.GetUsageOfCol(1) == gdal.GFU_PixelCount, 'Wrong usage of col 1' - if rat.GetValueAsInt(2641, 0) != 3627: - gdaltest.post_reason('Wrong value in RAT') - return 'fail' + assert rat.GetValueAsInt(2641, 0) == 3627, 'Wrong value in RAT' - if ds.GetRasterBand(1).GetMinimum() != 0.0: - gdaltest.post_reason('Wrong minimum') - return 'fail' + assert ds.GetRasterBand(1).GetMinimum() == 0.0, 'Wrong minimum' - if ds.GetRasterBand(1).GetMaximum() != 3627.0: - gdaltest.post_reason('Wrong maximum') - return 'fail' - - return 'success' + assert ds.GetRasterBand(1).GetMaximum() == 3627.0, 'Wrong maximum' ############################################################################### # Test on real dataset downloaded from http://download.osgeo.org/gdal/data/aig/nzdem -def aigrid_online_2(): +def test_aigrid_online_2(): if not gdaltest.download_file('http://download.osgeo.org/gdal/data/aig/ai_bug_6886.zip', 'ai_bug_6886.zip'): - return 'skip' + pytest.skip() try: os.stat('tmp/cache/ai_bug') @@ -260,9 +202,9 @@ def aigrid_online_2(): try: os.stat('tmp/cache/ai_bug') except OSError: - return 'skip' + pytest.skip() except: - return 'skip' + pytest.skip() tst = gdaltest.GDALTest('AIG', 'tmp/cache/ai_bug/ai_bug/hdr.adf', 1, 16018, filename_absolute=1) return tst.testOpen() @@ -270,20 +212,4 @@ def aigrid_online_2(): ############################################################################### -gdaltest_list = [ - aigrid_1, - aigrid_2, - aigrid_3, - aigrid_4, - aigrid_5, - aigrid_6, - aigrid_online_1, - aigrid_online_2] - -if __name__ == '__main__': - - gdaltest.setup_run('aigrid') - - gdaltest.run_tests(gdaltest_list) - sys.exit(gdaltest.summarize()) diff --git a/autotest/gdrivers/arg.py b/autotest/gdrivers/arg.py index b12a11023deb..16ae26c85a9d 100755 --- a/autotest/gdrivers/arg.py +++ b/autotest/gdrivers/arg.py @@ -29,14 +29,13 @@ ############################################################################### import os -import sys import struct from copy import copy from osgeo import gdal -sys.path.append('../pymod') import gdaltest +import pytest # given fmt and nodata, encodes a value as bytes @@ -57,10 +56,10 @@ def encode(fmt, nodata, values): # -def arg_init(): +def test_arg_init(): gdaltest.argDriver = gdal.GetDriverByName('ARG') if gdaltest.argDriver is None: - return 'skip' + pytest.skip() gdaltest.argJsontpl = """{ "layer": "%(fmt)s", @@ -120,14 +119,13 @@ def arg_init(): gdaltest.argDriver = None if gdaltest.argDriver is None: - return 'skip' + pytest.skip() - return 'success' + - -def arg_unsupported(): +def test_arg_unsupported(): if gdaltest.argDriver is None: - return 'skip' + pytest.skip() # int8 is unsupported for d in gdaltest.argTests: @@ -135,19 +133,16 @@ def arg_unsupported(): if name == 'int64' or name == 'uint64': with gdaltest.error_handler('CPLQuietErrorHandler'): ds = gdal.Open('data/arg-' + name + '.arg') - if ds is not None: - return 'fail' + assert ds is None else: ds = gdal.Open('data/arg-' + name + '.arg') - if ds is None: - return 'fail' - - return 'success' + assert ds is not None + -def arg_getrastercount(): +def test_arg_getrastercount(): if gdaltest.argDriver is None: - return 'skip' + pytest.skip() for d in gdaltest.argTests: for (name, _, _) in d['formats']: @@ -156,15 +151,13 @@ def arg_getrastercount(): if ds is None: continue - if ds.RasterCount != 1: - return 'fail' - - return 'success' + assert ds.RasterCount == 1 + -def arg_getgeotransform(): +def test_arg_getgeotransform(): if gdaltest.argDriver is None: - return 'skip' + pytest.skip() for d in gdaltest.argTests: for (name, _, _) in d['formats']: @@ -175,24 +168,21 @@ def arg_getgeotransform(): gt = ds.GetGeoTransform() - if gt[0] != 0 or \ - gt[1] != 1 or \ - gt[2] != 0 or \ - gt[3] != 2 or \ - gt[4] != 0 or \ - gt[5] != -1: - return 'fail' + assert (gt[0] == 0 and \ + gt[1] == 1 and \ + gt[2] == 0 and \ + gt[3] == 2 and \ + gt[4] == 0 and \ + gt[5] == -1) - return 'success' + - -def arg_blocksize(): +def test_arg_blocksize(): if gdaltest.argDriver is None: - return 'skip' + pytest.skip() tifDriver = gdal.GetDriverByName('GTiff') - if tifDriver is None: - return 'fail' + assert tifDriver is not None ds = gdal.Open('data/utm.tif') xsize = ds.RasterXSize @@ -213,20 +203,17 @@ def arg_blocksize(): os.remove('data/utm-uneven-blocks.tif') gdal.GetDriverByName('ARG').Delete('data/utm.arg') - if stat.st_size != (xsize * ysize): - return 'fail' - - return 'success' + assert stat.st_size == (xsize * ysize) -def arg_layername(): +def test_arg_layername(): """ The layer name of the ARG in the .json file need not be the name of the .arg file. The original driver enforced this constraint, but that behavior was wrong. See ticket #4609 """ if gdaltest.argDriver is None: - return 'skip' + pytest.skip() ds = gdal.Open('data/arg-int16.arg') @@ -236,8 +223,7 @@ def arg_layername(): ds.SetMetadataItem('LAYER', lyr) # did the layer name stick? - if ds.GetMetadata()['LAYER'] != lyr: - return 'fail' + assert ds.GetMetadata()['LAYER'] == lyr # copy the dataset to a new ARG ds2 = gdaltest.argDriver.CreateCopy('data/arg-int16-2.arg', ds, False) @@ -254,31 +240,25 @@ def arg_layername(): gdal.GetDriverByName('ARG').Delete('data/arg-int16-2.arg') # does the new dataset's layer match the layer set before copying - if lyr2 != lyr: - return 'fail' + assert lyr2 == lyr os.unlink('data/arg-int16.arg.aux.xml') - return 'success' - -def arg_nodata(): +def test_arg_nodata(): """ Check that the NoData value for int8 images is 128, as per the ARG spec. See ticket #4610 """ if gdaltest.argDriver is None: - return 'skip' + pytest.skip() ds = gdal.Open('data/arg-int8.arg') - if ds.GetRasterBand(1).GetNoDataValue() != 128: - return 'fail' + assert ds.GetRasterBand(1).GetNoDataValue() == 128 - return 'success' - -def arg_byteorder(): +def test_arg_byteorder(): """ Check that a roundtrip from ARG -> GTiff -> ARG has the same binary values. See ticket #4779 @@ -287,11 +267,10 @@ def arg_byteorder(): when the binary data is the same. Compare them byte-by-byte. """ if gdaltest.argDriver is None: - return 'skip' + pytest.skip() tifDriver = gdal.GetDriverByName('GTiff') - if tifDriver is None: - return 'fail' + assert tifDriver is not None for d in gdaltest.argTests: for (name, _, _) in d['formats']: @@ -303,12 +282,10 @@ def arg_byteorder(): continue dest = tifDriver.CreateCopy(basename + '.tif', orig, False) - if dest is None: - return 'fail' + assert dest is not None mirror = gdaltest.argDriver.CreateCopy(basename + '2.arg', dest, False) - if mirror is None: - return 'fail' + assert mirror is not None orig = None dest = None @@ -326,39 +303,19 @@ def arg_byteorder(): gdal.GetDriverByName('GTiff').Delete(basename + '.tif') gdal.GetDriverByName('ARG').Delete(basename + '2.arg') - if data1 != data2: - return 'fail' - - return 'success' + assert data1 == data2 + -def arg_destroy(): +def test_arg_destroy(): if gdaltest.argDriver is None: - return 'skip' + pytest.skip() for d in gdaltest.argTests: for (name, _, _) in d['formats']: os.remove('data/arg-' + name + '.arg') os.remove('data/arg-' + name + '.json') - return 'success' - - -gdaltest_list = [ - arg_init, - arg_unsupported, - arg_getrastercount, - arg_getgeotransform, - arg_blocksize, - arg_layername, - arg_nodata, - arg_byteorder, - arg_destroy] - -if __name__ == '__main__': - - gdaltest.setup_run('ARG') + - gdaltest.run_tests(gdaltest_list) - sys.exit(gdaltest.summarize()) diff --git a/autotest/gdrivers/bag.py b/autotest/gdrivers/bag.py index 8bf4a746a007..0b03b38ebf69 100755 --- a/autotest/gdrivers/bag.py +++ b/autotest/gdrivers/bag.py @@ -30,142 +30,107 @@ # DEALINGS IN THE SOFTWARE. ############################################################################### -import sys -from osgeo import gdal -sys.path.append('../pymod') +import pytest + +from osgeo import gdal import gdaltest -############################################################################### -# Test if BAG driver is present +pytestmark = pytest.mark.require_driver('BAG') -def bag_1(): - gdaltest.bag_drv = gdal.GetDriverByName('BAG') - if gdaltest.bag_drv is None: - return 'skip' +@pytest.fixture(autouse=True, scope='module') +def check_no_file_leaks(): + num_files = len(gdaltest.get_opened_files()) + + yield - gdaltest.count_opened_files = len(gdaltest.get_opened_files()) + diff = len(gdaltest.get_opened_files()) - num_files + assert diff == 0, 'Leak of file handles: %d leaked' % diff - return 'success' ############################################################################### # Confirm various info on true_n_nominal 1.1 sample file. -def bag_2(): +def test_bag_2(): if gdaltest.bag_drv is None: - return 'skip' + pytest.skip() ds = gdal.Open('data/true_n_nominal.bag') cs = ds.GetRasterBand(1).Checksum() - if cs != 1072: - gdaltest.post_reason('Wrong checksum on band 1, got %d.' % cs) - return 'fail' + assert cs == 1072, ('Wrong checksum on band 1, got %d.' % cs) cs = ds.GetRasterBand(2).Checksum() - if cs != 150: - gdaltest.post_reason('Wrong checksum on band 2, got %d.' % cs) - return 'fail' + assert cs == 150, ('Wrong checksum on band 2, got %d.' % cs) cs = ds.GetRasterBand(3).Checksum() - if cs != 1315: - gdaltest.post_reason('Wrong checksum on band 3, got %d.' % cs) - return 'fail' + assert cs == 1315, ('Wrong checksum on band 3, got %d.' % cs) b1 = ds.GetRasterBand(1) - if abs(b1.GetMinimum() - 10) > 0.01: - gdaltest.post_reason('band 1 minimum wrong.') - return 'fail' + assert abs(b1.GetMinimum() - 10) <= 0.01, 'band 1 minimum wrong.' - if abs(b1.GetMaximum() - 19.8) > 0.01: - gdaltest.post_reason('band 1 maximum wrong.') - return 'fail' + assert abs(b1.GetMaximum() - 19.8) <= 0.01, 'band 1 maximum wrong.' - if abs(b1.GetNoDataValue() - 1000000.0) > 0.1: - gdaltest.post_reason('band 1 nodata wrong.') - return 'fail' + assert abs(b1.GetNoDataValue() - 1000000.0) <= 0.1, 'band 1 nodata wrong.' b2 = ds.GetRasterBand(2) - if abs(b2.GetNoDataValue() - 1000000.0) > 0.1: - gdaltest.post_reason('band 2 nodata wrong.') - return 'fail' + assert abs(b2.GetNoDataValue() - 1000000.0) <= 0.1, 'band 2 nodata wrong.' b3 = ds.GetRasterBand(3) - if abs(b3.GetNoDataValue() - 0.0) > 0.1: - gdaltest.post_reason('band 3 nodata wrong.') - return 'fail' + assert abs(b3.GetNoDataValue() - 0.0) <= 0.1, 'band 3 nodata wrong.' # It would be nice to test srs and geotransform but they are # pretty much worthless on this dataset. # Test the xml:BAG metadata domain xmlBag = ds.GetMetadata('xml:BAG')[0] - if xmlBag.find('<?xml') != 0: - gdaltest.post_reason('did not get xml:BAG metadata') - print(xmlBag) - return 'fail' + assert xmlBag.find('<?xml') == 0, 'did not get xml:BAG metadata' ds = None - if gdaltest.is_file_open('data/true_n_nominal.bag'): - gdaltest.post_reason('file still opened.') - return 'fail' - - return 'success' + assert not gdaltest.is_file_open('data/true_n_nominal.bag'), 'file still opened.' ############################################################################### # Test a southern hemisphere falseNorthing sample file. -def bag_3(): +def test_bag_3(): if gdaltest.bag_drv is None: - return 'skip' + pytest.skip() ds = gdal.Open('data/southern_hemi_false_northing.bag') nr = ds.RasterCount - if nr != 2: - gdaltest.post_reason('Expected 2 bands, got %d.' % nr) - return 'fail' + assert nr == 2, ('Expected 2 bands, got %d.' % nr) cs = ds.GetRasterBand(1).Checksum() - if cs != 21402: - gdaltest.post_reason('Wrong checksum on band 1, got %d.' % cs) - return 'fail' + assert cs == 21402, ('Wrong checksum on band 1, got %d.' % cs) cs = ds.GetRasterBand(2).Checksum() - if cs != 33216: - gdaltest.post_reason('Wrong checksum on band 2, got %d.' % cs) - return 'fail' + assert cs == 33216, ('Wrong checksum on band 2, got %d.' % cs) pj = ds.GetProjection() - if 'Southern Hemisphere' not in pj: - gdaltest.post_reason('Southern Hemisphere not in projection') - return 'fail' - if 'PARAMETER["false_northing",10000000]' not in pj: - gdaltest.post_reason('Did not find false_northing of 10000000') - return 'fail' - - return 'success' + assert 'Southern Hemisphere' in pj, 'Southern Hemisphere not in projection' + assert 'PARAMETER["false_northing",10000000]' in pj, \ + 'Did not find false_northing of 10000000' ############################################################################### # -def bag_vr_normal(): +def test_bag_vr_normal(): if gdaltest.bag_drv is None: - return 'skip' + pytest.skip() ds = gdal.Open('data/test_vr.bag') - if ds is None: - return 'fail' + assert ds is not None got_md = gdal.Info(ds, computeChecksum=True, format='json') expected_md = { @@ -205,51 +170,34 @@ def bag_vr_normal(): for key in expected_md: if key not in got_md or got_md[key] != expected_md[key]: - gdaltest.post_reason('fail') - print(key) import pprint pp = pprint.PrettyPrinter() pp.pprint(got_md) - return 'fail' + pytest.fail(key) with gdaltest.error_handler(): ds = gdal.OpenEx('data/test_vr.bag', open_options=['MODE=LOW_RES_GRID', 'MINX=0']) - if gdal.GetLastErrorMsg() == '': - gdaltest.post_reason('warning expected') - return 'fail' + assert gdal.GetLastErrorMsg() != '', 'warning expected' got_md2 = gdal.Info(ds, computeChecksum=True, format='json') - if got_md2 != got_md: - gdaltest.post_reason('fail') - return 'fail' - - return 'success' + assert got_md2 == got_md ############################################################################### # -def bag_vr_list_supergrids(): +def test_bag_vr_list_supergrids(): if gdaltest.bag_drv is None: - return 'skip' + pytest.skip() ds = gdal.OpenEx('data/test_vr.bag', open_options=['MODE=LIST_SUPERGRIDS']) - if ds is None: - gdaltest.post_reason('fail') - return 'fail' + assert ds is not None sub_ds = ds.GetSubDatasets() - if len(sub_ds) != 24: - gdaltest.post_reason('fail') - print(len(sub_ds)) - print(sub_ds) - return 'fail' + assert len(sub_ds) == 24 - if sub_ds[0][0] != 'BAG:"data/test_vr.bag":supergrid:0:0': - gdaltest.post_reason('fail') - print(sub_ds) - return 'fail' + assert sub_ds[0][0] == 'BAG:"data/test_vr.bag":supergrid:0:0' with gdaltest.error_handler(): # Bounding box filter ignored since only part of MINX, MINY, MAXX and @@ -257,60 +205,32 @@ def bag_vr_list_supergrids(): ds = gdal.OpenEx('data/test_vr.bag', open_options=['MODE=LIST_SUPERGRIDS', 'MINX=200']) sub_ds = ds.GetSubDatasets() - if len(sub_ds) != 24: - gdaltest.post_reason('fail') - print(len(sub_ds)) - print(sub_ds) - return 'fail' + assert len(sub_ds) == 24 ds = gdal.OpenEx('data/test_vr.bag', open_options=[ 'MODE=LIST_SUPERGRIDS', 'MINX=100', 'MAXX=220', 'MINY=500000', 'MAXY=500100']) sub_ds = ds.GetSubDatasets() - if len(sub_ds) != 6: - gdaltest.post_reason('fail') - print(len(sub_ds)) - print(sub_ds) - return 'fail' - if sub_ds[0][0] != 'BAG:"data/test_vr.bag":supergrid:1:1': - gdaltest.post_reason('fail') - print(sub_ds) - return 'fail' + assert len(sub_ds) == 6 + assert sub_ds[0][0] == 'BAG:"data/test_vr.bag":supergrid:1:1' ds = gdal.OpenEx('data/test_vr.bag', open_options=[ 'MODE=LIST_SUPERGRIDS', 'RES_FILTER_MIN=5', 'RES_FILTER_MAX=10']) sub_ds = ds.GetSubDatasets() - if len(sub_ds) != 12: - gdaltest.post_reason('fail') - print(len(sub_ds)) - print(sub_ds) - return 'fail' - if sub_ds[0][0] != 'BAG:"data/test_vr.bag":supergrid:0:3': - gdaltest.post_reason('fail') - print(sub_ds) - return 'fail' + assert len(sub_ds) == 12 + assert sub_ds[0][0] == 'BAG:"data/test_vr.bag":supergrid:0:3' ds = gdal.OpenEx('data/test_vr.bag', open_options=[ 'SUPERGRIDS_INDICES=(2,1),(3,4)']) sub_ds = ds.GetSubDatasets() - if len(sub_ds) != 2: - gdaltest.post_reason('fail') - print(len(sub_ds)) - print(sub_ds) - return 'fail' - if sub_ds[0][0] != 'BAG:"data/test_vr.bag":supergrid:2:1' or \ - sub_ds[1][0] != 'BAG:"data/test_vr.bag":supergrid:3:4': - gdaltest.post_reason('fail') - print(sub_ds) - return 'fail' + assert len(sub_ds) == 2 + assert (sub_ds[0][0] == 'BAG:"data/test_vr.bag":supergrid:2:1' and \ + sub_ds[1][0] == 'BAG:"data/test_vr.bag":supergrid:3:4') # One single tuple: open the subdataset directly ds = gdal.OpenEx('data/test_vr.bag', open_options=[ 'SUPERGRIDS_INDICES=(2,1)']) ds2 = gdal.Open('BAG:"data/test_vr.bag":supergrid:2:1') - if gdal.Info(ds) != gdal.Info(ds2): - gdaltest.post_reason('fail') - print(sub_ds) - return 'fail' + assert gdal.Info(ds) == gdal.Info(ds2), sub_ds # Test invalid values for SUPERGRIDS_INDICES for invalid_val in ['', 'x', '(', '(1', '(1,', '(1,)', '(1,2),', @@ -318,26 +238,20 @@ def bag_vr_list_supergrids(): with gdaltest.error_handler(): ds = gdal.OpenEx('data/test_vr.bag', open_options=[ 'SUPERGRIDS_INDICES=' + invalid_val]) - if gdal.GetLastErrorMsg() == '': - gdaltest.post_reason('fail') - print(invalid_val) - return 'fail' - - return 'success' + assert gdal.GetLastErrorMsg() != '', invalid_val + ############################################################################### # -def bag_vr_open_supergrids(): +def test_bag_vr_open_supergrids(): if gdaltest.bag_drv is None: - return 'skip' + pytest.skip() ds = gdal.Open('BAG:"data/test_vr.bag":supergrid:0:0') - if ds is None: - gdaltest.post_reason('fail') - return 'fail' + assert ds is not None got_md = gdal.Info(ds, computeChecksum=True, format='json') expected_md = { @@ -374,53 +288,39 @@ def bag_vr_open_supergrids(): for key in expected_md: if key not in got_md or got_md[key] != expected_md[key]: - gdaltest.post_reason('fail') - print(key) import pprint pp = pprint.PrettyPrinter() pp.pprint(got_md) - return 'fail' + pytest.fail(key) with gdaltest.error_handler(): ds = gdal.Open('BAG:"/vsimem/unexisting.bag":supergrid:0:0') - if ds is not None: - gdaltest.post_reason('fail') - return 'fail' + assert ds is None with gdaltest.error_handler(): ds = gdal.Open('BAG:"data/test_vr.bag":supergrid:4:0') - if ds is not None: - gdaltest.post_reason('fail') - return 'fail' + assert ds is None with gdaltest.error_handler(): ds = gdal.Open('BAG:"data/test_vr.bag":supergrid:0:6') - if ds is not None: - gdaltest.post_reason('fail') - return 'fail' + assert ds is None with gdaltest.error_handler(): ds = gdal.OpenEx('BAG:"data/test_vr.bag":supergrid:0:0', open_options=['MINX=0']) - if gdal.GetLastErrorMsg() == '': - gdaltest.post_reason('warning expected') - return 'fail' - - return 'success' + assert gdal.GetLastErrorMsg() != '', 'warning expected' ############################################################################### # -def bag_vr_resampled(): +def test_bag_vr_resampled(): if gdaltest.bag_drv is None: - return 'skip' + pytest.skip() ds = gdal.OpenEx('data/test_vr.bag', open_options=['MODE=RESAMPLED_GRID']) - if ds is None: - gdaltest.post_reason('fail') - return 'fail' + assert ds is not None got_md = gdal.Info(ds, computeChecksum=True, format='json') expected_md = { @@ -461,12 +361,10 @@ def bag_vr_resampled(): for key in expected_md: if key not in got_md or got_md[key] != expected_md[key]: - gdaltest.post_reason('fail') - print(key) import pprint pp = pprint.PrettyPrinter() pp.pprint(got_md) - return 'fail' + pytest.fail(key) data_ref = ds.ReadRaster() @@ -475,118 +373,74 @@ def bag_vr_resampled(): with gdaltest.config_option('GDAL_BAG_BLOCK_SIZE', str(block_size)): ds = gdal.OpenEx('data/test_vr.bag', open_options=['MODE=RESAMPLED_GRID']) - if ds.GetRasterBand(1).GetBlockSize() != [block_size, block_size]: - gdaltest.post_reason('fail') - print(block_size) - print(ds.GetRasterBand(1).GetBlockSize()) - return 'fail' + assert ds.GetRasterBand(1).GetBlockSize() == [block_size, block_size] data = ds.ReadRaster() - if data != data_ref: - gdaltest.post_reason('fail') - print(block_size) - return 'fail' + assert data == data_ref, block_size # Test overviews with gdaltest.config_option('GDAL_BAG_MIN_OVR_SIZE', '4'): ds = gdal.OpenEx('data/test_vr.bag', open_options=['MODE=RESAMPLED_GRID']) - if ds.GetRasterBand(1).GetOverviewCount() != 2: - gdaltest.post_reason('fail') - print(ds.GetRasterBand(1).GetOverviewCount()) - return 'fail' - if ds.GetRasterBand(1).GetOverview(-1) is not None: - gdaltest.post_reason('fail') - return 'fail' - if ds.GetRasterBand(1).GetOverview(2) is not None: - gdaltest.post_reason('fail') - return 'fail' + assert ds.GetRasterBand(1).GetOverviewCount() == 2 + assert ds.GetRasterBand(1).GetOverview(-1) is None + assert ds.GetRasterBand(1).GetOverview(2) is None ovr = ds.GetRasterBand(1).GetOverview(0) cs = ovr.Checksum() - if cs != 681: - gdaltest.post_reason('fail') - print(cs) - return 'fail' + assert cs == 681 ovr = ds.GetRasterBand(2).GetOverview(0) cs = ovr.Checksum() - if cs != 1344: - gdaltest.post_reason('fail') - print(cs) - return 'fail' + assert cs == 1344 ds.GetRasterBand(1).GetOverview(0).FlushCache() ds.GetRasterBand(1).GetOverview(1).FlushCache() cs = ovr.Checksum() - if cs != 1344: - gdaltest.post_reason('fail') - print(cs) - return 'fail' + assert cs == 1344 ovr = ds.GetRasterBand(1).GetOverview(0) cs = ovr.Checksum() - if cs != 681: - gdaltest.post_reason('fail') - print(cs) - return 'fail' + assert cs == 681 ds = gdal.OpenEx('data/test_vr.bag', open_options=['MODE=RESAMPLED_GRID', 'MINX=90', 'MAXX=120', 'MAXY=500112']) gt = ds.GetGeoTransform() got = (gt[0], gt[3], ds.RasterXSize) - if got != (90.0, 500112.0, 6): - gdaltest.post_reason('fail') - print(got) - return 'fail' + assert got == (90.0, 500112.0, 6) ds = gdal.OpenEx('data/test_vr.bag', open_options=['MODE=RESAMPLED_GRID', 'MINY=500000']) gt = ds.GetGeoTransform() got = (gt[3] + gt[5] * ds.RasterYSize, ds.RasterYSize) - if got != (500000.0, 21): - gdaltest.post_reason('fail') - print(got) - return 'fail' + assert got == (500000.0, 21) ds = gdal.OpenEx('data/test_vr.bag', open_options=['MODE=RESAMPLED_GRID', 'RESX=5', 'RESY=6']) gt = ds.GetGeoTransform() got = (gt[1], gt[5]) - if got != (5.0, -6.0): - gdaltest.post_reason('fail') - print(got) - return 'fail' + assert got == (5.0, -6.0) ds = gdal.OpenEx('data/test_vr.bag', open_options=['MODE=RESAMPLED_GRID', 'RES_STRATEGY=MIN']) gt = ds.GetGeoTransform() got = (gt[1], gt[5]) - if got != (4.983333110809326, -5.316666603088379): - gdaltest.post_reason('fail') - print(got) - return 'fail' + assert got == (4.983333110809326, -5.316666603088379) ds = gdal.OpenEx('data/test_vr.bag', open_options=['MODE=RESAMPLED_GRID', 'RES_STRATEGY=MAX']) gt = ds.GetGeoTransform() got = (gt[1], gt[5]) - if got != (29.899999618530273, -31.899999618530273): - gdaltest.post_reason('fail') - print(got) - return 'fail' + assert got == (29.899999618530273, -31.899999618530273) ds = gdal.OpenEx('data/test_vr.bag', open_options=['MODE=RESAMPLED_GRID', 'RES_STRATEGY=MEAN']) gt = ds.GetGeoTransform() got = (gt[1], gt[5]) - if got != (12.209166447321573, -13.025833209355673): - gdaltest.post_reason('fail') - print(got) - return 'fail' + assert got == (12.209166447321573, -13.025833209355673) ds = gdal.OpenEx('data/test_vr.bag', open_options=['MODE=RESAMPLED_GRID', @@ -594,30 +448,18 @@ def bag_vr_resampled(): 'RES_FILTER_MAX=8']) gt = ds.GetGeoTransform() got = (gt[1], gt[5]) - if got != (8.0, -8.0): - gdaltest.post_reason('fail') - print(got) - return 'fail' + assert got == (8.0, -8.0) got = (ds.GetRasterBand(1).Checksum(), ds.GetRasterBand(2).Checksum()) - if got != (2099, 2747): - gdaltest.post_reason('fail') - print(got) - return 'fail' + assert got == (2099, 2747) ds = gdal.OpenEx('data/test_vr.bag', open_options=['MODE=RESAMPLED_GRID', 'RES_FILTER_MAX=8']) gt = ds.GetGeoTransform() got = (gt[1], gt[5]) - if got != (8.0, -8.0): - gdaltest.post_reason('fail') - print(got) - return 'fail' + assert got == (8.0, -8.0) got = (ds.GetRasterBand(1).Checksum(), ds.GetRasterBand(2).Checksum()) - if got != (2099, 2747): - gdaltest.post_reason('fail') - print(got) - return 'fail' + assert got == (2099, 2747) ds = gdal.OpenEx('data/test_vr.bag', open_options=['MODE=RESAMPLED_GRID', @@ -625,15 +467,9 @@ def bag_vr_resampled(): 'RES_FILTER_MAX=16']) gt = ds.GetGeoTransform() got = (gt[1], gt[5]) - if got != (16.0, -16.0): - gdaltest.post_reason('fail') - print(got) - return 'fail' + assert got == (16.0, -16.0) got = (ds.GetRasterBand(1).Checksum(), ds.GetRasterBand(2).Checksum()) - if got != (796, 864): - gdaltest.post_reason('fail') - print(got) - return 'fail' + assert got == (796, 864) ds = gdal.OpenEx('data/test_vr.bag', open_options=['MODE=RESAMPLED_GRID', @@ -641,48 +477,32 @@ def bag_vr_resampled(): 'RES_FILTER_MAX=32']) gt = ds.GetGeoTransform() got = (gt[1], gt[5]) - if got != (32.0, -32.0): - gdaltest.post_reason('fail') - print(got) - return 'fail' + assert got == (32.0, -32.0) got = (ds.GetRasterBand(1).Checksum(), ds.GetRasterBand(2).Checksum()) - if got != (207, 207): - gdaltest.post_reason('fail') - print(got) - return 'fail' + assert got == (207, 207) ds = gdal.OpenEx('data/test_vr.bag', open_options=['MODE=RESAMPLED_GRID', 'RES_FILTER_MIN=16']) gt = ds.GetGeoTransform() got = (gt[1], gt[5]) - if got != (29.899999618530273, -31.899999618530273): - gdaltest.post_reason('fail') - print(got) - return 'fail' + assert got == (29.899999618530273, -31.899999618530273) got = (ds.GetRasterBand(1).Checksum(), ds.GetRasterBand(2).Checksum()) - if got != (165, 205): - gdaltest.post_reason('fail') - print(got) - return 'fail' + assert got == (165, 205) # Too big RES_FILTER_MIN with gdaltest.error_handler(): ds = gdal.OpenEx('data/test_vr.bag', open_options=['MODE=RESAMPLED_GRID', 'RES_FILTER_MIN=32']) - if ds is not None: - gdaltest.post_reason('fail') - return 'fail' + assert ds is None # Too small RES_FILTER_MAX with gdaltest.error_handler(): ds = gdal.OpenEx('data/test_vr.bag', open_options=['MODE=RESAMPLED_GRID', 'RES_FILTER_MAX=4']) - if ds is not None: - gdaltest.post_reason('fail') - return 'fail' + assert ds is None # RES_FILTER_MIN >= RES_FILTER_MAX with gdaltest.error_handler(): @@ -690,9 +510,7 @@ def bag_vr_resampled(): open_options=['MODE=RESAMPLED_GRID', 'RES_FILTER_MIN=4', 'RES_FILTER_MAX=4']) - if ds is not None: - gdaltest.post_reason('fail') - return 'fail' + assert ds is None # Test VALUE_POPULATION ds = gdal.OpenEx('data/test_vr.bag', @@ -719,86 +537,60 @@ def bag_vr_resampled(): m2_min, M2_min, mean2_min, _ = ds.GetRasterBand(2).ComputeStatistics(False) if mean1_min >= mean1_mean or mean1_mean >= mean1_max: - gdaltest.post_reason('fail') print(m1_max, M1_max, mean1_max) print(m2_max, M2_max, mean2_max) print(m1_mean, M1_mean, mean1_mean) print(m2_mean, M2_mean, mean2_mean) print(m1_min, M1_min, mean1_min) - print(m2_min, M2_min, mean2_min) - return 'fail' + pytest.fail(m2_min, M2_min, mean2_min) if m2_min >= m2_max or \ (m2_mean, M2_mean, mean2_mean) != (m2_max, M2_max, mean2_max): - gdaltest.post_reason('fail') print(m1_max, M1_max, mean1_max) - print(m2_max, M2_max, mean2_max) print(m1_mean, M1_mean, mean1_mean) - print(m2_mean, M2_mean, mean2_mean) print(m1_min, M1_min, mean1_min) - print(m2_min, M2_min, mean2_min) - return 'fail' - - return 'success' + pytest.fail(m2_min, M2_min, mean2_min) + ############################################################################### # -def bag_vr_resampled_mask(): +def test_bag_vr_resampled_mask(): if gdaltest.bag_drv is None: - return 'skip' + pytest.skip() ds = gdal.OpenEx('data/test_vr.bag', open_options=['MODE=RESAMPLED_GRID', 'SUPERGRIDS_MASK=YES']) - if ds is None: - gdaltest.post_reason('fail') - return 'fail' - if ds.RasterCount != 1: - gdaltest.post_reason('fail') - return 'fail' - if ds.GetRasterBand(1).DataType != gdal.GDT_Byte: - gdaltest.post_reason('fail') - return 'fail' - if ds.GetRasterBand(1).GetNoDataValue() is not None: - gdaltest.post_reason('fail') - return 'fail' + assert ds is not None + assert ds.RasterCount == 1 + assert ds.GetRasterBand(1).DataType == gdal.GDT_Byte + assert ds.GetRasterBand(1).GetNoDataValue() is None cs = ds.GetRasterBand(1).Checksum() - if cs != 4507: - gdaltest.post_reason('fail') - print(cs) - return 'fail' - - return 'success' + assert cs == 4507 ############################################################################### # -def bag_vr_resampled_interpolated(): +def test_bag_vr_resampled_interpolated(): if gdaltest.bag_drv is None: - return 'skip' + pytest.skip() ds = gdal.OpenEx('data/test_vr.bag', open_options=['MODE=RESAMPLED_GRID', 'INTERPOLATION=INVDIST']) cs = ds.GetRasterBand(1).Checksum() - if cs != 2175: - gdaltest.post_reason('fail') - print(cs) - return 'fail' + assert cs == 2175 # Test overviews with gdaltest.config_option('GDAL_BAG_MIN_OVR_SIZE', '4'): ds = gdal.OpenEx('data/test_vr.bag', open_options=['MODE=RESAMPLED_GRID']) - if ds.GetRasterBand(1).GetOverviewCount() != 2: - gdaltest.post_reason('fail') - print(ds.GetRasterBand(1).GetOverviewCount()) - return 'fail' + assert ds.GetRasterBand(1).GetOverviewCount() == 2 # Incompatible options with gdaltest.error_handler(): @@ -806,20 +598,16 @@ def bag_vr_resampled_interpolated(): open_options=['MODE=RESAMPLED_GRID', 'SUPERGRIDS_MASK=YES', 'INTERPOLATION=INVDIST']) - if ds is not None: - gdaltest.post_reason('fail') - return 'fail' - - return 'success' + assert ds is None ############################################################################### # -def bag_write_single_band(): +def test_bag_write_single_band(): if gdaltest.bag_drv is None: - return 'skip' + pytest.skip() tst = gdaltest.GDALTest('BAG', 'byte.tif', 1, 4672) ret = tst.testCreateCopy(quiet_error_handler=False, @@ -830,44 +618,34 @@ def bag_write_single_band(): # -def bag_write_two_bands(): +def test_bag_write_two_bands(): if gdaltest.bag_drv is None: - return 'skip' + pytest.skip() tst = gdaltest.GDALTest('BAG', 'test_vr.bag', 2, 60, options=['BLOCK_SIZE=2', 'VAR_ABSTRACT=foo', 'VAR_XML_IDENTIFICATION_CITATION=<bar/>']) - ret = tst.testCreateCopy(quiet_error_handler=False, + tst.testCreateCopy(quiet_error_handler=False, delete_copy=False, new_filename='/vsimem/out.bag') - if ret != 'success': - return ret ds = gdal.Open('/vsimem/out.bag') xml = ds.GetMetadata_List('xml:BAG')[0] - if xml.find('<bar />') < 0: - gdaltest.post_reason('fail') - print(xml) - return 'fail' - if xml.find('Generated by GDAL ') < 0: - gdaltest.post_reason('fail') - print(xml) - return 'fail' + assert xml.find('<bar />') >= 0 + assert xml.find('Generated by GDAL ') >= 0 gdal.Unlink('/vsimem/out.bag') - return 'success' - ############################################################################### # -def bag_write_south_up(): +def test_bag_write_south_up(): if gdaltest.bag_drv is None: - return 'skip' + pytest.skip() # Generate a south-up dataset src_ds = gdal.Warp('', 'data/byte.tif', @@ -879,55 +657,14 @@ def bag_write_south_up(): # Check that it is presented as north-up cs = ds.GetRasterBand(1).Checksum() - if cs != 4672: - gdaltest.post_reason('fail') - print(cs) - return 'fail' + assert cs == 4672 gt = ds.GetGeoTransform() - if gt != (440720.0, 60.0, 0.0, 3751320.0, 0.0, -60.0): - gdaltest.post_reason('fail') - print(gt) - return 'fail' + assert gt == (440720.0, 60.0, 0.0, 3751320.0, 0.0, -60.0) ds = None gdal.Unlink('/vsimem/out.bag') - return 'success' - - -def bag_postcheck(): - - if gdaltest.bag_drv is None: - return 'skip' - - diff = len(gdaltest.get_opened_files()) - gdaltest.count_opened_files - if diff != 0: - gdaltest.post_reason('Leak of file handles: %d leaked' % diff) - return 'fail' - - return 'success' - -gdaltest_list = [bag_1, - bag_2, - bag_3, - bag_vr_normal, - bag_vr_list_supergrids, - bag_vr_open_supergrids, - bag_vr_resampled, - bag_vr_resampled_mask, - bag_vr_resampled_interpolated, - bag_write_single_band, - bag_write_two_bands, - bag_write_south_up, - bag_postcheck, - ] - -if __name__ == '__main__': - - gdaltest.setup_run('hdf5') - gdaltest.run_tests(gdaltest_list) - sys.exit(gdaltest.summarize()) diff --git a/autotest/gdrivers/blx.py b/autotest/gdrivers/blx.py index 83093afb106d..0dfff762bc68 100755 --- a/autotest/gdrivers/blx.py +++ b/autotest/gdrivers/blx.py @@ -28,10 +28,8 @@ # DEALINGS IN THE SOFTWARE. ############################################################################### -import sys from osgeo import gdal -sys.path.append('../pymod') import gdaltest @@ -39,7 +37,7 @@ ############################################################################### # Test reading a little-endian BLX -def blx_1(): +def test_blx_1(): prj = 'WGS84' gt = [20.0004166, 0.0008333, 0.0, 50.0004166, 0.0, -0.0008333] @@ -50,7 +48,7 @@ def blx_1(): ############################################################################### # Test reading a big-endian BLX -def blx_2(): +def test_blx_2(): prj = 'WGS84' gt = [20.0004166, 0.0008333, 0.0, 50.0004166, 0.0, -0.0008333] @@ -61,7 +59,7 @@ def blx_2(): ############################################################################### # Test writing a little-endian BLX -def blx_3(): +def test_blx_3(): tst = gdaltest.GDALTest('BLX', 's4103.xlb', 1, 47024) return tst.testCreateCopy(check_gt=1, check_srs=1) @@ -70,7 +68,7 @@ def blx_3(): ############################################################################### # Test writing a big-endian BLX -def blx_4(): +def test_blx_4(): tst = gdaltest.GDALTest('BLX', 's4103.blx', 1, 47024, options=['BIGENDIAN=YES']) return tst.testCreateCopy(check_gt=1, check_srs=1) @@ -79,51 +77,25 @@ def blx_4(): ############################################################################### # Test overviews -def blx_5(): +def test_blx_5(): ds = gdal.Open('data/s4103.blx') band = ds.GetRasterBand(1) - if band.GetOverviewCount() != 4: - gdaltest.post_reason('did not get expected overview count') - return 'fail' + assert band.GetOverviewCount() == 4, 'did not get expected overview count' cs = band.GetOverview(0).Checksum() - if cs != 42981: - gdaltest.post_reason('wrong overview checksum (%d)' % cs) - return 'fail' + assert cs == 42981, ('wrong overview checksum (%d)' % cs) cs = band.GetOverview(1).Checksum() - if cs != 61363: - gdaltest.post_reason('wrong overview checksum (%d)' % cs) - return 'fail' + assert cs == 61363, ('wrong overview checksum (%d)' % cs) cs = band.GetOverview(2).Checksum() - if cs != 48060: - gdaltest.post_reason('wrong overview checksum (%d)' % cs) - return 'fail' + assert cs == 48060, ('wrong overview checksum (%d)' % cs) cs = band.GetOverview(3).Checksum() - if cs != 12058: - gdaltest.post_reason('wrong overview checksum (%d)' % cs) - return 'fail' + assert cs == 12058, ('wrong overview checksum (%d)' % cs) - return 'success' -gdaltest_list = [ - blx_1, - blx_2, - blx_3, - blx_4, - blx_5 -] - -if __name__ == '__main__': - - gdaltest.setup_run('blx') - - gdaltest.run_tests(gdaltest_list) - - sys.exit(gdaltest.summarize()) diff --git a/autotest/gdrivers/bsb.py b/autotest/gdrivers/bsb.py index 24440c42886f..264c2341d8d4 100755 --- a/autotest/gdrivers/bsb.py +++ b/autotest/gdrivers/bsb.py @@ -28,31 +28,29 @@ # DEALINGS IN THE SOFTWARE. ############################################################################### -import sys from osgeo import gdal -sys.path.append('../pymod') import gdaltest +import pytest ############################################################################### # Test driver availability -def bsb_0(): +def test_bsb_0(): gdaltest.bsb_dr = gdal.GetDriverByName('BSB') if gdaltest.bsb_dr is None: - return 'skip' - - return 'success' + pytest.skip() + ############################################################################### # Test Read -def bsb_1(): +def test_bsb_1(): if gdaltest.bsb_dr is None: - return 'skip' + pytest.skip() tst = gdaltest.GDALTest('BSB', 'rgbsmall.kap', 1, 30321) @@ -62,13 +60,13 @@ def bsb_1(): # Test CreateCopy -def bsb_2(): +def test_bsb_2(): if gdaltest.bsb_dr is None: - return 'skip' + pytest.skip() md = gdaltest.bsb_dr.GetMetadata() if 'DMD_CREATIONDATATYPES' not in md: - return 'skip' + pytest.skip() tst = gdaltest.GDALTest('BSB', 'rgbsmall.kap', 1, 30321) @@ -81,9 +79,9 @@ def bsb_2(): # --> This is probably not a valid BSB file, but it proves that we can read the index table -def bsb_3(): +def test_bsb_3(): if gdaltest.bsb_dr is None: - return 'skip' + pytest.skip() tst = gdaltest.GDALTest('BSB', 'rgbsmall_index.kap', 1, 30321) @@ -95,9 +93,9 @@ def bsb_3(): # adding a 0 character in the middle of line data -def bsb_4(): +def test_bsb_4(): if gdaltest.bsb_dr is None: - return 'skip' + pytest.skip() tst = gdaltest.GDALTest('BSB', 'rgbsmall_with_line_break.kap', 1, 30321) @@ -107,9 +105,9 @@ def bsb_4(): # Read a truncated BSB (at the level of the written scanline number starting a new row) -def bsb_5(): +def test_bsb_5(): if gdaltest.bsb_dr is None: - return 'skip' + pytest.skip() tst = gdaltest.GDALTest('BSB', 'rgbsmall_truncated.kap', 1, 29696) @@ -123,9 +121,9 @@ def bsb_5(): # Read another truncated BSB (in the middle of row data) -def bsb_6(): +def test_bsb_6(): if gdaltest.bsb_dr is None: - return 'skip' + pytest.skip() tst = gdaltest.GDALTest('BSB', 'rgbsmall_truncated2.kap', 1, 29696) @@ -136,21 +134,5 @@ def bsb_6(): return ret -gdaltest_list = [ - bsb_0, - bsb_1, - bsb_2, - bsb_3, - bsb_4, - bsb_5, - bsb_6 -] - - -if __name__ == '__main__': - - gdaltest.setup_run('BSB') - gdaltest.run_tests(gdaltest_list) - sys.exit(gdaltest.summarize()) diff --git a/autotest/gdrivers/bt.py b/autotest/gdrivers/bt.py index 91ee51cdf5e7..e2d38950b829 100755 --- a/autotest/gdrivers/bt.py +++ b/autotest/gdrivers/bt.py @@ -28,10 +28,8 @@ # DEALINGS IN THE SOFTWARE. ############################################################################### -import sys from osgeo import osr -sys.path.append('../pymod') from osgeo import gdal import gdaltest @@ -40,7 +38,7 @@ # Test CreateCopy() of int16.tif -def bt_1(): +def test_bt_1(): tst = gdaltest.GDALTest('BT', 'int16.tif', 1, 4672) srs = osr.SpatialReference() @@ -52,7 +50,7 @@ def bt_1(): # Test CreateCopy() of int32.tif -def bt_2(): +def test_bt_2(): tst = gdaltest.GDALTest('BT', 'int32.tif', 1, 4672) srs = osr.SpatialReference() @@ -64,7 +62,7 @@ def bt_2(): # Test CreateCopy() of float32.tif -def bt_3(): +def test_bt_3(): tst = gdaltest.GDALTest('BT', 'float32.tif', 1, 4672) srs = osr.SpatialReference() @@ -76,7 +74,7 @@ def bt_3(): # Test Create() of float32.tif -def bt_4(): +def test_bt_4(): tst = gdaltest.GDALTest('BT', 'float32.tif', 1, 4672) return tst.testCreate(out_bands=1) @@ -85,7 +83,7 @@ def bt_4(): # Test testSetProjection() of float32.tif -def bt_5(): +def test_bt_5(): tst = gdaltest.GDALTest('BT', 'float32.tif', 1, 4672) return tst.testSetProjection() @@ -94,7 +92,7 @@ def bt_5(): # Test testSetGeoTransform() of float32.tif -def bt_6(): +def test_bt_6(): tst = gdaltest.GDALTest('BT', 'float32.tif', 1, 4672) return tst.testSetGeoTransform() @@ -103,28 +101,11 @@ def bt_6(): # Cleanup -def bt_cleanup(): +def test_bt_cleanup(): gdal.Unlink('/vsimem/int16.tif.prj') gdal.Unlink('tmp/int32.tif.prj') gdal.Unlink('tmp/float32.tif.prj') - return 'success' -gdaltest_list = [ - bt_1, - bt_2, - bt_3, - bt_4, - bt_5, - bt_6, - bt_cleanup] - -if __name__ == '__main__': - - gdaltest.setup_run('bt') - - gdaltest.run_tests(gdaltest_list) - - sys.exit(gdaltest.summarize()) diff --git a/autotest/gdrivers/byn.py b/autotest/gdrivers/byn.py index 7d85011aee2c..7fe9add179fd 100755 --- a/autotest/gdrivers/byn.py +++ b/autotest/gdrivers/byn.py @@ -30,9 +30,7 @@ # DEALINGS IN THE SOFTWARE. ############################################################################### -import sys -sys.path.append('../pymod') import gdaltest @@ -40,7 +38,7 @@ # Read test of byte file. -def byn_1(): +def test_byn_1(): tst = gdaltest.GDALTest('BYN', 'cgg2013ai08_reduced.byn', 1, 64764) return tst.testOpen() @@ -48,7 +46,7 @@ def byn_1(): ############################################################################### # -def byn_2(): +def test_byn_2(): tst = gdaltest.GDALTest('BYN', 'cgg2013ai08_reduced.byn', 1, 64764) return tst.testCreateCopy(new_filename='tmp/byn_test_2.byn') @@ -56,14 +54,4 @@ def byn_2(): ############################################################################### # -gdaltest_list = [ - byn_1, - byn_2] -if __name__ == '__main__': - - gdaltest.setup_run('byn') - - gdaltest.run_tests(gdaltest_list) - - sys.exit(gdaltest.summarize()) diff --git a/autotest/gdrivers/cals.py b/autotest/gdrivers/cals.py index e9cf612f9a13..678928086e1c 100755 --- a/autotest/gdrivers/cals.py +++ b/autotest/gdrivers/cals.py @@ -28,9 +28,7 @@ # DEALINGS IN THE SOFTWARE. ############################################################################### -import sys -sys.path.append('../pymod') from osgeo import gdal import gdaltest @@ -39,7 +37,7 @@ # Source has no color table -def cals_1(): +def test_cals_1(): tst = gdaltest.GDALTest('CALS', 'small1bit.img', 1, 9907) @@ -49,7 +47,7 @@ def cals_1(): # Source has a color table (0,0,0),(255,255,255) -def cals_2(): +def test_cals_2(): # Has no color table tst = gdaltest.GDALTest('CALS', '../../gcore/data/oddsize1bit.tif', 1, 3883) @@ -60,68 +58,50 @@ def cals_2(): # Source has a color table (255,255,255),(0,0,0) -def cals_3(): +def test_cals_3(): src_ds = gdal.Open('../gcore/data/oddsize1bit.tif') tmp_ds = gdal.GetDriverByName('CALS').CreateCopy('/vsimem/cals_2_tmp.cal', src_ds) tmp_ds.SetMetadataItem('TIFFTAG_XRESOLUTION', '600') tmp_ds.SetMetadataItem('TIFFTAG_YRESOLUTION', '600') out_ds = gdal.GetDriverByName('CALS').CreateCopy('/vsimem/cals_2.cal', tmp_ds) - if gdal.VSIStatL('/vsimem/cals_2.cal.aux.xml') is not None: - gdaltest.post_reason('fail') - return 'fail' - if out_ds.GetRasterBand(1).Checksum() != 3883: - gdaltest.post_reason('fail') - return 'fail' - if out_ds.GetMetadataItem('PIXEL_PATH') is not None: - gdaltest.post_reason('fail') - return 'fail' - if out_ds.GetMetadataItem('TIFFTAG_XRESOLUTION') != '600': - gdaltest.post_reason('fail') - return 'fail' - if out_ds.GetRasterBand(1).GetColorInterpretation() != gdal.GCI_PaletteIndex: - gdaltest.post_reason('fail') - return 'fail' + assert gdal.VSIStatL('/vsimem/cals_2.cal.aux.xml') is None + assert out_ds.GetRasterBand(1).Checksum() == 3883 + assert out_ds.GetMetadataItem('PIXEL_PATH') is None + assert out_ds.GetMetadataItem('TIFFTAG_XRESOLUTION') == '600' + assert out_ds.GetRasterBand(1).GetColorInterpretation() == gdal.GCI_PaletteIndex tmp_ds = None out_ds = None gdal.Unlink('/vsimem/cals_2_tmp.cal') gdal.Unlink('/vsimem/cals_2_tmp.cal.aux.xml') gdal.Unlink('/vsimem/cals_2.cal') - return 'success' - ############################################################################### # Test CreateCopy() error conditions -def cals_4(): +def test_cals_4(): # 0 band src_ds = gdal.GetDriverByName('MEM').Create('', 1, 1, 0) gdal.PushErrorHandler() out_ds = gdal.GetDriverByName('CALS').CreateCopy('/vsimem/cals_4.cal', src_ds) gdal.PopErrorHandler() - if out_ds is not None: - gdaltest.post_reason('fail') - return 'fail' + assert out_ds is None # 2 bands src_ds = gdal.GetDriverByName('MEM').Create('', 1, 1, 2) gdal.PushErrorHandler() out_ds = gdal.GetDriverByName('CALS').CreateCopy('/vsimem/cals_4.cal', src_ds, strict=True) gdal.PopErrorHandler() - if out_ds is not None: - gdaltest.post_reason('fail') - return 'fail' + assert out_ds is None # 1 band but not 1-bit src_ds = gdal.GetDriverByName('MEM').Create('', 1, 1, 1) gdal.PushErrorHandler() out_ds = gdal.GetDriverByName('CALS').CreateCopy('/vsimem/cals_4.cal', src_ds, strict=True) gdal.PopErrorHandler() - if out_ds is not None: - gdaltest.post_reason('fail') - return 'fail' + assert out_ds is None # Dimension > 999999 src_ds = gdal.GetDriverByName('MEM').Create('', 1000000, 1, 1) @@ -129,9 +109,7 @@ def cals_4(): gdal.PushErrorHandler() out_ds = gdal.GetDriverByName('CALS').CreateCopy('/vsimem/cals_4.cal', src_ds, strict=True) gdal.PopErrorHandler() - if out_ds is not None: - gdaltest.post_reason('fail') - return 'fail' + assert out_ds is None # Invalid output filename src_ds = gdal.GetDriverByName('MEM').Create('', 1, 1, 1) @@ -139,53 +117,27 @@ def cals_4(): gdal.PushErrorHandler() out_ds = gdal.GetDriverByName('CALS').CreateCopy('/not_existing_dir/cals_4.cal', src_ds) gdal.PopErrorHandler() - if out_ds is not None: - gdaltest.post_reason('fail') - return 'fail' - - return 'success' + assert out_ds is None ############################################################################### # Test PIXEL_PATH & LINE_PROGRESSION metadata item -def cals_5(): +def test_cals_5(): src_ds = gdal.GetDriverByName('MEM').Create('', 1, 1, 1) src_ds.GetRasterBand(1).SetMetadataItem('NBITS', '1', 'IMAGE_STRUCTURE') src_ds.SetMetadataItem('PIXEL_PATH', '90') src_ds.SetMetadataItem('LINE_PROGRESSION', '270') out_ds = gdal.GetDriverByName('CALS').CreateCopy('/vsimem/cals_5.cal', src_ds) - if gdal.VSIStatL('/vsimem/cals_5.cal.aux.xml') is not None: - gdaltest.post_reason('fail') - return 'fail' - if out_ds.GetMetadataItem('PIXEL_PATH') != '90': - gdaltest.post_reason('fail') - return 'fail' - if out_ds.GetMetadataItem('LINE_PROGRESSION') != '270': - gdaltest.post_reason('fail') - return 'fail' + assert gdal.VSIStatL('/vsimem/cals_5.cal.aux.xml') is None + assert out_ds.GetMetadataItem('PIXEL_PATH') == '90' + assert out_ds.GetMetadataItem('LINE_PROGRESSION') == '270' out_ds = None gdal.Unlink('/vsimem/cals_5.cal') - return 'success' - ############################################################################### -gdaltest_list = [ - cals_1, - cals_2, - cals_3, - cals_4, - cals_5, -] - - -if __name__ == '__main__': - - gdaltest.setup_run('cals') - gdaltest.run_tests(gdaltest_list) - sys.exit(gdaltest.summarize()) diff --git a/autotest/gdrivers/ceos.py b/autotest/gdrivers/ceos.py index fc5660d1214c..0b2f316002f6 100755 --- a/autotest/gdrivers/ceos.py +++ b/autotest/gdrivers/ceos.py @@ -28,9 +28,7 @@ # DEALINGS IN THE SOFTWARE. ############################################################################### -import sys -sys.path.append('../pymod') import gdaltest @@ -39,20 +37,11 @@ # contains 3 complete scanlines. Bizarre little endian CEOS variant. (#1862) -def ceos_1(): +def test_ceos_1(): tst = gdaltest.GDALTest('CEOS', 'IMAGERY-75K.L-3', 4, 9956, xoff=0, yoff=0, xsize=5932, ysize=3) return tst.testOpen() -gdaltest_list = [ - ceos_1] -if __name__ == '__main__': - - gdaltest.setup_run('ceos') - - gdaltest.run_tests(gdaltest_list) - - sys.exit(gdaltest.summarize()) diff --git a/autotest/gdrivers/cpg.py b/autotest/gdrivers/cpg.py index de3f50b8a233..4c44e203a934 100755 --- a/autotest/gdrivers/cpg.py +++ b/autotest/gdrivers/cpg.py @@ -28,9 +28,7 @@ # DEALINGS IN THE SOFTWARE. ############################################################################### -import sys -sys.path.append('../pymod') import gdaltest @@ -38,19 +36,10 @@ # Test a fake CPG dataset -def cpg_1(): +def test_cpg_1(): tst = gdaltest.GDALTest('CPG', 'fakecpgSIRC.hdr', 1, 0) return tst.testOpen() -gdaltest_list = [ - cpg_1] -if __name__ == '__main__': - - gdaltest.setup_run('cpg') - - gdaltest.run_tests(gdaltest_list) - - sys.exit(gdaltest.summarize()) diff --git a/autotest/gdrivers/ctg.py b/autotest/gdrivers/ctg.py index ac8b4e948a4e..8322fc51f677 100755 --- a/autotest/gdrivers/ctg.py +++ b/autotest/gdrivers/ctg.py @@ -28,10 +28,8 @@ # DEALINGS IN THE SOFTWARE. ############################################################################### -import sys from osgeo import gdal -sys.path.append('../pymod') import gdaltest @@ -39,7 +37,7 @@ # Test a fake CTG dataset -def ctg_1(): +def test_ctg_1(): tst = gdaltest.GDALTest('CTG', 'fake_grid_cell', 1, 21) expected_gt = [421000.0, 200.0, 0.0, 5094400.0, 0.0, -200.0] @@ -70,27 +68,13 @@ def ctg_1(): if ret == 'success': ds = gdal.Open('data/fake_grid_cell') lst = ds.GetRasterBand(1).GetCategoryNames() - if lst is None or not lst: - gdaltest.post_reason('expected non empty category names for band 1') - return 'fail' + assert lst is not None and lst, 'expected non empty category names for band 1' lst = ds.GetRasterBand(2).GetCategoryNames() - if lst is not None: - gdaltest.post_reason('expected empty category names for band 2') - return 'fail' - if ds.GetRasterBand(1).GetNoDataValue() != 0: - gdaltest.post_reason('did not get expected nodata value') - return 'fail' + assert lst is None, 'expected empty category names for band 2' + assert ds.GetRasterBand(1).GetNoDataValue() == 0, \ + 'did not get expected nodata value' return ret -gdaltest_list = [ - ctg_1] -if __name__ == '__main__': - - gdaltest.setup_run('ctg') - - gdaltest.run_tests(gdaltest_list) - - sys.exit(gdaltest.summarize()) diff --git a/autotest/gdrivers/db2.py b/autotest/gdrivers/db2.py index 6c6881811471..6806ac8b5512 100755 --- a/autotest/gdrivers/db2.py +++ b/autotest/gdrivers/db2.py @@ -31,13 +31,13 @@ import os import sys +import pytest # Make sure we run from the directory of the script if os.path.basename(sys.argv[0]) == os.path.basename(__file__): if os.path.dirname(sys.argv[0]) != '': os.chdir(os.path.dirname(sys.argv[0])) -sys.path.append('../pymod') from osgeo import gdal import gdaltest @@ -46,13 +46,13 @@ # Test if DB2 and tile drivers are available -def gpkg_init(): +def test_gpkg_init(): gdaltest.db2_drv = None gdaltest.db2_drv = gdal.GetDriverByName('DB2ODBC') if gdaltest.db2_drv is None: - return 'skip' + pytest.skip() gdaltest.png_dr = gdal.GetDriverByName('PNG') gdaltest.jpeg_dr = gdal.GetDriverByName('JPEG') @@ -66,14 +66,11 @@ def gpkg_init(): if 'DB2_TEST_SERVER' in os.environ: gdaltest.db2_test_server = "DB2ODBC:" + os.environ['DB2_TEST_SERVER'] else: - gdaltest.post_reason('Environment variable DB2_TEST_SERVER not found') gdaltest.db2_drv = None - return 'skip' + pytest.skip('Environment variable DB2_TEST_SERVER not found') print("\ntest server: " + gdaltest.db2_test_server + "\n") - return 'success' - ############################################################################### # @@ -142,8 +139,8 @@ def check_tile_format(out_ds, expected_format, expected_band_count, expected_ct, if expected_format is None: if mime_type is None: - return 'success' - return 'fail' + return + pytest.fail() if expected_format == 'PNG': expected_mime_type = 'image/png' @@ -152,30 +149,20 @@ def check_tile_format(out_ds, expected_format, expected_band_count, expected_ct, elif expected_format == 'WEBP': expected_mime_type = 'image/x-webp' - if mime_type != expected_mime_type: - gdaltest.post_reason('fail') - print(mime_type) - return 'fail' - if band_count != expected_band_count: - gdaltest.post_reason('fail') - print(band_count) - return 'fail' - if expected_ct != has_ct: - gdaltest.post_reason('fail') - print(has_ct) - return 'fail' - return 'success' + assert mime_type == expected_mime_type + assert band_count == expected_band_count + assert expected_ct == has_ct ############################################################################### # Single band, PNG -def gpkg_1(): +def test_gpkg_1(): if gdaltest.db2_drv is None: - return 'skip' + pytest.skip() if gdaltest.png_dr is None: - return 'skip' + pytest.skip() # With padding ds = gdal.Open('data/byte.tif') @@ -190,49 +177,23 @@ def gpkg_1(): out_ds = gdal.OpenEx(gdaltest.db2_test_server, gdal.OF_RASTER | gdal.OF_UPDATE, open_options=['TABLE=byte']) bnd = out_ds.GetRasterBand(1) - if bnd.Checksum() != 4672: - gdaltest.post_reason('Didnt get expected checksum on reopened file') - return 'fail' + assert bnd.Checksum() == 4672, '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' got_gt = out_ds.GetGeoTransform() for i in range(6): - if abs(expected_gt[i] - got_gt[i]) > 1e-8: - gdaltest.post_reason('fail') - return 'fail' + assert abs(expected_gt[i] - got_gt[i]) <= 1e-8 got_wkt = out_ds.GetProjectionRef() print("\n** expected_wkt " + expected_wkt + " **\n") print("\n** got_wkt " + got_wkt + " **\n") # string comparison doesn't work with DB2 due to differences in # the WKT (similar but different) # just check if it contains '11N' for NAD27 UTM zone 11N - if got_wkt.find('11N') == -1: - gdaltest.post_reason('fail') - return 'fail' + assert got_wkt.find('11N') != -1 expected_cs = [expected_cs, expected_cs, expected_cs, 4873] got_cs = [out_ds.GetRasterBand(i + 1).Checksum() for i in range(4)] - if got_cs != expected_cs: - gdaltest.post_reason('fail') - print('Got %s, expected %s' % (str(got_cs), str(expected_cs))) - return 'fail' - - return 'success' + assert got_cs == expected_cs ############################################################################### - - -gdaltest_list = [ - gpkg_init, - gpkg_1 -] -# gdaltest_list = [ gpkg_init, gpkg_26, gpkg_cleanup ] -if __name__ == '__main__': - - gdaltest.setup_run('gpkg') - - gdaltest.run_tests(gdaltest_list) - - sys.exit(gdaltest.summarize()) diff --git a/autotest/gdrivers/derived.py b/autotest/gdrivers/derived.py index 94bb573fc92a..2a470ffb3587 100755 --- a/autotest/gdrivers/derived.py +++ b/autotest/gdrivers/derived.py @@ -28,21 +28,18 @@ # DEALINGS IN THE SOFTWARE. ############################################################################### -import sys from osgeo import gdal -sys.path.append('../pymod') import gdaltest +import pytest -def derived_test1(): +def test_derived_test1(): filename = "../gcore/data/cfloat64.tif" gdal.ErrorReset() ds = gdal.Open(filename) - if ds is None or gdal.GetLastErrorMsg() != '': - gdaltest.post_reason('fail') - return 'fail' + assert ds is not None and gdal.GetLastErrorMsg() == '' got_dsds = ds.GetMetadata('DERIVED_SUBDATASETS') expected_gt = ds.GetGeoTransform() expected_prj = ds.GetProjection() @@ -62,40 +59,32 @@ def derived_test1(): 'DERIVED_SUBDATASET_7_DESC': 'log10 of amplitude of input bands from ../gcore/data/cfloat64.tif'} if got_dsds != expected_dsds: - gdaltest.post_reason('fail') import pprint pprint.pprint(got_dsds) - return 'fail' + pytest.fail() for key in expected_dsds: val = expected_dsds[key] if key.endswith('_NAME'): ds = gdal.Open(val) - if ds is None or gdal.GetLastErrorMsg() != '': - gdaltest.post_reason('fail') - return 'fail' + assert ds is not None and gdal.GetLastErrorMsg() == '' gt = ds.GetGeoTransform() if gt != expected_gt: - gdaltest.post_reason('fail') import pprint pprint.pprint("Expected geotransform: " + str(expected_gt) + ", got " + str(gt)) - return 'fail' + pytest.fail() prj = ds.GetProjection() if prj != expected_prj: - gdaltest.post_reason('fail') import pprint pprint.pprint("Expected projection: " + str(expected_prj) + ", got: " + str(gt)) - return 'fail' - return 'success' + pytest.fail() + - -def derived_test2(): +def test_derived_test2(): filename = "../gcore/data/cint_sar.tif" gdal.ErrorReset() ds = gdal.Open(filename) - if ds is None or gdal.GetLastErrorMsg() != '': - gdaltest.post_reason('fail') - return 'fail' + assert ds is not None and gdal.GetLastErrorMsg() == '' got_dsds = ds.GetMetadata('DERIVED_SUBDATASETS') expected_dsds = {'DERIVED_SUBDATASET_1_NAME': 'DERIVED_SUBDATASET:AMPLITUDE:../gcore/data/cint_sar.tif', 'DERIVED_SUBDATASET_1_DESC': 'Amplitude of input bands from ../gcore/data/cint_sar.tif', @@ -121,57 +110,44 @@ def derived_test2(): 'DERIVED_SUBDATASET_7_NAME': 55} if got_dsds != expected_dsds: - gdaltest.post_reason('fail') import pprint pprint.pprint(got_dsds) - return 'fail' + pytest.fail() for key in expected_dsds: val = expected_dsds[key] if key.endswith('_NAME'): ds = gdal.Open(val) - if ds is None or gdal.GetLastErrorMsg() != '': - gdaltest.post_reason('fail') - return 'fail' + assert ds is not None and gdal.GetLastErrorMsg() == '' cs = ds.GetRasterBand(1).Checksum() if expected_cs[key] != cs: - gdaltest.post_reason('fail') import pprint pprint.pprint("Expected checksum " + str(expected_cs[key]) + ", got " + str(cs)) - return 'fail' - - return 'success' + pytest.fail() + # Error cases -def derived_test3(): +def test_derived_test3(): with gdaltest.error_handler(): # Missing filename ds = gdal.Open('DERIVED_SUBDATASET:LOGAMPLITUDE') - if ds is not None: - gdaltest.post_reason('fail') - return 'fail' + assert ds is None with gdaltest.error_handler(): ds = gdal.Open('DERIVED_SUBDATASET:invalid_alg:../gcore/data/byte.tif') - if ds is not None: - gdaltest.post_reason('fail') - return 'fail' + assert ds is None with gdaltest.error_handler(): ds = gdal.Open('DERIVED_SUBDATASET:LOGAMPLITUDE:dataset_does_not_exist') - if ds is not None: - gdaltest.post_reason('fail') - return 'fail' + assert ds is None with gdaltest.error_handler(): # Raster with zero band ds = gdal.Open('DERIVED_SUBDATASET:LOGAMPLITUDE:data/CSK_DGM.h5') - if ds is not None: - gdaltest.post_reason('fail') - return 'fail' + assert ds is None for function in ['real', 'imag', 'complex', 'mod', 'phase', 'conj', 'sum', 'diff', 'mul', 'cmul', 'inv', 'intensity', @@ -180,19 +156,6 @@ def derived_test3(): with gdaltest.error_handler(): ds.GetRasterBand(1).Checksum() - return 'success' - - -gdaltest_list = [ - derived_test1, - derived_test2, - derived_test3 -] - -if __name__ == '__main__': - - gdaltest.setup_run('derived') + - gdaltest.run_tests(gdaltest_list) - sys.exit(gdaltest.summarize()) diff --git a/autotest/gdrivers/dimap.py b/autotest/gdrivers/dimap.py index 543f85f71e1f..d083c2cc34a4 100755 --- a/autotest/gdrivers/dimap.py +++ b/autotest/gdrivers/dimap.py @@ -29,19 +29,16 @@ ############################################################################### import os -import sys import shutil from osgeo import gdal -sys.path.append('../pymod') -import gdaltest ############################################################################### # Open and verify a the GCPs and metadata. -def dimap_1(): +def test_dimap_1(): shutil.copy('data/dimap/METADATA.DIM', 'tmp') shutil.copy('data/dimap/IMAGERY.TIF', 'tmp') @@ -49,100 +46,55 @@ def dimap_1(): ds = gdal.Open('tmp/METADATA.DIM') - if ds.RasterCount != 1 \ - or ds.RasterXSize != 6000 \ - or ds.RasterYSize != 6000: - gdaltest.post_reason('wrong size or bands') - return 'fail' + assert ds.RasterCount == 1 and ds.RasterXSize == 6000 and ds.RasterYSize == 6000, \ + 'wrong size or bands' - if ds.GetRasterBand(1).Checksum(0, 0, 100, 100) != 21586: - gdaltest.post_reason('wrong checksum') - return 'fail' + assert ds.GetRasterBand(1).Checksum(0, 0, 100, 100) == 21586, 'wrong checksum' md = ds.GetMetadata() - if md['PROCESSING_LEVEL'] != '1A': - gdaltest.post_reason('metadata wrong.') - return 'fail' + assert md['PROCESSING_LEVEL'] == '1A', 'metadata wrong.' md = ds.GetMetadata() - if md['SPECTRAL_PHYSICAL_BIAS'] != '0.000000': - gdaltest.post_reason('metadata wrong.') - return 'fail' + assert md['SPECTRAL_PHYSICAL_BIAS'] == '0.000000', 'metadata wrong.' gcp_srs = ds.GetGCPProjection() - if gcp_srs[:6] != 'GEOGCS' \ + assert (not (gcp_srs[:6] != 'GEOGCS' \ or gcp_srs.find('WGS') == -1 \ - or gcp_srs.find('84') == -1: - gdaltest.post_reason('GCP Projection not retained.') - print(gcp_srs) - return 'fail' + or gcp_srs.find('84') == -1)), 'GCP Projection not retained.' gcps = ds.GetGCPs() - if len(gcps) != 4 \ - or gcps[0].GCPPixel != 0.5 \ - or gcps[0].GCPLine != 0.5 \ - or abs(gcps[0].GCPX - 4.3641728) > 0.0000002 \ - or abs(gcps[0].GCPY - 44.2082255) > 0.0000002 \ - or abs(gcps[0].GCPZ - 0) > 0.0000002: - gdaltest.post_reason('GCPs wrong.') - print(len(gcps)) - print(gcps[0]) - return 'fail' + assert len(gcps) == 4 and gcps[0].GCPPixel == 0.5 and gcps[0].GCPLine == 0.5 and abs(gcps[0].GCPX - 4.3641728) <= 0.0000002 and abs(gcps[0].GCPY - 44.2082255) <= 0.0000002 and abs(gcps[0].GCPZ - 0) <= 0.0000002, \ + 'GCPs wrong.' ds = None os.unlink('tmp/METADATA.DIM') os.unlink('tmp/IMAGERY.TIF') os.unlink('tmp/rgbsmall.tif') - return 'success' - ############################################################################### # Open DIMAP 2 -def dimap_2(): +def test_dimap_2(): for name in ['data/dimap2', 'data/dimap2/VOL_PHR.XML', 'data/dimap2/DIM_foo.XML']: ds = gdal.Open(name) - if ds.RasterCount != 4 \ - or ds.RasterXSize != 20 \ - or ds.RasterYSize != 30: - gdaltest.post_reason('wrong size or bands') - return 'fail' + assert ds.RasterCount == 4 and ds.RasterXSize == 20 and ds.RasterYSize == 30, \ + 'wrong size or bands' md = ds.GetMetadata() expected_md = {'GEOMETRIC_ATTITUDES_USED': 'ACCURATE', 'FACILITY_PROCESSING_CENTER': 'PROCESSING_CENTER', 'GEOMETRIC_VERTICAL_DESC': 'REFERENCE3D', 'EPHEMERIS_ACQUISITION_ORBIT_DIRECTION': 'DESCENDING', 'BAND_MODE': 'PX', 'EPHEMERIS_NADIR_LON': 'NADIR_LON', 'EPHEMERIS_ACQUISITION_ORBIT_NUMBER': 'ACQUISITION_ORBIT_NUMBER', 'SPECTRAL_PROCESSING': 'PMS', 'CLOUDCOVER_MEASURE_TYPE': 'AUTOMATIC', 'DATASET_JOB_ID': 'JOB_ID', 'MISSION': 'PHR', 'GEOMETRIC_GROUND_SETTING': 'true', 'GEOMETRIC_VERTICAL_SETTING': 'true', 'DATASET_PRODUCTION_DATE': 'PRODUCTION_DATE', 'DATASET_PRODUCER_CONTACT': 'PRODUCER_CONTACT', 'IMAGING_DATE': '2016-06-17', 'CLOUDCOVER_QUALITY_TABLES': 'PHR', 'DATASET_PRODUCER_NAME': 'PRODUCER_NAME', 'GEOMETRIC_GEOMETRIC_PROCESSING': 'SENSOR', 'GEOMETRIC_EPHEMERIS_USED': 'CORRECTED', 'GEOMETRIC_GROUND_DESC': 'R3D_ORTHO', 'DATASET_DELIVERY_TYPE': 'DELIVERY_TYPE', 'PROCESSING_LEVEL': 'SENSOR', 'DATASET_PRODUCER_ADDRESS': 'PRODUCER_ADDRESS', 'DATASET_PRODUCT_CODE': 'PRODUCT_CODE', 'INSTRUMENT_INDEX': '1A', 'EPHEMERIS_NADIR_LAT': 'NADIR_LAT', 'INSTRUMENT': 'PHR', 'CLOUDCOVER_MEASURE_NAME': 'Cloud_Cotation (CLD)', 'FACILITY_SOFTWARE': 'SOFTWARE', 'IMAGING_TIME': '12:34:56', 'MISSION_INDEX': '1A'} - if md != expected_md: - gdaltest.post_reason('metadata wrong.') - print(md) - return 'fail' + assert md == expected_md, 'metadata wrong.' rpc = ds.GetMetadata('RPC') expected_rpc = {'HEIGHT_OFF': 'HEIGHT_OFF', 'LINE_NUM_COEFF': ' LINE_NUM_COEFF_1 LINE_NUM_COEFF_2 LINE_NUM_COEFF_3 LINE_NUM_COEFF_4 LINE_NUM_COEFF_5 LINE_NUM_COEFF_6 LINE_NUM_COEFF_7 LINE_NUM_COEFF_8 LINE_NUM_COEFF_9 LINE_NUM_COEFF_10 LINE_NUM_COEFF_11 LINE_NUM_COEFF_12 LINE_NUM_COEFF_13 LINE_NUM_COEFF_14 LINE_NUM_COEFF_15 LINE_NUM_COEFF_16 LINE_NUM_COEFF_17 LINE_NUM_COEFF_18 LINE_NUM_COEFF_19 LINE_NUM_COEFF_20', 'LONG_OFF': 'LONG_OFF', 'SAMP_DEN_COEFF': ' SAMP_DEN_COEFF_1 SAMP_DEN_COEFF_2 SAMP_DEN_COEFF_3 SAMP_DEN_COEFF_4 SAMP_DEN_COEFF_5 SAMP_DEN_COEFF_6 SAMP_DEN_COEFF_7 SAMP_DEN_COEFF_8 SAMP_DEN_COEFF_9 SAMP_DEN_COEFF_10 SAMP_DEN_COEFF_11 SAMP_DEN_COEFF_12 SAMP_DEN_COEFF_13 SAMP_DEN_COEFF_14 SAMP_DEN_COEFF_15 SAMP_DEN_COEFF_16 SAMP_DEN_COEFF_17 SAMP_DEN_COEFF_18 SAMP_DEN_COEFF_19 SAMP_DEN_COEFF_20', 'LINE_SCALE': 'LINE_SCALE', 'SAMP_NUM_COEFF': ' SAMP_NUM_COEFF_1 SAMP_NUM_COEFF_2 SAMP_NUM_COEFF_3 SAMP_NUM_COEFF_4 SAMP_NUM_COEFF_5 SAMP_NUM_COEFF_6 SAMP_NUM_COEFF_7 SAMP_NUM_COEFF_8 SAMP_NUM_COEFF_9 SAMP_NUM_COEFF_10 SAMP_NUM_COEFF_11 SAMP_NUM_COEFF_12 SAMP_NUM_COEFF_13 SAMP_NUM_COEFF_14 SAMP_NUM_COEFF_15 SAMP_NUM_COEFF_16 SAMP_NUM_COEFF_17 SAMP_NUM_COEFF_18 SAMP_NUM_COEFF_19 SAMP_NUM_COEFF_20', 'LONG_SCALE': 'LONG_SCALE', 'SAMP_SCALE': 'SAMP_SCALE', 'SAMP_OFF': '4', 'LAT_SCALE': 'LAT_SCALE', 'LAT_OFF': 'LAT_OFF', 'LINE_OFF': '9', 'LINE_DEN_COEFF': ' LINE_DEN_COEFF_1 LINE_DEN_COEFF_2 LINE_DEN_COEFF_3 LINE_DEN_COEFF_4 LINE_DEN_COEFF_5 LINE_DEN_COEFF_6 LINE_DEN_COEFF_7 LINE_DEN_COEFF_8 LINE_DEN_COEFF_9 LINE_DEN_COEFF_10 LINE_DEN_COEFF_11 LINE_DEN_COEFF_12 LINE_DEN_COEFF_13 LINE_DEN_COEFF_14 LINE_DEN_COEFF_15 LINE_DEN_COEFF_16 LINE_DEN_COEFF_17 LINE_DEN_COEFF_18 LINE_DEN_COEFF_19 LINE_DEN_COEFF_20', 'HEIGHT_SCALE': 'HEIGHT_SCALE'} - if rpc != expected_rpc: - gdaltest.post_reason('RPC wrong.') - print(rpc) - return 'fail' + assert rpc == expected_rpc, 'RPC wrong.' cs = ds.GetRasterBand(1).Checksum() - if cs != 7024: - gdaltest.post_reason('wrong checksum.') - print(cs) - return 'fail' + assert cs == 7024, 'wrong checksum.' ds = None - return 'success' - - -gdaltest_list = [ - dimap_1, - dimap_2] - -if __name__ == '__main__': - - gdaltest.setup_run('dimap') + - gdaltest.run_tests(gdaltest_list) - sys.exit(gdaltest.summarize()) diff --git a/autotest/gdrivers/dipex.py b/autotest/gdrivers/dipex.py index 169ab5e8ad1a..b4ebd39f645e 100755 --- a/autotest/gdrivers/dipex.py +++ b/autotest/gdrivers/dipex.py @@ -28,9 +28,7 @@ # DEALINGS IN THE SOFTWARE. ############################################################################### -import sys -sys.path.append('../pymod') import gdaltest @@ -38,19 +36,10 @@ # Test a fake DIPex dataset -def dipex_1(): +def test_dipex_1(): tst = gdaltest.GDALTest('DIPEx', 'fakedipex.dat', 1, 1) return tst.testOpen() -gdaltest_list = [ - dipex_1] -if __name__ == '__main__': - - gdaltest.setup_run('dipex') - - gdaltest.run_tests(gdaltest_list) - - sys.exit(gdaltest.summarize()) diff --git a/autotest/gdrivers/dods.py b/autotest/gdrivers/dods.py index a895ae870978..8ef21f59dc70 100755 --- a/autotest/gdrivers/dods.py +++ b/autotest/gdrivers/dods.py @@ -28,40 +28,40 @@ # DEALINGS IN THE SOFTWARE. ############################################################################### -import sys from osgeo import gdal -sys.path.append('../pymod') import gdaltest +import pytest ############################################################################### # Open DODS datasource. -def dods_1(): +@pytest.mark.skip() +def test_dods_1(): gdaltest.dods_ds = None gdaltest.dods_dr = None gdaltest.dods_dr = gdal.GetDriverByName('DODS') if gdaltest.dods_dr is None: - return 'skip' + pytest.skip() gdaltest.dods_grid_ds = gdal.Open('http://disc1.sci.gsfc.nasa.gov/opendap/tovs/TOVSAMNF/1985/032/TOVS_MONTHLY_PM_8502_NF.HDF.Z?Data-Set-11[y][x]') if gdaltest.dods_grid_ds is None: gdaltest.dods_dr = None - return 'fail' + pytest.fail() - return 'success' ############################################################################### # Simple read test on a single variable. -def dods_2(): +@pytest.mark.skip() +def test_dods_2(): if gdaltest.dods_dr is None: - return 'skip' + pytest.skip() tst = gdaltest.GDALTest('dods', 'http://disc1.sci.gsfc.nasa.gov/opendap/tovs/TOVSAMNF/1985/032/TOVS_MONTHLY_PM_8502_NF.HDF.Z?Data-Set-11', 1, 3391, filename_absolute=1) return tst.testOpen() @@ -69,9 +69,10 @@ def dods_2(): # Access all grids at once. -def dods_3(): +@pytest.mark.skip() +def test_dods_3(): if gdaltest.dods_dr is None: - return 'skip' + pytest.skip() tst = gdaltest.GDALTest('dods', 'http://disc1.sci.gsfc.nasa.gov/opendap/tovs/TOVSAMNF/1985/032/TOVS_MONTHLY_PM_8502_NF.HDF.Z', 12, 43208, filename_absolute=1) return tst.testOpen() @@ -79,9 +80,10 @@ def dods_3(): # Test explicit transpose. -def dods_4(): +@pytest.mark.skip() +def test_dods_4(): if gdaltest.dods_dr is None: - return 'skip' + pytest.skip() tst = gdaltest.GDALTest('dods', 'http://disc1.sci.gsfc.nasa.gov/opendap/tovs/TOVSAMNF/1985/032/TOVS_MONTHLY_PM_8502_NF.HDF.Z?Data-Set-11[y][x]', 1, 3391, filename_absolute=1) return tst.testOpen() @@ -89,9 +91,10 @@ def dods_4(): # Test explicit flipping. -def dods_5(): +@pytest.mark.skip() +def test_dods_5(): if gdaltest.dods_dr is None: - return 'skip' + pytest.skip() tst = gdaltest.GDALTest('dods', 'http://disc1.sci.gsfc.nasa.gov/opendap/tovs/TOVSAMNF/1985/032/TOVS_MONTHLY_PM_8502_NF.HDF.Z?Data-Set-11[y][-x]', 1, 2436, filename_absolute=1) return tst.testOpen() @@ -100,53 +103,28 @@ def dods_5(): # Check nodata value. -def dods_6(): +@pytest.mark.skip() +def test_dods_6(): if gdaltest.dods_dr is None: - return 'skip' + pytest.skip() # This server seems to no longer be online, skipping test. - return 'skip' + pytest.skip() # pylint: disable=unreachable gdaltest.dods_grid_ds = gdal.Open('http://g0dup05u.ecs.nasa.gov/opendap/AIRS/AIRX3STD.003/2004.12.28/AIRS.2004.12.28.L3.RetStd001.v4.0.9.0.G05253115303.hdf?TotH2OVap_A[y][x]') nd = gdaltest.dods_grid_ds.GetRasterBand(1).GetNoDataValue() - if nd != -9999.0: - gdaltest.post_reason('nodata value wrong or missing.') - print(nd) - return 'fail' - return 'success' + assert nd == -9999.0, 'nodata value wrong or missing.' ############################################################################### # Cleanup -def dods_cleanup(): +@pytest.mark.skip() +def test_dods_cleanup(): if gdaltest.dods_dr is None: - return 'skip' + pytest.skip() gdaltest.dods_dr = None gdaltest.dods_grid_ds = None - - return 'success' - - -gdaltest_list = [] - -manual_gdaltest_list = [ - dods_1, - dods_2, - dods_3, - dods_4, - dods_5, - dods_6, - dods_cleanup] - - -if __name__ == '__main__': - - gdaltest.setup_run('dods') - - gdaltest.run_tests(manual_gdaltest_list) - - sys.exit(gdaltest.summarize()) diff --git a/autotest/gdrivers/doq1.py b/autotest/gdrivers/doq1.py index 4eb590abaa64..3a9d448275ac 100755 --- a/autotest/gdrivers/doq1.py +++ b/autotest/gdrivers/doq1.py @@ -28,10 +28,8 @@ # DEALINGS IN THE SOFTWARE. ############################################################################### -import sys from osgeo import gdal -sys.path.append('../pymod') import gdaltest @@ -39,7 +37,7 @@ # Test a fake DOQ1 dataset -def doq1_1(): +def test_doq1_1(): tst = gdaltest.GDALTest('DOQ1', 'fakedoq1.doq', 1, 1) gdal.PushErrorHandler('CPLQuietErrorHandler') @@ -48,13 +46,4 @@ def doq1_1(): return ret -gdaltest_list = [ - doq1_1] -if __name__ == '__main__': - - gdaltest.setup_run('doq') - - gdaltest.run_tests(gdaltest_list) - - sys.exit(gdaltest.summarize()) diff --git a/autotest/gdrivers/doq2.py b/autotest/gdrivers/doq2.py index c55146969869..33aafd26f129 100755 --- a/autotest/gdrivers/doq2.py +++ b/autotest/gdrivers/doq2.py @@ -28,61 +28,38 @@ # DEALINGS IN THE SOFTWARE. ############################################################################### -import sys from osgeo import gdal -sys.path.append('../pymod') -import gdaltest ############################################################################### # Read a truncated and modified version of C3607614.NWS # downloaded from http://edcftp.cr.usgs.gov/pub/data/samples/doq-clr-native.tar.gz -def doq2_1(): +def test_doq2_1(): ds = gdal.Open('data/C3607614_truncated.NWS') mem_ds = gdal.GetDriverByName('MEM').Create('mem_1.mem', 500, 1, gdal.GDT_Byte, 1) mem_ds.GetRasterBand(1).WriteRaster(0, 0, 500, 1, ds.GetRasterBand(1).ReadRaster(0, 0, 500, 1)) - if mem_ds.GetRasterBand(1).Checksum() != 4201: - gdaltest.post_reason('wrong checksum for band 1') - return 'fail' + assert mem_ds.GetRasterBand(1).Checksum() == 4201, 'wrong checksum for band 1' mem_ds.GetRasterBand(1).WriteRaster(0, 0, 500, 1, ds.GetRasterBand(2).ReadRaster(0, 0, 500, 1)) - if mem_ds.GetRasterBand(1).Checksum() != 4010: - gdaltest.post_reason('wrong checksum for band 2') - return 'fail' + assert mem_ds.GetRasterBand(1).Checksum() == 4010, 'wrong checksum for band 2' mem_ds.GetRasterBand(1).WriteRaster(0, 0, 500, 1, ds.GetRasterBand(3).ReadRaster(0, 0, 500, 1)) - if mem_ds.GetRasterBand(1).Checksum() != 5820: - gdaltest.post_reason('wrong checksum for band 3') - return 'fail' + assert mem_ds.GetRasterBand(1).Checksum() == 5820, 'wrong checksum for band 3' - if ds.GetGeoTransform() != (377054, 1, 0, 4082205, 0, -1): - gdaltest.post_reason('wrong geotransform') - return 'fail' + assert ds.GetGeoTransform() == (377054, 1, 0, 4082205, 0, -1), 'wrong geotransform' md = ds.GetMetadata() - if md['QUADRANGLE_NAME'] != 'NORFOLK SOUTH 3.45 or 7.5-min. name*': - gdaltest.post_reason('wrong metadata') - return 'fail' + assert md['QUADRANGLE_NAME'] == 'NORFOLK SOUTH 3.45 or 7.5-min. name*', \ + 'wrong metadata' mem_ds = None ds = None - return 'success' -gdaltest_list = [ - doq2_1] - -if __name__ == '__main__': - - gdaltest.setup_run('doq2') - - gdaltest.run_tests(gdaltest_list) - - sys.exit(gdaltest.summarize()) diff --git a/autotest/gdrivers/dted.py b/autotest/gdrivers/dted.py index d7d37441bdbc..67190c9dcaeb 100755 --- a/autotest/gdrivers/dted.py +++ b/autotest/gdrivers/dted.py @@ -31,10 +31,8 @@ ############################################################################### import os -import sys from osgeo import gdal -sys.path.append('../pymod') import gdaltest @@ -42,7 +40,7 @@ # Perform simple read test. -def dted_1(): +def test_dted_1(): tst = gdaltest.GDALTest('dted', 'n43.dt0', 1, 49187) return tst.testOpen() @@ -51,7 +49,7 @@ def dted_1(): # Verify some auxiliary data. -def dted_2(): +def test_dted_2(): ds = gdal.Open('data/n43.dt0') @@ -59,33 +57,23 @@ def dted_2(): max_error = 0.000001 - if abs(gt[0] - (-80.004166666666663)) > max_error or abs(gt[1] - 0.0083333333333333332) > max_error \ - or abs(gt[2] - 0) > max_error or abs(gt[3] - 44.00416666666667) > max_error \ - or abs(gt[4] - 0) > max_error or abs(gt[5] - (-0.0083333333333333332)) > max_error: - gdaltest.post_reason('DTED geotransform wrong.') - return 'fail' + assert abs(gt[0] - (-80.004166666666663)) <= max_error and abs(gt[1] - 0.0083333333333333332) <= max_error and abs(gt[2] - 0) <= max_error and abs(gt[3] - 44.00416666666667) <= max_error and abs(gt[4] - 0) <= max_error and abs(gt[5] - (-0.0083333333333333332)) <= max_error, \ + 'DTED geotransform wrong.' prj = ds.GetProjection() - if prj != 'GEOGCS["WGS 84",DATUM["WGS_1984",SPHEROID["WGS 84",6378137,298.257223563,AUTHORITY["EPSG","7030"]],AUTHORITY["EPSG","6326"]],PRIMEM["Greenwich",0,AUTHORITY["EPSG","8901"]],UNIT["degree",0.0174532925199433,AUTHORITY["EPSG","9122"]],AUTHORITY["EPSG","4326"]]': - gdaltest.post_reason('Projection does not match expected:\n%s' % prj) - return 'fail' + assert prj == 'GEOGCS["WGS 84",DATUM["WGS_1984",SPHEROID["WGS 84",6378137,298.257223563,AUTHORITY["EPSG","7030"]],AUTHORITY["EPSG","6326"]],PRIMEM["Greenwich",0,AUTHORITY["EPSG","8901"]],UNIT["degree",0.0174532925199433,AUTHORITY["EPSG","9122"]],AUTHORITY["EPSG","4326"]]', \ + ('Projection does not match expected:\n%s' % prj) band1 = ds.GetRasterBand(1) - if band1.GetNoDataValue() != -32767: - gdaltest.post_reason('Grid NODATA value wrong or missing.') - return 'fail' + assert band1.GetNoDataValue() == -32767, 'Grid NODATA value wrong or missing.' - if band1.DataType != gdal.GDT_Int16: - gdaltest.post_reason('Data type is not Int16!') - return 'fail' - - return 'success' + assert band1.DataType == gdal.GDT_Int16, 'Data type is not Int16!' ############################################################################### # Create simple copy and check. -def dted_3(): +def test_dted_3(): tst = gdaltest.GDALTest('DTED', 'n43.dt0', 1, 49187) @@ -97,7 +85,7 @@ def dted_3(): # Read subwindow. Tests the tail recursion problem. -def dted_4(): +def test_dted_4(): tst = gdaltest.GDALTest('dted', 'n43.dt0', 1, 305, 5, 5, 5, 5) @@ -107,7 +95,7 @@ def dted_4(): # Test a DTED Level 1 (made from a DTED Level 0) -def dted_5(): +def test_dted_5(): driver = gdal.GetDriverByName("GTiff") ds = driver.Create('tmp/n43.dt1.tif', 1201, 1201, 1, gdal.GDT_Int16) @@ -120,18 +108,15 @@ def dted_5(): ds = gdal.Open('tmp/n43.dt1.tif') geotransform = ds.GetGeoTransform() for i in range(6): - if abs(geotransform[i] - ref_geotransform[i]) > 1e-10: - return 'fail' + assert abs(geotransform[i] - ref_geotransform[i]) <= 1e-10 ds = None - return 'success' - ############################################################################### # Test a DTED Level 2 (made from a DTED Level 0) -def dted_6(): +def test_dted_6(): driver = gdal.GetDriverByName("GTiff") ds = driver.Create('tmp/n43.dt2.tif', 3601, 3601, 1, gdal.GDT_Int16) @@ -144,18 +129,15 @@ def dted_6(): ds = gdal.Open('tmp/n43.dt2.tif') geotransform = ds.GetGeoTransform() for i in range(6): - if abs(geotransform[i] - ref_geotransform[i]) > 1e-10: - return 'fail' + assert abs(geotransform[i] - ref_geotransform[i]) <= 1e-10 ds = None - return 'success' - ############################################################################### # Test a WGS72 georeferenced DTED -def dted_7(): +def test_dted_7(): ds = gdal.Open('data/n43_wgs72.dt0') # a warning is issued @@ -163,21 +145,16 @@ def dted_7(): prj = ds.GetProjection() gdal.PopErrorHandler() - if gdal.GetLastErrorMsg() is None: - gdaltest.post_reason('An expected warning was not emitted') - return 'fail' + assert gdal.GetLastErrorMsg() is not None, 'An expected warning was not emitted' - if prj != 'GEOGCS["WGS 72",DATUM["WGS_1972",SPHEROID["WGS 72",6378135,298.26]],PRIMEM["Greenwich",0],UNIT["degree",0.0174532925199433],AUTHORITY["EPSG","4322"]]': - gdaltest.post_reason('Projection does not match expected:\n%s' % prj) - return 'fail' - - return 'success' + assert prj == 'GEOGCS["WGS 72",DATUM["WGS_1972",SPHEROID["WGS 72",6378135,298.26]],PRIMEM["Greenwich",0],UNIT["degree",0.0174532925199433],AUTHORITY["EPSG","4322"]]', \ + ('Projection does not match expected:\n%s' % prj) ############################################################################### # Test a file whose checksum is corrupted -def dted_8(): +def test_dted_8(): # this will enable DTED_VERIFY_CHECKSUM gdal.SetConfigOption('DTED_VERIFY_CHECKSUM', 'YES') @@ -191,23 +168,17 @@ def dted_8(): gdal.SetConfigOption('DTED_VERIFY_CHECKSUM', 'NO') - if gdal.GetLastErrorMsg() is None: - gdaltest.post_reason('An expected warning was not emitted') - return 'fail' + assert gdal.GetLastErrorMsg() is not None, 'An expected warning was not emitted' # 49187 is the checksum of data is the DTED is read without checking its checksum # so we should not get this value - if chksum == 49187: - gdaltest.post_reason('DTED_VERIFY_CHECKSUM=YES has had no effect!') - return 'fail' - - return 'success' + assert chksum != 49187, 'DTED_VERIFY_CHECKSUM=YES has had no effect!' ############################################################################### # Test a DTED Level 1 above latitude 50 (made from a DTED Level 0) -def dted_9(): +def test_dted_9(): ds = gdal.Open('data/n43.dt0') @@ -236,17 +207,13 @@ def dted_9(): band = dsDst.GetRasterBand(1) chksum = band.Checksum() - if chksum != 36542: - gdaltest.post_reason('Wrong checksum. Checksum found %d' % chksum) - return 'fail' - - return 'success' + assert chksum == 36542, ('Wrong checksum. Checksum found %d' % chksum) ############################################################################### # Test creating an in memory copy. -def dted_10(): +def test_dted_10(): tst = gdaltest.GDALTest('dted', 'n43.dt0', 1, 49187) return tst.testCreateCopy(vsimem=1) @@ -258,7 +225,7 @@ def dted_10(): # inverted. This was fixed in MIL-D-89020 Amendment 1, but some products may # be affected. -def dted_11(): +def test_dted_11(): ds = gdal.Open('data/n43_coord_inverted.dt0') @@ -266,46 +233,33 @@ def dted_11(): max_error = 0.000001 - if abs(gt[0] - (-80.004166666666663)) > max_error or abs(gt[1] - 0.0083333333333333332) > max_error \ - or abs(gt[2] - 0) > max_error or abs(gt[3] - 44.00416666666667) > max_error \ - or abs(gt[4] - 0) > max_error or abs(gt[5] - (-0.0083333333333333332)) > max_error: - gdaltest.post_reason('DTED geotransform wrong.') - return 'fail' + assert abs(gt[0] - (-80.004166666666663)) <= max_error and abs(gt[1] - 0.0083333333333333332) <= max_error and abs(gt[2] - 0) <= max_error and abs(gt[3] - 44.00416666666667) <= max_error and abs(gt[4] - 0) <= max_error and abs(gt[5] - (-0.0083333333333333332)) <= max_error, \ + 'DTED geotransform wrong.' prj = ds.GetProjection() - if prj != 'GEOGCS["WGS 84",DATUM["WGS_1984",SPHEROID["WGS 84",6378137,298.257223563,AUTHORITY["EPSG","7030"]],AUTHORITY["EPSG","6326"]],PRIMEM["Greenwich",0,AUTHORITY["EPSG","8901"]],UNIT["degree",0.0174532925199433,AUTHORITY["EPSG","9122"]],AUTHORITY["EPSG","4326"]]': - gdaltest.post_reason('Projection does not match expected:\n%s' % prj) - return 'fail' + assert prj == 'GEOGCS["WGS 84",DATUM["WGS_1984",SPHEROID["WGS 84",6378137,298.257223563,AUTHORITY["EPSG","7030"]],AUTHORITY["EPSG","6326"]],PRIMEM["Greenwich",0,AUTHORITY["EPSG","8901"]],UNIT["degree",0.0174532925199433,AUTHORITY["EPSG","9122"]],AUTHORITY["EPSG","4326"]]', \ + ('Projection does not match expected:\n%s' % prj) band1 = ds.GetRasterBand(1) - if band1.GetNoDataValue() != -32767: - gdaltest.post_reason('Grid NODATA value wrong or missing.') - return 'fail' + assert band1.GetNoDataValue() == -32767, 'Grid NODATA value wrong or missing.' - if band1.DataType != gdal.GDT_Int16: - gdaltest.post_reason('Data type is not Int16!') - return 'fail' - - return 'success' + assert band1.DataType == gdal.GDT_Int16, 'Data type is not Int16!' ############################################################################### # Test a DTED file that begins with a HDR record, and not directly the UHL record (#2951) -def dted_12(): +def test_dted_12(): ds = gdal.Open('data/w118n033_trunc.dt1') - if ds is None: - return 'fail' - - return 'success' + assert ds is not None ############################################################################### # Test a DTED file that has only a few (sequential) columns. Derived from # a real-world DTED file -def dted_13(): +def test_dted_13(): tst = gdaltest.GDALTest('dted', 'n43_partial_cols.dt0', 1, 56006) return tst.testOpen() @@ -315,7 +269,7 @@ def dted_13(): # case for now. -def dted_14(): +def test_dted_14(): tst = gdaltest.GDALTest('dted', 'n43_sparse_cols.dt0', 1, 56369) return tst.testOpen() @@ -324,7 +278,7 @@ def dted_14(): # Perform simple read test with GDAL_DTED_SINGLE_BLOCK = YES -def dted_15(): +def test_dted_15(): gdal.SetConfigOption('GDAL_DTED_SINGLE_BLOCK', 'YES') tst = gdaltest.GDALTest('dted', 'n43.dt0', 1, 49187) @@ -336,7 +290,7 @@ def dted_15(): # Cleanup. -def dted_cleanup(): +def test_dted_cleanup(): try: os.remove('tmp/n43.dt1.tif') os.remove('tmp/n43.dt1.aux.xml') @@ -349,33 +303,7 @@ def dted_cleanup(): os.remove('tmp/n43.dt2') except OSError: pass - return 'success' - - -gdaltest_list = [ - dted_1, - dted_2, - dted_3, - dted_4, - dted_5, - dted_6, - dted_7, - dted_8, - dted_9, - dted_10, - dted_11, - dted_12, - dted_13, - dted_14, - dted_15, - dted_cleanup -] - - -if __name__ == '__main__': + - gdaltest.setup_run('dted') - gdaltest.run_tests(gdaltest_list) - sys.exit(gdaltest.summarize()) diff --git a/autotest/gdrivers/e00grid.py b/autotest/gdrivers/e00grid.py index 7f34a7b0ed9b..b80797229e63 100755 --- a/autotest/gdrivers/e00grid.py +++ b/autotest/gdrivers/e00grid.py @@ -28,10 +28,8 @@ # DEALINGS IN THE SOFTWARE. ############################################################################### -import sys from osgeo import gdal -sys.path.append('../pymod') import gdaltest @@ -39,7 +37,7 @@ # Test a fake E00GRID dataset -def e00grid_1(): +def test_e00grid_1(): tst = gdaltest.GDALTest('E00GRID', 'fake_e00grid.e00', 1, 65359) expected_gt = [500000.0, 1000.0, 0.0, 4000000.0, 0.0, -1000.0] @@ -66,12 +64,10 @@ def e00grid_1(): if ret == 'success': ds = gdal.Open('data/fake_e00grid.e00') - if ds.GetRasterBand(1).GetNoDataValue() != -32767: - gdaltest.post_reason('did not get expected nodata value') - return 'fail' - if ds.GetRasterBand(1).GetUnitType() != 'ft': - gdaltest.post_reason('did not get expected nodata value') - return 'fail' + assert ds.GetRasterBand(1).GetNoDataValue() == -32767, \ + 'did not get expected nodata value' + assert ds.GetRasterBand(1).GetUnitType() == 'ft', \ + 'did not get expected nodata value' return ret @@ -79,7 +75,7 @@ def e00grid_1(): # Test a fake E00GRID dataset, compressed and with statistics -def e00grid_2(): +def test_e00grid_2(): tst = gdaltest.GDALTest('E00GRID', 'fake_e00grid_compressed.e00', 1, 65347) expected_gt = [500000.0, 1000.0, 0.0, 4000000.0, 0.0, -1000.0] @@ -109,40 +105,19 @@ def e00grid_2(): line0 = ds.ReadRaster(0, 0, 5, 1) ds.ReadRaster(0, 1, 5, 1) line2 = ds.ReadRaster(0, 2, 5, 1) - if line0 == line2: - gdaltest.post_reason('should not have gotten the same values') - return 'fail' + assert line0 != line2, 'should not have gotten the same values' ds.ReadRaster(0, 0, 5, 1) line2_bis = ds.ReadRaster(0, 2, 5, 1) - if line2 != line2_bis: - gdaltest.post_reason('did not get the same values for the same line') - return 'fail' - - if ds.GetRasterBand(1).GetMinimum() != 1: - gdaltest.post_reason('did not get expected minimum value') - print(ds.GetRasterBand(1).GetMinimum()) - return 'fail' - if ds.GetRasterBand(1).GetMaximum() != 50: - gdaltest.post_reason('did not get expected maximum value') - print(ds.GetRasterBand(1).GetMaximum()) - return 'fail' + assert line2 == line2_bis, 'did not get the same values for the same line' + + assert ds.GetRasterBand(1).GetMinimum() == 1, \ + 'did not get expected minimum value' + assert ds.GetRasterBand(1).GetMaximum() == 50, \ + 'did not get expected maximum value' stats = ds.GetRasterBand(1).GetStatistics(False, True) - if stats != [1.0, 50.0, 25.5, 24.5]: - gdaltest.post_reason('did not get expected statistics') - print(stats) - return 'fail' + assert stats == [1.0, 50.0, 25.5, 24.5], 'did not get expected statistics' return ret -gdaltest_list = [ - e00grid_1, - e00grid_2] - -if __name__ == '__main__': - - gdaltest.setup_run('e00grid') - - gdaltest.run_tests(gdaltest_list) - sys.exit(gdaltest.summarize()) diff --git a/autotest/gdrivers/ecrgtoc.py b/autotest/gdrivers/ecrgtoc.py index dd01513dd01a..cd8b9181ecdc 100755 --- a/autotest/gdrivers/ecrgtoc.py +++ b/autotest/gdrivers/ecrgtoc.py @@ -29,18 +29,17 @@ ############################################################################### import os -import sys from osgeo import gdal -sys.path.append('../pymod') import gdaltest +import pytest ############################################################################### # Basic test -def ecrgtoc_1(): +def test_ecrgtoc_1(): toc_xml = """<Table_of_Contents> <file_header file_status="new"> @@ -81,8 +80,7 @@ def ecrgtoc_1(): gdal.VSIFCloseL(f) ds = gdal.Open('/vsimem/TOC.xml') - if ds is None: - return 'fail' + assert ds is not None expected_gt = [-85.43147208121826, 0.00059486040609137061, 0.0, 33.166986564299428, 0.0, -0.00044985604606525913] gt = ds.GetGeoTransform() @@ -92,16 +90,10 @@ def ecrgtoc_1(): print(gt) wkt = ds.GetProjectionRef() - if wkt.find('WGS 84') == -1: - gdaltest.post_reason('did not get expected SRS') - print(wkt) - return 'fail' + assert wkt.find('WGS 84') != -1, 'did not get expected SRS' filelist = ds.GetFileList() - if len(filelist) != 3: - gdaltest.post_reason('did not get expected filelist') - print(filelist) - return 'fail' + assert len(filelist) == 3, 'did not get expected filelist' ds2 = gdal.GetDriverByName('NITF').Create('/vsimem/clfc/2/000000009s0013.lf2', 2304, 2304, 3, options=['ICORDS=G', 'TRE=GEOLOB=000605184000800256-85.43147208122+33.16698656430']) @@ -120,18 +112,13 @@ def ecrgtoc_1(): ds = None - if cs != 5966: - gdaltest.post_reason('bad checksum') - print(cs) - return 'fail' - - return 'success' + assert cs == 5966, 'bad checksum' ############################################################################### # Test overviews -def ecrgtoc_2(): +def test_ecrgtoc_2(): ds = gdal.Open('/vsimem/TOC.xml') ds.BuildOverviews('NEAR', [2]) @@ -140,20 +127,15 @@ def ecrgtoc_2(): ds = gdal.Open('/vsimem/TOC.xml') filelist = ds.GetFileList() - if len(filelist) != 4: - gdaltest.post_reason('did not get expected filelist') - print(filelist) - return 'fail' + assert len(filelist) == 4, 'did not get expected filelist' ds = None - return 'success' - ############################################################################### # Test opening subdataset -def ecrgtoc_3(): +def test_ecrgtoc_3(): # Try different errors for name in ['ECRG_TOC_ENTRY:', @@ -171,22 +153,15 @@ def ecrgtoc_3(): gdal.PushErrorHandler() ds = gdal.Open(name) gdal.PopErrorHandler() - if ds is not None: - gdaltest.post_reason('fail') - print(name) - return 'fail' + assert ds is None, name # Legacy syntax ds = gdal.Open('ECRG_TOC_ENTRY:ProductTitle:DiscId:/vsimem/TOC.xml') - if ds is None: - gdaltest.post_reason('fail') - return 'fail' + assert ds is not None ds = None ds = gdal.Open('ECRG_TOC_ENTRY:ProductTitle:DiscId:1_500_K:/vsimem/TOC.xml') - if ds is None: - gdaltest.post_reason('fail') - return 'fail' + assert ds is not None ds = None gdal.Unlink('/vsimem/TOC.xml') @@ -194,13 +169,11 @@ def ecrgtoc_3(): gdal.Unlink('/vsimem/clfc/2/000000009s0013.lf2') gdal.Unlink('/vsimem/clfc/2/000000009t0013.lf2') - return 'success' - ############################################################################### # Test dataset with 3 subdatasets -def ecrgtoc_4(): +def test_ecrgtoc_4(): toc_xml = """<Table_of_Contents> <file_header file_status="new"> @@ -255,85 +228,61 @@ def ecrgtoc_4(): gdal.VSIFCloseL(f) ds = gdal.Open('/vsimem/TOC.xml') - if ds is None: - return 'fail' - if ds.RasterCount != 0: - gdaltest.post_reason('bad raster count') - return 'fail' + assert ds is not None + assert ds.RasterCount == 0, 'bad raster count' expected_gt = (-85.43147208121826, 0.00059486040609137061, 0.0, 37.241379310344833, 0.0, -0.00044985604606525913) gt = ds.GetGeoTransform() for i in range(6): - if abs(gt[i] - expected_gt[i]) > 1e-10: - gdaltest.post_reason('did not get expected geotransform') - print(gt) - return 'fail' + assert abs(gt[i] - expected_gt[i]) <= 1e-10, 'did not get expected geotransform' wkt = ds.GetProjectionRef() - if wkt.find('WGS 84') == -1: - gdaltest.post_reason('did not get expected SRS') - print(wkt) - return 'fail' + assert wkt.find('WGS 84') != -1, 'did not get expected SRS' filelist = ds.GetFileList() - if len(filelist) != 4: - gdaltest.post_reason('did not get expected filelist') - print(filelist) - return 'fail' + assert len(filelist) == 4, 'did not get expected filelist' subdatasets = ds.GetMetadata('SUBDATASETS') if len(subdatasets) != 6: - gdaltest.post_reason('did not get expected subdatasets') print(filelist) - return 'fail' + pytest.fail('did not get expected subdatasets') ds = None ds = gdal.Open('ECRG_TOC_ENTRY:ProductTitle:DiscId:1_500_K:/vsimem/TOC.xml') - if ds is None: - gdaltest.post_reason('did not get subdataset') - return 'fail' + assert ds is not None, 'did not get subdataset' ds = None ds = gdal.Open('ECRG_TOC_ENTRY:ProductTitle:DiscId:1_1000_K:/vsimem/TOC.xml') - if ds is None: - gdaltest.post_reason('did not get subdataset') - return 'fail' + assert ds is not None, 'did not get subdataset' ds = None ds = gdal.Open('ECRG_TOC_ENTRY:ProductTitle:DiscId2:1_500_K:/vsimem/TOC.xml') - if ds is None: - gdaltest.post_reason('did not get subdataset') - return 'fail' + assert ds is not None, 'did not get subdataset' ds = None gdal.PushErrorHandler('CPLQuietErrorHandler') ds = gdal.Open('ECRG_TOC_ENTRY:ProductTitle:DiscId:/vsimem/TOC.xml') gdal.PopErrorHandler() - if ds is not None: - gdaltest.post_reason('should not have got subdataset') - return 'fail' + assert ds is None, 'should not have got subdataset' gdal.Unlink('/vsimem/TOC.xml') - return 'success' - ############################################################################### -def ecrgtoc_online_1(): +def test_ecrgtoc_online_1(): if not gdaltest.download_file('http://www.falconview.org/trac/FalconView/downloads/17', 'ECRG_Sample.zip'): - return 'skip' + pytest.skip() try: os.stat('tmp/cache/ECRG_Sample.zip') except OSError: - return 'skip' + pytest.skip() ds = gdal.Open('/vsizip/tmp/cache/ECRG_Sample.zip/ECRG_Sample/EPF/TOC.xml') - if ds is None: - return 'fail' + assert ds is not None expected_gt = (-85.43147208121826, 0.00059486040609137061, 0.0, 35.239923224568145, 0.0, -0.00044985604606525913) gt = ds.GetGeoTransform() @@ -343,31 +292,10 @@ def ecrgtoc_online_1(): print(gt) wkt = ds.GetProjectionRef() - if wkt.find('WGS 84') == -1: - gdaltest.post_reason('did not get expected SRS') - print(wkt) - return 'fail' + assert wkt.find('WGS 84') != -1, 'did not get expected SRS' filelist = ds.GetFileList() - if len(filelist) != 7: - gdaltest.post_reason('did not get expected filelist') - print(filelist) - return 'fail' - - return 'success' - - -gdaltest_list = [ - ecrgtoc_1, - ecrgtoc_2, - ecrgtoc_3, - ecrgtoc_4, - ecrgtoc_online_1] - -if __name__ == '__main__': + assert len(filelist) == 7, 'did not get expected filelist' - gdaltest.setup_run('ecrgtoc') - gdaltest.run_tests(gdaltest_list) - sys.exit(gdaltest.summarize()) diff --git a/autotest/gdrivers/ecw.py b/autotest/gdrivers/ecw.py index d20ce05f75d3..48763caa6d5a 100755 --- a/autotest/gdrivers/ecw.py +++ b/autotest/gdrivers/ecw.py @@ -39,9 +39,9 @@ from osgeo import gdal from osgeo import osr -sys.path.append('../pymod') import gdaltest +import pytest ############################################################################### @@ -50,9 +50,9 @@ def has_write_support(): if hasattr(gdaltest, 'b_ecw_has_write_support'): return gdaltest.b_ecw_has_write_support gdaltest.b_ecw_has_write_support = False - if ecw_1() != 'success': + if test_ecw_1() != 'success': return False - if ecw_3() == 'success': + if test_ecw_3() == 'success': gdaltest.b_ecw_has_write_support = True try: os.remove('tmp/jrc_out.ecw') @@ -64,16 +64,15 @@ def has_write_support(): # -def ecw_init(): +def test_ecw_init(): gdaltest.deregister_all_jpeg2000_drivers_but('JP2ECW') - return 'success' ############################################################################### # Verify we have the driver. -def ecw_1(): +def test_ecw_1(): gdaltest.ecw_drv = gdal.GetDriverByName('ECW') gdaltest.jp2ecw_drv = gdal.GetDriverByName('JP2ECW') @@ -103,16 +102,15 @@ def ecw_1(): # we set ECW to not resolve projection and datum strings to get 3.x behavior. gdal.SetConfigOption("ECW_DO_NOT_RESOLVE_DATUM_PROJECTION", "YES") - return 'success' ############################################################################### # Verify various information about our test image. -def ecw_2(): +def test_ecw_2(): if gdaltest.ecw_drv is None: - return 'skip' + pytest.skip() ds = gdal.Open('data/jrc.ecw') @@ -126,66 +124,50 @@ def ecw_2(): (mean, stddev) = ds.GetRasterBand(1).ComputeBandStats() - if abs(mean - exp_mean) > 0.5 or abs(stddev - exp_stddev) > 0.5: - gdaltest.post_reason('mean/stddev of (%g,%g) diffs from expected(%g,%g)' % (mean, stddev, exp_mean, exp_stddev)) - return 'fail' + assert abs(mean - exp_mean) <= 0.5 and abs(stddev - exp_stddev) <= 0.5, \ + ('mean/stddev of (%g,%g) diffs from expected(%g,%g)' % (mean, stddev, exp_mean, exp_stddev)) geotransform = ds.GetGeoTransform() - if abs(geotransform[0] - 467498.5) > 0.1 \ - or abs(geotransform[1] - 16.5475) > 0.001 \ - or abs(geotransform[2] - 0) > 0.001 \ - or abs(geotransform[3] - 5077883.2825) > 0.1 \ - or abs(geotransform[4] - 0) > 0.001 \ - or abs(geotransform[5] - -16.5475) > 0.001: - print(geotransform) - gdaltest.post_reason('geotransform differs from expected') - return 'fail' - - return 'success' + assert abs(geotransform[0] - 467498.5) <= 0.1 and abs(geotransform[1] - 16.5475) <= 0.001 and abs(geotransform[2] - 0) <= 0.001 and abs(geotransform[3] - 5077883.2825) <= 0.1 and abs(geotransform[4] - 0) <= 0.001 and abs(geotransform[5] - -16.5475) <= 0.001, \ + 'geotransform differs from expected' ############################################################################### # Verify that an write the imagery out to a new file. -def ecw_3(): +def test_ecw_3(): if gdaltest.ecw_drv is None or gdaltest.ecw_write == 0: - return 'skip' + pytest.skip() ds = gdal.Open('data/jrc.ecw') out_ds = gdaltest.ecw_drv.CreateCopy('tmp/jrc_out.ecw', ds, options=['TARGET=75']) if out_ds is not None: version = out_ds.GetMetadataItem('VERSION') - if version != '2': - gdaltest.post_reason('bad VERSION') - return 'fail' + assert version == '2', 'bad VERSION' ds = None if out_ds is None: if gdal.GetLastErrorMsg().find('ECW_ENCODE_KEY') >= 0: gdaltest.ecw_write = 0 - return 'skip' + pytest.skip() gdaltest.b_ecw_has_write_support = True - return 'success' - ############################################################################### # Verify various information about our generated image. -def ecw_4(): +def test_ecw_4(): if gdaltest.ecw_drv is None or gdaltest.ecw_write == 0: - return 'skip' + pytest.skip() gdal.Unlink('tmp/jrc_out.ecw.aux.xml') ds = gdal.Open('tmp/jrc_out.ecw') version = ds.GetMetadataItem('VERSION') - if version != '2': - gdaltest.post_reason('bad VERSION') - return 'fail' + assert version == '2', 'bad VERSION' if gdaltest.ecw_drv.major_version == 3: (exp_mean, exp_stddev) = (140.290, 66.6303) @@ -197,53 +179,38 @@ def ecw_4(): (mean, stddev) = ds.GetRasterBand(1).ComputeBandStats() - if abs(mean - exp_mean) > 1.5 or abs(stddev - exp_stddev) > 0.5: - gdaltest.post_reason('mean/stddev of (%g,%g) diffs from expected(%g,%g)' % (mean, stddev, exp_mean, exp_stddev)) - return 'fail' + assert abs(mean - exp_mean) <= 1.5 and abs(stddev - exp_stddev) <= 0.5, \ + ('mean/stddev of (%g,%g) diffs from expected(%g,%g)' % (mean, stddev, exp_mean, exp_stddev)) geotransform = ds.GetGeoTransform() - if abs(geotransform[0] - 467498.5) > 0.1 \ - or abs(geotransform[1] - 16.5475) > 0.001 \ - or abs(geotransform[2] - 0) > 0.001 \ - or abs(geotransform[3] - 5077883.2825) > 0.1 \ - or abs(geotransform[4] - 0) > 0.001 \ - or abs(geotransform[5] - -16.5475) > 0.001: - print(geotransform) - gdaltest.post_reason('geotransform differs from expected') - return 'fail' + assert abs(geotransform[0] - 467498.5) <= 0.1 and abs(geotransform[1] - 16.5475) <= 0.001 and abs(geotransform[2] - 0) <= 0.001 and abs(geotransform[3] - 5077883.2825) <= 0.1 and abs(geotransform[4] - 0) <= 0.001 and abs(geotransform[5] - -16.5475) <= 0.001, \ + 'geotransform differs from expected' ds = None - return 'success' - ############################################################################### # Now try writing a JPEG2000 compressed version of the same with the ECW driver -def ecw_5(): +def test_ecw_5(): if gdaltest.jp2ecw_drv is None or gdaltest.ecw_write == 0: - return 'skip' + pytest.skip() ds = gdal.Open('data/small.vrt') ds_out = gdaltest.jp2ecw_drv.CreateCopy('tmp/ecw_5.jp2', ds, options=['TARGET=75']) - if ds_out.GetDriver().ShortName != "JP2ECW": - return 'fail' + assert ds_out.GetDriver().ShortName == "JP2ECW" version = ds_out.GetMetadataItem('VERSION') - if version != '1': - gdaltest.post_reason('bad VERSION') - return 'fail' + assert version == '1', 'bad VERSION' ds = None - return 'success' - ############################################################################### # Verify various information about our generated image. -def ecw_6(): +def test_ecw_6(): if gdaltest.jp2ecw_drv is None or gdaltest.ecw_write == 0: - return 'skip' + pytest.skip() ds = gdal.Open('tmp/ecw_5.jp2') @@ -255,109 +222,81 @@ def ecw_6(): # The difference in the stddev is outrageously large between win32 and # Linux, but I don't know why. - if abs(mean - exp_mean) > 1.5 or abs(stddev - exp_stddev) > 6: - gdaltest.post_reason('mean/stddev of (%g,%g) diffs from ' + assert abs(mean - exp_mean) <= 1.5 and abs(stddev - exp_stddev) <= 6, \ + ('mean/stddev of (%g,%g) diffs from ' 'expected(%g,%g)' % (mean, stddev, exp_mean, exp_stddev)) - return 'fail' (mean, stddev) = ds.GetRasterBand(2).ComputeBandStats() # The difference in the stddev is outrageously large between win32 and # Linux, but I don't know why. - if abs(mean - exp_mean) > 1.0 or abs(stddev - exp_stddev) > 6: - gdaltest.post_reason('mean/stddev of (%g,%g) diffs from ' + assert abs(mean - exp_mean) <= 1.0 and abs(stddev - exp_stddev) <= 6, \ + ('mean/stddev of (%g,%g) diffs from ' 'expected(%g,%g)' % (mean, stddev, exp_mean, exp_stddev)) - return 'fail' geotransform = ds.GetGeoTransform() - if abs(geotransform[0] - 440720) > 0.1 \ - or abs(geotransform[1] - 60) > 0.001 \ - or abs(geotransform[2] - 0) > 0.001 \ - or abs(geotransform[3] - 3751320) > 0.1 \ - or abs(geotransform[4] - 0) > 0.001 \ - or abs(geotransform[5] - -60) > 0.001: - print(geotransform) - gdaltest.post_reason('geotransform differs from expected') - return 'fail' + assert abs(geotransform[0] - 440720) <= 0.1 and abs(geotransform[1] - 60) <= 0.001 and abs(geotransform[2] - 0) <= 0.001 and abs(geotransform[3] - 3751320) <= 0.1 and abs(geotransform[4] - 0) <= 0.001 and abs(geotransform[5] - -60) <= 0.001, \ + 'geotransform differs from expected' prj = ds.GetProjectionRef() - if prj.find('UTM') == -1 or prj.find('NAD27') == -1 \ - or prj.find('one 11') == -1: - print(prj) - gdaltest.post_reason('Coordinate system not UTM 11, NAD27?') - return 'fail' + assert (not (prj.find('UTM') == -1 or prj.find('NAD27') == -1 \ + or prj.find('one 11') == -1)), 'Coordinate system not UTM 11, NAD27?' ds = None - return 'success' - ############################################################################### # Write the same image to NITF. -def ecw_7(): +def test_ecw_7(): if gdaltest.jp2ecw_drv is None or gdaltest.ecw_write == 0: - return 'skip' + pytest.skip() ds = gdal.Open('data/small.vrt') drv = gdal.GetDriverByName('NITF') drv.CreateCopy('tmp/ecw_7.ntf', ds, options=['IC=C8', 'TARGET=75'], strict=0) ds = None - return 'success' - ############################################################################### # Verify various information about our generated image. -def ecw_8(): +def test_ecw_8(): if gdaltest.jp2ecw_drv is None or gdaltest.ecw_write == 0: - return 'skip' + pytest.skip() ds = gdal.Open('tmp/ecw_7.ntf') (exp_mean, exp_stddev) = (145.57, 43.1712) (mean, stddev) = ds.GetRasterBand(1).ComputeBandStats() - if abs(mean - exp_mean) > 1.0 or abs(stddev - exp_stddev) > 1.0: - gdaltest.post_reason('mean/stddev of (%g,%g) diffs from expected(%g,%g)' % (mean, stddev, exp_mean, exp_stddev)) - return 'fail' + assert abs(mean - exp_mean) <= 1.0 and abs(stddev - exp_stddev) <= 1.0, \ + ('mean/stddev of (%g,%g) diffs from expected(%g,%g)' % (mean, stddev, exp_mean, exp_stddev)) geotransform = ds.GetGeoTransform() - if abs(geotransform[0] - 440720) > 0.1 \ - or abs(geotransform[1] - 60) > 0.001 \ - or abs(geotransform[2] - 0) > 0.001 \ - or abs(geotransform[3] - 3751320) > 0.1 \ - or abs(geotransform[4] - 0) > 0.001 \ - or abs(geotransform[5] - -60) > 0.001: - print(geotransform) - gdaltest.post_reason('geotransform differs from expected') - return 'fail' + assert abs(geotransform[0] - 440720) <= 0.1 and abs(geotransform[1] - 60) <= 0.001 and abs(geotransform[2] - 0) <= 0.001 and abs(geotransform[3] - 3751320) <= 0.1 and abs(geotransform[4] - 0) <= 0.001 and abs(geotransform[5] - -60) <= 0.001, \ + 'geotransform differs from expected' prj = ds.GetProjectionRef() - if prj.find('UTM Zone 11') == -1 or prj.find('WGS 84') == -1: - gdaltest.post_reason('Coordinate system not UTM 11, WGS 84?') - print(prj) - return 'fail' + assert not (prj.find('UTM Zone 11') == -1 or prj.find('WGS 84') == -1), \ + 'Coordinate system not UTM 11, WGS 84?' ds = None - return 'success' - ############################################################################### # Try writing 16bit JP2 file directly using Create(). -def ecw_9(): +def test_ecw_9(): if gdaltest.jp2ecw_drv is None or gdaltest.ecw_write == 0: - return 'skip' + pytest.skip() # This always crashes on Frank's machine - some bug in old sdk. if os.getenv('USER') == 'warmerda' and gdaltest.ecw_drv.major_version == 3: - return 'skip' + pytest.skip() ds = gdaltest.jp2ecw_drv.Create('tmp/ecw9.jp2', 200, 100, 1, gdal.GDT_Int16, options=['TARGET=75']) @@ -372,51 +311,37 @@ def ecw_9(): buf_type=gdal.GDT_Int16) ds = None - return 'success' - ############################################################################### # Verify previous 16bit file. -def ecw_10(): +def test_ecw_10(): if gdaltest.jp2ecw_drv is None or gdaltest.ecw_write == 0: - return 'skip' + pytest.skip() # This always crashes on Frank's machine - some bug in old sdk. if os.getenv('USER') == 'warmerda' and gdaltest.ecw_drv.major_version == 3: - return 'skip' + pytest.skip() ds = gdal.Open('tmp/ecw9.jp2') (exp_mean, exp_stddev) = (98.49, 57.7129) (mean, stddev) = ds.GetRasterBand(1).ComputeBandStats() - if abs(mean - exp_mean) > 1.1 or abs(stddev - exp_stddev) > 0.1: - gdaltest.post_reason('mean/stddev of (%g,%g) diffs from expected(%g,%g)' % (mean, stddev, exp_mean, exp_stddev)) - return 'fail' + assert abs(mean - exp_mean) <= 1.1 and abs(stddev - exp_stddev) <= 0.1, \ + ('mean/stddev of (%g,%g) diffs from expected(%g,%g)' % (mean, stddev, exp_mean, exp_stddev)) geotransform = ds.GetGeoTransform() - if abs(geotransform[0] - 100) > 0.1 \ - or abs(geotransform[1] - 0.1) > 0.001 \ - or abs(geotransform[2] - 0) > 0.001 \ - or abs(geotransform[3] - 30) > 0.1 \ - or abs(geotransform[4] - 0) > 0.001 \ - or abs(geotransform[5] - -0.1) > 0.001: - print(geotransform) - gdaltest.post_reason('geotransform differs from expected') - return 'fail' - - # should check the projection, but I'm too lazy just now. - - return 'success' + assert abs(geotransform[0] - 100) <= 0.1 and abs(geotransform[1] - 0.1) <= 0.001 and abs(geotransform[2] - 0) <= 0.001 and abs(geotransform[3] - 30) <= 0.1 and abs(geotransform[4] - 0) <= 0.001 and abs(geotransform[5] - -0.1) <= 0.001, \ + 'geotransform differs from expected' ############################################################################### # Test direct creation of an NITF/JPEG2000 file. -def ecw_11(): +def test_ecw_11(): if gdaltest.jp2ecw_drv is None or gdaltest.ecw_write == 0: - return 'skip' + pytest.skip() drv = gdal.GetDriverByName('NITF') ds = drv.Create('tmp/test_11.ntf', 200, 100, 3, gdal.GDT_Byte, @@ -437,44 +362,30 @@ def ecw_11(): ds = None - return 'success' - ############################################################################### # Verify previous file -def ecw_12(): +def test_ecw_12(): if gdaltest.jp2ecw_drv is None or gdaltest.ecw_write == 0: - return 'skip' + pytest.skip() ds = gdal.Open('tmp/test_11.ntf') geotransform = ds.GetGeoTransform() - if abs(geotransform[0] - 100) > 0.1 \ - or abs(geotransform[1] - 0.1) > 0.001 \ - or abs(geotransform[2] - 0) > 0.001 \ - or abs(geotransform[3] - 30.0) > 0.1 \ - or abs(geotransform[4] - 0) > 0.001 \ - or abs(geotransform[5] - -0.1) > 0.001: - print(geotransform) - gdaltest.post_reason('geotransform differs from expected') - return 'fail' - - if ds.GetRasterBand(1).GetRasterColorInterpretation() != gdal.GCI_BlueBand: - gdaltest.post_reason('Got wrong color interpretation.') - return 'fail' - - if ds.GetRasterBand(2).GetRasterColorInterpretation() != gdal.GCI_GreenBand: - gdaltest.post_reason('Got wrong color interpretation.') - return 'fail' - - if ds.GetRasterBand(3).GetRasterColorInterpretation() != gdal.GCI_RedBand: - gdaltest.post_reason('Got wrong color interpretation.') - return 'fail' + assert abs(geotransform[0] - 100) <= 0.1 and abs(geotransform[1] - 0.1) <= 0.001 and abs(geotransform[2] - 0) <= 0.001 and abs(geotransform[3] - 30.0) <= 0.1 and abs(geotransform[4] - 0) <= 0.001 and abs(geotransform[5] - -0.1) <= 0.001, \ + 'geotransform differs from expected' - ds = None + assert ds.GetRasterBand(1).GetRasterColorInterpretation() == gdal.GCI_BlueBand, \ + 'Got wrong color interpretation.' - return 'success' + assert ds.GetRasterBand(2).GetRasterColorInterpretation() == gdal.GCI_GreenBand, \ + 'Got wrong color interpretation.' + + assert ds.GetRasterBand(3).GetRasterColorInterpretation() == gdal.GCI_RedBand, \ + 'Got wrong color interpretation.' + + ds = None ############################################################################### # This is intended to verify that the ECWDataset::RasterIO() special case @@ -483,9 +394,9 @@ def ecw_12(): # type and select an altered band list. -def ecw_13(): +def test_ecw_13(): if gdaltest.jp2ecw_drv is None: - return 'skip' + pytest.skip() ds = gdal.Open('data/rgb16_ecwsdk.jp2') @@ -503,68 +414,50 @@ def ecw_13(): ds.GetRasterBand(3).Checksum()) ds = None - if checksums != (19253, 17848, 19127): - gdaltest.post_reason('Expected checksums do match expected checksums') - print(checksums) - return 'fail' - - return 'success' + assert checksums == (19253, 17848, 19127), \ + 'Expected checksums do match expected checksums' ############################################################################### # Write out image with GCPs. -def ecw_14(): +def test_ecw_14(): if gdaltest.jp2ecw_drv is None or gdaltest.ecw_write == 0: - return 'skip' + pytest.skip() ds = gdal.Open('data/rgb_gcp.vrt') gdaltest.jp2ecw_drv.CreateCopy('tmp/rgb_gcp.jp2', ds) ds = None - - return 'success' ############################################################################### # Verify various information about our generated image. -def ecw_15(): +def test_ecw_15(): if gdaltest.jp2ecw_drv is None or gdaltest.ecw_write == 0: - return 'skip' + pytest.skip() ds = gdal.Open('tmp/rgb_gcp.jp2') gcp_srs = ds.GetGCPProjection() - if gcp_srs[:6] != 'GEOGCS' \ + assert (not (gcp_srs[:6] != 'GEOGCS' \ or gcp_srs.find('WGS') == -1 \ - or gcp_srs.find('84') == -1: - gdaltest.post_reason('GCP Projection not retained.') - print(gcp_srs) - return 'fail' + or gcp_srs.find('84') == -1)), 'GCP Projection not retained.' gcps = ds.GetGCPs() - if len(gcps) != 4 \ - or gcps[1].GCPPixel != 0 \ - or gcps[1].GCPLine != 50 \ - or gcps[1].GCPX != 0 \ - or gcps[1].GCPY != 50 \ - or gcps[1].GCPZ != 0: - gdaltest.post_reason('GCPs wrong.') - print(gcps) - return 'fail' + assert len(gcps) == 4 and gcps[1].GCPPixel == 0 and gcps[1].GCPLine == 50 and gcps[1].GCPX == 0 and gcps[1].GCPY == 50 and gcps[1].GCPZ == 0, \ + 'GCPs wrong.' ds = None - return 'success' - ############################################################################### # Open byte.jp2 -def ecw_16(): +def test_ecw_16(): if gdaltest.jp2ecw_drv is None: - return 'skip' + pytest.skip() srs = """PROJCS["NAD27 / UTM zone 11N", GEOGCS["NAD27", @@ -594,14 +487,13 @@ def ecw_16(): # Open int16.jp2 -def ecw_17(): +def test_ecw_17(): if gdaltest.jp2ecw_drv is None: - return 'skip' + pytest.skip() if gdaltest.ecw_drv.major_version == 4: - gdaltest.post_reason('4.x SDK gets unreliable results for jp2') - return 'skip' + pytest.skip('4.x SDK gets unreliable results for jp2') ds = gdal.Open('data/int16.jp2') ds_ref = gdal.Open('data/int16.tif') @@ -612,20 +504,16 @@ def ecw_17(): ds_ref = None # Quite a bit of difference... - if maxdiff > 6: - gdaltest.post_reason('Image too different from reference') - return 'fail' - - return 'success' + assert maxdiff <= 6, 'Image too different from reference' ############################################################################### # Open byte.jp2.gz (test use of the VSIL API) -def ecw_18(): +def test_ecw_18(): if gdaltest.jp2ecw_drv is None: - return 'skip' + pytest.skip() srs = """PROJCS["NAD27 / UTM zone 11N", GEOGCS["NAD27", @@ -655,49 +543,40 @@ def ecw_18(): # Test a JPEG2000 with the 3 bands having 13bit depth and the 4th one 1 bit -def ecw_19(): +def test_ecw_19(): if gdaltest.jp2ecw_drv is None: - return 'skip' + pytest.skip() ds = gdal.Open('data/3_13bit_and_1bit.jp2') expected_checksums = [64570, 57277, 56048, 61292] for i in range(4): - if ds.GetRasterBand(i + 1).Checksum() != expected_checksums[i]: - gdaltest.post_reason('unexpected checksum (%d) for band %d' % (expected_checksums[i], i + 1)) - return 'fail' - - if ds.GetRasterBand(1).DataType != gdal.GDT_UInt16: - gdaltest.post_reason('unexpected data type') - return 'fail' + assert ds.GetRasterBand(i + 1).Checksum() == expected_checksums[i], \ + ('unexpected checksum (%d) for band %d' % (expected_checksums[i], i + 1)) - return 'success' + assert ds.GetRasterBand(1).DataType == gdal.GDT_UInt16, 'unexpected data type' ############################################################################### # Confirm that we have an overview for this image and that the statistics # are as expected. -def ecw_20(): +def test_ecw_20(): if gdaltest.ecw_drv is None: - return 'skip' + pytest.skip() ds = gdal.Open('data/jrc.ecw') band = ds.GetRasterBand(1) - if band.GetOverviewCount() != 1: - gdaltest.post_reason('did not get expected number of overview') - return 'fail' + assert band.GetOverviewCount() == 1, 'did not get expected number of overview' # Both requests should go *exactly* to the same code path data_subsampled = band.ReadRaster(0, 0, 400, 400, 200, 200) data_overview = band.GetOverview(0).ReadRaster(0, 0, 200, 200) - if data_subsampled != data_overview: - gdaltest.post_reason('inconsistent overview behaviour') - return 'fail' + assert data_subsampled == data_overview, 'inconsistent overview behaviour' if gdaltest.ecw_drv.major_version == 3: (exp_mean, exp_stddev) = (141.644, 67.2186) @@ -708,13 +587,10 @@ def ecw_20(): (exp_mean, exp_stddev) = (140.889, 62.742) (mean, stddev) = band.GetOverview(0).ComputeBandStats() - if abs(mean - exp_mean) > 0.5 or abs(stddev - exp_stddev) > 0.5: - gdaltest.post_reason('mean/stddev of (%g,%g) diffs from ' + assert abs(mean - exp_mean) <= 0.5 and abs(stddev - exp_stddev) <= 0.5, \ + ('mean/stddev of (%g,%g) diffs from ' 'expected(%g,%g)' % (mean, stddev, exp_mean, exp_stddev)) - return 'fail' - - return 'success' ############################################################################### # This test is intended to go through an optimized data path (likely @@ -723,10 +599,10 @@ def ecw_20(): # line by line. -def ecw_21(): +def test_ecw_21(): if gdaltest.ecw_drv is None: - return 'skip' + pytest.skip() ds = gdal.Open('data/jrc.ecw') mem_ds = gdal.GetDriverByName('MEM').CreateCopy('xxxyyy', ds, options=['INTERLEAVE=PIXEL']) @@ -742,43 +618,35 @@ def ecw_21(): (mean, stddev) = mem_ds.GetRasterBand(1).ComputeBandStats() - if abs(mean - exp_mean) > 0.5 or abs(stddev - exp_stddev) > 0.5: - gdaltest.post_reason('mean/stddev of (%g,%g) diffs from expected(%g,%g)' % (mean, stddev, exp_mean, exp_stddev)) - return 'fail' - - return 'success' + assert abs(mean - exp_mean) <= 0.5 and abs(stddev - exp_stddev) <= 0.5, \ + ('mean/stddev of (%g,%g) diffs from expected(%g,%g)' % (mean, stddev, exp_mean, exp_stddev)) ############################################################################### # This tests reading of georeferencing and coordinate system from within an # ECW file. -def ecw_22(): +def test_ecw_22(): if gdaltest.ecw_drv is None: - return 'skip' + pytest.skip() ds = gdal.Open('data/spif83.ecw') expected_wkt = """PROJCS["L2CAL6M",GEOGCS["NAD83",DATUM["North_American_Datum_1983",SPHEROID["GRS 1980",6378137,298.257222101,AUTHORITY["EPSG","7019"]],TOWGS84[0,0,0,0,0,0,0],AUTHORITY["EPSG","6269"]],PRIMEM["Greenwich",0,AUTHORITY["EPSG","8901"]],UNIT["degree",0.0174532925199433,AUTHORITY["EPSG","9108"]],AXIS["Lat",NORTH],AXIS["Long",EAST],AUTHORITY["EPSG","4269"]],PROJECTION["Lambert_Conformal_Conic_2SP"],PARAMETER["standard_parallel_1",32.78333330780953],PARAMETER["standard_parallel_2",33.88333332087654],PARAMETER["latitude_of_origin",32.16666668243202],PARAMETER["central_meridian",-116.2499999745946],PARAMETER["false_easting",2000000],PARAMETER["false_northing",500000],UNIT["Meter",1]]""" wkt = ds.GetProjectionRef() - if wkt != expected_wkt: - print(wkt) - gdaltest.post_reason('did not get expected SRS.') - return 'fail' - - return 'success' + assert wkt == expected_wkt, 'did not get expected SRS.' ############################################################################### # This tests overriding the coordinate system from an .aux.xml file, while # preserving the ecw derived georeferencing. -def ecw_23(): +def test_ecw_23(): if gdaltest.ecw_drv is None: - return 'skip' + pytest.skip() shutil.copyfile('data/spif83.ecw', 'tmp/spif83.ecw') shutil.copyfile('data/spif83_hidden.ecw.aux.xml', 'tmp/spif83.ecw.aux.xml') @@ -788,17 +656,11 @@ def ecw_23(): expected_wkt = """PROJCS["OSGB 1936 / British National Grid",GEOGCS["OSGB 1936",DATUM["OSGB_1936",SPHEROID["Airy 1830",6377563.396,299.3249646,AUTHORITY["EPSG","7001"]],TOWGS84[446.448,-125.157,542.06,0.15,0.247,0.842,-20.489],AUTHORITY["EPSG","6277"]],PRIMEM["Greenwich",0,AUTHORITY["EPSG","8901"]],UNIT["degree",0.0174532925199433,AUTHORITY["EPSG","9122"]],AUTHORITY["EPSG","4277"]],UNIT["metre",1,AUTHORITY["EPSG","9001"]],PROJECTION["Transverse_Mercator"],PARAMETER["latitude_of_origin",49],PARAMETER["central_meridian",-2],PARAMETER["scale_factor",0.9996012717],PARAMETER["false_easting",400000],PARAMETER["false_northing",-100000],AUTHORITY["EPSG","27700"],AXIS["Easting",EAST],AXIS["Northing",NORTH]]""" wkt = ds.GetProjectionRef() - if wkt != expected_wkt: - print(wkt) - gdaltest.post_reason('did not get expected SRS.') - return 'fail' + assert wkt == expected_wkt, 'did not get expected SRS.' gt = ds.GetGeoTransform() expected_gt = (6138559.5576418638, 195.5116973254697, 0.0, 2274798.7836679211, 0.0, -198.32414964918371) - if gt != expected_gt: - print(gt) - gdaltest.post_reason('did not get expected geotransform.') - return 'fail' + assert gt == expected_gt, 'did not get expected geotransform.' try: os.remove('tmp/spif83.ecw') @@ -806,16 +668,15 @@ def ecw_23(): except OSError: pass - return 'success' - + ############################################################################### # Test that we can alter geotransform on existing ECW -def ecw_24(): +def test_ecw_24(): if gdaltest.ecw_drv is None: - return 'skip' + pytest.skip() shutil.copyfile('data/spif83.ecw', 'tmp/spif83.ecw') try: @@ -829,43 +690,36 @@ def ecw_24(): os.remove('tmp/spif83.ecw') except OSError: pass - return 'skip' + pytest.skip() gt = [1, 2, 0, 3, 0, -4] ds.SetGeoTransform(gt) ds = None - try: + with pytest.raises(OSError): os.stat('tmp/spif83.ecw.aux.xml') - gdaltest.post_reason('fail') - return 'fail' - except OSError: - pass + ds = gdal.Open('tmp/spif83.ecw') got_gt = ds.GetGeoTransform() ds = None for i in range(6): - if abs(gt[i] - got_gt[i]) > 1e-5: - gdaltest.post_reason('fail') - print(got_gt) - return 'fail' + assert abs(gt[i] - got_gt[i]) <= 1e-5 try: os.remove('tmp/spif83.ecw') except OSError: pass - return 'success' - + ############################################################################### # Test that we can alter projection info on existing ECW (through SetProjection()) -def ecw_25(): +def test_ecw_25(): if gdaltest.ecw_drv is None: - return 'skip' + pytest.skip() shutil.copyfile('data/spif83.ecw', 'tmp/spif83.ecw') try: @@ -883,19 +737,16 @@ def ecw_25(): os.remove('tmp/spif83.ecw') except OSError: pass - return 'skip' + pytest.skip() sr = osr.SpatialReference() sr.ImportFromERM(proj, datum, units) wkt = sr.ExportToWkt() ds.SetProjection(wkt) ds = None - try: + with pytest.raises(OSError): os.stat('tmp/spif83.ecw.aux.xml') - gdaltest.post_reason('fail') - return 'fail' - except OSError: - pass + ds = gdal.Open('tmp/spif83.ecw') got_proj = ds.GetMetadataItem("PROJ", "ECW") @@ -904,39 +755,26 @@ def ecw_25(): got_wkt = ds.GetProjectionRef() ds = None - if got_proj != proj: - gdaltest.post_reason('fail') - print(got_proj) - return 'fail' - if got_datum != datum: - gdaltest.post_reason('fail') - print(got_datum) - return 'fail' - if got_units != units: - gdaltest.post_reason('fail') - print(got_units) - return 'fail' - - if wkt != got_wkt: - gdaltest.post_reason('fail') - print(got_wkt) - return 'fail' + assert got_proj == proj + assert got_datum == datum + assert got_units == units + + assert wkt == got_wkt try: os.remove('tmp/spif83.ecw') except OSError: pass - return 'success' - + ############################################################################### # Test that we can alter projection info on existing ECW (through SetMetadataItem()) -def ecw_26(): +def test_ecw_26(): if gdaltest.ecw_drv is None: - return 'skip' + pytest.skip() shutil.copyfile('data/spif83.ecw', 'tmp/spif83.ecw') try: @@ -954,18 +792,15 @@ def ecw_26(): os.remove('tmp/spif83.ecw') except OSError: pass - return 'skip' + pytest.skip() ds.SetMetadataItem("PROJ", proj, "ECW") ds.SetMetadataItem("DATUM", datum, "ECW") ds.SetMetadataItem("UNITS", units, "ECW") ds = None - try: + with pytest.raises(OSError): os.stat('tmp/spif83.ecw.aux.xml') - gdaltest.post_reason('fail') - return 'fail' - except OSError: - pass + ds = gdal.Open('tmp/spif83.ecw') got_proj = ds.GetMetadataItem("PROJ", "ECW") @@ -974,69 +809,47 @@ def ecw_26(): got_wkt = ds.GetProjectionRef() ds = None - if got_proj != proj: - gdaltest.post_reason('fail') - print(proj) - return 'fail' - if got_datum != datum: - gdaltest.post_reason('fail') - print(datum) - return 'fail' - if got_units != units: - gdaltest.post_reason('fail') - print(units) - return 'fail' + assert got_proj == proj + assert got_datum == datum + assert got_units == units sr = osr.SpatialReference() sr.ImportFromERM(proj, datum, units) wkt = sr.ExportToWkt() - if wkt != got_wkt: - gdaltest.post_reason('fail') - print(got_wkt) - return 'fail' + assert wkt == got_wkt try: os.remove('tmp/spif83.ecw') except OSError: pass - return 'success' - + ############################################################################### # Check that we can use .j2w world files (#4651) -def ecw_27(): +def test_ecw_27(): if gdaltest.jp2ecw_drv is None or gdaltest.ecw_write == 0: - return 'skip' + pytest.skip() ds = gdal.Open('data/byte_without_geotransform.jp2') geotransform = ds.GetGeoTransform() - if abs(geotransform[0] - 440720) > 0.1 \ - or abs(geotransform[1] - 60) > 0.001 \ - or abs(geotransform[2] - 0) > 0.001 \ - or abs(geotransform[3] - 3751320) > 0.1 \ - or abs(geotransform[4] - 0) > 0.001 \ - or abs(geotransform[5] - -60) > 0.001: - print(geotransform) - gdaltest.post_reason('geotransform differs from expected') - return 'fail' + assert abs(geotransform[0] - 440720) <= 0.1 and abs(geotransform[1] - 60) <= 0.001 and abs(geotransform[2] - 0) <= 0.001 and abs(geotransform[3] - 3751320) <= 0.1 and abs(geotransform[4] - 0) <= 0.001 and abs(geotransform[5] - -60) <= 0.001, \ + 'geotransform differs from expected' ds = None - return 'success' - ############################################################################### # Check picking use case -def ecw_28(): +def test_ecw_28(): if gdaltest.ecw_drv is None: - return 'skip' + pytest.skip() x = y = 50 @@ -1054,19 +867,14 @@ def ecw_28(): struct.unpack('B' * 3, multiband_data) struct.unpack('B' * 3, data1 + data2 + data3) - # Due to the nature of ECW, reading one band or several bands does not give - # the same results. - - return 'success' - ############################################################################### # Test supersampling -def ecw_29(): +def test_ecw_29(): if gdaltest.ecw_drv is None: - return 'skip' + pytest.skip() ds = gdal.Open('data/jrc.ecw') data_b1 = ds.GetRasterBand(1).ReadRaster(0, 0, 400, 400) @@ -1134,10 +942,10 @@ def ecw_29(): # Test IReadBlock() -def ecw_30(): +def test_ecw_30(): if gdaltest.ecw_drv is None: - return 'skip' + pytest.skip() ds = gdal.Open('data/jrc.ecw') (blockxsize, blockysize) = ds.GetRasterBand(1).GetBlockSize() @@ -1145,22 +953,19 @@ def ecw_30(): data_readblock = ds.GetRasterBand(1).ReadBlock(0, 0) ds = None - if data_readraster != data_readblock: - return 'fail' - - return 'success' + assert data_readraster == data_readblock ############################################################################### # Test async reader interface ( SDK >= 4.x ) -def ecw_31(): +def test_ecw_31(): if gdaltest.ecw_drv is None: - return 'skip' + pytest.skip() if gdaltest.ecw_drv.major_version < 4: - return 'skip' + pytest.skip() ds = gdal.Open('data/jrc.ecw') ref_buf = ds.ReadRaster(0, 0, ds.RasterXSize, ds.RasterYSize) @@ -1176,15 +981,13 @@ def ecw_31(): elif result[0] != gdal.GARIO_ERROR: continue else: - gdaltest.post_reason('error occurred') ds.EndAsyncReader(asyncreader) - return 'fail' + pytest.fail('error occurred') if result != [gdal.GARIO_COMPLETE, 0, 0, ds.RasterXSize, ds.RasterYSize]: - gdaltest.post_reason('wrong return values for GetNextUpdatedRegion()') print(result) ds.EndAsyncReader(asyncreader) - return 'fail' + pytest.fail('wrong return values for GetNextUpdatedRegion()') async_buf = asyncreader.GetBuffer() @@ -1192,11 +995,7 @@ def ecw_31(): asyncreader = None ds = None - if async_buf != ref_buf: - gdaltest.post_reason('async_buf != ref_buf') - return 'fail' - - return 'success' + assert async_buf == ref_buf, 'async_buf != ref_buf' ############################################################################### # ECW SDK 3.3 has a bug with the ECW format when we query the @@ -1204,17 +1003,15 @@ def ecw_31(): # It ignores the content of panBandMap. (#4234) -def ecw_32(): +def test_ecw_32(): if gdaltest.ecw_drv is None: - return 'skip' + pytest.skip() ds = gdal.Open('data/jrc.ecw') data_123 = ds.ReadRaster(0, 0, ds.RasterXSize, ds.RasterYSize, band_list=[1, 2, 3]) data_321 = ds.ReadRaster(0, 0, ds.RasterXSize, ds.RasterYSize, band_list=[3, 2, 1]) - if data_123 == data_321: - gdaltest.post_reason('failure') - return 'fail' + assert data_123 != data_321 vrt_ds = gdal.Open("""<VRTDataset rasterXSize="400" rasterYSize="400"> <VRTRasterBand dataType="Byte" band="1"> @@ -1238,20 +1035,16 @@ def ecw_32(): </VRTDataset>""") data_vrt = vrt_ds.ReadRaster(0, 0, ds.RasterXSize, ds.RasterYSize, band_list=[1, 2, 3]) - if data_321 != data_vrt: - gdaltest.post_reason('failure') - return 'fail' - - return 'success' + assert data_321 == data_vrt ############################################################################### # Test heuristics that detect successive band reading pattern -def ecw_33(): +def test_ecw_33(): if gdaltest.ecw_drv is None: - return 'skip' + pytest.skip() ds = gdal.Open('data/jrc.ecw') multiband_data = ds.ReadRaster(100, 100, 50, 50) @@ -1285,31 +1078,25 @@ def ecw_33(): ds = None - if data1_1 != data1_2 or data2_1 != data2_2 or data3_1 != data3_2: - gdaltest.post_reason('fail') - return 'fail' + assert data1_1 == data1_2 and data2_1 == data2_2 and data3_1 == data3_2 # When heuristics is ON, returned values should be the same as # 3-band at a time reading import struct tab1 = struct.unpack('B' * 3 * 50 * 50, multiband_data) tab2 = struct.unpack('B' * 3 * 50 * 50, data1_1 + data2_1 + data3_2) - if tab1 != tab2: - gdaltest.post_reason('fail') - return 'fail' + assert tab1 == tab2 ds = None - return 'success' - ############################################################################### # Check bugfix for #5262 -def ecw_33_bis(): +def test_ecw_33_bis(): if gdaltest.ecw_drv is None: - return 'skip' + pytest.skip() ds = gdal.Open('data/jrc.ecw') data_ref = ds.ReadRaster(0, 0, 50, 50) @@ -1331,30 +1118,22 @@ def ecw_33_bis(): # not consistent. (which seems to be no longer the case with more recent # SDK such as 5.0) for i in range(50 * 50): - if data1[i * 4] != data_ref[i]: - gdaltest.post_reason('fail') - return 'fail' - if data2[i * 4] != data_ref[50 * 50 + i]: - gdaltest.post_reason('fail') - return 'fail' - if data3[i * 4] != data_ref[2 * 50 * 50 + i]: - gdaltest.post_reason('fail') - return 'fail' + assert data1[i * 4] == data_ref[i] + assert data2[i * 4] == data_ref[50 * 50 + i] + assert data3[i * 4] == data_ref[2 * 50 * 50 + i] ds = None - return 'success' - ############################################################################### # Verify that an write the imagery out to a new ecw file. Source file is 16 bit. -def ecw_34(): +def test_ecw_34(): if gdaltest.ecw_drv is None or gdaltest.ecw_write == 0: - return 'skip' + pytest.skip() if gdaltest.ecw_drv.major_version < 5: - return 'skip' + pytest.skip() ds = gdal.GetDriverByName('MEM').Create('MEM:::', 128, 128, 1, gdal.GDT_UInt16) ds.GetRasterBand(1).Fill(65535) @@ -1368,22 +1147,16 @@ def ecw_34(): version = ds.GetMetadataItem('VERSION') ds = None - if got_data != ref_data: - return 'fail' - if version != '3': - gdaltest.post_reason('bad VERSION') - print(version) - return 'fail' - - return 'success' + assert got_data == ref_data + assert version == '3', 'bad VERSION' ############################################################################### # Verify that an write the imagery out to a new JP2 file. Source file is 16 bit. -def ecw_35(): +def test_ecw_35(): if gdaltest.jp2ecw_drv is None or gdaltest.ecw_write == 0: - return 'skip' + pytest.skip() ds = gdal.GetDriverByName('MEM').Create('MEM:::', 128, 128, 1, gdal.GDT_UInt16) ds.GetRasterBand(1).Fill(65535) @@ -1396,20 +1169,18 @@ def ecw_35(): got_data = ds.GetRasterBand(1).ReadRaster(0, 0, 128, 128, buf_type=gdal.GDT_UInt16) ds = None - if got_data != ref_data: - return 'fail' - return 'success' + assert got_data == ref_data ############################################################################### # Make sure that band descriptions are preserved for version 3 ECW files. -def ecw_36(): +def test_ecw_36(): if gdaltest.ecw_drv is None or gdaltest.ecw_write == 0: - return 'skip' + pytest.skip() if gdaltest.ecw_drv.major_version < 5: - return 'skip' + pytest.skip() vrt_ds = gdal.Open("""<VRTDataset rasterXSize="400" rasterYSize="400"> <VRTRasterBand dataType="Byte" band="1"> @@ -1437,85 +1208,69 @@ def ecw_36(): dswr = gdaltest.ecw_drv.CreateCopy('tmp/jrc312.ecw', vrt_ds, options=['ECW_FORMAT_VERSION=3', 'TARGET=75']) - if dswr.GetRasterBand(1).GetColorInterpretation() != gdal.GCI_BlueBand: - print('Band 1 color interpretation should be Blue but is : ' + gdal.GetColorInterpretationName(dswr.GetRasterBand(1).GetColorInterpretation())) - return 'fail' - if dswr.GetRasterBand(2).GetColorInterpretation() != gdal.GCI_RedBand: - print('Band 2 color interpretation should be Red but is : ' + gdal.GetColorInterpretationName(dswr.GetRasterBand(2).GetColorInterpretation())) - return 'fail' - if dswr.GetRasterBand(3).GetColorInterpretation() != gdal.GCI_GreenBand: - print('Band 3 color interpretation should be Green but is : ' + gdal.GetColorInterpretationName(dswr.GetRasterBand(3).GetColorInterpretation())) - return 'fail' + assert dswr.GetRasterBand(1).GetColorInterpretation() == gdal.GCI_BlueBand, \ + ('Band 1 color interpretation should be Blue but is : ' + gdal.GetColorInterpretationName(dswr.GetRasterBand(1).GetColorInterpretation())) + assert dswr.GetRasterBand(2).GetColorInterpretation() == gdal.GCI_RedBand, \ + ('Band 2 color interpretation should be Red but is : ' + gdal.GetColorInterpretationName(dswr.GetRasterBand(2).GetColorInterpretation())) + assert dswr.GetRasterBand(3).GetColorInterpretation() == gdal.GCI_GreenBand, \ + ('Band 3 color interpretation should be Green but is : ' + gdal.GetColorInterpretationName(dswr.GetRasterBand(3).GetColorInterpretation())) dswr = None dsr = gdal.Open('tmp/jrc312.ecw') - if dsr.GetRasterBand(1).GetColorInterpretation() != gdal.GCI_BlueBand: - print('Band 1 color interpretation should be Blue but is : ' + gdal.GetColorInterpretationName(dsr.GetRasterBand(1).GetColorInterpretation())) - return 'fail' - if dsr.GetRasterBand(2).GetColorInterpretation() != gdal.GCI_RedBand: - print('Band 2 color interpretation should be Red but is : ' + gdal.GetColorInterpretationName(dsr.GetRasterBand(2).GetColorInterpretation())) - return 'fail' - if dsr.GetRasterBand(3).GetColorInterpretation() != gdal.GCI_GreenBand: - print('Band 3 color interpretation should be Green but is : ' + gdal.GetColorInterpretationName(dsr.GetRasterBand(3).GetColorInterpretation())) - return 'fail' + assert dsr.GetRasterBand(1).GetColorInterpretation() == gdal.GCI_BlueBand, \ + ('Band 1 color interpretation should be Blue but is : ' + gdal.GetColorInterpretationName(dsr.GetRasterBand(1).GetColorInterpretation())) + assert dsr.GetRasterBand(2).GetColorInterpretation() == gdal.GCI_RedBand, \ + ('Band 2 color interpretation should be Red but is : ' + gdal.GetColorInterpretationName(dsr.GetRasterBand(2).GetColorInterpretation())) + assert dsr.GetRasterBand(3).GetColorInterpretation() == gdal.GCI_GreenBand, \ + ('Band 3 color interpretation should be Green but is : ' + gdal.GetColorInterpretationName(dsr.GetRasterBand(3).GetColorInterpretation())) dsr = None - - return 'success' ############################################################################### # Make sure that band descriptions are preserved for version 2 ECW files when # color space set implicitly to sRGB. -def ecw_37(): +def test_ecw_37(): if gdaltest.ecw_drv is None or gdaltest.ecw_write == 0: - return 'skip' + pytest.skip() if gdaltest.ecw_drv.major_version < 5: - return 'skip' + pytest.skip() ds = gdal.Open("data/jrc.ecw") dswr = gdaltest.ecw_drv.CreateCopy('tmp/jrc123.ecw', ds, options=['ECW_FORMAT_VERSION=3', 'TARGET=75']) - if dswr.GetRasterBand(1).GetColorInterpretation() != gdal.GCI_RedBand: - print('Band 1 color interpretation should be Red but is : ' + gdal.GetColorInterpretationName(dswr.GetRasterBand(1).GetColorInterpretation())) - return 'fail' - if dswr.GetRasterBand(2).GetColorInterpretation() != gdal.GCI_GreenBand: - print('Band 2 color interpretation should be Green but is : ' + gdal.GetColorInterpretationName(dswr.GetRasterBand(2).GetColorInterpretation())) - return 'fail' - if dswr.GetRasterBand(3).GetColorInterpretation() != gdal.GCI_BlueBand: - print('Band 3 color interpretation should be Blue but is : ' + gdal.GetColorInterpretationName(dswr.GetRasterBand(3).GetColorInterpretation())) - return 'fail' + assert dswr.GetRasterBand(1).GetColorInterpretation() == gdal.GCI_RedBand, \ + ('Band 1 color interpretation should be Red but is : ' + gdal.GetColorInterpretationName(dswr.GetRasterBand(1).GetColorInterpretation())) + assert dswr.GetRasterBand(2).GetColorInterpretation() == gdal.GCI_GreenBand, \ + ('Band 2 color interpretation should be Green but is : ' + gdal.GetColorInterpretationName(dswr.GetRasterBand(2).GetColorInterpretation())) + assert dswr.GetRasterBand(3).GetColorInterpretation() == gdal.GCI_BlueBand, \ + ('Band 3 color interpretation should be Blue but is : ' + gdal.GetColorInterpretationName(dswr.GetRasterBand(3).GetColorInterpretation())) dswr = None dsr = gdal.Open('tmp/jrc123.ecw') - if dsr.GetRasterBand(1).GetColorInterpretation() != gdal.GCI_RedBand: - print('Band 1 color interpretation should be Red but is : ' + gdal.GetColorInterpretationName(dsr.GetRasterBand(1).GetColorInterpretation())) - return 'fail' - if dsr.GetRasterBand(2).GetColorInterpretation() != gdal.GCI_GreenBand: - print('Band 2 color interpretation should be Green but is : ' + gdal.GetColorInterpretationName(dsr.GetRasterBand(2).GetColorInterpretation())) - return 'fail' - if dsr.GetRasterBand(3).GetColorInterpretation() != gdal.GCI_BlueBand: - print('Band 3 color interpretation should be Blue but is : ' + gdal.GetColorInterpretationName(dsr.GetRasterBand(3).GetColorInterpretation())) - return 'fail' + assert dsr.GetRasterBand(1).GetColorInterpretation() == gdal.GCI_RedBand, \ + ('Band 1 color interpretation should be Red but is : ' + gdal.GetColorInterpretationName(dsr.GetRasterBand(1).GetColorInterpretation())) + assert dsr.GetRasterBand(2).GetColorInterpretation() == gdal.GCI_GreenBand, \ + ('Band 2 color interpretation should be Green but is : ' + gdal.GetColorInterpretationName(dsr.GetRasterBand(2).GetColorInterpretation())) + assert dsr.GetRasterBand(3).GetColorInterpretation() == gdal.GCI_BlueBand, \ + ('Band 3 color interpretation should be Blue but is : ' + gdal.GetColorInterpretationName(dsr.GetRasterBand(3).GetColorInterpretation())) dsr = None - return 'success' - ############################################################################### # Check opening unicode files. -def ecw_38(): +def test_ecw_38(): if gdaltest.ecw_drv is None: - return 'skip' + pytest.skip() gdaltest.ecw_38_fname = '' if version_info >= (3, 0, 0): @@ -1525,7 +1280,7 @@ def ecw_38(): fname = gdaltest.ecw_38_fname if gdaltest.ecw_drv.major_version < 4: - return 'skip' + pytest.skip() shutil.copyfile('data/jrc.ecw', fname) @@ -1539,22 +1294,18 @@ def ecw_38(): ds_ref = None # Quite a bit of difference... - if maxdiff > 0: - gdaltest.post_reason('Image too different from reference') - return 'fail' - - return 'success' + assert maxdiff <= 0, 'Image too different from reference' ############################################################################### # Check writing histograms. -def ecw_39(): +def test_ecw_39(): if gdaltest.ecw_drv is None or gdaltest.ecw_write == 0: - return 'skip' + pytest.skip() if gdaltest.ecw_drv.major_version < 5: - return 'skip' + pytest.skip() ds = gdal.Open('data/jrc.ecw') @@ -1570,30 +1321,24 @@ def ecw_39(): result = (hist == ds.GetRasterBand(1).GetDefaultHistogram(force=0)) ds = None - if not result: - gdaltest.post_reason('Default histogram written incorrectly') - return 'fail' - - return 'success' + assert result, 'Default histogram written incorrectly' ############################################################################### # Check reading a ECW v3 file -def ecw_40(): +def test_ecw_40(): if gdaltest.ecw_drv is None: - return 'skip' + pytest.skip() ds = gdal.Open('data/stefan_full_rgba_ecwv3_meta.ecw') if ds is None: if gdaltest.ecw_drv.major_version < 5: if gdal.GetLastErrorMsg().find('requires ECW SDK 5.0') >= 0: - return 'skip' - gdaltest.post_reason('explicit error message expected') - return 'fail' - gdaltest.post_reason('fail') - return 'fail' + pytest.skip() + pytest.fail('explicit error message expected') + pytest.fail() expected_md = [ ('CLOCKWISE_ROTATION_DEG', '0.000000'), @@ -1616,31 +1361,22 @@ def ecw_40(): got_md = ds.GetMetadata() for (key, value) in expected_md: - if key not in got_md or got_md[key] != value: - gdaltest.post_reason('fail') - print(key) - print(got_md[key]) - return 'fail' + assert key in got_md and got_md[key] == value expected_cs_list = [28760, 59071, 54087, 22499] for i in range(4): got_cs = ds.GetRasterBand(i + 1).Checksum() - if got_cs != expected_cs_list[i]: - gdaltest.post_reason('fail') - print(expected_cs_list[i]) - print(got_cs) - return 'fail' - - return 'success' + assert got_cs == expected_cs_list[i] + ############################################################################### # Check generating statistics & histogram for a ECW v3 file -def ecw_41(): +def test_ecw_41(): if gdaltest.ecw_drv is None or gdaltest.ecw_drv.major_version < 5: - return 'skip' + pytest.skip() shutil.copy('data/stefan_full_rgba_ecwv3_meta.ecw', 'tmp/stefan_full_rgba_ecwv3_meta.ecw') try: @@ -1651,67 +1387,38 @@ def ecw_41(): ds = gdal.Open('tmp/stefan_full_rgba_ecwv3_meta.ecw') # Check that no statistics is already included in the file - if ds.GetRasterBand(1).GetMinimum() is not None: - gdaltest.post_reason('fail') - return 'fail' - if ds.GetRasterBand(1).GetMaximum() is not None: - gdaltest.post_reason('fail') - return 'fail' - if ds.GetRasterBand(1).GetStatistics(1, 0) != [0.0, 0.0, 0.0, -1.0]: - gdaltest.post_reason('fail') - return 'fail' - if ds.GetRasterBand(1).GetDefaultHistogram(force=0) is not None: - gdaltest.post_reason('fail') - return 'fail' + assert ds.GetRasterBand(1).GetMinimum() is None + assert ds.GetRasterBand(1).GetMaximum() is None + assert ds.GetRasterBand(1).GetStatistics(1, 0) == [0.0, 0.0, 0.0, -1.0] + assert ds.GetRasterBand(1).GetDefaultHistogram(force=0) is None # Now compute the stats stats = ds.GetRasterBand(1).GetStatistics(0, 1) expected_stats = [0.0, 255.0, 21.662427983539093, 51.789457392268119] for i in range(4): - if abs(stats[i] - expected_stats[i]) > 1: - gdaltest.post_reason('fail') - print(stats) - print(expected_stats) - return 'fail' + assert abs(stats[i] - expected_stats[i]) <= 1 ds = None # Check that there's no .aux.xml file - try: + with pytest.raises(OSError): os.stat('tmp/stefan_full_rgba_ecwv3_meta.ecw.aux.xml') - gdaltest.post_reason('fail') - return 'fail' - except OSError: - pass + ds = gdal.Open('tmp/stefan_full_rgba_ecwv3_meta.ecw') - if ds.GetRasterBand(1).GetMinimum() != 0: - gdaltest.post_reason('fail') - print(ds.GetRasterBand(1).GetMinimum()) - return 'fail' - if ds.GetRasterBand(1).GetMaximum() != 255: - gdaltest.post_reason('fail') - print(ds.GetRasterBand(1).GetMaximum()) - return 'fail' + assert ds.GetRasterBand(1).GetMinimum() == 0 + assert ds.GetRasterBand(1).GetMaximum() == 255 stats = ds.GetRasterBand(1).GetStatistics(0, 0) expected_stats = [0.0, 255.0, 21.662427983539093, 51.789457392268119] for i in range(4): - if abs(stats[i] - expected_stats[i]) > 1: - gdaltest.post_reason('fail') - print(stats[i]) - print(expected_stats[i]) - return 'fail' + assert abs(stats[i] - expected_stats[i]) <= 1 ds = None ds = gdal.Open('tmp/stefan_full_rgba_ecwv3_meta.ecw') # And compute the histogram got_hist = ds.GetRasterBand(1).GetDefaultHistogram() expected_hist = (-0.5, 255.5, 256, [1006, 16106, 548, 99, 13, 24, 62, 118, 58, 125, 162, 180, 133, 146, 70, 81, 84, 97, 90, 60, 79, 70, 85, 77, 73, 63, 60, 64, 56, 69, 63, 73, 70, 72, 61, 66, 40, 52, 65, 44, 62, 54, 56, 55, 63, 51, 47, 39, 58, 44, 36, 43, 47, 45, 54, 28, 40, 41, 37, 36, 33, 31, 28, 34, 19, 32, 19, 23, 23, 33, 16, 34, 32, 54, 29, 33, 40, 37, 27, 34, 24, 29, 26, 21, 22, 24, 25, 19, 29, 22, 24, 14, 20, 20, 29, 28, 13, 19, 21, 19, 19, 21, 13, 19, 13, 14, 22, 15, 13, 26, 10, 13, 13, 14, 10, 17, 15, 19, 11, 18, 11, 14, 8, 12, 20, 12, 17, 10, 15, 15, 16, 14, 11, 7, 7, 10, 8, 12, 7, 8, 14, 7, 9, 12, 4, 6, 12, 5, 5, 4, 11, 8, 4, 8, 7, 10, 11, 6, 7, 5, 6, 8, 10, 10, 7, 5, 3, 5, 5, 6, 4, 10, 7, 6, 8, 4, 6, 6, 4, 6, 6, 7, 10, 4, 5, 2, 5, 6, 1, 1, 2, 6, 2, 1, 7, 4, 1, 3, 3, 2, 6, 2, 3, 3, 3, 3, 5, 5, 4, 2, 3, 2, 1, 3, 5, 5, 4, 1, 1, 2, 5, 10, 5, 9, 3, 5, 3, 5, 4, 5, 4, 4, 6, 7, 9, 17, 13, 15, 14, 13, 20, 18, 16, 27, 35, 53, 60, 51, 46, 40, 38, 50, 66, 36, 45, 13]) - if got_hist != expected_hist: - gdaltest.post_reason('fail') - print(got_hist) - print(expected_hist) - return 'fail' + assert got_hist == expected_hist ds = None # Remove the .aux.xml file @@ -1721,40 +1428,26 @@ def ecw_41(): pass ds = gdal.Open('tmp/stefan_full_rgba_ecwv3_meta.ecw') - if ds.GetRasterBand(1).GetMinimum() != 0: - gdaltest.post_reason('fail') - print(ds.GetRasterBand(1).GetMinimum()) - return 'fail' - if ds.GetRasterBand(1).GetMaximum() != 255: - gdaltest.post_reason('fail') - print(ds.GetRasterBand(1).GetMaximum()) - return 'fail' + assert ds.GetRasterBand(1).GetMinimum() == 0 + assert ds.GetRasterBand(1).GetMaximum() == 255 got_hist = ds.GetRasterBand(1).GetDefaultHistogram(force=0) - if got_hist != expected_hist: - gdaltest.post_reason('fail') - print(got_hist) - print(expected_hist) - return 'fail' + assert got_hist == expected_hist ds = None # Check that there's no .aux.xml file - try: + with pytest.raises(OSError): os.stat('tmp/stefan_full_rgba_ecwv3_meta.ecw.aux.xml') - gdaltest.post_reason('fail') - return 'fail' - except OSError: - pass - - return 'success' + + ############################################################################### # Test setting/unsetting file metadata of a ECW v3 file -def ecw_42(): +def test_ecw_42(): if gdaltest.ecw_drv is None or gdaltest.ecw_drv.major_version < 5: - return 'skip' + pytest.skip() shutil.copy('data/stefan_full_rgba_ecwv3_meta.ecw', 'tmp/stefan_full_rgba_ecwv3_meta.ecw') try: @@ -1778,22 +1471,15 @@ def ecw_42(): ds = None # Check that there's no .aux.xml file - try: + with pytest.raises(OSError): os.stat('tmp/stefan_full_rgba_ecwv3_meta.ecw.aux.xml') - gdaltest.post_reason('fail') - return 'fail' - except OSError: - pass + # Check item values ds = gdal.Open('tmp/stefan_full_rgba_ecwv3_meta.ecw') got_md = ds.GetMetadata() for item in md: - if got_md[item] != md[item]: - gdaltest.post_reason('fail') - print(got_md[item]) - print(md[item]) - return 'fail' + assert got_md[item] == md[item] ds = None # Test unsetting all the stuff @@ -1813,45 +1499,32 @@ def ecw_42(): ds = None # Check that there's no .aux.xml file - try: + with pytest.raises(OSError): os.stat('tmp/stefan_full_rgba_ecwv3_meta.ecw.aux.xml') - gdaltest.post_reason('fail') - return 'fail' - except OSError: - pass + # Check item values ds = gdal.Open('tmp/stefan_full_rgba_ecwv3_meta.ecw') got_md = ds.GetMetadata() for item in md: - if item in got_md and item != 'FILE_METADATA_ACQUISITION_DATE': - gdaltest.post_reason('fail') - print(got_md[item]) - print(md[item]) - return 'fail' + assert item not in got_md or item == 'FILE_METADATA_ACQUISITION_DATE', md[item] ds = None - return 'success' - ############################################################################### # Test auto-promotion of 1bit alpha band to 8bit # Note: only works on reversible files like this one -def ecw_43(): +def test_ecw_43(): if gdaltest.jp2ecw_drv is None: - return 'skip' + pytest.skip() ds = gdal.Open('data/stefan_full_rgba_alpha_1bit.jp2') fourth_band = ds.GetRasterBand(4) - if fourth_band.GetMetadataItem('NBITS', 'IMAGE_STRUCTURE') is not None: - return 'fail' + assert fourth_band.GetMetadataItem('NBITS', 'IMAGE_STRUCTURE') is None got_cs = fourth_band.Checksum() - if got_cs != 8527: - gdaltest.post_reason('fail') - print(got_cs) - return 'fail' + assert got_cs == 8527 jp2_bands_data = ds.ReadRaster(0, 0, ds.RasterXSize, ds.RasterYSize) jp2_fourth_band_data = fourth_band.ReadRaster(0, 0, ds.RasterXSize, ds.RasterYSize) fourth_band.ReadRaster(0, 0, ds.RasterXSize, ds.RasterYSize, int(ds.RasterXSize / 16), int(ds.RasterYSize / 16)) @@ -1864,37 +1537,26 @@ def ecw_43(): # gtiff_fourth_band_subsampled_data = fourth_band.ReadRaster(0,0,ds.RasterXSize,ds.RasterYSize,ds.RasterXSize/16,ds.RasterYSize/16) tmp_ds = None gdal.GetDriverByName('GTiff').Delete('/vsimem/ecw_43.tif') - if got_cs != 8527: - gdaltest.post_reason('fail') - print(got_cs) - return 'fail' + assert got_cs == 8527 - if jp2_bands_data != gtiff_bands_data: - gdaltest.post_reason('fail') - return 'fail' + assert jp2_bands_data == gtiff_bands_data - if jp2_fourth_band_data != gtiff_fourth_band_data: - gdaltest.post_reason('fail') - return 'fail' + assert jp2_fourth_band_data == gtiff_fourth_band_data ds = gdal.OpenEx('data/stefan_full_rgba_alpha_1bit.jp2', open_options=['1BIT_ALPHA_PROMOTION=NO']) fourth_band = ds.GetRasterBand(4) - if fourth_band.GetMetadataItem('NBITS', 'IMAGE_STRUCTURE') != '1': - gdaltest.post_reason('fail') - return 'fail' - - return 'success' + assert fourth_band.GetMetadataItem('NBITS', 'IMAGE_STRUCTURE') == '1' ############################################################################### # Test metadata retrieval from JP2 file -def ecw_44(): +def test_ecw_44(): if gdaltest.jp2ecw_drv is None: - return 'skip' + pytest.skip() if gdaltest.ecw_drv.major_version < 5 or (gdaltest.ecw_drv.major_version == 5 and gdaltest.ecw_drv.minor_version < 1): - return 'skip' + pytest.skip() ds = gdal.Open('data/stefan_full_rgba_alpha_1bit.jp2') @@ -1920,14 +1582,9 @@ def ecw_44(): got_md = ds.GetMetadata('JPEG2000') for (key, value) in expected_md: - if key not in got_md or got_md[key] != value: - gdaltest.post_reason('fail') - print(key) - print(got_md) - return 'fail' - - return 'success' + assert key in got_md and got_md[key] == value + ############################################################################### # Test metadata reading & writing @@ -1942,23 +1599,18 @@ def RemoveDriverMetadata(md): return md -def ecw_45(): +def test_ecw_45(): if gdaltest.jp2ecw_drv is None or gdaltest.ecw_write == 0: - return 'skip' + pytest.skip() # No metadata src_ds = gdal.GetDriverByName('MEM').Create('', 2, 2) out_ds = gdaltest.jp2ecw_drv.CreateCopy('/vsimem/ecw_45.jp2', src_ds, options=['WRITE_METADATA=YES']) del out_ds - if gdal.VSIStatL('/vsimem/ecw_45.jp2.aux.xml') is not None: - gdaltest.post_reason('fail') - return 'fail' + assert gdal.VSIStatL('/vsimem/ecw_45.jp2.aux.xml') is None ds = gdal.Open('/vsimem/ecw_45.jp2') md = RemoveDriverMetadata(ds.GetMetadata()) - if md != {}: - gdaltest.post_reason('fail') - print(md) - return 'fail' + assert md == {} gdal.Unlink('/vsimem/ecw_45.jp2') # Simple metadata in main domain @@ -1967,15 +1619,10 @@ def ecw_45(): src_ds.SetMetadataItem('FOO', 'BAR') out_ds = gdaltest.jp2ecw_drv.CreateCopy('/vsimem/ecw_45.jp2', src_ds, options=options) del out_ds - if gdal.VSIStatL('/vsimem/ecw_45.jp2.aux.xml') is not None: - gdaltest.post_reason('fail') - return 'fail' + assert gdal.VSIStatL('/vsimem/ecw_45.jp2.aux.xml') is None ds = gdal.Open('/vsimem/ecw_45.jp2') md = RemoveDriverMetadata(ds.GetMetadata()) - if md != {'FOO': 'BAR'}: - gdaltest.post_reason('fail') - print(md) - return 'fail' + assert md == {'FOO': 'BAR'} gdal.Unlink('/vsimem/ecw_45.jp2') # Simple metadata in auxiliary domain @@ -1983,15 +1630,10 @@ def ecw_45(): src_ds.SetMetadataItem('FOO', 'BAR', 'SOME_DOMAIN') out_ds = gdaltest.jp2ecw_drv.CreateCopy('/vsimem/ecw_45.jp2', src_ds, options=['WRITE_METADATA=YES']) del out_ds - if gdal.VSIStatL('/vsimem/ecw_45.jp2.aux.xml') is not None: - gdaltest.post_reason('fail') - return 'fail' + assert gdal.VSIStatL('/vsimem/ecw_45.jp2.aux.xml') is None ds = gdal.Open('/vsimem/ecw_45.jp2') md = RemoveDriverMetadata(ds.GetMetadata('SOME_DOMAIN')) - if md != {'FOO': 'BAR'}: - gdaltest.post_reason('fail') - print(md) - return 'fail' + assert md == {'FOO': 'BAR'} gdal.Unlink('/vsimem/ecw_45.jp2') # Simple metadata in auxiliary XML domain @@ -1999,13 +1641,9 @@ def ecw_45(): src_ds.SetMetadata(['<some_arbitrary_xml_box/>'], 'xml:SOME_DOMAIN') out_ds = gdaltest.jp2ecw_drv.CreateCopy('/vsimem/ecw_45.jp2', src_ds, options=['WRITE_METADATA=YES']) del out_ds - if gdal.VSIStatL('/vsimem/ecw_45.jp2.aux.xml') is not None: - gdaltest.post_reason('fail') - return 'fail' + assert gdal.VSIStatL('/vsimem/ecw_45.jp2.aux.xml') is None ds = gdal.Open('/vsimem/ecw_45.jp2') - if ds.GetMetadata('xml:SOME_DOMAIN')[0] != '<some_arbitrary_xml_box />\n': - gdaltest.post_reason('fail') - return 'fail' + assert ds.GetMetadata('xml:SOME_DOMAIN')[0] == '<some_arbitrary_xml_box />\n' gdal.Unlink('/vsimem/ecw_45.jp2') # Special xml:BOX_ metadata domain @@ -2014,13 +1652,9 @@ def ecw_45(): src_ds.SetMetadata(['<some_arbitrary_xml_box/>'], 'xml:BOX_1') out_ds = gdaltest.jp2ecw_drv.CreateCopy('/vsimem/ecw_45.jp2', src_ds, options=options) del out_ds - if gdal.VSIStatL('/vsimem/ecw_45.jp2.aux.xml') is not None: - gdaltest.post_reason('fail') - return 'fail' + assert gdal.VSIStatL('/vsimem/ecw_45.jp2.aux.xml') is None ds = gdal.Open('/vsimem/ecw_45.jp2') - if ds.GetMetadata('xml:BOX_0')[0] != '<some_arbitrary_xml_box/>': - gdaltest.post_reason('fail') - return 'fail' + assert ds.GetMetadata('xml:BOX_0')[0] == '<some_arbitrary_xml_box/>' gdal.Unlink('/vsimem/ecw_45.jp2') # Special xml:XMP metadata domain @@ -2029,25 +1663,20 @@ def ecw_45(): src_ds.SetMetadata(['<fake_xmp_box/>'], 'xml:XMP') out_ds = gdaltest.jp2ecw_drv.CreateCopy('/vsimem/ecw_45.jp2', src_ds, options=options) del out_ds - if gdal.VSIStatL('/vsimem/ecw_45.jp2.aux.xml') is not None: - gdaltest.post_reason('fail') - return 'fail' + assert gdal.VSIStatL('/vsimem/ecw_45.jp2.aux.xml') is None ds = gdal.Open('/vsimem/ecw_45.jp2') - if ds.GetMetadata('xml:XMP')[0] != '<fake_xmp_box/>': - gdaltest.post_reason('fail') - return 'fail' + assert ds.GetMetadata('xml:XMP')[0] == '<fake_xmp_box/>' gdal.Unlink('/vsimem/ecw_45.jp2') - return 'success' - + ############################################################################### # Test non nearest upsampling -def ecw_46(): +def test_ecw_46(): if gdaltest.jp2ecw_drv is None or gdaltest.ecw_write == 0: - return 'skip' + pytest.skip() tmp_ds = gdaltest.jp2ecw_drv.CreateCopy('/vsimem/ecw_46.jp2', gdal.Open('data/int16.tif')) tmp_ds = None @@ -2066,33 +1695,25 @@ def ecw_46(): ref_cs = mem_ds.GetRasterBand(1).Checksum() mem_ds.GetRasterBand(1).WriteRaster(0, 0, 40, 40, upsampled_data) cs = mem_ds.GetRasterBand(1).Checksum() - if cs != ref_cs: - gdaltest.post_reason('fail') - print(cs) - print(ref_cs) - return 'fail' - - return 'success' + assert cs == ref_cs ############################################################################### # /vsi reading with ECW (#6482) -def ecw_47(): +def test_ecw_47(): if gdaltest.ecw_drv is None: - return 'skip' + pytest.skip() if gdaltest.ecw_drv.major_version == 3: - return 'skip' + pytest.skip() data = open('data/jrc.ecw', 'rb').read() gdal.FileFromMemBuffer('/vsimem/ecw_47.ecw', data) ds = gdal.Open('/vsimem/ecw_47.ecw') - if ds is None: - gdaltest.post_reason('fail') - return 'fail' + assert ds is not None mean_tolerance = 0.5 @@ -2103,48 +1724,39 @@ def ecw_47(): (mean, stddev) = ds.GetRasterBand(1).ComputeBandStats() - if abs(mean - exp_mean) > mean_tolerance or abs(stddev - exp_stddev) > 0.5: - gdaltest.post_reason('mean/stddev of (%g,%g) diffs from expected(%g,%g)' % (mean, stddev, exp_mean, exp_stddev)) - return 'fail' + assert abs(mean - exp_mean) <= mean_tolerance and abs(stddev - exp_stddev) <= 0.5, \ + ('mean/stddev of (%g,%g) diffs from expected(%g,%g)' % (mean, stddev, exp_mean, exp_stddev)) gdal.Unlink('/vsimem/ecw_47.ecw') - return 'success' - ############################################################################### # Test "Upward" orientation is forced by default -def ecw_48(): +def test_ecw_48(): if gdaltest.ecw_drv is None: - return 'skip' + pytest.skip() ecw_upward = gdal.GetConfigOption('ECW_ALWAYS_UPWARD', 'TRUE') - if ecw_upward != 'TRUE' and ecw_upward != 'ON': - gdaltest.post_reason('ECW_ALWAYS_UPWARD default value must be TRUE.') - return 'fail' + assert ecw_upward == 'TRUE' or ecw_upward == 'ON', \ + 'ECW_ALWAYS_UPWARD default value must be TRUE.' ds = gdal.Open('data/spif83_downward.ecw') gt = ds.GetGeoTransform() # expect Y resolution negative expected_gt = (6138559.5576418638, 195.5116973254697, 0.0, 2274798.7836679211, 0.0, -198.32414964918371) - if gt != expected_gt: - print(gt) - gdaltest.post_reason('did not get expected geotransform.') - return 'fail' - - return 'success' + assert gt == expected_gt, 'did not get expected geotransform.' ############################################################################### # Test "Upward" orientation can be overridden with ECW_ALWAYS_UPWARD=FALSE -def ecw_49(): +def test_ecw_49(): if gdaltest.ecw_drv is None: - return 'skip' + pytest.skip() ecw_upward_old = gdal.GetConfigOption('ECW_ALWAYS_UPWARD', 'TRUE') gdal.SetConfigOption('ECW_ALWAYS_UPWARD', 'FALSE') @@ -2154,86 +1766,69 @@ def ecw_49(): # expect Y resolution positive expected_gt = (6138559.5576418638, 195.5116973254697, 0.0, 2274798.7836679211, 0.0, 198.32414964918371) - if gt != expected_gt: - print(gt) - gdaltest.post_reason('did not get expected geotransform.') - return 'fail' - - return 'success' + assert gt == expected_gt, 'did not get expected geotransform.' ############################################################################### -def ecw_online_1(): +def test_ecw_online_1(): if gdaltest.jp2ecw_drv is None: - return 'skip' + pytest.skip() if not gdaltest.download_file('http://download.osgeo.org/gdal/data/jpeg2000/7sisters200.j2k', '7sisters200.j2k'): - return 'skip' + pytest.skip() # checksum = 32316 on my PC tst = gdaltest.GDALTest('JP2ECW', 'tmp/cache/7sisters200.j2k', 1, None, filename_absolute=1) - if tst.testOpen() != 'success': - return 'fail' + tst.testOpen() ds = gdal.Open('tmp/cache/7sisters200.j2k') ds.GetRasterBand(1).Checksum() ds = None - return 'success' - ############################################################################### -def ecw_online_2(): +def test_ecw_online_2(): if gdaltest.jp2ecw_drv is None: - return 'skip' + pytest.skip() if not gdaltest.download_file('http://download.osgeo.org/gdal/data/jpeg2000/gcp.jp2', 'gcp.jp2'): - return 'skip' + pytest.skip() # checksum = 1292 on my PC tst = gdaltest.GDALTest('JP2ECW', 'tmp/cache/gcp.jp2', 1, None, filename_absolute=1) - if tst.testOpen() != 'success': - return 'fail' + tst.testOpen() ds = gdal.Open('tmp/cache/gcp.jp2') ds.GetRasterBand(1).Checksum() - if len(ds.GetGCPs()) != 15: - gdaltest.post_reason('bad number of GCP') - return 'fail' + assert len(ds.GetGCPs()) == 15, 'bad number of GCP' 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 ds.GetGCPProjection() != expected_wkt: - gdaltest.post_reason('bad GCP projection') - return 'fail' + assert ds.GetGCPProjection() == expected_wkt, 'bad GCP projection' ds = None - return 'success' - ############################################################################### def ecw_online_3(): if gdaltest.jp2ecw_drv is None: - return 'skip' + pytest.skip() if gdaltest.ecw_drv.major_version == 4: - gdaltest.post_reason('4.x SDK gets unreliable results for jp2') - return 'skip' + pytest.skip('4.x SDK gets unreliable results for jp2') if not gdaltest.download_file('http://www.openjpeg.org/samples/Bretagne1.j2k', 'Bretagne1.j2k'): - return 'skip' + pytest.skip() if not gdaltest.download_file('http://www.openjpeg.org/samples/Bretagne1.bmp', 'Bretagne1.bmp'): - return 'skip' + pytest.skip() # checksum = 16481 on my PC tst = gdaltest.GDALTest('JP2ECW', 'tmp/cache/Bretagne1.j2k', 1, None, filename_absolute=1) - if tst.testOpen() != 'success': - return 'fail' + tst.testOpen() ds = gdal.Open('tmp/cache/Bretagne1.j2k') ds_ref = gdal.Open('tmp/cache/Bretagne1.bmp') @@ -2245,34 +1840,28 @@ def ecw_online_3(): ds_ref = None # Difference between the image before and after compression - if maxdiff > 16: - gdaltest.post_reason('Image too different from reference') - return 'fail' - - return 'success' + assert maxdiff <= 16, 'Image too different from reference' ############################################################################### -def ecw_online_4(): +def test_ecw_online_4(): if gdaltest.jp2ecw_drv is None: - return 'skip' + pytest.skip() if gdaltest.ecw_drv.major_version == 5 and gdaltest.ecw_drv.minor_version == 2: - print('This test hangs on Linux in a mutex in the SDK 5.2.1') - return 'skip' + pytest.skip('This test hangs on Linux in a mutex in the SDK 5.2.1') if not gdaltest.download_file('http://www.openjpeg.org/samples/Bretagne2.j2k', 'Bretagne2.j2k'): - return 'skip' + pytest.skip() if not gdaltest.download_file('http://www.openjpeg.org/samples/Bretagne2.bmp', 'Bretagne2.bmp'): - return 'skip' + pytest.skip() # Checksum = 53054 on my PC tst = gdaltest.GDALTest('JP2ECW', 'tmp/cache/Bretagne2.j2k', 1, None, filename_absolute=1) - if tst.testOpen() != 'success': - return 'fail' + tst.testOpen() ds = gdal.Open('tmp/cache/Bretagne2.j2k') ds_ref = gdal.Open('tmp/cache/Bretagne2.bmp') @@ -2284,22 +1873,18 @@ def ecw_online_4(): ds_ref = None # Difference between the image before and after compression - if maxdiff > 1: - gdaltest.post_reason('Image too different from reference') - return 'fail' - - return 'success' + assert maxdiff <= 1, 'Image too different from reference' ############################################################################### -def ecw_online_5(): +def test_ecw_online_5(): if gdaltest.ecw_drv is None: - return 'skip' + pytest.skip() if not gdaltest.download_file('http://download.osgeo.org/gdal/data/ecw/red_flower.ecw', 'red_flower.ecw'): - return 'skip' + pytest.skip() ds = gdal.Open('tmp/cache/red_flower.ecw') @@ -2316,25 +1901,22 @@ def ecw_online_5(): (mean, stddev) = ds.GetRasterBand(2).ComputeBandStats() - if abs(mean - exp_mean) > mean_tolerance or abs(stddev - exp_stddev) > 0.5: - gdaltest.post_reason('mean/stddev of (%g,%g) diffs from expected(%g,%g)' % (mean, stddev, exp_mean, exp_stddev)) - return 'fail' - - return 'success' + assert abs(mean - exp_mean) <= mean_tolerance and abs(stddev - exp_stddev) <= 0.5, \ + ('mean/stddev of (%g,%g) diffs from expected(%g,%g)' % (mean, stddev, exp_mean, exp_stddev)) ############################################################################### # This tests the HTTP driver in fact. To ensure if keeps the original filename, # and in particular the .ecw extension, to make the ECW driver happy -def ecw_online_6(): +def test_ecw_online_6(): if gdaltest.ecw_drv is None: - return 'skip' + pytest.skip() drv = gdal.GetDriverByName('HTTP') if drv is None: - return 'skip' + pytest.skip() dods_drv = gdal.GetDriverByName('DODS') if dods_drv is not None: @@ -2350,46 +1932,40 @@ def ecw_online_6(): # The ECW driver (3.3) doesn't manage to open in /vsimem, thus fallbacks # to writing to /tmp, which doesn't work on Windows if sys.platform == 'win32': - return 'skip' + pytest.skip() conn = gdaltest.gdalurlopen(url) if conn is None: - print('cannot open URL') - return 'skip' + pytest.skip('cannot open URL') conn.close() - return 'fail' + pytest.fail() ds = None - return 'success' - ############################################################################### # ECWv2 file with alpha channel (#6028) -def ecw_online_7(): +def test_ecw_online_7(): if gdaltest.ecw_drv is None: - return 'skip' + pytest.skip() if not gdaltest.download_file('http://download.osgeo.org/gdal/data/ecw/sandiego2m_null.ecw', 'sandiego2m_null.ecw'): - return 'skip' + pytest.skip() ds = gdal.Open('tmp/cache/sandiego2m_null.ecw') if gdaltest.ecw_drv.major_version == 3: expected_band_count = 3 else: expected_band_count = 4 - if ds.RasterCount != expected_band_count: - gdaltest.post_reason('Expected %d bands, got %d' % (expected_band_count, ds.RasterCount)) - return 'fail' - - return 'success' + assert ds.RasterCount == expected_band_count, \ + ('Expected %d bands, got %d' % (expected_band_count, ds.RasterCount)) ############################################################################### -def ecw_cleanup(): +def test_ecw_cleanup(): # gdaltest.clean_tmp() @@ -2472,74 +2048,5 @@ def ecw_cleanup(): pass gdaltest.reregister_all_jpeg2000_drivers() - return 'success' - - -gdaltest_list = [ - ecw_init, - ecw_1, - ecw_2, - ecw_3, - ecw_4, - ecw_5, - ecw_6, - ecw_7, - ecw_8, - ecw_9, - ecw_10, - ecw_11, - ecw_12, - ecw_13, - ecw_14, - ecw_15, - ecw_16, - ecw_17, - ecw_18, - ecw_19, - ecw_20, - ecw_21, - ecw_22, - ecw_23, - ecw_24, - ecw_25, - ecw_26, - ecw_27, - ecw_28, - ecw_29, - ecw_30, - ecw_31, - ecw_32, - ecw_33, - ecw_33_bis, - ecw_34, - ecw_35, - ecw_36, - ecw_37, - ecw_38, - ecw_39, - ecw_40, - ecw_41, - ecw_42, - ecw_43, - ecw_44, - ecw_45, - ecw_46, - ecw_47, - ecw_48, - ecw_49, - ecw_online_1, - ecw_online_2, - # JTO this test does not make sense. It tests difference between two files pixel by pixel but compression is lossy# ecw_online_3, - ecw_online_4, - ecw_online_5, - ecw_online_6, - ecw_online_7, - ecw_cleanup] - -if __name__ == '__main__': - - gdaltest.setup_run('ecw') - - gdaltest.run_tests(gdaltest_list) - - sys.exit(gdaltest.summarize()) + + diff --git a/autotest/gdrivers/eedai.py b/autotest/gdrivers/eedai.py index 458880d9bab9..15826fd93dc5 100644 --- a/autotest/gdrivers/eedai.py +++ b/autotest/gdrivers/eedai.py @@ -33,24 +33,24 @@ import struct import sys -sys.path.append('../pymod') from osgeo import gdal import gdaltest import webserver +import pytest ############################################################################### # Find EEDAI driver -def eedai_1(): +def test_eedai_1(): gdaltest.eedai_drv = gdal.GetDriverByName('EEDAI') if gdaltest.eedai_drv is None: - return 'skip' + pytest.skip() gdal.SetConfigOption('CPL_CURL_ENABLE_VSIMEM', 'YES') @@ -61,16 +61,14 @@ def eedai_1(): gdaltest.GOOGLE_APPLICATION_CREDENTIALS = gdal.GetConfigOption('GOOGLE_APPLICATION_CREDENTIALS') gdal.SetConfigOption('GOOGLE_APPLICATION_CREDENTIALS', '') - return 'success' - ############################################################################### # Nominal case -def eedai_2(): +def test_eedai_2(): if gdaltest.eedai_drv is None: - return 'skip' + pytest.skip() gdal.FileFromMemBuffer('/vsimem/ee/projects/earthengine-public/assets/image', json.dumps({ 'type': 'IMAGE', @@ -286,8 +284,6 @@ def eedai_2(): info = gdal.Info(ds, format='json') for key in expected_info: if not (key in info and info[key] == expected_info[key]): - gdaltest.post_reason('fail') - print('Got difference for key %s' % key) if key in info: print('Got: ' + str(info[key])) else: @@ -295,20 +291,13 @@ def eedai_2(): print('Expected: ' + str(expected_info[key])) print('Whole info:') print(json.dumps(info, indent=4)) - return 'fail' + pytest.fail('Got difference for key %s' % key) - if ds.GetProjectionRef().find('32610') < 0: - gdaltest.post_reason('fail') - print(ds.GetProjectionRef()) - return 'fail' + assert ds.GetProjectionRef().find('32610') >= 0 - 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(3) is not None: - gdaltest.post_reason('fail') - return 'fail' + assert ds.GetRasterBand(1).GetOverview(3) is None npy_serialized = struct.pack( 'B' * 8, 0x93, ord('N'), ord('U'), ord('M'), ord('P'), ord('Y'), 1, 0) @@ -323,57 +312,40 @@ def eedai_2(): '/vsimem/ee/projects/earthengine-public/assets/image:getPixels&CUSTOMREQUEST=POST&POSTFIELDS={ "fileFormat": "NPY", "bandIds": [ "B1", "B9" ], "grid": { "affineTransform": { "translateX": 607500.0, "translateY": 4092480.0, "scaleX": 60.0, "scaleY": -60.0, "shearX": 0.0, "shearY": 0.0 }, "dimensions": { "width": 38, "height": 39 } } }', npy_serialized) got_data = ds.GetRasterBand(1).ReadRaster(1800, 1810, 1, 1) got_data = struct.unpack('h', got_data)[0] - if got_data != 12345: - gdaltest.post_reason('fail') - print(got_data) - return 'fail' + assert got_data == 12345 got_data = ds.GetRasterBand(2).ReadRaster(1800, 1810, 1, 1) got_data = struct.unpack('h', got_data)[0] - if got_data != 23456: - gdaltest.post_reason('fail') - print(got_data) - return 'fail' + assert got_data == 23456 ds = None gdal.SetConfigOption('EEDA_URL', '/vsimem/ee/') sub_ds = gdal.Open('EEDAI:image:B1,B9') gdal.SetConfigOption('EEDA_URL', None) - if sub_ds.RasterCount != 2: - gdaltest.post_reason('fail') - print(sub_ds.RasterCount) - return 'fail' + assert sub_ds.RasterCount == 2 gdal.SetConfigOption('EEDA_URL', '/vsimem/ee/') sub_ds = gdal.Open('EEDAI:image:B2') gdal.SetConfigOption('EEDA_URL', None) - if sub_ds.RasterCount != 1: - gdaltest.post_reason('fail') - print(sub_ds.RasterCount) - return 'fail' + assert sub_ds.RasterCount == 1 got_md = sub_ds.GetRasterBand(1).GetMetadata() expected_md = {'prop': 'the_prop_B2'} - if got_md != expected_md: - gdaltest.post_reason('fail') - print(got_md) - return 'fail' + assert got_md == expected_md gdal.SetConfigOption('EEDA_BEARER', None) - return 'success' - ############################################################################### # Test OAuth2 with ServiceAccount -def eedai_3(): +def test_eedai_3(): if gdaltest.eedai_drv is None: - return 'skip' + pytest.skip() if gdaltest.is_travis_branch('gcc52_stdcpp14_sanitize'): - return 'skip' + pytest.skip() gdal.SetConfigOption('EEDA_URL', '/vsimem/ee/') # Generated with 'openssl genrsa -out rsa-openssl.pem 1024' and @@ -409,24 +381,21 @@ def eedai_3(): gdal.SetConfigOption('EEDA_CLIENT_EMAIL', None) if gdal.GetLastErrorMsg().find('CPLRSASHA256Sign() not implemented') >= 0: - return 'skip' - - if ds is None: - return 'fail' + pytest.skip() - return 'success' + assert ds is not None ############################################################################### # Test OAuth2 with GOOGLE_APPLICATION_CREDENTIALS -def eedai_GOOGLE_APPLICATION_CREDENTIALS(): +def test_eedai_GOOGLE_APPLICATION_CREDENTIALS(): if gdaltest.eedai_drv is None: - return 'skip' + pytest.skip() if gdaltest.is_travis_branch('gcc52_stdcpp14_sanitize'): - return 'skip' + pytest.skip() gdal.FileFromMemBuffer('/vsimem/my.json', """{ "private_key":"-----BEGIN PRIVATE KEY----- @@ -467,34 +436,31 @@ def eedai_GOOGLE_APPLICATION_CREDENTIALS(): gdal.SetConfigOption('EEDA_CLIENT_EMAIL', None) if gdal.GetLastErrorMsg().find('CPLRSASHA256Sign() not implemented') >= 0: - return 'skip' + pytest.skip() - if ds is None: - return 'fail' - - return 'success' + assert ds is not None ############################################################################### # Read credentials from simulated GCE instance -def eedai_gce_credentials(): +def test_eedai_gce_credentials(): if gdaltest.eedai_drv is None: - return 'skip' + pytest.skip() if sys.platform not in ('linux', 'linux2', 'win32'): - return 'skip' + pytest.skip() 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('CPL_GCE_CREDENTIALS_URL', 'http://localhost:%d/computeMetadata/v1/instance/service-accounts/default/token' % gdaltest.webserver_port) @@ -538,19 +504,16 @@ def method(request): webserver.server_stop(gdaltest.webserver_process, gdaltest.webserver_port) - if ds is None: - return 'fail' - - return 'success' + assert ds is not None ############################################################################### # Request in PNG mode -def eedai_4(): +def test_eedai_4(): if gdaltest.eedai_drv is None: - return 'skip' + pytest.skip() gdal.FileFromMemBuffer('/vsimem/ee/projects/earthengine-public/assets/image', json.dumps({ 'type': 'IMAGE', @@ -644,27 +607,18 @@ def eedai_4(): '/vsimem/ee/projects/earthengine-public/assets/image:getPixels&CUSTOMREQUEST=POST&POSTFIELDS={ "fileFormat": "PNG", "bandIds": [ "B1", "B2", "B3" ], "grid": { "affineTransform": { "translateX": 499980.0, "translateY": 4200000.0, "scaleX": 60.0, "scaleY": -60.0, "shearX": 0.0, "shearY": 0.0 }, "dimensions": { "width": 256, "height": 256 } } }', png_data) got_data = ds.GetRasterBand(1).ReadRaster(0, 0, 1, 1) got_data = struct.unpack('B', got_data)[0] - if got_data != 127: - gdaltest.post_reason('fail') - print(got_data) - return 'fail' + assert got_data == 127 # Same with dataset RasterIO got_data = ds.ReadRaster(0, 0, 1, 1) got_data = struct.unpack('B' * 3, got_data) - if got_data != (127, 128, 129): - gdaltest.post_reason('fail') - print(got_data) - return 'fail' + assert got_data == (127, 128, 129) # Same after flushing cache ds.FlushCache() got_data = ds.ReadRaster(0, 0, 1, 1) got_data = struct.unpack('B' * 3, got_data) - if got_data != (127, 128, 129): - gdaltest.post_reason('fail') - print(got_data) - return 'fail' + assert got_data == (127, 128, 129) # Sub-sampled query gdal.FileFromMemBuffer( @@ -672,34 +626,26 @@ def eedai_4(): got_data = ds.GetRasterBand(1).ReadRaster( 0, 0, 2, 2, buf_xsize=1, buf_ysize=1) got_data = struct.unpack('B', got_data)[0] - if got_data != 127: - gdaltest.post_reason('fail') - print(got_data) - return 'fail' + assert got_data == 127 # Same after flushing cache with dataset RasterIO ds.FlushCache() got_data = ds.ReadRaster(0, 0, 2, 2, buf_xsize=1, buf_ysize=1) got_data = struct.unpack('B' * 3, got_data) - if got_data != (127, 128, 129): - gdaltest.post_reason('fail') - print(got_data) - return 'fail' + assert got_data == (127, 128, 129) ds = None gdal.SetConfigOption('EEDA_BEARER', None) - return 'success' - ############################################################################### # Request in AUTO GTIFF mode -def eedai_geotiff(): +def test_eedai_geotiff(): if gdaltest.eedai_drv is None: - return 'skip' + pytest.skip() gdal.FileFromMemBuffer('/vsimem/ee/projects/earthengine-public/assets/image', json.dumps({ 'type': 'IMAGE', @@ -747,74 +693,20 @@ def eedai_geotiff(): '/vsimem/ee/projects/earthengine-public/assets/image:getPixels&CUSTOMREQUEST=POST&POSTFIELDS={ "fileFormat": "GEO_TIFF", "bandIds": [ "B1" ], "grid": { "affineTransform": { "translateX": 499980.0, "translateY": 4200000.0, "scaleX": 60.0, "scaleY": -60.0, "shearX": 0.0, "shearY": 0.0 }, "dimensions": { "width": 256, "height": 256 } } }', data) got_data = ds.GetRasterBand(1).ReadRaster(0, 0, 1, 1) got_data = struct.unpack('H', got_data)[0] - if got_data != 12345: - gdaltest.post_reason('fail') - print(got_data) - return 'fail' + assert got_data == 12345 ds = None gdal.SetConfigOption('EEDA_BEARER', None) - return 'success' - ############################################################################### # -def eedai_real_service(): +def test_eedai_cleanup(): if gdaltest.eedai_drv is None: - return 'skip' - - if gdal.GetConfigOption('GOOGLE_APPLICATION_CREDENTIALS') is None: - - if gdal.GetConfigOption('EEDA_PRIVATE_KEY_FILE') is None and gdal.GetConfigOption('EEDA_PRIVATE_KEY') is None: - print('Missing EEDA_PRIVATE_KEY_FILE/EEDA_PRIVATE_KEY or GOOGLE_APPLICATION_CREDENTIALS') - return 'skip' - - if gdal.GetConfigOption('EEDA_CLIENT_EMAIL') is None: - print('Missing EEDA_CLIENT_EMAIL') - return 'skip' - - ds = gdal.Open('EEDAI:USDA/NAIP/DOQQ/n_4010064_se_14_2_20070725') - if ds is None: - gdaltest.post_reason('fail') - return 'fail' - res = gdal.Info(ds, format='json') - expected = {'files': [], 'cornerCoordinates': {'upperRight': [415016.0, 4435536.0], 'lowerLeft': [408970.0, 4427936.0], 'lowerRight': [415016.0, 4427936.0], 'upperLeft': [408970.0, 4435536.0], 'center': [411993.0, 4431736.0]}, 'wgs84Extent': {'type': 'Polygon', 'coordinates': [[]]}, 'description': 'EEDAI:USDA/NAIP/DOQQ/n_4010064_se_14_2_20070725', 'driverShortName': 'EEDAI', 'driverLongName': 'Earth Engine Data API Image', 'bands': [{'description': 'R', 'band': 1, 'colorInterpretation': 'Red', 'overviews': [{'size': [1511, 1900]}, {'size': [755, 950]}, {'size': [377, 475]}, {'size': [188, 237]}], 'type': 'Byte', 'block': [256, 256], 'metadata': {}}, {'description': 'G', 'band': 2, 'colorInterpretation': 'Green', 'overviews': [{'size': [1511, 1900]}, {'size': [755, 950]}, {'size': [377, 475]}, {'size': [188, 237]}], 'type': 'Byte', 'block': [256, 256], 'metadata': {}}, {'description': 'B', 'band': 3, 'colorInterpretation': 'Blue', 'overviews': [{'size': [1511, 1900]}, {'size': [755, 950]}, {'size': [377, 475]}, {'size': [188, 237]}], 'type': 'Byte', 'block': [256, 256], 'metadata': {}}], 'coordinateSystem': {'wkt': 'PROJCS["NAD83 / UTM zone 14N",\n GEOGCS["NAD83",\n DATUM["North_American_Datum_1983",\n SPHEROID["GRS 1980",6378137,298.257222101,\n AUTHORITY["EPSG","7019"]],\n TOWGS84[0,0,0,0,0,0,0],\n AUTHORITY["EPSG","6269"]],\n PRIMEM["Greenwich",0,\n AUTHORITY["EPSG","8901"]],\n UNIT["degree",0.0174532925199433,\n AUTHORITY["EPSG","9122"]],\n AUTHORITY["EPSG","4269"]],\n PROJECTION["Transverse_Mercator"],\n PARAMETER["latitude_of_origin",0],\n PARAMETER["central_meridian",-99],\n PARAMETER["scale_factor",0.9996],\n PARAMETER["false_easting",500000],\n PARAMETER["false_northing",0],\n UNIT["metre",1,\n AUTHORITY["EPSG","9001"]],\n AXIS["Easting",EAST],\n AXIS["Northing",NORTH],\n AUTHORITY["EPSG","26914"]]'}, 'geoTransform': [408970.0, 2.0, 0.0, 4435536.0, 0.0, -2.0], 'metadata': {'IMAGE_STRUCTURE': {'INTERLEAVE': 'PIXEL'}}, 'size': [3023, 3800]} - if expected != res: - gdaltest.post_reason('fail') - print(res) - return 'fail' - if ds.ReadRaster(0, 0, 1, 1) is None: - gdaltest.post_reason('fail') - return 'fail' - - ds = gdal.Open('EEDAI:MODIS/006/MYD09GA/2017_05_24') - if ds is None: - gdaltest.post_reason('fail') - return 'fail' - res = gdal.Info(ds, format='json') - expected = {'files': [], 'cornerCoordinates': {'upperRight': [20015109.354, 10007554.677], 'lowerLeft': [-20015109.354, -10007554.677], 'lowerRight': [20015109.354, -10007554.677], 'upperLeft': [-20015109.354, 10007554.677], 'center': [9.6e-06, 6e-06]}, 'wgs84Extent': {'type': 'Polygon', 'coordinates': [[]]}, 'description': 'EEDAI:MODIS/006/MYD09GA/2017_05_24', 'driverShortName': 'EEDAI', 'driverLongName': 'Earth Engine Data API Image', 'bands': [{'description': 'num_observations_1km', 'band': 1, 'colorInterpretation': 'Undefined', 'overviews': [{'size': [21600, 10800]}, {'size': [10800, 5400]}, {'size': [5400, 2700]}, {'size': [2700, 1350]}, {'size': [1350, 675]}, {'size': [675, 337]}, {'size': [337, 168]}, {'size': [168, 84]}], 'type': 'Byte', 'block': [256, 256], 'metadata': {'IMAGE_STRUCTURE': {'PIXELTYPE': 'SIGNEDBYTE'}}}, {'description': 'state_1km', 'band': 2, 'colorInterpretation': 'Undefined', 'overviews': [{'size': [21600, 10800]}, {'size': [10800, 5400]}, {'size': [5400, 2700]}, {'size': [2700, 1350]}, {'size': [1350, 675]}, {'size': [675, 337]}, {'size': [337, 168]}, {'size': [168, 84]}], 'type': 'UInt16', 'block': [256, 256], 'metadata': {}}, {'description': 'SensorZenith', 'band': 3, 'colorInterpretation': 'Undefined', 'overviews': [{'size': [21600, 10800]}, {'size': [10800, 5400]}, {'size': [5400, 2700]}, {'size': [2700, 1350]}, {'size': [1350, 675]}, {'size': [675, 337]}, {'size': [337, 168]}, {'size': [168, 84]}], 'type': 'Int16', 'block': [256, 256], 'metadata': {}}, {'description': 'SensorAzimuth', 'band': 4, 'colorInterpretation': 'Undefined', 'overviews': [{'size': [21600, 10800]}, {'size': [10800, 5400]}, {'size': [5400, 2700]}, {'size': [2700, 1350]}, {'size': [1350, 675]}, {'size': [675, 337]}, {'size': [337, 168]}, {'size': [168, 84]}], 'type': 'Int16', 'block': [256, 256], 'metadata': {}}, {'description': 'Range', 'band': 5, 'colorInterpretation': 'Undefined', 'overviews': [{'size': [21600, 10800]}, {'size': [10800, 5400]}, {'size': [5400, 2700]}, {'size': [2700, 1350]}, {'size': [1350, 675]}, {'size': [675, 337]}, {'size': [337, 168]}, {'size': [168, 84]}], 'type': 'UInt16', 'block': [256, 256], 'metadata': {}}, {'description': 'SolarZenith', 'band': 6, 'colorInterpretation': 'Undefined', 'overviews': [{'size': [21600, 10800]}, {'size': [10800, 5400]}, {'size': [5400, 2700]}, {'size': [2700, 1350]}, {'size': [1350, 675]}, {'size': [675, 337]}, {'size': [337, 168]}, {'size': [168, 84]}], 'type': 'Int16', 'block': [256, 256], 'metadata': {}}, {'description': 'SolarAzimuth', 'band': 7, 'colorInterpretation': 'Undefined', 'overviews': [{'size': [21600, 10800]}, {'size': [10800, 5400]}, {'size': [5400, 2700]}, {'size': [2700, 1350]}, {'size': [1350, 675]}, {'size': [675, 337]}, {'size': [337, 168]}, {'size': [168, 84]}], 'type': 'Int16', 'block': [256, 256], 'metadata': {}}, {'description': 'gflags', 'band': 8, 'colorInterpretation': 'Undefined', 'overviews': [{'size': [21600, 10800]}, {'size': [10800, 5400]}, {'size': [5400, 2700]}, {'size': [2700, 1350]}, {'size': [1350, 675]}, {'size': [675, 337]}, {'size': [337, 168]}, {'size': [168, 84]}], 'type': 'Byte', 'block': [256, 256], 'metadata': {}}, {'description': 'orbit_pnt', 'band': 9, 'colorInterpretation': 'Undefined', 'overviews': [{'size': [21600, 10800]}, {'size': [10800, 5400]}, {'size': [5400, 2700]}, {'size': [2700, 1350]}, {'size': [1350, 675]}, {'size': [675, 337]}, {'size': [337, 168]}, {'size': [168, 84]}], 'type': 'Byte', 'block': [256, 256], 'metadata': {'IMAGE_STRUCTURE': {'PIXELTYPE': 'SIGNEDBYTE'}}}, {'description': 'granule_pnt', 'band': 10, 'colorInterpretation': 'Undefined', 'overviews': [{'size': [21600, 10800]}, {'size': [10800, 5400]}, {'size': [5400, 2700]}, {'size': [2700, 1350]}, {'size': [1350, 675]}, {'size': [675, 337]}, {'size': [337, 168]}, {'size': [168, 84]}], 'type': 'Byte', 'block': [256, 256], 'metadata': {}}], 'coordinateSystem': {'wkt': 'PROJCS["MODIS Sinusoidal",\n GEOGCS["WGS 84",\n DATUM["WGS_1984",\n SPHEROID["WGS 84",6378137,298.257223563,\n AUTHORITY["EPSG","7030"]],\n AUTHORITY["EPSG","6326"]],\n PRIMEM["Greenwich",0,\n AUTHORITY["EPSG","8901"]],\n UNIT["degree",0.01745329251994328,\n AUTHORITY["EPSG","9122"]],\n AUTHORITY["EPSG","4326"]],\n PROJECTION["Sinusoidal"],\n PARAMETER["false_easting",0.0],\n PARAMETER["false_northing",0.0],\n PARAMETER["central_meridian",0.0],\n PARAMETER["semi_major",6371007.181],\n PARAMETER["semi_minor",6371007.181],\n UNIT["m",1.0],\n AUTHORITY["SR-ORG","6974"]]'}, 'geoTransform': [-20015109.354, 926.625433056, 0.0, 10007554.677, 0.0, -926.625433055], 'metadata': {'IMAGE_STRUCTURE': {'INTERLEAVE': 'PIXEL'}, 'SUBDATASETS': {'SUBDATASET_2_NAME': 'EEDAI:MODIS/006/MYD09GA/2017_05_24:num_observations_500m,sur_refl_b01,sur_refl_b02,sur_refl_b03,sur_refl_b04,sur_refl_b05,sur_refl_b06,sur_refl_b07,QC_500m,obscov_500m,iobs_res,q_scan', 'SUBDATASET_2_DESC': 'Bands num_observations_500m,sur_refl_b01,sur_refl_b02,sur_refl_b03,sur_refl_b04,sur_refl_b05,sur_refl_b06,sur_refl_b07,QC_500m,obscov_500m,iobs_res,q_scan of MODIS/006/MYD09GA/2017_05_24', 'SUBDATASET_1_NAME': 'EEDAI:MODIS/006/MYD09GA/2017_05_24:num_observations_1km,state_1km,SensorZenith,SensorAzimuth,Range,SolarZenith,SolarAzimuth,gflags,orbit_pnt,granule_pnt', 'SUBDATASET_1_DESC': 'Bands num_observations_1km,state_1km,SensorZenith,SensorAzimuth,Range,SolarZenith,SolarAzimuth,gflags,orbit_pnt,granule_pnt of MODIS/006/MYD09GA/2017_05_24'}}, 'size': [43200, 21600]} - if expected != res: - gdaltest.post_reason('fail') - print(res) - return 'fail' - if ds.ReadRaster(0, 0, 1, 1) is None: - gdaltest.post_reason('fail') - return 'fail' - - return 'success' - -############################################################################### -# - - -def eedai_cleanup(): - - if gdaltest.eedai_drv is None: - return 'skip' + pytest.skip() gdal.SetConfigOption('CPL_CURL_ENABLE_VSIMEM', None) gdal.SetConfigOption('EEDA_BEARER', gdaltest.EEDA_BEARER) @@ -828,25 +720,33 @@ def eedai_cleanup(): gdal.Unlink('/vsimem/ee/projects/earthengine-public/assets/image') gdal.RmdirRecursive('/vsimem/ee/') - return 'success' +############################################################################### +# -gdaltest_list = [ - eedai_1, - eedai_2, - eedai_3, - eedai_GOOGLE_APPLICATION_CREDENTIALS, - eedai_gce_credentials, - eedai_4, - eedai_geotiff, - eedai_cleanup, - eedai_real_service, -] +def test_eedai_real_service(): -if __name__ == '__main__': + if gdaltest.eedai_drv is None: + pytest.skip() - gdaltest.setup_run('eedai') + if gdal.GetConfigOption('GOOGLE_APPLICATION_CREDENTIALS') is None: - gdaltest.run_tests(gdaltest_list) + if gdal.GetConfigOption('EEDA_PRIVATE_KEY_FILE') is None and gdal.GetConfigOption('EEDA_PRIVATE_KEY') is None: + pytest.skip('Missing EEDA_PRIVATE_KEY_FILE/EEDA_PRIVATE_KEY or GOOGLE_APPLICATION_CREDENTIALS') + + if gdal.GetConfigOption('EEDA_CLIENT_EMAIL') is None: + pytest.skip('Missing EEDA_CLIENT_EMAIL') + + ds = gdal.Open('EEDAI:USDA/NAIP/DOQQ/n_4010064_se_14_2_20070725') + assert ds is not None + res = gdal.Info(ds, format='json') + expected = {'files': [], 'cornerCoordinates': {'upperRight': [415016.0, 4435536.0], 'lowerLeft': [408970.0, 4427936.0], 'lowerRight': [415016.0, 4427936.0], 'upperLeft': [408970.0, 4435536.0], 'center': [411993.0, 4431736.0]}, 'wgs84Extent': {'type': 'Polygon', 'coordinates': [[]]}, 'description': 'EEDAI:USDA/NAIP/DOQQ/n_4010064_se_14_2_20070725', 'driverShortName': 'EEDAI', 'driverLongName': 'Earth Engine Data API Image', 'bands': [{'description': 'R', 'band': 1, 'colorInterpretation': 'Red', 'overviews': [{'size': [1511, 1900]}, {'size': [755, 950]}, {'size': [377, 475]}, {'size': [188, 237]}], 'type': 'Byte', 'block': [256, 256], 'metadata': {}}, {'description': 'G', 'band': 2, 'colorInterpretation': 'Green', 'overviews': [{'size': [1511, 1900]}, {'size': [755, 950]}, {'size': [377, 475]}, {'size': [188, 237]}], 'type': 'Byte', 'block': [256, 256], 'metadata': {}}, {'description': 'B', 'band': 3, 'colorInterpretation': 'Blue', 'overviews': [{'size': [1511, 1900]}, {'size': [755, 950]}, {'size': [377, 475]}, {'size': [188, 237]}], 'type': 'Byte', 'block': [256, 256], 'metadata': {}}], 'coordinateSystem': {'wkt': 'PROJCS["NAD83 / UTM zone 14N",\n GEOGCS["NAD83",\n DATUM["North_American_Datum_1983",\n SPHEROID["GRS 1980",6378137,298.257222101,\n AUTHORITY["EPSG","7019"]],\n TOWGS84[0,0,0,0,0,0,0],\n AUTHORITY["EPSG","6269"]],\n PRIMEM["Greenwich",0,\n AUTHORITY["EPSG","8901"]],\n UNIT["degree",0.0174532925199433,\n AUTHORITY["EPSG","9122"]],\n AUTHORITY["EPSG","4269"]],\n PROJECTION["Transverse_Mercator"],\n PARAMETER["latitude_of_origin",0],\n PARAMETER["central_meridian",-99],\n PARAMETER["scale_factor",0.9996],\n PARAMETER["false_easting",500000],\n PARAMETER["false_northing",0],\n UNIT["metre",1,\n AUTHORITY["EPSG","9001"]],\n AXIS["Easting",EAST],\n AXIS["Northing",NORTH],\n AUTHORITY["EPSG","26914"]]'}, 'geoTransform': [408970.0, 2.0, 0.0, 4435536.0, 0.0, -2.0], 'metadata': {'IMAGE_STRUCTURE': {'INTERLEAVE': 'PIXEL'}}, 'size': [3023, 3800]} + assert expected == res + assert ds.ReadRaster(0, 0, 1, 1) is not None - sys.exit(gdaltest.summarize()) + ds = gdal.Open('EEDAI:MODIS/006/MYD09GA/2017_05_24') + assert ds is not None + res = gdal.Info(ds, format='json') + expected = {'files': [], 'cornerCoordinates': {'upperRight': [20015109.354, 10007554.677], 'lowerLeft': [-20015109.354, -10007554.677], 'lowerRight': [20015109.354, -10007554.677], 'upperLeft': [-20015109.354, 10007554.677], 'center': [9.6e-06, 6e-06]}, 'wgs84Extent': {'type': 'Polygon', 'coordinates': [[]]}, 'description': 'EEDAI:MODIS/006/MYD09GA/2017_05_24', 'driverShortName': 'EEDAI', 'driverLongName': 'Earth Engine Data API Image', 'bands': [{'description': 'num_observations_1km', 'band': 1, 'colorInterpretation': 'Undefined', 'overviews': [{'size': [21600, 10800]}, {'size': [10800, 5400]}, {'size': [5400, 2700]}, {'size': [2700, 1350]}, {'size': [1350, 675]}, {'size': [675, 337]}, {'size': [337, 168]}, {'size': [168, 84]}], 'type': 'Byte', 'block': [256, 256], 'metadata': {'IMAGE_STRUCTURE': {'PIXELTYPE': 'SIGNEDBYTE'}}}, {'description': 'state_1km', 'band': 2, 'colorInterpretation': 'Undefined', 'overviews': [{'size': [21600, 10800]}, {'size': [10800, 5400]}, {'size': [5400, 2700]}, {'size': [2700, 1350]}, {'size': [1350, 675]}, {'size': [675, 337]}, {'size': [337, 168]}, {'size': [168, 84]}], 'type': 'UInt16', 'block': [256, 256], 'metadata': {}}, {'description': 'SensorZenith', 'band': 3, 'colorInterpretation': 'Undefined', 'overviews': [{'size': [21600, 10800]}, {'size': [10800, 5400]}, {'size': [5400, 2700]}, {'size': [2700, 1350]}, {'size': [1350, 675]}, {'size': [675, 337]}, {'size': [337, 168]}, {'size': [168, 84]}], 'type': 'Int16', 'block': [256, 256], 'metadata': {}}, {'description': 'SensorAzimuth', 'band': 4, 'colorInterpretation': 'Undefined', 'overviews': [{'size': [21600, 10800]}, {'size': [10800, 5400]}, {'size': [5400, 2700]}, {'size': [2700, 1350]}, {'size': [1350, 675]}, {'size': [675, 337]}, {'size': [337, 168]}, {'size': [168, 84]}], 'type': 'Int16', 'block': [256, 256], 'metadata': {}}, {'description': 'Range', 'band': 5, 'colorInterpretation': 'Undefined', 'overviews': [{'size': [21600, 10800]}, {'size': [10800, 5400]}, {'size': [5400, 2700]}, {'size': [2700, 1350]}, {'size': [1350, 675]}, {'size': [675, 337]}, {'size': [337, 168]}, {'size': [168, 84]}], 'type': 'UInt16', 'block': [256, 256], 'metadata': {}}, {'description': 'SolarZenith', 'band': 6, 'colorInterpretation': 'Undefined', 'overviews': [{'size': [21600, 10800]}, {'size': [10800, 5400]}, {'size': [5400, 2700]}, {'size': [2700, 1350]}, {'size': [1350, 675]}, {'size': [675, 337]}, {'size': [337, 168]}, {'size': [168, 84]}], 'type': 'Int16', 'block': [256, 256], 'metadata': {}}, {'description': 'SolarAzimuth', 'band': 7, 'colorInterpretation': 'Undefined', 'overviews': [{'size': [21600, 10800]}, {'size': [10800, 5400]}, {'size': [5400, 2700]}, {'size': [2700, 1350]}, {'size': [1350, 675]}, {'size': [675, 337]}, {'size': [337, 168]}, {'size': [168, 84]}], 'type': 'Int16', 'block': [256, 256], 'metadata': {}}, {'description': 'gflags', 'band': 8, 'colorInterpretation': 'Undefined', 'overviews': [{'size': [21600, 10800]}, {'size': [10800, 5400]}, {'size': [5400, 2700]}, {'size': [2700, 1350]}, {'size': [1350, 675]}, {'size': [675, 337]}, {'size': [337, 168]}, {'size': [168, 84]}], 'type': 'Byte', 'block': [256, 256], 'metadata': {}}, {'description': 'orbit_pnt', 'band': 9, 'colorInterpretation': 'Undefined', 'overviews': [{'size': [21600, 10800]}, {'size': [10800, 5400]}, {'size': [5400, 2700]}, {'size': [2700, 1350]}, {'size': [1350, 675]}, {'size': [675, 337]}, {'size': [337, 168]}, {'size': [168, 84]}], 'type': 'Byte', 'block': [256, 256], 'metadata': {'IMAGE_STRUCTURE': {'PIXELTYPE': 'SIGNEDBYTE'}}}, {'description': 'granule_pnt', 'band': 10, 'colorInterpretation': 'Undefined', 'overviews': [{'size': [21600, 10800]}, {'size': [10800, 5400]}, {'size': [5400, 2700]}, {'size': [2700, 1350]}, {'size': [1350, 675]}, {'size': [675, 337]}, {'size': [337, 168]}, {'size': [168, 84]}], 'type': 'Byte', 'block': [256, 256], 'metadata': {}}], 'coordinateSystem': {'wkt': 'PROJCS["MODIS Sinusoidal",\n GEOGCS["WGS 84",\n DATUM["WGS_1984",\n SPHEROID["WGS 84",6378137,298.257223563,\n AUTHORITY["EPSG","7030"]],\n AUTHORITY["EPSG","6326"]],\n PRIMEM["Greenwich",0,\n AUTHORITY["EPSG","8901"]],\n UNIT["degree",0.01745329251994328,\n AUTHORITY["EPSG","9122"]],\n AUTHORITY["EPSG","4326"]],\n PROJECTION["Sinusoidal"],\n PARAMETER["false_easting",0.0],\n PARAMETER["false_northing",0.0],\n PARAMETER["central_meridian",0.0],\n PARAMETER["semi_major",6371007.181],\n PARAMETER["semi_minor",6371007.181],\n UNIT["m",1.0],\n AUTHORITY["SR-ORG","6974"]]'}, 'geoTransform': [-20015109.354, 926.625433056, 0.0, 10007554.677, 0.0, -926.625433055], 'metadata': {'IMAGE_STRUCTURE': {'INTERLEAVE': 'PIXEL'}, 'SUBDATASETS': {'SUBDATASET_2_NAME': 'EEDAI:MODIS/006/MYD09GA/2017_05_24:num_observations_500m,sur_refl_b01,sur_refl_b02,sur_refl_b03,sur_refl_b04,sur_refl_b05,sur_refl_b06,sur_refl_b07,QC_500m,obscov_500m,iobs_res,q_scan', 'SUBDATASET_2_DESC': 'Bands num_observations_500m,sur_refl_b01,sur_refl_b02,sur_refl_b03,sur_refl_b04,sur_refl_b05,sur_refl_b06,sur_refl_b07,QC_500m,obscov_500m,iobs_res,q_scan of MODIS/006/MYD09GA/2017_05_24', 'SUBDATASET_1_NAME': 'EEDAI:MODIS/006/MYD09GA/2017_05_24:num_observations_1km,state_1km,SensorZenith,SensorAzimuth,Range,SolarZenith,SolarAzimuth,gflags,orbit_pnt,granule_pnt', 'SUBDATASET_1_DESC': 'Bands num_observations_1km,state_1km,SensorZenith,SensorAzimuth,Range,SolarZenith,SolarAzimuth,gflags,orbit_pnt,granule_pnt of MODIS/006/MYD09GA/2017_05_24'}}, 'size': [43200, 21600]} + assert expected == res + assert ds.ReadRaster(0, 0, 1, 1) is not None diff --git a/autotest/gdrivers/ehdr.py b/autotest/gdrivers/ehdr.py index 160ee300b853..ec9068bca114 100755 --- a/autotest/gdrivers/ehdr.py +++ b/autotest/gdrivers/ehdr.py @@ -32,11 +32,9 @@ import array import struct -import sys from osgeo import gdal -sys.path.append('../pymod') import gdaltest @@ -44,7 +42,7 @@ # 16bit image. -def ehdr_1(): +def test_ehdr_1(): tst = gdaltest.GDALTest('EHDR', 'rgba16.png', 2, 2042) @@ -54,7 +52,7 @@ def ehdr_1(): # 8bit with geotransform and projection check. -def ehdr_2(): +def test_ehdr_2(): tst = gdaltest.GDALTest('EHDR', 'byte.tif', 1, 4672) @@ -64,7 +62,7 @@ def ehdr_2(): # 32bit floating point (read, and createcopy). -def ehdr_3(): +def test_ehdr_3(): tst = gdaltest.GDALTest('EHDR', 'float32.bil', 1, 27) @@ -74,7 +72,7 @@ def ehdr_3(): # create dataset with a nodata value and a color table. -def ehdr_4(): +def test_ehdr_4(): drv = gdal.GetDriverByName('EHdr') ds = drv.Create('tmp/test_4.bil', 200, 100, 1, gdal.GDT_Byte) @@ -101,29 +99,21 @@ def ehdr_4(): ds = None - return 'success' - ############################################################################### # verify last dataset's colortable and nodata value. -def ehdr_5(): +def test_ehdr_5(): ds = gdal.Open('tmp/test_4.bil') band = ds.GetRasterBand(1) - if band.GetNoDataValue() != 17: - gdaltest.post_reason('failed to preserve nodata value.') - return 'fail' + assert band.GetNoDataValue() == 17, 'failed to preserve nodata value.' ct = band.GetRasterColorTable() - if ct is None or ct.GetCount() != 4 \ - or ct.GetColorEntry(2) != (255, 0, 255, 255): - gdaltest.post_reason('color table not persisted properly.') - return 'fail' + assert ct is not None and ct.GetCount() == 4 and ct.GetColorEntry(2) == (255, 0, 255, 255), \ + 'color table not persisted properly.' - if band.GetDefaultRAT(): - gdaltest.post_reason('did not expect RAT') - return 'fail' + assert not band.GetDefaultRAT(), 'did not expect RAT' band = None ct = None @@ -131,13 +121,11 @@ def ehdr_5(): gdal.GetDriverByName('EHdr').Delete('tmp/test_4.bil') - return 'success' - ############################################################################### # Test creating an in memory copy. -def ehdr_6(): +def test_ehdr_6(): tst = gdaltest.GDALTest('EHDR', 'float32.bil', 1, 27) @@ -147,7 +135,7 @@ def ehdr_6(): # 32bit integer (read, and createcopy). -def ehdr_7(): +def test_ehdr_7(): tst = gdaltest.GDALTest('EHDR', 'int32.tif', 1, 4672) @@ -157,7 +145,7 @@ def ehdr_7(): # Test signed 8bit integer support. (#2717) -def ehdr_8(): +def test_ehdr_8(): drv = gdal.GetDriverByName('EHDR') src_ds = gdal.Open('data/8s.vrt') @@ -165,23 +153,17 @@ def ehdr_8(): src_ds = None md = ds.GetRasterBand(1).GetMetadata('IMAGE_STRUCTURE') - if 'PIXELTYPE' not in md or md['PIXELTYPE'] != 'SIGNEDBYTE': - gdaltest.post_reason('Failed to detect SIGNEDBYTE') - return 'fail' + assert 'PIXELTYPE' in md and md['PIXELTYPE'] == 'SIGNEDBYTE', \ + 'Failed to detect SIGNEDBYTE' cs = ds.GetRasterBand(1).Checksum() expected = 4672 - if cs != expected: - print(cs) - gdaltest.post_reason('Did not get expected image checksum.') - return 'fail' + assert cs == expected, 'Did not get expected image checksum.' ds = None drv.Delete('tmp/ehdr_8.bil') - return 'success' - ############################################################################### # Test opening worldclim .hdr files that have a few extensions fields in the # .hdr file to specify minimum, maximum and projection. Also test that we @@ -189,35 +171,24 @@ def ehdr_8(): # value. -def ehdr_9(): +def test_ehdr_9(): ds = gdal.Open('data/wc_10m_CCCMA_A2a_2020_tmin_9.bil') - if ds.GetRasterBand(1).DataType != gdal.GDT_Int16: - gdaltest.post_reason('wrong datatype') - print(ds.GetRasterBand(1).DataType) - return 'fail' + assert ds.GetRasterBand(1).DataType == gdal.GDT_Int16, 'wrong datatype' - if ds.GetRasterBand(1).GetMinimum() != -191: - gdaltest.post_reason('wrong minimum value') - print(ds.GetRasterBand(1).GetMinimum()) - return 'fail' + assert ds.GetRasterBand(1).GetMinimum() == -191, 'wrong minimum value' wkt = ds.GetProjectionRef() - if wkt.find('GEOGCS["WGS 84') != 0: - gdaltest.post_reason('wrong projection') - print(wkt) - return 'fail' + assert wkt.find('GEOGCS["WGS 84') == 0, 'wrong projection' ds = None - return 'success' - ############################################################################### # Test detecting floating point file based on image file size (#3933) -def ehdr_10(): +def test_ehdr_10(): tst = gdaltest.GDALTest('EHDR', 'ehdr10.bil', 1, 8202) return tst.testOpen() @@ -225,7 +196,7 @@ def ehdr_10(): # Test detecting floating point file based on .flt extension (#3933) -def ehdr_11(): +def test_ehdr_11(): tst = gdaltest.GDALTest('EHDR', 'ehdr11.flt', 1, 8202) return tst.testOpen() @@ -233,7 +204,7 @@ def ehdr_11(): # Test CreateCopy with 1bit data -def ehdr_12(): +def test_ehdr_12(): src_ds = gdal.Open('../gcore/data/1bit.bmp') ds = gdal.GetDriverByName('EHDR').CreateCopy('/vsimem/1bit.bil', src_ds, @@ -241,21 +212,18 @@ def ehdr_12(): ds = None ds = gdal.Open('/vsimem/1bit.bil') - if ds.GetRasterBand(1).Checksum() != src_ds.GetRasterBand(1).Checksum(): - gdaltest.post_reason('did not get expected checksum') - return 'fail' + assert ds.GetRasterBand(1).Checksum() == src_ds.GetRasterBand(1).Checksum(), \ + 'did not get expected checksum' ds = None src_ds = None gdal.GetDriverByName('EHDR').Delete('/vsimem/1bit.bil') - return 'success' - ############################################################################### # Test statistics -def ehdr_13(): +def test_ehdr_13(): gdal.Unlink('data/byte.tif.aux.xml') @@ -265,50 +233,36 @@ def ehdr_13(): src_ds = None ds = gdal.Open('/vsimem/byte.bil') - if ds.GetRasterBand(1).GetMinimum() is not None: - gdaltest.post_reason('did not expected minimum') - return 'fail' - if ds.GetRasterBand(1).GetMaximum() is not None: - gdaltest.post_reason('did not expected maximum') - return 'fail' + assert ds.GetRasterBand(1).GetMinimum() is None, 'did not expected minimum' + assert ds.GetRasterBand(1).GetMaximum() is None, 'did not expected maximum' stats = ds.GetRasterBand(1).GetStatistics(False, True) expected_stats = [74.0, 255.0, 126.765, 22.928470838675704] for i in range(4): - if abs(stats[i] - expected_stats[i]) > 0.0001: - gdaltest.post_reason('did not get expected statistics') - return 'fail' + assert abs(stats[i] - expected_stats[i]) <= 0.0001, 'did not get expected statistics' ds = None f = gdal.VSIFOpenL('/vsimem/byte.stx', 'rb') - if f is None: - gdaltest.post_reason('expected .stx file') - return 'fail' + assert f is not None, 'expected .stx file' gdal.VSIFCloseL(f) ds = gdal.Open('/vsimem/byte.bil') - if abs(ds.GetRasterBand(1).GetMinimum() - 74) > 0.0001: - gdaltest.post_reason('did not get expected minimum') - return 'fail' - if abs(ds.GetRasterBand(1).GetMaximum() - 255) > 0.0001: - gdaltest.post_reason('did not get expected maximum') - return 'fail' + assert abs(ds.GetRasterBand(1).GetMinimum() - 74) <= 0.0001, \ + 'did not get expected minimum' + assert abs(ds.GetRasterBand(1).GetMaximum() - 255) <= 0.0001, \ + 'did not get expected maximum' stats = ds.GetRasterBand(1).GetStatistics(False, True) expected_stats = [74.0, 255.0, 126.765, 22.928470838675704] for i in range(4): - if abs(stats[i] - expected_stats[i]) > 0.0001: - gdaltest.post_reason('did not get expected statistics') - return 'fail' + assert abs(stats[i] - expected_stats[i]) <= 0.0001, 'did not get expected statistics' ds = None gdal.GetDriverByName('EHDR').Delete('/vsimem/byte.bil') - return 'success' - ############################################################################### # Test optimized RasterIO() (#5438) -def ehdr_14(): +def test_ehdr_14(): src_ds = gdal.Open('data/byte.tif') ds = gdal.GetDriverByName('EHDR').CreateCopy('/vsimem/byte.bil', src_ds) @@ -331,17 +285,9 @@ def ehdr_14(): out_ds.FlushCache() cs2 = out_ds.GetRasterBand(1).Checksum() - if space == 1 and data != data2: - gdaltest.post_reason('fail') - print(space) - return 'fail' + assert space != 1 or data == data2 - if (cs1 != 1087 and cs1 != 1192) or (cs2 != 1087 and cs2 != 1192): - gdaltest.post_reason('fail') - print(space) - print(cs1) - print(cs2) - return 'fail' + assert not (cs1 != 1087 and cs1 != 1192) or (cs2 != 1087 and cs2 != 1192), space gdal.SetConfigOption('GDAL_ONE_BIG_READ', 'YES') out_ds.GetRasterBand(1).WriteRaster( @@ -350,53 +296,31 @@ def ehdr_14(): out_ds.FlushCache() cs3 = out_ds.GetRasterBand(1).Checksum() - if cs3 != 1087 and cs3 != 1192: - gdaltest.post_reason('fail') - print(space) - print(cs3) - return 'fail' + assert cs3 == 1087 or cs3 == 1192, space ds = None gdal.GetDriverByName('EHDR').Delete('/vsimem/byte.bil') gdal.GetDriverByName('EHDR').Delete('/vsimem/byte_reduced.bil') - return 'success' - ############################################################################### # Test support for RAT (#3253) -def ehdr_rat(): +def test_ehdr_rat(): tmpfile = '/vsimem/rat.bil' gdal.Translate(tmpfile, 'data/int16_rat.bil', format='EHdr') ds = gdal.Open(tmpfile) rat = ds.GetRasterBand(1).GetDefaultRAT() - if rat is None: - gdaltest.post_reason('fail') - return 'fail' - if rat.GetColumnCount() != 4: - gdaltest.post_reason('fail') - print(rat.GetColumnCount()) - return 'fail' - if rat.GetRowCount() != 25: - gdaltest.post_reason('fail') - print(rat.GetRowCount()) - return 'fail' + assert rat is not None + assert rat.GetColumnCount() == 4 + assert rat.GetRowCount() == 25 for (idx, val) in [(0, -500), (1, 127), (2, 40), (3, 65)]: - if rat.GetValueAsInt(0, idx) != val: - gdaltest.post_reason('fail') - print(idx, rat.GetValueAsInt(0, idx)) - return 'fail' + assert rat.GetValueAsInt(0, idx) == val for (idx, val) in [(0, 2000), (1, 145), (2, 97), (3, 47)]: - if rat.GetValueAsInt(24, idx) != val: - gdaltest.post_reason('fail') - print(idx, rat.GetValueAsInt(24, idx)) - return 'fail' - if ds.GetRasterBand(1).GetColorTable() is None: - gdaltest.post_reason('fail') - return 'fail' + assert rat.GetValueAsInt(24, idx) == val + assert ds.GetRasterBand(1).GetColorTable() is not None ds = None ds = gdal.Open(tmpfile, gdal.GA_Update) @@ -405,26 +329,20 @@ def ehdr_rat(): ds = None ds = gdal.Open(tmpfile, gdal.GA_Update) - if ds.GetRasterBand(1).GetDefaultRAT() or ds.GetRasterBand(1).GetColorTable(): - gdaltest.post_reason('fail') - return 'fail' + assert not (ds.GetRasterBand(1).GetDefaultRAT() or ds.GetRasterBand(1).GetColorTable()) with gdaltest.error_handler(): ret = ds.GetRasterBand(1).SetDefaultRAT(gdal.RasterAttributeTable()) - if ret == 0: - gdaltest.post_reason('fail') - return 'fail' + assert ret != 0 ds = None gdal.GetDriverByName('EHDR').Delete(tmpfile) - return 'success' - ############################################################################### # Test STATISTICS_APPROXIMATE -def ehdr_approx_stats_flag(): +def test_ehdr_approx_stats_flag(): src_ds = gdal.GetDriverByName('MEM').Create('', 2000, 2000) src_ds.GetRasterBand(1).WriteRaster(1000, 1000, 1, 1, struct.pack('B' * 1, 20)) @@ -435,74 +353,30 @@ def ehdr_approx_stats_flag(): 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 'STATISTICS_APPROXIMATE' not in md: - gdaltest.post_reason('did not get expected metadata') - print(md) - return 'fail' + assert 'STATISTICS_APPROXIMATE' in md, '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' ds = gdal.Open(tmpfile, gdal.GA_Update) 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' + assert 'STATISTICS_APPROXIMATE' not in md, 'did not get expected metadata' ds = None gdal.GetDriverByName('EHDR').Delete(tmpfile) - return 'success' - - -gdaltest_list = [ - ehdr_1, - ehdr_2, - ehdr_3, - ehdr_4, - ehdr_5, - ehdr_6, - ehdr_7, - ehdr_8, - ehdr_9, - ehdr_10, - ehdr_11, - ehdr_12, - ehdr_13, - ehdr_14, - ehdr_rat, - ehdr_approx_stats_flag] - -if __name__ == '__main__': - - gdaltest.setup_run('ehdr') - gdaltest.run_tests(gdaltest_list) - sys.exit(gdaltest.summarize()) diff --git a/autotest/gdrivers/eir.py b/autotest/gdrivers/eir.py index 1f27fb2277b1..8abf87b0686d 100755 --- a/autotest/gdrivers/eir.py +++ b/autotest/gdrivers/eir.py @@ -28,9 +28,7 @@ # DEALINGS IN THE SOFTWARE. ############################################################################### -import sys -sys.path.append('../pymod') import gdaltest @@ -38,19 +36,10 @@ # Test a fake EIR dataset -def eir_1(): +def test_eir_1(): tst = gdaltest.GDALTest('EIR', 'fakeeir.hdr', 1, 1) return tst.testOpen() -gdaltest_list = [ - eir_1] -if __name__ == '__main__': - - gdaltest.setup_run('eir') - - gdaltest.run_tests(gdaltest_list) - - sys.exit(gdaltest.summarize()) diff --git a/autotest/gdrivers/elas.py b/autotest/gdrivers/elas.py index 6a86a29b7718..a1a47af112cb 100755 --- a/autotest/gdrivers/elas.py +++ b/autotest/gdrivers/elas.py @@ -28,9 +28,7 @@ # DEALINGS IN THE SOFTWARE. ############################################################################### -import sys -sys.path.append('../pymod') import gdaltest @@ -38,7 +36,7 @@ # Test a dataset generated by Create() -def elas_1(): +def test_elas_1(): tst = gdaltest.GDALTest('ELAS', 'byte_elas.bin', 1, 4672) return tst.testOpen() @@ -47,20 +45,10 @@ def elas_1(): # Test Create() -def elas_2(): +def test_elas_2(): tst = gdaltest.GDALTest('ELAS', 'byte_elas.bin', 1, 4672) return tst.testCreate() -gdaltest_list = [ - elas_1, - elas_2] -if __name__ == '__main__': - - gdaltest.setup_run('elas') - - gdaltest.run_tests(gdaltest_list) - - sys.exit(gdaltest.summarize()) diff --git a/autotest/gdrivers/envi.py b/autotest/gdrivers/envi.py index ac0c971cdb2a..e8b09067dee6 100755 --- a/autotest/gdrivers/envi.py +++ b/autotest/gdrivers/envi.py @@ -32,10 +32,8 @@ # DEALINGS IN THE SOFTWARE. ############################################################################### -import sys from osgeo import gdal -sys.path.append('../pymod') import gdaltest @@ -43,7 +41,7 @@ # Perform simple read test. -def envi_1(): +def test_envi_1(): tst = gdaltest.GDALTest('envi', 'aea.dat', 1, 14823) @@ -70,7 +68,7 @@ def envi_1(): # Verify this can be exported losslessly. -def envi_2(): +def test_envi_2(): tst = gdaltest.GDALTest('envi', 'aea.dat', 1, 14823) return tst.testCreateCopy(check_gt=1) @@ -79,7 +77,7 @@ def envi_2(): # Try the Create interface with an RGB image. -def envi_3(): +def test_envi_3(): tst = gdaltest.GDALTest('envi', 'rgbsmall.tif', 2, 21053) return tst.testCreate() @@ -88,7 +86,7 @@ def envi_3(): # Test LCC Projection. -def envi_4(): +def test_envi_4(): tst = gdaltest.GDALTest('envi', 'aea.dat', 1, 24) @@ -113,7 +111,7 @@ def envi_4(): # Test TM Projection. -def envi_5(): +def test_envi_5(): tst = gdaltest.GDALTest('envi', 'aea.dat', 1, 24) prj = """PROJCS["OSGB 1936 / British National Grid", @@ -159,7 +157,7 @@ def envi_5(): # Test LAEA Projection. -def envi_6(): +def test_envi_6(): gdaltest.envi_tst = gdaltest.GDALTest('envi', 'aea.dat', 1, 24) @@ -181,7 +179,7 @@ def envi_6(): # Verify VSIF*L capacity -def envi_7(): +def test_envi_7(): tst = gdaltest.GDALTest('envi', 'aea.dat', 1, 14823) return tst.testCreateCopy(check_gt=1, vsimem=1) @@ -190,27 +188,22 @@ def envi_7(): # Test fix for #3751 -def envi_8(): +def test_envi_8(): ds = gdal.GetDriverByName('ENVI').Create('/vsimem/foo.bsq', 10, 10, 1) set_gt = (50000, 1, 0, 4500000, 0, -1) ds.SetGeoTransform(set_gt) got_gt = ds.GetGeoTransform() - if set_gt != got_gt: - gdaltest.post_reason('did not get expected geotransform') - print(got_gt) - return 'fail' + assert set_gt == got_gt, 'did not get expected geotransform' ds = None gdal.GetDriverByName('ENVI').Delete('/vsimem/foo.bsq') - return 'success' - ############################################################################### # Verify reading a compressed file -def envi_9(): +def test_envi_9(): tst = gdaltest.GDALTest('envi', 'aea_compressed.dat', 1, 14823) return tst.testCreateCopy(check_gt=1) @@ -219,7 +212,7 @@ def envi_9(): # Test RPC reading and writing -def envi_10(): +def test_envi_10(): src_ds = gdal.Open('data/envirpc.img') out_ds = gdal.GetDriverByName('ENVI').CreateCopy('/vsimem/envirpc.img', src_ds) @@ -234,34 +227,25 @@ def envi_10(): gdal.GetDriverByName('ENVI').Delete('/vsimem/envirpc.img') - if md['HEIGHT_OFF'] != '3355': - print(md) - return 'fail' - - return 'success' + assert md['HEIGHT_OFF'] == '3355' ############################################################################### # Check .sta reading -def envi_11(): +def test_envi_11(): ds = gdal.Open('data/envistat') val = ds.GetRasterBand(1).GetStatistics(0, 0) ds = None - if val != [1.0, 3.0, 2.0, 0.5]: - gdaltest.post_reason('bad stats') - print(val) - return 'fail' - - return 'success' + assert val == [1.0, 3.0, 2.0, 0.5], 'bad stats' ############################################################################### # Test category names reading and writing -def envi_12(): +def test_envi_12(): src_ds = gdal.Open('data/testenviclasses') out_ds = gdal.GetDriverByName('ENVI').CreateCopy('/vsimem/testenviclasses', src_ds) @@ -274,31 +258,20 @@ def envi_12(): category = ds.GetRasterBand(1).GetCategoryNames() ct = ds.GetRasterBand(1).GetColorTable() - if category != ['Black', 'White']: - gdaltest.post_reason('bad category names') - print(category) - return 'fail' + assert category == ['Black', 'White'], 'bad category names' - if ct.GetCount() != 2: - gdaltest.post_reason('bad color entry count') - print(ct.GetCount()) - return 'fail' + assert ct.GetCount() == 2, 'bad color entry count' - if ct.GetColorEntry(0) != (0, 0, 0, 255): - gdaltest.post_reason('bad color entry') - print(ct.GetColorEntry(0)) - return 'fail' + assert ct.GetColorEntry(0) == (0, 0, 0, 255), 'bad color entry' ds = None gdal.GetDriverByName('ENVI').Delete('/vsimem/testenviclasses') - return 'success' - ############################################################################### # Test writing of metadata from the ENVI metadata domain and read it back (#4957) -def envi_13(): +def test_envi_13(): ds = gdal.GetDriverByName('ENVI').Create('/vsimem/envi_13.dat', 1, 1) ds.SetMetadata(['lines=100', 'sensor_type=Landsat TM', 'foo'], 'ENVI') @@ -312,64 +285,51 @@ def envi_13(): ds = None gdal.GetDriverByName('ENVI').Delete('/vsimem/envi_13.dat') - if lines != 1: - return 'fail' - - if val != 'Landsat TM': - return 'fail' + assert lines == 1 - return 'success' + assert val == 'Landsat TM' ############################################################################### # Test that the image file is at the expected size on closing (#6662) -def envi_14(): +def test_envi_14(): gdal.GetDriverByName('ENVI').Create('/vsimem/envi_14.dat', 3, 4, 5, gdal.GDT_Int16) gdal.Unlink('/vsimem/envi_14.dat.aux.xml') - if gdal.VSIStatL('/vsimem/envi_14.dat').size != 3 * 4 * 5 * 2: - return 'fail' + assert gdal.VSIStatL('/vsimem/envi_14.dat').size == 3 * 4 * 5 * 2 gdal.GetDriverByName('ENVI').Delete('/vsimem/envi_14.dat') - return 'success' - ############################################################################### # Test reading and writing geotransform matrix with rotation -def envi_15(): +def test_envi_15(): src_ds = gdal.Open('data/rotation.img') got_gt = src_ds.GetGeoTransform() expected_gt = [736600.089, 1.0981889363046606, -2.4665727356350224, 4078126.75, -2.4665727356350224, -1.0981889363046606] - if max([abs((got_gt[i] - expected_gt[i]) / expected_gt[i]) for i in range(6)]) > 1e-5: - gdaltest.post_reason('did not get expected geotransform') - print(got_gt) - return 'fail' + assert max([abs((got_gt[i] - expected_gt[i]) / expected_gt[i]) for i in range(6)]) <= 1e-5, \ + 'did not get expected geotransform' gdal.GetDriverByName('ENVI').CreateCopy('/vsimem/envi_15.dat', src_ds) ds = gdal.Open('/vsimem/envi_15.dat') got_gt = ds.GetGeoTransform() - if max([abs((got_gt[i] - expected_gt[i]) / expected_gt[i]) for i in range(6)]) > 1e-5: - gdaltest.post_reason('did not get expected geotransform') - print(got_gt) - return 'fail' + assert max([abs((got_gt[i] - expected_gt[i]) / expected_gt[i]) for i in range(6)]) <= 1e-5, \ + 'did not get expected geotransform' ds = None gdal.GetDriverByName('ENVI').Delete('/vsimem/envi_15.dat') - return 'success' - ############################################################################### # Test reading a truncated ENVI dataset (see #915) -def envi_truncated(): +def test_envi_truncated(): gdal.GetDriverByName('ENVI').CreateCopy('/vsimem/envi_truncated.dat', gdal.Open('data/byte.tif')) @@ -384,37 +344,8 @@ def envi_truncated(): ds = None gdal.GetDriverByName('ENVI').Delete('/vsimem/envi_truncated.dat') - if cs != 2315: - print(cs) - return 'fail' - - return 'success' - - -gdaltest_list = [ - envi_1, - envi_2, - envi_3, - envi_4, - envi_5, - envi_6, - envi_7, - envi_8, - envi_9, - envi_10, - envi_11, - envi_12, - envi_13, - envi_14, - envi_15, - envi_truncated, -] - + assert cs == 2315 -if __name__ == '__main__': - gdaltest.setup_run('envi') - gdaltest.run_tests(gdaltest_list) - sys.exit(gdaltest.summarize()) diff --git a/autotest/gdrivers/envisat.py b/autotest/gdrivers/envisat.py index 0cdeb4c62587..4aa777a48452 100755 --- a/autotest/gdrivers/envisat.py +++ b/autotest/gdrivers/envisat.py @@ -31,13 +31,12 @@ ############################################################################### import os -import sys import gzip from osgeo import gdal -sys.path.append('../pymod') import gdaltest +import pytest def _get_mds_num(filename): @@ -75,15 +74,9 @@ def _get_mds_num(filename): # -class TestEnvisat(object): +class EnvisatTestBase(object): # Just a base class - def __init__(self, downloadURL, fileName, size, checksum): - self.downloadURL = downloadURL - self.fileName = fileName - self.size = size - self.checksum = checksum - def download_file(self): # download and decompress if not gdaltest.download_file(self.downloadURL, os.path.basename(self.downloadURL), -1): @@ -104,130 +97,107 @@ def download_file(self): def test_envisat_1(self): if not self.download_file(): - return 'skip' + pytest.skip() ds = gdal.Open(os.path.join('tmp', 'cache', self.fileName)) - if ds is None: - return 'fail' - - if (ds.RasterXSize, ds.RasterYSize) != self.size: - gdaltest.post_reason('Bad size. Expected %s, got %s' % (self.size, (ds.RasterXSize, ds.RasterYSize))) - return 'fail' + assert ds is not None - return 'success' + assert (ds.RasterXSize, ds.RasterYSize) == self.size, \ + ('Bad size. Expected %s, got %s' % (self.size, (ds.RasterXSize, ds.RasterYSize))) def test_envisat_2(self): if not self.download_file(): - return 'skip' + pytest.skip() ds = gdal.Open(os.path.join('tmp', 'cache', self.fileName)) - if ds is None: - return 'fail' + assert ds is not None - if ds.GetRasterBand(1).Checksum() != self.checksum: - gdaltest.post_reason('Bad checksum. Expected %d, got %d' % (self.checksum, ds.GetRasterBand(1).Checksum())) - return 'fail' - - return 'success' + assert ds.GetRasterBand(1).Checksum() == self.checksum, \ + ('Bad checksum. Expected %d, got %d' % (self.checksum, ds.GetRasterBand(1).Checksum())) def test_envisat_3(self): # Regression test for #3160 and #3709. if not self.download_file(): - return 'skip' + pytest.skip() ds = gdal.Open(os.path.join('tmp', 'cache', self.fileName)) - if ds is None: - return 'fail' + assert ds is not None d = {} for gcp in ds.GetGCPs(): lp = (gcp.GCPLine, gcp.GCPPixel) if lp in d: - gdaltest.post_reason('Duplicate GCP coordinates.') - return 'fail' + pytest.fail('Duplicate GCP coordinates.') else: d[lp] = (gcp.GCPX, gcp.GCPY, gcp.GCPZ) - return 'success' - + def test_envisat_4(self): # test number of bands if not self.download_file(): - return 'skip' + pytest.skip() filename = os.path.join('tmp', 'cache', self.fileName) mds_num = _get_mds_num(filename) ds = gdal.Open(filename) - if ds is None: - return 'fail' + assert ds is not None - if ds.RasterCount < mds_num: - gdaltest.post_reason('Not all bands have been detected') - return 'fail' - - return 'success' + assert ds.RasterCount >= mds_num, 'Not all bands have been detected' def test_envisat_5(self): # test metadata in RECORDS domain if not self.download_file(): - return 'skip' + pytest.skip() ds = gdal.Open(os.path.join('tmp', 'cache', self.fileName)) - if ds is None: - return 'fail' + assert ds is not None product = ds.GetMetadataItem('MPH_PRODUCT') record_md = ds.GetMetadata('RECORDS') - if product[:3] not in ('ASA', 'SAR', 'MER') and record_md: - gdaltest.post_reason('Unexpected metadata in the "RECORDS" domain.') - return 'fail' - - return 'success' + assert product[:3] in ('ASA', 'SAR', 'MER') or not record_md, \ + 'Unexpected metadata in the "RECORDS" domain.' ############################################################################### # -class TestEnvisatASAR(TestEnvisat): +class TestEnvisatASAR(EnvisatTestBase): + downloadURL = 'http://earth.esa.int/services/sample_products/asar/DS1/WS/ASA_WS__BPXPDE20020714_100425_000001202007_00380_01937_0053.N1.gz' + fileName = 'ASA_WS__BPXPDE20020714_100425_000001202007_00380_01937_0053.N1' + size = (524, 945) + checksum = 44998 + def test_envisat_asar_1(self): # test sensor ID if not self.download_file(): - return 'skip' + pytest.skip() ds = gdal.Open(os.path.join('tmp', 'cache', self.fileName)) - if ds is None: - return 'fail' + assert ds is not None product = ds.GetMetadataItem('MPH_PRODUCT') - if product[:3] not in ('ASA', 'SAR'): - gdaltest.post_reason('Wrong sensor ID.') - return 'fail' - - return 'success' + assert product[:3] in ('ASA', 'SAR'), 'Wrong sensor ID.' def test_envisat_asar_2(self): # test metadata in RECORDS domain if not self.download_file(): - return 'skip' + pytest.skip() ds = gdal.Open(os.path.join('tmp', 'cache', self.fileName)) - if ds is None: - return 'fail' + assert ds is not None product = ds.GetMetadataItem('MPH_PRODUCT') record_md = ds.GetMetadata('RECORDS') - if not record_md: - gdaltest.post_reason('Unable to read ADS metadata from ASAR.') - return 'fail' + assert record_md, 'Unable to read ADS metadata from ASAR.' record = 'SQ_ADS' # it is present in all ASAR poducts if product.startswith('ASA_WV'): @@ -237,11 +207,9 @@ def test_envisat_asar_2(self): 'PHASE_CROSS_CONF'): key0 = '%s_%s' % (record, field) key1 = '%s_0_%s' % (record, field) - if key0 not in record_md and key1 not in record_md: - gdaltest.post_reason( - 'No "%s" or "%s" key in "RECORDS" domain.' % + assert key0 in record_md or key1 in record_md, \ + ('No "%s" or "%s" key in "RECORDS" domain.' % (key0, key1)) - return 'fail' else: for mds in range(1, ds.RasterCount + 1): for field in ('ZERO_DOPPLER_TIME', @@ -249,75 +217,65 @@ def test_envisat_asar_2(self): 'INPUT_STD_DEV'): key0 = 'MDS%d_%s_%s' % (mds, record, field) key1 = 'MDS%d_%s_0_%s' % (mds, record, field) - if key0 not in record_md and key1 not in record_md: - gdaltest.post_reason( - 'No "%s" or "%s" key in "RECORDS" domain.' % + assert key0 in record_md or key1 in record_md, \ + ('No "%s" or "%s" key in "RECORDS" domain.' % (key0, key1)) - return 'fail' - - return 'success' + ############################################################################### # -class TestEnvisatMERIS(TestEnvisat): +class TestEnvisatMERIS(EnvisatTestBase): + downloadURL = 'http://earth.esa.int/services/sample_products/meris/RRC/L2/MER_RRC_2PTGMV20000620_104318_00000104X000_00000_00000_0001.N1.gz' + fileName = 'MER_RRC_2PTGMV20000620_104318_00000104X000_00000_00000_0001.N1' + size = (1121, 593) + checksum = 55146 + def test_envisat_meris_1(self): # test sensor ID if not self.download_file(): - return 'skip' + pytest.skip() ds = gdal.Open(os.path.join('tmp', 'cache', self.fileName)) - if ds is None: - return 'fail' + assert ds is not None product = ds.GetMetadataItem('MPH_PRODUCT') - if product[:3] not in ('MER',): - gdaltest.post_reason('Wrong sensor ID.') - return 'fail' - - return 'success' + assert product[:3] in ('MER',), 'Wrong sensor ID.' def test_envisat_meris_2(self): # test metadata in RECORDS domain if not self.download_file(): - return 'skip' + pytest.skip() ds = gdal.Open(os.path.join('tmp', 'cache', self.fileName)) - if ds is None: - return 'fail' + assert ds is not None record_md = ds.GetMetadata('RECORDS') - if not record_md: - gdaltest.post_reason('Unable to read ADS metadata from ASAR.') - return 'fail' + assert record_md, 'Unable to read ADS metadata from ASAR.' record = 'Quality_ADS' # it is present in all MER poducts for field in ('DSR_TIME', 'ATTACH_FLAG'): key0 = '%s_%s' % (record, field) key1 = '%s_0_%s' % (record, field) - if key0 not in record_md and key1 not in record_md: - gdaltest.post_reason( - 'No "%s" or "%s" key in "RECORDS" domain.' % + assert key0 in record_md or key1 in record_md, \ + ('No "%s" or "%s" key in "RECORDS" domain.' % (key0, key1)) - return 'fail' - - return 'success' + def test_envisat_meris_3(self): # test Flag bands if not self.download_file(): - return 'skip' + pytest.skip() ds = gdal.Open(os.path.join('tmp', 'cache', self.fileName)) - if ds is None: - return 'fail' + assert ds is not None flags_band = None detector_index_band = None @@ -332,52 +290,39 @@ def test_envisat_meris_3(self): product = ds.GetMetadataItem('MPH_PRODUCT') level = product[8] if level == '1': - if not flags_band: - gdaltest.post_reason('No flag band in MERIS Level 1 product.') - return 'fail' + assert flags_band, 'No flag band in MERIS Level 1 product.' band = ds.GetRasterBand(flags_band) - if band.DataType != gdal.GDT_Byte: - gdaltest.post_reason('Incorrect data type of the flag band in ' + assert band.DataType == gdal.GDT_Byte, \ + ('Incorrect data type of the flag band in ' 'MERIS Level 1 product.') - return 'fail' - if not detector_index_band: - gdaltest.post_reason('No "detector index" band in MERIS ' + assert detector_index_band, ('No "detector index" band in MERIS ' 'Level 1 product.') - return 'fail' band = ds.GetRasterBand(detector_index_band) - if band.DataType != gdal.GDT_Int16: - gdaltest.post_reason('Incorrect data type of the ' + assert band.DataType == gdal.GDT_Int16, ('Incorrect data type of the ' '"detector index" band in MERIS Level 2 ' 'product.') - return 'fail' elif level == '2': - if not flags_band: - gdaltest.post_reason('No flag band in MERIS Level 2 product.') - return 'fail' + assert flags_band, 'No flag band in MERIS Level 2 product.' band = ds.GetRasterBand(flags_band) - if band.DataType != gdal.GDT_UInt32: - gdaltest.post_reason('Incorrect data type of the flag band in ' + assert band.DataType == gdal.GDT_UInt32, \ + ('Incorrect data type of the flag band in ' 'MERIS Level 2 product.') - return 'fail' else: - gdaltest.post_reason('Invalid product level: %s.' % level) - return 'fail' - - return 'success' + pytest.fail('Invalid product level: %s.' % level) + def test_envisat_meris_4(self): # test DEM corrections (see #5423) if not self.download_file(): - return 'skip' + pytest.skip() ds = gdal.Open(os.path.join('tmp', 'cache', self.fileName)) - if ds is None: - return 'fail' + assert ds is not None gcp_values = [ (gcp.Id, gcp.GCPLine, gcp.GCPPixel, gcp.GCPX, gcp.GCPY, gcp.GCPZ) @@ -400,47 +345,7 @@ def test_envisat_meris_4(self): for r, v in zip(ref, gcp_values): for i, ri in enumerate(r): if abs(float(ri) - float(v[i])) > 1e-10: - gdaltest.post_reason('Wrong GCP coordinates.') print(r) - print(v) - return 'fail' - - return 'success' - - -ut1 = TestEnvisatASAR( - 'http://earth.esa.int/services/sample_products/asar/DS1/WS/ASA_WS__BPXPDE20020714_100425_000001202007_00380_01937_0053.N1.gz', - 'ASA_WS__BPXPDE20020714_100425_000001202007_00380_01937_0053.N1', - (524, 945), - 44998) -ut2 = TestEnvisatMERIS( - 'http://earth.esa.int/services/sample_products/meris/RRC/L2/MER_RRC_2PTGMV20000620_104318_00000104X000_00000_00000_0001.N1.gz', - 'MER_RRC_2PTGMV20000620_104318_00000104X000_00000_00000_0001.N1', - (1121, 593), - 55146) - -gdaltest_list = [ - ut1.test_envisat_1, - ut1.test_envisat_2, - ut1.test_envisat_3, - ut1.test_envisat_4, - ut1.test_envisat_asar_1, - ut1.test_envisat_asar_2, - ut2.test_envisat_1, - ut2.test_envisat_2, - ut2.test_envisat_3, - ut2.test_envisat_4, - ut2.test_envisat_meris_1, - ut2.test_envisat_meris_2, - ut2.test_envisat_meris_3, - ut2.test_envisat_meris_4, -] - - -if __name__ == '__main__': - - gdaltest.setup_run('envisat') - - gdaltest.run_tests(gdaltest_list) - - sys.exit(gdaltest.summarize()) + pytest.fail('Wrong GCP coordinates.') + + diff --git a/autotest/gdrivers/ers.py b/autotest/gdrivers/ers.py index a4407ef385ec..2ec2d6e806e5 100755 --- a/autotest/gdrivers/ers.py +++ b/autotest/gdrivers/ers.py @@ -30,37 +30,31 @@ # DEALINGS IN THE SOFTWARE. ############################################################################### -import sys from osgeo import gdal from osgeo import osr -sys.path.append('../pymod') import gdaltest +import pytest ############################################################################### # Perform simple read test. -def ers_1(): +def test_ers_1(): tst = gdaltest.GDALTest('ERS', 'srtm.ers', 1, 64074) - if tst.testOpen() != 'success': - return 'fail' + tst.testOpen() ds = gdal.Open('data/srtm.ers') md = ds.GetRasterBand(1).GetMetadata() expected_md = {'STATISTICS_MEAN': '-4020.25', 'STATISTICS_MINIMUM': '-4315', 'STATISTICS_MAXIMUM': '-3744', 'STATISTICS_MEDIAN': '-4000'} - if md != expected_md: - gdaltest.post_reason('fail') - print(md) - return 'fail' - return 'success' + assert md == expected_md ############################################################################### # Create simple copy and check. -def ers_2(): +def test_ers_2(): tst = gdaltest.GDALTest('ERS', 'float32.bil', 1, 27) return tst.testCreateCopy(new_filename='tmp/float32.ers', @@ -70,7 +64,7 @@ def ers_2(): # Test multi-band file. -def ers_3(): +def test_ers_3(): tst = gdaltest.GDALTest('ERS', 'rgbsmall.tif', 2, 21053) return tst.testCreate(new_filename='tmp/rgbsmall.ers') @@ -79,7 +73,7 @@ def ers_3(): # Test HeaderOffset case. -def ers_4(): +def test_ers_4(): gt = (143.59625, 0.025, 0.0, -39.38125, 0.0, -0.025) srs = """GEOGCS["GEOCENTRIC DATUM of AUSTRALIA", @@ -95,24 +89,20 @@ def ers_4(): # Confirm we can recognised signed 8bit data. -def ers_5(): +def test_ers_5(): ds = gdal.Open('data/8s.ers') md = ds.GetRasterBand(1).GetMetadata('IMAGE_STRUCTURE') - if md['PIXELTYPE'] != 'SIGNEDBYTE': - gdaltest.post_reason('Failed to detect SIGNEDBYTE') - return 'fail' + assert md['PIXELTYPE'] == 'SIGNEDBYTE', 'Failed to detect SIGNEDBYTE' ds = None - return 'success' - ############################################################################### # Confirm a copy preserves the signed byte info. -def ers_6(): +def test_ers_6(): drv = gdal.GetDriverByName('ERS') @@ -122,38 +112,29 @@ def ers_6(): md = ds.GetRasterBand(1).GetMetadata('IMAGE_STRUCTURE') - if md['PIXELTYPE'] != 'SIGNEDBYTE': - gdaltest.post_reason('Failed to detect SIGNEDBYTE') - return 'fail' + assert md['PIXELTYPE'] == 'SIGNEDBYTE', 'Failed to detect SIGNEDBYTE' ds = None drv.Delete('tmp/8s.ers') - return 'success' - ############################################################################### # Test opening a file with everything in lower case. -def ers_7(): +def test_ers_7(): ds = gdal.Open('data/caseinsensitive.ers') desc = ds.GetRasterBand(1).GetDescription() - if desc != 'RTP 1st Vertical Derivative': - print(desc) - gdaltest.post_reason('did not get expected values.') - return 'fail' - - return 'success' + assert desc == 'RTP 1st Vertical Derivative', 'did not get expected values.' ############################################################################### # Test GCP support -def ers_8(): +def test_ers_8(): src_ds = gdal.Open('../gcore/data/gcps.vrt') drv = gdal.GetDriverByName('ERS') @@ -169,33 +150,27 @@ def ers_8(): wkt = ds.GetGCPProjection() ds = None - if wkt != """PROJCS["NUTM11",GEOGCS["NAD27",DATUM["North_American_Datum_1927",SPHEROID["Clarke 1866",6378206.4,294.978698213898,AUTHORITY["EPSG","7008"]],TOWGS84[-3,142,183,0,0,0,0],AUTHORITY["EPSG","6267"]],PRIMEM["Greenwich",0,AUTHORITY["EPSG","8901"]],UNIT["degree",0.0174532925199433,AUTHORITY["EPSG","9108"]],AXIS["Lat",NORTH],AXIS["Long",EAST],AUTHORITY["EPSG","4267"]],PROJECTION["Transverse_Mercator"],PARAMETER["latitude_of_origin",0],PARAMETER["central_meridian",-117],PARAMETER["scale_factor",0.9996],PARAMETER["false_easting",500000],PARAMETER["false_northing",0],UNIT["Meter",1]]""": - gdaltest.post_reason('did not get expected GCP projection') - print(wkt) - return 'fail' + assert wkt == """PROJCS["NUTM11",GEOGCS["NAD27",DATUM["North_American_Datum_1927",SPHEROID["Clarke 1866",6378206.4,294.978698213898,AUTHORITY["EPSG","7008"]],TOWGS84[-3,142,183,0,0,0,0],AUTHORITY["EPSG","6267"]],PRIMEM["Greenwich",0,AUTHORITY["EPSG","8901"]],UNIT["degree",0.0174532925199433,AUTHORITY["EPSG","9108"]],AXIS["Lat",NORTH],AXIS["Long",EAST],AUTHORITY["EPSG","4267"]],PROJECTION["Transverse_Mercator"],PARAMETER["latitude_of_origin",0],PARAMETER["central_meridian",-117],PARAMETER["scale_factor",0.9996],PARAMETER["false_easting",500000],PARAMETER["false_northing",0],UNIT["Meter",1]]""", \ + 'did not get expected GCP projection' - if len(gcps) != len(expected_gcps) or len(gcps) != gcp_count: - gdaltest.post_reason('did not get expected GCP number') - return 'fail' + assert len(gcps) == len(expected_gcps) and len(gcps) == gcp_count, \ + 'did not get expected GCP number' for i, gcp in enumerate(gcps): if abs(gcp.GCPPixel - expected_gcps[i].GCPPixel) > 1e-6 or \ abs(gcp.GCPLine - expected_gcps[i].GCPLine) > 1e-6 or \ abs(gcp.GCPX - expected_gcps[i].GCPX) > 1e-6 or \ abs(gcp.GCPY - expected_gcps[i].GCPY) > 1e-6: - gdaltest.post_reason('did not get expected GCP %d' % i) print(gcps[i]) - return 'fail' + pytest.fail('did not get expected GCP %d' % i) drv.Delete('/vsimem/ers_8.ers') - return 'success' - ############################################################################### # Test NoData support (#4207) -def ers_9(): +def test_ers_9(): drv = gdal.GetDriverByName('ERS') ds = drv.Create('/vsimem/ers_9.ers', 1, 1) @@ -204,10 +179,9 @@ def ers_9(): f = gdal.VSIFOpenL('/vsimem/ers_9.ers.aux.xml', 'rb') if f is not None: - gdaltest.post_reason('/vsimem/ers_9.ers.aux.xml should not exist') gdal.VSIFCloseL(f) drv.Delete('/vsimem/ers_9.ers') - return 'fail' + pytest.fail('/vsimem/ers_9.ers.aux.xml should not exist') ds = gdal.Open('/vsimem/ers_9.ers') val = ds.GetRasterBand(1).GetNoDataValue() @@ -215,18 +189,13 @@ def ers_9(): drv.Delete('/vsimem/ers_9.ers') - if val != 123: - gdaltest.post_reason('did not get expected nodata value') - print(val) - return 'fail' - - return 'success' + assert val == 123, 'did not get expected nodata value' ############################################################################### # Test PROJ, DATUM, UNITS support (#4229) -def ers_10(): +def test_ers_10(): drv = gdal.GetDriverByName('ERS') ds = drv.Create('/vsimem/ers_10.ers', 1, 1, options=['DATUM=GDA94', 'PROJ=MGA55', 'UNITS=METERS']) @@ -234,20 +203,11 @@ def ers_10(): proj = ds.GetMetadataItem("PROJ", "ERS") datum = ds.GetMetadataItem("DATUM", "ERS") units = ds.GetMetadataItem("UNITS", "ERS") - if proj != 'MGA55': - gdaltest.post_reason('did not get expected PROJ') - print(proj) - return 'fail' + assert proj == 'MGA55', 'did not get expected PROJ' - if datum != 'GDA94': - gdaltest.post_reason('did not get expected DATUM') - print(datum) - return 'fail' + assert datum == 'GDA94', 'did not get expected DATUM' - if units != 'METERS': - gdaltest.post_reason('did not get expected UNITS') - print(units) - return 'fail' + assert units == 'METERS', 'did not get expected UNITS' # This should be overridden by the above values sr = osr.SpatialReference() @@ -257,29 +217,19 @@ def ers_10(): proj = ds.GetMetadataItem("PROJ", "ERS") datum = ds.GetMetadataItem("DATUM", "ERS") units = ds.GetMetadataItem("UNITS", "ERS") - if proj != 'MGA55': - gdaltest.post_reason('did not get expected PROJ') - print(proj) - return 'fail' + assert proj == 'MGA55', 'did not get expected PROJ' - if datum != 'GDA94': - gdaltest.post_reason('did not get expected DATUM') - print(datum) - return 'fail' + assert datum == 'GDA94', 'did not get expected DATUM' - if units != 'METERS': - gdaltest.post_reason('did not get expected UNITS') - print(units) - return 'fail' + assert units == 'METERS', 'did not get expected UNITS' ds = None f = gdal.VSIFOpenL('/vsimem/ers_10.ers.aux.xml', 'rb') if f is not None: - gdaltest.post_reason('/vsimem/ers_10.ers.aux.xml should not exist') gdal.VSIFCloseL(f) drv.Delete('/vsimem/ers_10.ers') - return 'fail' + pytest.fail('/vsimem/ers_10.ers.aux.xml should not exist') ds = gdal.Open('/vsimem/ers_10.ers') wkt = ds.GetProjectionRef() @@ -291,31 +241,17 @@ def ers_10(): drv.Delete('/vsimem/ers_10.ers') - if proj != 'MGA55': - gdaltest.post_reason('did not get expected PROJ') - print(proj) - return 'fail' + assert proj == 'MGA55', 'did not get expected PROJ' - if datum != 'GDA94': - gdaltest.post_reason('did not get expected DATUM') - print(datum) - return 'fail' + assert datum == 'GDA94', 'did not get expected DATUM' - if units != 'METERS': - gdaltest.post_reason('did not get expected UNITS') - print(units) - return 'fail' + assert units == 'METERS', 'did not get expected UNITS' - if md_ers["PROJ"] != proj or md_ers["DATUM"] != datum or md_ers["UNITS"] != units: - gdaltest.post_reason('GetMetadata() not consistent with ' + assert md_ers["PROJ"] == proj and md_ers["DATUM"] == datum and md_ers["UNITS"] == units, \ + ('GetMetadata() not consistent with ' 'GetMetadataItem()') - print(md_ers) - return 'fail' - if wkt.find("""PROJCS["MGA55""") != 0: - gdaltest.post_reason('did not get expected projection') - print(wkt) - return 'fail' + assert wkt.find("""PROJCS["MGA55""") == 0, 'did not get expected projection' ds = drv.Create('/vsimem/ers_10.ers', 1, 1, options=['DATUM=GDA94', 'PROJ=MGA55', 'UNITS=FEET']) ds = None @@ -328,20 +264,11 @@ def ers_10(): proj = ds.GetMetadataItem("PROJ", "ERS") datum = ds.GetMetadataItem("DATUM", "ERS") units = ds.GetMetadataItem("UNITS", "ERS") - if proj != 'GEODETIC': - gdaltest.post_reason('did not get expected PROJ') - print(proj) - return 'fail' - - if datum != 'WGS84': - gdaltest.post_reason('did not get expected DATUM') - print(datum) - return 'fail' - - if units != 'METERS': - gdaltest.post_reason('did not get expected UNITS') - print(units) - return 'fail' + assert proj == 'GEODETIC', 'did not get expected PROJ' + + assert datum == 'WGS84', 'did not get expected DATUM' + + assert units == 'METERS', 'did not get expected UNITS' ds = None ds = gdal.Open('/vsimem/ers_10.ers') @@ -352,61 +279,27 @@ def ers_10(): drv.Delete('/vsimem/ers_10.ers') - if proj != 'GEODETIC': - gdaltest.post_reason('did not get expected PROJ') - print(proj) - return 'fail' - - if datum != 'WGS84': - gdaltest.post_reason('did not get expected DATUM') - print(datum) - return 'fail' + assert proj == 'GEODETIC', 'did not get expected PROJ' - if units != 'METERS': - gdaltest.post_reason('did not get expected UNITS') - print(units) - return 'fail' + assert datum == 'WGS84', 'did not get expected DATUM' - return 'success' + assert units == 'METERS', 'did not get expected UNITS' ############################################################################### # Test fix for https://bugs.chromium.org/p/oss-fuzz/issues/detail?id=8744 -def ers_recursive_opening(): +def test_ers_recursive_opening(): ds = gdal.Open('/vsitar/data/test_ers_recursive.tar/test.ers') ds.GetFileList() - return 'success' ############################################################################### # Cleanup -def ers_cleanup(): +def test_ers_cleanup(): gdaltest.clean_tmp() - return 'success' - - -gdaltest_list = [ - ers_1, - ers_2, - ers_3, - ers_4, - ers_5, - ers_6, - ers_7, - ers_8, - ers_9, - ers_10, - ers_recursive_opening, - ers_cleanup -] - -if __name__ == '__main__': - gdaltest.setup_run('ers') - gdaltest.run_tests(gdaltest_list) - sys.exit(gdaltest.summarize()) diff --git a/autotest/gdrivers/fast.py b/autotest/gdrivers/fast.py index 17d5d1266450..4858b04b96c9 100755 --- a/autotest/gdrivers/fast.py +++ b/autotest/gdrivers/fast.py @@ -29,33 +29,31 @@ # DEALINGS IN THE SOFTWARE. ############################################################################### -import sys from osgeo import gdal -sys.path.append('../pymod') import gdaltest +import pytest ############################################################################### # Verify we have the driver. -def fast_1(): +def test_fast_1(): gdaltest.fast_drv = gdal.GetDriverByName('FAST') if gdaltest.fast_drv is None: - return 'skip' - - return 'success' + pytest.skip() + ############################################################################### # Perform simple read test. -def fast_2(): +def test_fast_2(): if gdaltest.fast_drv is None: - return 'skip' + pytest.skip() # Actually, the band (a placeholder) is of 0 bytes size, # so the checksum is 0 expected. @@ -68,33 +66,23 @@ def fast_2(): # Verify metadata. -def fast_3(): +def test_fast_3(): if gdaltest.fast_drv is None: - return 'skip' + pytest.skip() gdaltest.fast_ds = gdal.Open('data/L71118038_03820020111_HPN.FST') ds = gdaltest.fast_ds - if ds is None: - gdaltest.post_reason('Missing test dataset') - return 'fail' + assert ds is not None, 'Missing test dataset' md = ds.GetMetadata() - if md is None: - gdaltest.post_reason('Missing metadata in test dataset') - return 'fail' + assert md is not None, 'Missing metadata in test dataset' - if md['ACQUISITION_DATE'] != '20020111': - gdaltest.post_reason('ACQUISITION_DATE wrong') - return 'fail' + assert md['ACQUISITION_DATE'] == '20020111', 'ACQUISITION_DATE wrong' - if md['SATELLITE'] != 'LANDSAT7': - gdaltest.post_reason('SATELLITE wrong') - return 'fail' + assert md['SATELLITE'] == 'LANDSAT7', 'SATELLITE wrong' - if md['SENSOR'] != 'ETM+': - gdaltest.post_reason('SENSOR wrong') - return 'fail' + assert md['SENSOR'] == 'ETM+', 'SENSOR wrong' # GAIN and BIAS expected values gb_expected = (-6.199999809265137, 0.775686297697179) @@ -109,21 +97,18 @@ def fast_3(): print('expected:', gb_expected[1]) print('got:', bias) - return 'success' - + ############################################################################### # Test geotransform data. -def fast_4(): +def test_fast_4(): if gdaltest.fast_drv is None: - return 'skip' + pytest.skip() ds = gdaltest.fast_ds - if ds is None: - gdaltest.post_reason('Missing test dataset') - return 'fail' + assert ds is not None, 'Missing test dataset' gt = ds.GetGeoTransform() @@ -131,22 +116,19 @@ def fast_4(): ds = None tolerance = 0.01 - if abs(gt[0] - 280342.5) > tolerance or abs(gt[1] - 15.0) > tolerance or \ - abs(gt[2] - 0.0) > tolerance or abs(gt[3] - 3621457.5) > tolerance or \ - abs(gt[4] - 0.0) > tolerance or abs(gt[5] + 15.0) > tolerance: - gdaltest.post_reason('FAST geotransform wrong') - return 'fail' - - return 'success' + assert (abs(gt[0] - 280342.5) <= tolerance and abs(gt[1] - 15.0) <= tolerance and \ + abs(gt[2] - 0.0) <= tolerance and abs(gt[3] - 3621457.5) <= tolerance and \ + abs(gt[4] - 0.0) <= tolerance and abs(gt[5] + 15.0) <= tolerance), \ + 'FAST geotransform wrong' ############################################################################### # Test 2 bands dataset with checking projections and geotransform. -def fast_5(): +def test_fast_5(): if gdaltest.fast_drv is None: - return 'skip' + pytest.skip() tst = gdaltest.GDALTest('fast', 'L71230079_07920021111_HTM.FST', 2, 19110, 0, 0, 7000, 1) @@ -183,10 +165,10 @@ def fast_5(): ############################################################################### # Test Euromap LISS3 dataset -def fast_6(): +def test_fast_6(): if gdaltest.fast_drv is None: - return 'skip' + pytest.skip() tst = gdaltest.GDALTest('fast', 'n0o0y867.0fl', 1, 0, 0, 0, 2741, 1) @@ -204,10 +186,10 @@ def fast_6(): ############################################################################### # Test Euromap PAN dataset -def fast_7(): +def test_fast_7(): if gdaltest.fast_drv is None: - return 'skip' + pytest.skip() tst = gdaltest.GDALTest('fast', 'h0o0y867.1ah', 1, 0, 0, 0, 5815, 1) @@ -236,10 +218,10 @@ def fast_7(): # Test Euromap WIFS dataset -def fast_8(): +def test_fast_8(): if gdaltest.fast_drv is None: - return 'skip' + pytest.skip() tst = gdaltest.GDALTest('fast', 'w0y13a4t.010', 1, 0, 0, 0, 4748, 1) @@ -270,41 +252,18 @@ def fast_8(): # Check some metadata and opening for a RevB L7 file (#3306, #3307). -def fast_9(): +def test_fast_9(): if gdaltest.fast_drv is None: - return 'skip' + pytest.skip() ds = gdal.Open('data/HEADER.DAT') - if ds.GetMetadataItem('SENSOR') != '': - gdaltest.post_reason('Did not get expected SENSOR value.') - return 'fail' - - if ds.RasterCount != 7: - gdaltest.post_reason('Did not get expected band count.') - return 'fail' + assert ds.GetMetadataItem('SENSOR') == '', 'Did not get expected SENSOR value.' - return 'success' + assert ds.RasterCount == 7, 'Did not get expected band count.' ############################################################################### # -gdaltest_list = [ - fast_1, - fast_2, - fast_3, - fast_4, - fast_5, - fast_6, - fast_7, - fast_8, - fast_9] - -if __name__ == '__main__': - - gdaltest.setup_run('fast') - - gdaltest.run_tests(gdaltest_list) - sys.exit(gdaltest.summarize()) diff --git a/autotest/gdrivers/fit.py b/autotest/gdrivers/fit.py index 3f280e011de9..7cbc6318ed14 100755 --- a/autotest/gdrivers/fit.py +++ b/autotest/gdrivers/fit.py @@ -28,52 +28,22 @@ # DEALINGS IN THE SOFTWARE. ############################################################################### -import sys -from osgeo import gdal - -sys.path.append('../pymod') - -import gdaltest - -############################################################################### -# - - -class TestFIT(object): - def __init__(self, fileName): - self.fileName = fileName - self.fitDriver = gdal.GetDriverByName('FIT') - - def test(self): +import pytest - ds = gdal.Open('../gcore/data/' + self.fileName + '.tif') - self.fitDriver.CreateCopy('tmp/' + self.fileName + '.fit', ds, options=['PAGESIZE=2,2']) - - ds2 = gdal.Open('tmp/' + self.fileName + '.fit') - if ds2.GetRasterBand(1).Checksum() != ds.GetRasterBand(1).Checksum(): - return 'fail' - - if ds2.GetRasterBand(1).DataType != ds.GetRasterBand(1).DataType: - return 'fail' - - ds2 = None - self.fitDriver.Delete('tmp/' + self.fileName + '.fit') - return 'success' - - -gdaltest_list = [] - -fit_list = ['byte', 'int16', 'uint16', 'int32', 'uint32', 'float32', 'float64'] - -for item in fit_list: - ut = TestFIT(item) - gdaltest_list.append((ut.test, item)) +from osgeo import gdal -if __name__ == '__main__': +@pytest.mark.parametrize('filename', [ + 'byte', 'int16', 'uint16', 'int32', 'uint32', 'float32', 'float64' +]) +def test_fit(filename): + fitDriver = gdal.GetDriverByName('FIT') - gdaltest.setup_run('fit') + ds = gdal.Open('../gcore/data/' + filename + '.tif') + fitDriver.CreateCopy('tmp/' + filename + '.fit', ds, options=['PAGESIZE=2,2']) - gdaltest.run_tests(gdaltest_list) + ds2 = gdal.Open('tmp/' + filename + '.fit') + assert ds2.GetRasterBand(1).Checksum() == ds.GetRasterBand(1).Checksum() - sys.exit(gdaltest.summarize()) + assert ds2.GetRasterBand(1).DataType == ds.GetRasterBand(1).DataType + ds2 = None diff --git a/autotest/gdrivers/fits.py b/autotest/gdrivers/fits.py index 11816a78e7a4..2b33f76823d8 100755 --- a/autotest/gdrivers/fits.py +++ b/autotest/gdrivers/fits.py @@ -28,60 +28,38 @@ # DEALINGS IN THE SOFTWARE. ############################################################################### -import sys -from osgeo import gdal - -sys.path.append('../pymod') - -import gdaltest - -############################################################################### -# - +import pytest -def fits_init(): - gdaltest.fitsDriver = gdal.GetDriverByName('FITS') - if gdaltest.fitsDriver is None: - return 'skip' - - return 'success' - -############################################################################### -# +from osgeo import gdal -class TestFITS(object): - def __init__(self, fileName): - self.fileName = fileName +pytestmark = pytest.mark.require_driver('FITS') - def test(self): - if gdaltest.fitsDriver is None: - return 'skip' - ds = gdal.Open('../gcore/data/' + self.fileName + '.tif') - gdaltest.fitsDriver.CreateCopy('tmp/' + self.fileName + '.fits', ds, options=['PAGESIZE=2,2']) +@pytest.mark.parametrize( + 'filename', + ['byte', 'int16', 'int32', 'float32', 'float64'] +) +def test_fits(filename): + driver = gdal.GetDriverByName('FITS') - ds2 = gdal.Open('tmp/' + self.fileName + '.fits') - if ds2.GetRasterBand(1).Checksum() != ds.GetRasterBand(1).Checksum(): - return 'fail' + ds = gdal.Open('../gcore/data/' + filename + '.tif') + driver.CreateCopy('tmp/' + filename + '.fits', ds, options=['PAGESIZE=2,2']) - if ds2.GetRasterBand(1).DataType != ds.GetRasterBand(1).DataType: - return 'fail' + ds2 = gdal.Open('tmp/' + filename + '.fits') + assert ds2.GetRasterBand(1).Checksum() == ds.GetRasterBand(1).Checksum() - ds2 = None - gdaltest.fitsDriver.Delete('tmp/' + self.fileName + '.fits') - return 'success' + assert ds2.GetRasterBand(1).DataType == ds.GetRasterBand(1).DataType -############################################################################### -# + ds2 = None + driver.Delete('tmp/' + filename + '.fits') def fits_metadata(): - if gdaltest.fitsDriver is None: - return 'skip' + driver = gdal.GetDriverByName('FITS') ds = gdal.Open('../gcore/data/byte.tif') - ds2 = gdaltest.fitsDriver.CreateCopy('tmp/byte.fits', ds) + ds2 = driver.CreateCopy('tmp/byte.fits', ds) md = {'TEST': 'test_value'} ds2.SetMetadata(md) ds2 = None @@ -91,8 +69,7 @@ def fits_metadata(): md = ds2.GetMetadata() ds2 = None - if md['TEST'] != 'test_value': - return 'fail' + assert md['TEST'] == 'test_value' ds2 = gdal.Open('tmp/byte.fits', gdal.GA_Update) md = {'TEST2': 'test_value2'} @@ -104,30 +81,4 @@ def fits_metadata(): md = ds2.GetMetadata() ds2 = None - if md['TEST2'] != 'test_value2': - return 'fail' - - gdaltest.fitsDriver.Delete('tmp/byte.fits') - - return 'success' - - -############################################################################### -# -gdaltest_list = [fits_init] - -fits_list = ['byte', 'int16', 'int32', 'float32', 'float64'] - -for item in fits_list: - ut = TestFITS(item) - gdaltest_list.append((ut.test, item)) - -gdaltest_list.append(fits_metadata) - -if __name__ == '__main__': - - gdaltest.setup_run('fits') - - gdaltest.run_tests(gdaltest_list) - - sys.exit(gdaltest.summarize()) + assert md['TEST2'] == 'test_value2' diff --git a/autotest/gdrivers/fujibas.py b/autotest/gdrivers/fujibas.py index cc45c4506c74..702a80996b12 100755 --- a/autotest/gdrivers/fujibas.py +++ b/autotest/gdrivers/fujibas.py @@ -28,9 +28,7 @@ # DEALINGS IN THE SOFTWARE. ############################################################################### -import sys -sys.path.append('../pymod') import gdaltest @@ -38,19 +36,10 @@ # Test a fake - and certainly incorrect - FUJIBAS dataset -def fujibas_1(): +def test_fujibas_1(): tst = gdaltest.GDALTest('FujiBAS', 'fakefujibas.pcb', 1, 1) return tst.testOpen() -gdaltest_list = [ - fujibas_1] -if __name__ == '__main__': - - gdaltest.setup_run('fujibas') - - gdaltest.run_tests(gdaltest_list) - - sys.exit(gdaltest.summarize()) diff --git a/autotest/gdrivers/gdalhttp.py b/autotest/gdrivers/gdalhttp.py index 9ab7bd90c9c1..40c496dcd5d1 100755 --- a/autotest/gdrivers/gdalhttp.py +++ b/autotest/gdrivers/gdalhttp.py @@ -31,25 +31,32 @@ ############################################################################### import os +import subprocess import sys from osgeo import gdal from osgeo import ogr -sys.path.append('../pymod') +import pytest -import gdaltest +try: + import gdaltest +except ImportError: + # running as a subprocess in the windows build (see __main__ block), + # so conftest.py hasn't run, so sys.path doesn't have pymod in it + sys.path.append('../pymod') + import gdaltest ############################################################################### # Verify we have the driver. -def http_1(): +def test_http_1(): gdaltest.dods_drv = None drv = gdal.GetDriverByName('HTTP') if drv is None: - return 'skip' + pytest.skip() gdaltest.dods_drv = gdal.GetDriverByName('DODS') if gdaltest.dods_drv is not None: @@ -61,8 +68,7 @@ def http_1(): if ret == 'fail': conn = gdaltest.gdalurlopen('http://gdal.org/gdalicon.png') if conn is None: - print('cannot open URL') - return 'skip' + pytest.skip('cannot open URL') conn.close() return ret @@ -71,11 +77,11 @@ def http_1(): # Verify /vsicurl (subversion file listing) -def http_2(): +def test_http_2(): drv = gdal.GetDriverByName('HTTP') if drv is None: - return 'skip' + pytest.skip() tst = gdaltest.GDALTest('GTiff', '/vsicurl/https://raw.githubusercontent.com/OSGeo/gdal/master/autotest/gcore/data/byte.tif', 1, 4672, filename_absolute=1) @@ -83,8 +89,7 @@ def http_2(): if ret == 'fail': conn = gdaltest.gdalurlopen('https://raw.githubusercontent.com/OSGeo/gdal/master/autotest/gcore/data/byte.tif') if conn is None: - print('cannot open URL') - return 'skip' + pytest.skip('cannot open URL') conn.close() return ret @@ -93,11 +98,11 @@ def http_2(): # Verify /vsicurl (apache file listing) -def http_3(): +def test_http_3(): drv = gdal.GetDriverByName('HTTP') if drv is None: - return 'skip' + pytest.skip() gdal.SetConfigOption('GDAL_HTTP_TIMEOUT', '5') ds = gdal.Open('/vsicurl/http://download.osgeo.org/gdal/data/ehdr/elggll.bil') @@ -105,13 +110,11 @@ def http_3(): if ds is None: conn = gdaltest.gdalurlopen('http://download.osgeo.org/gdal/data/ehdr/elggll.bil') if conn is None: - print('cannot open URL') - return 'skip' + pytest.skip('cannot open URL') conn.close() - return 'fail' - - return 'success' + pytest.fail() + ############################################################################### # Verify /vsicurl (ftp) @@ -120,7 +123,7 @@ def http_4_old(): drv = gdal.GetDriverByName('HTTP') if drv is None: - return 'skip' + pytest.skip() ds = gdal.Open('/vsicurl/ftp://ftp2.cits.rncan.gc.ca/pub/cantopo/250k_tif/MCR2010_01.tif') if ds is None: @@ -129,133 +132,107 @@ def http_4_old(): # builds on other machines... # This heuristics might be fragile ! if "GDAL_DATA" in os.environ and os.environ["GDAL_DATA"].find("E:\\builds\\..\\sdk\\") == 0: - return 'skip' + pytest.skip() conn = gdaltest.gdalurlopen('ftp://ftp2.cits.rncan.gc.ca/pub/cantopo/250k_tif/MCR2010_01.tif') if conn is None: - print('cannot open URL') - return 'skip' + pytest.skip('cannot open URL') conn.close() - return 'fail' + pytest.fail() filelist = ds.GetFileList() - if filelist[0] != '/vsicurl/ftp://ftp2.cits.rncan.gc.ca/pub/cantopo/250k_tif/MCR2010_01.tif': - print(filelist) - return 'fail' - - return 'success' + assert filelist[0] == '/vsicurl/ftp://ftp2.cits.rncan.gc.ca/pub/cantopo/250k_tif/MCR2010_01.tif' ############################################################################### # Verify /vsicurl (ftp) -def http_4(): +def test_http_4(): # Too unreliable if gdaltest.skip_on_travis(): - return 'skip' + pytest.skip() drv = gdal.GetDriverByName('HTTP') if drv is None: - return 'skip' + pytest.skip() ds = gdal.Open('/vsicurl/ftp://download.osgeo.org/gdal/data/gtiff/utm.tif') if ds is None: conn = gdaltest.gdalurlopen('ftp://download.osgeo.org/gdal/data/gtiff/utm.tif', timeout=4) if conn is None: - print('cannot open URL') - return 'skip' + pytest.skip('cannot open URL') try: conn.read() except: - print('cannot read') - return 'skip' + pytest.skip('cannot read') conn.close() if sys.platform == 'darwin' and gdal.GetConfigOption('TRAVIS', None) is not None: - print("Fails on MacOSX Travis sometimes. Not sure why.") - return 'skip' - gdaltest.post_reason('fail') - return 'fail' + pytest.skip("Fails on MacOSX Travis sometimes. Not sure why.") + pytest.fail() filelist = ds.GetFileList() - if '/vsicurl/ftp://download.osgeo.org/gdal/data/gtiff/utm.tif' not in filelist: - print(filelist) - gdaltest.post_reason('fail') - return 'fail' - - return 'success' + assert '/vsicurl/ftp://download.osgeo.org/gdal/data/gtiff/utm.tif' in filelist ############################################################################### # Test HTTP driver with non VSIL driver -def http_5(): +def test_http_5(): drv = gdal.GetDriverByName('HTTP') if drv is None: - return 'skip' + pytest.skip() ds = gdal.Open('https://raw.githubusercontent.com/OSGeo/gdal/master/autotest/gdrivers/data/s4103.blx') if ds is None: conn = gdaltest.gdalurlopen('https://raw.githubusercontent.com/OSGeo/gdal/master/autotest/gdrivers/data/s4103.blx') if conn is None: - print('cannot open URL') - return 'skip' + pytest.skip('cannot open URL') try: conn.read() except: - print('cannot read') - return 'skip' + pytest.skip('cannot read') conn.close() - gdaltest.post_reason('fail') - return 'fail' + pytest.fail() filename = ds.GetDescription() ds = None - try: + with pytest.raises(OSError, message='file %s should have been removed' % filename): os.stat(filename) - gdaltest.post_reason('file %s should have been removed' % filename) - return 'fail' - except OSError: - pass - - return 'success' + + ############################################################################### # Test HTTP driver with OGR driver -def http_6(): +def test_http_6(): drv = gdal.GetDriverByName('HTTP') if drv is None: - return 'skip' + pytest.skip() ds = ogr.Open('https://raw.githubusercontent.com/OSGeo/gdal/master/autotest/ogr/data/test.jml') if ds is None: conn = gdaltest.gdalurlopen('https://raw.githubusercontent.com/OSGeo/gdal/master/autotest/ogr/data/test.jml') if conn is None: - print('cannot open URL') - return 'skip' + pytest.skip('cannot open URL') try: conn.read() except: - print('cannot read') - return 'skip' + pytest.skip('cannot read') conn.close() - gdaltest.post_reason('fail') - return 'fail' + pytest.fail() ds = None - return 'success' - ############################################################################### -def http_test_ssl_verifystatus(): +def test_http_ssl_verifystatus(): if gdal.GetDriverByName('HTTP') is None: - return 'skip' + pytest.skip() with gdaltest.config_option('GDAL_HTTP_SSL_VERIFYSTATUS', 'YES'): with gdaltest.error_handler(): @@ -266,73 +243,46 @@ def http_test_ssl_verifystatus(): # The test actually works on Travis Mac if sys.platform == 'darwin' and gdal.GetConfigOption('TRAVIS', None) is not None: - return 'skip' - - print(last_err) - return 'fail' + pytest.skip() - return 'success' + pytest.fail(last_err) + ############################################################################### -def http_test_use_capi_store(): +def test_http_use_capi_store(): if gdal.GetDriverByName('HTTP') is None: - return 'skip' + pytest.skip() if sys.platform != 'win32': with gdaltest.error_handler(): - return http_test_use_capi_store_sub() - - import test_py_scripts - ret = test_py_scripts.run_py_script_as_external_script('.', 'gdalhttp', ' -use_capi_store', display_live_on_parent_stdout=True) - - if ret.find('Failed: 0') == -1: - return 'fail' + return test_http_use_capi_store_sub() - return 'success' + # Prints this to stderr in many cases (but doesn't error) + # Warning 6: GDAL_HTTP_USE_CAPI_STORE requested, but libcurl too old, non-Windows platform or OpenSSL missing. + subprocess.check_call( + [sys.executable, 'gdalhttp.py', '-use_capi_store'], + ) -def http_test_use_capi_store_sub(): +def test_http_use_capi_store_sub(): with gdaltest.config_option('GDAL_HTTP_USE_CAPI_STORE', 'YES'): gdal.OpenEx('https://google.com', allowed_drivers=['HTTP']) - return 'success' - + ############################################################################### # -def http_cleanup(): +def test_http_cleanup(): if gdaltest.dods_drv is not None: gdaltest.dods_drv.Register() gdaltest.dods_drv = None - return 'success' - - -gdaltest_list = [http_1, - http_2, - http_3, - # http_4_old, - http_4, - http_5, - http_6, - http_test_ssl_verifystatus, - http_test_use_capi_store, - http_cleanup] - -# gdaltest_list = [ http_test_use_capi_store ] if __name__ == '__main__': - - gdaltest.setup_run('http') - if len(sys.argv) == 2 and sys.argv[1] == '-use_capi_store': - gdaltest_list = [http_test_use_capi_store_sub] - - gdaltest.run_tests(gdaltest_list) - - sys.exit(gdaltest.summarize()) + test_http_use_capi_store_sub() diff --git a/autotest/gdrivers/genbin.py b/autotest/gdrivers/genbin.py index 3886f44ef85a..e06170f8a76c 100755 --- a/autotest/gdrivers/genbin.py +++ b/autotest/gdrivers/genbin.py @@ -28,9 +28,7 @@ # DEALINGS IN THE SOFTWARE. ############################################################################### -import sys -sys.path.append('../pymod') import gdaltest @@ -38,7 +36,7 @@ # Perform simple read test. -def genbin_1(): +def test_genbin_1(): tst = gdaltest.GDALTest('GenBin', 'tm4628_96.bil', 1, 5738, 0, 0, 500, 1) @@ -73,15 +71,5 @@ def genbin_1(): return tst.testOpen(check_prj=prj, check_gt=gt) -gdaltest_list = [ - genbin_1 -] -if __name__ == '__main__': - - gdaltest.setup_run('genbin') - - gdaltest.run_tests(gdaltest_list) - - sys.exit(gdaltest.summarize()) diff --git a/autotest/gdrivers/georaster.py b/autotest/gdrivers/georaster.py index bfc99f1748e8..1213321fd060 100755 --- a/autotest/gdrivers/georaster.py +++ b/autotest/gdrivers/georaster.py @@ -29,13 +29,12 @@ ############################################################################### import os -import sys from osgeo import gdal from osgeo import ogr -sys.path.append('../pymod') import gdaltest +import pytest ############################################################################### # @@ -54,21 +53,21 @@ def get_connection_str(): # -def georaster_init(): +def test_georaster_init(): gdaltest.oci_ds = None gdaltest.georasterDriver = gdal.GetDriverByName('GeoRaster') if gdaltest.georasterDriver is None: - return 'skip' + pytest.skip() if os.environ.get('OCI_DSNAME') is None: - return 'skip' + pytest.skip() gdaltest.oci_ds = ogr.Open(os.environ.get('OCI_DSNAME')) if gdaltest.oci_ds is None: - return 'skip' + pytest.skip() gdal.PushErrorHandler('CPLQuietErrorHandler') rs = gdaltest.oci_ds.ExecuteSQL('select owner from all_sdo_geor_sysdata') @@ -81,25 +80,22 @@ def georaster_init(): rs = None if err_msg != '': - gdaltest.post_reason('ALL_SDO_GEOR_SYSDATA inaccessible, ' - 'likely georaster unavailable.') - gdaltest.oci_ds = None - return 'skip' - - return 'success' + pytest.skip('ALL_SDO_GEOR_SYSDATA inaccessible, ' + 'likely georaster unavailable.') + ############################################################################### # -def georaster_byte(): +def test_georaster_byte(): if gdaltest.georasterDriver is None: - return 'skip' + pytest.skip() if gdaltest.oci_ds is None: - return 'skip' + pytest.skip() ds_src = gdal.Open('data/byte.tif') @@ -120,13 +116,13 @@ def georaster_byte(): # -def georaster_int16(): +def test_georaster_int16(): if gdaltest.georasterDriver is None: - return 'skip' + pytest.skip() if gdaltest.oci_ds is None: - return 'skip' + pytest.skip() get_connection_str() @@ -149,13 +145,13 @@ def georaster_int16(): # -def georaster_int32(): +def test_georaster_int32(): if gdaltest.georasterDriver is None: - return 'skip' + pytest.skip() if gdaltest.oci_ds is None: - return 'skip' + pytest.skip() get_connection_str() @@ -178,13 +174,13 @@ def georaster_int32(): # -def georaster_rgb_b1(): +def test_georaster_rgb_b1(): if gdaltest.georasterDriver is None: - return 'skip' + pytest.skip() if gdaltest.oci_ds is None: - return 'skip' + pytest.skip() ds_src = gdal.Open('data/rgbsmall.tif') @@ -206,13 +202,13 @@ def georaster_rgb_b1(): # -def georaster_rgb_b2(): +def test_georaster_rgb_b2(): if gdaltest.georasterDriver is None: - return 'skip' + pytest.skip() if gdaltest.oci_ds is None: - return 'skip' + pytest.skip() ds_src = gdal.Open('data/rgbsmall.tif') @@ -234,13 +230,13 @@ def georaster_rgb_b2(): # -def georaster_rgb_b3_bsq(): +def test_georaster_rgb_b3_bsq(): if gdaltest.georasterDriver is None: - return 'skip' + pytest.skip() if gdaltest.oci_ds is None: - return 'skip' + pytest.skip() ds_src = gdal.Open('data/rgbsmall.tif') @@ -262,13 +258,13 @@ def georaster_rgb_b3_bsq(): # -def georaster_rgb_b3_bip(): +def test_georaster_rgb_b3_bip(): if gdaltest.georasterDriver is None: - return 'skip' + pytest.skip() if gdaltest.oci_ds is None: - return 'skip' + pytest.skip() ds_src = gdal.Open('data/rgbsmall.tif') @@ -290,13 +286,13 @@ def georaster_rgb_b3_bip(): # -def georaster_rgb_b3_bil(): +def test_georaster_rgb_b3_bil(): if gdaltest.georasterDriver is None: - return 'skip' + pytest.skip() if gdaltest.oci_ds is None: - return 'skip' + pytest.skip() ds_src = gdal.Open('data/rgbsmall.tif') @@ -318,13 +314,13 @@ def georaster_rgb_b3_bil(): # -def georaster_byte_deflate(): +def test_georaster_byte_deflate(): if gdaltest.georasterDriver is None: - return 'skip' + pytest.skip() if gdaltest.oci_ds is None: - return 'skip' + pytest.skip() ds_src = gdal.Open('data/byte.tif') @@ -346,13 +342,13 @@ def georaster_byte_deflate(): # -def georaster_rgb_deflate_b3(): +def test_georaster_rgb_deflate_b3(): if gdaltest.georasterDriver is None: - return 'skip' + pytest.skip() if gdaltest.oci_ds is None: - return 'skip' + pytest.skip() ds_src = gdal.Open('data/rgbsmall.tif') @@ -374,13 +370,13 @@ def georaster_rgb_deflate_b3(): # -def georaster_1bit(): +def test_georaster_1bit(): if gdaltest.georasterDriver is None: - return 'skip' + pytest.skip() if gdaltest.oci_ds is None: - return 'skip' + pytest.skip() ds_src = gdal.Open('data/byte.tif') @@ -402,13 +398,13 @@ def georaster_1bit(): # -def georaster_2bit(): +def test_georaster_2bit(): if gdaltest.georasterDriver is None: - return 'skip' + pytest.skip() if gdaltest.oci_ds is None: - return 'skip' + pytest.skip() ds_src = gdal.Open('data/byte.tif') @@ -430,13 +426,13 @@ def georaster_2bit(): # -def georaster_4bit(): +def test_georaster_4bit(): if gdaltest.georasterDriver is None: - return 'skip' + pytest.skip() if gdaltest.oci_ds is None: - return 'skip' + pytest.skip() ds_src = gdal.Open('data/byte.tif') @@ -458,13 +454,13 @@ def georaster_4bit(): # -def georaster_cleanup(): +def test_georaster_cleanup(): if gdaltest.georasterDriver is None: - return 'skip' + pytest.skip() if gdaltest.oci_ds is None: - return 'skip' + pytest.skip() gdaltest.oci_ds.ExecuteSQL('drop table GDAL_TEST') gdaltest.oci_ds.ExecuteSQL('drop table GDAL_TEST_RDT') @@ -472,39 +468,8 @@ def georaster_cleanup(): gdaltest.oci_ds.Destroy() gdaltest.oci_ds = None - return 'success' - ############################################################################### # -gdaltest_list = [ - georaster_init, - georaster_byte, - georaster_int16, - georaster_int32, - georaster_rgb_b1, - georaster_rgb_b2, - georaster_rgb_b3_bsq, - georaster_rgb_b3_bip, - georaster_rgb_b3_bil, - georaster_byte_deflate, - georaster_rgb_deflate_b3, - georaster_1bit, - georaster_2bit, - georaster_4bit, - georaster_cleanup -] - -if __name__ == '__main__': - - if 'OCI_DSNAME' not in os.environ: - print('Enter ORACLE connection (e.g. OCI:scott/tiger@orcl): ') - oci_dsname = sys.stdin.readline().strip() - os.environ['OCI_DSNAME'] = oci_dsname - - gdaltest.setup_run('GeoRaster') - - gdaltest.run_tests(gdaltest_list) - - sys.exit(gdaltest.summarize()) + diff --git a/autotest/gdrivers/gff.py b/autotest/gdrivers/gff.py index be72bd1eae96..088a324ca3ef 100755 --- a/autotest/gdrivers/gff.py +++ b/autotest/gdrivers/gff.py @@ -28,21 +28,20 @@ # DEALINGS IN THE SOFTWARE. ############################################################################### -import sys from osgeo import gdal -sys.path.append('../pymod') import gdaltest +import pytest ############################################################################### # Test an extract from a real dataset -def gff_1(): +def test_gff_1(): # 12088 = 2048 + 8 * 1255 if not gdaltest.download_file('http://sandia.gov/RADAR/complex_data/MiniSAR20050519p0001image008.gff', 'MiniSAR20050519p0001image008.gff', 12088): - return 'skip' + pytest.skip() tst = gdaltest.GDALTest('GFF', 'tmp/cache/MiniSAR20050519p0001image008.gff', 1, 29757, filename_absolute=1) gdal.PushErrorHandler('CPLQuietErrorHandler') @@ -51,13 +50,4 @@ def gff_1(): return ret -gdaltest_list = [ - gff_1] -if __name__ == '__main__': - - gdaltest.setup_run('gff') - - gdaltest.run_tests(gdaltest_list) - - sys.exit(gdaltest.summarize()) diff --git a/autotest/gdrivers/gif.py b/autotest/gdrivers/gif.py index 876d8a02ce51..fdf8628a2b81 100755 --- a/autotest/gdrivers/gif.py +++ b/autotest/gdrivers/gif.py @@ -29,10 +29,8 @@ # DEALINGS IN THE SOFTWARE. ############################################################################### -import sys from osgeo import gdal -sys.path.append('../pymod') import gdaltest @@ -40,7 +38,7 @@ # Get the GIF driver, and verify a few things about it. -def gif_1(): +def test_gif_1(): gdaltest.gif_drv = gdal.GetDriverByName('GIF') if gdaltest.gif_drv is None: @@ -57,13 +55,12 @@ def gif_1(): gdaltest.post_reason('mime type is wrong') return 'false' - return 'success' - + ############################################################################### # Read test of simple byte reference data. -def gif_2(): +def test_gif_2(): tst = gdaltest.GDALTest('GIF', 'bug407.gif', 1, 57921) return tst.testOpen() @@ -72,7 +69,7 @@ def gif_2(): # Test lossless copying. -def gif_3(): +def test_gif_3(): tst = gdaltest.GDALTest('GIF', 'bug407.gif', 1, 57921, options=['INTERLACING=NO']) @@ -83,35 +80,26 @@ def gif_3(): # Verify the colormap, and nodata setting for test file. -def gif_4(): +def test_gif_4(): ds = gdal.Open('data/bug407.gif') cm = ds.GetRasterBand(1).GetRasterColorTable() - if cm.GetCount() != 16 \ - or cm.GetColorEntry(0) != (255, 255, 255, 255) \ - or cm.GetColorEntry(1) != (255, 255, 208, 255): - gdaltest.post_reason('Wrong colormap entries') - return 'fail' + assert cm.GetCount() == 16 and cm.GetColorEntry(0) == (255, 255, 255, 255) and cm.GetColorEntry(1) == (255, 255, 208, 255), \ + 'Wrong colormap entries' cm = None - if ds.GetRasterBand(1).GetNoDataValue() is not None: - gdaltest.post_reason('Wrong nodata value.') - return 'fail' + assert ds.GetRasterBand(1).GetNoDataValue() is None, 'Wrong nodata value.' md = ds.GetRasterBand(1).GetMetadata() - if 'GIF_BACKGROUND' not in md or md['GIF_BACKGROUND'] != '0': - print(md) - gdaltest.post_reason('background metadata missing.') - return 'fail' - - return 'success' + assert 'GIF_BACKGROUND' in md and md['GIF_BACKGROUND'] == '0', \ + 'background metadata missing.' ############################################################################### # Test creating an in memory copy. -def gif_5(): +def test_gif_5(): tst = gdaltest.GDALTest('GIF', 'byte.tif', 1, 4672) @@ -121,7 +109,7 @@ def gif_5(): # Verify nodata support -def gif_6(): +def test_gif_6(): src_ds = gdal.Open('../gcore/data/nodata_byte.tif') @@ -157,13 +145,11 @@ def gif_6(): gdaltest.gif_drv.Delete('tmp/nodata_byte.gif') - return 'success' - ############################################################################### # Confirm reading with the BIGGIF driver. -def gif_7(): +def test_gif_7(): # Move the GIF driver after the BIGGIF driver. drv = gdal.GetDriverByName('GIF') @@ -172,23 +158,18 @@ def gif_7(): tst = gdaltest.GDALTest('BIGGIF', 'bug407.gif', 1, 57921) - if tst.testOpen() != 'success': - return 'fail' + tst.testOpen() ds = gdal.Open('data/bug407.gif') - if ds is None: - return 'fail' + assert ds is not None - if ds.GetDriver().ShortName != 'BIGGIF': - return 'fail' - - return 'success' + assert ds.GetDriver().ShortName == 'BIGGIF' ############################################################################### # Confirm that BIGGIF driver is selected for huge gifs -def gif_8(): +def test_gif_8(): # Move the BIGGIF driver after the GIF driver. drv = gdal.GetDriverByName('BIGGIF') @@ -196,43 +177,34 @@ def gif_8(): drv.Register() ds = gdal.Open('data/fakebig.gif') - if ds is None: - return 'fail' - - if ds.GetDriver().ShortName != 'BIGGIF': - return 'fail' + assert ds is not None - return 'success' + assert ds.GetDriver().ShortName == 'BIGGIF' ############################################################################### # Test writing to /vsistdout/ -def gif_9(): +def test_gif_9(): src_ds = gdal.Open('data/byte.tif') ds = gdal.GetDriverByName('GIF').CreateCopy( '/vsistdout_redirect//vsimem/tmp.gif', src_ds) - if ds.GetRasterBand(1).Checksum() != 0: - return 'fail' + assert ds.GetRasterBand(1).Checksum() == 0 src_ds = None ds = None ds = gdal.Open('/vsimem/tmp.gif') - if ds is None: - return 'fail' - if ds.GetRasterBand(1).Checksum() != 4672: - return 'fail' + assert ds is not None + assert ds.GetRasterBand(1).Checksum() == 4672 gdal.Unlink('/vsimem/tmp.gif') - return 'success' - ############################################################################### # Test interlacing -def gif_10(): +def test_gif_10(): tst = gdaltest.GDALTest('GIF', 'byte.tif', 1, 4672, options=['INTERLACING=YES']) @@ -243,28 +215,8 @@ def gif_10(): # Cleanup. -def gif_cleanup(): +def test_gif_cleanup(): gdaltest.clean_tmp() - return 'success' - - -gdaltest_list = [ - gif_1, - gif_2, - gif_3, - gif_4, - gif_5, - gif_6, - gif_7, - gif_8, - gif_9, - gif_10, - gif_cleanup] - -if __name__ == '__main__': - gdaltest.setup_run('gif') - gdaltest.run_tests(gdaltest_list) - sys.exit(gdaltest.summarize()) diff --git a/autotest/gdrivers/gmt.py b/autotest/gdrivers/gmt.py index d6edb163701a..6057595c4c57 100755 --- a/autotest/gdrivers/gmt.py +++ b/autotest/gdrivers/gmt.py @@ -28,23 +28,22 @@ # DEALINGS IN THE SOFTWARE. ############################################################################### -import sys from osgeo import gdal -sys.path.append('../pymod') import gdaltest +import pytest ############################################################################### # Perform simple read test. -def gmt_1(): +def test_gmt_1(): gdaltest.gmt_drv = gdal.GetDriverByName('GMT') if gdaltest.gmt_drv is None: - return 'skip' + pytest.skip() tst = gdaltest.GDALTest('GMT', 'gmt_1.grd', 1, 34762) @@ -57,10 +56,10 @@ def gmt_1(): # Verify a simple createcopy operation with 16bit data. -def gmt_2(): +def test_gmt_2(): if gdaltest.gmt_drv is None: - return 'skip' + pytest.skip() tst = gdaltest.GDALTest('GMT', 'int16.tif', 1, 4672) return tst.testCreateCopy(check_gt=1) @@ -68,15 +67,5 @@ def gmt_2(): ############################################################################### -gdaltest_list = [ - gmt_1, - gmt_2] -if __name__ == '__main__': - - gdaltest.setup_run('gmt') - - gdaltest.run_tests(gdaltest_list) - - sys.exit(gdaltest.summarize()) diff --git a/autotest/gdrivers/gpkg.py b/autotest/gdrivers/gpkg.py index 5320e4db8cc7..721bc05d8ca0 100755 --- a/autotest/gdrivers/gpkg.py +++ b/autotest/gdrivers/gpkg.py @@ -31,13 +31,13 @@ import os import sys +import pytest # Make sure we run from the directory of the script if os.path.basename(sys.argv[0]) == os.path.basename(__file__): if os.path.dirname(sys.argv[0]) != '': os.chdir(os.path.dirname(sys.argv[0])) -sys.path.append('../pymod') sys.path.append('../../gdal/swig/python/samples') from osgeo import osr, gdal, ogr @@ -80,13 +80,13 @@ def validate(filename, quiet=False): # Test if GPKG and tile drivers are available -def gpkg_init(): +def test_gpkg_init(): gdaltest.gpkg_dr = None gdaltest.gpkg_dr = gdal.GetDriverByName('GPKG') if gdaltest.gpkg_dr is None: - return 'skip' + pytest.skip() gdaltest.png_dr = gdal.GetDriverByName('PNG') gdaltest.jpeg_dr = gdal.GetDriverByName('JPEG') @@ -104,8 +104,6 @@ def gpkg_init(): gdal.SetConfigOption('GPKG_DEBUG', 'ON') - return 'success' - ############################################################################### # @@ -174,8 +172,8 @@ def check_tile_format(out_ds, expected_format, expected_band_count, expected_ct, if expected_format is None: if mime_type is None: - return 'success' - return 'fail' + return + pytest.fail() if expected_format == 'PNG': expected_mime_type = 'image/png' @@ -184,30 +182,20 @@ def check_tile_format(out_ds, expected_format, expected_band_count, expected_ct, elif expected_format == 'WEBP': expected_mime_type = 'image/x-webp' - if mime_type != expected_mime_type: - gdaltest.post_reason('fail') - print(mime_type) - return 'fail' - if band_count != expected_band_count: - gdaltest.post_reason('fail') - print(band_count) - return 'fail' - if expected_ct != has_ct: - gdaltest.post_reason('fail') - print(has_ct) - return 'fail' - return 'success' + assert mime_type == expected_mime_type + assert band_count == expected_band_count + assert expected_ct == has_ct ############################################################################### # Single band, PNG -def gpkg_1(): +def test_gpkg_1(): if gdaltest.gpkg_dr is None: - return 'skip' + pytest.skip() if gdaltest.png_dr is None: - return 'skip' + pytest.skip() gdal.Unlink('/vsimem/tmp.gpkg') @@ -221,44 +209,30 @@ def gpkg_1(): gdaltest.gpkg_dr.CreateCopy('/vsimem/tmp.gpkg', ds, options=['TILE_FORMAT=PNG']) ds = None - if not validate('/vsimem/tmp.gpkg'): - gdaltest.post_reason('validation failed') - return 'fail' + assert validate('/vsimem/tmp.gpkg'), 'validation failed' out_ds = gdal.Open('/vsimem/tmp.gpkg') # Check there's no ogr_empty_table sql_lyr = out_ds.ExecuteSQL("SELECT COUNT(*) FROM sqlite_master WHERE name = 'ogr_empty_table'") f = sql_lyr.GetNextFeature() - if f.GetField(0) != 0: - gdaltest.post_reason('fail') - return 'fail' + assert f.GetField(0) == 0 out_ds.ReleaseResultSet(sql_lyr) got_gt = out_ds.GetGeoTransform() for i in range(6): - if abs(expected_gt[i] - got_gt[i]) > 1e-8: - gdaltest.post_reason('fail') - return 'fail' + assert abs(expected_gt[i] - got_gt[i]) <= 1e-8 got_wkt = out_ds.GetProjectionRef() - if expected_wkt != got_wkt: - gdaltest.post_reason('fail') - return 'fail' + assert expected_wkt == got_wkt expected_cs = [expected_cs, expected_cs, expected_cs, 4873] got_cs = [out_ds.GetRasterBand(i + 1).Checksum() for i in range(4)] - if got_cs != expected_cs: - gdaltest.post_reason('fail') - print('Got %s, expected %s' % (str(got_cs), str(expected_cs))) - return 'fail' - if check_tile_format(out_ds, 'PNG', 2, False) != 'success': - return 'fail' + assert got_cs == expected_cs + check_tile_format(out_ds, 'PNG', 2, False) # Check that there's no extensions out_ds = gdal.Open('/vsimem/tmp.gpkg') sql_lyr = out_ds.ExecuteSQL("SELECT * FROM sqlite_master WHERE type = 'table' AND name = 'gpkg_extensions'") - if sql_lyr.GetFeatureCount() != 0: - gdaltest.post_reason('fail') - return 'fail' + assert sql_lyr.GetFeatureCount() == 0 out_ds.ReleaseResultSet(sql_lyr) out_ds = None @@ -266,22 +240,14 @@ def gpkg_1(): out_ds = gdal.OpenEx('/vsimem/tmp.gpkg', open_options=['BAND_COUNT=3']) expected_cs = expected_cs[0:3] got_cs = [out_ds.GetRasterBand(i + 1).Checksum() for i in range(out_ds.RasterCount)] - if got_cs != expected_cs: - gdaltest.post_reason('fail') - print('Got %s, expected %s' % (str(got_cs), str(expected_cs))) - return 'fail' + assert got_cs == expected_cs out_ds = None ds = gdal.OpenEx('/vsimem/tmp.gpkg', open_options=['USE_TILE_EXTENT=YES']) - if ds.RasterXSize != 256 or ds.RasterYSize != 256: - gdaltest.post_reason('fail') - return 'fail' + assert ds.RasterXSize == 256 and ds.RasterYSize == 256 expected_cs = [clamped_expected_cs, clamped_expected_cs, clamped_expected_cs, 4898] got_cs = [ds.GetRasterBand(i + 1).Checksum() for i in range(4)] - if got_cs != expected_cs: - gdaltest.post_reason('fail') - print('Got %s, expected %s' % (str(got_cs), str(expected_cs))) - return 'fail' + assert got_cs == expected_cs ds = None # Test USE_TILE_EXTENT=YES with empty table @@ -289,9 +255,7 @@ def gpkg_1(): ds.ExecuteSQL('DELETE FROM tmp') ds = None ds = gdal.OpenEx('/vsimem/tmp.gpkg', gdal.OF_RASTER, open_options=['USE_TILE_EXTENT=YES']) - if ds is not None: - gdaltest.post_reason('fail') - return 'fail' + assert ds is None gdal.Unlink('/vsimem/tmp.gpkg') @@ -304,28 +268,22 @@ def gpkg_1(): out_ds = gdal.Open('/vsimem/tmp.gpkg') expected_cs = [expected_cs, expected_cs, expected_cs, 4873] got_cs = [out_ds.GetRasterBand(i + 1).Checksum() for i in range(4)] - if got_cs != expected_cs: - gdaltest.post_reason('fail') - print('Got %s, expected %s' % (str(got_cs), str(expected_cs))) - return 'fail' - if check_tile_format(out_ds, 'PNG', 1, False) != 'success': - return 'fail' + assert got_cs == expected_cs + check_tile_format(out_ds, 'PNG', 1, False) out_ds = None gdal.Unlink('/vsimem/tmp.gpkg') - return 'success' - ############################################################################### # Single band, JPEG -def gpkg_2(): +def test_gpkg_2(): if gdaltest.gpkg_dr is None: - return 'skip' + pytest.skip() if gdaltest.jpeg_dr is None: - return 'skip' + pytest.skip() gdal.Unlink('/vsimem/tmp.gpkg') @@ -341,29 +299,20 @@ def gpkg_2(): out_ds = gdal.Open('/vsimem/tmp.gpkg') expected_cs = [expected_cs, expected_cs, expected_cs, 4873] got_cs = [out_ds.GetRasterBand(i + 1).Checksum() for i in range(4)] - if got_cs != expected_cs: - gdaltest.post_reason('fail') - print('Got %s, expected %s' % (str(got_cs), str(expected_cs))) - return 'fail' - if check_tile_format(out_ds, 'JPEG', 1, False) != 'success': - return 'fail' + assert got_cs == expected_cs + check_tile_format(out_ds, 'JPEG', 1, False) # Check that there's no extensions out_ds = gdal.Open('/vsimem/tmp.gpkg') sql_lyr = out_ds.ExecuteSQL("SELECT * FROM sqlite_master WHERE type = 'table' AND name = 'gpkg_extensions'") - if sql_lyr.GetFeatureCount() != 0: - gdaltest.post_reason('fail') - return 'fail' + assert sql_lyr.GetFeatureCount() == 0 out_ds.ReleaseResultSet(sql_lyr) out_ds = None ds = gdal.OpenEx('/vsimem/tmp.gpkg', open_options=['USE_TILE_EXTENT=YES']) got_cs = [ds.GetRasterBand(i + 1).Checksum() for i in range(4)] - if got_cs != clamped_expected_cs: - gdaltest.post_reason('fail') - print('Got %s, expected %s' % (str(got_cs), str(clamped_expected_cs))) - return 'fail' + assert got_cs == clamped_expected_cs ds = None gdal.Unlink('/vsimem/tmp.gpkg') @@ -377,12 +326,8 @@ def gpkg_2(): out_ds = gdal.Open('/vsimem/tmp.gpkg') expected_cs = [expected_cs, expected_cs, expected_cs, 4873] got_cs = [out_ds.GetRasterBand(i + 1).Checksum() for i in range(4)] - if got_cs != expected_cs: - gdaltest.post_reason('fail') - print('Got %s, expected %s' % (str(got_cs), str(expected_cs))) - return 'fail' - if check_tile_format(out_ds, 'JPEG', 1, False) != 'success': - return 'fail' + assert got_cs == expected_cs + check_tile_format(out_ds, 'JPEG', 1, False) # Try deregistering JPEG driver gdaltest.jpeg_dr.Deregister() @@ -393,9 +338,7 @@ def gpkg_2(): gdal.PushErrorHandler('CPLQuietErrorHandler') out_ds.GetRasterBand(1).Checksum() gdal.PopErrorHandler() - if gdal.GetLastErrorMsg() == '': - gdaltest.post_reason('fail') - return 'fail' + assert gdal.GetLastErrorMsg() != '' out_ds = None gdal.Unlink('/vsimem/tmp.gpkg') @@ -406,9 +349,7 @@ def gpkg_2(): gdal.PushErrorHandler('CPLQuietErrorHandler') out_ds.FlushCache() gdal.PopErrorHandler() - if gdal.GetLastErrorMsg() == '': - gdaltest.post_reason('fail') - return 'fail' + assert gdal.GetLastErrorMsg() != '' out_ds = None # Re-register driver @@ -416,18 +357,16 @@ def gpkg_2(): gdal.Unlink('/vsimem/tmp.gpkg') - return 'success' - ############################################################################### # Single band, WEBP -def gpkg_3(): +def test_gpkg_3(): if gdaltest.gpkg_dr is None: - return 'skip' + pytest.skip() if gdaltest.webp_dr is None: - return 'skip' + pytest.skip() gdal.Unlink('/vsimem/tmp.gpkg') @@ -442,39 +381,28 @@ def gpkg_3(): out_ds = gdaltest.gpkg_dr.CreateCopy('/vsimem/tmp.gpkg', ds, options=['TILE_FORMAT=WEBP']) out_ds = None - if not validate('/vsimem/tmp.gpkg'): - gdaltest.post_reason('validation failed') - return 'fail' + assert validate('/vsimem/tmp.gpkg'), 'validation failed' out_ds = gdal.OpenEx('/vsimem/tmp.gpkg') got_cs = [out_ds.GetRasterBand(i + 1).Checksum() for i in range(3)] - if got_cs not in (expected_cs, [4736, 4734, 4736]): - gdaltest.post_reason('fail') - print('Got %s, expected %s' % (str(got_cs), str(expected_cs))) - return 'fail' + assert got_cs in (expected_cs, [4736, 4734, 4736]) # Check that extension is declared sql_lyr = out_ds.ExecuteSQL("SELECT * FROM gpkg_extensions WHERE table_name = 'tmp' AND column_name = 'tile_data' AND extension_name = 'gpkg_webp'") - if sql_lyr.GetFeatureCount() != 1: - gdaltest.post_reason('fail') - return 'fail' + assert sql_lyr.GetFeatureCount() == 1 out_ds.ReleaseResultSet(sql_lyr) if gdaltest.webp_supports_rgba: expected_band_count = 4 else: expected_band_count = 3 - if check_tile_format(out_ds, 'WEBP', expected_band_count, False) != 'success': - return 'fail' + check_tile_format(out_ds, 'WEBP', expected_band_count, False) out_ds = None ds = gdal.OpenEx('/vsimem/tmp.gpkg', open_options=['USE_TILE_EXTENT=YES']) got_cs = [ds.GetRasterBand(i + 1).Checksum() for i in range(4)] - if got_cs not in (clamped_expected_cs, [6850, 6848, 6850, 4898]): - gdaltest.post_reason('fail') - print('Got %s, expected %s' % (str(got_cs), str(clamped_expected_cs))) - return 'fail' + assert got_cs in (clamped_expected_cs, [6850, 6848, 6850, 4898]) ds = None gdal.Unlink('/vsimem/tmp.gpkg') @@ -488,12 +416,8 @@ def gpkg_3(): out_ds = gdal.Open('/vsimem/tmp.gpkg') expected_cs.append(4873) got_cs = [out_ds.GetRasterBand(i + 1).Checksum() for i in range(4)] - if got_cs != expected_cs: - gdaltest.post_reason('fail') - print('Got %s, expected %s' % (str(got_cs), str(expected_cs))) - return 'fail' - if check_tile_format(out_ds, 'WEBP', 3, False) != 'success': - return 'fail' + assert got_cs == expected_cs + check_tile_format(out_ds, 'WEBP', 3, False) # Try deregistering WEBP driver gdaltest.webp_dr.Deregister() @@ -505,8 +429,7 @@ def gpkg_3(): gdal.PopErrorHandler() if gdal.GetLastErrorMsg() == '': gdaltest.webp_dr.Register() - gdaltest.post_reason('fail') - return 'fail' + pytest.fail() # And at pixel reading time as well gdal.ErrorReset() @@ -515,8 +438,7 @@ def gpkg_3(): gdal.PopErrorHandler() if gdal.GetLastErrorMsg() == '': gdaltest.webp_dr.Register() - gdaltest.post_reason('fail') - return 'fail' + pytest.fail() out_ds = None # Re-register driver @@ -531,24 +453,20 @@ def gpkg_3(): out_ds = gdal.OpenEx('/vsimem/tmp.gpkg', gdal.OF_RASTER | gdal.OF_UPDATE, open_options=['TILE_FORMAT=WEBP']) sql_lyr = out_ds.ExecuteSQL("SELECT * FROM gpkg_extensions WHERE table_name = 'tmp' AND column_name = 'tile_data' AND extension_name = 'gpkg_webp'") - if sql_lyr.GetFeatureCount() != 1: - gdaltest.post_reason('fail') - return 'fail' + assert sql_lyr.GetFeatureCount() == 1 out_ds.ReleaseResultSet(sql_lyr) out_ds = None gdal.Unlink('/vsimem/tmp.gpkg') - return 'success' - ############################################################################### # Three band, PNG -def gpkg_4(tile_drv_name='PNG'): +def test_gpkg_4(tile_drv_name='PNG'): if gdaltest.gpkg_dr is None: - return 'skip' + pytest.skip() if tile_drv_name == 'PNG': tile_drv = gdaltest.png_dr working_bands = 4 @@ -562,7 +480,7 @@ def gpkg_4(tile_drv_name='PNG'): else: working_bands = 3 if tile_drv is None: - return 'skip' + pytest.skip() gdal.Unlink('/vsimem/tmp.gpkg') @@ -581,20 +499,13 @@ def gpkg_4(tile_drv_name='PNG'): out_ds = gdal.Open('/vsimem/tmp.gpkg') expected_cs.append(30658) got_cs = [out_ds.GetRasterBand(i + 1).Checksum() for i in range(4)] - if got_cs not in (expected_cs, [22290, 21651, 21551, 30658]): - gdaltest.post_reason('fail') - print('Got %s, expected %s' % (str(got_cs), str(expected_cs))) - return 'fail' - if check_tile_format(out_ds, tile_drv_name, working_bands, False) != 'success': - return 'fail' + assert got_cs in (expected_cs, [22290, 21651, 21551, 30658]) + check_tile_format(out_ds, tile_drv_name, working_bands, False) out_ds = None ds = gdal.OpenEx('/vsimem/tmp.gpkg', open_options=['USE_TILE_EXTENT=YES']) got_cs = [ds.GetRasterBand(i + 1).Checksum() for i in range(4)] - if got_cs not in (clamped_expected_cs, [56886, 43228, 56508, 30638]): - gdaltest.post_reason('fail') - print('Got %s, expected %s' % (str(got_cs), str(clamped_expected_cs))) - return 'fail' + assert got_cs in (clamped_expected_cs, [56886, 43228, 56508, 30638]) ds = None gdal.Unlink('/vsimem/tmp.gpkg') @@ -608,31 +519,25 @@ def gpkg_4(tile_drv_name='PNG'): out_ds = gdal.Open('/vsimem/tmp.gpkg') got_cs = [out_ds.GetRasterBand(i + 1).Checksum() for i in range(4)] - if got_cs != expected_cs: - gdaltest.post_reason('fail') - print('Got %s, expected %s' % (str(got_cs), str(expected_cs))) - return 'fail' - if check_tile_format(out_ds, tile_drv_name, 3, False) != 'success': - return 'fail' + assert got_cs == expected_cs + check_tile_format(out_ds, tile_drv_name, 3, False) out_ds = None gdal.Unlink('/vsimem/tmp.gpkg') - return 'success' - ############################################################################### # Three band, JPEG -def gpkg_5(): - return gpkg_4(tile_drv_name='JPEG') +def test_gpkg_5(): + return test_gpkg_4(tile_drv_name='JPEG') ############################################################################### # Three band, WEBP -def gpkg_6(): - return gpkg_4(tile_drv_name='WEBP') +def test_gpkg_6(): + return test_gpkg_4(tile_drv_name='WEBP') ############################################################################### # 4 band, PNG @@ -653,10 +558,10 @@ def get_georeferenced_rgba_ds(alpha_fully_transparent=False, alpha_fully_opaque= return tmp_ds -def gpkg_7(tile_drv_name='PNG'): +def test_gpkg_7(tile_drv_name='PNG'): if gdaltest.gpkg_dr is None: - return 'skip' + pytest.skip() if tile_drv_name == 'PNG': tile_drv = gdaltest.png_dr working_bands = 4 @@ -670,7 +575,7 @@ def gpkg_7(tile_drv_name='PNG'): else: working_bands = 3 if tile_drv is None: - return 'skip' + pytest.skip() gdal.Unlink('/vsimem/tmp.gpkg') @@ -686,12 +591,8 @@ def gpkg_7(tile_drv_name='PNG'): out_ds = gdal.Open('/vsimem/tmp.gpkg') got_cs = [out_ds.GetRasterBand(i + 1).Checksum() for i in range(working_bands)] - if got_cs != expected_cs: - gdaltest.post_reason('fail') - print('Got %s, expected %s' % (str(got_cs), str(expected_cs))) - return 'fail' - if check_tile_format(out_ds, tile_drv_name, working_bands, False) != 'success': - return 'fail' + assert got_cs == expected_cs + check_tile_format(out_ds, tile_drv_name, working_bands, False) out_ds = None gdal.Unlink('/vsimem/tmp.gpkg') @@ -707,12 +608,8 @@ def gpkg_7(tile_drv_name='PNG'): out_ds = gdal.Open('/vsimem/tmp.gpkg') got_cs = [out_ds.GetRasterBand(i + 1).Checksum() for i in range(3)] - if got_cs != expected_cs: - gdaltest.post_reason('fail') - print('Got %s, expected %s' % (str(got_cs), str(expected_cs))) - return 'fail' - if check_tile_format(out_ds, tile_drv_name, 3, False) != 'success': - return 'fail' + assert got_cs == expected_cs + check_tile_format(out_ds, tile_drv_name, 3, False) out_ds = None gdal.Unlink('/vsimem/tmp.gpkg') @@ -728,31 +625,25 @@ def gpkg_7(tile_drv_name='PNG'): out_ds = gdal.Open('/vsimem/tmp.gpkg') expected_cs = [0, 0, 0, 0] got_cs = [out_ds.GetRasterBand(i + 1).Checksum() for i in range(4)] - if got_cs != expected_cs: - gdaltest.post_reason('fail') - print('Got %s, expected %s' % (str(got_cs), str(expected_cs))) - return 'fail' - if check_tile_format(out_ds, None, None, None) != 'success': - return 'fail' + assert got_cs == expected_cs + check_tile_format(out_ds, None, None, None) out_ds = None gdal.Unlink('/vsimem/tmp.gpkg') - return 'success' - ############################################################################### # 4 band, JPEG -def gpkg_8(): - return gpkg_7(tile_drv_name='JPEG') +def test_gpkg_8(): + return test_gpkg_7(tile_drv_name='JPEG') ############################################################################### # 4 band, WEBP -def gpkg_9(): - return gpkg_7(tile_drv_name='WEBP') +def test_gpkg_9(): + return test_gpkg_7(tile_drv_name='WEBP') ############################################################################### # @@ -772,12 +663,12 @@ def get_georeferenced_ds_with_pct32(): # Single band with 32 bit color table, PNG -def gpkg_10(): +def test_gpkg_10(): if gdaltest.gpkg_dr is None: - return 'skip' + pytest.skip() if gdaltest.png_dr is None: - return 'skip' + pytest.skip() gdal.Unlink('/vsimem/tmp.gpkg') @@ -793,53 +684,35 @@ def gpkg_10(): expected_cs = [10991, 57677, 34965, 10638] out_ds = gdal.Open('/vsimem/tmp.gpkg') block_size = out_ds.GetRasterBand(1).GetBlockSize() - if block_size != [out_ds.RasterXSize, out_ds.RasterYSize]: - gdaltest.post_reason('fail') - print(block_size) - return 'fail' + assert block_size == [out_ds.RasterXSize, out_ds.RasterYSize] got_cs = [out_ds.GetRasterBand(i + 1).Checksum() for i in range(4)] - if got_cs != expected_cs: - gdaltest.post_reason('fail') - print('Got %s, expected %s' % (str(got_cs), str(expected_cs))) - return 'fail' - if check_tile_format(out_ds, 'PNG', 1, True) != 'success': - return 'fail' + assert got_cs == expected_cs + check_tile_format(out_ds, 'PNG', 1, True) got_ct = out_ds.GetRasterBand(1).GetColorTable() - if got_ct is not None: - gdaltest.post_reason('fail') - return 'fail' + assert got_ct is None # SetColorTable() on a non single-band dataset gdal.ErrorReset() gdal.PushErrorHandler() out_ds.GetRasterBand(1).SetColorTable(None) gdal.PopErrorHandler() - if gdal.GetLastErrorMsg() == '': - gdaltest.post_reason('fail') - return 'fail' + assert gdal.GetLastErrorMsg() != '' out_ds = None expected_cs = [expected_cs_single_band] out_ds = gdal.OpenEx('/vsimem/tmp.gpkg', open_options=['BAND_COUNT=1']) got_cs = [out_ds.GetRasterBand(i + 1).Checksum() for i in range(out_ds.RasterCount)] - if got_cs != expected_cs: - gdaltest.post_reason('fail') - print('Got %s, expected %s' % (str(got_cs), str(expected_cs))) - return 'fail' + assert got_cs == expected_cs got_ct = out_ds.GetRasterBand(1).GetColorTable() - if expected_ct.GetCount() != got_ct.GetCount(): - gdaltest.post_reason('fail') - return 'fail' + assert expected_ct.GetCount() == got_ct.GetCount() # SetColorTable() on a re-opened dataset gdal.ErrorReset() gdal.PushErrorHandler() out_ds.GetRasterBand(1).SetColorTable(None) gdal.PopErrorHandler() - if gdal.GetLastErrorMsg() == '': - gdaltest.post_reason('fail') - return 'fail' + assert gdal.GetLastErrorMsg() != '' out_ds = None @@ -853,9 +726,7 @@ def gpkg_10(): gdal.PushErrorHandler() out_ds.GetRasterBand(1).SetColorTable(None) gdal.PopErrorHandler() - if gdal.GetLastErrorMsg() == '': - gdaltest.post_reason('fail') - return 'fail' + assert gdal.GetLastErrorMsg() != '' gdal.PushErrorHandler() out_ds = None @@ -876,27 +747,19 @@ def gpkg_10(): expected_cs = [10991, 57677, 34965, 10638] out_ds = gdal.Open('/vsimem/tmp.gpkg') got_cs = [out_ds.GetRasterBand(i + 1).Checksum() for i in range(4)] - if got_cs != expected_cs: - gdaltest.post_reason('fail') - print('Got %s, expected %s' % (str(got_cs), str(expected_cs))) - return 'fail' - if check_tile_format(out_ds, 'PNG', 4, False) != 'success': - return 'fail' + assert got_cs == expected_cs + check_tile_format(out_ds, 'PNG', 4, False) got_ct = out_ds.GetRasterBand(1).GetColorTable() - if got_ct is not None: - gdaltest.post_reason('fail') - return 'fail' - - return 'success' + assert got_ct is None ############################################################################### # Single band with 32 bit color table, JPEG -def gpkg_11(tile_drv_name='JPEG'): +def test_gpkg_11(tile_drv_name='JPEG'): if gdaltest.gpkg_dr is None: - return 'skip' + pytest.skip() if tile_drv_name == 'JPEG': tile_drv = gdaltest.jpeg_dr working_bands = 3 @@ -907,7 +770,7 @@ def gpkg_11(tile_drv_name='JPEG'): else: working_bands = 3 if tile_drv is None: - return 'skip' + pytest.skip() gdal.Unlink('/vsimem/tmp.gpkg') @@ -935,33 +798,28 @@ def gpkg_11(tile_drv_name='JPEG'): out_ds = gdal.Open('/vsimem/tmp.gpkg') got_cs = [out_ds.GetRasterBand(i + 1).Checksum() for i in range(working_bands)] - if got_cs != expected_cs: - gdaltest.post_reason('fail') - print('Got %s, expected %s' % (str(got_cs), str(expected_cs))) - return 'fail' + assert got_cs == expected_cs out_ds = None gdal.Unlink('/vsimem/tmp.gpkg') - return 'success' - ############################################################################### # Single band with 32 bit color table, WEBP -def gpkg_12(): - return gpkg_11(tile_drv_name='WEBP') +def test_gpkg_12(): + return test_gpkg_11(tile_drv_name='WEBP') ############################################################################### # Single band with 24 bit color table, PNG -def gpkg_13(): +def test_gpkg_13(): if gdaltest.gpkg_dr is None: - return 'skip' + pytest.skip() if gdaltest.png_dr is None: - return 'skip' + pytest.skip() gdal.Unlink('/vsimem/tmp.gpkg') @@ -975,27 +833,17 @@ def gpkg_13(): expected_cs = [63025, 48175, 12204] out_ds = gdal.Open('/vsimem/tmp.gpkg') got_cs = [out_ds.GetRasterBand(i + 1).Checksum() for i in range(3)] - if got_cs != expected_cs: - gdaltest.post_reason('fail') - print('Got %s, expected %s' % (str(got_cs), str(expected_cs))) - return 'fail' + assert got_cs == expected_cs got_ct = out_ds.GetRasterBand(1).GetColorTable() - if got_ct is not None: - gdaltest.post_reason('fail') - return 'fail' + assert got_ct is None out_ds = None expected_cs = [expected_cs_single_band] out_ds = gdal.OpenEx('/vsimem/tmp.gpkg', open_options=['BAND_COUNT=1']) got_cs = [out_ds.GetRasterBand(i + 1).Checksum() for i in range(out_ds.RasterCount)] - if got_cs != expected_cs: - gdaltest.post_reason('fail') - print('Got %s, expected %s' % (str(got_cs), str(expected_cs))) - return 'fail' + assert got_cs == expected_cs got_ct = out_ds.GetRasterBand(1).GetColorTable() - if expected_ct.GetCount() != got_ct.GetCount(): - gdaltest.post_reason('fail') - return 'fail' + assert expected_ct.GetCount() == got_ct.GetCount() out_ds = None gdal.Unlink('/vsimem/tmp.gpkg') @@ -1009,30 +857,24 @@ def gpkg_13(): src_ds = None ds = gdal.OpenEx('/vsimem/tmp.gpkg', open_options=['USE_TILE_EXTENT=YES']) - if ds.RasterXSize != 512 or ds.RasterYSize != 256: - gdaltest.post_reason('fail') - return 'fail' + assert ds.RasterXSize == 512 and ds.RasterYSize == 256 expected_cs = [62358, 45823, 12238, 64301] got_cs = [ds.GetRasterBand(i + 1).Checksum() for i in range(4)] - if got_cs != expected_cs: - gdaltest.post_reason('fail') - print('Got %s, expected %s' % (str(got_cs), str(expected_cs))) - return 'fail' + assert got_cs == expected_cs ds = None gdal.Unlink('/vsimem/tmp.gpkg') - return 'success' ############################################################################### # Test creation and opening options -def gpkg_14(): +def test_gpkg_14(): if gdaltest.gpkg_dr is None: - return 'skip' + pytest.skip() if gdaltest.png_dr is None: - return 'skip' + pytest.skip() gdal.Unlink('/vsimem/tmp.gpkg') @@ -1043,86 +885,46 @@ def gpkg_14(): gdal.PushErrorHandler() ds = gdal.OpenEx('/vsimem/tmp.gpkg', open_options=['TABLE=non_existing']) gdal.PopErrorHandler() - if ds is not None: - gdaltest.post_reason('fail') - return 'fail' + assert ds is None ds = gdal.Open('/vsimem/tmp.gpkg') sql_lyr = ds.ExecuteSQL("SELECT * FROM gpkg_contents WHERE table_name='foo'") feat_count = sql_lyr.GetFeatureCount() ds.ReleaseResultSet(sql_lyr) - if feat_count != 1: - gdaltest.post_reason('fail') - return 'fail' - if ds.GetMetadataItem('IDENTIFIER') != 'bar': - gdaltest.post_reason('fail') - print(ds.GetMetadata()) - return 'fail' - if ds.GetMetadataItem('DESCRIPTION') != 'baz': - gdaltest.post_reason('fail') - print(ds.GetMetadata()) - return 'fail' - if ds.GetMetadataItem('ZOOM_LEVEL') != '1': - gdaltest.post_reason('fail') - print(ds.GetMetadata()) - return 'fail' - if ds.GetRasterBand(1).GetOverviewCount() != 0: - gdaltest.post_reason('fail') - return 'fail' - if ds.GetRasterBand(1).GetOverview(0) is not None: - gdaltest.post_reason('fail') - return 'fail' + assert feat_count == 1 + assert ds.GetMetadataItem('IDENTIFIER') == 'bar', ds.GetMetadata() + assert ds.GetMetadataItem('DESCRIPTION') == 'baz', ds.GetMetadata() + assert ds.GetMetadataItem('ZOOM_LEVEL') == '1', ds.GetMetadata() + assert ds.GetRasterBand(1).GetOverviewCount() == 0 + assert ds.GetRasterBand(1).GetOverview(0) is None ds = None # In update mode, we expose even empty overview levels ds = gdal.Open('/vsimem/tmp.gpkg', gdal.GA_Update) - if ds.GetMetadataItem('ZOOM_LEVEL') != '1': - gdaltest.post_reason('fail') - print(ds.GetMetadata()) - return 'fail' - if ds.GetRasterBand(1).GetOverviewCount() != 1: - gdaltest.post_reason('fail') - return 'fail' - if ds.GetRasterBand(1).GetOverview(0) is None: - gdaltest.post_reason('fail') - return 'fail' - if ds.GetRasterBand(1).GetOverview(0).Checksum() != 0: - gdaltest.post_reason('fail') - return 'fail' + assert ds.GetMetadataItem('ZOOM_LEVEL') == '1', ds.GetMetadata() + assert ds.GetRasterBand(1).GetOverviewCount() == 1 + assert ds.GetRasterBand(1).GetOverview(0) is not None + assert ds.GetRasterBand(1).GetOverview(0).Checksum() == 0 ds = None ds = gdal.OpenEx('/vsimem/tmp.gpkg', open_options=['ZOOM_LEVEL=2']) - if ds.RasterXSize != 400: - gdaltest.post_reason('fail') - return 'fail' + assert ds.RasterXSize == 400 ds = None ds = gdal.OpenEx('/vsimem/tmp.gpkg', open_options=['ZOOM_LEVEL=1']) - if ds.RasterXSize != 400: - gdaltest.post_reason('fail') - return 'fail' - if ds.GetRasterBand(1).GetOverviewCount() != 0: - gdaltest.post_reason('fail') - return 'fail' + assert ds.RasterXSize == 400 + assert ds.GetRasterBand(1).GetOverviewCount() == 0 ds = None # In update mode, we expose even empty overview levels ds = gdal.OpenEx('/vsimem/tmp.gpkg', gdal.OF_UPDATE, open_options=['ZOOM_LEVEL=1']) - if ds.RasterXSize != 400: - gdaltest.post_reason('fail') - return 'fail' - if ds.GetRasterBand(1).GetOverviewCount() != 1: - gdaltest.post_reason('fail') - return 'fail' + assert ds.RasterXSize == 400 + assert ds.GetRasterBand(1).GetOverviewCount() == 1 ds = None ds = gdal.OpenEx('/vsimem/tmp.gpkg', open_options=['ZOOM_LEVEL=0']) - if ds.RasterXSize != 200: - gdaltest.post_reason('fail') - return 'fail' - if ds.GetRasterBand(1).Checksum() != 0: - gdaltest.post_reason('fail') - return 'fail' + assert ds.RasterXSize == 200 + assert ds.GetRasterBand(1).Checksum() == 0 ds = None gdal.Translate('/vsimem/tmp2.gpkg', 'data/byte.tif', format='GPKG') @@ -1131,34 +933,22 @@ def gpkg_14(): ds = None with gdaltest.error_handler(): ds = gdal.OpenEx('/vsimem/tmp2.gpkg', open_options=['ZOOM_LEVEL=-1']) - if ds is not None: - gdaltest.post_reason('fail') - return 'fail' + assert ds is None gdal.Unlink('/vsimem/tmp2.gpkg') ds = gdal.OpenEx('/vsimem/tmp.gpkg', open_options=['USE_TILE_EXTENT=YES']) - if ds.RasterXSize != 512 or ds.RasterYSize != 256: - gdaltest.post_reason('fail') - return 'fail' + assert ds.RasterXSize == 512 and ds.RasterYSize == 256 expected_cs = [27644, 31968, 38564, 64301] got_cs = [ds.GetRasterBand(i + 1).Checksum() for i in range(4)] - if got_cs != expected_cs: - gdaltest.post_reason('fail') - print('Got %s, expected %s' % (str(got_cs), str(expected_cs))) - return 'fail' + assert got_cs == expected_cs ds = None # Open with exactly one tile shift ds = gdal.OpenEx('/vsimem/tmp.gpkg', gdal.OF_UPDATE, open_options=['TILE_FORMAT=PNG', 'MINX=-410.4', 'MAXY=320.4']) - if ds.RasterXSize != 400 + 256 or ds.RasterYSize != 200 + 256: - gdaltest.post_reason('fail') - return 'fail' + assert ds.RasterXSize == 400 + 256 and ds.RasterYSize == 200 + 256 expected_cs = [29070, 32796, 41086, 64288] got_cs = [ds.GetRasterBand(i + 1).Checksum() for i in range(4)] - if got_cs != expected_cs: - gdaltest.post_reason('fail') - print('Got %s, expected %s' % (str(got_cs), str(expected_cs))) - return 'fail' + assert got_cs == expected_cs data = ds.ReadRaster(0, 0, ds.RasterXSize, ds.RasterYSize) for i in range(ds.RasterCount): ds.GetRasterBand(i + 1).Fill(0) @@ -1166,25 +956,16 @@ def gpkg_14(): sql_lyr = ds.ExecuteSQL('SELECT * FROM foo') fc = sql_lyr.GetFeatureCount() ds.ReleaseResultSet(sql_lyr) - if fc != 0: - gdaltest.post_reason('fail') - return 'fail' + assert fc == 0 ds.WriteRaster(0, 0, ds.RasterXSize, ds.RasterYSize, data) ds = None # Partial tile shift (enclosing tiles) ds = gdal.OpenEx('GPKG:/vsimem/tmp.gpkg:foo', gdal.OF_UPDATE, open_options=['MINX=-270', 'MAXY=180', 'MINY=-180', 'MAXX=270']) - if ds.RasterXSize != 600 or ds.RasterYSize != 400: - print(ds.RasterXSize) - print(ds.RasterYSize) - gdaltest.post_reason('fail') - return 'fail' + assert ds.RasterXSize == 600 and ds.RasterYSize == 400 expected_cs = [28940, 32454, 40526, 64323] got_cs = [ds.GetRasterBand(i + 1).Checksum() for i in range(4)] - if got_cs != expected_cs: - gdaltest.post_reason('fail') - print('Got %s, expected %s' % (str(got_cs), str(expected_cs))) - return 'fail' + assert got_cs == expected_cs # Force full rewrite data = ds.ReadRaster(0, 0, ds.RasterXSize, ds.RasterYSize) @@ -1195,19 +976,14 @@ def gpkg_14(): sql_lyr = ds.ExecuteSQL('SELECT * FROM foo') fc = sql_lyr.GetFeatureCount() ds.ReleaseResultSet(sql_lyr) - if fc != 0: - gdaltest.post_reason('fail') - return 'fail' + assert fc == 0 ds.WriteRaster(0, 0, ds.RasterXSize, ds.RasterYSize, data) ds = None ds = gdal.OpenEx('GPKG:/vsimem/tmp.gpkg:foo', gdal.OF_UPDATE, open_options=['MINX=-270', 'MAXY=180', 'MINY=-180', 'MAXX=270']) expected_cs = [28940, 32454, 40526, 64323] got_cs = [ds.GetRasterBand(i + 1).Checksum() for i in range(4)] - if got_cs != expected_cs: - gdaltest.post_reason('fail') - print('Got %s, expected %s' % (str(got_cs), str(expected_cs))) - return 'fail' + assert got_cs == expected_cs # Partial rewrite data = ds.GetRasterBand(1).ReadRaster(0, 0, 256, 256) ds.GetRasterBand(1).WriteRaster(0, 0, 256, 256, data) @@ -1216,23 +992,15 @@ def gpkg_14(): ds = gdal.OpenEx('GPKG:/vsimem/tmp.gpkg:foo', open_options=['MINX=-270', 'MAXY=180', 'MINY=-180', 'MAXX=270']) expected_cs = [28940, 32454, 40526, 64323] got_cs = [ds.GetRasterBand(i + 1).Checksum() for i in range(4)] - if got_cs != expected_cs: - gdaltest.post_reason('fail') - print('Got %s, expected %s' % (str(got_cs), str(expected_cs))) - return 'fail' + assert got_cs == expected_cs ds = None # Partial tile shift (included in tiles) ds = gdal.OpenEx('GPKG:/vsimem/tmp.gpkg:foo', gdal.OF_UPDATE, open_options=['MINX=-90', 'MAXY=45', 'MINY=-45', 'MAXX=90']) - if ds.RasterXSize != 200 or ds.RasterYSize != 100: - gdaltest.post_reason('fail') - return 'fail' + assert ds.RasterXSize == 200 and ds.RasterYSize == 100 expected_cs = [9586, 9360, 26758, 48827] got_cs = [ds.GetRasterBand(i + 1).Checksum() for i in range(4)] - if got_cs != expected_cs: - gdaltest.post_reason('fail') - print('Got %s, expected %s' % (str(got_cs), str(expected_cs))) - return 'fail' + assert got_cs == expected_cs # Force full rewrite data = ds.ReadRaster(0, 0, ds.RasterXSize, ds.RasterYSize) @@ -1240,15 +1008,10 @@ def gpkg_14(): ds = None ds = gdal.OpenEx('GPKG:/vsimem/tmp.gpkg:foo', open_options=['MINX=-90', 'MAXY=45', 'MINY=-45', 'MAXX=90']) - if ds.RasterXSize != 200 or ds.RasterYSize != 100: - gdaltest.post_reason('fail') - return 'fail' + assert ds.RasterXSize == 200 and ds.RasterYSize == 100 expected_cs = [9586, 9360, 26758, 48827] got_cs = [ds.GetRasterBand(i + 1).Checksum() for i in range(4)] - if got_cs != expected_cs: - gdaltest.post_reason('fail') - print('Got %s, expected %s' % (str(got_cs), str(expected_cs))) - return 'fail' + assert got_cs == expected_cs ds = None ds = gdaltest.gpkg_dr.CreateCopy('/vsimem/tmp.gpkg', src_ds, options=['APPEND_SUBDATASET=YES', 'RASTER_TABLE=other', 'BLOCKSIZE=64', 'TILE_FORMAT=PNG']) @@ -1260,53 +1023,26 @@ def gpkg_14(): ds = gdal.Open('/vsimem/tmp.gpkg') md = ds.GetMetadata('SUBDATASETS') - if md['SUBDATASET_1_NAME'] != 'GPKG:/vsimem/tmp.gpkg:foo': - gdaltest.post_reason('fail') - print(md) - return 'fail' - if md['SUBDATASET_1_DESC'] != 'foo - bar': - gdaltest.post_reason('fail') - print(md) - return 'fail' - if md['SUBDATASET_2_NAME'] != 'GPKG:/vsimem/tmp.gpkg:other': - gdaltest.post_reason('fail') - print(md) - return 'fail' - if md['SUBDATASET_2_DESC'] != 'other - other': - gdaltest.post_reason('fail') - print(md) - return 'fail' - if md['SUBDATASET_3_NAME'] != 'GPKG:/vsimem/tmp.gpkg:byte': - gdaltest.post_reason('fail') - print(md) - return 'fail' - if md['SUBDATASET_3_DESC'] != 'byte - byte': - gdaltest.post_reason('fail') - print(md) - return 'fail' + assert md['SUBDATASET_1_NAME'] == 'GPKG:/vsimem/tmp.gpkg:foo' + assert md['SUBDATASET_1_DESC'] == 'foo - bar' + assert md['SUBDATASET_2_NAME'] == 'GPKG:/vsimem/tmp.gpkg:other' + assert md['SUBDATASET_2_DESC'] == 'other - other' + assert md['SUBDATASET_3_NAME'] == 'GPKG:/vsimem/tmp.gpkg:byte' + assert md['SUBDATASET_3_DESC'] == 'byte - byte' ds = None ds = gdal.Open('GPKG:/vsimem/tmp.gpkg:other') block_size = ds.GetRasterBand(1).GetBlockSize() - if block_size != [64, 64]: - gdaltest.post_reason('fail') - return 'fail' + assert block_size == [64, 64] ds = None ds = gdal.OpenEx('/vsimem/tmp.gpkg', open_options=['TABLE=other', 'MINX=-90', 'MAXY=45', 'MINY=-45', 'MAXX=90']) - if ds.RasterXSize != 200 or ds.RasterYSize != 100: - gdaltest.post_reason('fail') - return 'fail' + assert ds.RasterXSize == 200 and ds.RasterYSize == 100 block_size = ds.GetRasterBand(1).GetBlockSize() - if block_size != [64, 64]: - gdaltest.post_reason('fail') - return 'fail' + assert block_size == [64, 64] expected_cs = [9586, 9360, 26758, 48827] got_cs = [ds.GetRasterBand(i + 1).Checksum() for i in range(4)] - if got_cs != expected_cs: - gdaltest.post_reason('fail') - print('Got %s, expected %s' % (str(got_cs), str(expected_cs))) - return 'fail' + assert got_cs == expected_cs ds = None gdal.Unlink('/vsimem/tmp.gpkg') @@ -1323,10 +1059,7 @@ def gpkg_14(): ds = gdal.OpenEx('/vsimem/tmp.gpkg', open_options=['MINX=-10', 'MAXY=10', 'MINY=-30', 'MAXX=30']) expected_cs = [4934, 4934, 4934, 4934] got_cs = [ds.GetRasterBand(i + 1).Checksum() for i in range(4)] - if got_cs != expected_cs: - gdaltest.post_reason('fail') - print('Got %s, expected %s' % (str(got_cs), str(expected_cs))) - return 'fail' + assert got_cs == expected_cs ds = None gdal.Unlink('/vsimem/tmp.gpkg') @@ -1344,10 +1077,7 @@ def gpkg_14(): ds = gdal.OpenEx('/vsimem/tmp.gpkg', open_options=['MINX=-10', 'MAXY=10', 'MINY=-30', 'MAXX=30']) expected_cs = [1223, 1223, 1223, 1223] got_cs = [ds.GetRasterBand(i + 1).Checksum() for i in range(4)] - if got_cs != expected_cs: - gdaltest.post_reason('fail') - print('Got %s, expected %s' % (str(got_cs), str(expected_cs))) - return 'fail' + assert got_cs == expected_cs ds = None gdal.Unlink('/vsimem/tmp.gpkg') @@ -1365,10 +1095,7 @@ def gpkg_14(): ds = gdal.OpenEx('/vsimem/tmp.gpkg') expected_cs = [13365, 13365, 13365, 13365] got_cs = [ds.GetRasterBand(i + 1).Checksum() for i in range(4)] - if got_cs != expected_cs: - gdaltest.post_reason('fail') - print('Got %s, expected %s' % (str(got_cs), str(expected_cs))) - return 'fail' + assert got_cs == expected_cs ds = None gdal.Unlink('/vsimem/tmp.gpkg') @@ -1395,33 +1122,25 @@ def gpkg_14(): sql_lyr = ds.ExecuteSQL('SELECT * FROM tmp') fc = sql_lyr.GetFeatureCount() ds.ReleaseResultSet(sql_lyr) - if fc != 0: - gdaltest.post_reason('fail') - return 'fail' + assert fc == 0 expected_cs = [0, 56451, 0, 0] got_cs = [ds.GetRasterBand(i + 1).Checksum() for i in range(4)] if got_cs != expected_cs: - gdaltest.post_reason('fail') - print('Got %s, expected %s' % (str(got_cs), str(expected_cs))) ds.GetRasterBand(4).Fill(255) # sys.exit(0) - return 'fail' + pytest.fail('Got %s, expected %s' % (str(got_cs), str(expected_cs))) ds = None # Overflow occurred in ComputeTileAndPixelShifts() with gdaltest.error_handler(): ds = gdal.OpenEx('/vsimem/tmp.gpkg', open_options=['MINX=-1e12', 'MAXX=-0.9999e12']) - if ds is not None: - gdaltest.post_reason('fail') - return 'fail' + assert ds is None # Overflow occurred in ComputeTileAndPixelShifts() with gdaltest.error_handler(): ds = gdal.OpenEx('/vsimem/tmp.gpkg', open_options=['MINY=-1e12', 'MAXY=-0.9999e12']) - if ds is not None: - gdaltest.post_reason('fail') - return 'fail' + assert ds is None # Overflow occurred in ComputeTileAndPixelShifts() gdal.Translate('/vsimem/tmp.gpkg', 'data/byte.tif', format='GPKG') @@ -1430,47 +1149,36 @@ def gpkg_14(): ds = None with gdaltest.error_handler(): ds = gdal.Open('/vsimem/tmp.gpkg') - if ds is not None: - gdaltest.post_reason('fail') - return 'fail' + assert ds is None gdal.Unlink('/vsimem/tmp.gpkg') - return 'success' ############################################################################### # Test error cases -def gpkg_15(): +def test_gpkg_15(): if gdaltest.gpkg_dr is None: - return 'skip' + pytest.skip() gdal.Unlink('/vsimem/tmp.gpkg') # SetGeoTransform() and SetProjection() on a non-raster GPKG out_ds = gdaltest.gpkg_dr.Create('/vsimem/tmp.gpkg', 0, 0, 0) - if out_ds.GetGeoTransform(can_return_null=True) is not None: - gdaltest.post_reason('fail') - return 'fail' - if out_ds.GetProjectionRef() != '': - gdaltest.post_reason('fail') - return 'fail' + assert out_ds.GetGeoTransform(can_return_null=True) is None + assert out_ds.GetProjectionRef() == '' gdal.PushErrorHandler() ret = out_ds.SetGeoTransform([0, 1, 0, 0, 0, -1]) gdal.PopErrorHandler() - if ret == 0: - gdaltest.post_reason('fail') - return 'fail' + assert ret != 0 srs = osr.SpatialReference() srs.ImportFromEPSG(4326) gdal.PushErrorHandler() ret = out_ds.SetProjection(srs.ExportToWkt()) gdal.PopErrorHandler() - if ret == 0: - gdaltest.post_reason('fail') - return 'fail' + assert ret != 0 out_ds = None gdal.Unlink('/vsimem/tmp.gpkg') @@ -1478,57 +1186,39 @@ def gpkg_15(): # Repeated SetGeoTransform() out_ds = gdaltest.gpkg_dr.Create('/vsimem/tmp.gpkg', 1, 1) ret = out_ds.SetGeoTransform([0, 1, 0, 0, 0, -1]) - if ret != 0: - gdaltest.post_reason('fail') - return 'fail' + assert ret == 0 gdal.PushErrorHandler() ret = out_ds.SetGeoTransform([0, 1, 0, 0, 0, -1]) gdal.PopErrorHandler() - if ret == 0: - gdaltest.post_reason('fail') - return 'fail' + assert ret != 0 out_ds = None # Repeated SetProjection() out_ds = gdal.Open('/vsimem/tmp.gpkg', gdal.GA_Update) - if out_ds.GetProjectionRef() != '': - gdaltest.post_reason('fail') - return 'fail' + assert out_ds.GetProjectionRef() == '' srs = osr.SpatialReference() srs.ImportFromEPSG(4326) ret = out_ds.SetProjection(srs.ExportToWkt()) - if ret != 0: - gdaltest.post_reason('fail') - return 'fail' - if out_ds.GetProjectionRef().find('4326') < 0: - gdaltest.post_reason('fail') - return 'fail' + assert ret == 0 + assert out_ds.GetProjectionRef().find('4326') >= 0 out_ds = None out_ds = gdal.Open('/vsimem/tmp.gpkg', gdal.GA_Update) - if out_ds.GetProjectionRef().find('4326') < 0: - gdaltest.post_reason('fail') - return 'fail' + assert out_ds.GetProjectionRef().find('4326') >= 0 out_ds.SetProjection('') out_ds = None out_ds = gdal.Open('/vsimem/tmp.gpkg') - if out_ds.GetProjectionRef() != '': - gdaltest.post_reason('fail') - return 'fail' + assert out_ds.GetProjectionRef() == '' # Test setting on read-only dataset gdal.PushErrorHandler() ret = out_ds.SetProjection('') gdal.PopErrorHandler() - if ret == 0: - gdaltest.post_reason('fail') - return 'fail' + assert ret != 0 gdal.PushErrorHandler() ret = out_ds.SetGeoTransform([0, 1, 0, 0, 0, -1]) gdal.PopErrorHandler() - if ret == 0: - gdaltest.post_reason('fail') - return 'fail' + assert ret != 0 out_ds = None gdal.Unlink('/vsimem/tmp.gpkg') @@ -1537,23 +1227,15 @@ def gpkg_15(): out_ds = gdaltest.gpkg_dr.Create('/vsimem/tmp.gpkg', 1, 1) out_ds.SetGeoTransform([0, 1, 0, 0, 0, -1]) ret = out_ds.GetRasterBand(1).SetColorInterpretation(gdal.GCI_Undefined) - if ret != 0: - gdaltest.post_reason('fail') - return 'fail' + assert ret == 0 ret = out_ds.GetRasterBand(1).SetColorInterpretation(gdal.GCI_GrayIndex) - if ret != 0: - gdaltest.post_reason('fail') - return 'fail' + assert ret == 0 ret = out_ds.GetRasterBand(1).SetColorInterpretation(gdal.GCI_PaletteIndex) - if ret != 0: - gdaltest.post_reason('fail') - return 'fail' + assert ret == 0 gdal.PushErrorHandler() ret = out_ds.GetRasterBand(1).SetColorInterpretation(gdal.GCI_RedBand) gdal.PopErrorHandler() - if ret == 0: - gdaltest.post_reason('fail') - return 'fail' + assert ret != 0 out_ds = None gdal.Unlink('/vsimem/tmp.gpkg') @@ -1561,15 +1243,11 @@ def gpkg_15(): out_ds = gdaltest.gpkg_dr.Create('/vsimem/tmp.gpkg', 1, 1, 3) out_ds.SetGeoTransform([0, 1, 0, 0, 0, -1]) ret = out_ds.GetRasterBand(1).SetColorInterpretation(gdal.GCI_RedBand) - if ret != 0: - gdaltest.post_reason('fail') - return 'fail' + assert ret == 0 gdal.PushErrorHandler() ret = out_ds.GetRasterBand(2).SetColorInterpretation(gdal.GCI_RedBand) gdal.PopErrorHandler() - if ret == 0: - gdaltest.post_reason('fail') - return 'fail' + assert ret != 0 out_ds = None gdal.Unlink('/vsimem/tmp.gpkg') @@ -1577,41 +1255,31 @@ def gpkg_15(): out_ds = gdaltest.gpkg_dr.Create('/vsimem/tmp.gpkg', 1, 1, 2) out_ds.SetGeoTransform([0, 1, 0, 0, 0, -1]) ret = out_ds.GetRasterBand(1).SetColorInterpretation(gdal.GCI_GrayIndex) - if ret != 0: - gdaltest.post_reason('fail') - return 'fail' + assert ret == 0 gdal.PushErrorHandler() ret = out_ds.GetRasterBand(1).SetColorInterpretation(gdal.GCI_RedBand) gdal.PopErrorHandler() - if ret == 0: - gdaltest.post_reason('fail') - return 'fail' + assert ret != 0 ret = out_ds.GetRasterBand(2).SetColorInterpretation(gdal.GCI_AlphaBand) - if ret != 0: - gdaltest.post_reason('fail') - return 'fail' + assert ret == 0 gdal.PushErrorHandler() ret = out_ds.GetRasterBand(2).SetColorInterpretation(gdal.GCI_RedBand) gdal.PopErrorHandler() - if ret == 0: - gdaltest.post_reason('fail') - return 'fail' + assert ret != 0 out_ds = None gdal.Unlink('/vsimem/tmp.gpkg') - return 'success' - ############################################################################### # Test block/tile caching -def gpkg_16(): +def test_gpkg_16(): if gdaltest.gpkg_dr is None: - return 'skip' + pytest.skip() if gdaltest.jpeg_dr is None: - return 'skip' + pytest.skip() gdal.Unlink('/vsimem/tmp.gpkg') @@ -1632,32 +1300,21 @@ def gpkg_16(): val3 = ord(out_ds.GetRasterBand(3).ReadRaster(0, 0, 1, 1)) out_ds = None - if abs(val1 - 255) > 1: - gdaltest.post_reason('fail') - print(val1) - return 'fail' - if abs(val2 - 127) > 1: - gdaltest.post_reason('fail') - print(val2) - return 'fail' - if abs(val3 - 0) > 1: - gdaltest.post_reason('fail') - print(val3) - return 'fail' + assert abs(val1 - 255) <= 1 + assert abs(val2 - 127) <= 1 + assert abs(val3 - 0) <= 1 gdal.Unlink('/vsimem/tmp.gpkg') - return 'success' - ############################################################################### # Test overviews with single band dataset -def gpkg_17(): +def test_gpkg_17(): if gdaltest.gpkg_dr is None: - return 'skip' + pytest.skip() if gdaltest.png_dr is None: - return 'skip' + pytest.skip() gdal.Unlink('/vsimem/tmp.gpkg') @@ -1668,21 +1325,13 @@ def gpkg_17(): out_ds = None ds = None - if not validate('/vsimem/tmp.gpkg'): - gdaltest.post_reason('validation failed') - return 'fail' + assert validate('/vsimem/tmp.gpkg'), 'validation failed' out_ds = gdal.Open('/vsimem/tmp.gpkg') got_cs = out_ds.GetRasterBand(1).GetOverview(0).Checksum() - if got_cs != 1087: - gdaltest.post_reason('fail') - print(got_cs) - return 'fail' - if check_tile_format(out_ds, 'PNG', 1, False, zoom_level=0) != 'success': - return 'fail' - if out_ds.GetRasterBand(1).GetOverview(0).GetColorTable() is not None: - gdaltest.post_reason('fail') - return 'fail' + assert got_cs == 1087 + check_tile_format(out_ds, 'PNG', 1, False, zoom_level=0) + assert out_ds.GetRasterBand(1).GetOverview(0).GetColorTable() is None out_ds = None gdal.Unlink('/vsimem/tmp.gpkg') @@ -1698,12 +1347,8 @@ def gpkg_17(): out_ds = gdal.Open('/vsimem/tmp.gpkg') got_cs = out_ds.GetRasterBand(1).GetOverview(0).Checksum() - if got_cs != 1087: - gdaltest.post_reason('fail') - print(got_cs) - return 'fail' - if check_tile_format(out_ds, 'PNG', 1, False, zoom_level=0) != 'success': - return 'fail' + assert got_cs == 1087 + check_tile_format(out_ds, 'PNG', 1, False, zoom_level=0) out_ds = None gdal.Unlink('/vsimem/tmp.gpkg') @@ -1719,19 +1364,13 @@ def gpkg_17(): out_ds = gdal.Open('/vsimem/tmp.gpkg') got_cs = out_ds.GetRasterBand(1).GetOverview(0).Checksum() - if got_cs != 1087: - gdaltest.post_reason('fail') - print(got_cs) - return 'fail' - if check_tile_format(out_ds, 'PNG', 3, False, zoom_level=0) != 'success': - return 'fail' + assert got_cs == 1087 + check_tile_format(out_ds, 'PNG', 3, False, zoom_level=0) # Check that there's no extensions out_ds = gdal.Open('/vsimem/tmp.gpkg') sql_lyr = out_ds.ExecuteSQL("SELECT * FROM sqlite_master WHERE type = 'table' AND name = 'gpkg_extensions'") - if sql_lyr.GetFeatureCount() != 0: - gdaltest.post_reason('fail') - return 'fail' + assert sql_lyr.GetFeatureCount() == 0 out_ds.ReleaseResultSet(sql_lyr) out_ds = None @@ -1741,9 +1380,7 @@ def gpkg_17(): out_ds.BuildOverviews('NONE', []) out_ds = None out_ds = gdal.Open('/vsimem/tmp.gpkg') - if out_ds.GetRasterBand(1).GetOverviewCount() != 0: - gdaltest.post_reason('fail') - return 'fail' + assert out_ds.GetRasterBand(1).GetOverviewCount() == 0 out_ds = None # Test building on an overview dataset --> error @@ -1751,9 +1388,7 @@ def gpkg_17(): gdal.PushErrorHandler() ret = out_ds.GetRasterBand(1).GetOverview(0).GetDataset().BuildOverviews('NONE', []) gdal.PopErrorHandler() - if ret == 0: - gdaltest.post_reason('fail') - return 'fail' + assert ret != 0 out_ds = None # Test building overview factor 1 --> error @@ -1761,9 +1396,7 @@ def gpkg_17(): gdal.PushErrorHandler() ret = out_ds.BuildOverviews('NEAR', [1]) gdal.PopErrorHandler() - if ret == 0: - gdaltest.post_reason('fail') - return 'fail' + assert ret != 0 out_ds = None # Test building non-supported overview levels @@ -1773,9 +1406,7 @@ def gpkg_17(): ret = out_ds.BuildOverviews('NEAR', [3]) gdal.SetConfigOption('ALLOW_GPKG_ZOOM_OTHER_EXTENSION', None) gdal.PopErrorHandler() - if ret == 0: - gdaltest.post_reason('fail') - return 'fail' + assert ret != 0 out_ds = None # Test building non-supported overview levels @@ -1785,9 +1416,7 @@ def gpkg_17(): ret = out_ds.BuildOverviews('NEAR', [2, 4]) gdal.SetConfigOption('ALLOW_GPKG_ZOOM_OTHER_EXTENSION', None) gdal.PopErrorHandler() - if ret == 0: - gdaltest.post_reason('fail') - return 'fail' + assert ret != 0 out_ds = None # Test gpkg_zoom_other extension @@ -1796,9 +1425,7 @@ def gpkg_17(): gdal.PushErrorHandler() ret = out_ds.BuildOverviews('NEAR', [3]) gdal.PopErrorHandler() - if ret == 0: - gdaltest.post_reason('fail') - return 'fail' + assert ret != 0 out_ds = None # Test building overviews on read-only dataset @@ -1806,25 +1433,21 @@ def gpkg_17(): gdal.PushErrorHandler() ret = out_ds.BuildOverviews('NEAR', [2]) gdal.PopErrorHandler() - if ret == 0: - gdaltest.post_reason('fail') - return 'fail' + assert ret != 0 out_ds = None gdal.Unlink('/vsimem/tmp.gpkg') - return 'success' - ############################################################################### # Test overviews with 3 band dataset -def gpkg_18(): +def test_gpkg_18(): if gdaltest.gpkg_dr is None: - return 'skip' + pytest.skip() if gdaltest.png_dr is None: - return 'skip' + pytest.skip() gdal.Unlink('/vsimem/tmp.gpkg') # Without padding, immediately after create copy @@ -1846,21 +1469,11 @@ def gpkg_18(): out_ds = gdal.Open('/vsimem/tmp.gpkg') got_cs = [out_ds.GetRasterBand(i + 1).GetOverview(0).Checksum() for i in range(3)] - if got_cs != expected_cs_ov0: - gdaltest.post_reason('fail') - print(got_cs) - print(expected_cs_ov0) - return 'fail' + assert got_cs == expected_cs_ov0 got_cs = [out_ds.GetRasterBand(i + 1).GetOverview(1).Checksum() for i in range(3)] - if got_cs != expected_cs_ov1: - gdaltest.post_reason('fail') - print(got_cs) - print(expected_cs_ov1) - return 'fail' - if check_tile_format(out_ds, 'PNG', 3, False, zoom_level=1) != 'success': - return 'fail' - if check_tile_format(out_ds, 'PNG', 4, False, zoom_level=0) != 'success': - return 'fail' + assert got_cs == expected_cs_ov1 + check_tile_format(out_ds, 'PNG', 3, False, zoom_level=1) + check_tile_format(out_ds, 'PNG', 4, False, zoom_level=0) out_ds = None # Test gpkg_zoom_other extension @@ -1869,79 +1482,41 @@ def gpkg_18(): gdal.PushErrorHandler() ret = out_ds.BuildOverviews('NEAR', [3]) gdal.PopErrorHandler() - if ret != 0: - gdaltest.post_reason('fail') - return 'fail' - if out_ds.GetRasterBand(1).GetOverviewCount() != 3: - gdaltest.post_reason('fail') - return 'fail' + assert ret == 0 + assert out_ds.GetRasterBand(1).GetOverviewCount() == 3 got_cs = [out_ds.GetRasterBand(i + 1).GetOverview(0).Checksum() for i in range(3)] - if got_cs != expected_cs_ov0: - gdaltest.post_reason('fail') - print(got_cs) - print(expected_cs_ov0) - return 'fail' + assert got_cs == expected_cs_ov0 expected_cs = [24807, 25544, 34002] got_cs = [out_ds.GetRasterBand(i + 1).GetOverview(1).Checksum() for i in range(3)] - if got_cs != expected_cs: - gdaltest.post_reason('fail') - print(got_cs) - print(expected_cs) - return 'fail' + assert got_cs == expected_cs got_cs = [out_ds.GetRasterBand(i + 1).GetOverview(2).Checksum() for i in range(3)] - if got_cs != expected_cs_ov1: - gdaltest.post_reason('fail') - print(got_cs) - print(expected_cs_ov1) - return 'fail' + assert got_cs == expected_cs_ov1 # Check that extension is declared sql_lyr = out_ds.ExecuteSQL("SELECT * FROM gpkg_extensions WHERE table_name = 'tmp' AND extension_name = 'gpkg_zoom_other'") - if sql_lyr.GetFeatureCount() != 1: - gdaltest.post_reason('fail') - return 'fail' + assert sql_lyr.GetFeatureCount() == 1 out_ds.ReleaseResultSet(sql_lyr) out_ds = None out_ds = gdal.Open('/vsimem/tmp.gpkg') - if out_ds.GetRasterBand(1).GetOverviewCount() != 3: - gdaltest.post_reason('fail') - return 'fail' + assert out_ds.GetRasterBand(1).GetOverviewCount() == 3 got_cs = [out_ds.GetRasterBand(i + 1).GetOverview(0).Checksum() for i in range(3)] - if got_cs != expected_cs_ov0: - gdaltest.post_reason('fail') - print(got_cs) - print(expected_cs_ov0) - return 'fail' + assert got_cs == expected_cs_ov0 expected_cs = [24807, 25544, 34002] got_cs = [out_ds.GetRasterBand(i + 1).GetOverview(1).Checksum() for i in range(3)] - if got_cs != expected_cs: - gdaltest.post_reason('fail') - print(got_cs) - print(expected_cs) - return 'fail' + assert got_cs == expected_cs got_cs = [out_ds.GetRasterBand(i + 1).GetOverview(2).Checksum() for i in range(3)] - if got_cs != expected_cs_ov1: - gdaltest.post_reason('fail') - print(got_cs) - print(expected_cs_ov1) - return 'fail' + assert got_cs == expected_cs_ov1 out_ds = None # Add terminating overview out_ds = gdal.OpenEx('/vsimem/tmp.gpkg', gdal.OF_RASTER | gdal.OF_UPDATE) ret = out_ds.BuildOverviews('NEAR', [8]) - if ret != 0: - gdaltest.post_reason('fail') - return 'fail' + assert ret == 0 expected_cs = [12725, 12539, 13553] got_cs = [out_ds.GetRasterBand(i + 1).GetOverview(3).Checksum() for i in range(3)] - if got_cs != expected_cs: - gdaltest.post_reason('fail') - print(got_cs) - print(expected_cs) - return 'fail' + assert got_cs == expected_cs out_ds = None gdal.Unlink('/vsimem/tmp.gpkg') @@ -1952,34 +1527,28 @@ def gpkg_18(): out_ds = gdaltest.gpkg_dr.CreateCopy('/vsimem/tmp.gpkg', ds, options=['TILE_FORMAT=PNG', 'BLOCKXSIZE=100', 'BLOCKYSIZE=100']) # Should not result in gpkg_zoom_other ret = out_ds.BuildOverviews('NEAR', [8]) - if ret != 0: - gdaltest.post_reason('fail') - return 'fail' + assert ret == 0 out_ds = None # Check that there's no extensions out_ds = gdal.Open('/vsimem/tmp.gpkg') sql_lyr = out_ds.ExecuteSQL("SELECT * FROM sqlite_master WHERE type = 'table' AND name = 'gpkg_extensions'") - if sql_lyr.GetFeatureCount() != 0: - gdaltest.post_reason('fail') - return 'fail' + assert sql_lyr.GetFeatureCount() == 0 out_ds.ReleaseResultSet(sql_lyr) out_ds = None gdal.Unlink('/vsimem/tmp.gpkg') - return 'success' - ############################################################################### # Test overviews with 24-bit color palette single band dataset -def gpkg_19(): +def test_gpkg_19(): if gdaltest.gpkg_dr is None: - return 'skip' + pytest.skip() if gdaltest.png_dr is None: - return 'skip' + pytest.skip() gdal.Unlink('/vsimem/tmp.gpkg') @@ -1999,40 +1568,26 @@ def gpkg_19(): ds = None out_ds = gdal.OpenEx('/vsimem/tmp.gpkg', gdal.OF_RASTER, open_options=['BAND_COUNT=1']) - if out_ds.GetRasterBand(1).GetOverview(0).GetColorTable() is None: - gdaltest.post_reason('fail') - return 'fail' + assert out_ds.GetRasterBand(1).GetOverview(0).GetColorTable() is not None got_cs = [out_ds.GetRasterBand(i + 1).GetOverview(0).Checksum() for i in range(1)] - if got_cs != expected_cs_ov0: - gdaltest.post_reason('fail') - print(got_cs) - print(expected_cs_ov0) - return 'fail' + assert got_cs == expected_cs_ov0 got_cs = [out_ds.GetRasterBand(i + 1).GetOverview(1).Checksum() for i in range(1)] - if got_cs != expected_cs_ov1: - gdaltest.post_reason('fail') - print(got_cs) - print(expected_cs_ov1) - return 'fail' - if check_tile_format(out_ds, 'PNG', 1, True, zoom_level=1) != 'success': - return 'fail' - if check_tile_format(out_ds, 'PNG', 4, False, zoom_level=0) != 'success': - return 'fail' + assert got_cs == expected_cs_ov1 + check_tile_format(out_ds, 'PNG', 1, True, zoom_level=1) + check_tile_format(out_ds, 'PNG', 4, False, zoom_level=0) out_ds = None gdal.Unlink('/vsimem/tmp.gpkg') - return 'success' - ############################################################################### # Test PNG8 -def gpkg_20(): +def test_gpkg_20(): if gdaltest.gpkg_dr is None: - return 'skip' + pytest.skip() if gdaltest.png_dr is None: - return 'skip' + pytest.skip() gdal.Unlink('/vsimem/tmp.gpkg') @@ -2045,13 +1600,8 @@ def gpkg_20(): out_ds = gdal.OpenEx('/vsimem/tmp.gpkg', gdal.OF_RASTER) got_cs = [out_ds.GetRasterBand(i + 1).Checksum() for i in range(4)] expected_cs = [30875, 31451, 38110, 64269] - if got_cs != expected_cs: - gdaltest.post_reason('fail') - print(got_cs) - print(expected_cs) - return 'fail' - if check_tile_format(out_ds, 'PNG', 1, True) != 'success': - return 'fail' + assert got_cs == expected_cs + check_tile_format(out_ds, 'PNG', 1, True) out_ds = None gdal.Unlink('/vsimem/tmp.gpkg') @@ -2064,13 +1614,8 @@ def gpkg_20(): out_ds = gdal.OpenEx('/vsimem/tmp.gpkg', gdal.OF_RASTER) got_cs = [out_ds.GetRasterBand(i + 1).Checksum() for i in range(4)] expected_cs = [27001, 30168, 34800, 64269] - if got_cs != expected_cs: - gdaltest.post_reason('fail') - print(got_cs) - print(expected_cs) - return 'fail' - if check_tile_format(out_ds, 'PNG', 1, True) != 'success': - return 'fail' + assert got_cs == expected_cs + check_tile_format(out_ds, 'PNG', 1, True) out_ds = None gdal.Unlink('/vsimem/tmp.gpkg') @@ -2083,15 +1628,9 @@ def gpkg_20(): out_ds = gdal.OpenEx('/vsimem/tmp.gpkg', gdal.OF_RASTER) got_cs = [out_ds.GetRasterBand(i + 1).Checksum() for i in range(4)] expected_cs = [27718, 31528, 42062, 64269] - if got_cs != expected_cs: - gdaltest.post_reason('fail') - print(got_cs) - print(expected_cs) - return 'fail' - if check_tile_format(out_ds, 'PNG', 1, True) != 'success': - return 'fail' - if check_tile_format(out_ds, 'PNG', 4, False, row=0, col=2) != 'success': - return 'fail' + assert got_cs == expected_cs + check_tile_format(out_ds, 'PNG', 1, True) + check_tile_format(out_ds, 'PNG', 4, False, row=0, col=2) out_ds = None gdal.Unlink('/vsimem/tmp.gpkg') @@ -2109,43 +1648,31 @@ def gpkg_20(): out_ds = gdal.OpenEx('/vsimem/tmp.gpkg', gdal.OF_RASTER) got_cs = [out_ds.GetRasterBand(i + 1).Checksum() for i in range(4)] expected_cs = [2500, 5000, 7500, 30658] - if got_cs != expected_cs: - gdaltest.post_reason('fail') - print(got_cs) - print(expected_cs) - return 'fail' - if check_tile_format(out_ds, 'PNG', 1, True) != 'success': - return 'fail' + assert got_cs == expected_cs + check_tile_format(out_ds, 'PNG', 1, True) out_ds = None out_ds = gdal.OpenEx('/vsimem/tmp.gpkg', gdal.OF_RASTER, open_options=['BAND_COUNT=1']) - if out_ds.GetRasterBand(1).GetColorTable().GetCount() != 1: - gdaltest.post_reason('fail') - return 'fail' + assert out_ds.GetRasterBand(1).GetColorTable().GetCount() == 1 out_ds = None gdal.Unlink('/vsimem/tmp.gpkg') - return 'success' - ############################################################################### # Test metadata -def gpkg_21(): +def test_gpkg_21(): if gdaltest.gpkg_dr is None: - return 'skip' + pytest.skip() if gdaltest.png_dr is None: - return 'skip' + pytest.skip() gdal.Unlink('/vsimem/tmp.gpkg') out_ds = gdaltest.gpkg_dr.Create('/vsimem/tmp.gpkg', 1, 1) out_ds.SetGeoTransform([0, 1, 0, 0, 0, -1]) mddlist = out_ds.GetMetadataDomainList() - if len(mddlist) != 3: - gdaltest.post_reason('fail') - print(mddlist) - return 'fail' + assert len(mddlist) == 3 out_ds = None out_ds = gdal.Open('/vsimem/tmp.gpkg', gdal.GA_Update) @@ -2155,9 +1682,7 @@ def gpkg_21(): feat = sql_lyr.GetNextFeature() out_ds.ReleaseResultSet(sql_lyr) feat_is_none = feat is None - if not feat_is_none: - gdaltest.post_reason('fail') - return 'fail' + assert feat_is_none # Set a metadata item now out_ds.SetMetadataItem('foo', 'bar') @@ -2168,21 +1693,15 @@ def gpkg_21(): out_ds = gdal.Open('/vsimem/tmp.gpkg', gdal.GA_Update) - if out_ds.GetMetadata('GEOPACKAGE'): - gdaltest.post_reason('fail') - return 'fail' + assert not out_ds.GetMetadata('GEOPACKAGE') if out_ds.GetMetadataItem('foo') != foo_value: - gdaltest.post_reason('fail') - print(out_ds.GetMetadataItem('foo')) feat.DumpReadable() - return 'fail' + pytest.fail(out_ds.GetMetadataItem('foo')) md = out_ds.GetMetadata() if len(md) != 3 or md['foo'] != foo_value or \ md['IDENTIFIER'] != 'tmp' or md['ZOOM_LEVEL'] != '0': - gdaltest.post_reason('fail') - print(md) feat.DumpReadable() - return 'fail' + pytest.fail(md) sql_lyr = out_ds.ExecuteSQL('SELECT * FROM gpkg_metadata') feat = sql_lyr.GetNextFeature() @@ -2195,10 +1714,8 @@ def gpkg_21(): </Metadata> </GDALMultiDomainMetadata> """ % foo_value: - gdaltest.post_reason('fail') - print(i) feat.DumpReadable() - return 'fail' + pytest.fail(i) out_ds.ReleaseResultSet(sql_lyr) sql_lyr = out_ds.ExecuteSQL('SELECT * FROM gpkg_metadata_reference') @@ -2210,10 +1727,8 @@ def gpkg_21(): not feat.IsFieldSet('timestamp') or \ feat.GetField('md_file_id') != 1 or \ not feat.IsFieldNull('md_parent_id'): - gdaltest.post_reason('fail') - print(i) feat.DumpReadable() - return 'fail' + pytest.fail(i) out_ds.ReleaseResultSet(sql_lyr) if i == 1: @@ -2234,18 +1749,16 @@ def gpkg_21(): sql_lyr = out_ds.ExecuteSQL('SELECT * FROM gpkg_metadata') feat = sql_lyr.GetNextFeature() if feat is not None: - gdaltest.post_reason('fail') feat.DumpReadable() out_ds.ReleaseResultSet(sql_lyr) - return 'fail' + pytest.fail() out_ds.ReleaseResultSet(sql_lyr) sql_lyr = out_ds.ExecuteSQL('SELECT * FROM gpkg_metadata_reference') feat = sql_lyr.GetNextFeature() if feat is not None: - gdaltest.post_reason('fail') feat.DumpReadable() out_ds.ReleaseResultSet(sql_lyr) - return 'fail' + pytest.fail() out_ds.ReleaseResultSet(sql_lyr) out_ds.SetMetadataItem('IDENTIFIER', 'my_identifier') @@ -2254,27 +1767,21 @@ def gpkg_21(): # Still no metadata out_ds = gdal.Open('/vsimem/tmp.gpkg', gdal.GA_Update) - if out_ds.GetMetadataItem('IDENTIFIER') != 'my_identifier': - gdaltest.post_reason('fail') - return 'fail' - if out_ds.GetMetadataItem('DESCRIPTION') != 'my_description': - gdaltest.post_reason('fail') - return 'fail' + assert out_ds.GetMetadataItem('IDENTIFIER') == 'my_identifier' + assert out_ds.GetMetadataItem('DESCRIPTION') == 'my_description' sql_lyr = out_ds.ExecuteSQL('SELECT * FROM gpkg_metadata') feat = sql_lyr.GetNextFeature() if feat is not None: - gdaltest.post_reason('fail') feat.DumpReadable() out_ds.ReleaseResultSet(sql_lyr) - return 'fail' + pytest.fail() out_ds.ReleaseResultSet(sql_lyr) sql_lyr = out_ds.ExecuteSQL('SELECT * FROM gpkg_metadata_reference') feat = sql_lyr.GetNextFeature() if feat is not None: - gdaltest.post_reason('fail') feat.DumpReadable() out_ds.ReleaseResultSet(sql_lyr) - return 'fail' + pytest.fail() out_ds.ReleaseResultSet(sql_lyr) # Write metadata in global scope @@ -2284,9 +1791,7 @@ def gpkg_21(): out_ds = gdal.Open('/vsimem/tmp.gpkg', gdal.GA_Update) - if out_ds.GetMetadataItem('bar', 'GEOPACKAGE') != 'foo': - gdaltest.post_reason('fail') - return 'fail' + assert out_ds.GetMetadataItem('bar', 'GEOPACKAGE') == 'foo' sql_lyr = out_ds.ExecuteSQL('SELECT * FROM gpkg_metadata') feat = sql_lyr.GetNextFeature() @@ -2299,10 +1804,9 @@ def gpkg_21(): </Metadata> </GDALMultiDomainMetadata> """: - gdaltest.post_reason('fail') feat.DumpReadable() out_ds.ReleaseResultSet(sql_lyr) - return 'fail' + pytest.fail() out_ds.ReleaseResultSet(sql_lyr) sql_lyr = out_ds.ExecuteSQL('SELECT * FROM gpkg_metadata_reference') @@ -2314,26 +1818,21 @@ def gpkg_21(): not feat.IsFieldSet('timestamp') or \ feat.GetField('md_file_id') != 1 or \ not feat.IsFieldNull('md_parent_id'): - gdaltest.post_reason('fail') feat.DumpReadable() out_ds.ReleaseResultSet(sql_lyr) - return 'fail' + pytest.fail() out_ds.ReleaseResultSet(sql_lyr) out_ds.SetMetadataItem('bar', 'baz', 'GEOPACKAGE') out_ds = None out_ds = gdal.Open('/vsimem/tmp.gpkg', gdal.GA_Update) - if out_ds.GetMetadataItem('bar', 'GEOPACKAGE') != 'baz': - gdaltest.post_reason('fail') - return 'fail' + assert out_ds.GetMetadataItem('bar', 'GEOPACKAGE') == 'baz' out_ds.SetMetadata(None, 'GEOPACKAGE') out_ds = None out_ds = gdal.Open('/vsimem/tmp.gpkg', gdal.GA_Update) - if out_ds.GetMetadata('GEOPACKAGE'): - gdaltest.post_reason('fail') - return 'fail' + assert not out_ds.GetMetadata('GEOPACKAGE') out_ds.SetMetadataItem('1', '2') out_ds.SetMetadataItem('3', '4', 'CUSTOM_DOMAIN') @@ -2351,31 +1850,17 @@ def gpkg_21(): for i in range(2): out_ds = gdal.Open('/vsimem/tmp.gpkg', gdal.GA_Update) - if out_ds.GetMetadataItem('1') != '2': - gdaltest.post_reason('fail') - return 'fail' - if out_ds.GetMetadataItem('GPKG_METADATA_ITEM_1') != 'my_metadata_local': - gdaltest.post_reason('fail') - print(out_ds.GetMetadata()) - return 'fail' - if out_ds.GetMetadataItem('GPKG_METADATA_ITEM_2') != 'other_metadata_local': - gdaltest.post_reason('fail') - print(out_ds.GetMetadata()) - return 'fail' - if out_ds.GetMetadataItem('GPKG_METADATA_ITEM_1', 'GEOPACKAGE') != 'my_metadata': - gdaltest.post_reason('fail') - print(out_ds.GetMetadata('GEOPACKAGE')) - return 'fail' - if out_ds.GetMetadataItem('GPKG_METADATA_ITEM_2', 'GEOPACKAGE') != 'other_metadata': - gdaltest.post_reason('fail') - print(out_ds.GetMetadata('GEOPACKAGE')) - return 'fail' - if out_ds.GetMetadataItem('3', 'CUSTOM_DOMAIN') != '4': - gdaltest.post_reason('fail') - return 'fail' - if out_ds.GetMetadataItem('6', 'GEOPACKAGE') != '7': - gdaltest.post_reason('fail') - return 'fail' + assert out_ds.GetMetadataItem('1') == '2' + assert out_ds.GetMetadataItem('GPKG_METADATA_ITEM_1') == 'my_metadata_local', \ + out_ds.GetMetadata() + assert out_ds.GetMetadataItem('GPKG_METADATA_ITEM_2') == 'other_metadata_local', \ + out_ds.GetMetadata() + assert out_ds.GetMetadataItem('GPKG_METADATA_ITEM_1', 'GEOPACKAGE') == 'my_metadata', \ + out_ds.GetMetadata('GEOPACKAGE') + assert out_ds.GetMetadataItem('GPKG_METADATA_ITEM_2', 'GEOPACKAGE') == 'other_metadata', \ + out_ds.GetMetadata('GEOPACKAGE') + assert out_ds.GetMetadataItem('3', 'CUSTOM_DOMAIN') == '4' + assert out_ds.GetMetadataItem('6', 'GEOPACKAGE') == '7' out_ds.SetMetadata(out_ds.GetMetadata()) out_ds.SetMetadata(out_ds.GetMetadata('GEOPACKAGE'), 'GEOPACKAGE') out_ds = None @@ -2387,32 +1872,26 @@ def gpkg_21(): out_ds = None out_ds = gdal.Open('/vsimem/tmp.gpkg', gdal.GA_Update) - if out_ds.GetMetadataItem('GPKG_METADATA_ITEM_1', 'GEOPACKAGE') != 'my_metadata': - gdaltest.post_reason('fail') - print(out_ds.GetMetadata()) - return 'fail' + assert out_ds.GetMetadataItem('GPKG_METADATA_ITEM_1', 'GEOPACKAGE') == 'my_metadata', \ + out_ds.GetMetadata() sql_lyr = out_ds.ExecuteSQL('SELECT * FROM gpkg_metadata WHERE id < 10') feat = sql_lyr.GetNextFeature() if feat is not None: - gdaltest.post_reason('fail') feat.DumpReadable() out_ds.ReleaseResultSet(sql_lyr) - return 'fail' + pytest.fail() out_ds.ReleaseResultSet(sql_lyr) sql_lyr = out_ds.ExecuteSQL('SELECT * FROM gpkg_metadata_reference WHERE md_file_id < 10') feat = sql_lyr.GetNextFeature() if feat is not None: - gdaltest.post_reason('fail') feat.DumpReadable() out_ds.ReleaseResultSet(sql_lyr) - return 'fail' + pytest.fail() out_ds.ReleaseResultSet(sql_lyr) out_ds = None gdal.Unlink('/vsimem/tmp.gpkg') - return 'success' - ############################################################################### # Two band, PNG @@ -2427,14 +1906,14 @@ def get_georeferenced_greyalpha_ds(): return tmp_ds -def gpkg_22(tile_drv_name='PNG'): +def test_gpkg_22(tile_drv_name='PNG'): if gdaltest.gpkg_dr is None: - return 'skip' + pytest.skip() if tile_drv_name is None: tile_drv = gdaltest.png_dr if gdaltest.jpeg_dr is None: - return 'skip' + pytest.skip() expected_cs = [2466, 10807] clamped_expected_cs = [1989, 1989, 1989, 11580] if tile_drv_name == 'PNG': @@ -2454,7 +1933,7 @@ def gpkg_22(tile_drv_name='PNG'): expected_cs = [13112, 32706] clamped_expected_cs = [13380, 13380, 13380, 32744] if tile_drv is None: - return 'skip' + pytest.skip() gdal.Unlink('/vsimem/tmp.gpkg') @@ -2472,66 +1951,55 @@ def gpkg_22(tile_drv_name='PNG'): out_ds = gdal.OpenEx('/vsimem/tmp.gpkg', open_options=['BAND_COUNT=2']) got_cs = [out_ds.GetRasterBand(i + 1).Checksum() for i in range(2)] if got_cs != expected_cs: - if tile_drv_name != 'WEBP' or got_cs not in ([4899, 10807], [6274, 10807], [17638, 10807]): - gdaltest.post_reason('fail') - print('Got %s, expected %s' % (str(got_cs), str(expected_cs))) - return 'fail' + assert tile_drv_name == 'WEBP' and got_cs in ([4899, 10807], [6274, 10807], [17638, 10807]) out_ds = None out_ds = gdal.Open('/vsimem/tmp.gpkg') got_cs = [out_ds.GetRasterBand(i + 1).Checksum() for i in range(4)] expected_cs = [expected_cs[0], expected_cs[0], expected_cs[0], expected_cs[1]] if got_cs != expected_cs: - if tile_drv_name != 'WEBP' or got_cs not in ([4899, 4899, 4899, 10807], [4899, 4984, 4899, 10807], [6274, 6274, 6274, 10807], [17638, 17631, 17638, 10807]): - gdaltest.post_reason('fail') - print('Got %s, expected %s' % (str(got_cs), str(expected_cs))) - return 'fail' + assert tile_drv_name == 'WEBP' and got_cs in ([4899, 4899, 4899, 10807], [4899, 4984, 4899, 10807], [6274, 6274, 6274, 10807], [17638, 17631, 17638, 10807]) out_ds = None ds = gdal.OpenEx('/vsimem/tmp.gpkg', open_options=['USE_TILE_EXTENT=YES']) got_cs = [ds.GetRasterBand(i + 1).Checksum() for i in range(4)] if got_cs != clamped_expected_cs: - if tile_drv_name != 'WEBP' or got_cs not in ([5266, 5266, 5266, 11580], [5266, 5310, 5266, 11580], [6436, 6436, 6436, 11580], [17007, 17000, 17007, 11580]): - gdaltest.post_reason('fail') - print('Got %s, expected %s' % (str(got_cs), str(clamped_expected_cs))) - return 'fail' + assert tile_drv_name == 'WEBP' and got_cs in ([5266, 5266, 5266, 11580], [5266, 5310, 5266, 11580], [6436, 6436, 6436, 11580], [17007, 17000, 17007, 11580]) ds = None gdal.Unlink('/vsimem/tmp.gpkg') - return 'success' - ############################################################################### # Two band, JPEG -def gpkg_23(): - return gpkg_22(tile_drv_name='JPEG') +def test_gpkg_23(): + return test_gpkg_22(tile_drv_name='JPEG') ############################################################################### # Two band, WEBP -def gpkg_24(): - return gpkg_22(tile_drv_name='WEBP') +def test_gpkg_24(): + return test_gpkg_22(tile_drv_name='WEBP') ############################################################################### # Two band, mixed -def gpkg_25(): - return gpkg_22(tile_drv_name=None) +def test_gpkg_25(): + return test_gpkg_22(tile_drv_name=None) ############################################################################### # Test TILING_SCHEME -def gpkg_26(): +def test_gpkg_26(): if gdaltest.gpkg_dr is None: - return 'skip' + pytest.skip() if gdaltest.png_dr is None: - return 'skip' + pytest.skip() gdal.Unlink('/vsimem/tmp.gpkg') @@ -2556,17 +2024,13 @@ def gpkg_26(): ds = None ds = gdal.Open('/vsimem/tmp.gpkg') - if ds.GetMetadataItem('AREA_OR_POINT') != 'Area': - gdaltest.post_reason('fail') - return 'fail' + assert ds.GetMetadataItem('AREA_OR_POINT') == 'Area' got_cs = [ds.GetRasterBand(i + 1).Checksum() for i in range(4)] # VC12 returns [3561, 3561, 3561, 3691] for GoogleCRS84Quad # and For GoogleCRS84Quad RESAMPLING=CUBIC, got [3415, 3415, 3415, 3691] if max([abs(got_cs[i] - expected_cs[i]) for i in range(4)]) > 2: - gdaltest.post_reason('fail') print('For %s, got %s, expected %s' % (scheme, str(got_cs), str(expected_cs))) - if gdal.GetConfigOption('APPVEYOR') is None: - return 'fail' + assert gdal.GetConfigOption('APPVEYOR') is not None ds = None gdal.Unlink('/vsimem/tmp.gpkg') @@ -2586,10 +2050,8 @@ def gpkg_26(): ds = gdal.Open('/vsimem/tmp.gpkg') got_cs = [ds.GetRasterBand(i + 1).Checksum() for i in range(4)] if got_cs not in expected_cs: - gdaltest.post_reason('fail') print('For %s, got %s, expected %s' % (scheme, str(got_cs), str(expected_cs))) - if gdal.GetConfigOption('APPVEYOR') is None: - return 'fail' + assert gdal.GetConfigOption('APPVEYOR') is not None ds = None gdal.Unlink('/vsimem/tmp.gpkg') @@ -2598,30 +2060,22 @@ def gpkg_26(): gdal.PushErrorHandler() ds = gdaltest.gpkg_dr.Create('/vsimem/tmp.gpkg', 1, 1, 1, options=['TILING_SCHEME=GoogleCRS84Quad', 'BLOCKSIZE=128']) gdal.PopErrorHandler() - if ds is not None: - gdaltest.post_reason('fail') - return 'fail' + assert ds is None gdal.Unlink('/vsimem/tmp.gpkg') ds = gdaltest.gpkg_dr.Create('/vsimem/tmp.gpkg', 1, 1, 1, options=['TILING_SCHEME=GoogleCRS84Quad']) # Test that implicit SRS registration works. - if ds.GetProjectionRef().find('4326') < 0: - gdaltest.post_reason('fail') - return 'fail' + assert ds.GetProjectionRef().find('4326') >= 0 gdal.PushErrorHandler() ret = ds.SetGeoTransform([0, 10, 0, 0, 0, -10]) gdal.PopErrorHandler() - if ret == 0: - gdaltest.post_reason('fail') - return 'fail' + assert ret != 0 srs = osr.SpatialReference() srs.ImportFromEPSG(32630) gdal.PushErrorHandler() ret = ds.SetProjection(srs.ExportToWkt()) gdal.PopErrorHandler() - if ret == 0: - gdaltest.post_reason('fail') - return 'fail' + assert ret != 0 gdal.PushErrorHandler() ds = None gdal.PopErrorHandler() @@ -2633,40 +2087,32 @@ def gpkg_26(): gdal.PushErrorHandler() ds = gdaltest.gpkg_dr.CreateCopy('/foo/tmp.gpkg', src_ds, options=['TILING_SCHEME=invalid']) gdal.PopErrorHandler() - if ds is not None: - gdaltest.post_reason('fail') - return 'fail' + assert ds is None # Invalid target filename src_ds = gdal.Open('data/byte.tif') gdal.PushErrorHandler() ds = gdaltest.gpkg_dr.CreateCopy('/foo/tmp.gpkg', src_ds, options=['TILING_SCHEME=GoogleCRS84Quad']) gdal.PopErrorHandler() - if ds is not None: - gdaltest.post_reason('fail') - return 'fail' + assert ds is None # Source is not georeferenced src_ds = gdal.Open('../gcore/data/stefan_full_rgba.tif') gdal.PushErrorHandler() ds = gdaltest.gpkg_dr.CreateCopy('/vsimem/tmp.gpkg', src_ds, options=['TILING_SCHEME=GoogleCRS84Quad']) gdal.PopErrorHandler() - if ds is not None: - gdaltest.post_reason('fail') - return 'fail' - - return 'success' + assert ds is None ############################################################################### # Test behaviour with low block cache max -def gpkg_27(): +def test_gpkg_27(): if gdaltest.gpkg_dr is None: - return 'skip' + pytest.skip() if gdaltest.png_dr is None: - return 'skip' + pytest.skip() gdal.Unlink('/vsimem/tmp.gpkg') @@ -2678,24 +2124,19 @@ def gpkg_27(): expected_cs = [src_ds.GetRasterBand(i + 1).Checksum() for i in range(3)] got_cs = [out_ds.GetRasterBand(i + 1).Checksum() for i in range(3)] - if got_cs != expected_cs: - gdaltest.post_reason('fail') - print('Got %s, expected %s' % (str(got_cs), str(expected_cs))) - return 'fail' - - return 'success' + assert got_cs == expected_cs ############################################################################### # Test that reading a block in a band doesn't wipe another band of the same # block that would have gone through the GPKG in-memory cache -def gpkg_28(): +def test_gpkg_28(): if gdaltest.gpkg_dr is None: - return 'skip' + pytest.skip() if gdaltest.png_dr is None: - return 'skip' + pytest.skip() gdal.Unlink('/vsimem/tmp.gpkg') @@ -2722,23 +2163,18 @@ def gpkg_28(): out_ds = None out_ds = gdal.OpenEx('/vsimem/tmp.gpkg', open_options=['BAND_COUNT=3']) got_cs = [out_ds.GetRasterBand(i + 1).Checksum() for i in range(3)] - if got_cs != expected_cs: - gdaltest.post_reason('fail') - print('Got %s, expected %s' % (str(got_cs), str(expected_cs))) - return 'fail' - - return 'success' + assert got_cs == expected_cs ############################################################################### # Variation of gpkg_28 with 2 blocks -def gpkg_29(x=0): +def test_gpkg_29(x=0): if gdaltest.gpkg_dr is None: - return 'skip' + pytest.skip() if gdaltest.png_dr is None: - return 'skip' + pytest.skip() gdal.Unlink('/vsimem/tmp.gpkg') @@ -2767,31 +2203,26 @@ def gpkg_29(x=0): out_ds = None out_ds = gdal.OpenEx('/vsimem/tmp.gpkg', open_options=['BAND_COUNT=3']) got_cs = [out_ds.GetRasterBand(i + 1).Checksum() for i in range(3)] - if got_cs != expected_cs: - gdaltest.post_reason('fail') - print('Got %s, expected %s' % (str(got_cs), str(expected_cs))) - return 'fail' - - return 'success' + assert got_cs == expected_cs ############################################################################### # Variation of gpkg_29 where the read is done in another block -def gpkg_30(): +def test_gpkg_30(): - return gpkg_29(x=200) + return test_gpkg_29(x=200) ############################################################################### # 1 band to RGBA -def gpkg_31(): +def test_gpkg_31(): if gdaltest.gpkg_dr is None: - return 'skip' + pytest.skip() if gdaltest.png_dr is None: - return 'skip' + pytest.skip() gdal.Unlink('/vsimem/tmp.gpkg') @@ -2802,27 +2233,21 @@ def gpkg_31(): gdal.SetConfigOption('GPKG_PNG_SUPPORTS_2BANDS', None) ds = gdal.Open('/vsimem/tmp.gpkg') - if check_tile_format(ds, 'PNG', 4, False) != 'success': - return 'fail' + check_tile_format(ds, 'PNG', 4, False) expected_cs = [4672, 4672, 4672, 4873] got_cs = [ds.GetRasterBand(i + 1).Checksum() for i in range(4)] - if got_cs != expected_cs: - gdaltest.post_reason('fail') - print('Got %s, expected %s' % (str(got_cs), str(expected_cs))) - return 'fail' - - return 'success' + assert got_cs == expected_cs ############################################################################### # grey-alpha to RGBA -def gpkg_32(): +def test_gpkg_32(): if gdaltest.gpkg_dr is None: - return 'skip' + pytest.skip() if gdaltest.png_dr is None: - return 'skip' + pytest.skip() gdal.Unlink('/vsimem/tmp.gpkg') @@ -2833,35 +2258,26 @@ def gpkg_32(): gdal.SetConfigOption('GPKG_PNG_SUPPORTS_2BANDS', None) ds = gdal.Open('/vsimem/tmp.gpkg') - if check_tile_format(ds, 'PNG', 4, False) != 'success': - return 'fail' + check_tile_format(ds, 'PNG', 4, False) expected_cs = [1970, 1970, 1970, 10807] got_cs = [ds.GetRasterBand(i + 1).Checksum() for i in range(ds.RasterCount)] - if got_cs != expected_cs: - gdaltest.post_reason('fail') - print('Got %s, expected %s' % (str(got_cs), str(expected_cs))) - return 'fail' + assert got_cs == expected_cs ds = gdal.OpenEx('/vsimem/tmp.gpkg', open_options=['BAND_COUNT=2']) expected_cs = [1970, 10807] got_cs = [ds.GetRasterBand(i + 1).Checksum() for i in range(ds.RasterCount)] - if got_cs != expected_cs: - gdaltest.post_reason('fail') - print('Got %s, expected %s' % (str(got_cs), str(expected_cs))) - return 'fail' - - return 'success' + assert got_cs == expected_cs ############################################################################### # Single band with 32 bit color table -> RGBA -def gpkg_33(): +def test_gpkg_33(): if gdaltest.gpkg_dr is None: - return 'skip' + pytest.skip() if gdaltest.png_dr is None: - return 'skip' + pytest.skip() gdal.Unlink('/vsimem/tmp.gpkg') @@ -2874,27 +2290,21 @@ def gpkg_33(): gdal.Unlink(src_ds.GetDescription()) ds = gdal.Open('/vsimem/tmp.gpkg') - if check_tile_format(ds, 'PNG', 4, False) != 'success': - return 'fail' + check_tile_format(ds, 'PNG', 4, False) expected_cs = [10991, 57677, 34965, 10638] got_cs = [ds.GetRasterBand(i + 1).Checksum() for i in range(4)] - if got_cs != expected_cs: - gdaltest.post_reason('fail') - print('Got %s, expected %s' % (str(got_cs), str(expected_cs))) - return 'fail' - - return 'success' + assert got_cs == expected_cs ############################################################################### # Test partial tiles with overviews (#6335) -def gpkg_34(): +def test_gpkg_34(): if gdaltest.gpkg_dr is None: - return 'skip' + pytest.skip() if gdaltest.png_dr is None: - return 'skip' + pytest.skip() gdal.Unlink('/vsimem/tmp.gpkg') @@ -2909,21 +2319,18 @@ def gpkg_34(): gdal.ErrorReset() ds.BuildOverviews('NEAR', [2]) ds = None - if gdal.GetLastErrorMsg() != '': - return 'fail' - - return 'success' + assert gdal.GetLastErrorMsg() == '' ############################################################################### # Test dirty block flushing while reading block (#6365) -def gpkg_35(): +def test_gpkg_35(): if gdaltest.gpkg_dr is None: - return 'skip' + pytest.skip() if gdaltest.png_dr is None: - return 'skip' + pytest.skip() gdal.Unlink('/vsimem/tmp.gpkg') @@ -2960,21 +2367,18 @@ def gpkg_35(): gdal.SetCacheMax(oldSize) - if got_data != expected_data: - return 'fail' - - return 'success' + assert got_data == expected_data ############################################################################### # Single band with 24 bit color table, PNG, GoogleMapsCompatible -def gpkg_36(): +def test_gpkg_36(): if gdaltest.gpkg_dr is None: - return 'skip' + pytest.skip() if gdaltest.png_dr is None: - return 'skip' + pytest.skip() src_ds = gdal.Open('data/small_world_pct.tif') out_ds = gdaltest.gpkg_dr.CreateCopy('/vsimem/gpkg_36.gpkg', src_ds, options=['TILE_FORMAT=PNG', 'TILING_SCHEME=GoogleMapsCompatible', 'RESAMPLING=NEAREST']) @@ -2984,18 +2388,12 @@ def gpkg_36(): expected_cs = [993, 50461, 64354, 17849] out_ds = gdal.Open('/vsimem/gpkg_36.gpkg') got_cs = [out_ds.GetRasterBand(i + 1).Checksum() for i in range(4)] - if got_cs != expected_cs: - gdaltest.post_reason('fail') - print('Got %s, expected %s' % (str(got_cs), str(expected_cs))) - return 'fail' + assert got_cs == expected_cs got_ct = out_ds.GetRasterBand(1).GetColorTable() - if got_ct is not None: - gdaltest.post_reason('fail') - return 'fail' + assert got_ct is None out_ds = None gdal.Unlink('/vsimem/gpkg_36.gpkg') - return 'success' ############################################################################### # Test that we don't crash when generating big overview factors on rasters with big dimensions @@ -3003,10 +2401,10 @@ def gpkg_36(): # factors -def gpkg_37(): +def test_gpkg_37(): if gdaltest.gpkg_dr is None: - return 'skip' + pytest.skip() ds = gdal.GetDriverByName('GPKG').Create('/vsimem/gpkg_37.gpkg', 205000, 200000) ds.SetGeoTransform([100, 0.000001, 0, 100, 0, -0.000001]) @@ -3014,31 +2412,26 @@ def gpkg_37(): ds = gdal.Open('/vsimem/gpkg_37.gpkg', gdal.GA_Update) ret = ds.BuildOverviews('NONE', [2, 4, 8, 16, 32, 64, 128, 256, 512, 1024, 2048]) - if ret != 0 or gdal.GetLastErrorMsg() != '': - gdaltest.post_reason('fail') - return 'fail' + assert ret == 0 and gdal.GetLastErrorMsg() == '' ds = None gdal.Unlink('/vsimem/gpkg_37.gpkg') - return 'success' ############################################################################### # Test generating more than 1000 tiles -def gpkg_38(): +def test_gpkg_38(): if gdaltest.gpkg_dr is None: - return 'skip' + pytest.skip() # Without padding, immediately after create copy src_ds = gdal.Open('data/small_world.tif') gdaltest.gpkg_dr.CreateCopy('/vsimem/gpkg_38.gpkg', src_ds, options=['TILE_FORMAT=PNG', 'BLOCKSIZE=8']) ds = gdal.Open('/vsimem/gpkg_38.gpkg') - if ds.GetRasterBand(1).Checksum() != src_ds.GetRasterBand(1).Checksum(): - gdaltest.post_reason('fail') - return 'fail' + assert ds.GetRasterBand(1).Checksum() == src_ds.GetRasterBand(1).Checksum() ds = None filesize = gdal.VSIStatL('/vsimem/gpkg_38.gpkg').size gdal.Unlink('/vsimem/gpkg_38.gpkg') @@ -3049,9 +2442,7 @@ def gpkg_38(): ds_is_none = ds is None ds = None gdal.Unlink(filename) - if not ds_is_none and gdal.GetLastErrorMsg() == '': - gdaltest.post_reason('fail') - return 'fail' + assert ds_is_none or gdal.GetLastErrorMsg() != '' filename = '/vsimem/||maxlength=%d||gpkg_38.gpkg' % (filesize - 1) with gdaltest.error_handler(): @@ -3059,65 +2450,48 @@ def gpkg_38(): ds_is_none = ds is None ds = None gdal.Unlink(filename) - if not ds_is_none and gdal.GetLastErrorMsg() == '': - gdaltest.post_reason('fail') - return 'fail' - - return 'success' + assert ds_is_none or gdal.GetLastErrorMsg() != '' ############################################################################### # Test tile gridded coverage data -def gpkg_39(): +def test_gpkg_39(): if gdaltest.gpkg_dr is None: - return 'skip' + pytest.skip() src_ds = gdal.Open('data/int16.tif') gdal.Translate('/vsimem/gpkg_39.gpkg', src_ds, format='GPKG') - if not validate('/vsimem/gpkg_39.gpkg'): - gdaltest.post_reason('validation failed') - return 'fail' + assert validate('/vsimem/gpkg_39.gpkg'), 'validation failed' ds = gdal.Open('/vsimem/gpkg_39.gpkg') # Check there a ogr_empty_table sql_lyr = ds.ExecuteSQL("SELECT COUNT(*) FROM sqlite_master WHERE name = 'ogr_empty_table'") f = sql_lyr.GetNextFeature() - if f.GetField(0) != 1: - gdaltest.post_reason('fail') - return 'fail' + assert f.GetField(0) == 1 ds.ReleaseResultSet(sql_lyr) - if ds.GetRasterBand(1).DataType != gdal.GDT_Int16: - gdaltest.post_reason('fail') - return 'fail' - if ds.GetRasterBand(1).Checksum() != 4672: - gdaltest.post_reason('fail') - return 'fail' - if ds.GetMetadataItem('AREA_OR_POINT') != 'Area': - gdaltest.post_reason('fail') - return 'fail' + assert ds.GetRasterBand(1).DataType == gdal.GDT_Int16 + assert ds.GetRasterBand(1).Checksum() == 4672 + assert ds.GetMetadataItem('AREA_OR_POINT') == 'Area' sql_lyr = ds.ExecuteSQL('SELECT scale, offset FROM gpkg_2d_gridded_tile_ancillary') f = sql_lyr.GetNextFeature() if f['scale'] != 1.0: - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' + pytest.fail() if f['offset'] != 0.0: - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' + pytest.fail() ds.ReleaseResultSet(sql_lyr) sql_lyr = ds.ExecuteSQL('SELECT grid_cell_encoding FROM gpkg_2d_gridded_coverage_ancillary') f = sql_lyr.GetNextFeature() if f['grid_cell_encoding'] != 'grid-value-is-area': - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' + pytest.fail() ds.ReleaseResultSet(sql_lyr) # No metadata for now @@ -3125,44 +2499,31 @@ def gpkg_39(): feat = sql_lyr.GetNextFeature() ds.ReleaseResultSet(sql_lyr) feat_is_none = feat is None - if not feat_is_none: - gdaltest.post_reason('fail') - return 'fail' + assert feat_is_none sql_lyr = ds.ExecuteSQL('PRAGMA application_id') f = sql_lyr.GetNextFeature() if f['application_id'] != 1196444487: - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' + pytest.fail() ds.ReleaseResultSet(sql_lyr) sql_lyr = ds.ExecuteSQL('PRAGMA user_version') f = sql_lyr.GetNextFeature() if f['user_version'] != 10200: - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' + pytest.fail() ds.ReleaseResultSet(sql_lyr) # Statistics not available on partial tile without nodata md = ds.GetRasterBand(1).GetMetadata() - if md != {}: - gdaltest.post_reason('fail') - print(md) - return 'fail' + assert md == {} ds = None # From a AREA_OR_POINT=Point dataset gdal.Translate('/vsimem/gpkg_39.gpkg', 'data/n43.dt0', format='GPKG') ds = gdal.Open('/vsimem/gpkg_39.gpkg') - if ds.GetMetadataItem('AREA_OR_POINT') != 'Point': - gdaltest.post_reason('fail') - print(ds.GetMetadata()) - return 'fail' - if ds.GetRasterBand(1).GetUnitType() != 'm': - gdaltest.post_reason('fail') - print(ds.GetRasterBand(1).GetUnitType()) - return 'fail' + assert ds.GetMetadataItem('AREA_OR_POINT') == 'Point', ds.GetMetadata() + assert ds.GetRasterBand(1).GetUnitType() == 'm' ds = None # Test GRID_CELL_ENCODING=grid-value-is-corner @@ -3170,23 +2531,15 @@ def gpkg_39(): outputType=gdal.GDT_UInt16, creationOptions=['GRID_CELL_ENCODING=grid-value-is-corner']) ds = gdal.Open('/vsimem/gpkg_39.gpkg') - if ds.GetMetadataItem('AREA_OR_POINT') != 'Point': - gdaltest.post_reason('fail') - print(ds.GetMetadata()) - return 'fail' - if ds.GetRasterBand(1).GetMetadataItem('GRID_CELL_ENCODING') != 'grid-value-is-corner': - gdaltest.post_reason('fail') - print(ds.GetRasterBand(1).GetMetadataItem()) - return 'fail' + assert ds.GetMetadataItem('AREA_OR_POINT') == 'Point', ds.GetMetadata() + assert ds.GetRasterBand(1).GetMetadataItem('GRID_CELL_ENCODING') == 'grid-value-is-corner' # No metadata for now sql_lyr = ds.ExecuteSQL("SELECT 1 FROM sqlite_master WHERE name = 'gpkg_metadata'") feat = sql_lyr.GetNextFeature() ds.ReleaseResultSet(sql_lyr) feat_is_none = feat is None - if not feat_is_none: - gdaltest.post_reason('fail') - return 'fail' + assert feat_is_none ds = None @@ -3195,18 +2548,12 @@ def gpkg_39(): ds = gdal.Open('/vsimem/gpkg_39.gpkg') md = ds.GetRasterBand(1).GetMetadata() - if md != {'STATISTICS_MINIMUM': '74', 'STATISTICS_MAXIMUM': '255'}: - gdaltest.post_reason('fail') - print(md) - return 'fail' + assert md == {'STATISTICS_MINIMUM': '74', 'STATISTICS_MAXIMUM': '255'} ds = None ds = gdal.Open('/vsimem/gpkg_39.gpkg') mdi = ds.GetRasterBand(1).GetMetadataItem('STATISTICS_MINIMUM') - if mdi != '74': - gdaltest.post_reason('fail') - print(mdi) - return 'fail' + assert mdi == '74' ds = None # Entire tile: statistics available @@ -3214,165 +2561,97 @@ def gpkg_39(): ds = gdal.Open('/vsimem/gpkg_39.gpkg') md = ds.GetRasterBand(1).GetMetadata() - if md != {'STATISTICS_MINIMUM': '74', 'STATISTICS_MAXIMUM': '255'}: - gdaltest.post_reason('fail') - print(md) - return 'fail' + assert md == {'STATISTICS_MINIMUM': '74', 'STATISTICS_MAXIMUM': '255'} ds = None ds = gdal.Open('/vsimem/gpkg_39.gpkg') mdi = ds.GetRasterBand(1).GetMetadataItem('STATISTICS_MINIMUM') - if mdi != '74': - gdaltest.post_reason('fail') - print(mdi) - return 'fail' + assert mdi == '74' ds = None gdal.Translate('/vsimem/gpkg_39.gpkg', src_ds, format='GPKG', noData=1) ds = gdal.Open('/vsimem/gpkg_39.gpkg') - if ds.GetRasterBand(1).Checksum() != 4672: - gdaltest.post_reason('fail') - return 'fail' - if ds.GetRasterBand(1).GetNoDataValue() != -32768.0: - gdaltest.post_reason('fail') - print(ds.GetRasterBand(1).GetNoDataValue()) - return 'fail' + assert ds.GetRasterBand(1).Checksum() == 4672 + assert ds.GetRasterBand(1).GetNoDataValue() == -32768.0 gdal.Translate('/vsimem/gpkg_39.gpkg', src_ds, format='GPKG', noData=74) ds = gdal.Open('/vsimem/gpkg_39.gpkg') cs = ds.GetRasterBand(1).Checksum() - if cs != 4649: - gdaltest.post_reason('fail') - print(cs) - return 'fail' - if ds.GetRasterBand(1).GetNoDataValue() != -32768.0: - gdaltest.post_reason('fail') - print(ds.GetRasterBand(1).GetNoDataValue()) - return 'fail' + assert cs == 4649 + assert ds.GetRasterBand(1).GetNoDataValue() == -32768.0 gdal.Translate('/vsimem/gpkg_39.gpkg', src_ds, format='GPKG', noData=1, creationOptions=['TILING_SCHEME=GoogleMapsCompatible']) ds = gdal.Open('/vsimem/gpkg_39.gpkg') cs = ds.GetRasterBand(1).Checksum() - if cs != 4118 and cs != 4077: - gdaltest.post_reason('fail') - print(cs) - return 'fail' + assert cs == 4118 or cs == 4077 gdal.SetConfigOption('GPKG_ADD_DEFINITION_12_063', 'YES') gdal.Translate('/vsimem/gpkg_39.gpkg', src_ds, format='GPKG', noData=1, creationOptions=['TILING_SCHEME=GoogleMapsCompatible']) gdal.SetConfigOption('GPKG_ADD_DEFINITION_12_063', None) ds = gdal.Open('/vsimem/gpkg_39.gpkg') cs = ds.GetRasterBand(1).Checksum() - if cs != 4118 and cs != 4077: - gdaltest.post_reason('fail') - print(cs) - return 'fail' + assert cs == 4118 or cs == 4077 gdal.Translate('/vsimem/gpkg_39.gpkg', src_ds, format='GPKG', width=1024, height=1024) ds = gdal.Open('/vsimem/gpkg_39.gpkg', gdal.GA_Update) ds.BuildOverviews('NEAR', [2, 4]) - if ds.GetRasterBand(1).GetOverview(0).Checksum() != 37308: - gdaltest.post_reason('fail') - print(ds.GetRasterBand(1).GetOverview(0).Checksum()) - return 'fail' + assert ds.GetRasterBand(1).GetOverview(0).Checksum() == 37308 ds.BuildOverviews('NONE', []) ds = gdal.Open('/vsimem/gpkg_39.gpkg') - if ds.GetRasterBand(1).GetOverviewCount() != 0: - gdaltest.post_reason('fail') - return 'fail' + assert ds.GetRasterBand(1).GetOverviewCount() == 0 gdal.Translate('/vsimem/gpkg_39.gpkg', src_ds, format='GPKG', outputType=gdal.GDT_UInt16) ds = gdal.Open('/vsimem/gpkg_39.gpkg') - if ds.GetRasterBand(1).DataType != gdal.GDT_UInt16: - gdaltest.post_reason('fail') - return 'fail' - if ds.GetRasterBand(1).Checksum() != 4672: - gdaltest.post_reason('fail') - return 'fail' + assert ds.GetRasterBand(1).DataType == gdal.GDT_UInt16 + assert ds.GetRasterBand(1).Checksum() == 4672 sql_lyr = ds.ExecuteSQL('SELECT scale, offset FROM gpkg_2d_gridded_tile_ancillary') f = sql_lyr.GetNextFeature() - if f['scale'] != 1.0: - gdaltest.post_reason('fail') - return 'fail' + assert f['scale'] == 1.0 ds.ReleaseResultSet(sql_lyr) gdal.Translate('/vsimem/gpkg_39.gpkg', src_ds, format='GPKG', outputType=gdal.GDT_UInt16, noData=1) ds = gdal.Open('/vsimem/gpkg_39.gpkg') - if ds.GetRasterBand(1).Checksum() != 4672: - gdaltest.post_reason('fail') - return 'fail' - if ds.GetRasterBand(1).GetNoDataValue() != 1.0: - gdaltest.post_reason('fail') - print(ds.GetRasterBand(1).GetNoDataValue()) - return 'fail' + assert ds.GetRasterBand(1).Checksum() == 4672 + assert ds.GetRasterBand(1).GetNoDataValue() == 1.0 gdal.Translate('/vsimem/gpkg_39.gpkg', src_ds, format='GPKG', outputType=gdal.GDT_UInt16, noData=74) ds = gdal.Open('/vsimem/gpkg_39.gpkg') cs = ds.GetRasterBand(1).Checksum() - if cs != 4672: - gdaltest.post_reason('fail') - print(cs) - return 'fail' - if ds.GetRasterBand(1).GetNoDataValue() != 74.0: - gdaltest.post_reason('fail') - print(ds.GetRasterBand(1).GetNoDataValue()) - return 'fail' + assert cs == 4672 + assert ds.GetRasterBand(1).GetNoDataValue() == 74.0 src_ds = gdal.Open('data/float32.tif') gdal.Translate('/vsimem/gpkg_39.gpkg', src_ds, format='GPKG') ds = gdal.Open('/vsimem/gpkg_39.gpkg') - if ds.GetRasterBand(1).DataType != gdal.GDT_Float32: - gdaltest.post_reason('fail') - return 'fail' - if ds.GetRasterBand(1).Checksum() != 4672: - gdaltest.post_reason('fail') - return 'fail' + assert ds.GetRasterBand(1).DataType == gdal.GDT_Float32 + assert ds.GetRasterBand(1).Checksum() == 4672 sql_lyr = ds.ExecuteSQL('SELECT scale, offset FROM gpkg_2d_gridded_tile_ancillary') f = sql_lyr.GetNextFeature() - if f.GetField('scale') != 1.0: - gdaltest.post_reason('fail') - return 'fail' + assert f.GetField('scale') == 1.0 ds.ReleaseResultSet(sql_lyr) gdal.Translate('/vsimem/gpkg_39.gpkg', src_ds, format='GPKG', noData=1) ds = gdal.Open('/vsimem/gpkg_39.gpkg') - if ds.GetRasterBand(1).Checksum() != 4672: - gdaltest.post_reason('fail') - return 'fail' - if ds.GetRasterBand(1).GetNoDataValue() != 1: - gdaltest.post_reason('fail') - return 'fail' + assert ds.GetRasterBand(1).Checksum() == 4672 + assert ds.GetRasterBand(1).GetNoDataValue() == 1 gdal.Translate('/vsimem/gpkg_39.gpkg', src_ds, format='GPKG', creationOptions=['TILE_FORMAT=PNG']) ds = gdal.Open('/vsimem/gpkg_39.gpkg') - if ds.GetRasterBand(1).DataType != gdal.GDT_Float32: - gdaltest.post_reason('fail') - return 'fail' - if ds.GetRasterBand(1).Checksum() != 4672: - gdaltest.post_reason('fail') - return 'fail' + assert ds.GetRasterBand(1).DataType == gdal.GDT_Float32 + assert ds.GetRasterBand(1).Checksum() == 4672 sql_lyr = ds.ExecuteSQL('SELECT scale, offset FROM gpkg_2d_gridded_tile_ancillary') f = sql_lyr.GetNextFeature() - if f['scale'] == 1.0 or not f.IsFieldSetAndNotNull('scale'): - gdaltest.post_reason('fail') - return 'fail' + assert f['scale'] != 1.0 and f.IsFieldSetAndNotNull('scale') ds.ReleaseResultSet(sql_lyr) gdal.Translate('/vsimem/gpkg_39.gpkg', src_ds, format='GPKG', noData=74, creationOptions=['TILE_FORMAT=PNG']) ds = gdal.Open('/vsimem/gpkg_39.gpkg') - if ds.GetRasterBand(1).DataType != gdal.GDT_Float32: - gdaltest.post_reason('fail') - return 'fail' + assert ds.GetRasterBand(1).DataType == gdal.GDT_Float32 cs = ds.GetRasterBand(1).Checksum() - if cs != 4680: - gdaltest.post_reason('fail') - print(cs) - return 'fail' + assert cs == 4680 sql_lyr = ds.ExecuteSQL('SELECT scale, offset FROM gpkg_2d_gridded_tile_ancillary') f = sql_lyr.GetNextFeature() - if f['scale'] == 1.0 or not f.IsFieldSetAndNotNull('scale'): - gdaltest.post_reason('fail') - return 'fail' + assert f['scale'] != 1.0 and f.IsFieldSetAndNotNull('scale') ds.ReleaseResultSet(sql_lyr) # Particular case with nodata = -32768 for Int16 @@ -3387,17 +2666,10 @@ def gpkg_39(): gdal.Translate('/vsimem/gpkg_39.gpkg', '/vsimem/gpkg_39.asc', format='GPKG', outputType=gdal.GDT_Int16) src_ds = gdal.Open('/vsimem/gpkg_39.asc') ds = gdal.Open('/vsimem/gpkg_39.gpkg') - if ds.GetRasterBand(1).DataType != gdal.GDT_Int16: - gdaltest.post_reason('fail') - return 'fail' - if ds.GetRasterBand(1).GetNoDataValue() != -32768.0: - gdaltest.post_reason('fail') - print(ds.GetRasterBand(1).GetNoDataValue()) - return 'fail' - if ds.GetRasterBand(1).Checksum() != src_ds.GetRasterBand(1).Checksum(): - gdaltest.post_reason('fail') - print(ds.GetRasterBand(1).GetNoDataValue()) - return 'fail' + assert ds.GetRasterBand(1).DataType == gdal.GDT_Int16 + assert ds.GetRasterBand(1).GetNoDataValue() == -32768.0 + assert ds.GetRasterBand(1).Checksum() == src_ds.GetRasterBand(1).Checksum(), \ + ds.GetRasterBand(1).GetNoDataValue() ds = None src_ds = None gdal.Unlink('/vsimem/gpkg_39.asc') @@ -3414,17 +2686,10 @@ def gpkg_39(): gdal.Translate('/vsimem/gpkg_39.gpkg', '/vsimem/gpkg_39.asc', format='GPKG', outputType=gdal.GDT_UInt16) src_ds = gdal.Open('/vsimem/gpkg_39.asc') ds = gdal.Open('/vsimem/gpkg_39.gpkg') - if ds.GetRasterBand(1).DataType != gdal.GDT_UInt16: - gdaltest.post_reason('fail') - return 'fail' - if ds.GetRasterBand(1).GetNoDataValue() != 65535.0: - gdaltest.post_reason('fail') - print(ds.GetRasterBand(1).GetNoDataValue()) - return 'fail' - if ds.GetRasterBand(1).Checksum() != src_ds.GetRasterBand(1).Checksum(): - gdaltest.post_reason('fail') - print(ds.GetRasterBand(1).GetNoDataValue()) - return 'fail' + assert ds.GetRasterBand(1).DataType == gdal.GDT_UInt16 + assert ds.GetRasterBand(1).GetNoDataValue() == 65535.0 + assert ds.GetRasterBand(1).Checksum() == src_ds.GetRasterBand(1).Checksum(), \ + ds.GetRasterBand(1).GetNoDataValue() ds = None src_ds = None gdal.Unlink('/vsimem/gpkg_39.asc') @@ -3441,17 +2706,10 @@ def gpkg_39(): gdal.Translate('/vsimem/gpkg_39.gpkg', '/vsimem/gpkg_39.asc', format='GPKG', outputType=gdal.GDT_UInt16) src_ds = gdal.Open('/vsimem/gpkg_39.asc') ds = gdal.Open('/vsimem/gpkg_39.gpkg') - if ds.GetRasterBand(1).DataType != gdal.GDT_UInt16: - gdaltest.post_reason('fail') - return 'fail' - if ds.GetRasterBand(1).GetNoDataValue() != 0: - gdaltest.post_reason('fail') - print(ds.GetRasterBand(1).GetNoDataValue()) - return 'fail' - if ds.GetRasterBand(1).Checksum() != src_ds.GetRasterBand(1).Checksum(): - gdaltest.post_reason('fail') - print(ds.GetRasterBand(1).GetNoDataValue()) - return 'fail' + assert ds.GetRasterBand(1).DataType == gdal.GDT_UInt16 + assert ds.GetRasterBand(1).GetNoDataValue() == 0 + assert ds.GetRasterBand(1).Checksum() == src_ds.GetRasterBand(1).Checksum(), \ + ds.GetRasterBand(1).GetNoDataValue() ds = None src_ds = None gdal.Unlink('/vsimem/gpkg_39.asc') @@ -3466,19 +2724,13 @@ def gpkg_39(): -100000 100000""") gdal.Translate('/vsimem/gpkg_39.gpkg', '/vsimem/gpkg_39.asc', format='GPKG', outputType=gdal.GDT_Float32, creationOptions=['TILE_FORMAT=PNG']) - if not validate('/vsimem/gpkg_39.gpkg'): - gdaltest.post_reason('validation failed') - return 'fail' + assert validate('/vsimem/gpkg_39.gpkg'), 'validation failed' src_ds = gdal.Open('/vsimem/gpkg_39.asc') ds = gdal.Open('/vsimem/gpkg_39.gpkg') - if ds.GetRasterBand(1).DataType != gdal.GDT_Float32: - gdaltest.post_reason('fail') - return 'fail' - if ds.GetRasterBand(1).Checksum() != src_ds.GetRasterBand(1).Checksum(): - gdaltest.post_reason('fail') - print(ds.GetRasterBand(1).GetNoDataValue()) - return 'fail' + assert ds.GetRasterBand(1).DataType == gdal.GDT_Float32 + assert ds.GetRasterBand(1).Checksum() == src_ds.GetRasterBand(1).Checksum(), \ + ds.GetRasterBand(1).GetNoDataValue() ds = None src_ds = None gdal.Unlink('/vsimem/gpkg_39.asc') @@ -3494,13 +2746,9 @@ def gpkg_39(): gdal.Translate('/vsimem/gpkg_39.gpkg', '/vsimem/gpkg_39.asc', format='GPKG', outputType=gdal.GDT_Float32, noData=0, creationOptions=['TILE_FORMAT=PNG']) src_ds = gdal.Open('/vsimem/gpkg_39.asc') ds = gdal.Open('/vsimem/gpkg_39.gpkg') - if ds.GetRasterBand(1).DataType != gdal.GDT_Float32: - gdaltest.post_reason('fail') - return 'fail' - if ds.GetRasterBand(1).Checksum() != src_ds.GetRasterBand(1).Checksum(): - gdaltest.post_reason('fail') - print(ds.GetRasterBand(1).GetNoDataValue()) - return 'fail' + assert ds.GetRasterBand(1).DataType == gdal.GDT_Float32 + assert ds.GetRasterBand(1).Checksum() == src_ds.GetRasterBand(1).Checksum(), \ + ds.GetRasterBand(1).GetNoDataValue() ds = None src_ds = None gdal.Unlink('/vsimem/gpkg_39.asc') @@ -3518,9 +2766,7 @@ def gpkg_39(): ds.GetRasterBand(1).FlushCache() sql_lyr = ds.ExecuteSQL('SELECT scale, offset FROM gpkg_2d_gridded_tile_ancillary') f = sql_lyr.GetNextFeature() - if f is not None: - gdaltest.post_reason('fail') - return 'fail' + assert f is None ds.ReleaseResultSet(sql_lyr) ds = None @@ -3536,9 +2782,7 @@ def gpkg_39(): ds.GetRasterBand(1).FlushCache() sql_lyr = ds.ExecuteSQL('SELECT * FROM gpkg_39') f = sql_lyr.GetNextFeature() - if f is not None: - gdaltest.post_reason('fail') - return 'fail' + assert f is None ds.ReleaseResultSet(sql_lyr) ds = None @@ -3555,25 +2799,21 @@ def gpkg_39(): ds.GetRasterBand(1).FlushCache() sql_lyr = ds.ExecuteSQL('SELECT * FROM gpkg_39') f = sql_lyr.GetNextFeature() - if f is not None: - gdaltest.post_reason('fail') - return 'fail' + assert f is None ds.ReleaseResultSet(sql_lyr) ds = None gdal.Unlink('/vsimem/gpkg_39.gpkg') gdal.Unlink('/vsimem/gpkg_39.gpkg.aux.xml') - return 'success' - ############################################################################### # Test VERSION -def gpkg_40(): +def test_gpkg_40(): if gdaltest.gpkg_dr is None: - return 'skip' + pytest.skip() src_ds = gdal.Open('data/byte.tif') # Should default to 1.2 @@ -3582,16 +2822,14 @@ def gpkg_40(): sql_lyr = ds.ExecuteSQL('PRAGMA application_id') f = sql_lyr.GetNextFeature() if f['application_id'] != 1196444487: - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' + pytest.fail() ds.ReleaseResultSet(sql_lyr) sql_lyr = ds.ExecuteSQL('PRAGMA user_version') f = sql_lyr.GetNextFeature() if f['user_version'] != 10200: - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' + pytest.fail() ds.ReleaseResultSet(sql_lyr) ds = None @@ -3602,16 +2840,14 @@ def gpkg_40(): sql_lyr = ds.ExecuteSQL('PRAGMA application_id') f = sql_lyr.GetNextFeature() if f['application_id'] != 1196437808: - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' + pytest.fail() ds.ReleaseResultSet(sql_lyr) sql_lyr = ds.ExecuteSQL('PRAGMA user_version') f = sql_lyr.GetNextFeature() if f['user_version'] != 0: - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' + pytest.fail() ds.ReleaseResultSet(sql_lyr) ds = None @@ -3621,16 +2857,14 @@ def gpkg_40(): sql_lyr = ds.ExecuteSQL('PRAGMA application_id') f = sql_lyr.GetNextFeature() if f['application_id'] != 1196437809: - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' + pytest.fail() ds.ReleaseResultSet(sql_lyr) sql_lyr = ds.ExecuteSQL('PRAGMA user_version') f = sql_lyr.GetNextFeature() if f['user_version'] != 0: - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' + pytest.fail() ds.ReleaseResultSet(sql_lyr) ds = None @@ -3640,32 +2874,28 @@ def gpkg_40(): sql_lyr = ds.ExecuteSQL('PRAGMA application_id') f = sql_lyr.GetNextFeature() if f['application_id'] != 1196444487: - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' + pytest.fail() ds.ReleaseResultSet(sql_lyr) sql_lyr = ds.ExecuteSQL('PRAGMA user_version') f = sql_lyr.GetNextFeature() if f['user_version'] != 10200: - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' + pytest.fail() ds.ReleaseResultSet(sql_lyr) ds = None gdal.Unlink('/vsimem/gpkg_40.gpkg') - return 'success' - ############################################################################### # Robustness test -def gpkg_41(): +def test_gpkg_41(): if gdaltest.gpkg_dr is None or gdal.GetConfigOption('TRAVIS') is not None or \ gdal.GetConfigOption('APPVEYOR') is not None: - return 'skip' + pytest.skip() gdal.SetConfigOption('GPKG_ALLOW_CRAZY_SETTINGS', 'YES') with gdaltest.error_handler(): @@ -3676,16 +2906,14 @@ def gpkg_41(): gdal.Unlink('/vsimem/gpkg_41.gpkg') - return 'success' - ############################################################################### # Test opening in vector mode a database without gpkg_geometry_columns -def gpkg_42(): +def test_gpkg_42(): if gdaltest.gpkg_dr is None: - return 'skip' + pytest.skip() gdal.SetConfigOption('CREATE_GEOMETRY_COLUMNS', 'NO') gdal.Translate('/vsimem/gpkg_42.gpkg', 'data/byte.tif', format='GPKG') @@ -3695,31 +2923,23 @@ def gpkg_42(): sql_lyr = ds.ExecuteSQL("SELECT 1 FROM sqlite_master WHERE name = 'gpkg_geometry_columns'") fc = sql_lyr.GetFeatureCount() ds.ReleaseResultSet(sql_lyr) - if fc != 0: - gdaltest.post_reason('fail') - return 'fail' + assert fc == 0 lyr = ds.CreateLayer('test') - if lyr is None: - gdaltest.post_reason('fail') - return 'fail' + assert lyr is not None ds.FlushCache() - if gdal.GetLastErrorMsg() != '': - gdaltest.post_reason('fail') - return 'fail' + assert gdal.GetLastErrorMsg() == '' ds = None gdal.Unlink('/vsimem/gpkg_42.gpkg') - return 'success' - ############################################################################### # Test adding raster to a database without pre-existing raster support tables. -def gpkg_43(): +def test_gpkg_43(): if gdaltest.gpkg_dr is None: - return 'skip' + pytest.skip() gdal.SetConfigOption('CREATE_RASTER_TABLES', 'NO') ds = gdaltest.gpkg_dr.Create('/vsimem/gpkg_43.gpkg', 0, 0, 0, gdal.GDT_Unknown) @@ -3731,71 +2951,55 @@ def gpkg_43(): sql_lyr = ds.ExecuteSQL("SELECT 1 FROM sqlite_master WHERE name = 'gpkg_tile_matrix_set'") fc = sql_lyr.GetFeatureCount() ds.ReleaseResultSet(sql_lyr) - if fc != 0: - gdaltest.post_reason('fail') - return 'fail' + assert fc == 0 ds = None gdal.Translate('/vsimem/gpkg_43.gpkg', 'data/byte.tif', format='GPKG', creationOptions=['APPEND_SUBDATASET=YES']) ds = gdal.OpenEx('/vsimem/gpkg_43.gpkg') - if ds.GetRasterBand(1).Checksum() != 4672: - gdaltest.post_reason('fail') - return 'fail' - if ds.GetLayerCount() != 1: - gdaltest.post_reason('fail') - return 'fail' + assert ds.GetRasterBand(1).Checksum() == 4672 + assert ds.GetLayerCount() == 1 ds = None - if not validate('/vsimem/gpkg_43.gpkg'): - gdaltest.post_reason('validation failed') - return 'fail' + assert validate('/vsimem/gpkg_43.gpkg'), 'validation failed' gdal.Unlink('/vsimem/gpkg_43.gpkg') - return 'success' - ############################################################################### # Test opening a .gpkg.sql file -def gpkg_44(): +def test_gpkg_44(): if gdaltest.gpkg_dr is None: - return 'skip' + pytest.skip() if gdaltest.gpkg_dr.GetMetadataItem("ENABLE_SQL_GPKG_FORMAT") != 'YES': - return 'skip' + pytest.skip() ds = gdal.Open('data/byte.gpkg.sql') - if ds.GetRasterBand(1).Checksum() != 4672: - gdaltest.post_reason('validation failed') - return 'fail' - return 'success' + assert ds.GetRasterBand(1).Checksum() == 4672, 'validation failed' ############################################################################### # Test opening a .gpkg file -def gpkg_45(): +def test_gpkg_45(): if gdaltest.gpkg_dr is None: - return 'skip' + pytest.skip() ds = gdal.Open('data/byte.gpkg') - if ds.GetRasterBand(1).Checksum() != 4672: - gdaltest.post_reason('validation failed') - return 'fail' - return 'success' + assert ds.GetRasterBand(1).Checksum() == 4672, 'validation failed' ############################################################################### # Test fix for #6932 -def gpkg_46(): +def test_gpkg_46(): if gdaltest.gpkg_dr is None: - return 'skip' + pytest.skip() ds = gdaltest.gpkg_dr.Create('/vsimem/gpkg_46.gpkg', 6698, 6698, options=['TILING_SCHEME=GoogleMapsCompatible']) @@ -3816,30 +3020,25 @@ def gpkg_46(): count += 1 if abs(f.GetField(1) - 40075016.6855785) > 1e-7 or \ abs(f.GetField(2) - 40075016.6855785) > 1e-7: - gdaltest.post_reason('fail') f.DumpReadable() ds.ReleaseResultSet(sql_lyr) gdal.Unlink('/vsimem/gpkg_46.gpkg') - return 'fail' + pytest.fail() ds.ReleaseResultSet(sql_lyr) ds = None gdal.Unlink('/vsimem/gpkg_46.gpkg') - if count != 23: - gdaltest.post_reason('fail') - return 'fail' - - return 'success' + assert count == 23 ############################################################################### # Test fix for #6976 -def gpkg_47(): +def test_gpkg_47(): if gdaltest.gpkg_dr is None: - return 'skip' + pytest.skip() tmpfile = '/vsimem/gpkg_47.gpkg' ds = gdaltest.gpkg_dr.CreateCopy(tmpfile, @@ -3848,23 +3047,20 @@ def gpkg_47(): ds = None with gdaltest.error_handler(): ds = gdal.Open(tmpfile) - if ds.RasterXSize != 256: - return 'fail' + assert ds.RasterXSize == 256 ds = None gdal.Unlink(tmpfile) - return 'success' - ############################################################################### # Test fix for https://issues.qgis.org/issues/16997 (opening a file with # subdatasets on Windows) -def gpkg_48(): +def test_gpkg_48(): if gdaltest.gpkg_dr is None: - return 'skip' + pytest.skip() if sys.platform == 'win32': filename = os.path.join(os.getcwd(), 'tmp', 'byte.gpkg') @@ -3877,25 +3073,23 @@ def gpkg_48(): ds = gdal.Open('GPKG:' + filename + ':foo') if ds is None: gdal.Unlink(filename) - return 'fail' + pytest.fail() ds = None ds = gdal.Open('GPKG:' + filename + ':bar') if ds is None: gdal.Unlink(filename) - return 'fail' + pytest.fail() ds = None gdal.Unlink(filename) - return 'success' - ############################################################################### -def gpkg_delete_raster_layer(): +def test_gpkg_delete_raster_layer(): if gdaltest.gpkg_dr is None: - return 'skip' + pytest.skip() filename = '/vsimem/byte.gpkg' gdal.Translate(filename, 'data/byte.tif', format='GPKG', @@ -3908,32 +3102,25 @@ def gpkg_delete_raster_layer(): ds.ExecuteSQL('VACUUM') ds = None - if fc != 0: - gdaltest.post_reason('fail') - print(fc) - return 'fail' + assert fc == 0 # Check that there is no more any reference to the layer f = gdal.VSIFOpenL(filename, 'rb') content = gdal.VSIFReadL(1, 1000000, f).decode('latin1') gdal.VSIFCloseL(f) - if content.find('foo') >= 0: - gdaltest.post_reason('fail') - return 'fail' + assert content.find('foo') < 0 gdal.Unlink(filename) - return 'success' - ############################################################################### -def gpkg_delete_gridded_coverage_raster_layer(): +def test_gpkg_delete_gridded_coverage_raster_layer(): if gdaltest.gpkg_dr is None: - return 'skip' + pytest.skip() filename = '/vsimem/float32.gpkg' gdal.Translate(filename, 'data/float32.tif', format='GPKG', @@ -3948,157 +3135,71 @@ def gpkg_delete_gridded_coverage_raster_layer(): content = gdal.VSIFReadL(1, 1000000, f).decode('latin1') gdal.VSIFCloseL(f) - if content.find('foo') >= 0: - gdaltest.post_reason('fail') - return 'fail' + assert content.find('foo') < 0 gdal.Unlink(filename) - return 'success' - ############################################################################### -def gpkg_open_old_gpkg_elevation_tiles_extension(): +def test_gpkg_open_old_gpkg_elevation_tiles_extension(): if gdaltest.gpkg_dr is None: - return 'skip' + pytest.skip() gdal.ErrorReset() ds = gdal.Open('data/uint16-old-elevation-extension.gpkg') - if gdal.GetLastErrorMsg() != '': - gdaltest.post_reason('fail') - return 'fail' + assert gdal.GetLastErrorMsg() == '' cs = ds.GetRasterBand(1).Checksum() - if cs != 4672: - gdaltest.post_reason('fail') - return 'fail' - - return 'success' + assert cs == 4672 ############################################################################### -def gpkg_GeneralCmdLineProcessor(): +def test_gpkg_GeneralCmdLineProcessor(): if gdaltest.gpkg_dr is None: - return 'skip' + pytest.skip() import test_cli_utilities if test_cli_utilities.get_gdalinfo_path() is not None and test_cli_utilities.get_ogrinfo_path() is not None: ret_gdalinfo = gdaltest.runexternal(test_cli_utilities.get_gdalinfo_path() + ' --format GPKG') ret_ogrinfo = gdaltest.runexternal(test_cli_utilities.get_ogrinfo_path() + ' --format GPKG') - if ret_gdalinfo.find('<CreationOptionList>') < 0 or \ - ret_ogrinfo.find('<CreationOptionList>') < 0 or \ - ret_gdalinfo.find('scope=') >= 0 or \ - ret_ogrinfo.find('scope=') >= 0: - print(ret_gdalinfo) - print(ret_ogrinfo) - return 'fail' - - return 'success' + assert (ret_gdalinfo.find('<CreationOptionList>') >= 0 and \ + ret_ogrinfo.find('<CreationOptionList>') >= 0 and \ + ret_gdalinfo.find('scope=') < 0 and \ + ret_ogrinfo.find('scope=') < 0) + ############################################################################### -def gpkg_match_overview_factor(): +def test_gpkg_match_overview_factor(): if gdaltest.gpkg_dr is None: - return 'skip' + pytest.skip() gdal.FileFromMemBuffer('/vsimem/gpkg_match_overview_factor.gpkg', open('data/test_match_overview_factor.gpkg', 'rb').read()) ds = gdal.Open('/vsimem/gpkg_match_overview_factor.gpkg', gdal.GA_Update) ret = ds.BuildOverviews('NONE', [2, 4, 8, 16, 32, 64, 128, 256, 512, 1024, 2048]) - if ret != 0 or gdal.GetLastErrorMsg() != '': - gdaltest.post_reason('fail') - return 'fail' + assert ret == 0 and gdal.GetLastErrorMsg() == '' ds = None gdal.Unlink('/vsimem/gpkg_match_overview_factor.gpkg') - return 'success' ############################################################################### # -def gpkg_cleanup(): +def test_gpkg_cleanup(): if gdaltest.gpkg_dr is None: - return 'skip' + pytest.skip() gdal.Unlink('/vsimem/tmp.gpkg') gdal.Unlink('/vsimem/tmp.gpkg.aux.xml') gdal.SetConfigOption('GPKG_DEBUG', None) - return 'success' - ############################################################################### - - -gdaltest_list = [ - gpkg_init, - gpkg_1, - gpkg_2, - gpkg_3, - gpkg_4, - gpkg_5, - gpkg_6, - gpkg_7, - gpkg_8, - gpkg_9, - gpkg_10, - gpkg_11, - gpkg_12, - gpkg_13, - gpkg_14, - gpkg_15, - gpkg_16, - gpkg_17, - gpkg_18, - gpkg_19, - gpkg_20, - gpkg_21, - gpkg_22, - gpkg_23, - gpkg_24, - gpkg_25, - gpkg_26, - gpkg_27, - gpkg_28, - gpkg_29, - gpkg_30, - gpkg_31, - gpkg_32, - gpkg_33, - gpkg_34, - gpkg_35, - gpkg_36, - gpkg_37, - gpkg_38, - gpkg_39, - gpkg_40, - gpkg_41, - gpkg_42, - gpkg_43, - gpkg_44, - gpkg_45, - gpkg_46, - gpkg_47, - gpkg_48, - gpkg_delete_raster_layer, - gpkg_open_old_gpkg_elevation_tiles_extension, - gpkg_GeneralCmdLineProcessor, - gpkg_match_overview_factor, - gpkg_delete_gridded_coverage_raster_layer, - gpkg_cleanup, -] -# gdaltest_list = [ gpkg_init, gpkg_47, gpkg_cleanup ] -if __name__ == '__main__': - - gdaltest.setup_run('gpkg') - - gdaltest.run_tests(gdaltest_list) - - sys.exit(gdaltest.summarize()) diff --git a/autotest/gdrivers/grass.py b/autotest/gdrivers/grass.py index cde00a6cd07e..f06ac4b5b306 100755 --- a/autotest/gdrivers/grass.py +++ b/autotest/gdrivers/grass.py @@ -28,33 +28,31 @@ # DEALINGS IN THE SOFTWARE. ############################################################################### -import sys from osgeo import gdal -sys.path.append('../pymod') import gdaltest +import pytest ############################################################################### # Test if GRASS driver is present -def grass_1(): +def test_grass_1(): gdaltest.grass_drv = gdal.GetDriverByName('GRASS') if gdaltest.grass_drv is None: - return 'skip' - - return 'success' + pytest.skip() + ############################################################################### # Read existing simple 1 band GRASS dataset. -def grass_2(): +def test_grass_2(): if gdaltest.grass_drv is None: - return 'skip' + pytest.skip() tst = gdaltest.GDALTest('GRASS', 'small_grass_dataset/demomapset/cellhd/elevation', 1, 41487) @@ -79,16 +77,5 @@ def grass_2(): return ret -gdaltest_list = [ - grass_1, - grass_2 -] - - -if __name__ == '__main__': - - gdaltest.setup_run('GRASS') - gdaltest.run_tests(gdaltest_list) - sys.exit(gdaltest.summarize()) diff --git a/autotest/gdrivers/grassasciigrid.py b/autotest/gdrivers/grassasciigrid.py index 12dde9da0c54..32e3154d72c2 100755 --- a/autotest/gdrivers/grassasciigrid.py +++ b/autotest/gdrivers/grassasciigrid.py @@ -28,9 +28,7 @@ # DEALINGS IN THE SOFTWARE. ############################################################################### -import sys -sys.path.append('../pymod') import gdaltest @@ -38,7 +36,7 @@ # Perform simple read test. -def grassasciigrid_1(): +def test_grassasciigrid_1(): tst = gdaltest.GDALTest('GRASSASCIIGrid', 'grassascii.txt', 1, 212) expected_gt = [-100.0, 62.5, 0.0, 250.0, 0.0, -41.666666666666664] @@ -47,14 +45,4 @@ def grassasciigrid_1(): ############################################################################### -gdaltest_list = [ - grassasciigrid_1 -] -if __name__ == '__main__': - - gdaltest.setup_run('grassasciigrid') - - gdaltest.run_tests(gdaltest_list) - - sys.exit(gdaltest.summarize()) diff --git a/autotest/gdrivers/grib.py b/autotest/gdrivers/grib.py index a0d84451b6c7..6873bfe42b6f 100755 --- a/autotest/gdrivers/grib.py +++ b/autotest/gdrivers/grib.py @@ -36,13 +36,16 @@ import shutil from osgeo import gdal from osgeo import osr +import pytest -sys.path.append('../pymod') sys.path.append('../osr') import gdaltest +pytestmark = pytest.mark.require_driver('GRIB') + + def has_jp2kdrv(): for i in range(gdal.GetDriverCount()): if gdal.GetDriver(i).ShortName.startswith('JP2'): @@ -53,15 +56,10 @@ def has_jp2kdrv(): # Do a simple checksum on our test file -def grib_1(): - - gdaltest.grib_drv = gdal.GetDriverByName('GRIB') - if gdaltest.grib_drv is None: - return 'skip' - +def test_grib_1(): # Test proj4 presence import osr_ct - osr_ct.osr_ct_1() + osr_ct.test_osr_ct_1() tst = gdaltest.GDALTest('GRIB', 'grib/ds.mint.bin', 2, 46927) return tst.testOpen() @@ -70,10 +68,7 @@ def grib_1(): ############################################################################### # Test a small GRIB 1 sample file. -def grib_2(): - - if gdaltest.grib_drv is None: - return 'skip' +def test_grib_2(): tst = gdaltest.GDALTest('GRIB', 'grib/Sample_QuikSCAT.grb', 4, 50714) return tst.testOpen() @@ -83,10 +78,7 @@ def grib_2(): # we sort-of-support per ticket Test a small GRIB 1 sample file. -def grib_read_different_sizes_messages(): - - if gdaltest.grib_drv is None: - return 'skip' +def test_grib_read_different_sizes_messages(): tst = gdaltest.GDALTest('GRIB', 'grib/bug3246.grb', 4, 4081) gdal.PushErrorHandler('CPLQuietErrorHandler') @@ -104,34 +96,22 @@ def grib_read_different_sizes_messages(): # Check nodata -def grib_grib2_read_nodata(): - - if gdaltest.grib_drv is None: - return 'skip' +def test_grib_grib2_read_nodata(): ds = gdal.Open('data/grib/ds.mint.bin') - if ds.GetRasterBand(1).GetNoDataValue() != 9999: - return 'fail' - if ds.GetRasterBand(2).GetNoDataValue() != 9999: - return 'fail' + assert ds.GetRasterBand(1).GetNoDataValue() == 9999 + assert ds.GetRasterBand(2).GetNoDataValue() == 9999 md = ds.GetRasterBand(1).GetMetadata() expected_md = {'GRIB_REF_TIME': ' 1203613200 sec UTC', 'GRIB_PDS_TEMPLATE_ASSEMBLED_VALUES': '0 5 2 0 0 255 255 1 19 1 0 0 255 -1 -2147483647 2008 2 22 12 0 0 1 0 3 255 1 12 1 0', 'GRIB_VALID_TIME': ' 1203681600 sec UTC', 'GRIB_FORECAST_SECONDS': '68400 sec', 'GRIB_UNIT': '[C]', 'GRIB_PDS_TEMPLATE_NUMBERS': '0 5 2 0 0 0 255 255 1 0 0 0 19 1 0 0 0 0 0 255 129 255 255 255 255 7 216 2 22 12 0 0 1 0 0 0 0 3 255 1 0 0 0 12 1 0 0 0 0', 'GRIB_DISCIPLINE': '0(Meteorological)', 'GRIB_PDS_PDTN': '8', 'GRIB_COMMENT': 'Minimum temperature [C]', 'GRIB_SHORT_NAME': '0-SFC', 'GRIB_ELEMENT': 'MinT'} for k in expected_md: - if k not in md or md[k] != expected_md[k]: - gdaltest.post_reason('Did not get expected metadata') - print(md) - return 'fail' + assert k in md and md[k] == expected_md[k], 'Did not get expected metadata' - return 'success' ############################################################################### # Check grib units (#3606) -def grib_read_units(): - - if gdaltest.grib_drv is None: - return 'skip' +def test_grib_read_units(): gdal.Unlink('tmp/ds.mint.bin.aux.xml') @@ -139,14 +119,12 @@ def grib_read_units(): ds = gdal.Open('tmp/ds.mint.bin') md = ds.GetRasterBand(1).GetMetadata() if md['GRIB_UNIT'] != '[C]' or md['GRIB_COMMENT'] != 'Minimum temperature [C]': - gdaltest.post_reason('fail') print(md) - return 'success' + return ds.GetRasterBand(1).ComputeStatistics(False) if abs(ds.GetRasterBand(1).GetMinimum() - 13) > 1: - gdaltest.post_reason('fail') print(ds.GetRasterBand(1).GetMinimum()) - return 'success' + return ds = None os.unlink('tmp/ds.mint.bin.aux.xml') @@ -156,30 +134,23 @@ def grib_read_units(): gdal.SetConfigOption('GRIB_NORMALIZE_UNITS', None) md = ds.GetRasterBand(1).GetMetadata() if md['GRIB_UNIT'] != '[K]' or md['GRIB_COMMENT'] != 'Minimum temperature [K]': - gdaltest.post_reason('fail') print(md) - return 'success' + return ds.GetRasterBand(1).ComputeStatistics(False) if abs(ds.GetRasterBand(1).GetMinimum() - 286) > 1: - gdaltest.post_reason('fail') print(ds.GetRasterBand(1).GetMinimum()) - return 'success' + return ds = None gdal.GetDriverByName('GRIB').Delete('tmp/ds.mint.bin') - return 'success' - ############################################################################### # Handle geotransform for 1xn or nx1 grids. The geotransform was faulty when # grib files had one cell in either direction for geographic projections. See # ticket #5532 -def grib_read_geotransform_one_n_or_n_one(): - - if gdaltest.grib_drv is None: - return 'skip' +def test_grib_read_geotransform_one_n_or_n_one(): ds = gdal.Open('data/grib/one_one.grib2') egt = (-114.25, 0.5, 0.0, 47.250, 0.0, -0.5) @@ -187,212 +158,136 @@ def grib_read_geotransform_one_n_or_n_one(): ds = None if gt != egt: print(gt, '!=', egt) - gdaltest.post_reason('Invalid geotransform') - return 'fail' - return 'success' - + pytest.fail('Invalid geotransform') + ############################################################################### # This is more a /vsizip/ file test than a GRIB one, but could not easily # come up with a pure /vsizip/ test case, so here's a real world use # case (#5530). -def grib_read_vsizip(): - - if gdaltest.grib_drv is None: - return 'skip' +def test_grib_read_vsizip(): ds = gdal.Open('/vsizip/data/grib/gfs.t00z.mastergrb2f03.zip/gfs.t00z.mastergrb2f03') - if ds is None: - return 'fail' - - return 'success' + assert ds is not None ############################################################################### # Write PDS numbers to all bands -def grib_grib2_test_grib_pds_all_bands(): - - if gdaltest.grib_drv is None: - return 'skip' +def test_grib_grib2_test_grib_pds_all_bands(): ds = gdal.Open('/vsizip/data/grib/gfs.t00z.mastergrb2f03.zip/gfs.t00z.mastergrb2f03') - if ds is None: - return 'fail' + assert ds is not None band = ds.GetRasterBand(2) md = band.GetMetadataItem('GRIB_PDS_TEMPLATE_NUMBERS') ds = None - if md is None: - gdaltest.post_reason('Failed to fetch pds numbers (#5144)') - return 'fail' + assert md is not None, 'Failed to fetch pds numbers (#5144)' gdal.SetConfigOption('GRIB_PDS_ALL_BANDS', 'OFF') ds = gdal.Open('/vsizip/data/grib/gfs.t00z.mastergrb2f03.zip/gfs.t00z.mastergrb2f03') - if ds is None: - return 'fail' + assert ds is not None band = ds.GetRasterBand(2) md = band.GetMetadataItem('GRIB_PDS_TEMPLATE_NUMBERS') ds = None - if md is not None: - gdaltest.post_reason('Got pds numbers, when disabled (#5144)') - return 'fail' - return 'success' + assert md is None, 'Got pds numbers, when disabled (#5144)' ############################################################################### # Test support for template 4.15 (#5768) -def grib_grib2_read_template_4_15(): - - if gdaltest.grib_drv is None: - return 'skip' +def test_grib_grib2_read_template_4_15(): import test_cli_utilities if test_cli_utilities.get_gdalinfo_path() is None: - return 'skip' + pytest.skip() ret, err = gdaltest.runexternal_out_and_err(test_cli_utilities.get_gdalinfo_path() + ' data/grib/template_4_15.grb2 -checksum') # This is a JPEG2000 compressed file, so just check we can open it or that we get a message saying there's no JPEG2000 driver available - if ret.find('Checksum=') < 0 and err.find('Is the JPEG2000 driver available?') < 0: - gdaltest.post_reason('Could not open file') - print(ret) - print(err) - return 'fail' - - # ds = gdal.Open('data/template4_15.grib') - # if ds is None: - # return 'fail' - - return 'success' + assert ret.find('Checksum=') >= 0 or err.find('Is the JPEG2000 driver available?') >= 0, \ + 'Could not open file' ############################################################################### # Test support for PNG compressed -def grib_grib2_read_png(): - - if gdaltest.grib_drv is None: - return 'skip' +def test_grib_grib2_read_png(): if gdal.GetDriverByName('PNG') is None: - return 'skip' + pytest.skip() ds = gdal.Open('data/grib/MRMS_EchoTop_18_00.50_20161015-133230.grib2') cs = ds.GetRasterBand(1).Checksum() - if cs != 41854: - gdaltest.post_reason('Could not open file') - print(cs) - return 'fail' - - return 'success' + assert cs == 41854, 'Could not open file' ############################################################################### # Test support for GRIB2 Section 4 Template 32, Analysis or forecast at a horizontal level or in a horizontal layer at a point in time for synthetic satellite data. -def grib_grib2_read_template_4_32(): - - if gdaltest.grib_drv is None: - return 'skip' +def test_grib_grib2_read_template_4_32(): # First band extracted from http://nomads.ncep.noaa.gov/pub/data/nccf/com/hur/prod/hwrf.2017102006/twenty-se27w.2017102006.hwrfsat.core.0p02.f000.grb2 ds = gdal.Open('data/grib/twenty-se27w.2017102006.hwrfsat.core.0p02.f000_truncated.grb2') cs = ds.GetRasterBand(1).Checksum() - if cs != 19911: - gdaltest.post_reason('Could not open file') - print(cs) - return 'fail' + assert cs == 19911, 'Could not open file' md = ds.GetRasterBand(1).GetMetadata() expected_md = {'GRIB_REF_TIME': ' 1508479200 sec UTC', 'GRIB_VALID_TIME': ' 1508479200 sec UTC', 'GRIB_FORECAST_SECONDS': '0 sec', 'GRIB_UNIT': '[C]', 'GRIB_PDS_TEMPLATE_NUMBERS': '5 7 2 0 0 0 0 0 1 0 0 0 0 1 0 31 1 29 67 140 2 0 0 238 217', 'GRIB_PDS_PDTN': '32', 'GRIB_COMMENT': 'Brightness Temperature [C]', 'GRIB_SHORT_NAME': '0 undefined', 'GRIB_ELEMENT': 'BRTEMP', 'GRIB_PDS_TEMPLATE_ASSEMBLED_VALUES': '5 7 2 0 0 0 0 1 0 1 31 285 17292 2 61145'} for k in expected_md: - if k not in md or md[k] != expected_md[k]: - gdaltest.post_reason('Did not get expected metadata') - print(md) - return 'fail' + assert k in md and md[k] == expected_md[k], 'Did not get expected metadata' - return 'success' ############################################################################### # GRIB2 file with all 0 data -def grib_grib2_read_all_zero_data(): - - if gdaltest.grib_drv is None: - return 'skip' +def test_grib_grib2_read_all_zero_data(): # From http://dd.weather.gc.ca/model_wave/great_lakes/erie/grib2/00/CMC_rdwps_lake-erie_ICEC_SFC_0_latlon0.05x0.05_2017111800_P000.grib2 ds = gdal.Open('data/grib/CMC_rdwps_lake-erie_ICEC_SFC_0_latlon0.05x0.05_2017111800_P000.grib2') cs = ds.GetRasterBand(1).Checksum() - if cs != 0: - gdaltest.post_reason('Could not open file') - print(cs) - return 'fail' + assert cs == 0, 'Could not open file' md = ds.GetRasterBand(1).GetMetadata() expected_md = {'GRIB_REF_TIME': ' 1510963200 sec UTC', 'GRIB_VALID_TIME': ' 1510963200 sec UTC', 'GRIB_FORECAST_SECONDS': '0 sec', 'GRIB_UNIT': '[Proportion]', 'GRIB_PDS_TEMPLATE_NUMBERS': '2 0 0 0 0 0 0 0 1 0 0 0 0 1 0 0 0 0 0 255 255 255 255 255 255', 'GRIB_PDS_PDTN': '0', 'GRIB_COMMENT': 'Ice cover [Proportion]', 'GRIB_SHORT_NAME': '0-SFC', 'GRIB_ELEMENT': 'ICEC'} for k in expected_md: - if k not in md or md[k] != expected_md[k]: - gdaltest.post_reason('Did not get expected metadata') - print(md) - return 'fail' + assert k in md and md[k] == expected_md[k], 'Did not get expected metadata' - return 'success' ############################################################################### # GRIB1 file with rotate pole lonlat -def grib_grib2_read_rotated_pole_lonlat(): - - if gdaltest.grib_drv is None: - return 'skip' +def test_grib_grib2_read_rotated_pole_lonlat(): ds = gdal.Open('/vsisparse/data/grib/rotated_pole.grb.xml') - if ds.RasterXSize != 726 or ds.RasterYSize != 550: - gdaltest.post_reason('Did not get expected dimensions') - print(ds.RasterXSize) - print(ds.RasterYSize) - return 'fail' + assert ds.RasterXSize == 726 and ds.RasterYSize == 550, \ + 'Did not get expected dimensions' projection = ds.GetProjectionRef() expected_projection = """PROJCS["unnamed",GEOGCS["Coordinate System imported from GRIB file",DATUM["unknown",SPHEROID["Sphere",6367470,0]],PRIMEM["Greenwich",0],UNIT["degree",0.0174532925199433]],PROJECTION["Rotated_pole"],EXTENSION["PROJ4","+proj=ob_tran +lon_0=-15 +o_proj=longlat +o_lon_p=0 +o_lat_p=30 +a=6367470 +b=6367470 +to_meter=0.0174532925199 +wktext"]]""" - if projection != expected_projection: - gdaltest.post_reason('Did not get expected projection') - print(projection) - return 'fail' + assert projection == expected_projection, 'Did not get expected projection' gt = ds.GetGeoTransform() expected_gt = (-30.25, 0.1, 0.0, 24.15, 0.0, -0.1) - if max([abs(gt[i] - expected_gt[i]) for i in range(6)]) > 1e-3: - gdaltest.post_reason('Did not get expected geotransform') - print(gt) - return 'fail' + assert max([abs(gt[i] - expected_gt[i]) for i in range(6)]) <= 1e-3, \ + 'Did not get expected geotransform' md = ds.GetRasterBand(1).GetMetadata() expected_md = {'GRIB_REF_TIME': ' 1503295200 sec UTC', 'GRIB_VALID_TIME': ' 1503295200 sec UTC', 'GRIB_FORECAST_SECONDS': '0 sec', 'GRIB_UNIT': '[m^2/s^2]', 'GRIB_COMMENT': 'Geopotential [m^2/s^2]', 'GRIB_SHORT_NAME': '0-HTGL', 'GRIB_ELEMENT': 'GP'} for k in expected_md: - if k not in md or md[k] != expected_md[k]: - gdaltest.post_reason('Did not get expected metadata') - print(md) - return 'fail' + assert k in md and md[k] == expected_md[k], 'Did not get expected metadata' - return 'success' ############################################################################### # Test support for GRIB2 Section 4 Template 40, Analysis or forecast at a horizontal level or in a horizontal layer at a point in time for atmospheric chemical constituents -def grib_grib2_read_template_4_40(): - - if gdaltest.grib_drv is None: - return 'skip' +def test_grib_grib2_read_template_4_40(): # We could use some other encoding that JP2K... if not has_jp2kdrv(): - return 'skip' + pytest.skip() # First band extracted from https://download.regional.atmosphere.copernicus.eu/services/CAMS50?token=__M0bChV6QsoOFqHz31VRqnpr4GhWPtcpaRy3oeZjBNSg__&grid=0.1&model=ENSEMBLE&package=ANALYSIS_PM10_SURFACE&time=-24H-1H&referencetime=2017-09-12T00:00:00Z&format=GRIB2&licence=yes # with data nullified @@ -400,308 +295,207 @@ def grib_grib2_read_template_4_40(): md = ds.GetRasterBand(1).GetMetadata() expected_md = {'GRIB_REF_TIME': ' 1505088000 sec UTC', 'GRIB_PDS_TEMPLATE_ASSEMBLED_VALUES': '20 0 40008 0 255 99 0 0 1 0 1 -127 -2147483647 255 -127 -2147483647', 'GRIB_VALID_TIME': ' 1505088000 sec UTC', 'GRIB_FORECAST_SECONDS': '0 sec', 'GRIB_UNIT': '[kg/(m^3)]', 'GRIB_PDS_TEMPLATE_NUMBERS': '20 0 156 72 0 255 99 0 0 0 1 0 0 0 0 1 255 255 255 255 255 255 255 255 255 255 255', 'GRIB_PDS_PDTN': '40', 'GRIB_COMMENT': 'Mass Density (Concentration) [kg/(m^3)]', 'GRIB_SHORT_NAME': '0-SFC', 'GRIB_ELEMENT': 'MASSDEN'} for k in expected_md: - if k not in md or md[k] != expected_md[k]: - gdaltest.post_reason('Did not get expected metadata') - print(md) - return 'fail' + assert k in md and md[k] == expected_md[k], 'Did not get expected metadata' - return 'success' ############################################################################### # Test support for a unhandled GRIB2 Section 4 Template -def grib_grib2_read_template_4_unhandled(): - - if gdaltest.grib_drv is None: - return 'skip' +def test_grib_grib2_read_template_4_unhandled(): with gdaltest.error_handler(): ds = gdal.Open('data/grib/template_4_65535.grb2') md = ds.GetRasterBand(1).GetMetadata() expected_md = {'GRIB_PDS_TEMPLATE_NUMBERS': '0 1 2 3 4 5', 'GRIB_PDS_PDTN': '65535'} for k in expected_md: - if k not in md or md[k] != expected_md[k]: - gdaltest.post_reason('Did not get expected metadata') - print(md) - return 'fail' + assert k in md and md[k] == expected_md[k], 'Did not get expected metadata' - return 'success' ############################################################################### # Test reading GRIB2 Transverse Mercator grid -def grib_grib2_read_transverse_mercator(): - - if gdaltest.grib_drv is None: - return 'skip' +def test_grib_grib2_read_transverse_mercator(): ds = gdal.Open('data/grib/transverse_mercator.grb2') projection = ds.GetProjectionRef() expected_projection = """PROJCS["unnamed",GEOGCS["Coordinate System imported from GRIB file",DATUM["unknown",SPHEROID["Sphere",6367470,0]],PRIMEM["Greenwich",0],UNIT["degree",0.0174532925199433]],PROJECTION["Transverse_Mercator"],PARAMETER["latitude_of_origin",0],PARAMETER["central_meridian",-117],PARAMETER["scale_factor",0.9996],PARAMETER["false_easting",500000],PARAMETER["false_northing",0],UNIT["Metre",1]]""" - if projection != expected_projection: - gdaltest.post_reason('Did not get expected projection') - print(projection) - return 'fail' + assert projection == expected_projection, 'Did not get expected projection' gt = ds.GetGeoTransform() expected_gt = (440720.0, 60.0, 0.0, 3751320.0, 0.0, -60.0) - if max([abs(gt[i] - expected_gt[i]) for i in range(6)]) > 1e-3: - gdaltest.post_reason('Did not get expected geotransform') - print(gt) - return 'fail' - - return 'success' + assert max([abs(gt[i] - expected_gt[i]) for i in range(6)]) <= 1e-3, \ + 'Did not get expected geotransform' ############################################################################### # Test reading GRIB2 Mercator grid -def grib_grib2_read_mercator(): - - if gdaltest.grib_drv is None: - return 'skip' +def test_grib_grib2_read_mercator(): if gdaltest.have_proj4 == 0: - return 'skip' + pytest.skip() ds = gdal.Open('data/grib/mercator.grb2') projection = ds.GetProjectionRef() expected_projection = """PROJCS["unnamed",GEOGCS["Coordinate System imported from GRIB file",DATUM["WGS_1984",SPHEROID["WGS 84",6378137,298.257223563]],PRIMEM["Greenwich",0],UNIT["degree",0.0174532925199433]],PROJECTION["Mercator_1SP"],PARAMETER["central_meridian",0],PARAMETER["scale_factor",1],PARAMETER["false_easting",0],PARAMETER["false_northing",0],UNIT["Metre",1]]""" - if projection != expected_projection: - gdaltest.post_reason('Did not get expected projection') - print(projection) - return 'fail' + assert projection == expected_projection, 'Did not get expected projection' gt = ds.GetGeoTransform() expected_gt = (-13095853.598139772, 72.237, 0.0, 3991876.4600486886, 0.0, -72.237) - if max([abs(gt[i] - expected_gt[i]) for i in range(6)]) > 1e-3: - gdaltest.post_reason('Did not get expected geotransform') - print(gt) - return 'fail' + assert max([abs(gt[i] - expected_gt[i]) for i in range(6)]) <= 1e-3, \ + 'Did not get expected geotransform' - return 'success' ############################################################################### # Test reading GRIB2 Mercator grid -def grib_grib2_read_mercator_2sp(): - - if gdaltest.grib_drv is None: - return 'skip' +def test_grib_grib2_read_mercator_2sp(): if gdaltest.have_proj4 == 0: - return 'skip' + pytest.skip() ds = gdal.Open('data/grib/mercator_2sp.grb2') projection = ds.GetProjectionRef() expected_projection = """PROJCS["unnamed",GEOGCS["Coordinate System imported from GRIB file",DATUM["WGS_1984",SPHEROID["WGS 84",6378137,298.257223563]],PRIMEM["Greenwich",0],UNIT["degree",0.0174532925199433]],PROJECTION["Mercator_2SP"],PARAMETER["standard_parallel_1",33.5],PARAMETER["central_meridian",0],PARAMETER["false_easting",0],PARAMETER["false_northing",0],UNIT["Metre",1]]""" - if projection != expected_projection: - gdaltest.post_reason('Did not get expected projection') - print(projection) - return 'fail' + assert projection == expected_projection, 'Did not get expected projection' gt = ds.GetGeoTransform() expected_gt = (-10931598.94836207, 60.299, 0.0, 3332168.629121481, 0.0, -60.299) - if max([abs(gt[i] - expected_gt[i]) for i in range(6)]) > 1e-3: - gdaltest.post_reason('Did not get expected geotransform') - print(gt) - return 'fail' + assert max([abs(gt[i] - expected_gt[i]) for i in range(6)]) <= 1e-3, \ + 'Did not get expected geotransform' - return 'success' ############################################################################### # Test reading GRIB2 Lambert Conformal Conic grid -def grib_grib2_read_lcc(): - - if gdaltest.grib_drv is None: - return 'skip' +def test_grib_grib2_read_lcc(): if gdaltest.have_proj4 == 0: - return 'skip' + pytest.skip() ds = gdal.Open('data/grib/lambert_conformal_conic.grb2') projection = ds.GetProjectionRef() expected_projection = """PROJCS["unnamed",GEOGCS["Coordinate System imported from GRIB file",DATUM["WGS_1984",SPHEROID["WGS 84",6378137,298.257223563]],PRIMEM["Greenwich",0],UNIT["degree",0.0174532925199433]],PROJECTION["Lambert_Conformal_Conic_2SP"],PARAMETER["standard_parallel_1",33],PARAMETER["standard_parallel_2",34],PARAMETER["latitude_of_origin",33.5],PARAMETER["central_meridian",117],PARAMETER["false_easting",0],PARAMETER["false_northing",0],UNIT["Metre",1]]""" - if projection != expected_projection: - gdaltest.post_reason('Did not get expected projection') - print(projection) - return 'fail' + assert projection == expected_projection, 'Did not get expected projection' gt = ds.GetGeoTransform() expected_gt = (8974734.737685828, 60.021, 0.0, 6235918.9698001575, 0.0, -60.021) - if max([abs(gt[i] - expected_gt[i]) for i in range(6)]) > 1e-3: - gdaltest.post_reason('Did not get expected geotransform') - print(gt) - return 'fail' + assert max([abs(gt[i] - expected_gt[i]) for i in range(6)]) <= 1e-3, \ + 'Did not get expected geotransform' - return 'success' ############################################################################### # Test reading GRIB2 Polar Stereographic grid -def grib_grib2_read_polar_stereo(): - - if gdaltest.grib_drv is None: - return 'skip' +def test_grib_grib2_read_polar_stereo(): if gdaltest.have_proj4 == 0: - return 'skip' + pytest.skip() ds = gdal.Open('data/grib/polar_stereographic.grb2') projection = ds.GetProjectionRef() expected_projection = """PROJCS["unnamed",GEOGCS["Coordinate System imported from GRIB file",DATUM["WGS_1984",SPHEROID["WGS 84",6378137,298.257223563]],PRIMEM["Greenwich",0],UNIT["degree",0.0174532925199433]],PROJECTION["Polar_Stereographic"],PARAMETER["latitude_of_origin",60],PARAMETER["central_meridian",0],PARAMETER["scale_factor",1],PARAMETER["false_easting",0],PARAMETER["false_northing",0],UNIT["Metre",1]]""" - if projection != expected_projection: - gdaltest.post_reason('Did not get expected projection') - print(projection) - return 'fail' + assert projection == expected_projection, 'Did not get expected projection' gt = ds.GetGeoTransform() expected_gt = (-5621962.072511509, 71.86, 0.0, 2943991.8007649644, 0.0, -71.86) - if max([abs(gt[i] - expected_gt[i]) for i in range(6)]) > 1e-3: - gdaltest.post_reason('Did not get expected geotransform') - print(gt) - return 'fail' + assert max([abs(gt[i] - expected_gt[i]) for i in range(6)]) <= 1e-3, \ + 'Did not get expected geotransform' - return 'success' ############################################################################### # Test reading GRIB2 Albers Equal Area grid -def grib_grib2_read_aea(): - - if gdaltest.grib_drv is None: - return 'skip' +def test_grib_grib2_read_aea(): if gdaltest.have_proj4 == 0: - return 'skip' + pytest.skip() ds = gdal.Open('data/grib/albers_equal_area.grb2') projection = ds.GetProjectionRef() expected_projection = """PROJCS["unnamed",GEOGCS["Coordinate System imported from GRIB file",DATUM["WGS_1984",SPHEROID["WGS 84",6378137,298.257223563]],PRIMEM["Greenwich",0],UNIT["degree",0.0174532925199433]],PROJECTION["Albers_Conic_Equal_Area"],PARAMETER["standard_parallel_1",33],PARAMETER["standard_parallel_2",34],PARAMETER["latitude_of_center",33.5],PARAMETER["longitude_of_center",117],PARAMETER["false_easting",0],PARAMETER["false_northing",0],UNIT["Metre",1]]""" - if projection != expected_projection: - gdaltest.post_reason('Did not get expected projection') - print(projection) - return 'fail' + assert projection == expected_projection, 'Did not get expected projection' gt = ds.GetGeoTransform() expected_gt = (8974979.714292033, 60.022, 0.0, 6235686.52464211, 0.0, -60.022) - if max([abs(gt[i] - expected_gt[i]) for i in range(6)]) > 1e-3: - gdaltest.post_reason('Did not get expected geotransform') - print(gt) - return 'fail' + assert max([abs(gt[i] - expected_gt[i]) for i in range(6)]) <= 1e-3, \ + 'Did not get expected geotransform' - return 'success' ############################################################################### # Test reading GRIB2 Lambert Azimuthal Equal Area grid -def grib_grib2_read_laea(): - - if gdaltest.grib_drv is None: - return 'skip' +def test_grib_grib2_read_laea(): if gdaltest.have_proj4 == 0: - return 'skip' + pytest.skip() ds = gdal.Open('data/grib/lambert_azimuthal_equal_area.grb2') projection = ds.GetProjectionRef() expected_projection = """PROJCS["unnamed",GEOGCS["Coordinate System imported from GRIB file",DATUM["WGS_1984",SPHEROID["WGS 84",6378137,298.257223563]],PRIMEM["Greenwich",0],UNIT["degree",0.0174532925199433]],PROJECTION["Lambert_Azimuthal_Equal_Area"],PARAMETER["latitude_of_center",33.5],PARAMETER["longitude_of_center",243],PARAMETER["false_easting",0],PARAMETER["false_northing",0],UNIT["Metre",1]]""" - if projection != expected_projection: - gdaltest.post_reason('Did not get expected projection') - print(projection) - return 'fail' + assert projection == expected_projection, 'Did not get expected projection' gt = ds.GetGeoTransform() expected_gt = (-59384.01063035424, 60.021, 0.0, 44812.5792223211, 0.0, -60.021) - if max([abs(gt[i] - expected_gt[i]) for i in range(6)]) > 1e-3: - gdaltest.post_reason('Did not get expected geotransform') - print(gt) - return 'fail' + assert max([abs(gt[i] - expected_gt[i]) for i in range(6)]) <= 1e-3, \ + 'Did not get expected geotransform' - return 'success' ############################################################################### # Test reading GRIB2 with Grid point data - IEEE Floating Point Data (template 5.4) -def grib_grib2_read_template_5_4_grid_point_ieee_floating_point(): - - if gdaltest.grib_drv is None: - return 'skip' +def test_grib_grib2_read_template_5_4_grid_point_ieee_floating_point(): ds = gdal.Open('data/grib/ieee754_single.grb2') cs = ds.GetRasterBand(1).Checksum() - if cs != 4727: - gdaltest.post_reason('Did not get expected checksum') - print(cs) - return 'fail' + assert cs == 4727, 'Did not get expected checksum' ds = gdal.Open('data/grib/ieee754_double.grb2') cs = ds.GetRasterBand(1).Checksum() - if cs != 4727: - gdaltest.post_reason('Did not get expected checksum') - print(cs) - return 'fail' + assert cs == 4727, 'Did not get expected checksum' - return 'success' ############################################################################### # Test reading GRIB2 with NBITS=0 and DECIMAL_SCALE !=0 -def grib_grib2_read_section_5_nbits_zero_decimal_scaled(): - - if gdaltest.grib_drv is None: - return 'skip' +def test_grib_grib2_read_section_5_nbits_zero_decimal_scaled(): ds = gdal.Open('data/grib/simple_packing_nbits_zero_decimal_scaled.grb2') cs = ds.GetRasterBand(1).Checksum() - if cs != 5: - gdaltest.post_reason('Did not get expected checksum') - print(cs) - return 'fail' + assert cs == 5, 'Did not get expected checksum' if gdal.GetDriverByName('PNG') is not None: ds = gdal.Open('data/grib/png_nbits_zero_decimal_scaled.grb2') cs = ds.GetRasterBand(1).Checksum() - if cs != 5: - gdaltest.post_reason('Did not get expected checksum') - print(cs) - return 'fail' + assert cs == 5, 'Did not get expected checksum' if has_jp2kdrv(): ds = gdal.Open('data/grib/jpeg2000_nbits_zero_decimal_scaled.grb2') cs = ds.GetRasterBand(1).Checksum() - if cs != 5: - gdaltest.post_reason('Did not get expected checksum') - print(cs) - return 'fail' + assert cs == 5, 'Did not get expected checksum' - return 'success' ############################################################################### # Test reading GRIB2 with complex packing and spatial differencing of order 1 -def grib_grib2_read_spatial_differencing_order_1(): - - if gdaltest.grib_drv is None: - return 'skip' +def test_grib_grib2_read_spatial_differencing_order_1(): ds = gdal.Open('data/grib/spatial_differencing_order_1.grb2') cs = ds.GetRasterBand(1).Checksum() @@ -709,16 +503,12 @@ def grib_grib2_read_spatial_differencing_order_1(): gdaltest.post_reason('Did not get expected checksum') print(cs) - return 'success' ############################################################################### # Test GRIB2 creation options -def grib_grib2_write_creation_options(): - - if gdaltest.grib_drv is None: - return 'skip' +def test_grib_grib2_write_creation_options(): tmpfilename = '/vsimem/out.grb2' gdal.Translate(tmpfilename, 'data/byte.tif', format='GRIB', @@ -734,10 +524,7 @@ def grib_grib2_write_creation_options(): md = ds.GetRasterBand(1).GetMetadata() expected_md = {'GRIB_IDS': 'CENTER=85(Toulouse) SUBCENTER=3 MASTER_TABLE=5 LOCAL_TABLE=0 SIGNF_REF_TIME=0(Analysis) REF_TIME=2017-09-11T12:34:56Z PROD_STATUS=2(Research) TYPE=0(Analysis)', 'GRIB_PDS_TEMPLATE_NUMBERS': '20 0 156 72 0 255 99 0 0 0 1 0 0 0 0 1 255 255 255 255 255 255 255 255 255 255 255', 'GRIB_DISCIPLINE': '1(Hydrological)', 'GRIB_PDS_PDTN': '40'} for k in expected_md: - if k not in md or md[k] != expected_md[k]: - gdaltest.post_reason('Did not get expected metadata') - print(md) - return 'fail' + assert k in md and md[k] == expected_md[k], 'Did not get expected metadata' ds = None gdal.Unlink(tmpfilename) @@ -748,18 +535,13 @@ def grib_grib2_write_creation_options(): "PDS_PDTN=40", "PDS_TEMPLATE_NUMBERS=20 0 156 72 0 255 99 0 0 0 1 0 0 0 0 1 255 255 255 255 255 255 255 255 255 255 255 0extra" ]) - if out_ds is None: - gdaltest.post_reason('failure') - return 'fail' + assert out_ds is not None out_ds = None ds = gdal.Open(tmpfilename) md = ds.GetRasterBand(1).GetMetadata() expected_md = {'GRIB_PDS_PDTN': '40', 'GRIB_PDS_TEMPLATE_NUMBERS': '20 0 156 72 0 255 99 0 0 0 1 0 0 0 0 1 255 255 255 255 255 255 255 255 255 255 255 0'} for k in expected_md: - if k not in md or md[k] != expected_md[k]: - gdaltest.post_reason('Did not get expected metadata') - print(md) - return 'fail' + assert k in md and md[k] == expected_md[k], 'Did not get expected metadata' ds = None gdal.Unlink(tmpfilename) @@ -770,9 +552,7 @@ def grib_grib2_write_creation_options(): "PDS_PDTN=40", "PDS_TEMPLATE_NUMBERS=20 0 156 72 0 255 99 0 0 0 1 0 0 0 0 1 255 255 255 255 255 255 255 255 255 255" ]) - if out_ds is not None: - gdaltest.post_reason('failure') - return 'fail' + assert out_ds is None gdal.Unlink(tmpfilename) # Test with PDS_TEMPLATE_ASSEMBLED_VALUES @@ -785,10 +565,7 @@ def grib_grib2_write_creation_options(): md = ds.GetRasterBand(1).GetMetadata() expected_md = {'GRIB_PDS_PDTN': '40', 'GRIB_PDS_TEMPLATE_ASSEMBLED_VALUES': '20 0 40008 0 255 99 0 0 1 0 1 -127 -2147483647 255 -127 -2147483647'} for k in expected_md: - if k not in md or md[k] != expected_md[k]: - gdaltest.post_reason('Did not get expected metadata') - print(md) - return 'fail' + assert k in md and md[k] == expected_md[k], 'Did not get expected metadata' ds = None gdal.Unlink(tmpfilename) @@ -799,18 +576,13 @@ def grib_grib2_write_creation_options(): "PDS_PDTN=40", "PDS_TEMPLATE_ASSEMBLED_VALUES=20 0 40008 0 255 99 0 0 1 0 1 -127 -2147483647 255 -127 -2147483647 0extra" ]) - if out_ds is None: - gdaltest.post_reason('failure') - return 'fail' + assert out_ds is not None out_ds = None ds = gdal.Open(tmpfilename) md = ds.GetRasterBand(1).GetMetadata() expected_md = {'GRIB_PDS_PDTN': '40', 'GRIB_PDS_TEMPLATE_ASSEMBLED_VALUES': '20 0 40008 0 255 99 0 0 1 0 1 -127 -2147483647 255 -127 -2147483647'} for k in expected_md: - if k not in md or md[k] != expected_md[k]: - gdaltest.post_reason('Did not get expected metadata') - print(md) - return 'fail' + assert k in md and md[k] == expected_md[k], 'Did not get expected metadata' ds = None gdal.Unlink(tmpfilename) @@ -821,9 +593,7 @@ def grib_grib2_write_creation_options(): "PDS_PDTN=40", "PDS_TEMPLATE_ASSEMBLED_VALUES=20 0 40008 0 255 99 0 0 1 0 1 -127 -2147483647 255 -127" ]) - if out_ds is not None: - gdaltest.post_reason('failure') - return 'fail' + assert out_ds is None gdal.Unlink(tmpfilename) # Test with PDS_TEMPLATE_ASSEMBLED_VALUES with variable number of elements @@ -836,10 +606,7 @@ def grib_grib2_write_creation_options(): md = ds.GetRasterBand(1).GetMetadata() expected_md = {'GRIB_PDS_PDTN': '32', 'GRIB_PDS_TEMPLATE_ASSEMBLED_VALUES': '5 7 2 0 0 0 0 1 0 2 31 285 17292 2 61145 31 285 17292 2 61145'} for k in expected_md: - if k not in md or md[k] != expected_md[k]: - gdaltest.post_reason('Did not get expected metadata') - print(md) - return 'fail' + assert k in md and md[k] == expected_md[k], 'Did not get expected metadata' ds = None gdal.Unlink(tmpfilename) @@ -850,9 +617,7 @@ def grib_grib2_write_creation_options(): "PDS_PDTN=32", "PDS_TEMPLATE_ASSEMBLED_VALUES=5 7 2 0 0 0 0 1 0 2 31 285 17292 2 61145 31 285 17292 2" ]) - if out_ds is not None: - gdaltest.post_reason('failure') - return 'fail' + assert out_ds is None gdal.Unlink(tmpfilename) # Test with PDS_TEMPLATE_ASSEMBLED_VALUES with variable number of elements, and extra elements @@ -866,10 +631,7 @@ def grib_grib2_write_creation_options(): md = ds.GetRasterBand(1).GetMetadata() expected_md = {'GRIB_PDS_PDTN': '32', 'GRIB_PDS_TEMPLATE_ASSEMBLED_VALUES': '5 7 2 0 0 0 0 1 0 2 31 285 17292 2 61145 31 285 17292 2 61145'} for k in expected_md: - if k not in md or md[k] != expected_md[k]: - gdaltest.post_reason('Did not get expected metadata') - print(md) - return 'fail' + assert k in md and md[k] == expected_md[k], 'Did not get expected metadata' ds = None gdal.Unlink(tmpfilename) @@ -883,10 +645,7 @@ def grib_grib2_write_creation_options(): md = ds.GetRasterBand(1).GetMetadata() expected_md = {'GRIB_PDS_PDTN': '32', 'GRIB_PDS_TEMPLATE_ASSEMBLED_VALUES': '5 7 2 0 0 0 0 1 0 2 31 285 17292 2 61145 31 285 17292 2 61145'} for k in expected_md: - if k not in md or md[k] != expected_md[k]: - gdaltest.post_reason('Did not get expected metadata') - print(md) - return 'fail' + assert k in md and md[k] == expected_md[k], 'Did not get expected metadata' ds = None gdal.Unlink(tmpfilename) @@ -897,19 +656,14 @@ def grib_grib2_write_creation_options(): "PDS_PDTN=65535", "PDS_TEMPLATE_NUMBERS=1 2 3 4 5" ]) - if out_ds is None: - gdaltest.post_reason('failure') - return 'fail' + assert out_ds is not None out_ds = None with gdaltest.error_handler(): ds = gdal.Open(tmpfilename) md = ds.GetRasterBand(1).GetMetadata() expected_md = {'GRIB_PDS_PDTN': '65535', 'GRIB_PDS_TEMPLATE_NUMBERS': '1 2 3 4 5'} for k in expected_md: - if k not in md or md[k] != expected_md[k]: - gdaltest.post_reason('Did not get expected metadata') - print(md) - return 'fail' + assert k in md and md[k] == expected_md[k], 'Did not get expected metadata' ds = None gdal.Unlink(tmpfilename) @@ -920,9 +674,7 @@ def grib_grib2_write_creation_options(): "PDS_PDTN=65535", "PDS_TEMPLATE_ASSEMBLED_VALUES=1 2 3 4 5" ]) - if out_ds is not None: - gdaltest.post_reason('failure') - return 'fail' + assert out_ds is None gdal.Unlink(tmpfilename) # Test with PDS_PDTN != 0 without template numbers @@ -931,9 +683,7 @@ def grib_grib2_write_creation_options(): creationOptions=[ "PDS_PDTN=32" ]) - if out_ds is not None: - gdaltest.post_reason('failure') - return 'fail' + assert out_ds is None gdal.Unlink(tmpfilename) # Test with invalid values in PDS_TEMPLATE_NUMBERS @@ -943,9 +693,7 @@ def grib_grib2_write_creation_options(): "PDS_PDTN=254", "PDS_TEMPLATE_NUMBERS=-1 256 0 0 0 0" ]) - if out_ds is None: - gdaltest.post_reason('failure') - return 'fail' + assert out_ds is not None out_ds = None gdal.Unlink(tmpfilename) @@ -957,9 +705,7 @@ def grib_grib2_write_creation_options(): # {44,21,0, {1, 1, 2,1,-1, -4, -1,-4,1,1,1, 2, 1,1,-2 ,1,-1, -4,1,-1,-4} }, "PDS_TEMPLATE_ASSEMBLED_VALUES=-1 256 -1 1 128 4000000000 -1 -4 1 1 1 65536 1 1 32768 1 -129 -4 1 -1 -4" ]) - if out_ds is None: - gdaltest.post_reason('failure') - return 'fail' + assert out_ds is not None out_ds = None gdal.Unlink(tmpfilename) @@ -971,21 +717,14 @@ def grib_grib2_write_creation_options(): "PDS_TEMPLATE_NUMBERS=20 0 156 72 0 255 99 0 0 0 1 0 0 0 0 1 255 255 255 255 255 255 255 255 255 255 255", "PDS_TEMPLATE_ASSEMBLED_VALUES=20 0 40008 0 255 99 0 0 1 0 1 -127 -2147483647 255 -127 -2147483647" ]) - if out_ds is not None: - gdaltest.post_reason('failure') - return 'fail' + assert out_ds is None gdal.Unlink(tmpfilename) - return 'success' - ############################################################################### # Test GRIB2 write support for projections -def grib_grib2_write_projections(): - - if gdaltest.grib_drv is None: - return 'skip' +def test_grib_grib2_write_projections(): filenames = ['albers_equal_area.grb2', 'lambert_azimuthal_equal_area.grb2', @@ -1002,19 +741,13 @@ def grib_grib2_write_projections(): gdal.Translate(tmpfilename, filename, format='GRIB') out_ds = gdal.Open(tmpfilename) - if src_ds.GetProjectionRef() != out_ds.GetProjectionRef(): - gdaltest.post_reason('did not get expected projection for %s' % filename) - print(out_ds.GetProjectionRef()) - print(src_ds.GetProjectionRef()) - return 'fail' + assert src_ds.GetProjectionRef() == out_ds.GetProjectionRef(), \ + ('did not get expected projection for %s' % filename) expected_gt = src_ds.GetGeoTransform() got_gt = out_ds.GetGeoTransform() - if max([abs(expected_gt[i] - got_gt[i]) for i in range(6)]) > 1e-5: - gdaltest.post_reason('did not get expected geotransform for %s' % filename) - print(got_gt) - print(expected_gt) - return 'fail' + assert max([abs(expected_gt[i] - got_gt[i]) for i in range(6)]) <= 1e-5, \ + ('did not get expected geotransform for %s' % filename) out_ds = None gdal.Unlink(tmpfilename) @@ -1032,10 +765,7 @@ def grib_grib2_write_projections(): wkt = out_ds.GetProjectionRef() out_ds = None gdal.Unlink(tmpfilename) - if wkt.find('SPHEROID["GRS80",6378137,298.257222101]') < 0: - gdaltest.post_reason('fail') - print(wkt) - return 'fail' + assert wkt.find('SPHEROID["GRS80",6378137,298.257222101]') >= 0 # Test writing Mercator_1SP with scale != 1 (will be read as Mercator_2SP) src_ds = gdal.Warp('', 'data/byte.tif', format='MEM', dstSRS="""PROJCS["unnamed", @@ -1065,15 +795,12 @@ def grib_grib2_write_projections(): expected_sr = osr.SpatialReference() expected_sr.SetFromUserInput(expected_wkt) if got_sr.IsSame(expected_sr) == 0: - gdaltest.post_reason('did not get expected projection for Mercator_1SP') print(out_ds.GetProjectionRef()) - return 'fail' + pytest.fail('did not get expected projection for Mercator_1SP') expected_gt = (-10931635.565066436, 60.297, 0.0, 3331982.221608528, 0.0, -60.297) got_gt = out_ds.GetGeoTransform() - if max([abs(expected_gt[i] - got_gt[i]) for i in range(6)]) > 1e-5: - gdaltest.post_reason('did not get expected geotransform for Mercator_1SP') - print(got_gt) - return 'fail' + assert max([abs(expected_gt[i] - got_gt[i]) for i in range(6)]) <= 1e-5, \ + 'did not get expected geotransform for Mercator_1SP' out_ds = None gdal.Unlink(tmpfilename) @@ -1104,20 +831,15 @@ def grib_grib2_write_projections(): expected_sr = osr.SpatialReference() expected_sr.SetFromUserInput(expected_wkt) if got_sr.IsSame(expected_sr) == 0: - gdaltest.post_reason('did not get expected projection for LCC_1SP') print(out_ds.GetProjectionRef()) - return 'fail' + pytest.fail('did not get expected projection for LCC_1SP') expected_gt = (8974472.884926716, 60.017, 0.0, 6235685.688523474, 0.0, -60.017) got_gt = out_ds.GetGeoTransform() - if max([abs(expected_gt[i] - got_gt[i]) for i in range(6)]) > 1e-5: - gdaltest.post_reason('did not get expected geotransform for LCC_1SP') - print(got_gt) - return 'fail' + assert max([abs(expected_gt[i] - got_gt[i]) for i in range(6)]) <= 1e-5, \ + 'did not get expected geotransform for LCC_1SP' out_ds = None gdal.Unlink(tmpfilename) - return 'success' - ############################################################################### @@ -1148,10 +870,7 @@ def _grib_read_section(filename, sect_num_to_read): # Test GRIB2 write support for data encodings -def grib_grib2_write_data_encodings(): - - if gdaltest.grib_drv is None: - return 'skip' +def test_grib_grib2_write_data_encodings(): # Template 5 numbers GS5_SIMPLE = 0 @@ -1263,16 +982,13 @@ def grib_grib2_write_data_encodings(): gdal.Translate(tmpfilename, filename, format='GRIB', creationOptions=options) error_msg = gdal.GetLastErrorMsg() - if error_msg != '': - gdaltest.post_reason('did not expect error for %s, %s' % (str(filename), str(options))) - return 'fail' + assert error_msg == '', \ + ('did not expect error for %s, %s' % (str(filename), str(options))) section5 = _grib_read_section(tmpfilename, 5) section5_template_number = struct.unpack('>h', section5[9:11])[0] - if section5_template_number != expected_section5_template_number: - gdaltest.post_reason('did not get expected section 5 template number for %s, %s' % (str(filename), str(options))) - print(section5_template_number, expected_section5_template_number) - return 'fail' + assert section5_template_number == expected_section5_template_number, \ + ('did not get expected section 5 template number for %s, %s' % (str(filename), str(options))) out_ds = gdal.Open(tmpfilename) cs = out_ds.GetRasterBand(1).Checksum() @@ -1281,10 +997,8 @@ def grib_grib2_write_data_encodings(): gdal.Unlink(tmpfilename) if not isinstance(expected_cs, tuple): expected_cs = (expected_cs,) - if cs not in expected_cs: - gdaltest.post_reason('did not get expected checksum for %s, %s' % (str(filename), str(options))) - print(cs, expected_cs) - return 'fail' + assert cs in expected_cs, \ + ('did not get expected checksum for %s, %s' % (str(filename), str(options))) if section5_template_number in (GS5_CMPLX, GS5_CMPLXSEC): if isinstance(filename, str): @@ -1292,10 +1006,8 @@ def grib_grib2_write_data_encodings(): else: ref_ds = filename expected_nd = ref_ds.GetRasterBand(1).GetNoDataValue() - if nd != expected_nd: - gdaltest.post_reason('did not get expected nodata for %s, %s' % (str(filename), str(options))) - print(nd, expected_nd) - return 'fail' + assert nd == expected_nd, \ + ('did not get expected nodata for %s, %s' % (str(filename), str(options))) # Test floating point data with dynamic < 1 test_ds = gdal.GetDriverByName('MEM').Create('', 2, 2, 1, gdal.GDT_Float32) @@ -1317,15 +1029,13 @@ def grib_grib2_write_data_encodings(): if encoding == 'COMPLEX_PACKING': with gdaltest.error_handler(): success = gdal.Translate(tmpfilename, test_ds, format='GRIB', creationOptions=options) - if success: - gdaltest.post_reason('expected error for %s, %s' % ('floating point data with dynamic < 1', str(options))) - return 'fail' + assert not success, \ + ('expected error for %s, %s' % ('floating point data with dynamic < 1', str(options))) else: gdal.Translate(tmpfilename, test_ds, format='GRIB', creationOptions=options) error_msg = gdal.GetLastErrorMsg() - if error_msg != '': - gdaltest.post_reason('did not expect error for %s, %s' % ('floating point data with dynamic < 1', str(options))) - return 'fail' + assert error_msg == '', \ + ('did not expect error for %s, %s' % ('floating point data with dynamic < 1', str(options))) out_ds = gdal.Open(tmpfilename) got_vals = struct.unpack(4 * 'd', out_ds.ReadRaster()) out_ds = None @@ -1333,10 +1043,8 @@ def grib_grib2_write_data_encodings(): expected_vals = (1.23, 1.45, 1.56, 1.78) else: expected_vals = (1.2300000190734863, 1.4487500190734863, 1.5581250190734863, 1.7807812690734863) - if max([abs(got_vals[i] - expected_vals[i]) for i in range(4)]) > 1e-7: - gdaltest.post_reason('did not get expected values') - print(got_vals) - return 'fail' + assert max([abs(got_vals[i] - expected_vals[i]) for i in range(4)]) <= 1e-7, \ + 'did not get expected values' gdal.Unlink(tmpfilename) test_ds = None @@ -1362,18 +1070,13 @@ def grib_grib2_write_data_encodings(): if encoding != 'SIMPLE_PACKING': gdal.PopErrorHandler() out_ds = gdal.Open(tmpfilename) - if out_ds is None: - gdaltest.post_reason('failed to re-open dataset for ' + encoding) - return 'fail' + assert out_ds is not None, ('failed to re-open dataset for ' + encoding) got_vals = struct.unpack(4 * 'd', out_ds.ReadRaster()) out_ds = None gdal.Unlink(tmpfilename) expected_vals = (1.23e10, -2.45e10, 1.23e10, -2.45e10) - if max([abs((got_vals[i] - expected_vals[i]) / expected_vals[i]) for i in range(4)]) > 1e-4: - gdaltest.post_reason('did not get expected values for ' + encoding) - print(got_vals) - print(max([abs((got_vals[i] - expected_vals[i]) / expected_vals[i]) for i in range(2)])) - return 'fail' + assert max([abs((got_vals[i] - expected_vals[i]) / expected_vals[i]) for i in range(4)]) <= 1e-4, \ + ('did not get expected values for ' + encoding) test_ds = None # Test lossy J2K compression @@ -1384,9 +1087,8 @@ def grib_grib2_write_data_encodings(): creationOptions=['JPEG2000_DRIVER=' + drvname, 'COMPRESSION_RATIO=20']) error_msg = gdal.GetLastErrorMsg() - if error_msg != '': - gdaltest.post_reason('did not expect error for %s, %s' % (str(filename), str(options))) - return 'fail' + assert error_msg == '', \ + ('did not expect error for %s, %s' % (str(filename), str(options))) out_ds = gdal.Open(tmpfilename) cs = out_ds.GetRasterBand(1).Checksum() out_ds = None @@ -1395,16 +1097,12 @@ def grib_grib2_write_data_encodings(): gdaltest.post_reason('did not get expected checksum for lossy JPEG2000 with ' + drvname) print(cs) - return 'success' ############################################################################### # Test GRIB2 write support with warnings/errors -def grib_grib2_write_data_encodings_warnings_and_errors(): - - if gdaltest.grib_drv is None: - return 'skip' +def test_grib_grib2_write_data_encodings_warnings_and_errors(): # Cases where warnings are expected tests = [] @@ -1424,12 +1122,10 @@ def grib_grib2_write_data_encodings_warnings_and_errors(): out_ds = gdaltest.grib_drv.CreateCopy(tmpfilename, src_ds, options=options) error_msg = gdal.GetLastErrorMsg() - if error_msg == '': - gdaltest.post_reason('expected warning for %s, %s' % (str(filename), str(options))) - return 'fail' - if out_ds is None: - gdaltest.post_reason('did not expect null return for %s, %s' % (str(filename), str(options))) - return 'fail' + assert error_msg != '', \ + ('expected warning for %s, %s' % (str(filename), str(options))) + assert out_ds is not None, \ + ('did not expect null return for %s, %s' % (str(filename), str(options))) cs = out_ds.GetRasterBand(1).Checksum() @@ -1437,10 +1133,8 @@ def grib_grib2_write_data_encodings_warnings_and_errors(): gdal.Unlink(tmpfilename) if not isinstance(expected_cs, tuple): expected_cs = (expected_cs,) - if cs not in expected_cs: - gdaltest.post_reason('did not get expected checksum for %s, %s' % (str(filename), str(options))) - print(cs, expected_cs) - return 'fail' + assert cs in expected_cs, \ + ('did not get expected checksum for %s, %s' % (str(filename), str(options))) # Cases where errors are expected tests = [] @@ -1464,12 +1158,10 @@ def grib_grib2_write_data_encodings_warnings_and_errors(): out_ds = gdaltest.grib_drv.CreateCopy(tmpfilename, src_ds, options=options) error_msg = gdal.GetLastErrorMsg() - if error_msg == '': - gdaltest.post_reason('expected warning for %s, %s' % (str(filename), str(options))) - return 'fail' - if out_ds is not None: - gdaltest.post_reason('expected null return for %s, %s' % (str(filename), str(options))) - return 'fail' + assert error_msg != '', \ + ('expected warning for %s, %s' % (str(filename), str(options))) + assert out_ds is None, \ + ('expected null return for %s, %s' % (str(filename), str(options))) out_ds = None gdal.Unlink(tmpfilename) @@ -1477,17 +1169,13 @@ def grib_grib2_write_data_encodings_warnings_and_errors(): with gdaltest.error_handler(): out_ds = gdal.Translate('/i/do_not/exist.grb2', 'data/byte.tif', format='GRIB') - if out_ds is not None: - gdaltest.post_reason('expected null return') - return 'fail' - - return 'success' + assert out_ds is None, 'expected null return' ############################################################################### # Test writing temperatures with automatic Celsius -> Kelvin conversion -def grib_grib2_write_temperatures(): +def test_grib_grib2_write_temperatures(): for (src_type, data_encoding, input_unit) in [ (gdal.GDT_Float32, 'IEEE_FLOATING_POINT', None), @@ -1523,21 +1211,17 @@ def grib_grib2_write_temperatures(): expected_vals = (25.0, 25.1, 25.1, 25.2) else: expected_vals = (25.0 - 273.15, 25.1 - 273.15, 25.1 - 273.15, 25.2 - 273.15) - if max([abs((got_vals[i] - expected_vals[i]) / expected_vals[i]) for i in range(4)]) > 1e-4: - gdaltest.post_reason('fail with data_encoding = %s and type = %s' % (data_encoding, str(src_type))) - print(got_vals) - print(max([abs((got_vals[i] - expected_vals[i]) / expected_vals[i]) for i in range(2)])) - return 'fail' + assert max([abs((got_vals[i] - expected_vals[i]) / expected_vals[i]) for i in range(4)]) <= 1e-4, \ + ('fail with data_encoding = %s and type = %s' % (data_encoding, str(src_type))) - return 'success' ############################################################################### -def grib_grib2_write_nodata(): +def test_grib_grib2_write_nodata(): if gdaltest.grib_drv is None: - return 'skip' + pytest.skip() for src_type in [ gdal.GDT_Byte, gdal.GDT_Float32 ]: src_ds = gdal.GetDriverByName('MEM').Create('', 2, 2, 1, src_type) @@ -1553,91 +1237,34 @@ def grib_grib2_write_nodata(): gdaltest.grib_drv.CreateCopy(tmpfilename, src_ds, options=options) ds = gdal.Open(tmpfilename) - if ds.GetRasterBand(1).GetNoDataValue() != 123: - gdaltest.post_reason('fail') - return 'fail' + assert ds.GetRasterBand(1).GetNoDataValue() == 123 ds = None gdal.Unlink(tmpfilename) - return 'success' - + ############################################################################### # Test GRIB2 file with JPEG2000 codestream on a single line (#6719) -def grib_online_grib2_jpeg2000_single_line(): - - if gdaltest.grib_drv is None: - return 'skip' +def test_grib_online_grib2_jpeg2000_single_line(): if not has_jp2kdrv(): - return 'skip' + pytest.skip() filename = 'CMC_hrdps_continental_PRATE_SFC_0_ps2.5km_2017111712_P001-00.grib2' if not gdaltest.download_file('http://download.osgeo.org/gdal/data/grib/' + filename): - return 'skip' + pytest.skip() ds = gdal.Open('tmp/cache/' + filename) cs = ds.GetRasterBand(1).Checksum() - if cs == 0: - gdaltest.post_reason('Could not open file') - print(cs) - return 'fail' + assert cs != 0, 'Could not open file' nd = ds.GetRasterBand(1).GetNoDataValue() - if nd != 9999: - gdaltest.post_reason('Bad nodata value') - print(nd) - return 'fail' + assert nd == 9999, 'Bad nodata value' md = ds.GetRasterBand(1).GetMetadata() expected_md = {'GRIB_REF_TIME': ' 1510920000 sec UTC', 'GRIB_VALID_TIME': ' 1510923600 sec UTC', 'GRIB_FORECAST_SECONDS': '3600 sec', 'GRIB_UNIT': '[kg/(m^2 s)]', 'GRIB_PDS_TEMPLATE_NUMBERS': '1 7 2 50 50 0 0 0 0 0 0 0 60 1 0 0 0 0 0 255 255 255 255 255 255', 'GRIB_PDS_PDTN': '0', 'GRIB_COMMENT': 'Precipitation rate [kg/(m^2 s)]', 'GRIB_SHORT_NAME': '0-SFC', 'GRIB_ELEMENT': 'PRATE'} for k in expected_md: - if k not in md or md[k] != expected_md[k]: - gdaltest.post_reason('Did not get expected metadata') - print(md) - return 'fail' - - return 'success' - - -gdaltest_list = [ - grib_1, - grib_2, - grib_read_different_sizes_messages, - grib_grib2_read_nodata, - grib_read_units, - grib_read_geotransform_one_n_or_n_one, - grib_read_vsizip, - grib_grib2_test_grib_pds_all_bands, - grib_grib2_read_template_4_15, - grib_grib2_read_png, - grib_grib2_read_template_4_32, - grib_grib2_read_all_zero_data, - grib_grib2_read_rotated_pole_lonlat, - grib_grib2_read_template_4_40, - grib_grib2_read_template_4_unhandled, - grib_grib2_read_transverse_mercator, - grib_grib2_read_mercator, - grib_grib2_read_mercator_2sp, - grib_grib2_read_lcc, - grib_grib2_read_polar_stereo, - grib_grib2_read_aea, - grib_grib2_read_laea, - grib_grib2_read_template_5_4_grid_point_ieee_floating_point, - grib_grib2_read_section_5_nbits_zero_decimal_scaled, - grib_grib2_read_spatial_differencing_order_1, - grib_grib2_write_creation_options, - grib_grib2_write_projections, - grib_grib2_write_data_encodings, - grib_grib2_write_data_encodings_warnings_and_errors, - grib_grib2_write_temperatures, - grib_grib2_write_nodata, - grib_online_grib2_jpeg2000_single_line -] - -if __name__ == '__main__': - - gdaltest.setup_run('grib') - - gdaltest.run_tests(gdaltest_list) - - sys.exit(gdaltest.summarize()) + assert k in md and md[k] == expected_md[k], 'Did not get expected metadata' + + + + diff --git a/autotest/gdrivers/gsc.py b/autotest/gdrivers/gsc.py index 877ad8492cb0..c4e603c3832d 100755 --- a/autotest/gdrivers/gsc.py +++ b/autotest/gdrivers/gsc.py @@ -28,9 +28,7 @@ # DEALINGS IN THE SOFTWARE. ############################################################################### -import sys -sys.path.append('../pymod') import gdaltest @@ -38,19 +36,10 @@ # Test a fake - and certainly incorrect - GSC dataset -def gsc_1(): +def test_gsc_1(): tst = gdaltest.GDALTest('GSC', 'fakegsc.gsc', 1, 0) return tst.testOpen() -gdaltest_list = [ - gsc_1] -if __name__ == '__main__': - - gdaltest.setup_run('gsc') - - gdaltest.run_tests(gdaltest_list) - - sys.exit(gdaltest.summarize()) diff --git a/autotest/gdrivers/gsg.py b/autotest/gdrivers/gsg.py index ee8fa74ec64e..1d42b45c1d89 100755 --- a/autotest/gdrivers/gsg.py +++ b/autotest/gdrivers/gsg.py @@ -28,9 +28,7 @@ # DEALINGS IN THE SOFTWARE. ############################################################################### -import sys -sys.path.append('../pymod') import gdaltest @@ -38,19 +36,19 @@ # Perform simple read tests. -def gsg_1(): +def test_gsg_1(): tst = gdaltest.GDALTest('gsbg', 'gsg_binary.grd', 1, 4672) return tst.testOpen(check_gt=(440720, 60, 0, 3751320, 0, -60)) -def gsg_2(): +def test_gsg_2(): tst = gdaltest.GDALTest('gsag', 'gsg_ascii.grd', 1, 4672) return tst.testOpen(check_gt=(440720, 60, 0, 3751320, 0, -60)) -def gsg_3(): +def test_gsg_3(): tst = gdaltest.GDALTest('gs7bg', 'gsg_7binary.grd', 1, 4672) return tst.testOpen(check_gt=(440720, 60, 0, 3751320, 0, -60)) @@ -59,35 +57,35 @@ def gsg_3(): # Create simple copy and check. -def gsg_4(): +def test_gsg_4(): tst = gdaltest.GDALTest('gsbg', 'gsg_binary.grd', 1, 4672) return tst.testCreateCopy(check_gt=1) -def gsg_5(): +def test_gsg_5(): tst = gdaltest.GDALTest('gsag', 'gsg_ascii.grd', 1, 4672) return tst.testCreateCopy(check_gt=1) -def gsg_6(): +def test_gsg_6(): tst = gdaltest.GDALTest('gsbg', 'gsg_binary.grd', 1, 4672) return tst.testCreate(out_bands=1) -def gsg_7(): +def test_gsg_7(): tst = gdaltest.GDALTest('gs7bg', 'gsg_7binary.grd', 1, 4672) return tst.testCreate(out_bands=1) -def gsg_8(): +def test_gsg_8(): tst = gdaltest.GDALTest('gs7bg', 'gsg_7binary.grd', 1, 4672) @@ -96,22 +94,5 @@ def gsg_8(): ############################################################################### -gdaltest_list = [ - gsg_1, - gsg_2, - gsg_3, - gsg_4, - gsg_5, - gsg_6, - gsg_7, - gsg_8 -] -if __name__ == '__main__': - - gdaltest.setup_run('gsg') - - gdaltest.run_tests(gdaltest_list) - - sys.exit(gdaltest.summarize()) diff --git a/autotest/gdrivers/gta.py b/autotest/gdrivers/gta.py index 5b9dc1062461..8fca58d1ea23 100755 --- a/autotest/gdrivers/gta.py +++ b/autotest/gdrivers/gta.py @@ -28,51 +28,47 @@ # DEALINGS IN THE SOFTWARE. ############################################################################### -import sys -sys.path.append('../pymod') +import pytest import gdaltest from osgeo import gdal -gdaltest_list = [] - init_list = [ - ('byte.tif', 1, 4672, []), - ('byte_signed.tif', 1, 4672, []), - ('int16.tif', 1, 4672, []), - ('uint16.tif', 1, 4672, []), - ('int32.tif', 1, 4672, []), - ('uint32.tif', 1, 4672, []), - ('float32.tif', 1, 4672, []), - ('float64.tif', 1, 4672, []), - ('cint16.tif', 1, 5028, []), - ('cint32.tif', 1, 5028, []), - ('cfloat32.tif', 1, 5028, []), - ('cfloat64.tif', 1, 5028, []), - ('rgbsmall.tif', 1, 21212, [])] + ('byte.tif', 4672), + ('byte_signed.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), + ('rgbsmall.tif', 21212)] ############################################################################### # Verify we have the driver. -def gta_1(): +def test_gta_1(): gdaltest.gta_drv = gdal.GetDriverByName('GTA') if gdaltest.gta_drv is None: - return 'skip' - - return 'success' + pytest.skip() + ############################################################################### # Test updating existing dataset, check srs, check gt -def gta_2(): +def test_gta_2(): if gdaltest.gta_drv is None: - return 'skip' + pytest.skip() src_ds = gdal.Open('data/byte.tif') out_ds = gdaltest.gta_drv.CreateCopy('/vsimem/byte.gta', src_ds) @@ -84,9 +80,7 @@ def gta_2(): out_ds = gdal.Open('/vsimem/byte.gta') cs = out_ds.GetRasterBand(1).Checksum() - if cs != 0: - gdaltest.post_reason('did not get expected checksum') - return 'fail' + assert cs == 0, 'did not get expected checksum' out_ds = None out_ds = gdal.Open('/vsimem/byte.gta', gdal.GA_Update) @@ -95,9 +89,7 @@ def gta_2(): out_ds = gdal.Open('/vsimem/byte.gta') cs = out_ds.GetRasterBand(1).Checksum() - if cs != src_ds.GetRasterBand(1).Checksum(): - gdaltest.post_reason('did not get expected checksum') - return 'fail' + assert cs == src_ds.GetRasterBand(1).Checksum(), 'did not get expected checksum' gt = out_ds.GetGeoTransform() wkt = out_ds.GetProjectionRef() @@ -105,26 +97,20 @@ def gta_2(): expected_gt = src_ds.GetGeoTransform() for i in range(6): - if abs(gt[i] - expected_gt[i]) > 1e-6: - gdaltest.post_reason('did not get expected wkt') - return 'fail' + assert abs(gt[i] - expected_gt[i]) <= 1e-6, 'did not get expected wkt' - if wkt != src_ds.GetProjectionRef(): - gdaltest.post_reason('did not get expected wkt') - return 'fail' + assert wkt == src_ds.GetProjectionRef(), 'did not get expected wkt' gdaltest.gta_drv.Delete('/vsimem/byte.gta') - return 'success' - ############################################################################### # Test writing and readings GCPs -def gta_3(): +def test_gta_3(): if gdaltest.gta_drv is None: - return 'skip' + pytest.skip() src_ds = gdal.Open('../gcore/data/gcps.vrt') @@ -133,38 +119,30 @@ def gta_3(): new_ds = gdal.Open('/vsimem/gta_3.gta') - if new_ds.GetGeoTransform() != (0.0, 1.0, 0.0, 0.0, 0.0, 1.0): - gdaltest.post_reason('GeoTransform not set properly.') - return 'fail' + assert new_ds.GetGeoTransform() == (0.0, 1.0, 0.0, 0.0, 0.0, 1.0), \ + 'GeoTransform not set properly.' - if new_ds.GetProjectionRef() != '': - gdaltest.post_reason('Projection not set properly.') - return 'fail' + assert new_ds.GetProjectionRef() == '', 'Projection not set properly.' - if new_ds.GetGCPProjection() != src_ds.GetGCPProjection(): - gdaltest.post_reason('GCP Projection not set properly.') - return 'fail' + assert new_ds.GetGCPProjection() == src_ds.GetGCPProjection(), \ + 'GCP Projection not set properly.' gcps = new_ds.GetGCPs() expected_gcps = src_ds.GetGCPs() - if len(gcps) != len(expected_gcps): - gdaltest.post_reason('GCP count wrong.') - return 'fail' + assert len(gcps) == len(expected_gcps), 'GCP count wrong.' new_ds = None gdaltest.gta_drv.Delete('/vsimem/gta_3.gta') - return 'success' - ############################################################################### # Test band metadata -def gta_4(): +def test_gta_4(): if gdaltest.gta_drv is None: - return 'skip' + pytest.skip() src_ds = gdal.GetDriverByName('MEM').Create('', 1, 1, 17) src_ds.GetRasterBand(1).Fill(255) @@ -184,61 +162,32 @@ def gta_4(): new_ds = gdal.Open('/vsimem/gta_4.gta') band = new_ds.GetRasterBand(1) - if band.GetNoDataValue() != 123: - gdaltest.post_reason('did not get expected nodata value') - print(band.GetNoDataValue()) - return 'fail' - if band.GetMinimum() != 255: - gdaltest.post_reason('did not get expected minimum value') - print(band.GetMinimum()) - return 'fail' - if band.GetMaximum() != 255: - gdaltest.post_reason('did not get expected maximum value') - print(band.GetMaximum()) - return 'fail' - if band.GetCategoryNames() != ['a', 'b']: - gdaltest.post_reason('did not get expected category names') - print(band.GetCategoryNames()) - return 'fail' - if band.GetOffset() != 2: - gdaltest.post_reason('did not get expected offset value') - print(band.GetOffset()) - return 'fail' - if band.GetScale() != 3: - gdaltest.post_reason('did not get expected scale value') - print(band.GetScale()) - return 'fail' - if band.GetUnitType() != 'custom': - gdaltest.post_reason('did not get expected unit value') - print(band.GetUnitType()) - return 'fail' - if band.GetDescription() != 'description': - gdaltest.post_reason('did not get expected description') - print(band.GetDescription()) - return 'fail' + assert band.GetNoDataValue() == 123, 'did not get expected nodata value' + assert band.GetMinimum() == 255, 'did not get expected minimum value' + assert band.GetMaximum() == 255, 'did not get expected maximum value' + assert band.GetCategoryNames() == ['a', 'b'], 'did not get expected category names' + assert band.GetOffset() == 2, 'did not get expected offset value' + assert band.GetScale() == 3, 'did not get expected scale value' + assert band.GetUnitType() == 'custom', 'did not get expected unit value' + assert band.GetDescription() == 'description', 'did not get expected description' for i in range(17): if i != gdal.GCI_PaletteIndex: - if new_ds.GetRasterBand(i + 1).GetColorInterpretation() != i: - gdaltest.post_reason( - 'did not get expected color interpretation ' + assert new_ds.GetRasterBand(i + 1).GetColorInterpretation() == i, \ + ('did not get expected color interpretation ' 'for band %d' % (i + 1)) - print(new_ds.GetRasterBand(i + 1).GetColorInterpretation()) - return 'fail' new_ds = None gdaltest.gta_drv.Delete('/vsimem/gta_4.gta') - return 'success' - ############################################################################### # Test compression algorithms -def gta_5(): +def test_gta_5(): if gdaltest.gta_drv is None: - return 'skip' + pytest.skip() src_ds = gdal.Open('data/byte.tif') @@ -262,30 +211,18 @@ def gta_5(): gdaltest.gta_drv.Delete('/vsimem/gta_5.gta') - return 'success' - - -for item in init_list: - if item[0] == 'byte_signed.tif': - filename = item[0] - else: - filename = '../../gcore/data/' + item[0] - ut = gdaltest.GDALTest('GTA', filename, item[1], item[2], options=item[3]) - if ut is None: - print('GTA tests skipped') - sys.exit() - gdaltest_list.append((ut.testCreateCopy, item[0])) - -gdaltest_list.append(gta_1) -gdaltest_list.append(gta_2) -gdaltest_list.append(gta_3) -gdaltest_list.append(gta_4) -gdaltest_list.append(gta_5) -if __name__ == '__main__': +@pytest.mark.parametrize( + 'filename,checksum', + init_list, + ids=[tup[0].split('.')[0] for tup in init_list], +) +@pytest.mark.require_driver('GTA') +def test_gta_create(filename, checksum): + if filename != 'byte_signed.tif': + filename = '../../gcore/data/' + filename + ut = gdaltest.GDALTest('GTA', filename, 1, checksum, options=[]) + ut.testCreateCopy() - gdaltest.setup_run('gta') - gdaltest.run_tests(gdaltest_list) - sys.exit(gdaltest.summarize()) diff --git a/autotest/gdrivers/gtx.py b/autotest/gdrivers/gtx.py index 6aa48f680f21..a754adc01929 100755 --- a/autotest/gdrivers/gtx.py +++ b/autotest/gdrivers/gtx.py @@ -28,9 +28,7 @@ # DEALINGS IN THE SOFTWARE. ############################################################################### -import sys -sys.path.append('../pymod') import gdaltest @@ -38,20 +36,11 @@ # Test reading a small gtx file. -def gtx_1(): +def test_gtx_1(): tst = gdaltest.GDALTest('GTX', 'hydroc1.gtx', 1, 64183) gt = (276.725, 0.05, 0.0, 42.775, 0.0, -0.05) return tst.testOpen(check_gt=gt, check_prj='WGS84') -gdaltest_list = [ - gtx_1] -if __name__ == '__main__': - - gdaltest.setup_run('gtx') - - gdaltest.run_tests(gdaltest_list) - - sys.exit(gdaltest.summarize()) diff --git a/autotest/gdrivers/gxf.py b/autotest/gdrivers/gxf.py index 6355ea150f8e..fce7b770e6ea 100755 --- a/autotest/gdrivers/gxf.py +++ b/autotest/gdrivers/gxf.py @@ -29,10 +29,11 @@ # DEALINGS IN THE SOFTWARE. ############################################################################### -import sys + +import pytest + from osgeo import gdal -sys.path.append('../pymod') import gdaltest @@ -40,7 +41,7 @@ # Test a small GXF sample -def gxf_1(): +def test_gxf_1(): tst = gdaltest.GDALTest('GXF', 'small.gxf', 1, 90) @@ -50,7 +51,7 @@ def gxf_1(): # Test an other GXF sample (with continuous line) -def gxf_2(): +def test_gxf_2(): tst = gdaltest.GDALTest('GXF', 'small2.gxf', 1, 65042) wkt = """PROJCS["NAD27 / Ohio North", @@ -69,49 +70,30 @@ def gxf_2(): return tst.testOpen(check_prj=wkt) -############################################################################### -# - - -class TestGXF(object): - def __init__(self, downloadURL, fileName, checksum, download_size): - self.downloadURL = downloadURL - self.fileName = fileName - self.checksum = checksum - self.download_size = download_size - - def test(self): - if not gdaltest.download_file(self.downloadURL + '/' + self.fileName, self.fileName, self.download_size): - return 'skip' - - ds = gdal.Open('tmp/cache/' + self.fileName) - - if ds.GetRasterBand(1).Checksum() != self.checksum: - gdaltest.post_reason('Bad checksum. Expected %d, got %d' % (self.checksum, ds.GetRasterBand(1).Checksum())) - return 'fail' - - return 'success' +gxf_list = [ + ('http://download.osgeo.org/gdal/data/gxf', 'SAMPLE.GXF', 24068, -1), + ('http://download.osgeo.org/gdal/data/gxf', 'gxf_compressed.gxf', 20120, -1), + ('http://download.osgeo.org/gdal/data/gxf', 'gxf_text.gxf', 20265, -1), + ('http://download.osgeo.org/gdal/data/gxf', 'gxf_ul_r.gxf', 19930, -1), + ('http://download.osgeo.org/gdal/data/gxf', 'latlong.gxf', 12243, -1), + ('http://download.osgeo.org/gdal/data/gxf', 'spif83.gxf', 28752, -1), +] -gdaltest_list = [gxf_1, gxf_2] -gxf_list = [('http://download.osgeo.org/gdal/data/gxf', 'SAMPLE.GXF', 24068, -1), - ('http://download.osgeo.org/gdal/data/gxf', 'gxf_compressed.gxf', 20120, -1), - ('http://download.osgeo.org/gdal/data/gxf', 'gxf_text.gxf', 20265, -1), - ('http://download.osgeo.org/gdal/data/gxf', 'gxf_ul_r.gxf', 19930, -1), - ('http://download.osgeo.org/gdal/data/gxf', 'latlong.gxf', 12243, -1), - ('http://download.osgeo.org/gdal/data/gxf', 'spif83.gxf', 28752, -1) - ] +@pytest.mark.parametrize( + 'downloadURL,fileName,checksum,download_size', + gxf_list, + ids=[tup[1] for tup in gxf_list], +) +def test_gxf(downloadURL, fileName, checksum, download_size): + if not gdaltest.download_file(downloadURL + '/' + fileName, fileName, download_size): + pytest.skip() -for item in gxf_list: - ut = TestGXF(item[0], item[1], item[2], item[3]) - gdaltest_list.append((ut.test, item[1])) + ds = gdal.Open('tmp/cache/' + fileName) + assert ds.GetRasterBand(1).Checksum() == checksum, 'Bad checksum. Expected %d, got %d' % (checksum, ds.GetRasterBand(1).Checksum()) -if __name__ == '__main__': - gdaltest.setup_run('gxf') - gdaltest.run_tests(gdaltest_list) - sys.exit(gdaltest.summarize()) diff --git a/autotest/gdrivers/hdf5.py b/autotest/gdrivers/hdf5.py index 8f87a30502db..e7b9dc289ef9 100755 --- a/autotest/gdrivers/hdf5.py +++ b/autotest/gdrivers/hdf5.py @@ -29,12 +29,12 @@ # DEALINGS IN THE SOFTWARE. ############################################################################### -import sys import shutil +import pytest + from osgeo import gdal -sys.path.append('../pymod') import gdaltest @@ -44,117 +44,80 @@ # Test if HDF5 driver is present -def hdf5_1(): +pytestmark = pytest.mark.require_driver('HDF5') - gdaltest.hdf5_drv = gdal.GetDriverByName('HDF5') - if gdaltest.hdf5_drv is None: - return 'skip' - gdaltest.count_opened_files = len(gdaltest.get_opened_files()) +@pytest.fixture(autouse=True) +def check_no_file_leaks(): + num_files = len(gdaltest.get_opened_files()) - return 'success' + yield -############################################################################### -# Confirm expected subdataset information. + diff = len(gdaltest.get_opened_files()) - num_files + assert diff == 0, 'Leak of file handles: %d leaked' % diff -def hdf5_2(): +############################################################################### +# Confirm expected subdataset information. - if gdaltest.hdf5_drv is None: - return 'skip' +def test_hdf5_2(): ds = gdal.Open('data/groups.h5') sds_list = ds.GetMetadata('SUBDATASETS') - if len(sds_list) != 4: - print(sds_list) - gdaltest.post_reason('Did not get expected subdataset count.') - return 'fail' + assert len(sds_list) == 4, 'Did not get expected subdataset count.' - if sds_list['SUBDATASET_1_NAME'] != 'HDF5:"data/groups.h5"://MyGroup/Group_A/dset2' \ - or sds_list['SUBDATASET_2_NAME'] != 'HDF5:"data/groups.h5"://MyGroup/dset1': - print(sds_list) - gdaltest.post_reason('did not get expected subdatasets.') - return 'fail' + assert sds_list['SUBDATASET_1_NAME'] == 'HDF5:"data/groups.h5"://MyGroup/Group_A/dset2' and sds_list['SUBDATASET_2_NAME'] == 'HDF5:"data/groups.h5"://MyGroup/dset1', \ + 'did not get expected subdatasets.' ds = None - if gdaltest.is_file_open('data/groups.h5'): - gdaltest.post_reason('file still opened.') - return 'fail' - - return 'success' + assert not gdaltest.is_file_open('data/groups.h5'), 'file still opened.' ############################################################################### # Confirm that single variable files can be accessed directly without # subdataset stuff. -def hdf5_3(): - - if gdaltest.hdf5_drv is None: - return 'skip' +def test_hdf5_3(): ds = gdal.Open('HDF5:"data/u8be.h5"://TestArray') cs = ds.GetRasterBand(1).Checksum() - if cs != 135: - gdaltest.post_reason('did not get expected checksum') - return 'fail' + assert cs == 135, 'did not get expected checksum' ds = None - if gdaltest.is_file_open('data/u8be.h5'): - gdaltest.post_reason('file still opened.') - return 'fail' - - return 'success' + assert not gdaltest.is_file_open('data/u8be.h5'), 'file still opened.' ############################################################################### # Confirm subdataset access, and checksum. -def hdf5_4(): - - if gdaltest.hdf5_drv is None: - return 'skip' +def test_hdf5_4(): ds = gdal.Open('HDF5:"data/u8be.h5"://TestArray') cs = ds.GetRasterBand(1).Checksum() - if cs != 135: - gdaltest.post_reason('did not get expected checksum') - return 'fail' - - return 'success' + assert cs == 135, 'did not get expected checksum' ############################################################################### # Similar check on a 16bit dataset. -def hdf5_5(): - - if gdaltest.hdf5_drv is None: - return 'skip' +def test_hdf5_5(): ds = gdal.Open('HDF5:"data/groups.h5"://MyGroup/dset1') cs = ds.GetRasterBand(1).Checksum() - if cs != 18: - gdaltest.post_reason('did not get expected checksum') - return 'fail' - - return 'success' + assert cs == 18, 'did not get expected checksum' ############################################################################### # Test generating an overview on a subdataset. -def hdf5_6(): - - if gdaltest.hdf5_drv is None: - return 'skip' +def test_hdf5_6(): shutil.copyfile('data/groups.h5', 'tmp/groups.h5') @@ -162,80 +125,56 @@ def hdf5_6(): ds.BuildOverviews(overviewlist=[2]) ds = None - if gdaltest.is_file_open('tmp/groups.h5'): - gdaltest.post_reason('file still opened.') - return 'fail' + assert not gdaltest.is_file_open('tmp/groups.h5'), 'file still opened.' ds = gdal.Open('HDF5:"tmp/groups.h5"://MyGroup/dset1') - if ds.GetRasterBand(1).GetOverviewCount() != 1: - gdaltest.post_reason('failed to find overview') - return 'fail' + assert ds.GetRasterBand(1).GetOverviewCount() == 1, 'failed to find overview' ds = None # confirm that it works with a different path. (#3290) ds = gdal.Open('HDF5:"data/../tmp/groups.h5"://MyGroup/dset1') - if ds.GetRasterBand(1).GetOverviewCount() != 1: - gdaltest.post_reason('failed to find overview with alternate path') - return 'fail' + assert ds.GetRasterBand(1).GetOverviewCount() == 1, \ + 'failed to find overview with alternate path' ovfile = ds.GetMetadataItem('OVERVIEW_FILE', 'OVERVIEWS') - if ovfile[:11] != 'data/../tmp': - print(ovfile) - gdaltest.post_reason('did not get expected OVERVIEW_FILE.') - return 'fail' + assert ovfile[:11] == 'data/../tmp', 'did not get expected OVERVIEW_FILE.' ds = None gdaltest.clean_tmp() - return 'success' - ############################################################################### # Coarse metadata check (regression test for #2412). -def hdf5_7(): - - if gdaltest.hdf5_drv is None: - return 'skip' +def test_hdf5_7(): ds = gdal.Open('data/metadata.h5') metadata = ds.GetMetadata() metadataList = ds.GetMetadata_List() ds = None - if gdaltest.is_file_open('data/metadata.h5'): - gdaltest.post_reason('file still opened.') - return 'fail' + assert not gdaltest.is_file_open('data/metadata.h5'), 'file still opened.' - if len(metadata) != len(metadataList): - gdaltest.post_reason('error in metadata dictionary setup') - return 'fail' + assert len(metadata) == len(metadataList), 'error in metadata dictionary setup' metadataList = [item.split('=', 1)[0] for item in metadataList] for key in metadataList: try: metadata.pop(key) except KeyError: - gdaltest.post_reason('unable to find "%s" key' % key) - return 'fail' - return 'success' - + pytest.fail('unable to find "%s" key' % key) + ############################################################################### # Test metadata names. -def hdf5_8(): - - if gdaltest.hdf5_drv is None: - return 'skip' +def test_hdf5_8(): ds = gdal.Open('data/metadata.h5') metadata = ds.GetMetadata() ds = None - if not metadata: - gdaltest.post_reason('no metadata found') - return 'fail' + assert metadata, 'no metadata found' h5groups = ['G1', 'Group with spaces', 'Group_with_underscores', 'Group with spaces_and_underscores'] @@ -252,60 +191,45 @@ def scanMetadata(parts): for attr in attributes: name = '_'.join(parts + [attr]) name = name.replace(' ', '_') - if name not in metadata: - gdaltest.post_reason('unable to find metadata: "%s"' % name) - return 'fail' + assert name in metadata, ('unable to find metadata: "%s"' % name) value = metadata.pop(name) value = value.strip(' d') value = type(attributes[attr])(value) - if value != attributes[attr]: - gdaltest.post_reason('incorrect metadata value for "%s": ' + assert value == attributes[attr], ('incorrect metadata value for "%s": ' '"%s" != "%s"' % (name, value, attributes[attr])) - return 'fail' # level0 - if scanMetadata([]) is not None: - return 'fail' + assert scanMetadata([]) is None # level1 datasets for h5dataset in h5datasets: - if scanMetadata([h5dataset]) is not None: - return 'fail' + assert scanMetadata([h5dataset]) is None # level1 groups for h5group in h5groups: - if scanMetadata([h5group]) is not None: - return 'fail' + assert scanMetadata([h5group]) is None # level2 datasets for h5dataset in h5datasets: - if scanMetadata([h5group, h5dataset]) is not None: - return 'fail' - - return 'success' + assert scanMetadata([h5group, h5dataset]) is None + ############################################################################### # Variable length string metadata check (regression test for #4228). -def hdf5_9(): - - if gdaltest.hdf5_drv is None: - return 'skip' +def test_hdf5_9(): if int(gdal.VersionInfo('VERSION_NUM')) < 1900: - gdaltest.post_reason('would crash') - return 'skip' + pytest.skip('would crash') ds = gdal.Open('data/vlstr_metadata.h5') metadata = ds.GetRasterBand(1).GetMetadata() ds = None - if gdaltest.is_file_open('data/vlstr_metadata.h5'): - gdaltest.post_reason('file still opened.') - return 'fail' + assert not gdaltest.is_file_open('data/vlstr_metadata.h5'), 'file still opened.' ref_metadata = { 'TEST_BANDNAMES': 'SAA', @@ -316,268 +240,165 @@ def hdf5_9(): 'TEST_RANGE': '0 255 0 255', } - if len(metadata) != len(ref_metadata): - gdaltest.post_reason('incorrect number of metadata: ' + assert len(metadata) == len(ref_metadata), ('incorrect number of metadata: ' 'expected %d, got %d' % (len(ref_metadata), len(metadata))) - return 'fail' for key in metadata: - if key not in ref_metadata: - gdaltest.post_reason('unexpected metadata key "%s"' % key) - return 'fail' + assert key in ref_metadata, ('unexpected metadata key "%s"' % key) - if metadata[key] != ref_metadata[key]: - gdaltest.post_reason('incorrect metadata value for key "%s": ' + assert metadata[key] == ref_metadata[key], \ + ('incorrect metadata value for key "%s": ' 'expected "%s", got "%s" ' % (key, ref_metadata[key], metadata[key])) - return 'fail' - - return 'success' + ############################################################################### # Test CSK_DGM.h5 (#4160) -def hdf5_10(): - - if gdaltest.hdf5_drv is None: - return 'skip' +def test_hdf5_10(): # Try opening the QLK subdataset to check that no error is generated gdal.ErrorReset() ds = gdal.Open('HDF5:"data/CSK_DGM.h5"://S01/QLK') - if ds is None or gdal.GetLastErrorMsg() != '': - gdaltest.post_reason('fail') - return 'fail' + assert ds is not None and gdal.GetLastErrorMsg() == '' ds = None ds = gdal.Open('HDF5:"data/CSK_DGM.h5"://S01/SBI') got_gcpprojection = ds.GetGCPProjection() - if got_gcpprojection.find('GEOGCS["WGS 84",DATUM["WGS_1984"') != 0: - print(got_gcpprojection) - gdaltest.post_reason('fail') - return 'fail' + assert got_gcpprojection.find('GEOGCS["WGS 84",DATUM["WGS_1984"') == 0 got_gcps = ds.GetGCPs() - if len(got_gcps) != 4: - gdaltest.post_reason('fail') - return 'fail' + assert len(got_gcps) == 4 - if abs(got_gcps[0].GCPPixel - 0) > 1e-5 or abs(got_gcps[0].GCPLine - 0) > 1e-5 or \ - abs(got_gcps[0].GCPX - 12.2395902509238) > 1e-5 or abs(got_gcps[0].GCPY - 44.7280047434954) > 1e-5: - gdaltest.post_reason('fail') - return 'fail' + assert (abs(got_gcps[0].GCPPixel - 0) <= 1e-5 and abs(got_gcps[0].GCPLine - 0) <= 1e-5 and \ + abs(got_gcps[0].GCPX - 12.2395902509238) <= 1e-5 and abs(got_gcps[0].GCPY - 44.7280047434954) <= 1e-5) ds = None - if gdaltest.is_file_open('data/CSK_DGM.h5'): - gdaltest.post_reason('file still opened.') - return 'fail' - - return 'success' + assert not gdaltest.is_file_open('data/CSK_DGM.h5'), 'file still opened.' ############################################################################### # Test CSK_GEC.h5 (#4160) -def hdf5_11(): - - if gdaltest.hdf5_drv is None: - return 'skip' +def test_hdf5_11(): # Try opening the QLK subdataset to check that no error is generated gdal.ErrorReset() ds = gdal.Open('HDF5:"data/CSK_GEC.h5"://S01/QLK') - if ds is None or gdal.GetLastErrorMsg() != '': - gdaltest.post_reason('fail') - return 'fail' + assert ds is not None and gdal.GetLastErrorMsg() == '' ds = None ds = gdal.Open('HDF5:"data/CSK_GEC.h5"://S01/SBI') got_projection = ds.GetProjection() - if got_projection.find('PROJCS["Transverse_Mercator",GEOGCS["WGS 84",DATUM["WGS_1984"') != 0: - print(got_projection) - gdaltest.post_reason('fail') - return 'fail' + assert got_projection.find('PROJCS["Transverse_Mercator",GEOGCS["WGS 84",DATUM["WGS_1984"') == 0 got_gt = ds.GetGeoTransform() expected_gt = (275592.5, 2.5, 0.0, 4998152.5, 0.0, -2.5) for i in range(6): - if abs(got_gt[i] - expected_gt[i]) > 1e-5: - print(got_gt) - gdaltest.post_reason('fail') - return 'fail' + assert abs(got_gt[i] - expected_gt[i]) <= 1e-5 ds = None - if gdaltest.is_file_open('data/CSK_GEC.h5'): - gdaltest.post_reason('file still opened.') - return 'fail' - - return 'success' + assert not gdaltest.is_file_open('data/CSK_GEC.h5'), 'file still opened.' ############################################################################### # Test ODIM_H5 (#5032) -def hdf5_12(): - - if gdaltest.hdf5_drv is None: - return 'skip' +def test_hdf5_12(): if not gdaltest.download_file('http://trac.osgeo.org/gdal/raw-attachment/ticket/5032/norsa.ss.ppi-00.5-dbz.aeqd-1000.20070601T000039Z.hdf', 'norsa.ss.ppi-00.5-dbz.aeqd-1000.20070601T000039Z.hdf'): - return 'skip' + pytest.skip() ds = gdal.Open('tmp/cache/norsa.ss.ppi-00.5-dbz.aeqd-1000.20070601T000039Z.hdf') got_projection = ds.GetProjection() - if got_projection.find('Azimuthal_Equidistant') < 0: - print(got_projection) - gdaltest.post_reason('fail') - return 'fail' + assert got_projection.find('Azimuthal_Equidistant') >= 0 got_gt = ds.GetGeoTransform() expected_gt = (-240890.02470187756, 1001.7181388478905, 0.0, 239638.21326987055, 0.0, -1000.3790932482976) # Proj 4.9.3 expected_gt2 = (-240889.94573659054, 1001.7178235672992, 0.0, 239638.28570609915, 0.0, -1000.3794089534567) - if max([abs(got_gt[i] - expected_gt[i]) for i in range(6)]) > 1e-5 and \ - max([abs(got_gt[i] - expected_gt2[i]) for i in range(6)]) > 1e-5: - print(got_gt) - gdaltest.post_reason('fail') - return 'fail' - - return 'success' + assert (max([abs(got_gt[i] - expected_gt[i]) for i in range(6)]) <= 1e-5 or \ + max([abs(got_gt[i] - expected_gt2[i]) for i in range(6)]) <= 1e-5) ############################################################################### # Test MODIS L2 HDF5 GCPs (#6666) -def hdf5_13(): - - if gdaltest.hdf5_drv is None: - return 'skip' +def test_hdf5_13(): if not gdaltest.download_file('http://oceandata.sci.gsfc.nasa.gov/cgi/getfile/A2016273115000.L2_LAC_OC.nc', 'A2016273115000.L2_LAC_OC.nc'): - return 'skip' + pytest.skip() ds = gdal.Open('HDF5:"tmp/cache/A2016273115000.L2_LAC_OC.nc"://geophysical_data/Kd_490') got_gcps = ds.GetGCPs() - if len(got_gcps) != 3030: - gdaltest.post_reason('fail') - return 'fail' - - if abs(got_gcps[0].GCPPixel - 0.5) > 1e-5 or abs(got_gcps[0].GCPLine - 0.5) > 1e-5 or \ - abs(got_gcps[0].GCPX - 33.1655693) > 1e-5 or abs(got_gcps[0].GCPY - 39.3207207) > 1e-5: - gdaltest.post_reason('fail') - print(got_gcps[0]) - return 'fail' + assert len(got_gcps) == 3030 - return 'success' + assert (abs(got_gcps[0].GCPPixel - 0.5) <= 1e-5 and abs(got_gcps[0].GCPLine - 0.5) <= 1e-5 and \ + abs(got_gcps[0].GCPX - 33.1655693) <= 1e-5 and abs(got_gcps[0].GCPY - 39.3207207) <= 1e-5) ############################################################################### # Test complex data subsets -def hdf5_14(): - - if gdaltest.hdf5_drv is None: - return 'skip' +def test_hdf5_14(): ds = gdal.Open('data/complex.h5') sds_list = ds.GetMetadata('SUBDATASETS') - if len(sds_list) != 6: - print(sds_list) - gdaltest.post_reason('Did not get expected complex subdataset count.') - return 'fail' + assert len(sds_list) == 6, 'Did not get expected complex subdataset count.' - if sds_list['SUBDATASET_1_NAME'] != 'HDF5:"data/complex.h5"://f16' \ - or sds_list['SUBDATASET_2_NAME'] != 'HDF5:"data/complex.h5"://f32' \ - or sds_list['SUBDATASET_3_NAME'] != 'HDF5:"data/complex.h5"://f64': - print(sds_list) - gdaltest.post_reason('did not get expected subdatasets.') - return 'fail' + assert sds_list['SUBDATASET_1_NAME'] == 'HDF5:"data/complex.h5"://f16' and sds_list['SUBDATASET_2_NAME'] == 'HDF5:"data/complex.h5"://f32' and sds_list['SUBDATASET_3_NAME'] == 'HDF5:"data/complex.h5"://f64', \ + 'did not get expected subdatasets.' ds = None - if gdaltest.is_file_open('data/complex.h5'): - gdaltest.post_reason('file still opened.') - return 'fail' - - return 'success' + assert not gdaltest.is_file_open('data/complex.h5'), 'file still opened.' ############################################################################### # Confirm complex subset data access and checksum # Start with Float32 -def hdf5_15(): - - if gdaltest.hdf5_drv is None: - return 'skip' +def test_hdf5_15(): ds = gdal.Open('HDF5:"data/complex.h5"://f32') cs = ds.GetRasterBand(1).Checksum() - if cs != 523: - gdaltest.post_reason('did not get expected checksum') - return 'fail' - - return 'success' + assert cs == 523, 'did not get expected checksum' # Repeat for Float64 -def hdf5_16(): - - if gdaltest.hdf5_drv is None: - return 'skip' +def test_hdf5_16(): ds = gdal.Open('HDF5:"data/complex.h5"://f64') cs = ds.GetRasterBand(1).Checksum() - if cs != 511: - gdaltest.post_reason('did not get expected checksum') - return 'fail' - - return 'success' + assert cs == 511, 'did not get expected checksum' # Repeat for Float16 -def hdf5_17(): - - if gdaltest.hdf5_drv is None: - return 'skip' +def test_hdf5_17(): ds = gdal.Open('HDF5:"data/complex.h5"://f16') cs = ds.GetRasterBand(1).Checksum() - if cs != 412: - gdaltest.post_reason('did not get expected checksum') - return 'fail' - - return 'success' + assert cs == 412, 'did not get expected checksum' -def hdf5_single_char_varname(): - - if gdaltest.hdf5_drv is None: - return 'skip' +def test_hdf5_single_char_varname(): ds = gdal.Open('HDF5:"data/single_char_varname.h5"://e') - if ds is None: - return 'fail' - - return 'success' - + assert ds is not None -def hdf5_virtual_file(): - - if gdaltest.hdf5_drv is None: - return 'skip' +def test_hdf5_virtual_file(): hdf5_files = [ 'CSK_GEC.h5', 'vlstr_metadata.h5', @@ -589,89 +410,34 @@ def hdf5_virtual_file(): 'metadata.h5' ] for hdf5_file in hdf5_files: - if uffd_compare(hdf5_file) is not True: - return 'fail' - - return 'success' - - -class TestHDF5(object): - def __init__(self, downloadURL, fileName, subdatasetname, checksum, download_size): - self.downloadURL = downloadURL - self.fileName = fileName - self.subdatasetname = subdatasetname - self.checksum = checksum - self.download_size = download_size - - def test(self): - if gdaltest.hdf5_drv is None: - return 'skip' - - if not gdaltest.download_file(self.downloadURL + '/' + self.fileName, self.fileName, self.download_size): - return 'skip' - - ds = gdal.Open('HDF5:"tmp/cache/' + self.fileName + '"://' + self.subdatasetname) - - if ds.GetRasterBand(1).Checksum() != self.checksum: - gdaltest.post_reason('Bad checksum. Expected %d, got %d' % (self.checksum, ds.GetRasterBand(1).Checksum())) - return 'fail' - - return 'success' - - - -def hdf5_postcheck(): - - if gdaltest.hdf5_drv is None: - return 'skip' - - diff = len(gdaltest.get_opened_files()) - gdaltest.count_opened_files - if diff != 0: - gdaltest.post_reason('Leak of file handles: %d leaked' % diff) - return 'fail' - - return 'success' - -gdaltest_list = [ - hdf5_1, - hdf5_2, - hdf5_3, - hdf5_4, - hdf5_5, - hdf5_6, - hdf5_7, - hdf5_8, - hdf5_9, - hdf5_10, - hdf5_11, - hdf5_12, - hdf5_13, - hdf5_14, - hdf5_15, - hdf5_16, - hdf5_17, - hdf5_single_char_varname, - hdf5_virtual_file, - hdf5_postcheck, + assert uffd_compare(hdf5_file) is True + + + +# FIXME: This FTP server seems to have disappeared. Replace with something else? +hdf5_list = [ + ('ftp://ftp.hdfgroup.uiuc.edu/pub/outgoing/hdf_files/hdf5/samples/convert', 'C1979091.h5', + 'HDF4_PALGROUP/HDF4_PALETTE_2', 7488, -1), + ('ftp://ftp.hdfgroup.uiuc.edu/pub/outgoing/hdf_files/hdf5/samples/convert', 'C1979091.h5', + 'Raster_Image_#0', 3661, -1), + ('ftp://ftp.hdfgroup.uiuc.edu/pub/outgoing/hdf_files/hdf5/geospatial/DEM', 'half_moon_bay.grid', + 'HDFEOS/GRIDS/DEMGRID/Data_Fields/Elevation', 30863, -1), ] -hdf5_list = [('ftp://ftp.hdfgroup.uiuc.edu/pub/outgoing/hdf_files/hdf5/samples/convert', 'C1979091.h5', - 'HDF4_PALGROUP/HDF4_PALETTE_2', 7488, -1), - ('ftp://ftp.hdfgroup.uiuc.edu/pub/outgoing/hdf_files/hdf5/samples/convert', 'C1979091.h5', - 'Raster_Image_#0', 3661, -1), - ('ftp://ftp.hdfgroup.uiuc.edu/pub/outgoing/hdf_files/hdf5/geospatial/DEM', 'half_moon_bay.grid', - 'HDFEOS/GRIDS/DEMGRID/Data_Fields/Elevation', 30863, -1), - ] -for item in hdf5_list: - ut = TestHDF5(item[0], item[1], item[2], item[3], item[4]) - gdaltest_list.append((ut.test, 'HDF5:"' + item[1] + '"://' + item[2])) +@pytest.mark.parametrize( + 'downloadURL,fileName,subdatasetname,checksum,download_size', + hdf5_list, + ids=['HDF5:"' + item[1] + '"://' + item[2] for item in hdf5_list], +) +def test_hdf5(downloadURL, fileName, subdatasetname, checksum, download_size): + if not gdaltest.download_file(downloadURL + '/' + fileName, fileName, download_size): + pytest.skip('no download') + + ds = gdal.Open('HDF5:"tmp/cache/' + fileName + '"://' + subdatasetname) + assert ds.GetRasterBand(1).Checksum() == checksum, 'Bad checksum. Expected %d, got %d' % (checksum, ds.GetRasterBand(1).Checksum()) -if __name__ == '__main__': - gdaltest.setup_run('hdf5') - gdaltest.run_tests(gdaltest_list) - sys.exit(gdaltest.summarize()) diff --git a/autotest/gdrivers/hf2.py b/autotest/gdrivers/hf2.py index 2dc0fa0fb256..f3fba5bce9f0 100755 --- a/autotest/gdrivers/hf2.py +++ b/autotest/gdrivers/hf2.py @@ -29,9 +29,7 @@ ############################################################################### import os -import sys -sys.path.append('../pymod') import gdaltest @@ -39,7 +37,7 @@ # Test CreateCopy() of byte.tif -def hf2_1(): +def test_hf2_1(): tst = gdaltest.GDALTest('HF2', 'byte.tif', 1, 4672) return tst.testCreateCopy(vsimem=1, check_gt=(-67.00041667, 0.00083333, 0.0, 50.000416667, 0.0, -0.00083333)) @@ -48,7 +46,7 @@ def hf2_1(): # Test CreateCopy() of byte.tif with options -def hf2_2(): +def test_hf2_2(): tst = gdaltest.GDALTest('HF2', 'byte.tif', 1, 4672, options=['COMPRESS=YES', 'BLOCKSIZE=10']) ret = tst.testCreateCopy(new_filename='tmp/hf2_2.hfz') @@ -62,7 +60,7 @@ def hf2_2(): # Test CreateCopy() of float.img -def hf2_3(): +def test_hf2_3(): tst = gdaltest.GDALTest('HF2', 'float.img', 1, 23529) return tst.testCreateCopy(check_minmax=0) @@ -71,7 +69,7 @@ def hf2_3(): # Test CreateCopy() of n43.dt0 -def hf2_4(): +def test_hf2_4(): tst = gdaltest.GDALTest('HF2', 'n43.dt0', 1, 49187) return tst.testCreateCopy() @@ -80,22 +78,8 @@ def hf2_4(): # Cleanup -def hf2_cleanup(): +def test_hf2_cleanup(): - return 'success' + pass -gdaltest_list = [ - hf2_1, - hf2_2, - hf2_3, - hf2_4, - hf2_cleanup] - -if __name__ == '__main__': - - gdaltest.setup_run('hf2') - - gdaltest.run_tests(gdaltest_list) - - sys.exit(gdaltest.summarize()) diff --git a/autotest/gdrivers/hfa.py b/autotest/gdrivers/hfa.py index 4fd1824b6a01..5b0be5b6db9c 100755 --- a/autotest/gdrivers/hfa.py +++ b/autotest/gdrivers/hfa.py @@ -30,60 +30,44 @@ ############################################################################### import os -import sys import array from osgeo import gdal -sys.path.append('../pymod') import gdaltest +import pytest ############################################################################### # Verify we can read the special histogram metadata from a provided image. -def hfa_histread(): +def test_hfa_histread(): ds = gdal.Open('../gcore/data/utmsmall.img') md = ds.GetRasterBand(1).GetMetadata() ds = None - if md['STATISTICS_MINIMUM'] != '8': - gdaltest.post_reason('STATISTICS_MINIMUM is wrong.') - return 'fail' + assert md['STATISTICS_MINIMUM'] == '8', 'STATISTICS_MINIMUM is wrong.' - if md['STATISTICS_MEDIAN'] != '148': - gdaltest.post_reason('STATISTICS_MEDIAN is wrong.') - return 'fail' + assert md['STATISTICS_MEDIAN'] == '148', 'STATISTICS_MEDIAN is wrong.' - if md['STATISTICS_HISTOMAX'] != '255': - gdaltest.post_reason('STATISTICS_HISTOMAX is wrong.') - return 'fail' + assert md['STATISTICS_HISTOMAX'] == '255', 'STATISTICS_HISTOMAX is wrong.' - if md['STATISTICS_HISTOBINVALUES'] != '0|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|': - gdaltest.post_reason('STATISTICS_HISTOBINVALUES is wrong.') - return 'fail' + assert md['STATISTICS_HISTOBINVALUES'] == '0|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|', \ + 'STATISTICS_HISTOBINVALUES is wrong.' - if md['STATISTICS_SKIPFACTORX'] != '1': - gdaltest.post_reason('STATISTICS_SKIPFACTORX is wrong.') - return 'fail' + assert md['STATISTICS_SKIPFACTORX'] == '1', 'STATISTICS_SKIPFACTORX is wrong.' - if md['STATISTICS_SKIPFACTORY'] != '1': - gdaltest.post_reason('STATISTICS_SKIPFACTORY is wrong.') - return 'fail' + assert md['STATISTICS_SKIPFACTORY'] == '1', 'STATISTICS_SKIPFACTORY is wrong.' - if md['STATISTICS_EXCLUDEDVALUES'] != '0': - gdaltest.post_reason('STATISTICS_EXCLUDEDVALUE is wrong.') - return 'fail' - - return 'success' + assert md['STATISTICS_EXCLUDEDVALUES'] == '0', 'STATISTICS_EXCLUDEDVALUE is wrong.' ############################################################################### # Verify that if we copy this test image to a new Imagine file the histogram # info is preserved. -def hfa_histwrite(): +def test_hfa_histwrite(): drv = gdal.GetDriverByName('HFA') ds_src = gdal.Open('../gcore/data/utmsmall.img') @@ -102,30 +86,21 @@ def hfa_histwrite(): drv.Delete('tmp/work.img') - if md['STATISTICS_MINIMUM'] != '8': - gdaltest.post_reason('STATISTICS_MINIMUM is wrong.') - return 'fail' - - if md['STATISTICS_MEDIAN'] != '148': - gdaltest.post_reason('STATISTICS_MEDIAN is wrong.') - return 'fail' + assert md['STATISTICS_MINIMUM'] == '8', 'STATISTICS_MINIMUM is wrong.' - if md['STATISTICS_HISTOMAX'] != '255': - gdaltest.post_reason('STATISTICS_HISTOMAX is wrong.') - return 'fail' + assert md['STATISTICS_MEDIAN'] == '148', 'STATISTICS_MEDIAN is wrong.' - if md['STATISTICS_HISTOBINVALUES'] != '0|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|': - gdaltest.post_reason('STATISTICS_HISTOBINVALUES is wrong.') - return 'fail' + assert md['STATISTICS_HISTOMAX'] == '255', 'STATISTICS_HISTOMAX is wrong.' - return 'success' + assert md['STATISTICS_HISTOBINVALUES'] == '0|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|', \ + 'STATISTICS_HISTOBINVALUES is wrong.' ############################################################################### # Verify that if we copy this test image to a new Imagine file and then re-write the # histogram information, the new histogram can then be read back in. -def hfa_histrewrite(): +def test_hfa_histrewrite(): drv = gdal.GetDriverByName('HFA') ds_src = gdal.Open('../gcore/data/utmsmall.img') @@ -156,57 +131,37 @@ def hfa_histrewrite(): drv.Delete('tmp/work.img') - if histStr != newHist: - gdaltest.post_reason('Rewritten STATISTICS_HISTOBINVALUES is wrong.') - return 'fail' - - return 'success' + assert histStr == newHist, 'Rewritten STATISTICS_HISTOBINVALUES is wrong.' ############################################################################### # Verify we can read metadata of int.img. -def hfa_int_stats_1(): +def test_hfa_int_stats_1(): ds = gdal.Open('data/int.img') md = ds.GetRasterBand(1).GetMetadata() ds = None - if md['STATISTICS_MINIMUM'] != '40918': - gdaltest.post_reason('STATISTICS_MINIMUM is wrong.') - return 'fail' + assert md['STATISTICS_MINIMUM'] == '40918', 'STATISTICS_MINIMUM is wrong.' - if md['STATISTICS_MAXIMUM'] != '41134': - gdaltest.post_reason('STATISTICS_MAXIMUM is wrong.') - return 'fail' + assert md['STATISTICS_MAXIMUM'] == '41134', 'STATISTICS_MAXIMUM is wrong.' - if md['STATISTICS_MEDIAN'] != '41017': - gdaltest.post_reason('STATISTICS_MEDIAN is wrong.') - return 'fail' + assert md['STATISTICS_MEDIAN'] == '41017', 'STATISTICS_MEDIAN is wrong.' - if md['STATISTICS_MODE'] != '41013': - gdaltest.post_reason('STATISTICS_MODE is wrong.') - return 'fail' + assert md['STATISTICS_MODE'] == '41013', 'STATISTICS_MODE is wrong.' - if md['STATISTICS_HISTOMIN'] != '40918': - gdaltest.post_reason('STATISTICS_HISTOMIN is wrong.') - return 'fail' + assert md['STATISTICS_HISTOMIN'] == '40918', 'STATISTICS_HISTOMIN is wrong.' - if md['STATISTICS_HISTOMAX'] != '41134': - gdaltest.post_reason('STATISTICS_HISTOMAX is wrong.') - return 'fail' + assert md['STATISTICS_HISTOMAX'] == '41134', 'STATISTICS_HISTOMAX is wrong.' - if md['LAYER_TYPE'] != 'athematic': - gdaltest.post_reason('LAYER_TYPE is wrong.') - return 'fail' - - return 'success' + assert md['LAYER_TYPE'] == 'athematic', 'LAYER_TYPE is wrong.' ############################################################################### # Verify we can read band statistics of int.img. -def hfa_int_stats_2(): +def test_hfa_int_stats_2(): ds = gdal.Open('data/int.img') stats = ds.GetRasterBand(1).GetStatistics(False, True) @@ -214,29 +169,19 @@ def hfa_int_stats_2(): tolerance = 0.0001 - if abs(stats[0] - 40918.0) > tolerance: - gdaltest.post_reason('Minimum value is wrong.') - return 'fail' - - if abs(stats[1] - 41134.0) > tolerance: - gdaltest.post_reason('Maximum value is wrong.') - return 'fail' + assert abs(stats[0] - 40918.0) <= tolerance, 'Minimum value is wrong.' - if abs(stats[2] - 41019.784218148) > tolerance: - gdaltest.post_reason('Mean value is wrong.') - return 'fail' + assert abs(stats[1] - 41134.0) <= tolerance, 'Maximum value is wrong.' - if abs(stats[3] - 44.637237445468) > tolerance: - gdaltest.post_reason('StdDev value is wrong.') - return 'fail' + assert abs(stats[2] - 41019.784218148) <= tolerance, 'Mean value is wrong.' - return 'success' + assert abs(stats[3] - 44.637237445468) <= tolerance, 'StdDev value is wrong.' ############################################################################### # Verify we can read metadata of float.img. -def hfa_float_stats_1(): +def test_hfa_float_stats_1(): ds = gdal.Open('data/float.img') md = ds.GetRasterBand(1).GetMetadata() @@ -245,46 +190,30 @@ def hfa_float_stats_1(): tolerance = 0.0001 mini = float(md['STATISTICS_MINIMUM']) - if abs(mini - 40.91858291626) > tolerance: - gdaltest.post_reason('STATISTICS_MINIMUM is wrong.') - return 'fail' + assert abs(mini - 40.91858291626) <= tolerance, 'STATISTICS_MINIMUM is wrong.' maxi = float(md['STATISTICS_MAXIMUM']) - if abs(maxi - 41.134323120117) > tolerance: - gdaltest.post_reason('STATISTICS_MAXIMUM is wrong.') - return 'fail' + assert abs(maxi - 41.134323120117) <= tolerance, 'STATISTICS_MAXIMUM is wrong.' median = float(md['STATISTICS_MEDIAN']) - if abs(median - 41.017182931304) > tolerance: - gdaltest.post_reason('STATISTICS_MEDIAN is wrong.') - return 'fail' + assert abs(median - 41.017182931304) <= tolerance, 'STATISTICS_MEDIAN is wrong.' mod = float(md['STATISTICS_MODE']) - if abs(mod - 41.0104410499) > tolerance: - gdaltest.post_reason('STATISTICS_MODE is wrong.') - return 'fail' + assert abs(mod - 41.0104410499) <= tolerance, 'STATISTICS_MODE is wrong.' histMin = float(md['STATISTICS_HISTOMIN']) - if abs(histMin - 40.91858291626) > tolerance: - gdaltest.post_reason('STATISTICS_HISTOMIN is wrong.') - return 'fail' + assert abs(histMin - 40.91858291626) <= tolerance, 'STATISTICS_HISTOMIN is wrong.' histMax = float(md['STATISTICS_HISTOMAX']) - if abs(histMax - 41.134323120117) > tolerance: - gdaltest.post_reason('STATISTICS_HISTOMAX is wrong.') - return 'fail' - - if md['LAYER_TYPE'] != 'athematic': - gdaltest.post_reason('LAYER_TYPE is wrong.') - return 'fail' + assert abs(histMax - 41.134323120117) <= tolerance, 'STATISTICS_HISTOMAX is wrong.' - return 'success' + assert md['LAYER_TYPE'] == 'athematic', 'LAYER_TYPE is wrong.' ############################################################################### # Verify we can read band statistics of float.img. -def hfa_float_stats_2(): +def test_hfa_float_stats_2(): ds = gdal.Open('data/float.img') stats = ds.GetRasterBand(1).GetStatistics(False, True) @@ -292,29 +221,19 @@ def hfa_float_stats_2(): tolerance = 0.0001 - if abs(stats[0] - 40.91858291626) > tolerance: - gdaltest.post_reason('Minimum value is wrong.') - return 'fail' + assert abs(stats[0] - 40.91858291626) <= tolerance, 'Minimum value is wrong.' - if abs(stats[1] - 41.134323120117) > tolerance: - gdaltest.post_reason('Maximum value is wrong.') - return 'fail' + assert abs(stats[1] - 41.134323120117) <= tolerance, 'Maximum value is wrong.' - if abs(stats[2] - 41.020284249223) > tolerance: - gdaltest.post_reason('Mean value is wrong.') - return 'fail' + assert abs(stats[2] - 41.020284249223) <= tolerance, 'Mean value is wrong.' - if abs(stats[3] - 0.044636441749041) > tolerance: - gdaltest.post_reason('StdDev value is wrong.') - return 'fail' - - return 'success' + assert abs(stats[3] - 0.044636441749041) <= tolerance, 'StdDev value is wrong.' ############################################################################### # Verify we can read image data. -def hfa_int_read(): +def test_hfa_int_read(): ds = gdal.Open('data/int.img') band = ds.GetRasterBand(1) @@ -322,17 +241,13 @@ def hfa_int_read(): band.ReadRaster(100, 100, 1, 1) ds = None - if cs != 6691: - gdaltest.post_reason('Checksum value is wrong.') - return 'fail' - - return 'success' + assert cs == 6691, 'Checksum value is wrong.' ############################################################################### # Verify we can read image data. -def hfa_float_read(): +def test_hfa_float_read(): ds = gdal.Open('data/float.img') band = ds.GetRasterBand(1) @@ -340,42 +255,31 @@ def hfa_float_read(): data = band.ReadRaster(100, 100, 1, 1) ds = None - if cs != 23529: - gdaltest.post_reason('Checksum value is wrong.') - return 'fail' + assert cs == 23529, 'Checksum value is wrong.' # Read raw data into tuple of float numbers import struct value = struct.unpack('f' * 1, data)[0] - if abs(value - 41.021659851074219) > 0.0001: - gdaltest.post_reason('Pixel value is wrong.') - return 'fail' - - return 'success' + assert abs(value - 41.021659851074219) <= 0.0001, 'Pixel value is wrong.' ############################################################################### # verify we can read PE_STRING coordinate system. -def hfa_pe_read(): +def test_hfa_pe_read(): ds = gdal.Open('data/87test.img') wkt = ds.GetProjectionRef() expected = 'PROJCS["World_Cube",GEOGCS["GCS_WGS_1984",DATUM["WGS_1984",SPHEROID["WGS_84",6378137.0,298.257223563]],PRIMEM["Greenwich",0.0],UNIT["Degree",0.0174532925199433]],PROJECTION["Cube"],PARAMETER["False_Easting",0.0],PARAMETER["False_Northing",0.0],PARAMETER["Central_Meridian",0.0],PARAMETER["Option",1.0],UNIT["Meter",1.0]]' - if wkt != expected: - print(wkt) - gdaltest.post_reason('failed to read pe string as expected.') - return 'fail' - - return 'success' + assert wkt == expected, 'failed to read pe string as expected.' ############################################################################### # Verify we can write PE_STRING nodes. -def hfa_pe_write(): +def test_hfa_pe_write(): drv = gdal.GetDriverByName('HFA') ds_src = gdal.Open('data/87test.img') @@ -390,20 +294,16 @@ def hfa_pe_write(): if wkt != expected: print('') - print(expected) - print(wkt) - gdaltest.post_reason('failed to write pe string as expected.') - return 'fail' + pytest.fail('failed to write pe string as expected.') ds = None drv.Delete('tmp/87test.img') - return 'success' ############################################################################### # Verify we can write and read large metadata items. -def hfa_metadata_1(): +def test_hfa_metadata_1(): drv = gdal.GetDriverByName('HFA') ds = drv.Create('tmp/md_1.img', 100, 150, 1, gdal.GDT_Byte) @@ -415,21 +315,15 @@ def hfa_metadata_1(): ds = gdal.Open('tmp/md_1.img') md = ds.GetRasterBand(1).GetMetadata() - if md['test'] != md_val: - print(md['test']) - print(md_val) - gdaltest.post_reason('got wrong metadata back') - return 'fail' + assert md['test'] == md_val, 'got wrong metadata back' ds = None - return 'success' - ############################################################################### # Verify that writing metadata multiple times does not result in duplicate # nodes. -def hfa_metadata_2(): +def test_hfa_metadata_2(): ds = gdal.Open('tmp/md_1.img', gdal.GA_Update) md = ds.GetRasterBand(1).GetMetadata() @@ -440,26 +334,19 @@ def hfa_metadata_2(): ds = gdal.Open('tmp/md_1.img') md = ds.GetRasterBand(1).GetMetadata() - if 'xxx' not in md: - gdaltest.post_reason('metadata rewrite seems not to have worked') - return 'fail' + assert 'xxx' in md, 'metadata rewrite seems not to have worked' - if md['xxx'] != '123' or md['test'] != '0123456789': - print(md) - gdaltest.post_reason('got wrong metadata back') - return 'fail' + assert md['xxx'] == '123' and md['test'] == '0123456789', 'got wrong metadata back' ds = None gdal.GetDriverByName('HFA').Delete('tmp/md_1.img') - return 'success' - ############################################################################### # Verify we can grow the RRD list in cases where this requires # moving the HFAEntry to the end of the file. (bug #1109) -def hfa_grow_rrdlist(): +def test_hfa_grow_rrdlist(): import shutil @@ -471,27 +358,20 @@ def hfa_grow_rrdlist(): result = ds.BuildOverviews(overviewlist=[4, 8]) ds = None - if result != 0: - gdaltest.post_reason('BuildOverviews failed.') - return 'fail' + assert result == 0, 'BuildOverviews failed.' # Verify overviews are now findable. ds = gdal.Open('tmp/bug_1109.img') - if ds.GetRasterBand(1).GetOverviewCount() != 3: - gdaltest.post_reason('Overview count wrong.') - print(ds.GetRasterBand(1).GetOverviewCount()) - return 'fail' + assert ds.GetRasterBand(1).GetOverviewCount() == 3, 'Overview count wrong.' ds = None gdal.GetDriverByName('HFA').Delete('tmp/bug_1109.img') - return 'success' - ############################################################################### # Make sure an old .ige file is deleted when creating a new dataset. (#1784) -def hfa_clean_ige(): +def test_hfa_clean_ige(): # Create an imagine file, forcing creation of an .ige file. @@ -505,8 +385,7 @@ def hfa_clean_ige(): try: open('tmp/igetest.ige') except IOError: - gdaltest.post_reason('ige file not created with USE_SPILL=YES') - return 'fail' + pytest.fail('ige file not created with USE_SPILL=YES') # confirm ige shows up in file list. ds = gdal.Open('tmp/igetest.img') @@ -520,30 +399,24 @@ def hfa_clean_ige(): if not found: print(filelist) - gdaltest.post_reason('no igetest.ige in file list!') - return 'fail' + pytest.fail('no igetest.ige in file list!') # Create a file without a spill file, and verify old ige cleaned up. out_ds = drv.CreateCopy('tmp/igetest.img', src_ds) del out_ds - try: + with pytest.raises(IOError, message='ige file not cleaned up properly.'): open('tmp/igetest.ige') - gdaltest.post_reason('ige file not cleaned up properly.') - return 'fail' - except IOError: - pass + drv.Delete('tmp/igetest.img') - return 'success' - ############################################################################### # Verify that we can read this corrupt .aux file without hanging (#1907) -def hfa_corrupt_aux(): +def test_hfa_corrupt_aux(): # NOTE: we depend on being able to open .aux files as a weak sort of # dataset. @@ -552,24 +425,18 @@ def hfa_corrupt_aux(): ds = gdal.Open('data/F0116231.aux') gdal.PopErrorHandler() - if ds.RasterXSize != 1104: - gdaltest.post_reason('did not get expected dataset characteristics') - return 'fail' + assert ds.RasterXSize == 1104, 'did not get expected dataset characteristics' - if gdal.GetLastErrorType() != 2 \ - or gdal.GetLastErrorMsg().find('Corrupt (looping)') == -1: - gdaltest.post_reason('Did not get expected warning.') - return 'fail' + assert gdal.GetLastErrorType() == 2 and gdal.GetLastErrorMsg().find('Corrupt (looping)') != -1, \ + 'Did not get expected warning.' ds = None - return 'success' - ############################################################################### # support MapInformation for units (#1967) -def hfa_mapinformation_units(): +def test_hfa_mapinformation_units(): # NOTE: we depend on being able to open .aux files as a weak sort of # dataset. @@ -582,14 +449,14 @@ def hfa_mapinformation_units(): expected_wkt = """PROJCS["NAD_1983_StatePlane_Virginia_North_FIPS_4501_Feet",GEOGCS["GCS_North_American_1983",DATUM["North_American_Datum_1983",SPHEROID["GRS_1980",6378137,298.257222101]],PRIMEM["Greenwich",0],UNIT["Degree",0.0174532925199432955],AUTHORITY["EPSG","4269"]],PROJECTION["Lambert_Conformal_Conic_2SP"],PARAMETER["False_Easting",11482916.66666666],PARAMETER["False_Northing",6561666.666666666],PARAMETER["Central_Meridian",-78.5],PARAMETER["Standard_Parallel_1",38.03333333333333],PARAMETER["Standard_Parallel_2",39.2],PARAMETER["Latitude_Of_Origin",37.66666666666666],UNIT["Foot_US",0.304800609601219241]]""" if gdaltest.equal_srs_from_wkt(expected_wkt, wkt): - return 'success' - return 'fail' + return + pytest.fail() ############################################################################### # Write nodata value. -def hfa_nodata_write(): +def test_hfa_nodata_write(): drv = gdal.GetDriverByName('HFA') ds = drv.Create('tmp/nodata.img', 7, 7, 1, gdal.GDT_Byte) @@ -606,53 +473,39 @@ def hfa_nodata_write(): ds = None - return 'success' - ############################################################################### # Verify written nodata value. -def hfa_nodata_read(): +def test_hfa_nodata_read(): ds = gdal.Open('tmp/nodata.img') b = ds.GetRasterBand(1) - if b.GetNoDataValue() != 1: - gdaltest.post_reason('failed to preserve nodata value') - return 'fail' + assert b.GetNoDataValue() == 1, 'failed to preserve nodata value' stats = b.GetStatistics(False, True) tolerance = 0.0001 - if abs(stats[0] - 2) > tolerance: - gdaltest.post_reason('Minimum value is wrong.') - return 'fail' + assert abs(stats[0] - 2) <= tolerance, 'Minimum value is wrong.' - if abs(stats[1] - 4) > tolerance: - gdaltest.post_reason('Maximum value is wrong.') - return 'fail' + assert abs(stats[1] - 4) <= tolerance, 'Maximum value is wrong.' - if abs(stats[2] - 2.6666666666667) > tolerance: - gdaltest.post_reason('Mean value is wrong.') - return 'fail' + assert abs(stats[2] - 2.6666666666667) <= tolerance, 'Mean value is wrong.' - if abs(stats[3] - 0.94280904158206) > tolerance: - gdaltest.post_reason('StdDev value is wrong.') - return 'fail' + assert abs(stats[3] - 0.94280904158206) <= tolerance, 'StdDev value is wrong.' b = None ds = None gdal.GetDriverByName('HFA').Delete('tmp/nodata.img') - return 'success' - ############################################################################### # Verify we read simple affine geotransforms properly. -def hfa_rotated_read(): +def test_hfa_rotated_read(): ds = gdal.Open('data/fg118-91.aux') @@ -667,17 +520,15 @@ def hfa_rotated_read(): print('') print('old = ', check_gt) print('new = ', new_gt) - gdaltest.post_reason('Geotransform differs.') - return 'fail' + pytest.fail('Geotransform differs.') ds = None - return 'success' ############################################################################### # Verify we can write affine geotransforms. -def hfa_rotated_write(): +def test_hfa_rotated_write(): # make sure we aren't preserving info in .aux.xml file try: @@ -731,24 +582,20 @@ def hfa_rotated_write(): print('') print('old = ', check_gt) print('new = ', new_gt) - gdaltest.post_reason('Geotransform differs.') - return 'fail' + pytest.fail('Geotransform differs.') wkt = ds.GetProjection() - if not gdaltest.equal_srs_from_wkt(expected_wkt, wkt): - return 'fail' + assert gdaltest.equal_srs_from_wkt(expected_wkt, wkt) ds = None gdal.GetDriverByName('HFA').Delete('tmp/rot.img') - return 'success' - ############################################################################### # Test creating an in memory copy. -def hfa_vsimem(): +def test_hfa_vsimem(): tst = gdaltest.GDALTest('HFA', 'byte.tif', 1, 4672) @@ -759,7 +606,7 @@ def hfa_vsimem(): # the .img file. (#2422) -def hfa_proName(): +def test_hfa_proName(): drv = gdal.GetDriverByName('HFA') src_ds = gdal.Open('data/stateplane.vrt') @@ -794,7 +641,7 @@ def hfa_proName(): ############################################################################### # Read a compressed file where no block has been written (#2523) -def hfa_read_empty_compressed(): +def test_hfa_read_empty_compressed(): drv = gdal.GetDriverByName('HFA') ds = drv.Create('tmp/emptycompressed.img', 64, 64, 1, options=['COMPRESSED=YES']) @@ -816,89 +663,59 @@ def hfa_read_empty_compressed(): # Verify "unique values" based color table (#2419) -def hfa_unique_values_color_table(): +def test_hfa_unique_values_color_table(): ds = gdal.Open('data/i8u_c_i.img') ct = ds.GetRasterBand(1).GetRasterColorTable() - if ct.GetCount() != 256: - print(ct.GetCount()) - gdaltest.post_reason('got wrong color count') - return 'fail' - - if ct.GetColorEntry(253) != (0, 0, 0, 0) \ - or ct.GetColorEntry(254) != (255, 255, 170, 255) \ - or ct.GetColorEntry(255) != (255, 255, 255, 255): - - print(ct.GetColorEntry(253)) - print(ct.GetColorEntry(254)) - print(ct.GetColorEntry(255)) + assert ct.GetCount() == 256, 'got wrong color count' - gdaltest.post_reason('Got wrong colors') - return 'fail' + assert ct.GetColorEntry(253) == (0, 0, 0, 0) and ct.GetColorEntry(254) == (255, 255, 170, 255) and ct.GetColorEntry(255) == (255, 255, 255, 255), \ + 'Got wrong colors' ct = None ds = None - return 'success' - ############################################################################### # Verify "unique values" based histogram. -def hfa_unique_values_hist(): +def test_hfa_unique_values_hist(): try: gdal.RasterAttributeTable() except: - return 'skip' + pytest.skip() ds = gdal.Open('data/i8u_c_i.img') md = ds.GetRasterBand(1).GetMetadata() expected = '12603|1|0|0|45|1|0|0|0|0|656|177|0|0|5026|1062|0|0|2|0|0|0|0|0|0|0|0|0|0|0|0|0|75|1|0|0|207|158|0|0|8|34|0|0|0|0|538|57|0|10|214|20|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|1|31|0|0|9|625|67|0|0|118|738|117|3004|1499|491|187|1272|513|1|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|16|3|0|0|283|123|5|1931|835|357|332|944|451|80|40|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|12|5|0|0|535|1029|118|0|33|246|342|0|0|10|8|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|169|439|0|0|6|990|329|0|0|120|295|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|164|42|0|0|570|966|0|0|18|152|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|45|106|0|0|16|16517|' - if md['STATISTICS_HISTOBINVALUES'] != expected: - print(md['STATISTICS_HISTOBINVALUES']) - gdaltest.post_reason('Unexpected HISTOBINVALUES.') - return 'fail' + assert md['STATISTICS_HISTOBINVALUES'] == expected, 'Unexpected HISTOBINVALUES.' - if md['STATISTICS_HISTOMIN'] != '0' \ - or md['STATISTICS_HISTOMAX'] != '255': - print(md) - gdaltest.post_reason("unexpected histomin/histomax value.") - return 'fail' + assert md['STATISTICS_HISTOMIN'] == '0' and md['STATISTICS_HISTOMAX'] == '255', \ + "unexpected histomin/histomax value." # lets also check the RAT to ensure it has the BinValues column added. rat = ds.GetRasterBand(1).GetDefaultRAT() - if rat.GetColumnCount() != 6 \ - or rat.GetTypeOfCol(0) != gdal.GFT_Real \ - or rat.GetUsageOfCol(0) != gdal.GFU_MinMax: - print(rat.GetColumnCount()) - print(rat.GetTypeOfCol(0)) - print(rat.GetUsageOfCol(0)) - gdaltest.post_reason('BinValues column wrong.') - return 'fail' + assert rat.GetColumnCount() == 6 and rat.GetTypeOfCol(0) == gdal.GFT_Real and rat.GetUsageOfCol(0) == gdal.GFU_MinMax, \ + 'BinValues column wrong.' - if rat.GetValueAsInt(2, 0) != 4: - print(rat.GetValueAsInt(2, 0)) - gdaltest.post_reason('BinValues value wrong.') - return 'fail' + assert rat.GetValueAsInt(2, 0) == 4, 'BinValues value wrong.' rat = None ds = None - return 'success' - ############################################################################### # Verify reading of 3rd order XFORM polynomials. -def hfa_xforms_3rd(): +def test_hfa_xforms_3rd(): ds = gdal.Open('data/42BW_420730_VT2.aux') @@ -918,44 +735,30 @@ def hfa_xforms_3rd(): try: value = float(xform_md[check_item[0]]) except (TypeError, ValueError): - gdaltest.post_reason('metadata item %d missing' % check_item[0]) - return 'fail' + pytest.fail('metadata item %d missing' % check_item[0]) - if abs(value - check_item[1]) > abs(value / 100000.0): - gdaltest.post_reason('metadata item %s has wrong value: %.15g' % + assert abs(value - check_item[1]) <= abs(value / 100000.0), \ + ('metadata item %s has wrong value: %.15g' % (check_item[0], value)) - return 'fail' # Check that the GCPs are as expected implying that the evaluation # function for XFORMs if working ok. gcps = ds.GetGCPs() - if gcps[0].GCPPixel != 0.5 \ - or gcps[0].GCPLine != 0.5 \ - or abs(gcps[0].GCPX - 1667635.007) > 0.001 \ - or abs(gcps[0].GCPY - 2620003.171) > 0.001: - print(gcps[0].GCPPixel, gcps[0].GCPLine, gcps[0].GCPX, gcps[0].GCPY) - gdaltest.post_reason('GCP 0 value wrong.') - return 'fail' - - if abs(gcps[14].GCPPixel - 1769.7) > 0.1 \ - or abs(gcps[14].GCPLine - 2124.9) > 0.1 \ - or abs(gcps[14].GCPX - 1665221.064) > 0.001 \ - or abs(gcps[14].GCPY - 2632414.379) > 0.001: - print(gcps[14].GCPPixel, gcps[14].GCPLine, gcps[14].GCPX, gcps[14].GCPY) - gdaltest.post_reason('GCP 14 value wrong.') - return 'fail' + assert gcps[0].GCPPixel == 0.5 and gcps[0].GCPLine == 0.5 and abs(gcps[0].GCPX - 1667635.007) <= 0.001 and abs(gcps[0].GCPY - 2620003.171) <= 0.001, \ + 'GCP 0 value wrong.' - ds = None + assert abs(gcps[14].GCPPixel - 1769.7) <= 0.1 and abs(gcps[14].GCPLine - 2124.9) <= 0.1 and abs(gcps[14].GCPX - 1665221.064) <= 0.001 and abs(gcps[14].GCPY - 2632414.379) <= 0.001, \ + 'GCP 14 value wrong.' - return 'success' + ds = None ############################################################################### # Verify that we can clear an existing color table -def hfa_delete_colortable(): +def test_hfa_delete_colortable(): # copy a file to tmp dir to modify. open('tmp/i8u.img', 'wb').write(open('data/i8u_c_i.img', 'rb').read()) @@ -970,28 +773,24 @@ def hfa_delete_colortable(): # value for them ds = None gdal.GetDriverByName('HFA').Delete('tmp/i8u.img') - return 'skip' + pytest.skip() ds.GetRasterBand(1).SetColorTable(None) ds = None # check color table gone. ds = gdal.Open('tmp/i8u.img') - if ds.GetRasterBand(1).GetColorTable() is not None: - gdaltest.post_reason('failed to remove color table') - return 'fail' + assert ds.GetRasterBand(1).GetColorTable() is None, 'failed to remove color table' ds = None gdal.GetDriverByName('HFA').Delete('tmp/i8u.img') - return 'success' - ############################################################################### # Verify that we can clear an existing color table (#2842) -def hfa_delete_colortable2(): +def test_hfa_delete_colortable2(): # copy a file to tmp dir to modify. src_ds = gdal.Open('../gcore/data/8bit_pal.bmp') @@ -1010,44 +809,37 @@ def hfa_delete_colortable2(): # value for them ds = None gdal.GetDriverByName('HFA').Delete('tmp/hfa_delete_colortable2.img') - return 'skip' + pytest.skip() ds.GetRasterBand(1).SetColorTable(None) ds = None # check color table gone. ds = gdal.Open('tmp/hfa_delete_colortable2.img') - if ds.GetRasterBand(1).GetColorTable() is not None: - gdaltest.post_reason('failed to remove color table') - return 'fail' + assert ds.GetRasterBand(1).GetColorTable() is None, 'failed to remove color table' ds = None gdal.GetDriverByName('HFA').Delete('tmp/hfa_delete_colortable2.img') - return 'success' - ############################################################################### # Verify we can read the special histogram metadata from a provided image. -def hfa_excluded_values(): +def test_hfa_excluded_values(): ds = gdal.Open('data/dem10.img') md = ds.GetRasterBand(1).GetMetadata() ds = None - if md['STATISTICS_EXCLUDEDVALUES'] != '0,8,9': - gdaltest.post_reason('STATISTICS_EXCLUDEDVALUE is wrong.') - return 'fail' - - return 'success' + assert md['STATISTICS_EXCLUDEDVALUES'] == '0,8,9', \ + 'STATISTICS_EXCLUDEDVALUE is wrong.' ############################################################################### # verify that we propagate nodata to overviews in .img/.rrd format. -def hfa_ov_nodata(): +def test_hfa_ov_nodata(): drv = gdal.GetDriverByName('HFA') src_ds = gdal.Open('data/nodata_int.asc') @@ -1060,13 +852,9 @@ def hfa_ov_nodata(): wrk2_ds = gdal.Open('/vsimem/ov_nodata.img') ovb = wrk2_ds.GetRasterBand(1).GetOverview(0) - if ovb.GetNoDataValue() != -99999: - gdaltest.post_reason('nodata not propagated to .img overview.') - return 'fail' + assert ovb.GetNoDataValue() == -99999, 'nodata not propagated to .img overview.' - if ovb.GetMaskFlags() != gdal.GMF_NODATA: - gdaltest.post_reason('mask flag not as expected.') - return 'fail' + assert ovb.GetMaskFlags() == gdal.GMF_NODATA, 'mask flag not as expected.' # Confirm that a .ovr file was *not* produced. gdal.PushErrorHandler('CPLQuietErrorHandler') @@ -1076,42 +864,34 @@ def hfa_ov_nodata(): wrk3_ds = None gdal.PopErrorHandler() - if wrk3_ds is not None: - gdaltest.post_reason('this test result is invalid since .ovr file was created, why?') - return 'fail' + assert wrk3_ds is None, \ + 'this test result is invalid since .ovr file was created, why?' wrk2_ds = None drv.Delete('/vsimem/ov_nodata.img') - return 'success' - ############################################################################### # Confirm that we can read 8bit grayscale overviews for 1bit images. -def hfa_read_bit2grayscale(): +def test_hfa_read_bit2grayscale(): ds = gdal.Open('data/small1bit.img') band = ds.GetRasterBand(1) ov = band.GetOverview(0) - if ov.Checksum() != 4247: - gdaltest.post_reason('did not get expected overview checksum') - return 'fail' + assert ov.Checksum() == 4247, 'did not get expected overview checksum' ds_md = ds.GetMetadata() - if ds_md['PyramidResamplingType'] != 'AVERAGE_BIT2GRAYSCALE': - gdaltest.post_reason('wrong pyramid resampling type metadata.') - return 'fail' - - return 'success' + assert ds_md['PyramidResamplingType'] == 'AVERAGE_BIT2GRAYSCALE', \ + 'wrong pyramid resampling type metadata.' ############################################################################### # Confirm that we can create overviews in rrd format for an .img file with # the bit2grayscale algorithm (#2914) -def hfa_write_bit2grayscale(): +def test_hfa_write_bit2grayscale(): import shutil @@ -1127,9 +907,7 @@ def hfa_write_bit2grayscale(): ov = ds.GetRasterBand(1).GetOverview(1) - if ov.Checksum() != 57325: - gdaltest.post_reason('wrong checksum for greyscale overview.') - return 'fail' + assert ov.Checksum() == 57325, 'wrong checksum for greyscale overview.' ds = None @@ -1139,20 +917,16 @@ def hfa_write_bit2grayscale(): gdal.SetConfigOption('HFA_USE_RRD', 'NO') # as an aside, confirm the .rrd file was deleted. - try: + with pytest.raises(IOError, message='tmp/small1bit.rrd not deleted!'): open('tmp/small1bit.rrd') - gdaltest.post_reason('tmp/small1bit.rrd not deleted!') - return 'fail' - except IOError: - pass - - return 'success' + + ############################################################################### # Verify handling of camera model metadata (#2675) -def hfa_camera_md(): +def test_hfa_camera_md(): ds = gdal.Open('/vsisparse/data/251_sparse.xml') @@ -1167,25 +941,19 @@ def hfa_camera_md(): try: value = md[check_item[0]] except IndexError: - gdaltest.post_reason('metadata item %d missing' % check_item[0]) - return 'fail' + pytest.fail('metadata item %d missing' % check_item[0]) - if value != check_item[1]: - gdaltest.post_reason('metadata item %s has wrong value: %s' % + assert value == check_item[1], ('metadata item %s has wrong value: %s' % (check_item[0], value)) - return 'fail' # Check that the SRS is reasonable. srs_wkt = md['outputProjection'] exp_wkt = 'PROJCS["UTM Zone 17, Northern Hemisphere",GEOGCS["NAD27",DATUM["North_American_Datum_1927",SPHEROID["Clarke 1866",6378206.4,294.978698213898,AUTHORITY["EPSG","7008"]],TOWGS84[-10,158,187,0,0,0,0],AUTHORITY["EPSG","6267"]],PRIMEM["Greenwich",0,AUTHORITY["EPSG","8901"]],UNIT["degree",0.0174532925199433,AUTHORITY["EPSG","9108"]],AUTHORITY["EPSG","4267"]],PROJECTION["Transverse_Mercator"],PARAMETER["latitude_of_origin",0],PARAMETER["central_meridian",-81],PARAMETER["scale_factor",0.9996],PARAMETER["false_easting",500000],PARAMETER["false_northing",0],UNIT["Meter",1],AUTHORITY["EPSG","26717"]]' - if not gdaltest.equal_srs_from_wkt(srs_wkt, exp_wkt): - gdaltest.post_reason('wrong outputProjection') - return 'fail' + assert gdaltest.equal_srs_from_wkt(srs_wkt, exp_wkt), 'wrong outputProjection' ds = None - return 'success' ############################################################################### # Verify dataset's projection matches expected @@ -1195,18 +963,15 @@ def hfa_verify_dataset_projection(dataset_path, exp_wkt): ds = gdal.Open(dataset_path) srs_wkt = ds.GetProjectionRef() - if not gdaltest.equal_srs_from_wkt(exp_wkt, srs_wkt): - gdaltest.post_reason('wrong outputProjection') - return 'fail' + assert gdaltest.equal_srs_from_wkt(exp_wkt, srs_wkt), 'wrong outputProjection' ds = None - return 'success' ############################################################################### # Verify can read Transverse Mercator (South Orientated) projections -def hfa_read_tmso_projection(): +def test_hfa_read_tmso_projection(): exp_wkt = 'PROJCS["Transverse Mercator (South Orientated)",GEOGCS["Cape-1",DATUM["Cape-1",SPHEROID["Clarke 1880 Arc",6378249.145,293.4663077168331],TOWGS84[-136,-108,-292,0,0,0,0]],PRIMEM["Greenwich",0],UNIT["degree",0.0174532925199433]],PROJECTION["Transverse_Mercator_South_Orientated"],PARAMETER["latitude_of_origin",0],PARAMETER["central_meridian",21],PARAMETER["scale_factor",1],PARAMETER["false_easting",0],PARAMETER["false_northing",0],UNIT["meters",1]]' return hfa_verify_dataset_projection('../gcore/data/22281.aux', exp_wkt) @@ -1214,7 +979,7 @@ def hfa_read_tmso_projection(): # Verify can write Transverse Mercator (South Orientated) projections to aux files -def hfa_write_tmso_projection(): +def test_hfa_write_tmso_projection(): dataset_path = 'tmp/tmso.img' out_ds = gdal.GetDriverByName('HFA').Create(dataset_path, 1, 1) gt = (0, 1, 0, 0, 0, 1) @@ -1230,7 +995,7 @@ def hfa_write_tmso_projection(): # Verify can read Hotine Oblique Mercator (Variant A) projections -def hfa_read_homva_projection(): +def test_hfa_read_homva_projection(): exp_wkt = 'PROJCS["Hotine Oblique Mercator (Variant A)",GEOGCS["GDM 2000",DATUM["GDM 2000",SPHEROID["GRS 1980",6378137,298.2572220960422],TOWGS84[0,0,0,0,0,0,0]],PRIMEM["Greenwich",0],UNIT["degree",0.0174532925199433]],PROJECTION["Hotine_Oblique_Mercator"],PARAMETER["latitude_of_center",4],PARAMETER["longitude_of_center",115],PARAMETER["azimuth",53.31580995],PARAMETER["rectified_grid_angle",53.13010236111111],PARAMETER["scale_factor",0.99984],PARAMETER["false_easting",0],PARAMETER["false_northing",0],UNIT["meters",1]]' return hfa_verify_dataset_projection('../gcore/data/3376.tif', exp_wkt) @@ -1238,7 +1003,7 @@ def hfa_read_homva_projection(): # Verify can write Transverse Mercator (South Orientated) projections to aux files -def hfa_write_homva_projection(): +def test_hfa_write_homva_projection(): dataset_path = 'tmp/homva.img' out_ds = gdal.GetDriverByName('HFA').Create(dataset_path, 1, 1) gt = (0, 1, 0, 0, 0, 1) @@ -1255,7 +1020,7 @@ def hfa_write_homva_projection(): # and fetching actual overviews. -def hfa_rde_overviews(): +def test_hfa_rde_overviews(): # Create an imagine file, forcing creation of an .ige file. @@ -1264,37 +1029,27 @@ def hfa_rde_overviews(): exp_cs = 1631 cs = ds.GetRasterBand(1).Checksum() - if exp_cs != cs: - print(cs) - gdaltest.post_reason('did not get expected band checksum') - return 'fail' + assert exp_cs == cs, 'did not get expected band checksum' exp_cs = 340 cs = ds.GetRasterBand(1).GetOverview(0).Checksum() - if exp_cs != cs: - print(cs) - gdaltest.post_reason('did not get expected overview checksum') - return 'fail' + assert exp_cs == cs, 'did not get expected overview checksum' filelist = ds.GetFileList() exp_filelist = ['data/spill.img', 'data/spill.ige', 'data/spill.rrd', 'data/spill.rde'] exp_filelist_win32 = ['data/spill.img', 'data\\spill.ige', 'data\\spill.rrd', 'data\\spill.rde'] - if filelist != exp_filelist and filelist != exp_filelist_win32: - print(filelist) - gdaltest.post_reason('did not get expected file list.') - return 'fail' + assert filelist == exp_filelist or filelist == exp_filelist_win32, \ + 'did not get expected file list.' ds = None - return 'success' - ############################################################################### # Check that we can copy and rename a complex file set, and that the internal filenames # in the .img and .rrd seem to be updated properly. -def hfa_copyfiles(): +def test_hfa_copyfiles(): drv = gdal.GetDriverByName('HFA') drv.CopyFiles('tmp/newnamexxx_after_copy.img', 'data/spill.img') @@ -1306,51 +1061,36 @@ def hfa_copyfiles(): exp_cs = 340 cs = ds.GetRasterBand(1).GetOverview(0).Checksum() - if exp_cs != cs: - print(cs) - gdaltest.post_reason('did not get expected overview checksum') - return 'fail' + assert exp_cs == cs, 'did not get expected overview checksum' filelist = ds.GetFileList() exp_filelist = ['tmp/newnamexxx.img', 'tmp/newnamexxx.ige', 'tmp/newnamexxx.rrd', 'tmp/newnamexxx.rde'] exp_filelist_win32 = ['tmp/newnamexxx.img', 'tmp\\newnamexxx.ige', 'tmp\\newnamexxx.rrd', 'tmp\\newnamexxx.rde'] - if filelist != exp_filelist and filelist != exp_filelist_win32: - print(filelist) - gdaltest.post_reason('did not get expected file list.') - return 'fail' + assert filelist == exp_filelist or filelist == exp_filelist_win32, \ + 'did not get expected file list.' ds = None # Check that the filenames in the actual files seem to have been updated. img = open('tmp/newnamexxx.img', 'rb').read() img = str(img) - if img.find('newnamexxx.rrd') == -1: - gdaltest.post_reason('RRDNames not updated?') - return 'fail' + assert img.find('newnamexxx.rrd') != -1, 'RRDNames not updated?' - if img.find('newnamexxx.ige') == -1: - gdaltest.post_reason('spill file not updated?') - return 'fail' + assert img.find('newnamexxx.ige') != -1, 'spill file not updated?' rrd = open('tmp/newnamexxx.rrd', 'rb').read() rrd = str(rrd) - if rrd.find('newnamexxx.img') == -1: - gdaltest.post_reason('DependentFile not updated?') - return 'fail' + assert rrd.find('newnamexxx.img') != -1, 'DependentFile not updated?' - if rrd.find('newnamexxx.rde') == -1: - gdaltest.post_reason('overview spill file not updated?') - return 'fail' + assert rrd.find('newnamexxx.rde') != -1, 'overview spill file not updated?' drv.Delete('tmp/newnamexxx.img') - return 'success' - ############################################################################### # Test the ability to write a RAT (#999) -def hfa_write_rat(): +def test_hfa_write_rat(): drv = gdal.GetDriverByName('HFA') @@ -1370,37 +1110,23 @@ def hfa_write_rat(): ds = gdal.Open('tmp/write_rat.img') rat = ds.GetRasterBand(1).GetDefaultRAT() - if rat.GetColumnCount() != 6 \ - or rat.GetTypeOfCol(0) != gdal.GFT_Real \ - or rat.GetUsageOfCol(0) != gdal.GFU_Generic: # should be GFU_MinMax - print(rat.GetColumnCount()) - print(rat.GetTypeOfCol(0)) - print(rat.GetUsageOfCol(0)) - gdaltest.post_reason('BinValues column wrong.') - return 'fail' - - if rat.GetValueAsInt(2, 0) != 4: - print(rat.GetValueAsInt(2, 0)) - gdaltest.post_reason('BinValues value wrong.') - return 'fail' - - if rat.GetValueAsInt(4, 5) != 656: - print(rat.GetValueAsInt(4, 5)) - gdaltest.post_reason('Histogram value wrong.') - return 'fail' + assert rat.GetColumnCount() == 6 and rat.GetTypeOfCol(0) == gdal.GFT_Real and rat.GetUsageOfCol(0) == gdal.GFU_Generic, \ + 'BinValues column wrong.' + + assert rat.GetValueAsInt(2, 0) == 4, 'BinValues value wrong.' + + assert rat.GetValueAsInt(4, 5) == 656, 'Histogram value wrong.' rat = None ds = None drv.Delete('tmp/write_rat.img') - return 'success' - ############################################################################### # Test STATISTICS creation option -def hfa_createcopy_statistics(): +def test_hfa_createcopy_statistics(): tmpAuxXml = '../gcore/data/byte.tif.aux.xml' try: @@ -1422,98 +1148,31 @@ def hfa_createcopy_statistics(): gdal.GetDriverByName('HFA').Delete('/vsimem/byte.img') - if md['STATISTICS_MINIMUM'] != '74': - gdaltest.post_reason('STATISTICS_MINIMUM is wrong.') - print(md['STATISTICS_MINIMUM']) - return 'fail' - - return 'success' + assert md['STATISTICS_MINIMUM'] == '74', 'STATISTICS_MINIMUM is wrong.' ############################################################################### # Test GetUnitType() -def hfa_read_elevation_units(): +def test_hfa_read_elevation_units(): ds = gdal.Open('../gcore/data/erdas_cm.img') unittype = ds.GetRasterBand(1).GetUnitType() - if unittype != 'cm': - gdaltest.post_reason('Failed to read elevation units') - print(unittype) - return 'fail' + assert unittype == 'cm', 'Failed to read elevation units' ds = None ds = gdal.Open('../gcore/data/erdas_feet.img') unittype = ds.GetRasterBand(1).GetUnitType() - if unittype != 'feet': - gdaltest.post_reason('Failed to read elevation units') - print(unittype) - return 'fail' + assert unittype == 'feet', 'Failed to read elevation units' ds = None ds = gdal.Open('../gcore/data/erdas_m.img') unittype = ds.GetRasterBand(1).GetUnitType() - if unittype != 'meters': - gdaltest.post_reason('Failed to read elevation units') - print(unittype) - return 'fail' + assert unittype == 'meters', 'Failed to read elevation units' ds = None - return 'success' - ############################################################################### # -gdaltest_list = [ - hfa_histread, - hfa_histwrite, - hfa_histrewrite, - hfa_int_stats_1, - hfa_int_stats_2, - hfa_float_stats_1, - hfa_float_stats_2, - hfa_int_read, - hfa_float_read, - hfa_pe_read, - hfa_pe_write, - hfa_metadata_1, - hfa_metadata_2, - hfa_grow_rrdlist, - hfa_clean_ige, - hfa_corrupt_aux, - hfa_mapinformation_units, - hfa_nodata_write, - hfa_nodata_read, - hfa_rotated_read, - hfa_rotated_write, - hfa_vsimem, - hfa_proName, - hfa_read_empty_compressed, - hfa_unique_values_color_table, - hfa_unique_values_hist, - hfa_xforms_3rd, - hfa_delete_colortable, - hfa_delete_colortable2, - hfa_excluded_values, - hfa_ov_nodata, - hfa_read_bit2grayscale, - hfa_write_bit2grayscale, - hfa_camera_md, - hfa_rde_overviews, - hfa_copyfiles, - hfa_write_rat, - hfa_createcopy_statistics, - hfa_read_tmso_projection, - hfa_read_homva_projection, - hfa_write_tmso_projection, - hfa_write_homva_projection, - hfa_read_elevation_units] - -if __name__ == '__main__': - - gdaltest.setup_run('hfa') - - gdaltest.run_tests(gdaltest_list) - - sys.exit(gdaltest.summarize()) + diff --git a/autotest/gdrivers/ida.py b/autotest/gdrivers/ida.py index 5f828838581a..78399c6f2f88 100755 --- a/autotest/gdrivers/ida.py +++ b/autotest/gdrivers/ida.py @@ -28,18 +28,17 @@ # DEALINGS IN THE SOFTWARE. ############################################################################### -import sys from osgeo import gdal -sys.path.append('../pymod') import gdaltest +import pytest ############################################################################### # Perform simple read test. -def ida_1(): +def test_ida_1(): tst = gdaltest.GDALTest('ida', 'DWI01012.AFC', 1, 4026) return tst.testOpen() @@ -48,7 +47,7 @@ def ida_1(): # Verify some auxiliary data. -def ida_2(): +def test_ida_2(): ds = gdal.Open('data/DWI01012.AFC') @@ -57,30 +56,22 @@ def ida_2(): if gt[0] != -17.875 or gt[1] != 0.25 or gt[2] != 0 \ or gt[3] != 37.875 or gt[4] != 0 or gt[5] != -0.25: print('got: ', gt) - gdaltest.post_reason('Aaigrid geotransform wrong.') - return 'fail' + pytest.fail('Aaigrid geotransform wrong.') prj = ds.GetProjection() - if prj != 'GEOGCS["WGS 84",DATUM["WGS_1984",SPHEROID["WGS 84",6378137,298.257223563,AUTHORITY["EPSG","7030"]],AUTHORITY["EPSG","6326"]],PRIMEM["Greenwich",0,AUTHORITY["EPSG","8901"]],UNIT["degree",0.0174532925199433,AUTHORITY["EPSG","9122"]],AUTHORITY["EPSG","4326"]]': - gdaltest.post_reason('Projection does not match expected:\n%s' % prj) - return 'fail' + assert prj == 'GEOGCS["WGS 84",DATUM["WGS_1984",SPHEROID["WGS 84",6378137,298.257223563,AUTHORITY["EPSG","7030"]],AUTHORITY["EPSG","6326"]],PRIMEM["Greenwich",0,AUTHORITY["EPSG","8901"]],UNIT["degree",0.0174532925199433,AUTHORITY["EPSG","9122"]],AUTHORITY["EPSG","4326"]]', \ + ('Projection does not match expected:\n%s' % prj) band1 = ds.GetRasterBand(1) - if band1.GetNoDataValue() != 255: - gdaltest.post_reason('Grid NODATA value wrong or missing.') - return 'fail' + assert band1.GetNoDataValue() == 255, 'Grid NODATA value wrong or missing.' - if band1.DataType != gdal.GDT_Byte: - gdaltest.post_reason('Data type is not byte.') - return 'fail' - - return 'success' + assert band1.DataType == gdal.GDT_Byte, 'Data type is not byte.' ############################################################################### # Create simple copy and check. -def ida_3(): +def test_ida_3(): tst = gdaltest.GDALTest('ida', 'DWI01012.AFC', 1, 4026) @@ -92,7 +83,7 @@ def ida_3(): # Test ACEA Projection. -def ida_4(): +def test_ida_4(): gdaltest.ida_tst = gdaltest.GDALTest('ida', 'DWI01012.AFC', 1, 4026) @@ -116,7 +107,7 @@ def ida_4(): # Test Goodes Projection. -def ida_5(): +def test_ida_5(): gdaltest.ida_tst = gdaltest.GDALTest('ida', 'DWI01012.AFC', 1, 4026) @@ -137,7 +128,7 @@ def ida_5(): # Test LCC Projection. -def ida_6(): +def test_ida_6(): gdaltest.ida_tst = gdaltest.GDALTest('ida', 'DWI01012.AFC', 1, 4026) @@ -161,7 +152,7 @@ def ida_6(): # Test LAEA Projection. -def ida_7(): +def test_ida_7(): gdaltest.ida_tst = gdaltest.GDALTest('ida', 'DWI01012.AFC', 1, 4026) @@ -180,21 +171,5 @@ def ida_7(): return gdaltest.ida_tst.testSetProjection(prj=prj) -gdaltest_list = [ - ida_1, - ida_2, - ida_3, - ida_4, - ida_5, - ida_6, - ida_7 -] - - -if __name__ == '__main__': - - gdaltest.setup_run('ida') - gdaltest.run_tests(gdaltest_list) - sys.exit(gdaltest.summarize()) diff --git a/autotest/gdrivers/idrisi.py b/autotest/gdrivers/idrisi.py index a7184d8a3c07..93d98b55e52b 100755 --- a/autotest/gdrivers/idrisi.py +++ b/autotest/gdrivers/idrisi.py @@ -30,9 +30,7 @@ ############################################################################### import os -import sys -sys.path.append('../pymod') import gdaltest @@ -40,7 +38,7 @@ # Read test of byte file. -def idrisi_1(): +def test_idrisi_1(): tst = gdaltest.GDALTest('RST', 'byte.rst', 1, 5044) return tst.testOpen() @@ -49,7 +47,7 @@ def idrisi_1(): # Read test of byte file. -def idrisi_2(): +def test_idrisi_2(): tst = gdaltest.GDALTest('RST', 'real.rst', 1, 5275) return tst.testOpen() @@ -58,7 +56,7 @@ def idrisi_2(): # -def idrisi_3(): +def test_idrisi_3(): tst = gdaltest.GDALTest('RST', 'float32.bil', 1, 27) @@ -68,7 +66,7 @@ def idrisi_3(): # -def idrisi_4(): +def test_idrisi_4(): tst = gdaltest.GDALTest('RST', 'rgbsmall.tif', 2, 21053) @@ -79,7 +77,7 @@ def idrisi_4(): # Cleanup. -def idrisi_cleanup(): +def test_idrisi_cleanup(): gdaltest.clean_tmp() try: os.unlink('data/rgbsmall.tif.aux.xml') @@ -89,20 +87,6 @@ def idrisi_cleanup(): print('FIXME?: data/rgbsmall.tif.aux.xml is produced by those tests') except OSError: pass - return 'success' + -gdaltest_list = [ - idrisi_1, - idrisi_2, - idrisi_3, - idrisi_4, - idrisi_cleanup] - -if __name__ == '__main__': - - gdaltest.setup_run('idrisi') - - gdaltest.run_tests(gdaltest_list) - - sys.exit(gdaltest.summarize()) diff --git a/autotest/gdrivers/ignfheightasciigrid.py b/autotest/gdrivers/ignfheightasciigrid.py index e2596b4b7db9..ec7224c35637 100755 --- a/autotest/gdrivers/ignfheightasciigrid.py +++ b/autotest/gdrivers/ignfheightasciigrid.py @@ -36,7 +36,7 @@ import gdaltest -def ignfheightasciigrid_1(): +def test_ignfheightasciigrid_1(): tst = gdaltest.GDALTest('IGNFHeightASCIIGrid', 'ignfheightasciigrid_ar1.mnt', 1, 21) @@ -44,7 +44,7 @@ def ignfheightasciigrid_1(): return tst.testOpen(check_gt=gt, check_prj='WGS84') -def ignfheightasciigrid_2(): +def test_ignfheightasciigrid_2(): tst = gdaltest.GDALTest('IGNFHeightASCIIGrid', 'ignfheightasciigrid_ar2.mnt', 1, 21) @@ -52,7 +52,7 @@ def ignfheightasciigrid_2(): return tst.testOpen(check_gt=gt, check_prj='WGS84') -def ignfheightasciigrid_3(): +def test_ignfheightasciigrid_3(): tst = gdaltest.GDALTest('IGNFHeightASCIIGrid', 'ignfheightasciigrid_ar3.mnt', 1, 21) @@ -60,7 +60,7 @@ def ignfheightasciigrid_3(): return tst.testOpen(check_gt=gt, check_prj='WGS84') -def ignfheightasciigrid_4(): +def test_ignfheightasciigrid_4(): tst = gdaltest.GDALTest('IGNFHeightASCIIGrid', 'ignfheightasciigrid_ar4.mnt', 1, 21) @@ -68,7 +68,7 @@ def ignfheightasciigrid_4(): return tst.testOpen(check_gt=gt, check_prj='WGS84') -def ignfheightasciigrid_5(): +def test_ignfheightasciigrid_5(): tst = gdaltest.GDALTest('IGNFHeightASCIIGrid', 'ignfheightasciigrid_ar1_nocoords.mnt', 1, 21) @@ -76,7 +76,7 @@ def ignfheightasciigrid_5(): return tst.testOpen(check_gt=gt, check_prj='WGS84') -def ignfheightasciigrid_6(): +def test_ignfheightasciigrid_6(): tst = gdaltest.GDALTest( 'IGNFHeightASCIIGrid', 'ignfheightasciigrid_ar1_nocoords_noprec.mnt', 1, 21) @@ -84,7 +84,7 @@ def ignfheightasciigrid_6(): return tst.testOpen(check_gt=gt, check_prj='WGS84') -def ignfheightasciigrid_7(): +def test_ignfheightasciigrid_7(): tst = gdaltest.GDALTest( 'IGNFHeightASCIIGrid', 'ignfheightasciigrid_ar1_noprec.mnt', 1, 21) @@ -92,31 +92,24 @@ def ignfheightasciigrid_7(): return tst.testOpen(check_gt=gt, check_prj='WGS84') -def ignfheightasciigrid_description_multiword(): +def test_ignfheightasciigrid_description_multiword(): filename = '/vsimem/ignfheightasciigrid_invalid' ok_content = '2 3 49 50 1 1 1 0 1 0 -0. MULTI WORD\r1 2 3 4' gdal.FileFromMemBuffer(filename, ok_content) ds = gdal.OpenEx(filename) desc = ds.GetMetadataItem('DESCRIPTION') - if desc != 'MULTI WORD': - print(desc) - return 'fail' - return 'success' + assert desc == 'MULTI WORD' -def ignfheightasciigrid_invalid(): +def test_ignfheightasciigrid_invalid(): filename = '/vsimem/ignfheightasciigrid_invalid' ok_content = '2 3 49 50 1 1 1 0 1 0 -0. DESC\r1 2 3 4' gdal.FileFromMemBuffer(filename, ok_content) ds = gdal.OpenEx(filename) - if not ds: - gdaltest.post_reason('fail') - return 'fail' - if ds.GetRasterBand(1).GetUnitType() != 'm': - gdaltest.post_reason('fail') - return 'fail' + assert ds + assert ds.GetRasterBand(1).GetUnitType() == 'm' gdal.Unlink(filename) contents = ['0 0 0 0 0 0 0 0 0 0 0 0\r', # a lot of invalid values @@ -150,15 +143,11 @@ def ignfheightasciigrid_invalid(): for content in contents: gdal.FileFromMemBuffer(filename, content) with gdaltest.error_handler(): - if gdal.OpenEx(filename, gdal.OF_RASTER): - gdaltest.post_reason('fail') - print(content) - return 'fail' + assert not gdal.OpenEx(filename, gdal.OF_RASTER), content gdal.Unlink(filename) - return 'success' + - -def ignfheightasciigrid_huge(): +def test_ignfheightasciigrid_huge(): filename = '/vsimem/ignfheightasciigrid_huge' ok_content = '2 3 49 50 1 1 1 0 1 0 -0. MULTI WORD\r1 2 3 4' @@ -171,27 +160,21 @@ def ignfheightasciigrid_huge(): ds = gdal.OpenEx(filename, gdal.OF_RASTER) gdal.Unlink(filename) - if ds is not None: - return 'fail' - return 'success' + assert ds is None -def ignfheightasciigrid_gra(): +def test_ignfheightasciigrid_gra(): tst = gdaltest.GDALTest( 'IGNFHeightASCIIGrid', 'ignfheightasciigrid.gra', 1, 21) gt = (-152.125, 0.25, 0.0, -16.375, 0.0, -0.25) - if tst.testOpen(check_gt=gt, check_prj='WGS84') != 'success': - return 'fail' + tst.testOpen(check_gt=gt, check_prj='WGS84') ds = gdal.OpenEx('data/ignfheightasciigrid.gra', gdal.OF_RASTER) - if ds.GetRasterBand(1).GetNoDataValue() != 9999: - gdaltest.post_reason('fail') - return 'fail' - return 'success' + assert ds.GetRasterBand(1).GetNoDataValue() == 9999 -def ignfheightasciigrid_gra_invalid(): +def test_ignfheightasciigrid_gra_invalid(): contents = ['49 50\r\n2\r\n', # missing values '49 50\r\n2 3\r\n', # missing line @@ -203,35 +186,10 @@ def ignfheightasciigrid_gra_invalid(): for content in contents: gdal.FileFromMemBuffer(filename, content) with gdaltest.error_handler(): - if gdal.OpenEx(filename, gdal.OF_RASTER): - gdaltest.post_reason('fail') - print(content) - return 'fail' + assert not gdal.OpenEx(filename, gdal.OF_RASTER), content gdal.Unlink(filename) - return 'success' - - - -gdaltest_list = [ - ignfheightasciigrid_1, - ignfheightasciigrid_2, - ignfheightasciigrid_3, - ignfheightasciigrid_4, - ignfheightasciigrid_5, - ignfheightasciigrid_6, - ignfheightasciigrid_7, - ignfheightasciigrid_description_multiword, - ignfheightasciigrid_invalid, - ignfheightasciigrid_huge, - ignfheightasciigrid_gra, - ignfheightasciigrid_gra_invalid, -] - + -if __name__ == '__main__': - gdaltest.setup_run('IGNFHeightASCIIGrid') - gdaltest.run_tests(gdaltest_list) - sys.exit(gdaltest.summarize()) diff --git a/autotest/gdrivers/ilwis.py b/autotest/gdrivers/ilwis.py index 6bc4239a14f3..dc088c798226 100755 --- a/autotest/gdrivers/ilwis.py +++ b/autotest/gdrivers/ilwis.py @@ -28,9 +28,7 @@ # DEALINGS IN THE SOFTWARE. ############################################################################### -import sys -sys.path.append('../pymod') import gdaltest @@ -38,7 +36,7 @@ # Perform simple read test. -def ilwis_1(): +def test_ilwis_1(): tst = gdaltest.GDALTest('ilwis', 'LanduseSmall.mpr', 1, 2351) @@ -70,7 +68,7 @@ def ilwis_1(): # copy byte data and verify. -def ilwis_2(): +def test_ilwis_2(): tst = gdaltest.GDALTest('ilwis', 'byte.tif', 1, 4672) @@ -81,7 +79,7 @@ def ilwis_2(): # copy floating point data and use Create interface. -def ilwis_3(): +def test_ilwis_3(): tst = gdaltest.GDALTest('ilwis', 'float.img', 1, 23529) @@ -91,7 +89,7 @@ def ilwis_3(): # Try multi band dataset. -def ilwis_4(): +def test_ilwis_4(): tst = gdaltest.GDALTest('ilwis', 'rgbsmall.tif', 2, 21053) @@ -102,7 +100,7 @@ def ilwis_4(): # Test vsi in-memory support. -def ilwis_5(): +def test_ilwis_5(): tst = gdaltest.GDALTest('ilwis', 'byte.tif', 1, 4672) @@ -118,23 +116,8 @@ def ilwis_5(): # properly. So we do the brute force approach... -def ilwis_cleanup(): +def test_ilwis_cleanup(): gdaltest.clean_tmp() - return 'success' -gdaltest_list = [ - ilwis_1, - ilwis_2, - ilwis_3, - ilwis_4, - ilwis_5, - ilwis_cleanup] -if __name__ == '__main__': - - gdaltest.setup_run('ilwis') - - gdaltest.run_tests(gdaltest_list) - - sys.exit(gdaltest.summarize()) diff --git a/autotest/gdrivers/ingr.py b/autotest/gdrivers/ingr.py index eb985bacf87e..3394026e356a 100755 --- a/autotest/gdrivers/ingr.py +++ b/autotest/gdrivers/ingr.py @@ -31,10 +31,8 @@ ############################################################################### import os -import sys from osgeo import gdal -sys.path.append('../pymod') import gdaltest @@ -42,7 +40,7 @@ # Read test of byte file. -def ingr_1(): +def test_ingr_1(): tst = gdaltest.GDALTest('INGR', '8bit_rgb.cot', 2, 4855) return tst.testOpen() @@ -51,7 +49,7 @@ def ingr_1(): # Read uint32 file. -def ingr_2(): +def test_ingr_2(): tst = gdaltest.GDALTest('INGR', 'uint32.cot', 1, 4672) return tst.testOpen() @@ -60,26 +58,21 @@ def ingr_2(): # Test paletted file, including checking the palette (format 02 I think). -def ingr_3(): +def test_ingr_3(): tst = gdaltest.GDALTest('INGR', '8bit_pal.cot', 1, 4855) - result = tst.testOpen() - if result != 'success': - return result + tst.testOpen() ds = gdal.Open('data/8bit_pal.cot') ct = ds.GetRasterBand(1).GetRasterColorTable() - if ct.GetCount() != 256 or ct.GetColorEntry(8) != (8, 8, 8, 255): - gdaltest.post_reason('Wrong color table entry.') - return 'fail' - - return 'success' + assert ct.GetCount() == 256 and ct.GetColorEntry(8) == (8, 8, 8, 255), \ + 'Wrong color table entry.' ############################################################################### # frmt02 is a plain byte format -def ingr_4(): +def test_ingr_4(): tst = gdaltest.GDALTest('INGR', 'frmt02.cot', 1, 26968) return tst.testOpen() @@ -88,7 +81,7 @@ def ingr_4(): # Test creation. -def ingr_5(): +def test_ingr_5(): tst = gdaltest.GDALTest('INGR', 'frmt02.cot', 1, 26968) return tst.testCreate() @@ -97,7 +90,7 @@ def ingr_5(): # Test createcopy. -def ingr_6(): +def test_ingr_6(): tst = gdaltest.GDALTest('INGR', 'frmt02.cot', 1, 26968) return tst.testCreate() @@ -106,7 +99,7 @@ def ingr_6(): # JPEG 8bit -def ingr_7(): +def test_ingr_7(): tst = gdaltest.GDALTest('INGR', 'frmt30.cot', 1, 29718) return tst.testOpen() @@ -115,7 +108,7 @@ def ingr_7(): # Read simple RLE -def ingr_8(): +def test_ingr_8(): tst = gdaltest.GDALTest('INGR', 'frmt09.cot', 1, 23035) return tst.testOpen() @@ -124,7 +117,7 @@ def ingr_8(): # Read Simple RLE Variable -def ingr_9(): +def test_ingr_9(): tst = gdaltest.GDALTest('INGR', 'frmt10.cot', 1, 47031) return tst.testOpen() @@ -133,7 +126,7 @@ def ingr_9(): # CCITT bitonal -def ingr_10(): +def test_ingr_10(): tst = gdaltest.GDALTest('INGR', 'frmt24.cit', 1, 23035) return tst.testOpen() @@ -142,7 +135,7 @@ def ingr_10(): # Adaptive RLE - 24 bit. -def ingr_11(): +def test_ingr_11(): tst = gdaltest.GDALTest('INGR', 'frmt27.cot', 2, 45616) return tst.testOpen() @@ -151,7 +144,7 @@ def ingr_11(): # Uncompressed RGB -def ingr_12(): +def test_ingr_12(): tst = gdaltest.GDALTest('INGR', 'frmt28.cot', 2, 45616) return tst.testOpen() @@ -160,7 +153,7 @@ def ingr_12(): # Adaptive RLE 8bit. -def ingr_13(): +def test_ingr_13(): tst = gdaltest.GDALTest('INGR', 'frmt29.cot', 1, 26968) return tst.testOpen() @@ -169,23 +162,19 @@ def ingr_13(): # JPEG RGB -def ingr_14(): +def test_ingr_14(): ds = gdal.Open('data/frmt31.cot') cs = ds.GetRasterBand(1).Checksum() ds = None - if cs != 11466 and cs != 11095: - print(cs) - return 'fail' - - return 'success' + assert cs == 11466 or cs == 11095 ############################################################################### # Same, but through vsimem all in memory. -def ingr_15(): +def test_ingr_15(): tst = gdaltest.GDALTest('INGR', 'frmt02.cot', 1, 26968) result = tst.testCreateCopy(vsimem=1) @@ -201,7 +190,7 @@ def ingr_15(): # Read simple RLE tiled -def ingr_16(): +def test_ingr_16(): tst = gdaltest.GDALTest('INGR', 'frmt09t.cot', 1, 3178) return tst.testOpen() @@ -210,7 +199,7 @@ def ingr_16(): # Test writing 9 RLE bitonal compression (#5030) -def ingr_17(): +def test_ingr_17(): src_ds = gdal.Open('data/frmt09.cot') out_ds = gdal.GetDriverByName('INGR').CreateCopy('/vsimem/ingr_17.rle', src_ds) @@ -224,19 +213,13 @@ def ingr_17(): gdal.GetDriverByName('INGR').Delete('/vsimem/ingr_17.rle') - if got_cs != ref_cs: - gdaltest.post_reason('fail') - print(got_cs) - print(ref_cs) - return 'fail' - - return 'success' + assert got_cs == ref_cs ############################################################################### # Test 'random access' in simple RLE -def ingr_18(): +def test_ingr_18(): ds = gdal.Open('data/frmt09.cot') for y in range(ds.RasterYSize): @@ -249,52 +232,18 @@ def ingr_18(): got_data = ds.ReadRaster(0, ds.RasterYSize - 1, ds.RasterXSize, 1) - if got_data != expected_data: - gdaltest.post_reason('fail') - return 'fail' + assert got_data == expected_data ds.FlushCache() got_data = ds.ReadRaster(0, ds.RasterYSize - 1, ds.RasterXSize, 1) - if got_data != expected_data: - gdaltest.post_reason('fail') - return 'fail' - - return 'success' + assert got_data == expected_data -def ingr_cleanup(): +def test_ingr_cleanup(): gdal.Unlink('data/frmt09.cot.aux.xml') - return 'success' - - -gdaltest_list = [ - ingr_1, - ingr_2, - ingr_3, - ingr_4, - ingr_5, - ingr_6, - ingr_7, - ingr_8, - ingr_9, - ingr_10, - ingr_11, - ingr_12, - ingr_13, - ingr_14, - ingr_15, - ingr_16, - ingr_17, - ingr_18, - ingr_cleanup] - -if __name__ == '__main__': - - gdaltest.setup_run('ingr') - - gdaltest.run_tests(gdaltest_list) - - sys.exit(gdaltest.summarize()) + + + diff --git a/autotest/gdrivers/iris.py b/autotest/gdrivers/iris.py index 8ed2af1a3d91..4aa09de92802 100755 --- a/autotest/gdrivers/iris.py +++ b/autotest/gdrivers/iris.py @@ -29,10 +29,8 @@ # DEALINGS IN THE SOFTWARE. ############################################################################### -import sys from osgeo import gdal -sys.path.append('../pymod') import gdaltest @@ -40,7 +38,7 @@ # Test reading a - fake - IRIS dataset -def iris_1(): +def test_iris_1(): tst = gdaltest.GDALTest('IRIS', 'fakeiris.dat', 1, 65532) return tst.testOpen() @@ -49,12 +47,10 @@ def iris_1(): # Test reading a real world IRIS dataset. -def iris_2(): +def test_iris_2(): ds = gdal.Open('data/iristest.dat') - if ds.GetRasterBand(1).Checksum() != 52872: - gdaltest.post_reason('fail') - return 'fail' + assert ds.GetRasterBand(1).Checksum() == 52872 ds.GetProjectionRef() # expected_wkt = """PROJCS["unnamed",GEOGCS["unnamed ellipse",DATUM["unknown",SPHEROID["unnamed",6371000.5,0]],PRIMEM["Greenwich",0],UNIT["degree",0.0174532925199433]],PROJECTION["Mercator_1SP"],PARAMETER["central_meridian",0],PARAMETER["scale_factor",1],PARAMETER["false_easting",0],PARAMETER["false_northing",0]]""" @@ -74,12 +70,8 @@ def iris_2(): got_gt = ds.GetGeoTransform() expected_gt = [16435.721785269096, 1370.4263720754534, 0.0, 5289830.4584420761, 0.0, -1357.6498705837876] for i in range(6): - if (expected_gt[i] == 0.0 and got_gt[i] != 0.0) or \ - (expected_gt[i] != 0.0 and abs(got_gt[i] - expected_gt[i]) / abs(expected_gt[i]) > 1e-5): - gdaltest.post_reason('fail') - print(got_gt) - print(i) - return 'fail' + assert (not (expected_gt[i] == 0.0 and got_gt[i] != 0.0) or \ + (expected_gt[i] != 0.0 and abs(got_gt[i] - expected_gt[i]) / abs(expected_gt[i]) > 1e-5)) expected_metadata = [ "AZIMUTH_SMOOTHING_FOR_SHEAR=0.0", @@ -113,22 +105,8 @@ def iris_2(): for md in expected_metadata: key = md[0:md.find('=')] value = md[md.find('=') + 1:] - if got_metadata[key] != value: - gdaltest.post_reason('did not find %s' % key) - print(got_metadata) - return 'fail' + assert got_metadata[key] == value, ('did not find %s' % key) - return 'success' + -gdaltest_list = [ - iris_1, - iris_2] - -if __name__ == '__main__': - - gdaltest.setup_run('iris') - - gdaltest.run_tests(gdaltest_list) - - sys.exit(gdaltest.summarize()) diff --git a/autotest/gdrivers/isce.py b/autotest/gdrivers/isce.py index 2279d8b301f7..3d3f73604ae7 100755 --- a/autotest/gdrivers/isce.py +++ b/autotest/gdrivers/isce.py @@ -29,10 +29,8 @@ # DEALINGS IN THE SOFTWARE. ############################################################################### -import sys from osgeo import gdal -sys.path.append('../pymod') import gdaltest @@ -40,7 +38,7 @@ # Perform simple read test. -def isce_1(): +def test_isce_1(): tst = gdaltest.GDALTest('isce', 'isce.slc', 1, 350) @@ -68,20 +66,17 @@ def isce_1(): # Test reading of metadata from the ISCE metadata domain -def isce_2(): +def test_isce_2(): ds = gdal.Open('data/isce.slc') val = ds.GetMetadataItem('IMAGE_TYPE', 'ISCE') - if val != 'slc': - return 'fail' - - return 'success' + assert val == 'slc' ############################################################################### # Verify this can be exported losslessly. -def isce_3(): +def test_isce_3(): tst = gdaltest.GDALTest('isce', 'isce.slc', 1, 350) return tst.testCreateCopy(check_gt=0, new_filename='isce.tst.slc') @@ -90,24 +85,11 @@ def isce_3(): # Verify VSIF*L capacity -def isce_4(): +def test_isce_4(): tst = gdaltest.GDALTest('isce', 'isce.slc', 1, 350) return tst.testCreateCopy(check_gt=0, new_filename='isce.tst.slc', vsimem=1) -gdaltest_list = [ - isce_1, - isce_2, - isce_3, - isce_4, -] - - -if __name__ == '__main__': - - gdaltest.setup_run('isce') - gdaltest.run_tests(gdaltest_list) - sys.exit(gdaltest.summarize()) diff --git a/autotest/gdrivers/isis.py b/autotest/gdrivers/isis.py index 2b4c9920d07e..e9650ac1243b 100755 --- a/autotest/gdrivers/isis.py +++ b/autotest/gdrivers/isis.py @@ -31,19 +31,18 @@ import json import struct -import sys -sys.path.append('../pymod') from osgeo import gdal from osgeo import osr import gdaltest +import pytest ############################################################################### # Perform simple read test on isis3 detached dataset. -def isis_1(): +def test_isis_1(): srs = """PROJCS["Equirectangular Mars", GEOGCS["GCS_Mars", DATUM["D_Mars", @@ -67,7 +66,7 @@ def isis_1(): # Perform simple read test on isis3 detached dataset. -def isis_2(): +def test_isis_2(): srs = """PROJCS["Equirectangular mars", GEOGCS["GCS_mars", DATUM["D_mars", @@ -91,7 +90,7 @@ def isis_2(): # Perform simple read test on isis3 detached dataset with GeoTIFF image file -def isis_3(): +def test_isis_3(): srs = """PROJCS["Equirectangular Mars", GEOGCS["GCS_Mars", DATUM["D_Mars", @@ -114,56 +113,31 @@ def isis_3(): # ISIS3 -> ISIS3 conversion -def isis_4(): +def test_isis_4(): tst = gdaltest.GDALTest('ISIS3', 'isis3_detached.lbl', 1, 9978) - ret = tst.testCreateCopy(new_filename='/vsimem/isis_tmp.lbl', + tst.testCreateCopy(new_filename='/vsimem/isis_tmp.lbl', delete_copy=0) - if ret != 'success': - return ret ds = gdal.Open('/vsimem/isis_tmp.lbl') - if ds.GetMetadataDomainList() != ['', 'json:ISIS3']: - gdaltest.post_reason('fail') - print(ds.GetMetadataDomainList()) - return 'fail' + assert ds.GetMetadataDomainList() == ['', 'json:ISIS3'] lbl = ds.GetMetadata_List('json:ISIS3')[0] # Couldn't be preserved, since points to dangling file - if lbl.find('OriginalLabel') >= 0: - gdaltest.post_reason('fail') - print(lbl) - return 'fail' - if lbl.find('PositiveWest') >= 0: - gdaltest.post_reason('fail') - print(lbl) - return 'fail' - if ds.GetRasterBand(1).GetMaskFlags() != 0: - gdaltest.post_reason('fail') - print(ds.GetRasterBand(1).GetMaskFlags()) - return 'fail' - if ds.GetRasterBand(1).GetMaskBand().Checksum() != 12220: - gdaltest.post_reason('fail') - print(ds.GetRasterBand(1).GetMaskBand().Checksum()) - return 'fail' + assert lbl.find('OriginalLabel') < 0 + assert lbl.find('PositiveWest') < 0 + assert ds.GetRasterBand(1).GetMaskFlags() == 0 + assert ds.GetRasterBand(1).GetMaskBand().Checksum() == 12220 ds = None gdal.GetDriverByName('ISIS3').Delete('/vsimem/isis_tmp.lbl') # Preserve source Mapping group as well tst = gdaltest.GDALTest('ISIS3', 'isis3_detached.lbl', 1, 9978, options=['USE_SRC_MAPPING=YES']) - ret = tst.testCreateCopy(new_filename='/vsimem/isis_tmp.lbl', + tst.testCreateCopy(new_filename='/vsimem/isis_tmp.lbl', delete_copy=0) - if ret != 'success': - return ret ds = gdal.Open('/vsimem/isis_tmp.lbl') lbl = ds.GetMetadata_List('json:ISIS3')[0] - if lbl.find('PositiveWest') < 0: - gdaltest.post_reason('fail') - print(lbl) - return 'fail' - if lbl.find('Planetographic') < 0: - gdaltest.post_reason('fail') - print(lbl) - return 'fail' + assert lbl.find('PositiveWest') >= 0 + assert lbl.find('Planetographic') >= 0 ds = None gdal.GetDriverByName('ISIS3').Delete('/vsimem/isis_tmp.lbl') @@ -173,112 +147,72 @@ def isis_4(): 'LONGITUDE_DIRECTION=PositiveEast', 'LATITUDE_TYPE=Planetocentric', 'TARGET_NAME=my_label']) - ret = tst.testCreateCopy(new_filename='/vsimem/isis_tmp.lbl', + tst.testCreateCopy(new_filename='/vsimem/isis_tmp.lbl', delete_copy=0) - if ret != 'success': - return ret ds = gdal.Open('/vsimem/isis_tmp.lbl') lbl = ds.GetMetadata_List('json:ISIS3')[0] - if lbl.find('PositiveEast') < 0: - gdaltest.post_reason('fail') - print(lbl) - return 'fail' - if lbl.find('Planetocentric') < 0: - gdaltest.post_reason('fail') - print(lbl) - return 'fail' - if lbl.find('my_label') < 0: - gdaltest.post_reason('fail') - print(lbl) - return 'fail' + assert lbl.find('PositiveEast') >= 0 + assert lbl.find('Planetocentric') >= 0 + assert lbl.find('my_label') >= 0 ds = None gdal.GetDriverByName('ISIS3').Delete('/vsimem/isis_tmp.lbl') - return 'success' - # Label+image creation + WRITE_BOUNDING_DEGREES=NO option -def isis_5(): +def test_isis_5(): tst = gdaltest.GDALTest('ISIS3', 'isis3_detached.lbl', 1, 9978, options=['USE_SRC_LABEL=NO', 'WRITE_BOUNDING_DEGREES=NO']) - ret = tst.testCreateCopy(new_filename='/vsimem/isis_tmp.lbl', + tst.testCreateCopy(new_filename='/vsimem/isis_tmp.lbl', delete_copy=0) - if ret != 'success': - return ret - if gdal.VSIStatL('/vsimem/isis_tmp.cub') is not None: - gdaltest.post_reason('fail') - return 'fail' + assert gdal.VSIStatL('/vsimem/isis_tmp.cub') is None ds = gdal.Open('/vsimem/isis_tmp.lbl') lbl = ds.GetMetadata_List('json:ISIS3')[0] - if lbl.find('MinimumLongitude') >= 0: - gdaltest.post_reason('fail') - print(lbl) - return 'fail' + assert lbl.find('MinimumLongitude') < 0 ds = None gdal.GetDriverByName('ISIS3').Delete('/vsimem/isis_tmp.lbl') - return 'success' # Detached label creation and COMMENT option -def isis_6(): +def test_isis_6(): tst = gdaltest.GDALTest('ISIS3', 'isis3_detached.lbl', 1, 9978, options=['DATA_LOCATION=EXTERNAL', 'USE_SRC_LABEL=NO', 'COMMENT=my comment']) - ret = tst.testCreateCopy(new_filename='/vsimem/isis_tmp.lbl', + tst.testCreateCopy(new_filename='/vsimem/isis_tmp.lbl', delete_copy=0) - if ret != 'success': - return ret - if gdal.VSIStatL('/vsimem/isis_tmp.cub') is None: - gdaltest.post_reason('fail') - return 'fail' + assert gdal.VSIStatL('/vsimem/isis_tmp.cub') is not None f = gdal.VSIFOpenL('/vsimem/isis_tmp.lbl', 'rb') content = gdal.VSIFReadL(1, 10000, f).decode('ASCII') gdal.VSIFCloseL(f) - if content.find('#my comment') < 0: - gdaltest.post_reason('fail') - print(content) - return 'fail' - if len(content) == 10000: - gdaltest.post_reason('fail') - return 'fail' + assert content.find('#my comment') >= 0 + assert len(content) != 10000 ds = gdal.Open('/vsimem/isis_tmp.lbl', gdal.GA_Update) ds.GetRasterBand(1).Fill(0) ds = None ds = gdal.Open('/vsimem/isis_tmp.lbl') - if ds.GetRasterBand(1).Checksum() != 0: - gdaltest.post_reason('fail') - return 'fail' + assert ds.GetRasterBand(1).Checksum() == 0 ds = None gdal.GetDriverByName('ISIS3').Delete('/vsimem/isis_tmp.lbl') - return 'success' # Uncompressed GeoTIFF creation -def isis_7(): +def test_isis_7(): tst = gdaltest.GDALTest('ISIS3', 'isis3_detached.lbl', 1, 9978, options=['DATA_LOCATION=GEOTIFF', 'USE_SRC_LABEL=NO']) - ret = tst.testCreateCopy(new_filename='/vsimem/isis_tmp.lbl', + tst.testCreateCopy(new_filename='/vsimem/isis_tmp.lbl', delete_copy=0) - if ret != 'success': - return ret - if gdal.VSIStatL('/vsimem/isis_tmp.tif') is None: - gdaltest.post_reason('fail') - return 'fail' + assert gdal.VSIStatL('/vsimem/isis_tmp.tif') is not None ds = gdal.Open('/vsimem/isis_tmp.lbl') lbl = ds.GetMetadata_List('json:ISIS3')[0] - if lbl.find('"Format":"BandSequential"') < 0: - gdaltest.post_reason('fail') - print(lbl) - return 'fail' + assert lbl.find('"Format":"BandSequential"') >= 0 ds = None gdal.GetDriverByName('ISIS3').Delete('/vsimem/isis_tmp.lbl') @@ -287,93 +221,64 @@ def isis_7(): options=['DATA_LOCATION=GEOTIFF', 'GEOTIFF_AS_REGULAR_EXTERNAL=NO', 'USE_SRC_LABEL=NO']) - ret = tst.testCreateCopy(new_filename='/vsimem/isis_tmp.lbl', + tst.testCreateCopy(new_filename='/vsimem/isis_tmp.lbl', delete_copy=0) - if ret != 'success': - return ret - if gdal.VSIStatL('/vsimem/isis_tmp.tif') is None: - gdaltest.post_reason('fail') - return 'fail' + assert gdal.VSIStatL('/vsimem/isis_tmp.tif') is not None ds = gdal.Open('/vsimem/isis_tmp.lbl') lbl = ds.GetMetadata_List('json:ISIS3')[0] - if lbl.find('"Format":"GeoTIFF"') < 0: - gdaltest.post_reason('fail') - print(lbl) - return 'fail' + assert lbl.find('"Format":"GeoTIFF"') >= 0 ds = None gdal.GetDriverByName('ISIS3').Delete('/vsimem/isis_tmp.lbl') - return 'success' - # Compressed GeoTIFF creation -def isis_8(): +def test_isis_8(): tst = gdaltest.GDALTest('ISIS3', 'isis3_detached.lbl', 1, 9978, options=['DATA_LOCATION=GEOTIFF', 'USE_SRC_LABEL=NO', 'GEOTIFF_OPTIONS=COMPRESS=LZW']) - ret = tst.testCreateCopy(new_filename='/vsimem/isis_tmp.lbl', + tst.testCreateCopy(new_filename='/vsimem/isis_tmp.lbl', delete_copy=0) - if ret != 'success': - return ret - if gdal.VSIStatL('/vsimem/isis_tmp.tif') is None: - gdaltest.post_reason('fail') - return 'fail' + assert gdal.VSIStatL('/vsimem/isis_tmp.tif') is not None ds = gdal.Open('/vsimem/isis_tmp.lbl') lbl = ds.GetMetadata_List('json:ISIS3')[0] - if lbl.find('"Format":"GeoTIFF"') < 0: - gdaltest.post_reason('fail') - print(lbl) - return 'fail' + assert lbl.find('"Format":"GeoTIFF"') >= 0 ds = None ds = gdal.Open('/vsimem/isis_tmp.lbl', gdal.GA_Update) ds.GetRasterBand(1).Fill(0) ds = None ds = gdal.Open('/vsimem/isis_tmp.lbl') - if ds.GetRasterBand(1).Checksum() != 0: - gdaltest.post_reason('fail') - return 'fail' + assert ds.GetRasterBand(1).Checksum() == 0 ds = None gdal.GetDriverByName('ISIS3').Delete('/vsimem/isis_tmp.lbl') - return 'success' # Tiled creation + EXTERNAL_FILENAME -def isis_9(): +def test_isis_9(): tst = gdaltest.GDALTest('ISIS3', 'isis3_detached.lbl', 1, 9978, options=['DATA_LOCATION=EXTERNAL', 'USE_SRC_LABEL=NO', 'TILED=YES', 'EXTERNAL_FILENAME=/vsimem/foo.bin']) - ret = tst.testCreateCopy(new_filename='/vsimem/isis_tmp.lbl', + tst.testCreateCopy(new_filename='/vsimem/isis_tmp.lbl', delete_copy=0) - if ret != 'success': - return ret - if gdal.VSIStatL('/vsimem/foo.bin') is None: - gdaltest.post_reason('fail') - return 'fail' + assert gdal.VSIStatL('/vsimem/foo.bin') is not None ds = gdal.Open('/vsimem/isis_tmp.lbl') lbl = ds.GetMetadata_List('json:ISIS3')[0] - if lbl.find('"Format":"Tile"') < 0 or lbl.find('"TileSamples":256') < 0 or \ - lbl.find('"TileLines":256') < 0: - gdaltest.post_reason('fail') - print(lbl) - return 'fail' + assert (lbl.find('"Format":"Tile"') >= 0 and lbl.find('"TileSamples":256') >= 0 and \ + lbl.find('"TileLines":256') >= 0) ds = None gdal.GetDriverByName('ISIS3').Delete('/vsimem/isis_tmp.lbl') - if gdal.VSIStatL('/vsimem/foo.bin') is not None: - gdaltest.post_reason('fail') - return 'fail' - return 'success' + assert gdal.VSIStatL('/vsimem/foo.bin') is None # Tiled creation + regular GeoTIFF + EXTERNAL_FILENAME -def isis_10(): +def test_isis_10(): tst = gdaltest.GDALTest('ISIS3', 'isis3_detached.lbl', 1, 9978, options=['USE_SRC_LABEL=NO', @@ -381,49 +286,35 @@ def isis_10(): 'TILED=YES', 'BLOCKXSIZE=16', 'BLOCKYSIZE=32', 'EXTERNAL_FILENAME=/vsimem/foo.tif']) - ret = tst.testCreateCopy(new_filename='/vsimem/isis_tmp.lbl', + tst.testCreateCopy(new_filename='/vsimem/isis_tmp.lbl', delete_copy=0) - if ret != 'success': - return ret ds = gdal.Open('/vsimem/foo.tif') - if ds.GetRasterBand(1).GetBlockSize() != [16, 32]: - gdaltest.post_reason('fail') - print(ds.GetRasterBand(1).GetBlockSize()) - return 'fail' + assert ds.GetRasterBand(1).GetBlockSize() == [16, 32] ds = None gdal.GetDriverByName('ISIS3').Delete('/vsimem/isis_tmp.lbl') - if gdal.VSIStatL('/vsimem/foo.tif') is not None: - gdaltest.post_reason('fail') - return 'fail' - return 'success' + assert gdal.VSIStatL('/vsimem/foo.tif') is None # Tiled creation + compressed GeoTIFF -def isis_11(): +def test_isis_11(): tst = gdaltest.GDALTest('ISIS3', 'isis3_detached.lbl', 1, 9978, options=['USE_SRC_LABEL=NO', 'DATA_LOCATION=GEOTIFF', 'TILED=YES', 'GEOTIFF_OPTIONS=COMPRESS=LZW']) - ret = tst.testCreateCopy(new_filename='/vsimem/isis_tmp.lbl', + tst.testCreateCopy(new_filename='/vsimem/isis_tmp.lbl', delete_copy=0) - if ret != 'success': - return ret ds = gdal.Open('/vsimem/isis_tmp.tif') - if ds.GetRasterBand(1).GetBlockSize() != [256, 256]: - gdaltest.post_reason('fail') - print(ds.GetRasterBand(1).GetBlockSize()) - return 'fail' + assert ds.GetRasterBand(1).GetBlockSize() == [256, 256] ds = None gdal.GetDriverByName('ISIS3').Delete('/vsimem/isis_tmp.lbl') - return 'success' # Multiband -def isis_12(): +def test_isis_12(): src_ds = gdal.Open('../gcore/data/stefan_full_rgba.tif') gdal.Translate('/vsimem/isis_tmp.lbl', src_ds, format='ISIS3') @@ -431,18 +322,14 @@ def isis_12(): for i in range(4): cs = ds.GetRasterBand(i + 1).Checksum() expected_cs = src_ds.GetRasterBand(i + 1).Checksum() - if cs != expected_cs: - gdaltest.post_reason('fail') - print(i + 1, cs, expected_cs) - return 'fail' + assert cs == expected_cs, (i + 1, cs, expected_cs) ds = None gdal.GetDriverByName('ISIS3').Delete('/vsimem/isis_tmp.lbl') - return 'success' # Multiband tiled -def isis_13(): +def test_isis_13(): src_ds = gdal.Open('../gcore/data/stefan_full_rgba.tif') gdal.Translate('/vsimem/isis_tmp.lbl', src_ds, format='ISIS3', @@ -452,18 +339,14 @@ def isis_13(): for i in range(4): cs = ds.GetRasterBand(i + 1).Checksum() expected_cs = src_ds.GetRasterBand(i + 1).Checksum() - if cs != expected_cs: - gdaltest.post_reason('fail') - print(i + 1, cs, expected_cs) - return 'fail' + assert cs == expected_cs, (i + 1, cs, expected_cs) ds = None gdal.GetDriverByName('ISIS3').Delete('/vsimem/isis_tmp.lbl') - return 'success' # Multiband with uncompressed GeoTIFF -def isis_14(): +def test_isis_14(): src_ds = gdal.Open('../gcore/data/stefan_full_rgba.tif') gdal.Translate('/vsimem/isis_tmp.lbl', src_ds, format='ISIS3', @@ -472,18 +355,14 @@ def isis_14(): for i in range(4): cs = ds.GetRasterBand(i + 1).Checksum() expected_cs = src_ds.GetRasterBand(i + 1).Checksum() - if cs != expected_cs: - gdaltest.post_reason('fail') - print(i + 1, cs, expected_cs) - return 'fail' + assert cs == expected_cs, (i + 1, cs, expected_cs) ds = None gdal.GetDriverByName('ISIS3').Delete('/vsimem/isis_tmp.lbl') - return 'success' # Multiband with uncompressed tiled GeoTIFF -def isis_15(): +def test_isis_15(): src_ds = gdal.Open('../gcore/data/stefan_full_rgba.tif') gdal.Translate('/vsimem/isis_tmp.lbl', src_ds, format='ISIS3', @@ -493,18 +372,14 @@ def isis_15(): for i in range(4): cs = ds.GetRasterBand(i + 1).Checksum() expected_cs = src_ds.GetRasterBand(i + 1).Checksum() - if cs != expected_cs: - gdaltest.post_reason('fail') - print(i + 1, cs, expected_cs) - return 'fail' + assert cs == expected_cs, (i + 1, cs, expected_cs) ds = None gdal.GetDriverByName('ISIS3').Delete('/vsimem/isis_tmp.lbl') - return 'success' # Test Create() without anything else -def isis_16(): +def test_isis_16(): for read_before_write in [False, True]: for init_nd in [False, True]: @@ -527,39 +402,26 @@ def isis_16(): ds.GetRasterBand(1).Fill(nd) ds = None ds = gdal.Open('/vsimem/isis_tmp.lbl') - if ds.GetRasterBand(1).Checksum() != cs: - gdaltest.post_reason('fail') - print(dt, cs, nd, options, init_nd, ds.GetRasterBand(1).Checksum()) - return 'fail' - if ds.GetRasterBand(1).GetMaskFlags() != 0: - gdaltest.post_reason('fail') - print(dt, cs, nd, options, init_nd, ds.GetRasterBand(1).GetMaskFlags()) - return 'fail' - if ds.GetRasterBand(1).GetMaskBand().Checksum() != 0: - gdaltest.post_reason('fail') - print(dt, cs, nd, options, init_nd, ds.GetRasterBand(1).GetMaskBand().Checksum()) - return 'fail' - if ds.GetRasterBand(1).GetOffset() != 10: - gdaltest.post_reason('fail') - print(dt, cs, nd, options, init_nd, ds.GetRasterBand(1).GetOffset()) - return 'fail' - if ds.GetRasterBand(1).GetScale() != 20: - gdaltest.post_reason('fail') - print(dt, cs, nd, options, init_nd, ds.GetRasterBand(1).GetScale()) - return 'fail' - if ds.GetRasterBand(1).GetNoDataValue() != nd: - gdaltest.post_reason('fail') - print(dt, cs, nd, options, init_nd, ds.GetRasterBand(1).GetNoDataValue()) - return 'fail' + assert ds.GetRasterBand(1).Checksum() == cs, \ + (dt, cs, nd, options, init_nd, ds.GetRasterBand(1).Checksum()) + assert ds.GetRasterBand(1).GetMaskFlags() == 0, \ + (dt, cs, nd, options, init_nd, ds.GetRasterBand(1).GetMaskFlags()) + assert ds.GetRasterBand(1).GetMaskBand().Checksum() == 0, \ + (dt, cs, nd, options, init_nd, ds.GetRasterBand(1).GetMaskBand().Checksum()) + assert ds.GetRasterBand(1).GetOffset() == 10, \ + (dt, cs, nd, options, init_nd, ds.GetRasterBand(1).GetOffset()) + assert ds.GetRasterBand(1).GetScale() == 20, \ + (dt, cs, nd, options, init_nd, ds.GetRasterBand(1).GetScale()) + assert ds.GetRasterBand(1).GetNoDataValue() == nd, \ + (dt, cs, nd, options, init_nd, ds.GetRasterBand(1).GetNoDataValue()) ds = None gdal.GetDriverByName('ISIS3').Delete('/vsimem/isis_tmp.lbl') - return 'success' - + # Test create copy through Create() -def isis_17(): +def test_isis_17(): tst = gdaltest.GDALTest('ISIS3', 'isis3_detached.lbl', 1, 9978) return tst.testCreate(vsimem=1) @@ -567,7 +429,7 @@ def isis_17(): # Test SRS serialization and deserialization -def isis_18(): +def test_isis_18(): sr = osr.SpatialReference() sr.SetEquirectangular2(0, 1, 2, 0, 0) @@ -578,10 +440,7 @@ def isis_18(): ds = gdal.Open('/vsimem/isis_tmp.lbl') wkt = ds.GetProjectionRef() ds = None - if not osr.SpatialReference(wkt).IsSame(osr.SpatialReference('PROJCS["Equirectangular DATUM_NAME",GEOGCS["GCS_DATUM_NAME",DATUM["D_DATUM_NAME",SPHEROID["DATUM_NAME_localRadius",123455.2424988797,0]],PRIMEM["Reference_Meridian",0],UNIT["degree",0.0174532925199433]],PROJECTION["Equirectangular"],PARAMETER["latitude_of_origin",0],PARAMETER["central_meridian",1],PARAMETER["standard_parallel_1",2],PARAMETER["false_easting",0],PARAMETER["false_northing",0]]')): - gdaltest.post_reason('fail') - print(wkt) - return 'fail' + assert osr.SpatialReference(wkt).IsSame(osr.SpatialReference('PROJCS["Equirectangular DATUM_NAME",GEOGCS["GCS_DATUM_NAME",DATUM["D_DATUM_NAME",SPHEROID["DATUM_NAME_localRadius",123455.2424988797,0]],PRIMEM["Reference_Meridian",0],UNIT["degree",0.0174532925199433]],PROJECTION["Equirectangular"],PARAMETER["latitude_of_origin",0],PARAMETER["central_meridian",1],PARAMETER["standard_parallel_1",2],PARAMETER["false_easting",0],PARAMETER["false_northing",0]]')) sr = osr.SpatialReference() sr.SetEquirectangular2(123456, 1, 2, 987654, 3210123) @@ -595,10 +454,7 @@ def isis_18(): ds = gdal.Open('/vsimem/isis_tmp.lbl') wkt = ds.GetProjectionRef() ds = None - if not osr.SpatialReference(wkt).IsSame(osr.SpatialReference('PROJCS["Equirectangular DATUM_NAME",GEOGCS["GCS_DATUM_NAME",DATUM["D_DATUM_NAME",SPHEROID["DATUM_NAME_localRadius",123455.2424988797,0]],PRIMEM["Reference_Meridian",0],UNIT["degree",0.0174532925199433]],PROJECTION["Equirectangular"],PARAMETER["latitude_of_origin",0],PARAMETER["central_meridian",1],PARAMETER["standard_parallel_1",2],PARAMETER["false_easting",0],PARAMETER["false_northing",0]]')): - gdaltest.post_reason('fail') - print(wkt) - return 'fail' + assert osr.SpatialReference(wkt).IsSame(osr.SpatialReference('PROJCS["Equirectangular DATUM_NAME",GEOGCS["GCS_DATUM_NAME",DATUM["D_DATUM_NAME",SPHEROID["DATUM_NAME_localRadius",123455.2424988797,0]],PRIMEM["Reference_Meridian",0],UNIT["degree",0.0174532925199433]],PROJECTION["Equirectangular"],PARAMETER["latitude_of_origin",0],PARAMETER["central_meridian",1],PARAMETER["standard_parallel_1",2],PARAMETER["false_easting",0],PARAMETER["false_northing",0]]')) sr = osr.SpatialReference() sr.SetOrthographic(1, 2, 0, 0) @@ -609,10 +465,7 @@ def isis_18(): ds = gdal.Open('/vsimem/isis_tmp.lbl') wkt = ds.GetProjectionRef() ds = None - if not osr.SpatialReference(wkt).IsSame(osr.SpatialReference('PROJCS["Orthographic DATUM_NAME",GEOGCS["GCS_DATUM_NAME",DATUM["D_DATUM_NAME",SPHEROID["DATUM_NAME",123456,0]],PRIMEM["Reference_Meridian",0],UNIT["degree",0.0174532925199433]],PROJECTION["Orthographic"],PARAMETER["latitude_of_origin",1],PARAMETER["central_meridian",2],PARAMETER["false_easting",0],PARAMETER["false_northing",0]]')): - gdaltest.post_reason('fail') - print(wkt) - return 'fail' + assert osr.SpatialReference(wkt).IsSame(osr.SpatialReference('PROJCS["Orthographic DATUM_NAME",GEOGCS["GCS_DATUM_NAME",DATUM["D_DATUM_NAME",SPHEROID["DATUM_NAME",123456,0]],PRIMEM["Reference_Meridian",0],UNIT["degree",0.0174532925199433]],PROJECTION["Orthographic"],PARAMETER["latitude_of_origin",1],PARAMETER["central_meridian",2],PARAMETER["false_easting",0],PARAMETER["false_northing",0]]')) sr = osr.SpatialReference() sr.SetSinusoidal(1, 0, 0) @@ -623,10 +476,7 @@ def isis_18(): ds = gdal.Open('/vsimem/isis_tmp.lbl') wkt = ds.GetProjectionRef() ds = None - if not osr.SpatialReference(wkt).IsSame(osr.SpatialReference('PROJCS["Sinusoidal DATUM_NAME",GEOGCS["GCS_DATUM_NAME",DATUM["D_DATUM_NAME",SPHEROID["DATUM_NAME",123456,0]],PRIMEM["Reference_Meridian",0],UNIT["degree",0.0174532925199433]],PROJECTION["Sinusoidal"],PARAMETER["longitude_of_center",1],PARAMETER["false_easting",0],PARAMETER["false_northing",0]]')): - gdaltest.post_reason('fail') - print(wkt) - return 'fail' + assert osr.SpatialReference(wkt).IsSame(osr.SpatialReference('PROJCS["Sinusoidal DATUM_NAME",GEOGCS["GCS_DATUM_NAME",DATUM["D_DATUM_NAME",SPHEROID["DATUM_NAME",123456,0]],PRIMEM["Reference_Meridian",0],UNIT["degree",0.0174532925199433]],PROJECTION["Sinusoidal"],PARAMETER["longitude_of_center",1],PARAMETER["false_easting",0],PARAMETER["false_northing",0]]')) sr = osr.SpatialReference() sr.SetMercator(1, 2, 0.9, 0, 0) @@ -637,10 +487,7 @@ def isis_18(): ds = gdal.Open('/vsimem/isis_tmp.lbl') wkt = ds.GetProjectionRef() ds = None - if not osr.SpatialReference(wkt).IsSame(osr.SpatialReference('PROJCS["Mercator DATUM_NAME",GEOGCS["GCS_DATUM_NAME",DATUM["D_DATUM_NAME",SPHEROID["DATUM_NAME",123456,0]],PRIMEM["Reference_Meridian",0],UNIT["degree",0.0174532925199433]],PROJECTION["Mercator_1SP"],PARAMETER["latitude_of_origin",1],PARAMETER["central_meridian",2],PARAMETER["scale_factor",0.9],PARAMETER["false_easting",0],PARAMETER["false_northing",0]]')): - gdaltest.post_reason('fail') - print(wkt) - return 'fail' + assert osr.SpatialReference(wkt).IsSame(osr.SpatialReference('PROJCS["Mercator DATUM_NAME",GEOGCS["GCS_DATUM_NAME",DATUM["D_DATUM_NAME",SPHEROID["DATUM_NAME",123456,0]],PRIMEM["Reference_Meridian",0],UNIT["degree",0.0174532925199433]],PROJECTION["Mercator_1SP"],PARAMETER["latitude_of_origin",1],PARAMETER["central_meridian",2],PARAMETER["scale_factor",0.9],PARAMETER["false_easting",0],PARAMETER["false_northing",0]]')) sr = osr.SpatialReference() sr.SetPS(1, 2, 0.9, 0, 0) @@ -651,10 +498,7 @@ def isis_18(): ds = gdal.Open('/vsimem/isis_tmp.lbl') wkt = ds.GetProjectionRef() ds = None - if not osr.SpatialReference(wkt).IsSame(osr.SpatialReference('PROJCS["PolarStereographic DATUM_NAME",GEOGCS["GCS_DATUM_NAME",DATUM["D_DATUM_NAME",SPHEROID["DATUM_NAME_polarRadius",122838.72,0]],PRIMEM["Reference_Meridian",0],UNIT["degree",0.0174532925199433]],PROJECTION["Polar_Stereographic"],PARAMETER["latitude_of_origin",1],PARAMETER["central_meridian",2],PARAMETER["scale_factor",0.9],PARAMETER["false_easting",0],PARAMETER["false_northing",0]]')): - gdaltest.post_reason('fail') - print(wkt) - return 'fail' + assert osr.SpatialReference(wkt).IsSame(osr.SpatialReference('PROJCS["PolarStereographic DATUM_NAME",GEOGCS["GCS_DATUM_NAME",DATUM["D_DATUM_NAME",SPHEROID["DATUM_NAME_polarRadius",122838.72,0]],PRIMEM["Reference_Meridian",0],UNIT["degree",0.0174532925199433]],PROJECTION["Polar_Stereographic"],PARAMETER["latitude_of_origin",1],PARAMETER["central_meridian",2],PARAMETER["scale_factor",0.9],PARAMETER["false_easting",0],PARAMETER["false_northing",0]]')) sr = osr.SpatialReference() sr.SetTM(1, 2, 0.9, 0, 0) @@ -665,10 +509,7 @@ def isis_18(): ds = gdal.Open('/vsimem/isis_tmp.lbl') wkt = ds.GetProjectionRef() ds = None - if not osr.SpatialReference(wkt).IsSame(osr.SpatialReference('PROJCS["TransverseMercator DATUM_NAME",GEOGCS["GCS_DATUM_NAME",DATUM["D_DATUM_NAME",SPHEROID["DATUM_NAME",123456,0]],PRIMEM["Reference_Meridian",0],UNIT["degree",0.0174532925199433]],PROJECTION["Transverse_Mercator"],PARAMETER["latitude_of_origin",1],PARAMETER["central_meridian",2],PARAMETER["scale_factor",0.9],PARAMETER["false_easting",0],PARAMETER["false_northing",0]]')): - gdaltest.post_reason('fail') - print(wkt) - return 'fail' + assert osr.SpatialReference(wkt).IsSame(osr.SpatialReference('PROJCS["TransverseMercator DATUM_NAME",GEOGCS["GCS_DATUM_NAME",DATUM["D_DATUM_NAME",SPHEROID["DATUM_NAME",123456,0]],PRIMEM["Reference_Meridian",0],UNIT["degree",0.0174532925199433]],PROJECTION["Transverse_Mercator"],PARAMETER["latitude_of_origin",1],PARAMETER["central_meridian",2],PARAMETER["scale_factor",0.9],PARAMETER["false_easting",0],PARAMETER["false_northing",0]]')) sr = osr.SpatialReference() sr.SetLCC(1, 2, 3, 4, 0, 0) @@ -679,10 +520,7 @@ def isis_18(): ds = gdal.Open('/vsimem/isis_tmp.lbl') wkt = ds.GetProjectionRef() ds = None - if not osr.SpatialReference(wkt).IsSame(osr.SpatialReference('PROJCS["LambertConformal DATUM_NAME",GEOGCS["GCS_DATUM_NAME",DATUM["D_DATUM_NAME",SPHEROID["DATUM_NAME",123456,0]],PRIMEM["Reference_Meridian",0],UNIT["degree",0.0174532925199433]],PROJECTION["Lambert_Conformal_Conic_2SP"],PARAMETER["standard_parallel_1",1],PARAMETER["standard_parallel_2",2],PARAMETER["latitude_of_origin",3],PARAMETER["central_meridian",4],PARAMETER["false_easting",0],PARAMETER["false_northing",0]]')): - gdaltest.post_reason('fail') - print(wkt) - return 'fail' + assert osr.SpatialReference(wkt).IsSame(osr.SpatialReference('PROJCS["LambertConformal DATUM_NAME",GEOGCS["GCS_DATUM_NAME",DATUM["D_DATUM_NAME",SPHEROID["DATUM_NAME",123456,0]],PRIMEM["Reference_Meridian",0],UNIT["degree",0.0174532925199433]],PROJECTION["Lambert_Conformal_Conic_2SP"],PARAMETER["standard_parallel_1",1],PARAMETER["standard_parallel_2",2],PARAMETER["latitude_of_origin",3],PARAMETER["central_meridian",4],PARAMETER["false_easting",0],PARAMETER["false_northing",0]]')) sr = osr.SpatialReference() sr.SetEquirectangular2(0, 1, 2, 0, 0) @@ -696,30 +534,12 @@ def isis_18(): ds = None ds = gdal.Open('/vsimem/isis_tmp.lbl') lbl = ds.GetMetadata_List('json:ISIS3')[0] - if lbl.find('"TargetName":"my_target"') < 0: - gdaltest.post_reason('fail') - print(lbl) - return 'fail' - if lbl.find('"LatitudeType":"Planetographic"') < 0: - gdaltest.post_reason('fail') - print(lbl) - return 'fail' - if lbl.find('"MinimumLatitude":2.5') < 0: - gdaltest.post_reason('fail') - print(lbl) - return 'fail' - if lbl.find('"MinimumLongitude":1.5') < 0: - gdaltest.post_reason('fail') - print(lbl) - return 'fail' - if lbl.find('"MaximumLatitude":4.5') < 0: - gdaltest.post_reason('fail') - print(lbl) - return 'fail' - if lbl.find('"MaximumLongitude":3.5') < 0: - gdaltest.post_reason('fail') - print(lbl) - return 'fail' + assert lbl.find('"TargetName":"my_target"') >= 0 + assert lbl.find('"LatitudeType":"Planetographic"') >= 0 + assert lbl.find('"MinimumLatitude":2.5') >= 0 + assert lbl.find('"MinimumLongitude":1.5') >= 0 + assert lbl.find('"MaximumLatitude":4.5') >= 0 + assert lbl.find('"MaximumLongitude":3.5') >= 0 ds = None sr = osr.SpatialReference() @@ -731,30 +551,12 @@ def isis_18(): ds = None ds = gdal.Open('/vsimem/isis_tmp.lbl') lbl = ds.GetMetadata_List('json:ISIS3')[0] - if lbl.find('"LongitudeDirection":"PositiveWest"') < 0: - gdaltest.post_reason('fail') - print(lbl) - return 'fail' - if lbl.find('"LongitudeDomain":180') < 0: - gdaltest.post_reason('fail') - print(lbl) - return 'fail' - if lbl.find('"MinimumLatitude":-60') < 0: - gdaltest.post_reason('fail') - print(lbl) - return 'fail' - if lbl.find('"MinimumLongitude":-110') < 0: - gdaltest.post_reason('fail') - print(lbl) - return 'fail' - if lbl.find('"MaximumLatitude":40') < 0: - gdaltest.post_reason('fail') - print(lbl) - return 'fail' - if lbl.find('"MaximumLongitude":-10') < 0: - gdaltest.post_reason('fail') - print(lbl) - return 'fail' + assert lbl.find('"LongitudeDirection":"PositiveWest"') >= 0 + assert lbl.find('"LongitudeDomain":180') >= 0 + assert lbl.find('"MinimumLatitude":-60') >= 0 + assert lbl.find('"MinimumLongitude":-110') >= 0 + assert lbl.find('"MaximumLatitude":40') >= 0 + assert lbl.find('"MaximumLongitude":-10') >= 0 ds = None sr = osr.SpatialReference() @@ -766,111 +568,68 @@ def isis_18(): ds = None ds = gdal.Open('/vsimem/isis_tmp.lbl') lbl = ds.GetMetadata_List('json:ISIS3')[0] - if lbl.find('"MinimumLatitude":-60') < 0: - gdaltest.post_reason('fail') - print(lbl) - return 'fail' - if lbl.find('"MinimumLongitude":90') < 0: - gdaltest.post_reason('fail') - print(lbl) - return 'fail' - if lbl.find('"MaximumLatitude":40') < 0: - gdaltest.post_reason('fail') - print(lbl) - return 'fail' - if lbl.find('"MaximumLongitude":350') < 0: - gdaltest.post_reason('fail') - print(lbl) - return 'fail' - if lbl.find('"UpperLeftCornerX":-21547') < 0: - gdaltest.post_reason('fail') - print(lbl) - return 'fail' - if lbl.find('"UpperLeftCornerY":86188') < 0: - gdaltest.post_reason('fail') - print(lbl) - return 'fail' + assert lbl.find('"MinimumLatitude":-60') >= 0 + assert lbl.find('"MinimumLongitude":90') >= 0 + assert lbl.find('"MaximumLatitude":40') >= 0 + assert lbl.find('"MaximumLongitude":350') >= 0 + assert lbl.find('"UpperLeftCornerX":-21547') >= 0 + assert lbl.find('"UpperLeftCornerY":86188') >= 0 ds = None gdal.GetDriverByName('ISIS3').Delete('/vsimem/isis_tmp.lbl') - return 'success' - # Test gdal.Info() with json:ISIS3 metadata domain -def isis_19(): +def test_isis_19(): ds = gdal.Open('data/isis3_detached.lbl') res = gdal.Info(ds, format='json', extraMDDomains=['json:ISIS3']) - if res['metadata']['json:ISIS3']['IsisCube']['_type'] != 'object': - gdaltest.post_reason('fail') - print(res) - return 'fail' + assert res['metadata']['json:ISIS3']['IsisCube']['_type'] == 'object' ds = gdal.Open('data/isis3_detached.lbl') res = gdal.Info(ds, extraMDDomains=['json:ISIS3']) - if res.find('IsisCube') < 0: - gdaltest.post_reason('fail') - print(res) - return 'fail' - - return 'success' + assert res.find('IsisCube') >= 0 # Test gdal.Translate() subsetting and label preservation -def isis_20(): +def test_isis_20(): with gdaltest.error_handler(): gdal.Translate('/vsimem/isis_tmp.lbl', 'data/isis3_detached.lbl', format='ISIS3', srcWin=[0, 0, 1, 1]) ds = gdal.Open('/vsimem/isis_tmp.lbl') lbl = ds.GetMetadata_List('json:ISIS3')[0] - if lbl.find('AMadeUpValue') < 0: - gdaltest.post_reason('fail') - print(lbl) - return 'fail' + assert lbl.find('AMadeUpValue') >= 0 ds = None gdal.GetDriverByName('ISIS3').Delete('/vsimem/isis_tmp.lbl') - return 'success' - # Test gdal.Warp() and label preservation -def isis_21(): +def test_isis_21(): with gdaltest.error_handler(): gdal.Warp('/vsimem/isis_tmp.lbl', 'data/isis3_detached.lbl', format='ISIS3') ds = gdal.Open('/vsimem/isis_tmp.lbl') - if ds.GetRasterBand(1).Checksum() != 9978: - gdaltest.post_reason('fail') - print(ds.GetRasterBand(1).Checksum()) - return 'fail' + assert ds.GetRasterBand(1).Checksum() == 9978 lbl = ds.GetMetadata_List('json:ISIS3')[0] - if lbl.find('AMadeUpValue') < 0: - gdaltest.post_reason('fail') - print(lbl) - return 'fail' + assert lbl.find('AMadeUpValue') >= 0 ds = None gdal.GetDriverByName('ISIS3').Delete('/vsimem/isis_tmp.lbl') - return 'success' - # Test source JSon use -def isis_22(): +def test_isis_22(): ds = gdal.GetDriverByName('ISIS3').Create('/vsimem/isis_tmp.lbl', 1, 1) # Invalid Json js = """invalid""" with gdaltest.error_handler(): - if ds.SetMetadata([js], 'json:ISIS3') == 0: - gdaltest.post_reason('fail') - return 'fail' + assert ds.SetMetadata([js], 'json:ISIS3') != 0 ds = None gdal.GetDriverByName('ISIS3').Delete('/vsimem/isis_tmp.lbl') @@ -879,15 +638,11 @@ def isis_22(): js = """{ "IsisCube": 5 }""" ds.SetMetadata([js], 'json:ISIS3') lbl = ds.GetMetadata_List('json:ISIS3') - if lbl is None: - gdaltest.post_reason('fail') - return 'fail' + assert lbl is not None ds.SetMetadata([js], 'json:ISIS3') ds = None ds = gdal.Open('/vsimem/isis_tmp.lbl') - if ds is None: - gdaltest.post_reason('fail') - return 'fail' + assert ds is not None gdal.GetDriverByName('ISIS3').Delete('/vsimem/isis_tmp.lbl') ds = gdal.GetDriverByName('ISIS3').Create('/vsimem/isis_tmp.lbl', 1, 1) @@ -896,9 +651,7 @@ def isis_22(): ds.SetMetadata([js], 'json:ISIS3') ds = None ds = gdal.Open('/vsimem/isis_tmp.lbl') - if ds is None: - gdaltest.post_reason('fail') - return 'fail' + assert ds is not None gdal.GetDriverByName('ISIS3').Delete('/vsimem/isis_tmp.lbl') ds = gdal.GetDriverByName('ISIS3').Create('/vsimem/isis_tmp.lbl', 1, 1) @@ -908,9 +661,7 @@ def isis_22(): ds.SetMetadata([js], 'json:ISIS3') ds = None ds = gdal.Open('/vsimem/isis_tmp.lbl') - if ds is None: - gdaltest.post_reason('fail') - return 'fail' + assert ds is not None gdal.GetDriverByName('ISIS3').Delete('/vsimem/isis_tmp.lbl') ds = gdal.GetDriverByName('ISIS3').Create('/vsimem/isis_tmp.lbl', 1, 1, @@ -923,44 +674,34 @@ def isis_22(): ds = None f = gdal.VSIFOpenL('/vsimem/isis_tmp.lbl', 'rb') - if f is None: - gdaltest.post_reason('fail') - return 'fail' + assert f is not None content = gdal.VSIFReadL(1, 10000, f).decode('ASCII') gdal.VSIFCloseL(f) - if content.find('foo = bar') < 0 or \ - content.find(' bar = (123, 124.0, 2.5, xyz') < 0 or \ - content.find(' anotherveeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee-') < 0 or \ - content.find(' eeeeeeeeeeeeeeeeeeeeeeeerylooooongtext, 234, 456, 789, 234, 567,') < 0 or \ - content.find(' 890, 123456789.0, 123456789.0, 123456789.0, 123456789.0,') < 0 or \ - content.find(' 123456789.0)') < 0 or \ - content.find('baz = 5 <M>') < 0 or \ - content.find('baw = "with space"') < 0 or \ - content.find('very_long = aveeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee-') < 0: - gdaltest.post_reason('fail') - print(content) - return 'fail' + assert (content.find('foo = bar') >= 0 and \ + content.find(' bar = (123, 124.0, 2.5, xyz') >= 0 and \ + content.find(' anotherveeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee-') >= 0 and \ + content.find(' eeeeeeeeeeeeeeeeeeeeeeeerylooooongtext, 234, 456, 789, 234, 567,') >= 0 and \ + content.find(' 890, 123456789.0, 123456789.0, 123456789.0, 123456789.0,') >= 0 and \ + content.find(' 123456789.0)') >= 0 and \ + content.find('baz = 5 <M>') >= 0 and \ + content.find('baw = "with space"') >= 0 and \ + content.find('very_long = aveeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee-') >= 0) ds = gdal.Open('/vsimem/isis_tmp.lbl') lbl = ds.GetMetadata_List('json:ISIS3')[0] - if lbl.find('"foo":"bar"') < 0 or lbl.find('123') < 0 or \ - lbl.find('2.5') < 0 or lbl.find('xyz') < 0 or \ - lbl.find('"value":5') < 0 or lbl.find('"unit":"M"') < 0 or \ - lbl.find('"baw":"with space"') < 0 or \ - lbl.find('"very_long":"aveeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeerylooooongtext"') < 0: - gdaltest.post_reason('fail') - print(lbl) - return 'fail' + assert (lbl.find('"foo":"bar"') >= 0 and lbl.find('123') >= 0 and \ + lbl.find('2.5') >= 0 and lbl.find('xyz') >= 0 and \ + lbl.find('"value":5') >= 0 and lbl.find('"unit":"M"') >= 0 and \ + lbl.find('"baw":"with space"') >= 0 and \ + lbl.find('"very_long":"aveeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeerylooooongtext"') >= 0) ds = None gdal.GetDriverByName('ISIS3').Delete('/vsimem/isis_tmp.lbl') - return 'success' - # Test nodata remapping -def isis_23(): +def test_isis_23(): mem_ds = gdal.Translate('', 'data/byte.tif', format='MEM') mem_ds.SetProjection('') @@ -970,27 +711,21 @@ def isis_23(): gdal.Translate('/vsimem/isis_tmp.lbl', mem_ds, format='ISIS3') ds = gdal.Open('/vsimem/isis_tmp.lbl') - if ref_data == ds.GetRasterBand(1).ReadRaster(): - gdaltest.post_reason('fail') - return 'fail' + assert ref_data != ds.GetRasterBand(1).ReadRaster() ds = None gdal.GetDriverByName('ISIS3').Delete('/vsimem/isis_tmp.lbl') gdal.Translate('/vsimem/isis_tmp.lbl', mem_ds, format='ISIS3', creationOptions=['DATA_LOCATION=GeoTIFF']) ds = gdal.Open('/vsimem/isis_tmp.lbl') - if ref_data == ds.GetRasterBand(1).ReadRaster(): - gdaltest.post_reason('fail') - return 'fail' + assert ref_data != ds.GetRasterBand(1).ReadRaster() ds = None gdal.GetDriverByName('ISIS3').Delete('/vsimem/isis_tmp.lbl') gdal.Translate('/vsimem/isis_tmp.lbl', mem_ds, format='ISIS3', creationOptions=['TILED=YES']) ds = gdal.Open('/vsimem/isis_tmp.lbl') - if ref_data == ds.GetRasterBand(1).ReadRaster(): - gdaltest.post_reason('fail') - return 'fail' + assert ref_data != ds.GetRasterBand(1).ReadRaster() ds = None gdal.GetDriverByName('ISIS3').Delete('/vsimem/isis_tmp.lbl') @@ -1003,14 +738,11 @@ def isis_23(): gdal.Translate('/vsimem/isis_tmp.lbl', mem_ds, format='ISIS3') ds = gdal.Open('/vsimem/isis_tmp.lbl') - if ref_data == ds.GetRasterBand(1).ReadRaster(): - gdaltest.post_reason('fail') - return 'fail' + assert ref_data != ds.GetRasterBand(1).ReadRaster() ds = None gdal.GetDriverByName('ISIS3').Delete('/vsimem/isis_tmp.lbl') - return 'success' - + def cancel_cbk(pct, msg, user_data): # pylint: disable=unused-argument @@ -1019,24 +751,20 @@ def cancel_cbk(pct, msg, user_data): # Test error cases -def isis_24(): +def test_isis_24(): # For DATA_LOCATION=EXTERNAL, the main filename should have a .lbl extension with gdaltest.error_handler(): ds = gdal.GetDriverByName('ISIS3').Create('/vsimem/error.txt', 1, 1, options=['DATA_LOCATION=EXTERNAL']) - if ds is not None: - gdaltest.post_reason('fail') - return 'fail' + assert ds is None # cannot create external filename with gdaltest.error_handler(): ds = gdal.GetDriverByName('ISIS3').Create('/vsimem/error.lbl', 1, 1, options=['DATA_LOCATION=EXTERNAL', 'EXTERNAL_FILENAME=/i_dont/exist/error.cub']) - if ds is not None: - gdaltest.post_reason('fail') - return 'fail' + assert ds is None # no GTiff driver # with gdaltest.error_handler(): @@ -1054,9 +782,7 @@ def isis_24(): ds = gdal.GetDriverByName('ISIS3').Create('/vsimem/error.lbl', 1, 1, options=['DATA_LOCATION=GEOTIFF', 'EXTERNAL_FILENAME=/i_dont/exist/error.tif']) - if ds is not None: - gdaltest.post_reason('fail') - return 'fail' + assert ds is None gdal.Unlink('/vsimem/error.lbl') # Output file has same name as input file @@ -1065,9 +791,7 @@ def isis_24(): ds = gdal.GetDriverByName('ISIS3').CreateCopy('/vsimem/out.lbl', src_ds, options=['DATA_LOCATION=GEOTIFF']) - if ds is not None: - gdaltest.post_reason('fail') - return 'fail' + assert ds is None gdal.Unlink('/vsimem/out.tif') # Missing /vsimem/out.cub @@ -1079,14 +803,10 @@ def isis_24(): gdal.Unlink('/vsimem/out.cub') with gdaltest.error_handler(): ds = gdal.Open('/vsimem/out.lbl') - if ds is not None: - gdaltest.post_reason('fail') - return 'fail' + assert ds is None with gdaltest.error_handler(): ds = gdal.Open('/vsimem/out.lbl', gdal.GA_Update) - if ds is not None: - gdaltest.post_reason('fail') - return 'fail' + assert ds is None # Delete would fail since ds is None gdal.Unlink('/vsimem/out.lbl') @@ -1100,9 +820,7 @@ def isis_24(): gdal.Unlink('/vsimem/out.tif') with gdaltest.error_handler(): ds = gdal.Open('/vsimem/out.lbl') - if ds is not None: - gdaltest.post_reason('fail') - return 'fail' + assert ds is None # Delete would fail since ds is None gdal.Unlink('/vsimem/out.lbl') @@ -1136,14 +854,10 @@ def isis_24(): gdal.GetDriverByName('ISIS3').Delete('/vsimem/out.lbl') gdal.FileFromMemBuffer('/vsimem/out.lbl', 'IsisCube') - if gdal.IdentifyDriver('/vsimem/out.lbl') is None: - gdaltest.post_reason('fail') - return 'fail' + assert gdal.IdentifyDriver('/vsimem/out.lbl') is not None with gdaltest.error_handler(): ds = gdal.Open('/vsimem/out.lbl') - if ds is not None: - gdaltest.post_reason('fail') - return 'fail' + assert ds is None # Delete would fail since ds is None gdal.Unlink('/vsimem/out.lbl') @@ -1167,9 +881,7 @@ def isis_24(): # Wrong tile dimensions : 0 x 0 with gdaltest.error_handler(): ds = gdal.Open('/vsimem/out.lbl') - if ds is not None: - gdaltest.post_reason('fail') - return 'fail' + assert ds is None # Delete would fail since ds is None gdal.Unlink('/vsimem/out.lbl') @@ -1193,9 +905,7 @@ def isis_24(): # Invalid dataset dimensions : 0 x 0 with gdaltest.error_handler(): ds = gdal.Open('/vsimem/out.lbl') - if ds is not None: - gdaltest.post_reason('fail') - return 'fail' + assert ds is None # Delete would fail since ds is None gdal.Unlink('/vsimem/out.lbl') @@ -1219,9 +929,7 @@ def isis_24(): # Invalid band count : 0 with gdaltest.error_handler(): ds = gdal.Open('/vsimem/out.lbl') - if ds is not None: - gdaltest.post_reason('fail') - return 'fail' + assert ds is None # Delete would fail since ds is None gdal.Unlink('/vsimem/out.lbl') @@ -1246,9 +954,7 @@ def isis_24(): # unhandled format with gdaltest.error_handler(): ds = gdal.Open('/vsimem/out.lbl') - if ds is not None: - gdaltest.post_reason('fail') - return 'fail' + assert ds is None # Delete would fail since ds is None gdal.Unlink('/vsimem/out.lbl') @@ -1273,9 +979,7 @@ def isis_24(): # bad PDL formatting with gdaltest.error_handler(): ds = gdal.Open('/vsimem/out.lbl') - if ds is not None: - gdaltest.post_reason('fail') - return 'fail' + assert ds is None # Delete would fail since ds is None gdal.Unlink('/vsimem/out.lbl') @@ -1293,9 +997,7 @@ def isis_24(): # missing Group = Pixels. This is actually valid. Assuming Real ds = gdal.Open('/vsimem/out.lbl') - if ds is None: - gdaltest.post_reason('fail') - return 'fail' + assert ds is not None # Delete would fail since ds is None gdal.Unlink('/vsimem/out.lbl') @@ -1306,27 +1008,19 @@ def isis_24(): gdal.GetDriverByName('GTiff').Create('/vsimem/out.tif', 1, 2) with gdaltest.error_handler(): ds = gdal.Open('/vsimem/out.lbl') - if ds is not None: - gdaltest.post_reason('fail') - return 'fail' + assert ds is None gdal.GetDriverByName('GTiff').Create('/vsimem/out.tif', 2, 1) with gdaltest.error_handler(): ds = gdal.Open('/vsimem/out.lbl') - if ds is not None: - gdaltest.post_reason('fail') - return 'fail' + assert ds is None gdal.GetDriverByName('GTiff').Create('/vsimem/out.tif', 1, 1, 2) with gdaltest.error_handler(): ds = gdal.Open('/vsimem/out.lbl') - if ds is not None: - gdaltest.post_reason('fail') - return 'fail' + assert ds is None gdal.GetDriverByName('GTiff').Create('/vsimem/out.tif', 1, 1, 1, gdal.GDT_Int16) with gdaltest.error_handler(): ds = gdal.Open('/vsimem/out.lbl') - if ds is not None: - gdaltest.post_reason('fail') - return 'fail' + assert ds is None # Delete would fail since ds is None gdal.Unlink('/vsimem/out.lbl') gdal.Unlink('/vsimem/out.tif') @@ -1338,44 +1032,32 @@ def isis_24(): gdal.ErrorReset() with gdaltest.error_handler(): ds = gdal.Open('/vsimem/out.lbl') - if gdal.GetLastErrorMsg() == '': - gdaltest.post_reason('fail') - return 'fail' + assert gdal.GetLastErrorMsg() != '' gdal.GetDriverByName('GTiff').Create('/vsimem/out.tif', 2, 1) gdal.ErrorReset() with gdaltest.error_handler(): ds = gdal.Open('/vsimem/out.lbl') - if gdal.GetLastErrorMsg() == '': - gdaltest.post_reason('fail') - return 'fail' + assert gdal.GetLastErrorMsg() != '' gdal.GetDriverByName('GTiff').Create('/vsimem/out.tif', 1, 1, 2) gdal.ErrorReset() with gdaltest.error_handler(): ds = gdal.Open('/vsimem/out.lbl') - if gdal.GetLastErrorMsg() == '': - gdaltest.post_reason('fail') - return 'fail' + assert gdal.GetLastErrorMsg() != '' gdal.GetDriverByName('GTiff').Create('/vsimem/out.tif', 1, 1, 1, gdal.GDT_Int16) gdal.ErrorReset() with gdaltest.error_handler(): ds = gdal.Open('/vsimem/out.lbl') - if gdal.GetLastErrorMsg() == '': - gdaltest.post_reason('fail') - return 'fail' + assert gdal.GetLastErrorMsg() != '' gdal.GetDriverByName('GTiff').Create('/vsimem/out.tif', 1, 1, options=['COMPRESS=LZW']) gdal.ErrorReset() with gdaltest.error_handler(): ds = gdal.Open('/vsimem/out.lbl') - if gdal.GetLastErrorMsg() == '': - gdaltest.post_reason('fail') - return 'fail' + assert gdal.GetLastErrorMsg() != '' gdal.GetDriverByName('GTiff').Create('/vsimem/out.tif', 1, 1, options=['TILED=YES']) gdal.ErrorReset() with gdaltest.error_handler(): ds = gdal.Open('/vsimem/out.lbl') - if gdal.GetLastErrorMsg() == '': - gdaltest.post_reason('fail') - return 'fail' + assert gdal.GetLastErrorMsg() != '' ds = gdal.GetDriverByName('GTiff').Create('/vsimem/out.tif', 1, 1) ds.GetRasterBand(1).SetNoDataValue(0) ds.SetMetadataItem('foo', 'bar') @@ -1383,9 +1065,7 @@ def isis_24(): gdal.ErrorReset() with gdaltest.error_handler(): ds = gdal.Open('/vsimem/out.lbl') - if gdal.GetLastErrorMsg() == '': - gdaltest.post_reason('fail') - return 'fail' + assert gdal.GetLastErrorMsg() != '' with gdaltest.error_handler(): gdal.GetDriverByName('ISIS3').Delete('/vsimem/out.lbl') gdal.Unlink('/vsimem/out.tif') @@ -1395,39 +1075,29 @@ def isis_24(): ds = gdal.GetDriverByName('ISIS3').CreateCopy('/vsimem/out.lbl', mem_ds, callback=cancel_cbk) - if ds is not None: - gdaltest.post_reason('fail') - return 'fail' + assert ds is None # Delete would fail since ds is None gdal.Unlink('/vsimem/out.lbl') - return 'success' - # Test CreateCopy() and scale and offset -def isis_25(): +def test_isis_25(): mem_ds = gdal.GetDriverByName('MEM').Create('', 1, 1, 1) mem_ds.GetRasterBand(1).SetScale(10) mem_ds.GetRasterBand(1).SetOffset(20) gdal.GetDriverByName('ISIS3').CreateCopy('/vsimem/out.lbl', mem_ds) ds = gdal.Open('/vsimem/out.lbl') - if ds.GetRasterBand(1).GetScale() != 10: - gdaltest.post_reason('fail') - return 'fail' - if ds.GetRasterBand(1).GetOffset() != 20: - gdaltest.post_reason('fail') - return 'fail' + assert ds.GetRasterBand(1).GetScale() == 10 + assert ds.GetRasterBand(1).GetOffset() == 20 ds = None gdal.GetDriverByName('ISIS3').Delete('/vsimem/out.lbl') - return 'success' - # Test objects with same name -def isis_26(): +def test_isis_26(): gdal.FileFromMemBuffer('/vsimem/in.lbl', """Object = IsisCube Object = Core StartByte = 1 @@ -1474,7 +1144,7 @@ def isis_26(): content = gdal.VSIFReadL(1, 10000, f).decode('ASCII') gdal.VSIFCloseL(f) - if content.find( + assert (content.find( """Object = Table Name = first_table End_Object @@ -1494,20 +1164,15 @@ def isis_26(): Object = foo x = C End_Object -""") < 0: - gdaltest.post_reason('fail') - print(content) - return 'fail' +""") >= 0) gdal.Unlink('/vsimem/in.lbl') gdal.GetDriverByName('ISIS3').Delete('/vsimem/out.lbl') - return 'success' - # Test history -def isis_27(): +def test_isis_27(): for src_location in ['LABEL', 'EXTERNAL']: for dst_location in ['LABEL', 'EXTERNAL']: @@ -1531,11 +1196,9 @@ def isis_27(): if dst_location == 'EXTERNAL': history_filename = lbl['History']['^History'] if history_filename != 'out2.History.IsisCube': - gdaltest.post_reason('fail') print(src_location) print(dst_location) - print(content) - return 'fail' + pytest.fail(content) f = gdal.VSIFOpenL('/vsimem/' + history_filename, 'rb') history = None @@ -1544,31 +1207,22 @@ def isis_27(): gdal.VSIFCloseL(f) if offset != 0 or size != len(history): - gdaltest.post_reason('fail') print(src_location) print(dst_location) - print(content) - print(history) - return 'fail' + pytest.fail(content) else: if offset + size != len(content): - gdaltest.post_reason('fail') print(src_location) - print(dst_location) - print(content) - return 'fail' + pytest.fail(dst_location) history = content[offset:] if history.find('Object = ') != 0 or \ history.find('FROM = out.lbl') < 0 or \ history.find('TO = out2.lbl') < 0 or \ history.find('TO = out.lbl') < 0: - gdaltest.post_reason('fail') print(src_location) print(dst_location) - print(content) - print(history) - return 'fail' + pytest.fail(content) gdal.GetDriverByName('ISIS3').Delete('/vsimem/out.lbl') gdal.GetDriverByName('ISIS3').Delete('/vsimem/out2.lbl') @@ -1581,18 +1235,13 @@ def isis_27(): if f is not None: content = gdal.VSIFReadL(1, 10000, f).decode('ASCII') gdal.VSIFCloseL(f) - if content.find('foo') < 0: - gdaltest.post_reason('fail') - print(content) - return 'fail' + assert content.find('foo') >= 0 gdal.GetDriverByName('ISIS3').Delete('/vsimem/out.lbl') - return 'success' - # Test preservation of non-pixel sections -def isis_28(): +def test_isis_28(): gdal.FileFromMemBuffer('/vsimem/in_table', "FOO") gdal.FileFromMemBuffer('/vsimem/in.lbl', """Object = IsisCube @@ -1624,9 +1273,8 @@ def isis_28(): ds = gdal.Open('/vsimem/in.lbl') fl = ds.GetFileList() if fl != ['/vsimem/in.lbl', '/vsimem/in_table']: - gdaltest.post_reason('fail') print(fl) - return 'success' + return ds = None gdal.Translate('/vsimem/in_label.lbl', '/vsimem/in.lbl', format='ISIS3') @@ -1654,11 +1302,9 @@ def isis_28(): if dst_location == 'EXTERNAL': table_filename = lbl['Table_first_table']['^Table'] if table_filename != 'out.Table.first_table': - gdaltest.post_reason('fail') print(src_location) print(dst_location) - print(content) - return 'fail' + pytest.fail(content) f = gdal.VSIFOpenL('/vsimem/' + table_filename, 'rb') table = None @@ -1667,39 +1313,29 @@ def isis_28(): gdal.VSIFCloseL(f) if offset != 0 or size != 3 or size != len(table): - gdaltest.post_reason('fail') print(src_location) print(dst_location) - print(content) - print(table) - return 'fail' + pytest.fail(content) else: if offset + size != len(content): - gdaltest.post_reason('fail') print(src_location) - print(dst_location) - print(content) - return 'fail' + pytest.fail(dst_location) table = content[offset:] if table != 'FOO': - gdaltest.post_reason('fail') print(src_location) print(dst_location) - print(content) - print(table) - return 'fail' + pytest.fail(content) gdal.GetDriverByName('ISIS3').Delete('/vsimem/out.lbl') gdal.GetDriverByName('ISIS3').Delete('/vsimem/in_label.lbl') gdal.GetDriverByName('ISIS3').Delete('/vsimem/in.lbl') - return 'success' # Test complete removal of history -def isis_29(): +def test_isis_29(): with gdaltest.error_handler(): gdal.Translate('/vsimem/in.lbl', 'data/byte.tif', format='ISIS3') @@ -1710,10 +1346,7 @@ def isis_29(): ds = gdal.Open('/vsimem/out.lbl') lbl = ds.GetMetadata_List('json:ISIS3')[0] lbl = json.loads(lbl) - if 'History' in lbl: - gdaltest.post_reason('fail') - print(lbl) - return 'fail' + assert 'History' not in lbl ds = None gdal.GetDriverByName('ISIS3').Delete('/vsimem/out.lbl') @@ -1724,24 +1357,17 @@ def isis_29(): ds = gdal.Open('/vsimem/out.lbl') lbl = ds.GetMetadata_List('json:ISIS3')[0] lbl = json.loads(lbl) - if 'History' in lbl: - gdaltest.post_reason('fail') - print(lbl) - return 'fail' + assert 'History' not in lbl ds = None - if gdal.VSIStatL('/vsimem/out.History.IsisCube') is not None: - gdaltest.post_reason('fail') - return 'fail' + assert gdal.VSIStatL('/vsimem/out.History.IsisCube') is None gdal.GetDriverByName('ISIS3').Delete('/vsimem/out.lbl') gdal.GetDriverByName('ISIS3').Delete('/vsimem/in.lbl') - return 'success' - # Test Fill() on a GeoTIFF file -def isis_30(): +def test_isis_30(): ds = gdal.GetDriverByName('ISIS3').Create('/vsimem/test.lbl', 1, 1, options=['DATA_LOCATION=GEOTIFF']) ds.GetRasterBand(1).Fill(1) @@ -1752,16 +1378,12 @@ def isis_30(): ds = None gdal.GetDriverByName('ISIS3').Delete('/vsimem/test.lbl') - if cs != 1: - print(cs) - return 'fail' - - return 'success' + assert cs == 1 # Test correct working of block caching with a GeoTIFF file -def isis_31(): +def test_isis_31(): gdal.SetConfigOption('GDAL_FORCE_CACHING', 'YES') ds = gdal.GetDriverByName('ISIS3').Create('/vsimem/test.lbl', 1, 1, options=['DATA_LOCATION=GEOTIFF']) @@ -1774,51 +1396,8 @@ def isis_31(): ds = None gdal.GetDriverByName('ISIS3').Delete('/vsimem/test.lbl') - if cs != 1: - print(cs) - return 'fail' - - return 'success' - - -gdaltest_list = [ - isis_1, - isis_2, - isis_3, - isis_4, - isis_5, - isis_6, - isis_7, - isis_8, - isis_9, - isis_10, - isis_11, - isis_12, - isis_13, - isis_14, - isis_15, - isis_16, - isis_17, - isis_18, - isis_19, - isis_20, - isis_21, - isis_22, - isis_23, - isis_24, - isis_25, - isis_26, - isis_27, - isis_28, - isis_29, - isis_30, - isis_31] - - -if __name__ == '__main__': - - gdaltest.setup_run('isis') - - gdaltest.run_tests(gdaltest_list) - - sys.exit(gdaltest.summarize()) + assert cs == 1 + + + + diff --git a/autotest/gdrivers/isis2.py b/autotest/gdrivers/isis2.py index cae8302053ad..9d82e0b53827 100755 --- a/autotest/gdrivers/isis2.py +++ b/autotest/gdrivers/isis2.py @@ -28,9 +28,7 @@ # DEALINGS IN THE SOFTWARE. ############################################################################### -import sys -sys.path.append('../pymod') import gdaltest @@ -39,7 +37,7 @@ # ftp://ftpflag.wr.usgs.gov/dist/pigpen/venus/venustopo_download/ovda_dtm.zip -def isis2_1(): +def test_isis2_1(): tst = gdaltest.GDALTest('ISIS2', 'arvidson_original_truncated.cub', 1, 382) expected_prj = """PROJCS["SIMPLE_CYLINDRICAL VENUS", @@ -62,7 +60,7 @@ def isis2_1(): ############################################################################### # Test simple creation on disk. -def isis2_2(): +def test_isis2_2(): tst = gdaltest.GDALTest('ISIS2', 'byte.tif', 1, 4672) @@ -72,7 +70,7 @@ def isis2_2(): # Test a different data type with some options. -def isis2_3(): +def test_isis2_3(): tst = gdaltest.GDALTest('ISIS2', 'float32.tif', 1, 4672, options=['LABELING_METHOD=DETACHED', 'IMAGE_EXTENSION=qub']) @@ -80,15 +78,4 @@ def isis2_3(): return tst.testCreateCopy(vsimem=1) -gdaltest_list = [ - isis2_1, - isis2_2, - isis2_3] -if __name__ == '__main__': - - gdaltest.setup_run('isis2') - - gdaltest.run_tests(gdaltest_list) - - sys.exit(gdaltest.summarize()) diff --git a/autotest/gdrivers/jdem.py b/autotest/gdrivers/jdem.py index 70ca710954f3..d869b0d715a8 100755 --- a/autotest/gdrivers/jdem.py +++ b/autotest/gdrivers/jdem.py @@ -28,9 +28,7 @@ # DEALINGS IN THE SOFTWARE. ############################################################################### -import sys -sys.path.append('../pymod') import gdaltest @@ -38,19 +36,10 @@ # Test reading a - fake - JDEM dataset -def jdem_1(): +def test_jdem_1(): tst = gdaltest.GDALTest('JDEM', 'fakejdem.mem', 1, 15) return tst.testOpen() -gdaltest_list = [ - jdem_1] -if __name__ == '__main__': - - gdaltest.setup_run('jdem') - - gdaltest.run_tests(gdaltest_list) - - sys.exit(gdaltest.summarize()) diff --git a/autotest/gdrivers/jp2kak.py b/autotest/gdrivers/jp2kak.py index fc724d4a177f..27aff615acc3 100755 --- a/autotest/gdrivers/jp2kak.py +++ b/autotest/gdrivers/jp2kak.py @@ -30,22 +30,21 @@ # DEALINGS IN THE SOFTWARE. ############################################################################### -import sys from osgeo import gdal -sys.path.append('../pymod') import gdaltest +import pytest ############################################################################### # Read test of simple byte reference data. -def jp2kak_1(): +def test_jp2kak_1(): gdaltest.jp2kak_drv = gdal.GetDriverByName('JP2KAK') if gdaltest.jp2kak_drv is None: - return 'skip' + pytest.skip() gdaltest.deregister_all_jpeg2000_drivers_but('JP2KAK') @@ -56,10 +55,10 @@ def jp2kak_1(): # Read test of simple 16bit reference data. -def jp2kak_2(): +def test_jp2kak_2(): if gdaltest.jp2kak_drv is None: - return 'skip' + pytest.skip() tst = gdaltest.GDALTest('JP2KAK', 'int16.jp2', 1, 4587) return tst.testOpen() @@ -68,10 +67,10 @@ def jp2kak_2(): # Test lossless copying. -def jp2kak_3(): +def test_jp2kak_3(): if gdaltest.jp2kak_drv is None: - return 'skip' + pytest.skip() tst = gdaltest.GDALTest('JP2KAK', 'byte.jp2', 1, 50054, options=['QUALITY=100']) @@ -82,10 +81,10 @@ def jp2kak_3(): # Test GeoJP2 production with geotransform. -def jp2kak_4(): +def test_jp2kak_4(): if gdaltest.jp2kak_drv is None: - return 'skip' + pytest.skip() tst = gdaltest.GDALTest('JP2KAK', 'rgbsmall.tif', 0, 0, options=['GMLJP2=OFF']) @@ -96,10 +95,10 @@ def jp2kak_4(): # Test GeoJP2 production with gcps. -def jp2kak_5(): +def test_jp2kak_5(): if gdaltest.jp2kak_drv is None: - return 'skip' + pytest.skip() tst = gdaltest.GDALTest('JP2KAK', 'rgbsmall.tif', 0, 0, options=['GEOJP2=OFF']) @@ -111,10 +110,10 @@ def jp2kak_5(): # -def jp2kak_8(): +def test_jp2kak_8(): if gdaltest.jp2kak_drv is None: - return 'skip' + pytest.skip() tst = gdaltest.GDALTest('JP2KAK', 'byte.jp2', 1, 50054, options=['QUALITY=100']) @@ -127,10 +126,10 @@ def jp2kak_8(): # -def jp2kak_9(): +def test_jp2kak_9(): if gdaltest.jp2kak_drv is None: - return 'skip' + pytest.skip() tst = gdaltest.GDALTest('JP2KAK', 'rgbwcmyk01_YeGeo_kakadu.jp2', 2, 32141) return tst.testOpen() @@ -141,10 +140,10 @@ def jp2kak_9(): # -def jp2kak_10(): +def test_jp2kak_10(): if gdaltest.jp2kak_drv is None: - return 'skip' + pytest.skip() ds = gdal.Open('data/rgbwcmyk01_YeGeo_kakadu.jp2') data = ds.ReadRaster(0, 0, 800, 100, band_list=[2, 3]).decode('latin1') @@ -157,162 +156,128 @@ def jp2kak_10(): for x in range(8): got.append((ord(data[x * 100]), ord(data[80000 + x * 100]))) - if got != expected: - print(got) - gdaltest.post_reason('did not get expected values.') - return 'fail' - - return 'success' + assert got == expected, 'did not get expected values.' ############################################################################### # Test handle of 11bit signed file. # -def jp2kak_11(): +def test_jp2kak_11(): if gdaltest.jp2kak_drv is None: - return 'skip' + pytest.skip() ds = gdal.Open('data/gtsmall_11_int16.jp2') cs = ds.GetRasterBand(1).Checksum() - if cs not in (63475, 63472, 63452, 63471): - gdaltest.post_reason('fail') - print(cs) - return 'fail' - return 'success' + assert cs in (63475, 63472, 63452, 63471) ############################################################################### # Test handle of 10bit unsigned file. # -def jp2kak_12(): +def test_jp2kak_12(): if gdaltest.jp2kak_drv is None: - return 'skip' + pytest.skip() ds = gdal.Open('data/gtsmall_10_uint16.jp2') cs = ds.GetRasterBand(1).Checksum() - if cs != 63360 and cs != 63357 and cs != 63358: - gdaltest.post_reason('fail') - print(cs) - return 'fail' - return 'success' + assert cs == 63360 or cs == 63357 or cs == 63358 ############################################################################### # Test internal overviews. # -def jp2kak_13(): +def test_jp2kak_13(): if gdaltest.jp2kak_drv is None: - return 'skip' + pytest.skip() src_ds = gdal.Open('data/utm.pix') jp2_ds = gdaltest.jp2kak_drv.CreateCopy('tmp/jp2kak_13.jp2', src_ds) src_ds = None jp2_band = jp2_ds.GetRasterBand(1) - if jp2_band.GetOverviewCount() != 1: - gdaltest.post_reason('did not get expected number of overviews on jp2') - return 'fail' + assert jp2_band.GetOverviewCount() == 1, \ + 'did not get expected number of overviews on jp2' ov_band = jp2_band.GetOverview(0) - if ov_band.XSize != 250 or ov_band.YSize != 4: - gdaltest.post_reason('did not get expected overview size.') - return 'fail' + assert ov_band.XSize == 250 and ov_band.YSize == 4, \ + 'did not get expected overview size.' # Note, due to oddities of rounding related to identifying discard # levels the overview is actually generated with no discard levels # and in the debug output we see 500x7 -> 500x7 -> 250x4. checksum = ov_band.Checksum() - if checksum not in (11776, 11736, 11801): - print(checksum) - gdaltest.post_reason('did not get expected overview checksum') - return 'fail' - - return 'success' + assert checksum in (11776, 11736, 11801), 'did not get expected overview checksum' ############################################################################### # Test external overviews. # -def jp2kak_14(): +def test_jp2kak_14(): if gdaltest.jp2kak_drv is None: - return 'skip' + pytest.skip() jp2_ds = gdal.Open('tmp/jp2kak_13.jp2') jp2_ds.BuildOverviews('NEAREST', overviewlist=[2, 4]) jp2_band = jp2_ds.GetRasterBand(1) - if jp2_band.GetOverviewCount() != 2: - gdaltest.post_reason('did not get expected number of overviews on jp2') - return 'fail' + assert jp2_band.GetOverviewCount() == 2, \ + 'did not get expected number of overviews on jp2' ov_band = jp2_band.GetOverview(0) - if ov_band.XSize != 250 or ov_band.YSize != 4: - gdaltest.post_reason('did not get expected overview size.') - return 'fail' + assert ov_band.XSize == 250 and ov_band.YSize == 4, \ + 'did not get expected overview size.' checksum = ov_band.Checksum() - if checksum not in (12288, 12272, 12224): - print(checksum) - gdaltest.post_reason('did not get expected overview checksum') - return 'fail' + assert checksum in (12288, 12272, 12224), 'did not get expected overview checksum' ov_band = jp2_band.GetOverview(1) - if ov_band.XSize != 125 or ov_band.YSize != 2: - gdaltest.post_reason('did not get expected overview size. (2)') - return 'fail' + assert ov_band.XSize == 125 and ov_band.YSize == 2, \ + 'did not get expected overview size. (2)' checksum = ov_band.Checksum() - if checksum not in (2957, 2980, 2990): - print(checksum) - gdaltest.post_reason('did not get expected overview checksum (2)') - return 'fail' + assert checksum in (2957, 2980, 2990), 'did not get expected overview checksum (2)' jp2_ds = None gdaltest.jp2kak_drv.Delete('tmp/jp2kak_13.jp2') - return 'success' - ############################################################################### # Confirm we can read resolution information. # -def jp2kak_15(): +def test_jp2kak_15(): if gdaltest.jp2kak_drv is None: - return 'skip' + pytest.skip() jp2_ds = gdal.Open('data/small_200ppcm.jp2') md = jp2_ds.GetMetadata() - if (md['TIFFTAG_RESOLUTIONUNIT'] != '3 (pixels/cm)' or - md['TIFFTAG_XRESOLUTION'] != '200.012'): - gdaltest.post_reason('did not get expected resolution metadata') - return 'fail' + assert (not (md['TIFFTAG_RESOLUTIONUNIT'] != '3 (pixels/cm)' or + md['TIFFTAG_XRESOLUTION'] != '200.012')), \ + 'did not get expected resolution metadata' jp2_ds = None - return 'success' - ############################################################################### # Confirm we can write and then reread resolution information. # -def jp2kak_16(): +def test_jp2kak_16(): if gdaltest.jp2kak_drv is None: - return 'skip' + pytest.skip() jp2_ds = gdal.Open('data/small_200ppcm.jp2') out_ds = gdaltest.jp2kak_drv.CreateCopy('tmp/jp2kak_16.jp2', jp2_ds) @@ -322,17 +287,14 @@ def jp2kak_16(): jp2_ds = gdal.Open('tmp/jp2kak_16.jp2') md = jp2_ds.GetMetadata() - if (md['TIFFTAG_RESOLUTIONUNIT'] != '3 (pixels/cm)' or - md['TIFFTAG_XRESOLUTION'] != '200.012'): - gdaltest.post_reason('did not get expected resolution metadata') - return 'fail' + assert (not (md['TIFFTAG_RESOLUTIONUNIT'] != '3 (pixels/cm)' or + md['TIFFTAG_XRESOLUTION'] != '200.012')), \ + 'did not get expected resolution metadata' jp2_ds = None gdaltest.jp2kak_drv.Delete('tmp/jp2kak_16.jp2') - return 'success' - ############################################################################### # Test reading a file with axis orientation set properly for an alternate # axis order coordinate system (urn:...:EPSG::4326). @@ -342,10 +304,10 @@ def jp2kak_16(): # This test case was adapted from the "jp2kak_7()" case above. -def jp2kak_17(): +def test_jp2kak_17(): if gdaltest.jp2kak_drv is None: - return 'skip' + pytest.skip() gdal.SetConfigOption('GDAL_JP2K_ALT_OFFSETVECTOR_ORDER', 'YES') @@ -361,25 +323,22 @@ def jp2kak_17(): abs(gt[2] - gte[2]) > 0.000000000005 or abs(gt[4] - gte[4]) > 0.000000000005 or abs(gt[5] - gte[5]) > 0.000000000005): - gdaltest.post_reason('did not get expected geotransform') print('got: ', gt) gdal.SetConfigOption('GDAL_JP2K_ALT_OFFSETVECTOR_ORDER', 'NO') - return 'fail' + pytest.fail('did not get expected geotransform') ds = None gdal.SetConfigOption('GDAL_JP2K_ALT_OFFSETVECTOR_ORDER', 'NO') - return 'success' - ############################################################################### # Test lossless copying of Int16 -def jp2kak_18(): +def test_jp2kak_18(): if gdaltest.jp2kak_drv is None: - return 'skip' + pytest.skip() tst = gdaltest.GDALTest('JP2KAK', 'int16.tif', 1, 4672, options=['QUALITY=100']) @@ -390,10 +349,10 @@ def jp2kak_18(): # Test lossless copying of UInt16 -def jp2kak_19(): +def test_jp2kak_19(): if gdaltest.jp2kak_drv is None: - return 'skip' + pytest.skip() tst = gdaltest.GDALTest('JP2KAK', '../gcore/data/uint16.tif', 1, 4672, options=['QUALITY=100'], filename_absolute=1) @@ -404,20 +363,16 @@ def jp2kak_19(): # Test auto-promotion of 1bit alpha band to 8bit -def jp2kak_20(): +def test_jp2kak_20(): if gdaltest.jp2kak_drv is None: - return 'skip' + pytest.skip() ds = gdal.Open('data/stefan_full_rgba_alpha_1bit.jp2') fourth_band = ds.GetRasterBand(4) - if fourth_band.GetMetadataItem('NBITS', 'IMAGE_STRUCTURE') is not None: - return 'fail' + assert fourth_band.GetMetadataItem('NBITS', 'IMAGE_STRUCTURE') is None got_cs = fourth_band.Checksum() - if got_cs != 8527: - gdaltest.post_reason('fail') - print(got_cs) - return 'fail' + assert got_cs == 8527 jp2_bands_data = ds.ReadRaster(0, 0, ds.RasterXSize, ds.RasterYSize) # jp2_fourth_band_data = fourth_band.ReadRaster( # 0, 0, ds.RasterXSize, ds.RasterYSize) @@ -436,14 +391,9 @@ def jp2kak_20(): # ds.RasterXSize/16, ds.RasterYSize/16) tmp_ds = None tiff_drv.Delete('/vsimem/jp2kak_20.tif') - if got_cs != 8527: - gdaltest.post_reason('fail') - print(got_cs) - return 'fail' + assert got_cs == 8527 - if jp2_bands_data != gtiff_bands_data: - gdaltest.post_reason('fail') - return 'fail' + assert jp2_bands_data == gtiff_bands_data # if jp2_fourth_band_data != gtiff_fourth_band_data: # gdaltest.post_reason('fail') @@ -452,20 +402,16 @@ def jp2kak_20(): ds = gdal.OpenEx('data/stefan_full_rgba_alpha_1bit.jp2', open_options=['1BIT_ALPHA_PROMOTION=NO']) fourth_band = ds.GetRasterBand(4) - if fourth_band.GetMetadataItem('NBITS', 'IMAGE_STRUCTURE') != '1': - gdaltest.post_reason('fail') - return 'fail' - - return 'success' + assert fourth_band.GetMetadataItem('NBITS', 'IMAGE_STRUCTURE') == '1' ############################################################################### # Test non nearest upsampling -def jp2kak_21(): +def test_jp2kak_21(): if gdaltest.jp2kak_drv is None: - return 'skip' + pytest.skip() tmp_ds = gdaltest.jp2kak_drv.CreateCopy( '/vsimem/jp2kak_21.jp2', @@ -488,22 +434,16 @@ def jp2kak_21(): ref_cs = mem_ds.GetRasterBand(1).Checksum() mem_ds.GetRasterBand(1).WriteRaster(0, 0, 40, 40, upsampled_data) cs = mem_ds.GetRasterBand(1).Checksum() - if cs != ref_cs: - gdaltest.post_reason('fail') - print(cs) - print(ref_cs) - return 'fail' - - return 'success' + assert cs == ref_cs ############################################################################### # Test RGBA datasets -def jp2kak_22(): +def test_jp2kak_22(): if gdaltest.jp2kak_drv is None: - return 'skip' + pytest.skip() src_ds = gdal.Open('../gcore/data/stefan_full_rgba.tif') gdaltest.jp2kak_drv.CreateCopy('/vsimem/jp2kak_22.jp2', src_ds, options=['QUALITY=100']) @@ -511,60 +451,20 @@ def jp2kak_22(): for i in range(4): ref_cs = src_ds.GetRasterBand(1).Checksum() cs = ds.GetRasterBand(1).Checksum() - if ref_cs != cs: - gdaltest.post_reason('fail') - print(i) - print(cs) - print(ref_cs) - return 'fail' - if src_ds.GetRasterBand(1).GetColorInterpretation() != ds.GetRasterBand(1).GetColorInterpretation(): - gdaltest.post_reason('fail') - print(i) - return 'fail' + assert ref_cs == cs, i + assert src_ds.GetRasterBand(1).GetColorInterpretation() == ds.GetRasterBand(1).GetColorInterpretation(), \ + i ds = None gdal.Unlink('/vsimem/jp2kak_22.jp2') - return 'success' - ############################################################################### # Cleanup. -def jp2kak_cleanup(): +def test_jp2kak_cleanup(): gdaltest.reregister_all_jpeg2000_drivers() - return 'success' - - -gdaltest_list = [ - jp2kak_1, - jp2kak_2, - jp2kak_3, - jp2kak_4, - jp2kak_5, - jp2kak_8, - jp2kak_9, - jp2kak_10, - jp2kak_11, - jp2kak_12, - jp2kak_13, - jp2kak_14, - jp2kak_15, - jp2kak_16, - jp2kak_17, - jp2kak_18, - jp2kak_19, - jp2kak_20, - jp2kak_21, - jp2kak_22, - jp2kak_cleanup] - -if __name__ == '__main__': - - gdaltest.setup_run('jp2kak') - - gdaltest.run_tests(gdaltest_list) - - sys.exit(gdaltest.summarize()) + + diff --git a/autotest/gdrivers/jp2lura.py b/autotest/gdrivers/jp2lura.py index 1fccd804103b..da332d9ea5a9 100755 --- a/autotest/gdrivers/jp2lura.py +++ b/autotest/gdrivers/jp2lura.py @@ -36,8 +36,8 @@ from osgeo import gdal from osgeo import ogr from osgeo import osr +import pytest -sys.path.append('../pymod') sys.path.append('../../gdal/swig/python/samples') import gdaltest @@ -46,37 +46,34 @@ # Verify we have the driver. -def jp2lura_1(): +def test_jp2lura_1(): gdaltest.jp2lura_drv = gdal.GetDriverByName('JP2Lura') if gdaltest.jp2lura_drv is None: - return 'skip' + pytest.skip() if gdaltest.jp2lura_drv is not None: if gdal.GetConfigOption('LURA_LICENSE_NUM_1') is None or \ gdal.GetConfigOption('LURA_LICENSE_NUM_2') is None: - print('Driver JP2Lura is registered, but missing LURA_LICENSE_NUM_1 and LURA_LICENSE_NUM_2') gdaltest.jp2lura_drv = None - return 'skip' + pytest.skip('Driver JP2Lura is registered, but missing LURA_LICENSE_NUM_1 and LURA_LICENSE_NUM_2') gdaltest.deregister_all_jpeg2000_drivers_but('JP2Lura') ds = gdal.Open('data/byte.jp2') if ds is None and gdal.GetLastErrorMsg().find('license') >= 0: - print('Driver JP2Lura is registered, but issue with license') gdaltest.jp2lura_drv = None - return 'skip' - - return 'success' + pytest.skip('Driver JP2Lura is registered, but issue with license') + ############################################################################### # -def jp2lura_missing_license_num(): +def test_jp2lura_missing_license_num(): if gdaltest.jp2lura_drv is None: - return 'skip' + pytest.skip() old_num_1 = gdal.GetConfigOption('LURA_LICENSE_NUM_1') old_num_2 = gdal.GetConfigOption('LURA_LICENSE_NUM_2') @@ -87,19 +84,16 @@ def jp2lura_missing_license_num(): gdal.SetConfigOption('LURA_LICENSE_NUM_1', old_num_1) gdal.SetConfigOption('LURA_LICENSE_NUM_2', old_num_2) - if ds is not None: - return 'fail' - - return 'success' + assert ds is None ############################################################################### # -def jp2lura_invalid_license_num(): +def test_jp2lura_invalid_license_num(): if gdaltest.jp2lura_drv is None: - return 'skip' + pytest.skip() old_num_1 = gdal.GetConfigOption('LURA_LICENSE_NUM_1') old_num_2 = gdal.GetConfigOption('LURA_LICENSE_NUM_2') @@ -110,10 +104,7 @@ def jp2lura_invalid_license_num(): gdal.SetConfigOption('LURA_LICENSE_NUM_1', old_num_1) gdal.SetConfigOption('LURA_LICENSE_NUM_2', old_num_2) - if ds is not None: - return 'fail' - - return 'success' + assert ds is None ############################################################################### @@ -123,8 +114,7 @@ def validate(filename, expected_gmljp2=True, return_error_count=False, oidoc=Non try: import validate_jp2 except ImportError: - print('Cannot run validate_jp2') - return 'skip' + pytest.skip('Cannot run validate_jp2') try: os.stat('tmp/cache/SCHEMAS_OPENGIS_NET') @@ -145,17 +135,17 @@ def validate(filename, expected_gmljp2=True, return_error_count=False, oidoc=Non if return_error_count: return (res.error_count, res.warning_count) if res.error_count == 0 and res.warning_count == 0: - return 'success' - return 'fail' + return + pytest.fail() ############################################################################### # Open byte.jp2 -def jp2lura_2(): +def test_jp2lura_2(): if gdaltest.jp2lura_drv is None: - return 'skip' + pytest.skip() srs = """PROJCS["NAD27 / UTM zone 11N", GEOGCS["NAD27", @@ -185,10 +175,10 @@ def jp2lura_2(): # Open int16.jp2 -def jp2lura_3(): +def test_jp2lura_3(): if gdaltest.jp2lura_drv is None: - return 'skip' + pytest.skip() ds = gdal.Open('data/int16.jp2') ds_ref = gdal.Open('data/int16.tif') @@ -201,25 +191,19 @@ def jp2lura_3(): ds_ref = None # Quite a bit of difference... - if maxdiff > 6: - gdaltest.post_reason('Image too different from reference') - return 'fail' + assert maxdiff <= 6, 'Image too different from reference' ds = ogr.Open('data/int16.jp2') - if ds is not None: - gdaltest.post_reason('fail') - return 'fail' - - return 'success' + assert ds is None ############################################################################### # Test copying byte.jp2 -def jp2lura_4(out_filename='tmp/jp2lura_4.jp2'): +def test_jp2lura_4(out_filename='tmp/jp2lura_4.jp2'): if gdaltest.jp2lura_drv is None: - return 'skip' + pytest.skip() src_ds = gdal.Open('data/byte.jp2') src_wkt = src_ds.GetProjectionRef() @@ -238,13 +222,9 @@ def jp2lura_4(out_filename='tmp/jp2lura_4.jp2'): vrt_ds = None gdal.Unlink('/vsimem/jp2lura_4.vrt') - if gdal.VSIStatL(out_filename + '.aux.xml') is not None: - gdaltest.post_reason('fail') - return 'fail' + assert gdal.VSIStatL(out_filename + '.aux.xml') is None - if validate(out_filename, inspire_tg=False) == 'fail': - gdaltest.post_reason('fail') - return 'fail' + assert validate(out_filename, inspire_tg=False) != 'fail' ds = gdal.Open(out_filename) cs = ds.GetRasterBand(1).Checksum() @@ -257,12 +237,8 @@ def jp2lura_4(out_filename='tmp/jp2lura_4.jp2'): gdal.Unlink(out_filename) - if xres != '300' or yres != '200' or resunit != '3 (pixels/cm)': - gdaltest.post_reason('bad resolution') - print(xres) - print(yres) - print(resunit) - return 'fail' + assert xres == '300' and yres == '200' and resunit == '3 (pixels/cm)', \ + 'bad resolution' sr1 = osr.SpatialReference() sr1.SetFromUserInput(got_wkt) @@ -270,37 +246,27 @@ def jp2lura_4(out_filename='tmp/jp2lura_4.jp2'): sr2.SetFromUserInput(src_wkt) if sr1.IsSame(sr2) == 0: - gdaltest.post_reason('bad spatial reference') print(got_wkt) print(src_wkt) - return 'fail' + pytest.fail('bad spatial reference') for i in range(6): - if abs(got_gt[i] - src_gt[i]) > 1e-8: - gdaltest.post_reason('bad geotransform') - print(got_gt) - print(src_gt) - return 'fail' - - if cs != 50054: - gdaltest.post_reason('bad checksum') - print(cs) - return 'fail' + assert abs(got_gt[i] - src_gt[i]) <= 1e-8, 'bad geotransform' - return 'success' + assert cs == 50054, 'bad checksum' -def jp2lura_4_vsimem(): - return jp2lura_4('/vsimem/jp2lura_4.jp2') +def test_jp2lura_4_vsimem(): + return test_jp2lura_4('/vsimem/jp2lura_4.jp2') ############################################################################### # Test copying int16.jp2 -def jp2lura_5(): +def test_jp2lura_5(): if gdaltest.jp2lura_drv is None: - return 'skip' + pytest.skip() tst = gdaltest.GDALTest('JP2Lura', 'int16.jp2', 1, None, options=['REVERSIBLE=YES', 'CODEC=J2K']) return tst.testCreateCopy() @@ -309,30 +275,27 @@ def jp2lura_5(): # Test reading ll.jp2 -def jp2lura_6(): +def test_jp2lura_6(): if gdaltest.jp2lura_drv is None: - return 'skip' + pytest.skip() tst = gdaltest.GDALTest('JP2Lura', 'll.jp2', 1, None) - if tst.testOpen() != 'success': - return 'fail' + tst.testOpen() ds = gdal.Open('data/ll.jp2') ds.GetRasterBand(1).Checksum() ds = None - return 'success' - ############################################################################### # Open byte.jp2.gz (test use of the VSIL API) -def jp2lura_7(): +def test_jp2lura_7(): if gdaltest.jp2lura_drv is None: - return 'skip' + pytest.skip() tst = gdaltest.GDALTest('JP2Lura', '/vsigzip/data/byte.jp2.gz', 1, 50054, filename_absolute=1) return tst.testOpen() @@ -341,52 +304,38 @@ def jp2lura_7(): # Test a JP2Lura with the 3 bands having 13bit depth and the 4th one 1 bit -def jp2lura_8(): +def test_jp2lura_8(): if gdaltest.jp2lura_drv is None: - return 'skip' + pytest.skip() ds = gdal.Open('data/3_13bit_and_1bit.jp2') expected_checksums = [64570, 57277, 56048] # 61292] for i, csum in enumerate(expected_checksums): - if ds.GetRasterBand(i + 1).Checksum() != csum: - gdaltest.post_reason('unexpected checksum (%d) for band %d' % (csum, i + 1)) - return 'fail' - - if ds.GetRasterBand(1).DataType != gdal.GDT_UInt16: - gdaltest.post_reason('unexpected data type') - return 'fail' + assert ds.GetRasterBand(i + 1).Checksum() == csum, \ + ('unexpected checksum (%d) for band %d' % (csum, i + 1)) - return 'success' + assert ds.GetRasterBand(1).DataType == gdal.GDT_UInt16, 'unexpected data type' ############################################################################### # Check that we can use .j2w world files (#4651) -def jp2lura_9(): +def test_jp2lura_9(): if gdaltest.jp2lura_drv is None: - return 'skip' + pytest.skip() ds = gdal.Open('data/byte_without_geotransform.jp2') geotransform = ds.GetGeoTransform() - if abs(geotransform[0] - 440720) > 0.1 \ - or abs(geotransform[1] - 60) > 0.001 \ - or abs(geotransform[2] - 0) > 0.001 \ - or abs(geotransform[3] - 3751320) > 0.1 \ - or abs(geotransform[4] - 0) > 0.001 \ - or abs(geotransform[5] - -60) > 0.001: - print(geotransform) - gdaltest.post_reason('geotransform differs from expected') - return 'fail' + assert abs(geotransform[0] - 440720) <= 0.1 and abs(geotransform[1] - 60) <= 0.001 and abs(geotransform[2] - 0) <= 0.001 and abs(geotransform[3] - 3751320) <= 0.1 and abs(geotransform[4] - 0) <= 0.001 and abs(geotransform[5] - -60) <= 0.001, \ + 'geotransform differs from expected' ds = None - return 'success' - ############################################################################### # Test YCBCR420 creation option @@ -394,30 +343,20 @@ def jp2lura_9(): def DISABLED_jp2lura_10(): if gdaltest.jp2lura_drv is None: - return 'skip' + pytest.skip() src_ds = gdal.Open('data/rgbsmall.tif') out_ds = gdaltest.jp2lura_drv.CreateCopy('/vsimem/jp2lura_10.jp2', src_ds, options=['YCBCR420=YES', 'RESOLUTIONS=3']) maxdiff = gdaltest.compare_ds(src_ds, out_ds) - if out_ds.GetRasterBand(1).GetColorInterpretation() != gdal.GCI_RedBand: - gdaltest.post_reason('fail') - return 'fail' - if out_ds.GetRasterBand(2).GetColorInterpretation() != gdal.GCI_GreenBand: - gdaltest.post_reason('fail') - return 'fail' - if out_ds.GetRasterBand(3).GetColorInterpretation() != gdal.GCI_BlueBand: - gdaltest.post_reason('fail') - return 'fail' + assert out_ds.GetRasterBand(1).GetColorInterpretation() == gdal.GCI_RedBand + assert out_ds.GetRasterBand(2).GetColorInterpretation() == gdal.GCI_GreenBand + assert out_ds.GetRasterBand(3).GetColorInterpretation() == gdal.GCI_BlueBand del out_ds src_ds = None gdal.Unlink('/vsimem/jp2lura_10.jp2') # Quite a bit of difference... - if maxdiff > 12: - gdaltest.post_reason('Image too different from reference') - return 'fail' - - return 'success' + assert maxdiff <= 12, 'Image too different from reference' ############################################################################### # Test auto-promotion of 1bit alpha band to 8bit @@ -426,18 +365,13 @@ def DISABLED_jp2lura_10(): def DISABLED_jp2lura_11(): if gdaltest.jp2lura_drv is None: - return 'skip' + pytest.skip() ds = gdal.Open('data/stefan_full_rgba_alpha_1bit.jp2') fourth_band = ds.GetRasterBand(4) - if fourth_band.GetMetadataItem('NBITS', 'IMAGE_STRUCTURE') is not None: - gdaltest.post_reason('fail') - return 'fail' + assert fourth_band.GetMetadataItem('NBITS', 'IMAGE_STRUCTURE') is None got_cs = fourth_band.Checksum() - if got_cs != 8527: - gdaltest.post_reason('fail') - print(got_cs) - return 'fail' + assert got_cs == 8527 jp2_bands_data = ds.ReadRaster(0, 0, ds.RasterXSize, ds.RasterYSize) jp2_fourth_band_data = fourth_band.ReadRaster(0, 0, ds.RasterXSize, ds.RasterYSize) fourth_band.ReadRaster(0, 0, ds.RasterXSize, ds.RasterYSize, int(ds.RasterXSize / 16), int(ds.RasterYSize / 16)) @@ -450,35 +384,24 @@ def DISABLED_jp2lura_11(): # gtiff_fourth_band_subsampled_data = fourth_band.ReadRaster(0,0,ds.RasterXSize,ds.RasterYSize,ds.RasterXSize/16,ds.RasterYSize/16) tmp_ds = None gdal.GetDriverByName('GTiff').Delete('/vsimem/jp2lura_11.tif') - if got_cs != 8527: - gdaltest.post_reason('fail') - print(got_cs) - return 'fail' + assert got_cs == 8527 - if jp2_bands_data != gtiff_bands_data: - gdaltest.post_reason('fail') - return 'fail' + assert jp2_bands_data == gtiff_bands_data - if jp2_fourth_band_data != gtiff_fourth_band_data: - gdaltest.post_reason('fail') - return 'fail' + assert jp2_fourth_band_data == gtiff_fourth_band_data ds = gdal.OpenEx('data/stefan_full_rgba_alpha_1bit.jp2', open_options=['1BIT_ALPHA_PROMOTION=NO']) fourth_band = ds.GetRasterBand(4) - if fourth_band.GetMetadataItem('NBITS', 'IMAGE_STRUCTURE') != '1': - gdaltest.post_reason('fail') - return 'fail' - - return 'success' + assert fourth_band.GetMetadataItem('NBITS', 'IMAGE_STRUCTURE') == '1' ############################################################################### # Check that PAM overrides internal georeferencing (#5279) -def jp2lura_12(): +def test_jp2lura_12(): if gdaltest.jp2lura_drv is None: - return 'skip' + pytest.skip() # Override projection shutil.copy('data/byte.jp2', 'tmp/jp2lura_12.jp2') @@ -495,10 +418,7 @@ def jp2lura_12(): gdaltest.jp2lura_drv.Delete('tmp/jp2lura_12.jp2') - if wkt.find('32631') < 0: - gdaltest.post_reason('fail') - print(wkt) - return 'fail' + assert wkt.find('32631') >= 0 # Override geotransform shutil.copy('data/byte.jp2', 'tmp/jp2lura_12.jp2') @@ -513,21 +433,16 @@ def jp2lura_12(): gdaltest.jp2lura_drv.Delete('tmp/jp2lura_12.jp2') - if gt != (1000, 1, 0, 2000, 0, -1): - gdaltest.post_reason('fail') - print(gt) - return 'fail' - - return 'success' + assert gt == (1000, 1, 0, 2000, 0, -1) ############################################################################### # Check that PAM overrides internal GCPs (#5279) -def jp2lura_13(): +def test_jp2lura_13(): if gdaltest.jp2lura_drv is None: - return 'skip' + pytest.skip() # Create a dataset with GCPs src_ds = gdal.Open('data/rgb_gcp.vrt') @@ -535,24 +450,15 @@ def jp2lura_13(): ds = None src_ds = None - if gdal.VSIStatL('tmp/jp2lura_13.jp2.aux.xml') is not None: - gdaltest.post_reason('fail') - return 'fail' + assert gdal.VSIStatL('tmp/jp2lura_13.jp2.aux.xml') is None ds = gdal.Open('tmp/jp2lura_13.jp2') count = ds.GetGCPCount() gcps = ds.GetGCPs() wkt = ds.GetGCPProjection() - if count != 4: - gdaltest.post_reason('fail') - return 'fail' - if len(gcps) != 4: - gdaltest.post_reason('fail') - return 'fail' - if wkt.find('4326') < 0: - gdaltest.post_reason('fail') - print(wkt) - return 'fail' + assert count == 4 + assert len(gcps) == 4 + assert wkt.find('4326') >= 0 ds = None # Override GCP @@ -571,57 +477,40 @@ def jp2lura_13(): gdaltest.jp2lura_drv.Delete('tmp/jp2lura_13.jp2') - if count != 1: - gdaltest.post_reason('fail') - return 'fail' - if len(gcps) != 1: - gdaltest.post_reason('fail') - return 'fail' - if wkt.find('32631') < 0: - gdaltest.post_reason('fail') - print(wkt) - return 'fail' - - return 'success' + assert count == 1 + assert len(gcps) == 1 + assert wkt.find('32631') >= 0 ############################################################################### # Check that we get GCPs even there's no projection info -def jp2lura_14(): +def test_jp2lura_14(): if gdaltest.jp2lura_drv is None: - return 'skip' + pytest.skip() ds = gdal.Open('data/byte_2gcps.jp2') - if ds.GetGCPCount() != 2: - gdaltest.post_reason('fail') - return 'fail' - - return 'success' + assert ds.GetGCPCount() == 2 ############################################################################### # Test reading PixelIsPoint file (#5437) -def jp2lura_16(): +def test_jp2lura_16(): if gdaltest.jp2lura_drv is None: - return 'skip' + pytest.skip() ds = gdal.Open('data/byte_point.jp2') gt = ds.GetGeoTransform() - if ds.GetMetadataItem('AREA_OR_POINT') != 'Point': - gdaltest.post_reason('did not get AREA_OR_POINT = Point') - return 'fail' + assert ds.GetMetadataItem('AREA_OR_POINT') == 'Point', \ + 'did not get AREA_OR_POINT = Point' ds = None 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') @@ -633,58 +522,46 @@ def jp2lura_16(): 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' - - return 'success' + assert gt == gt_expected, \ + 'did not get expected geotransform with GTIFF_POINT_GEO_IGNORE TRUE' ############################################################################### # Test writing PixelIsPoint file (#5437) -def jp2lura_17(): +def test_jp2lura_17(): if gdaltest.jp2lura_drv is None: - return 'skip' + pytest.skip() src_ds = gdal.Open('data/byte_point.jp2') ds = gdaltest.jp2lura_drv.CreateCopy('/vsimem/jp2lura_17.jp2', src_ds) ds = None src_ds = None - if gdal.VSIStatL('/vsimem/jp2lura_17.jp2.aux.xml') is not None: - gdaltest.post_reason('fail') - return 'fail' + assert gdal.VSIStatL('/vsimem/jp2lura_17.jp2.aux.xml') is None ds = gdal.Open('/vsimem/jp2lura_17.jp2') gt = ds.GetGeoTransform() - if ds.GetMetadataItem('AREA_OR_POINT') != 'Point': - gdaltest.post_reason('did not get AREA_OR_POINT = Point') - return 'fail' + assert ds.GetMetadataItem('AREA_OR_POINT') == 'Point', \ + 'did not get AREA_OR_POINT = Point' ds = None 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.Unlink('/vsimem/jp2lura_17.jp2') - return 'success' - ############################################################################### # Test when using the decode_area API when one dimension of the dataset is not a # multiple of 1024 (#5480) -def jp2lura_18(): +def test_jp2lura_18(): if gdaltest.jp2lura_drv is None: - return 'skip' + pytest.skip() src_ds = gdal.GetDriverByName('Mem').Create('', 2000, 2000) ds = gdaltest.jp2lura_drv.CreateCopy('/vsimem/jp2lura_18.jp2', src_ds, options=['TILEXSIZE=2000', 'TILEYSIZE=2000']) @@ -693,48 +570,39 @@ def jp2lura_18(): ds = gdal.Open('/vsimem/jp2lura_18.jp2') ds.GetRasterBand(1).Checksum() - if gdal.GetLastErrorMsg() != '': - gdaltest.post_reason('fail') - return 'fail' + assert gdal.GetLastErrorMsg() == '' ds = None gdal.Unlink('/vsimem/jp2lura_18.jp2') - return 'success' - ############################################################################### # Test reading file where GMLJP2 has nul character instead of \n (#5760) -def jp2lura_19(): +def test_jp2lura_19(): if gdaltest.jp2lura_drv is None: - return 'skip' + pytest.skip() ds = gdal.Open('data/byte_gmljp2_with_nul_car.jp2') - if ds.GetProjectionRef() == '': - gdaltest.post_reason('fail') - return 'fail' + assert ds.GetProjectionRef() != '' ds = None - return 'success' - ############################################################################### # Validate GMLJP2 content against schema -def jp2lura_20(): +def test_jp2lura_20(): if gdaltest.jp2lura_drv is None: - return 'skip' + pytest.skip() try: import xmlvalidate except ImportError: - print('Cannot import xmlvalidate') import traceback traceback.print_exc(file=sys.stdout) - return 'skip' + pytest.skip('Cannot import xmlvalidate') try: os.stat('tmp/cache/SCHEMAS_OPENGIS_NET.zip') @@ -745,8 +613,7 @@ def jp2lura_20(): except OSError: url = 'http://schemas.opengis.net/SCHEMAS_OPENGIS_NET.zip' if not gdaltest.download_file(url, 'SCHEMAS_OPENGIS_NET.zip', force_download=True, max_download_duration=20): - print('Cannot get SCHEMAS_OPENGIS_NET.zip') - return 'skip' + pytest.skip('Cannot get SCHEMAS_OPENGIS_NET.zip') try: os.mkdir('tmp/cache/SCHEMAS_OPENGIS_NET') @@ -765,8 +632,7 @@ def jp2lura_20(): if not gdaltest.download_file(xlink_xsd_url, 'SCHEMAS_OPENGIS_NET/xlink.xsd', force_download=True, max_download_duration=10): xlink_xsd_url = 'http://even.rouault.free.fr/xlink.xsd' if not gdaltest.download_file(xlink_xsd_url, 'SCHEMAS_OPENGIS_NET/xlink.xsd', force_download=True, max_download_duration=10): - print('Cannot get xlink.xsd') - return 'skip' + pytest.skip('Cannot get xlink.xsd') try: os.stat('tmp/cache/SCHEMAS_OPENGIS_NET/xml.xsd') @@ -775,8 +641,7 @@ def jp2lura_20(): if not gdaltest.download_file(xlink_xsd_url, 'SCHEMAS_OPENGIS_NET/xml.xsd', force_download=True, max_download_duration=10): xlink_xsd_url = 'http://even.rouault.free.fr/xml.xsd' if not gdaltest.download_file(xlink_xsd_url, 'SCHEMAS_OPENGIS_NET/xml.xsd', force_download=True, max_download_duration=10): - print('Cannot get xml.xsd') - return 'skip' + pytest.skip('Cannot get xml.xsd') xmlvalidate.transform_abs_links_to_ref_links('tmp/cache/SCHEMAS_OPENGIS_NET') @@ -786,19 +651,16 @@ def jp2lura_20(): ds = None gdal.Unlink('/vsimem/jp2lura_20.jp2') - if not xmlvalidate.validate(gmljp2, ogc_schemas_location='tmp/cache/SCHEMAS_OPENGIS_NET'): - return 'fail' - - return 'success' + assert xmlvalidate.validate(gmljp2, ogc_schemas_location='tmp/cache/SCHEMAS_OPENGIS_NET') ############################################################################### # Test RGBA support -def jp2lura_22(): +def test_jp2lura_22(): if gdaltest.jp2lura_drv is None: - return 'skip' + pytest.skip() # RGBA src_ds = gdal.Open('../gcore/data/stefan_full_rgba.tif') @@ -806,33 +668,19 @@ def jp2lura_22(): maxdiff = gdaltest.compare_ds(src_ds, out_ds) del out_ds src_ds = None - if gdal.VSIStatL('/vsimem/jp2lura_22.jp2.aux.xml') is not None: - gdaltest.post_reason('fail') - return 'fail' + assert gdal.VSIStatL('/vsimem/jp2lura_22.jp2.aux.xml') is None ds = gdal.Open('/vsimem/jp2lura_22.jp2') - 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_BlueBand: - gdaltest.post_reason('fail') - return 'fail' - if ds.GetRasterBand(4).GetColorInterpretation() != gdal.GCI_AlphaBand: - 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_BlueBand + assert ds.GetRasterBand(4).GetColorInterpretation() == gdal.GCI_AlphaBand ds = None - if validate('/vsimem/jp2lura_22.jp2', expected_gmljp2=False, inspire_tg=False) == 'fail': - gdaltest.post_reason('fail') - return 'fail' + assert validate('/vsimem/jp2lura_22.jp2', expected_gmljp2=False, inspire_tg=False) != 'fail' gdal.Unlink('/vsimem/jp2lura_22.jp2') - if maxdiff > 0: - gdaltest.post_reason('Image too different from reference') - return 'fail' + assert maxdiff <= 0, 'Image too different from reference' if False: # pylint: disable=using-constant-test # RGBA with 1BIT_ALPHA=YES @@ -840,20 +688,13 @@ def jp2lura_22(): out_ds = gdaltest.jp2lura_drv.CreateCopy('/vsimem/jp2lura_22.jp2', src_ds, options=['1BIT_ALPHA=YES']) del out_ds src_ds = None - if gdal.VSIStatL('/vsimem/jp2lura_22.jp2.aux.xml') is not None: - gdaltest.post_reason('fail') - return 'fail' + assert gdal.VSIStatL('/vsimem/jp2lura_22.jp2.aux.xml') is None ds = gdal.OpenEx('/vsimem/jp2lura_22.jp2', open_options=['1BIT_ALPHA_PROMOTION=NO']) fourth_band = ds.GetRasterBand(4) - if fourth_band.GetMetadataItem('NBITS', 'IMAGE_STRUCTURE') != '1': - gdaltest.post_reason('fail') - return 'fail' + assert fourth_band.GetMetadataItem('NBITS', 'IMAGE_STRUCTURE') == '1' ds = None ds = gdal.Open('/vsimem/jp2lura_22.jp2') - if ds.GetRasterBand(4).Checksum() != 23120: - gdaltest.post_reason('fail') - print(ds.GetRasterBand(4).Checksum()) - return 'fail' + assert ds.GetRasterBand(4).Checksum() == 23120 ds = None gdal.Unlink('/vsimem/jp2lura_22.jp2') @@ -862,26 +703,13 @@ def jp2lura_22(): out_ds = gdaltest.jp2lura_drv.CreateCopy('/vsimem/jp2lura_22.jp2', src_ds, options=['YCBCR420=YES']) del out_ds src_ds = None - if gdal.VSIStatL('/vsimem/jp2lura_22.jp2.aux.xml') is not None: - gdaltest.post_reason('fail') - return 'fail' + assert gdal.VSIStatL('/vsimem/jp2lura_22.jp2.aux.xml') is None ds = gdal.Open('/vsimem/jp2lura_22.jp2') - 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_BlueBand: - gdaltest.post_reason('fail') - return 'fail' - if ds.GetRasterBand(4).GetColorInterpretation() != gdal.GCI_AlphaBand: - gdaltest.post_reason('fail') - return 'fail' - if ds.GetRasterBand(1).Checksum() != 11457: - gdaltest.post_reason('fail') - print(ds.GetRasterBand(1).Checksum()) - 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_BlueBand + assert ds.GetRasterBand(4).GetColorInterpretation() == gdal.GCI_AlphaBand + assert ds.GetRasterBand(1).Checksum() == 11457 ds = None gdal.Unlink('/vsimem/jp2lura_22.jp2') @@ -892,14 +720,10 @@ def jp2lura_22(): maxdiff = gdaltest.compare_ds(src_ds, out_ds) del out_ds src_ds = None - if gdal.VSIStatL('/vsimem/jp2lura_22.jp2.aux.xml') is not None: - gdaltest.post_reason('fail') - return 'fail' + assert gdal.VSIStatL('/vsimem/jp2lura_22.jp2.aux.xml') is None gdal.Unlink('/vsimem/jp2lura_22.jp2') - if maxdiff > 0: - gdaltest.post_reason('Image too different from reference') - return 'fail' + assert maxdiff <= 0, 'Image too different from reference' # RGB,undefined src_ds = gdal.Open('../gcore/data/stefan_full_rgba_photometric_rgb.tif') @@ -907,28 +731,16 @@ def jp2lura_22(): maxdiff = gdaltest.compare_ds(src_ds, out_ds) del out_ds src_ds = None - if gdal.VSIStatL('/vsimem/jp2lura_22.jp2.aux.xml') is not None: - gdaltest.post_reason('fail') - return 'fail' + assert gdal.VSIStatL('/vsimem/jp2lura_22.jp2.aux.xml') is None ds = gdal.Open('/vsimem/jp2lura_22.jp2') - 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_BlueBand: - gdaltest.post_reason('fail') - return 'fail' - if ds.GetRasterBand(4).GetColorInterpretation() != gdal.GCI_Undefined: - 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_BlueBand + assert ds.GetRasterBand(4).GetColorInterpretation() == gdal.GCI_Undefined ds = None gdal.Unlink('/vsimem/jp2lura_22.jp2') - if maxdiff > 0: - gdaltest.post_reason('Image too different from reference') - return 'fail' + assert maxdiff <= 0, 'Image too different from reference' # RGB,undefined with ALPHA=YES src_ds = gdal.Open('../gcore/data/stefan_full_rgba_photometric_rgb.tif') @@ -936,31 +748,18 @@ def jp2lura_22(): maxdiff = gdaltest.compare_ds(src_ds, out_ds) del out_ds src_ds = None - if gdal.VSIStatL('/vsimem/jp2lura_22.jp2.aux.xml') is not None: - gdaltest.post_reason('fail') - return 'fail' + assert gdal.VSIStatL('/vsimem/jp2lura_22.jp2.aux.xml') is None ds = gdal.Open('/vsimem/jp2lura_22.jp2') - 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_BlueBand: - gdaltest.post_reason('fail') - return 'fail' - if ds.GetRasterBand(4).GetColorInterpretation() != gdal.GCI_AlphaBand: - 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_BlueBand + assert ds.GetRasterBand(4).GetColorInterpretation() == gdal.GCI_AlphaBand ds = None gdal.Unlink('/vsimem/jp2lura_22.jp2') - if maxdiff > 0: - gdaltest.post_reason('Image too different from reference') - return 'fail' - - return 'success' + assert maxdiff <= 0, 'Image too different from reference' + ############################################################################### # Test NBITS support @@ -968,7 +767,7 @@ def jp2lura_22(): def DISABLED_jp2lura_23(): if gdaltest.jp2lura_drv is None: - return 'skip' + pytest.skip() src_ds = gdal.Open('../gcore/data/uint16.tif') out_ds = gdaltest.jp2lura_drv.CreateCopy('/vsimem/jp2lura_23.jp2', src_ds, options=['NBITS=9', 'QUALITY=100', 'REVERSIBLE=YES']) @@ -976,37 +775,27 @@ def DISABLED_jp2lura_23(): del out_ds src_ds = None ds = gdal.Open('/vsimem/jp2lura_23.jp2') - if ds.GetRasterBand(1).GetMetadataItem('NBITS', 'IMAGE_STRUCTURE') != '9': - gdaltest.post_reason('failure') - return 'fail' + assert ds.GetRasterBand(1).GetMetadataItem('NBITS', 'IMAGE_STRUCTURE') == '9' out_ds = gdaltest.jp2lura_drv.CreateCopy('/vsimem/jp2lura_23_2.jp2', ds) - if out_ds.GetRasterBand(1).GetMetadataItem('NBITS', 'IMAGE_STRUCTURE') != '9': - gdaltest.post_reason('failure') - return 'fail' + assert out_ds.GetRasterBand(1).GetMetadataItem('NBITS', 'IMAGE_STRUCTURE') == '9' del out_ds ds = None - if gdal.VSIStatL('/vsimem/jp2lura_23.jp2.aux.xml') is not None: - gdaltest.post_reason('fail') - return 'fail' + assert gdal.VSIStatL('/vsimem/jp2lura_23.jp2.aux.xml') is None gdal.Unlink('/vsimem/jp2lura_23.jp2') gdal.Unlink('/vsimem/jp2lura_23_2.jp2') - if maxdiff > 1: - gdaltest.post_reason('Image too different from reference') - return 'fail' - - return 'success' + assert maxdiff <= 1, 'Image too different from reference' ############################################################################### # Test Grey+alpha support -def jp2lura_24(): +def test_jp2lura_24(): if gdaltest.jp2lura_drv is None: - return 'skip' + pytest.skip() # Grey+alpha src_ds = gdal.Open('../gcore/data/stefan_full_greyalpha.tif') @@ -1014,27 +803,17 @@ def jp2lura_24(): maxdiff = gdaltest.compare_ds(src_ds, out_ds) del out_ds src_ds = None - if gdal.VSIStatL('/vsimem/jp2lura_24.jp2.aux.xml') is not None: - gdaltest.post_reason('fail') - return 'fail' + assert gdal.VSIStatL('/vsimem/jp2lura_24.jp2.aux.xml') is None ds = gdal.Open('/vsimem/jp2lura_24.jp2') - if ds.GetRasterBand(1).GetColorInterpretation() != gdal.GCI_GrayIndex: - gdaltest.post_reason('fail') - return 'fail' - if ds.GetRasterBand(2).GetColorInterpretation() != gdal.GCI_AlphaBand: - gdaltest.post_reason('fail') - return 'fail' + assert ds.GetRasterBand(1).GetColorInterpretation() == gdal.GCI_GrayIndex + assert ds.GetRasterBand(2).GetColorInterpretation() == gdal.GCI_AlphaBand ds = None - if validate('/vsimem/jp2lura_24.jp2', expected_gmljp2=False, inspire_tg=False) == 'fail': - gdaltest.post_reason('fail') - return 'fail' + assert validate('/vsimem/jp2lura_24.jp2', expected_gmljp2=False, inspire_tg=False) != 'fail' gdal.Unlink('/vsimem/jp2lura_24.jp2') - if maxdiff > 0: - gdaltest.post_reason('Image too different from reference') - return 'fail' + assert maxdiff <= 0, 'Image too different from reference' if False: # pylint: disable=using-constant-test # Grey+alpha with 1BIT_ALPHA=YES @@ -1042,42 +821,27 @@ def jp2lura_24(): gdaltest.jp2lura_drv.CreateCopy('/vsimem/jp2lura_24.jp2', src_ds, options=['1BIT_ALPHA=YES']) src_ds = None - if gdal.VSIStatL('/vsimem/jp2lura_24.jp2.aux.xml') is not None: - gdaltest.post_reason('fail') - return 'fail' + assert gdal.VSIStatL('/vsimem/jp2lura_24.jp2.aux.xml') is None ds = gdal.OpenEx('/vsimem/jp2lura_24.jp2', open_options=['1BIT_ALPHA_PROMOTION=NO']) - if ds.GetRasterBand(1).GetColorInterpretation() != gdal.GCI_GrayIndex: - gdaltest.post_reason('fail') - return 'fail' - if ds.GetRasterBand(2).GetColorInterpretation() != gdal.GCI_AlphaBand: - gdaltest.post_reason('fail') - return 'fail' - if ds.GetRasterBand(2).GetMetadataItem('NBITS', 'IMAGE_STRUCTURE') != '1': - gdaltest.post_reason('fail') - return 'fail' + assert ds.GetRasterBand(1).GetColorInterpretation() == gdal.GCI_GrayIndex + assert ds.GetRasterBand(2).GetColorInterpretation() == gdal.GCI_AlphaBand + assert ds.GetRasterBand(2).GetMetadataItem('NBITS', 'IMAGE_STRUCTURE') == '1' ds = None ds = gdal.Open('/vsimem/jp2lura_24.jp2') - if ds.GetRasterBand(2).GetMetadataItem('NBITS', 'IMAGE_STRUCTURE') is not None: - gdaltest.post_reason('fail') - print(ds.GetRasterBand(2).GetMetadataItem('NBITS', 'IMAGE_STRUCTURE')) - return 'fail' - if ds.GetRasterBand(2).Checksum() != 23120: - gdaltest.post_reason('fail') - print(ds.GetRasterBand(2).Checksum()) - return 'fail' + assert ds.GetRasterBand(2).GetMetadataItem('NBITS', 'IMAGE_STRUCTURE') is None + assert ds.GetRasterBand(2).Checksum() == 23120 ds = None gdal.Unlink('/vsimem/jp2lura_24.jp2') - return 'success' - + ############################################################################### # Test multiband support -def jp2lura_25(): +def test_jp2lura_25(): if gdaltest.jp2lura_drv is None: - return 'skip' + pytest.skip() src_ds = gdal.GetDriverByName('MEM').Create('', 100, 100, 5) src_ds.GetRasterBand(1).Fill(255) @@ -1091,30 +855,22 @@ def jp2lura_25(): del out_ds src_ds = None ds = gdal.Open('/vsimem/jp2lura_25.jp2') - if ds.GetRasterBand(1).GetColorInterpretation() != gdal.GCI_Undefined: - gdaltest.post_reason('fail') - return 'fail' + assert ds.GetRasterBand(1).GetColorInterpretation() == gdal.GCI_Undefined ds = None - if gdal.VSIStatL('/vsimem/jp2lura_25.jp2.aux.xml') is not None: - gdaltest.post_reason('fail') - return 'fail' + assert gdal.VSIStatL('/vsimem/jp2lura_25.jp2.aux.xml') is None gdal.Unlink('/vsimem/jp2lura_25.jp2') - if maxdiff > 0: - gdaltest.post_reason('Image too different from reference') - return 'fail' - - return 'success' + assert maxdiff <= 0, 'Image too different from reference' ############################################################################### # Test CreateCopy() from a JPEG2000 with a 2048x2048 tiling -def jp2lura_27(): +def test_jp2lura_27(): if gdaltest.jp2lura_drv is None: - return 'skip' + pytest.skip() # Test optimization in GDALCopyWholeRasterGetSwathSize() # Not sure how we can check that except looking at logs with CPL_DEBUG=GDAL @@ -1129,8 +885,6 @@ def jp2lura_27(): gdal.Unlink('/vsimem/jp2lura_27.jp2') gdal.Unlink('/vsimem/jp2lura_27.tif') - return 'success' - ############################################################################### # Test CODEBLOCK_WIDTH/_HEIGHT @@ -1197,10 +951,10 @@ def jp2lura_test_codeblock(filename, codeblock_width, codeblock_height): return True -def jp2lura_28(): +def test_jp2lura_28(): if gdaltest.jp2lura_drv is None: - return 'skip' + pytest.skip() src_ds = gdal.GetDriverByName('MEM').Create('', 10, 10, 1) @@ -1219,27 +973,23 @@ def jp2lura_28(): out_ds = gdaltest.jp2lura_drv.CreateCopy('/vsimem/jp2lura_28.jp2', src_ds, options=options) gdal.PopErrorHandler() if warning_expected and gdal.GetLastErrorMsg() == '': - gdaltest.post_reason('warning expected') print(options) - return 'fail' + pytest.fail('warning expected') del out_ds if not jp2lura_test_codeblock('/vsimem/jp2lura_28.jp2', expected_cbkw, expected_cbkh): - gdaltest.post_reason('unexpected codeblock size') print(options) - return 'fail' + pytest.fail('unexpected codeblock size') gdal.Unlink('/vsimem/jp2lura_28.jp2') - return 'success' - ############################################################################### # Test color table support -def jp2lura_30(): +def test_jp2lura_30(): if gdaltest.jp2lura_drv is None: - return 'skip' + pytest.skip() src_ds = gdal.GetDriverByName('MEM').Create('', 10, 10, 1) ct = gdal.ColorTable() @@ -1253,10 +1003,7 @@ def jp2lura_30(): gdal.PushErrorHandler() out_ds = gdaltest.jp2lura_drv.CreateCopy('/vsimem/jp2lura_30.jp2', src_ds) gdal.PopErrorHandler() - if out_ds is not None: - return 'fail' - - return 'success' + assert out_ds is None ############################################################################### # Test unusual band color interpretation order @@ -1265,7 +1012,7 @@ def jp2lura_30(): def DISABLED_jp2lura_31(): if gdaltest.jp2lura_drv is None: - return 'skip' + pytest.skip() src_ds = gdal.GetDriverByName('MEM').Create('', 10, 10, 3) src_ds.GetRasterBand(1).SetColorInterpretation(gdal.GCI_GreenBand) @@ -1273,20 +1020,11 @@ def DISABLED_jp2lura_31(): src_ds.GetRasterBand(3).SetColorInterpretation(gdal.GCI_RedBand) out_ds = gdaltest.jp2lura_drv.CreateCopy('/vsimem/jp2lura_31.jp2', src_ds) del out_ds - if gdal.VSIStatL('/vsimem/jp2lura_31.jp2.aux.xml') is not None: - gdaltest.post_reason('fail') - return 'fail' + assert gdal.VSIStatL('/vsimem/jp2lura_31.jp2.aux.xml') is None ds = gdal.Open('/vsimem/jp2lura_31.jp2') - if ds.GetRasterBand(1).GetColorInterpretation() != gdal.GCI_GreenBand: - gdaltest.post_reason('fail') - print(ds.GetRasterBand(1).GetColorInterpretation()) - return 'fail' - if ds.GetRasterBand(2).GetColorInterpretation() != gdal.GCI_BlueBand: - 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_GreenBand + assert ds.GetRasterBand(2).GetColorInterpretation() == gdal.GCI_BlueBand + assert ds.GetRasterBand(3).GetColorInterpretation() == gdal.GCI_RedBand ds = None gdal.Unlink('/vsimem/jp2lura_31.jp2') @@ -1298,28 +1036,15 @@ def DISABLED_jp2lura_31(): src_ds.GetRasterBand(4).SetColorInterpretation(gdal.GCI_RedBand) out_ds = gdaltest.jp2lura_drv.CreateCopy('/vsimem/jp2lura_31.jp2', src_ds) del out_ds - if gdal.VSIStatL('/vsimem/jp2lura_31.jp2.aux.xml') is not None: - gdaltest.post_reason('fail') - return 'fail' + assert gdal.VSIStatL('/vsimem/jp2lura_31.jp2.aux.xml') is None ds = gdal.Open('/vsimem/jp2lura_31.jp2') - if ds.GetRasterBand(1).GetColorInterpretation() != gdal.GCI_AlphaBand: - gdaltest.post_reason('fail') - print(ds.GetRasterBand(1).GetColorInterpretation()) - return 'fail' - if ds.GetRasterBand(2).GetColorInterpretation() != gdal.GCI_GreenBand: - gdaltest.post_reason('fail') - return 'fail' - if ds.GetRasterBand(3).GetColorInterpretation() != gdal.GCI_BlueBand: - gdaltest.post_reason('fail') - return 'fail' - if ds.GetRasterBand(4).GetColorInterpretation() != gdal.GCI_RedBand: - gdaltest.post_reason('fail') - return 'fail' + assert ds.GetRasterBand(1).GetColorInterpretation() == gdal.GCI_AlphaBand + assert ds.GetRasterBand(2).GetColorInterpretation() == gdal.GCI_GreenBand + assert ds.GetRasterBand(3).GetColorInterpretation() == gdal.GCI_BlueBand + assert ds.GetRasterBand(4).GetColorInterpretation() == gdal.GCI_RedBand ds = None gdal.Unlink('/vsimem/jp2lura_31.jp2') - return 'success' - ############################################################################### # Test crazy tile size @@ -1327,7 +1052,7 @@ def DISABLED_jp2lura_31(): def DISABLED_jp2lura_33(): if gdaltest.jp2lura_drv is None: - return 'skip' + pytest.skip() src_ds = gdal.Open("""<VRTDataset rasterXSize="100000" rasterYSize="100000"> <VRTRasterBand dataType="Byte" band="1"> @@ -1336,89 +1061,69 @@ def DISABLED_jp2lura_33(): gdal.PushErrorHandler() out_ds = gdaltest.jp2lura_drv.CreateCopy('/vsimem/jp2lura_33.jp2', src_ds, options=['BLOCKXSIZE=100000', 'BLOCKYSIZE=100000']) gdal.PopErrorHandler() - if out_ds is not None: - gdaltest.post_reason('fail') - return 'fail' + assert out_ds is None out_ds = None gdal.Unlink('/vsimem/jp2lura_33.jp2') - return 'success' - ############################################################################### # Test opening a file whose dimensions are > 2^31-1 -def jp2lura_34(): +def test_jp2lura_34(): if gdaltest.jp2lura_drv is None: - return 'skip' + pytest.skip() gdal.PushErrorHandler() ds = gdal.Open('data/dimensions_above_31bit.jp2') gdal.PopErrorHandler() - if ds is not None: - gdaltest.post_reason('fail') - return 'fail' - - return 'success' + assert ds is None ############################################################################### # Test opening a truncated file -def jp2lura_35(): +def test_jp2lura_35(): if gdaltest.jp2lura_drv is None: - return 'skip' + pytest.skip() gdal.PushErrorHandler() ds = gdal.Open('data/truncated.jp2') gdal.PopErrorHandler() - if ds is not None: - gdaltest.post_reason('fail') - return 'fail' - - return 'success' + assert ds is None ############################################################################### # Test we cannot create files with more than 16384 bands -def jp2lura_36(): +def test_jp2lura_36(): if gdaltest.jp2lura_drv is None: - return 'skip' + pytest.skip() src_ds = gdal.GetDriverByName('MEM').Create('', 2, 2, 16385) gdal.PushErrorHandler() out_ds = gdaltest.jp2lura_drv.CreateCopy('/vsimem/jp2lura_36.jp2', src_ds) gdal.PopErrorHandler() - if out_ds is not None or gdal.VSIStatL('/vsimem/jp2lura_36.jp2') is not None: - gdaltest.post_reason('fail') - return 'fail' - - return 'success' + assert out_ds is None and gdal.VSIStatL('/vsimem/jp2lura_36.jp2') is None ############################################################################### # Test metadata reading & writing -def jp2lura_37(): +def test_jp2lura_37(): if gdaltest.jp2lura_drv is None: - return 'skip' + pytest.skip() # No metadata src_ds = gdal.GetDriverByName('MEM').Create('', 2, 2) out_ds = gdaltest.jp2lura_drv.CreateCopy('/vsimem/jp2lura_37.jp2', src_ds, options=['WRITE_METADATA=YES']) del out_ds - if gdal.VSIStatL('/vsimem/jp2lura_37.jp2.aux.xml') is not None: - gdaltest.post_reason('fail') - return 'fail' + assert gdal.VSIStatL('/vsimem/jp2lura_37.jp2.aux.xml') is None ds = gdal.Open('/vsimem/jp2lura_37.jp2') - if ds.GetMetadata() != {}: - gdaltest.post_reason('fail') - return 'fail' + assert ds.GetMetadata() == {} gdal.Unlink('/vsimem/jp2lura_37.jp2') # Simple metadata in main domain @@ -1427,13 +1132,9 @@ def jp2lura_37(): src_ds.SetMetadataItem('FOO', 'BAR') out_ds = gdaltest.jp2lura_drv.CreateCopy('/vsimem/jp2lura_37.jp2', src_ds, options=options) del out_ds - if gdal.VSIStatL('/vsimem/jp2lura_37.jp2.aux.xml') is not None: - gdaltest.post_reason('fail') - return 'fail' + assert gdal.VSIStatL('/vsimem/jp2lura_37.jp2.aux.xml') is None ds = gdal.Open('/vsimem/jp2lura_37.jp2') - if ds.GetMetadata() != {'FOO': 'BAR'}: - gdaltest.post_reason('fail') - return 'fail' + assert ds.GetMetadata() == {'FOO': 'BAR'} ds = None gdal.Unlink('/vsimem/jp2lura_37.jp2') @@ -1443,15 +1144,10 @@ def jp2lura_37(): src_ds.SetMetadataItem('FOO', 'BAR', 'SOME_DOMAIN') out_ds = gdaltest.jp2lura_drv.CreateCopy('/vsimem/jp2lura_37.jp2', src_ds, options=['WRITE_METADATA=YES']) del out_ds - if gdal.VSIStatL('/vsimem/jp2lura_37.jp2.aux.xml') is not None: - gdaltest.post_reason('fail') - return 'fail' + assert gdal.VSIStatL('/vsimem/jp2lura_37.jp2.aux.xml') is None ds = gdal.Open('/vsimem/jp2lura_37.jp2') md = ds.GetMetadata('SOME_DOMAIN') - if md != {'FOO': 'BAR'}: - gdaltest.post_reason('fail') - print(md) - return 'fail' + assert md == {'FOO': 'BAR'} gdal.Unlink('/vsimem/jp2lura_37.jp2') # Simple metadata in auxiliary XML domain @@ -1459,13 +1155,9 @@ def jp2lura_37(): src_ds.SetMetadata(['<some_arbitrary_xml_box/>'], 'xml:SOME_DOMAIN') out_ds = gdaltest.jp2lura_drv.CreateCopy('/vsimem/jp2lura_37.jp2', src_ds, options=['WRITE_METADATA=YES']) del out_ds - if gdal.VSIStatL('/vsimem/jp2lura_37.jp2.aux.xml') is not None: - gdaltest.post_reason('fail') - return 'fail' + assert gdal.VSIStatL('/vsimem/jp2lura_37.jp2.aux.xml') is None ds = gdal.Open('/vsimem/jp2lura_37.jp2') - if ds.GetMetadata('xml:SOME_DOMAIN')[0] != '<some_arbitrary_xml_box />\n': - gdaltest.post_reason('fail') - return 'fail' + assert ds.GetMetadata('xml:SOME_DOMAIN')[0] == '<some_arbitrary_xml_box />\n' gdal.Unlink('/vsimem/jp2lura_37.jp2') # Special xml:BOX_ metadata domain @@ -1474,13 +1166,9 @@ def jp2lura_37(): src_ds.SetMetadata(['<some_arbitrary_xml_box/>'], 'xml:BOX_1') out_ds = gdaltest.jp2lura_drv.CreateCopy('/vsimem/jp2lura_37.jp2', src_ds, options=options) del out_ds - if gdal.VSIStatL('/vsimem/jp2lura_37.jp2.aux.xml') is not None: - gdaltest.post_reason('fail') - return 'fail' + assert gdal.VSIStatL('/vsimem/jp2lura_37.jp2.aux.xml') is None ds = gdal.Open('/vsimem/jp2lura_37.jp2') - if ds.GetMetadata('xml:BOX_0')[0] != '<some_arbitrary_xml_box/>': - gdaltest.post_reason('fail') - return 'fail' + assert ds.GetMetadata('xml:BOX_0')[0] == '<some_arbitrary_xml_box/>' gdal.Unlink('/vsimem/jp2lura_37.jp2') # Special xml:XMP metadata domain @@ -1489,13 +1177,9 @@ def jp2lura_37(): src_ds.SetMetadata(['<fake_xmp_box/>'], 'xml:XMP') out_ds = gdaltest.jp2lura_drv.CreateCopy('/vsimem/jp2lura_37.jp2', src_ds, options=options) del out_ds - if gdal.VSIStatL('/vsimem/jp2lura_37.jp2.aux.xml') is not None: - gdaltest.post_reason('fail') - return 'fail' + assert gdal.VSIStatL('/vsimem/jp2lura_37.jp2.aux.xml') is None ds = gdal.Open('/vsimem/jp2lura_37.jp2') - if ds.GetMetadata('xml:XMP')[0] != '<fake_xmp_box/>': - gdaltest.post_reason('fail') - return 'fail' + assert ds.GetMetadata('xml:XMP')[0] == '<fake_xmp_box/>' ds = None gdal.Unlink('/vsimem/jp2lura_37.jp2') @@ -1517,16 +1201,15 @@ def jp2lura_37(): gdal.Unlink('/vsimem/jp2lura_37.jp2') - return 'success' - + ############################################################################### # Test non-EPSG SRS (so written with a GML dictionary) -def jp2lura_38(): +def test_jp2lura_38(): if gdaltest.jp2lura_drv is None: - return 'skip' + pytest.skip() # No metadata src_ds = gdal.GetDriverByName('MEM').Create('', 2, 2) @@ -1534,10 +1217,7 @@ def jp2lura_38(): src_ds.SetProjection(wkt) src_ds.SetGeoTransform([0, 60, 0, 0, 0, -60]) out_ds = gdaltest.jp2lura_drv.CreateCopy('/vsimem/jp2lura_38.jp2', src_ds, options=['GeoJP2=NO']) - if out_ds.GetProjectionRef() != wkt: - gdaltest.post_reason('fail') - print(out_ds.GetProjectionRef()) - return 'fail' + assert out_ds.GetProjectionRef() == wkt crsdictionary = out_ds.GetMetadata_List("xml:CRSDictionary.gml")[0] out_ds = None gdal.Unlink('/vsimem/jp2lura_38.jp2') @@ -1555,20 +1235,17 @@ def jp2lura_38(): do_validate = False if do_validate: - if not xmlvalidate.validate(crsdictionary, ogc_schemas_location='tmp/cache/SCHEMAS_OPENGIS_NET'): - print(crsdictionary) - return 'fail' - - return 'success' + assert xmlvalidate.validate(crsdictionary, ogc_schemas_location='tmp/cache/SCHEMAS_OPENGIS_NET') + ############################################################################### # Test GMLJP2OVERRIDE configuration option and DGIWG GMLJP2 -def jp2lura_39(): +def test_jp2lura_39(): if gdaltest.jp2lura_drv is None: - return 'skip' + pytest.skip() # No metadata src_ds = gdal.GetDriverByName('MEM').Create('', 20, 20) @@ -1626,23 +1303,18 @@ def jp2lura_39(): gdal.Unlink('/vsimem/override.gml') del out_ds ds = gdal.Open('/vsimem/jp2lura_39.jp2') - if ds.GetProjectionRef().find('4326') < 0: - gdaltest.post_reason('fail') - print(ds.GetProjectionRef()) - return 'fail' + assert ds.GetProjectionRef().find('4326') >= 0 ds = None gdal.Unlink('/vsimem/jp2lura_39.jp2') - return 'success' - ############################################################################### # Test we can parse GMLJP2 v2.0 -def jp2lura_40(): +def test_jp2lura_40(): if gdaltest.jp2lura_drv is None: - return 'skip' + pytest.skip() # No metadata src_ds = gdal.GetDriverByName('MEM').Create('', 20, 20) @@ -1703,41 +1375,29 @@ def jp2lura_40(): gdal.Unlink('/vsimem/override.gml') del out_ds ds = gdal.Open('/vsimem/jp2lura_40.jp2') - if ds.GetProjectionRef().find('4326') < 0: - gdaltest.post_reason('fail') - print(ds.GetProjectionRef()) - return 'fail' + assert ds.GetProjectionRef().find('4326') >= 0 got_gt = ds.GetGeoTransform() expected_gt = (2, 0.1, 0, 49, 0, -0.1) for i in range(6): - if abs(got_gt[i] - expected_gt[i]) > 1e-5: - gdaltest.post_reason('fail') - print(got_gt) - return 'fail' + assert abs(got_gt[i] - expected_gt[i]) <= 1e-5 ds = None gdal.Unlink('/vsimem/jp2lura_40.jp2') - return 'success' - ############################################################################### # Test USE_SRC_CODESTREAM=YES -def jp2lura_41(): +def test_jp2lura_41(): if gdaltest.jp2lura_drv is None: - return 'skip' + pytest.skip() src_ds = gdal.Open('data/byte.jp2') out_ds = gdaltest.jp2lura_drv.CreateCopy('/vsimem/jp2lura_41.jp2', src_ds, options=['USE_SRC_CODESTREAM=YES', '@PROFILE=PROFILE_1', 'GEOJP2=NO', 'GMLJP2=NO']) - if src_ds.GetRasterBand(1).Checksum() != out_ds.GetRasterBand(1).Checksum(): - gdaltest.post_reason('fail') - return 'fail' + assert src_ds.GetRasterBand(1).Checksum() == out_ds.GetRasterBand(1).Checksum() del out_ds - if gdal.VSIStatL('/vsimem/jp2lura_41.jp2').size != 9923: - gdaltest.post_reason('fail') - return 'fail' + assert gdal.VSIStatL('/vsimem/jp2lura_41.jp2').size == 9923 gdal.Unlink('/vsimem/jp2lura_41.jp2') gdal.Unlink('/vsimem/jp2lura_41.jp2.aux.xml') @@ -1762,47 +1422,36 @@ def jp2lura_41(): options=['USE_SRC_CODESTREAM=YES']) gdal.PopErrorHandler() del out_ds - if gdal.GetLastErrorMsg() == '': - gdaltest.post_reason('fail') - return 'fail' + assert gdal.GetLastErrorMsg() != '' gdal.Unlink('/vsimem/jp2lura_41.jp2') - return 'success' - ############################################################################### # Get structure of a JPEG2000 file -def jp2lura_43(): +def test_jp2lura_43(): ret = gdal.GetJPEG2000StructureAsString('data/byte.jp2', ['ALL=YES']) - if ret is None: - return 'fail' - - return 'success' + assert ret is not None ############################################################################### # Test GMLJP2v2 -def jp2lura_45(): +def test_jp2lura_45(): if gdaltest.jp2lura_drv is None: - return 'skip' + pytest.skip() if gdal.GetDriverByName('GML') is None: - return 'skip' + pytest.skip() if gdal.GetDriverByName('KML') is None and gdal.GetDriverByName('LIBKML') is None: - return 'skip' + pytest.skip() # Test GMLJP2V2_DEF=YES src_ds = gdal.Open('data/byte.tif') out_ds = gdaltest.jp2lura_drv.CreateCopy('/vsimem/jp2lura_45.jp2', src_ds, options=['GMLJP2V2_DEF=YES']) - if out_ds.GetLayerCount() != 0: - gdaltest.post_reason('fail') - return 'fail' - if out_ds.GetLayer(0) is not None: - gdaltest.post_reason('fail') - return 'fail' + assert out_ds.GetLayerCount() == 0 + assert out_ds.GetLayer(0) is None del out_ds ds = gdal.Open('/vsimem/jp2lura_45.jp2') @@ -1865,135 +1514,106 @@ def jp2lura_45(): </gmljp2:featureMember> </gmljp2:GMLJP2CoverageCollection> """ - if gmljp2 != minimal_instance: - gdaltest.post_reason('fail') - print(gmljp2) - return 'fail' + assert gmljp2 == minimal_instance gdal.Unlink('/vsimem/jp2lura_45.jp2') - return 'success' - ############################################################################### # Test writing & reading RPC in GeoJP2 box -def jp2lura_47(): +def test_jp2lura_47(): if gdaltest.jp2lura_drv is None: - return 'skip' + pytest.skip() src_ds = gdal.Open('../gcore/data/byte_rpc.tif') out_ds = gdaltest.jp2lura_drv.CreateCopy('/vsimem/jp2lura_47.jp2', src_ds) del out_ds - if gdal.VSIStatL('/vsimem/jp2lura_47.jp2.aux.xml') is not None: - gdaltest.post_reason('fail') - return 'fail' + assert gdal.VSIStatL('/vsimem/jp2lura_47.jp2.aux.xml') is None ds = gdal.Open('/vsimem/jp2lura_47.jp2') - if ds.GetMetadata('RPC') is None: - gdaltest.post_reason('fail') - return 'fail' + assert ds.GetMetadata('RPC') is not None ds = None gdal.Unlink('/vsimem/jp2lura_47.jp2') - return 'success' - ############################################################################### # Test reading a dataset whose tile dimensions are larger than dataset ones -def jp2lura_48(): +def test_jp2lura_48(): if gdaltest.jp2lura_drv is None: - return 'skip' + pytest.skip() ds = gdal.Open('data/byte_tile_2048.jp2') (blockxsize, blockysize) = ds.GetRasterBand(1).GetBlockSize() - if (blockxsize, blockysize) != (20, 20): - gdaltest.post_reason('fail') - print(blockxsize, blockysize) - return 'fail' - if ds.GetRasterBand(1).Checksum() != 4610: - gdaltest.post_reason('fail') - return 'fail' + assert (blockxsize, blockysize) == (20, 20) + assert ds.GetRasterBand(1).Checksum() == 4610 ds = None - return 'success' - ############################################################################### -def jp2lura_online_1(): +def test_jp2lura_online_1(): if gdaltest.jp2lura_drv is None: - return 'skip' + pytest.skip() if not gdaltest.download_file('http://download.osgeo.org/gdal/data/jpeg2000/7sisters200.j2k', '7sisters200.j2k'): - return 'skip' + pytest.skip() # Checksum = 32669 on my PC tst = gdaltest.GDALTest('JP2Lura', 'tmp/cache/7sisters200.j2k', 1, None, filename_absolute=1) - if tst.testOpen() != 'success': - return 'fail' + tst.testOpen() ds = gdal.Open('tmp/cache/7sisters200.j2k') ds.GetRasterBand(1).Checksum() ds = None - return 'success' - ############################################################################### -def jp2lura_online_2(): +def test_jp2lura_online_2(): if gdaltest.jp2lura_drv is None: - return 'skip' + pytest.skip() if not gdaltest.download_file('http://download.osgeo.org/gdal/data/jpeg2000/gcp.jp2', 'gcp.jp2'): - return 'skip' + pytest.skip() # Checksum = 15621 on my PC tst = gdaltest.GDALTest('JP2Lura', 'tmp/cache/gcp.jp2', 1, None, filename_absolute=1) - if tst.testOpen() != 'success': - return 'fail' + tst.testOpen() ds = gdal.Open('tmp/cache/gcp.jp2') ds.GetRasterBand(1).Checksum() - if len(ds.GetGCPs()) != 15: - gdaltest.post_reason('bad number of GCP') - return 'fail' + assert len(ds.GetGCPs()) == 15, 'bad number of GCP' 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 ds.GetGCPProjection() != expected_wkt: - gdaltest.post_reason('bad GCP projection') - return 'fail' + assert ds.GetGCPProjection() == expected_wkt, 'bad GCP projection' ds = None - return 'success' - ############################################################################### -def jp2lura_online_3(): +def test_jp2lura_online_3(): if gdaltest.jp2lura_drv is None: - return 'skip' + pytest.skip() if not gdaltest.download_file('http://www.openjpeg.org/samples/Bretagne1.j2k', 'Bretagne1.j2k'): - return 'skip' + pytest.skip() if not gdaltest.download_file('http://www.openjpeg.org/samples/Bretagne1.bmp', 'Bretagne1.bmp'): - return 'skip' + pytest.skip() tst = gdaltest.GDALTest('JP2Lura', 'tmp/cache/Bretagne1.j2k', 1, None, filename_absolute=1) - if tst.testOpen() != 'success': - return 'fail' + tst.testOpen() ds = gdal.Open('tmp/cache/Bretagne1.j2k') ds_ref = gdal.Open('tmp/cache/Bretagne1.bmp') @@ -2005,29 +1625,24 @@ def jp2lura_online_3(): ds_ref = None # Difference between the image before and after compression - if maxdiff > 17: - gdaltest.post_reason('Image too different from reference') - return 'fail' - - return 'success' + assert maxdiff <= 17, 'Image too different from reference' ############################################################################### -def jp2lura_online_4(): +def test_jp2lura_online_4(): if gdaltest.jp2lura_drv is None: - return 'skip' + pytest.skip() if not gdaltest.download_file('http://www.openjpeg.org/samples/Bretagne2.j2k', 'Bretagne2.j2k'): - return 'skip' + pytest.skip() if not gdaltest.download_file('http://www.openjpeg.org/samples/Bretagne2.bmp', 'Bretagne2.bmp'): - return 'skip' + pytest.skip() tst = gdaltest.GDALTest('JP2Lura', 'tmp/cache/Bretagne2.j2k', 1, None, filename_absolute=1) - if tst.testOpen() != 'success': - return 'expected_fail' + tst.testOpen() ds = gdal.Open('tmp/cache/Bretagne2.j2k') ds_ref = gdal.Open('tmp/cache/Bretagne2.bmp') @@ -2039,48 +1654,38 @@ def jp2lura_online_4(): ds_ref = None # Difference between the image before and after compression - if maxdiff > 10: - gdaltest.post_reason('Image too different from reference') - return 'fail' - - return 'success' + assert maxdiff <= 10, 'Image too different from reference' ############################################################################### # Try reading JP2Lura with color table -def jp2lura_online_5(): +def test_jp2lura_online_5(): if gdaltest.jp2lura_drv is None: - return 'skip' + pytest.skip() if not gdaltest.download_file('http://www.gwg.nga.mil/ntb/baseline/software/testfile/Jpeg2000/jp2_09/file9.jp2', 'file9.jp2'): - return 'skip' + pytest.skip() ds = gdal.Open('tmp/cache/file9.jp2') cs1 = ds.GetRasterBand(1).Checksum() - if cs1 != 47664: - gdaltest.post_reason('Did not get expected checksums') - print(cs1) - return 'fail' - if ds.GetRasterBand(1).GetColorTable() is None: - gdaltest.post_reason('Did not get expected color table') - return 'fail' + assert cs1 == 47664, 'Did not get expected checksums' + assert ds.GetRasterBand(1).GetColorTable() is not None, \ + 'Did not get expected color table' ds = None - return 'success' - ############################################################################### # Try reading YCbCr JP2Lura as RGB -def jp2lura_online_6(): +def test_jp2lura_online_6(): if gdaltest.jp2lura_drv is None: - return 'skip' + pytest.skip() if not gdaltest.download_file('http://www.gwg.nga.mil/ntb/baseline/software/testfile/Jpeg2000/jp2_03/file3.jp2', 'file3.jp2'): - return 'skip' + pytest.skip() ds = gdal.Open('tmp/cache/file3.jp2') # cs1 = ds.GetRasterBand(1).Checksum() @@ -2090,20 +1695,17 @@ def jp2lura_online_6(): # print(cs1, cs2, cs3) # gdaltest.post_reason('Did not get expected checksums') # return 'fail' - if ds is not None: - return 'fail' + assert ds is None ds = None - return 'success' - ############################################################################### # Test GDAL_GEOREF_SOURCES -def jp2lura_49(): +def test_jp2lura_49(): if gdaltest.jp2lura_drv is None: - return 'skip' + pytest.skip() tests = [(None, True, True, 'LOCAL_CS["PAM"]', (100.0, 1.0, 0.0, 300.0, 0.0, -1.0)), (None, True, False, 'LOCAL_CS["PAM"]', (100.0, 1.0, 0.0, 300.0, 0.0, -1.0)), @@ -2143,16 +1745,14 @@ def jp2lura_49(): gdal.Unlink('/vsimem/byte_nogeoref.j2w') if gt != expected_gt: - gdaltest.post_reason('Did not get expected gt for %s,copy_pam=%s,copy_worldfile=%s' % (config_option_value, str(copy_pam), str(copy_worldfile))) print('Got ' + str(gt)) print('Expected ' + str(expected_gt)) - return 'fail' + pytest.fail('Did not get expected gt for %s,copy_pam=%s,copy_worldfile=%s' % (config_option_value, str(copy_pam), str(copy_worldfile))) if (expected_srs == '' and srs_wkt != '') or (expected_srs != '' and srs_wkt.find(expected_srs) < 0): - gdaltest.post_reason('Did not get expected SRS for %s,copy_pam=%s,copy_worldfile=%s' % (config_option_value, str(copy_pam), str(copy_worldfile))) print('Got ' + srs_wkt) print('Expected ' + expected_srs) - return 'fail' + pytest.fail('Did not get expected SRS for %s,copy_pam=%s,copy_worldfile=%s' % (config_option_value, str(copy_pam), str(copy_worldfile))) tests = [(None, True, True, 'LOCAL_CS["PAM"]', (100.0, 1.0, 0.0, 300.0, 0.0, -1.0)), (None, True, False, 'LOCAL_CS["PAM"]', (100.0, 1.0, 0.0, 300.0, 0.0, -1.0)), @@ -2200,41 +1800,34 @@ def jp2lura_49(): gdal.Unlink('/vsimem/inconsitant_geojp2_gmljp2.j2w') if gt != expected_gt: - gdaltest.post_reason('Did not get expected gt for %s,copy_pam=%s,copy_worldfile=%s' % (config_option_value, str(copy_pam), str(copy_worldfile))) print('Got ' + str(gt)) print('Expected ' + str(expected_gt)) - return 'fail' + pytest.fail('Did not get expected gt for %s,copy_pam=%s,copy_worldfile=%s' % (config_option_value, str(copy_pam), str(copy_worldfile))) if (expected_srs == '' and srs_wkt != '') or (expected_srs != '' and srs_wkt.find(expected_srs) < 0): - gdaltest.post_reason('Did not get expected SRS for %s,copy_pam=%s,copy_worldfile=%s' % (config_option_value, str(copy_pam), str(copy_worldfile))) print('Got ' + srs_wkt) print('Expected ' + expected_srs) - return 'fail' + pytest.fail('Did not get expected SRS for %s,copy_pam=%s,copy_worldfile=%s' % (config_option_value, str(copy_pam), str(copy_worldfile))) ds = gdal.OpenEx('data/inconsitant_geojp2_gmljp2.jp2', open_options=['GEOREF_SOURCES=PAM,WORLDFILE']) fl = ds.GetFileList() - if set(fl) != set(['data/inconsitant_geojp2_gmljp2.jp2', 'data/inconsitant_geojp2_gmljp2.jp2.aux.xml']): - gdaltest.post_reason('Did not get expected filelist') - print(fl) - return 'fail' + assert set(fl) == set(['data/inconsitant_geojp2_gmljp2.jp2', 'data/inconsitant_geojp2_gmljp2.jp2.aux.xml']), \ + 'Did not get expected filelist' gdal.ErrorReset() with gdaltest.error_handler(): gdal.OpenEx('data/inconsitant_geojp2_gmljp2.jp2', open_options=['GEOREF_SOURCES=unhandled']) - if gdal.GetLastErrorMsg() == '': - gdaltest.post_reason('expected warning') - return 'fail' - - return 'success' + assert gdal.GetLastErrorMsg() != '', 'expected warning' + ############################################################################### # Test reading split IEEE-754 Float32 -def jp2lura_50(): +def test_jp2lura_50(): if gdaltest.jp2lura_drv is None: - return 'skip' + pytest.skip() tst = gdaltest.GDALTest('JP2Lura', 'float32_ieee754_split_reversible.jp2', 1, 4672) return tst.testOpen() @@ -2243,33 +1836,27 @@ def jp2lura_50(): # Test split IEEE-754 Float32 -def jp2lura_51(): +def test_jp2lura_51(): if gdaltest.jp2lura_drv is None: - return 'skip' + pytest.skip() # Don't allow it by default src_ds = gdal.Open('data/float32.tif') with gdaltest.error_handler(): ds = gdaltest.jp2lura_drv.CreateCopy('/vsimem/jp2lura_51.jp2', src_ds) - if ds is not None: - gdaltest.post_reason('fail') - return 'fail' + assert ds is None ds = gdaltest.jp2lura_drv.CreateCopy('/vsimem/jp2lura_51.jp2', src_ds, options=['SPLIT_IEEE754=YES']) maxdiff = gdaltest.compare_ds(ds, src_ds) ds = None - if validate('/vsimem/jp2lura_51.jp2', inspire_tg=False) == 'fail': - gdaltest.post_reason('fail') - return 'fail' + assert validate('/vsimem/jp2lura_51.jp2', inspire_tg=False) != 'fail' gdaltest.jp2lura_drv.Delete('/vsimem/jp2lura_51.jp2') - if maxdiff > 0.01: - gdaltest.post_reason('fail') - return 'fail' + assert maxdiff <= 0.01 # QUALITY with gdaltest.error_handler(): @@ -2278,14 +1865,9 @@ def jp2lura_51(): if ds is not None: maxdiff = gdaltest.compare_ds(ds, src_ds) ds = None - if maxdiff > 124: - gdaltest.post_reason('fail') - print(maxdiff) - return 'fail' - - if validate('/vsimem/jp2lura_51.jp2', inspire_tg=False) == 'fail': - gdaltest.post_reason('fail') - return 'fail' + assert maxdiff <= 124 + + assert validate('/vsimem/jp2lura_51.jp2', inspire_tg=False) != 'fail' ds = None with gdaltest.error_handler(): gdaltest.jp2lura_drv.Delete('/vsimem/jp2lura_51.jp2') @@ -2296,14 +1878,9 @@ def jp2lura_51(): options=['SPLIT_IEEE754=YES', 'RATE=1']) maxdiff = gdaltest.compare_ds(ds, src_ds) ds = None - if maxdiff > 370: - gdaltest.post_reason('fail') - print(maxdiff) - return 'fail' + assert maxdiff <= 370 - if validate('/vsimem/jp2lura_51.jp2', inspire_tg=False) == 'fail': - gdaltest.post_reason('fail') - return 'fail' + assert validate('/vsimem/jp2lura_51.jp2', inspire_tg=False) != 'fail' gdaltest.jp2lura_drv.Delete('/vsimem/jp2lura_51.jp2') @@ -2312,23 +1889,18 @@ def jp2lura_51(): options=['SPLIT_IEEE754=YES', 'REVERSIBLE=YES']) maxdiff = gdaltest.compare_ds(ds, src_ds) ds = None - if maxdiff != 0.0: - gdaltest.post_reason('fail') - print(maxdiff) - return 'fail' + assert maxdiff == 0.0 gdaltest.jp2lura_drv.Delete('/vsimem/jp2lura_51.jp2') - return 'success' - ############################################################################### # Test other data types -def jp2lura_52(): +def test_jp2lura_52(): if gdaltest.jp2lura_drv is None: - return 'skip' + pytest.skip() tests = [[-32768, gdal.GDT_Int16, 'h'], [-1, gdal.GDT_Int16, 'h'], @@ -2347,29 +1919,22 @@ def jp2lura_52(): ds = gdaltest.jp2lura_drv.CreateCopy('/vsimem/jp2lura_52.jp2', src_ds, options=['REVERSIBLE=YES']) got_min, got_max = ds.GetRasterBand(1).ComputeRasterMinMax() - if val != got_min or val != got_max: - gdaltest.post_reason('fail') - print(val, dt, fmt, got_min, got_max) - return 'fail' + assert val == got_min and val == got_max, (val, dt, fmt, got_min, got_max) ds = None - if val >= 0 and validate('/vsimem/jp2lura_52.jp2', expected_gmljp2=False, inspire_tg=False) == 'fail': - gdaltest.post_reason('fail') - print(val, dt, fmt) - return 'fail' + assert not (val >= 0 and validate('/vsimem/jp2lura_52.jp2', expected_gmljp2=False, inspire_tg=False) == 'fail'), \ + (val, dt, fmt) gdaltest.jp2lura_drv.Delete('/vsimem/jp2lura_52.jp2') - return 'success' - ############################################################################### # Test RATE and QUALITY -def jp2lura_53(): +def test_jp2lura_53(): if gdaltest.jp2lura_drv is None: - return 'skip' + pytest.skip() src_ds = gdal.Open('data/byte.tif') @@ -2377,10 +1942,7 @@ def jp2lura_53(): options=['RATE=1']) maxdiff = gdaltest.compare_ds(ds, src_ds) ds = None - if maxdiff > 8: - gdaltest.post_reason('fail') - print(maxdiff) - return 'fail' + assert maxdiff <= 8 gdaltest.jp2lura_drv.Delete('/vsimem/jp2lura_53.jp2') @@ -2388,10 +1950,7 @@ def jp2lura_53(): options=['QUALITY=100']) maxdiff = gdaltest.compare_ds(ds, src_ds) ds = None - if maxdiff > 2: - gdaltest.post_reason('fail') - print(maxdiff) - return 'fail' + assert maxdiff <= 2 gdaltest.jp2lura_drv.Delete('/vsimem/jp2lura_53.jp2') @@ -2400,10 +1959,7 @@ def jp2lura_53(): options=['REVERSIBLE=YES', 'RATE=1']) maxdiff = gdaltest.compare_ds(ds, src_ds) ds = None - if maxdiff > 8: - gdaltest.post_reason('fail') - print(maxdiff) - return 'fail' + assert maxdiff <= 8 gdaltest.jp2lura_drv.Delete('/vsimem/jp2lura_53.jp2') @@ -2412,23 +1968,18 @@ def jp2lura_53(): options=['REVERSIBLE=YES', 'QUALITY=100']) maxdiff = gdaltest.compare_ds(ds, src_ds) ds = None - if maxdiff > 0: - gdaltest.post_reason('fail') - print(maxdiff) - return 'fail' + assert maxdiff <= 0 gdaltest.jp2lura_drv.Delete('/vsimem/jp2lura_53.jp2') - return 'success' - ############################################################################### # Test RasterIO edge cases -def jp2lura_54(): +def test_jp2lura_54(): if gdaltest.jp2lura_drv is None: - return 'skip' + pytest.skip() # Tiled with incomplete boundary tiles src_ds = gdal.GetDriverByName('MEM').Create('', 100, 100, 1) @@ -2439,110 +1990,19 @@ def jp2lura_54(): data = ds.GetRasterBand(1).ReadRaster(0, 0, 100, 100, 100, 100, buf_type=gdal.GDT_Int16) data = struct.unpack('h' * 100 * 100, data) - if min(data) != 100 or max(data) != 100: - gdaltest.post_reason('fail') - print(min(data)) - print(max(data)) - return 'fail' + assert min(data) == 100 and max(data) == 100 # Request at a resolution that is not a power of two data = ds.GetRasterBand(1).ReadRaster(0, 0, 100, 100, 30, 30) data = struct.unpack('B' * 30 * 30, data) - if min(data) != 100 or max(data) != 100: - gdaltest.post_reason('fail') - print(min(data)) - print(max(data)) - return 'fail' + assert min(data) == 100 and max(data) == 100 ds = None gdaltest.jp2lura_drv.Delete('/vsimem/jp2lura_54.jp2') - return 'success' - ############################################################################### -def jp2lura_cleanup(): +def test_jp2lura_cleanup(): gdaltest.reregister_all_jpeg2000_drivers() - - return 'success' - - -gdaltest_list = [ - jp2lura_1, - jp2lura_missing_license_num, - jp2lura_invalid_license_num, - jp2lura_2, - jp2lura_3, - jp2lura_4, - jp2lura_4_vsimem, - jp2lura_5, - jp2lura_6, - jp2lura_7, - jp2lura_8, - jp2lura_9, - # jp2lura_10, - # jp2lura_11, - jp2lura_12, - jp2lura_13, - jp2lura_14, - jp2lura_16, - jp2lura_17, - jp2lura_18, - jp2lura_19, - jp2lura_20, - # jp2lura_21, - jp2lura_22, - # jp2lura_23, - jp2lura_24, - jp2lura_25, - # jp2lura_26, - jp2lura_27, - jp2lura_28, - # jp2lura_29, - jp2lura_30, - # jp2lura_31, - # jp2lura_32, - # jp2lura_33, - jp2lura_34, - jp2lura_35, - jp2lura_36, - jp2lura_37, - jp2lura_38, - jp2lura_39, - jp2lura_40, - jp2lura_41, - # jp2lura_42, - jp2lura_43, - # jp2lura_44, - jp2lura_45, - # jp2lura_46, - jp2lura_47, - jp2lura_48, - jp2lura_49, - jp2lura_50, - jp2lura_51, - jp2lura_52, - jp2lura_53, - jp2lura_54, - jp2lura_online_1, - jp2lura_online_2, - jp2lura_online_3, - jp2lura_online_4, - jp2lura_online_5, - jp2lura_online_6, - jp2lura_cleanup] - -disabled_gdaltest_list = [ - jp2lura_1, - jp2lura_53, - jp2lura_cleanup] - -if __name__ == '__main__': - - gdaltest.setup_run('jp2lura') - - gdaltest.run_tests(gdaltest_list) - - sys.exit(gdaltest.summarize()) diff --git a/autotest/gdrivers/jp2metadata.py b/autotest/gdrivers/jp2metadata.py index 2d9de1bd5c14..c8008ef6af6b 100755 --- a/autotest/gdrivers/jp2metadata.py +++ b/autotest/gdrivers/jp2metadata.py @@ -28,42 +28,35 @@ # DEALINGS IN THE SOFTWARE. ############################################################################### -import sys import os -sys.path.append('../pymod') from osgeo import gdal -import gdaltest +import pytest ############################################################################### # Test bugfix for #5249 (Irrelevant ERDAS GeoTIFF JP2Box read) -def jp2metadata_1(): +def test_jp2metadata_1(): ds = gdal.Open('data/erdas_foo.jp2') if ds is None: - return 'skip' + pytest.skip() wkt = ds.GetProjectionRef() gt = ds.GetGeoTransform() - if wkt.find('PROJCS["ETRS89') != 0: - print(wkt) - return 'fail' + assert wkt.find('PROJCS["ETRS89') == 0 expected_gt = (356000.0, 0.5, 0.0, 7596000.0, 0.0, -0.5) for i in range(6): - if abs(gt[i] - expected_gt[i]) > 1e-5: - print(gt) - return 'fail' - return 'success' - + assert abs(gt[i] - expected_gt[i]) <= 1e-5 + ############################################################################### # Test Pleiades imagery metadata -def jp2metadata_2(): +def test_jp2metadata_2(): # Pleiades product description http://www.cscrs.itu.edu.tr/assets/downloads/PleiadesUserGuide.pdf try: @@ -73,49 +66,36 @@ def jp2metadata_2(): ds = gdal.Open('data/IMG_md_ple_R1C1.jp2', gdal.GA_ReadOnly) if ds is None: - return 'skip' + pytest.skip() 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.' mddlist = ds.GetMetadataDomainList() - if 'IMD' not in mddlist or 'RPC' not in mddlist or 'IMAGERY' not in mddlist: - gdaltest.post_reason('did not get expected metadata list.') - print(mddlist) - return 'fail' + assert 'IMD' in mddlist and 'RPC' in mddlist and 'IMAGERY' in mddlist, \ + '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' ds = None - try: + with pytest.raises(OSError, message='Expected not generation of data/IMG_md_ple_R1C1.jp2.aux.xml'): os.stat('data/IMG_md_ple_R1C1.jp2.aux.xml') - gdaltest.post_reason('Expected not generation of data/IMG_md_ple_R1C1.jp2.aux.xml') - return 'fail' - except OSError: - pass - - return 'success' + + ############################################################################### # Test reading GMLJP2 file with srsName only on the Envelope, and lots of other # metadata junk. This file is also handled currently with axis reordering # disabled. -def jp2metadata_3(): +def test_jp2metadata_3(): gdal.SetConfigOption('GDAL_IGNORE_AXIS_ORIENTATION', 'YES') @@ -124,14 +104,13 @@ def jp2metadata_3(): ds = gdal.Open('data/ll.jp2') if ds is None: gdal.SetConfigOption('GDAL_IGNORE_AXIS_ORIENTATION', 'NO') - return 'skip' + pytest.skip() wkt = ds.GetProjection() if wkt != exp_wkt: - gdaltest.post_reason('did not get expected WKT, should be WGS84') print('got: ', wkt) print('exp: ', exp_wkt) - return 'fail' + pytest.fail('did not get expected WKT, should be WGS84') gt = ds.GetGeoTransform() if abs(gt[0] - 8) > 0.0000001 or abs(gt[3] - 50) > 0.000001 \ @@ -139,35 +118,31 @@ def jp2metadata_3(): or abs(gt[2] - 0.0) > 0.000000000005 \ or abs(gt[4] - 0.0) > 0.000000000005 \ or abs(gt[5] - -0.000761397164) > 0.000000000005: - gdaltest.post_reason('did not get expected geotransform') print('got: ', gt) - return 'fail' + pytest.fail('did not get expected geotransform') ds = None gdal.SetConfigOption('GDAL_IGNORE_AXIS_ORIENTATION', 'NO') - return 'success' - ############################################################################### # Test reading a file with axis orientation set properly for an alternate # axis order coordinate system (urn:...:EPSG::4326). -def jp2metadata_4(): +def test_jp2metadata_4(): exp_wkt = 'GEOGCS["WGS 84",DATUM["WGS_1984",SPHEROID["WGS 84",6378137,298.257223563,AUTHORITY["EPSG","7030"]],AUTHORITY["EPSG","6326"]],PRIMEM["Greenwich",0,AUTHORITY["EPSG","8901"]],UNIT["degree",0.0174532925199433,AUTHORITY["EPSG","9122"]],AUTHORITY["EPSG","4326"]]' ds = gdal.Open('data/gmljp2_dtedsm_epsg_4326_axes.jp2') if ds is None: - return 'skip' + pytest.skip() wkt = ds.GetProjection() if wkt != exp_wkt: - gdaltest.post_reason('did not get expected WKT, should be WGS84') print('got: ', wkt) print('exp: ', exp_wkt) - return 'fail' + pytest.fail('did not get expected WKT, should be WGS84') gt = ds.GetGeoTransform() gte = (42.999583333333369, 0.008271349862259, 0, @@ -178,33 +153,29 @@ def jp2metadata_4(): or abs(gt[2] - gte[2]) > 0.000000000005 \ or abs(gt[4] - gte[4]) > 0.000000000005 \ or abs(gt[5] - gte[5]) > 0.000000000005: - gdaltest.post_reason('did not get expected geotransform') print('got: ', gt) - return 'fail' + pytest.fail('did not get expected geotransform') ds = None - return 'success' - ############################################################################### # Test reading a file with EPSG axis orientation being northing, easting, # but with explicit axisName being easting, northing (#5960) -def jp2metadata_5(): +def test_jp2metadata_5(): exp_wkt = 'PROJCS["ETRS89 / LAEA Europe",GEOGCS["ETRS89",DATUM["European_Terrestrial_Reference_System_1989",SPHEROID["GRS 1980",6378137,298.257222101,AUTHORITY["EPSG","7019"]],TOWGS84[0,0,0,0,0,0,0],AUTHORITY["EPSG","6258"]],PRIMEM["Greenwich",0,AUTHORITY["EPSG","8901"]],UNIT["degree",0.0174532925199433,AUTHORITY["EPSG","9122"]],AUTHORITY["EPSG","4258"]],PROJECTION["Lambert_Azimuthal_Equal_Area"],PARAMETER["latitude_of_center",52],PARAMETER["longitude_of_center",10],PARAMETER["false_easting",4321000],PARAMETER["false_northing",3210000],UNIT["metre",1,AUTHORITY["EPSG","9001"]],AUTHORITY["EPSG","3035"]]' ds = gdal.Open('data/gmljp2_epsg3035_easting_northing.jp2') if ds is None: - return 'skip' + pytest.skip() wkt = ds.GetProjection() if wkt != exp_wkt: - gdaltest.post_reason('did not get expected WKT') print('got: ', wkt) print('exp: ', exp_wkt) - return 'fail' + pytest.fail('did not get expected WKT') gt = ds.GetGeoTransform() gte = (4895766.000000001, 2.0, 0.0, 2296946.0, 0.0, -2.0) @@ -214,28 +185,11 @@ def jp2metadata_5(): or abs(gt[2] - gte[2]) > 0.000000000005 \ or abs(gt[4] - gte[4]) > 0.000000000005 \ or abs(gt[5] - gte[5]) > 0.000000000005: - gdaltest.post_reason('did not get expected geotransform') print('got: ', gt) - return 'fail' + pytest.fail('did not get expected geotransform') ds = None - return 'success' - - -gdaltest_list = [ - jp2metadata_1, - jp2metadata_2, - jp2metadata_3, - jp2metadata_4, - jp2metadata_5 -] - - -if __name__ == '__main__': - gdaltest.setup_run('jp2metadata') - gdaltest.run_tests(gdaltest_list) - sys.exit(gdaltest.summarize()) diff --git a/autotest/gdrivers/jp2openjpeg.py b/autotest/gdrivers/jp2openjpeg.py index ef1d831fe280..278ec548802e 100755 --- a/autotest/gdrivers/jp2openjpeg.py +++ b/autotest/gdrivers/jp2openjpeg.py @@ -35,8 +35,8 @@ from osgeo import gdal from osgeo import ogr from osgeo import osr +import pytest -sys.path.append('../pymod') sys.path.append('../ogr') sys.path.append('../../gdal/swig/python/samples') @@ -46,24 +46,22 @@ # Verify we have the driver. -def jp2openjpeg_1(): +def test_jp2openjpeg_1(): gdaltest.jp2openjpeg_drv = gdal.GetDriverByName('JP2OpenJPEG') if gdaltest.jp2openjpeg_drv is None: - return 'skip' + pytest.skip() gdaltest.deregister_all_jpeg2000_drivers_but('JP2OpenJPEG') - return 'success' - ############################################################################### # Open byte.jp2 -def jp2openjpeg_2(): +def test_jp2openjpeg_2(): if gdaltest.jp2openjpeg_drv is None: - return 'skip' + pytest.skip() srs = """PROJCS["NAD27 / UTM zone 11N", GEOGCS["NAD27", @@ -93,10 +91,10 @@ def jp2openjpeg_2(): # Open int16.jp2 -def jp2openjpeg_3(): +def test_jp2openjpeg_3(): if gdaltest.jp2openjpeg_drv is None: - return 'skip' + pytest.skip() ds = gdal.Open('data/int16.jp2') ds_ref = gdal.Open('data/int16.tif') @@ -109,25 +107,19 @@ def jp2openjpeg_3(): ds_ref = None # Quite a bit of difference... - if maxdiff > 6: - gdaltest.post_reason('Image too different from reference') - return 'fail' + assert maxdiff <= 6, 'Image too different from reference' ds = ogr.Open('data/int16.jp2') - if ds is not None: - gdaltest.post_reason('fail') - return 'fail' - - return 'success' + assert ds is None ############################################################################### # Test copying byte.jp2 -def jp2openjpeg_4(out_filename='tmp/jp2openjpeg_4.jp2'): +def test_jp2openjpeg_4(out_filename='tmp/jp2openjpeg_4.jp2'): if gdaltest.jp2openjpeg_drv is None: - return 'skip' + pytest.skip() src_ds = gdal.Open('data/byte.jp2') src_wkt = src_ds.GetProjectionRef() @@ -146,9 +138,7 @@ def jp2openjpeg_4(out_filename='tmp/jp2openjpeg_4.jp2'): vrt_ds = None gdal.Unlink('/vsimem/jp2openjpeg_4.vrt') - if gdal.VSIStatL(out_filename + '.aux.xml') is not None: - gdaltest.post_reason('fail') - return 'fail' + assert gdal.VSIStatL(out_filename + '.aux.xml') is None ds = gdal.Open(out_filename) cs = ds.GetRasterBand(1).Checksum() @@ -161,12 +151,8 @@ def jp2openjpeg_4(out_filename='tmp/jp2openjpeg_4.jp2'): gdal.Unlink(out_filename) - if xres != '300' or yres != '200' or resunit != '3 (pixels/cm)': - gdaltest.post_reason('bad resolution') - print(xres) - print(yres) - print(resunit) - return 'fail' + assert xres == '300' and yres == '200' and resunit == '3 (pixels/cm)', \ + 'bad resolution' sr1 = osr.SpatialReference() sr1.SetFromUserInput(got_wkt) @@ -174,37 +160,27 @@ def jp2openjpeg_4(out_filename='tmp/jp2openjpeg_4.jp2'): sr2.SetFromUserInput(src_wkt) if sr1.IsSame(sr2) == 0: - gdaltest.post_reason('bad spatial reference') print(got_wkt) print(src_wkt) - return 'fail' + pytest.fail('bad spatial reference') for i in range(6): - if abs(got_gt[i] - src_gt[i]) > 1e-8: - gdaltest.post_reason('bad geotransform') - print(got_gt) - print(src_gt) - return 'fail' + assert abs(got_gt[i] - src_gt[i]) <= 1e-8, 'bad geotransform' - if cs != 50054: - gdaltest.post_reason('bad checksum') - print(cs) - return 'fail' + assert cs == 50054, 'bad checksum' - return 'success' - -def jp2openjpeg_4_vsimem(): - return jp2openjpeg_4('/vsimem/jp2openjpeg_4.jp2') +def test_jp2openjpeg_4_vsimem(): + return test_jp2openjpeg_4('/vsimem/jp2openjpeg_4.jp2') ############################################################################### # Test copying int16.jp2 -def jp2openjpeg_5(): +def test_jp2openjpeg_5(): if gdaltest.jp2openjpeg_drv is None: - return 'skip' + pytest.skip() tst = gdaltest.GDALTest('JP2OpenJPEG', 'int16.jp2', 1, None, options=['REVERSIBLE=YES', 'QUALITY=100', 'CODEC=J2K']) return tst.testCreateCopy() @@ -213,30 +189,27 @@ def jp2openjpeg_5(): # Test reading ll.jp2 -def jp2openjpeg_6(): +def test_jp2openjpeg_6(): if gdaltest.jp2openjpeg_drv is None: - return 'skip' + pytest.skip() tst = gdaltest.GDALTest('JP2OpenJPEG', 'll.jp2', 1, None) - if tst.testOpen() != 'success': - return 'fail' + tst.testOpen() ds = gdal.Open('data/ll.jp2') ds.GetRasterBand(1).Checksum() ds = None - return 'success' - ############################################################################### # Open byte.jp2.gz (test use of the VSIL API) -def jp2openjpeg_7(): +def test_jp2openjpeg_7(): if gdaltest.jp2openjpeg_drv is None: - return 'skip' + pytest.skip() tst = gdaltest.GDALTest('JP2OpenJPEG', '/vsigzip/data/byte.jp2.gz', 1, 50054, filename_absolute=1) return tst.testOpen() @@ -245,103 +218,74 @@ def jp2openjpeg_7(): # Test a JP2OpenJPEG with the 3 bands having 13bit depth and the 4th one 1 bit -def jp2openjpeg_8(): +def test_jp2openjpeg_8(): if gdaltest.jp2openjpeg_drv is None: - return 'skip' + pytest.skip() ds = gdal.Open('data/3_13bit_and_1bit.jp2') expected_checksums = [64570, 57277, 56048, 61292] for i in range(4): - if ds.GetRasterBand(i + 1).Checksum() != expected_checksums[i]: - gdaltest.post_reason('unexpected checksum (%d) for band %d' % (expected_checksums[i], i + 1)) - return 'fail' + assert ds.GetRasterBand(i + 1).Checksum() == expected_checksums[i], \ + ('unexpected checksum (%d) for band %d' % (expected_checksums[i], i + 1)) - if ds.GetRasterBand(1).DataType != gdal.GDT_UInt16: - gdaltest.post_reason('unexpected data type') - return 'fail' - - return 'success' + assert ds.GetRasterBand(1).DataType == gdal.GDT_UInt16, 'unexpected data type' ############################################################################### # Check that we can use .j2w world files (#4651) -def jp2openjpeg_9(): +def test_jp2openjpeg_9(): if gdaltest.jp2openjpeg_drv is None: - return 'skip' + pytest.skip() ds = gdal.Open('data/byte_without_geotransform.jp2') geotransform = ds.GetGeoTransform() - if abs(geotransform[0] - 440720) > 0.1 \ - or abs(geotransform[1] - 60) > 0.001 \ - or abs(geotransform[2] - 0) > 0.001 \ - or abs(geotransform[3] - 3751320) > 0.1 \ - or abs(geotransform[4] - 0) > 0.001 \ - or abs(geotransform[5] - -60) > 0.001: - print(geotransform) - gdaltest.post_reason('geotransform differs from expected') - return 'fail' + assert abs(geotransform[0] - 440720) <= 0.1 and abs(geotransform[1] - 60) <= 0.001 and abs(geotransform[2] - 0) <= 0.001 and abs(geotransform[3] - 3751320) <= 0.1 and abs(geotransform[4] - 0) <= 0.001 and abs(geotransform[5] - -60) <= 0.001, \ + 'geotransform differs from expected' ds = None - return 'success' - ############################################################################### # Test YCBCR420 creation option -def jp2openjpeg_10(): +def test_jp2openjpeg_10(): if gdaltest.jp2openjpeg_drv is None: - return 'skip' + pytest.skip() src_ds = gdal.Open('data/rgbsmall.tif') out_ds = gdaltest.jp2openjpeg_drv.CreateCopy('/vsimem/jp2openjpeg_10.jp2', src_ds, options=['YCBCR420=YES', 'RESOLUTIONS=3']) maxdiff = gdaltest.compare_ds(src_ds, out_ds) - if out_ds.GetRasterBand(1).GetColorInterpretation() != gdal.GCI_RedBand: - gdaltest.post_reason('fail') - return 'fail' - if out_ds.GetRasterBand(2).GetColorInterpretation() != gdal.GCI_GreenBand: - gdaltest.post_reason('fail') - return 'fail' - if out_ds.GetRasterBand(3).GetColorInterpretation() != gdal.GCI_BlueBand: - gdaltest.post_reason('fail') - return 'fail' + assert out_ds.GetRasterBand(1).GetColorInterpretation() == gdal.GCI_RedBand + assert out_ds.GetRasterBand(2).GetColorInterpretation() == gdal.GCI_GreenBand + assert out_ds.GetRasterBand(3).GetColorInterpretation() == gdal.GCI_BlueBand del out_ds src_ds = None gdal.Unlink('/vsimem/jp2openjpeg_10.jp2') # Quite a bit of difference... - if maxdiff > 12: - gdaltest.post_reason('Image too different from reference') - return 'fail' - - return 'success' + assert maxdiff <= 12, 'Image too different from reference' ############################################################################### # Test auto-promotion of 1bit alpha band to 8bit -def jp2openjpeg_11(): +def test_jp2openjpeg_11(): if gdaltest.jp2openjpeg_drv is None: - return 'skip' + pytest.skip() ds = gdal.Open('data/stefan_full_rgba_alpha_1bit.jp2') fourth_band = ds.GetRasterBand(4) - if fourth_band.GetMetadataItem('NBITS', 'IMAGE_STRUCTURE') is not None: - gdaltest.post_reason('fail') - return 'fail' + assert fourth_band.GetMetadataItem('NBITS', 'IMAGE_STRUCTURE') is None got_cs = fourth_band.Checksum() - if got_cs != 8527: - gdaltest.post_reason('fail') - print(got_cs) - return 'fail' + assert got_cs == 8527 jp2_bands_data = ds.ReadRaster(0, 0, ds.RasterXSize, ds.RasterYSize) jp2_fourth_band_data = fourth_band.ReadRaster(0, 0, ds.RasterXSize, ds.RasterYSize) fourth_band.ReadRaster(0, 0, ds.RasterXSize, ds.RasterYSize, int(ds.RasterXSize / 16), int(ds.RasterYSize / 16)) @@ -354,35 +298,24 @@ def jp2openjpeg_11(): # gtiff_fourth_band_subsampled_data = fourth_band.ReadRaster(0,0,ds.RasterXSize,ds.RasterYSize,ds.RasterXSize/16,ds.RasterYSize/16) tmp_ds = None gdal.GetDriverByName('GTiff').Delete('/vsimem/jp2openjpeg_11.tif') - if got_cs != 8527: - gdaltest.post_reason('fail') - print(got_cs) - return 'fail' + assert got_cs == 8527 - if jp2_bands_data != gtiff_bands_data: - gdaltest.post_reason('fail') - return 'fail' + assert jp2_bands_data == gtiff_bands_data - if jp2_fourth_band_data != gtiff_fourth_band_data: - gdaltest.post_reason('fail') - return 'fail' + assert jp2_fourth_band_data == gtiff_fourth_band_data ds = gdal.OpenEx('data/stefan_full_rgba_alpha_1bit.jp2', open_options=['1BIT_ALPHA_PROMOTION=NO']) fourth_band = ds.GetRasterBand(4) - if fourth_band.GetMetadataItem('NBITS', 'IMAGE_STRUCTURE') != '1': - gdaltest.post_reason('fail') - return 'fail' - - return 'success' + assert fourth_band.GetMetadataItem('NBITS', 'IMAGE_STRUCTURE') == '1' ############################################################################### # Check that PAM overrides internal georeferencing (#5279) -def jp2openjpeg_12(): +def test_jp2openjpeg_12(): if gdaltest.jp2openjpeg_drv is None: - return 'skip' + pytest.skip() # Override projection shutil.copy('data/byte.jp2', 'tmp/jp2openjpeg_12.jp2') @@ -399,10 +332,7 @@ def jp2openjpeg_12(): gdaltest.jp2openjpeg_drv.Delete('tmp/jp2openjpeg_12.jp2') - if wkt.find('32631') < 0: - gdaltest.post_reason('fail') - print(wkt) - return 'fail' + assert wkt.find('32631') >= 0 # Override geotransform shutil.copy('data/byte.jp2', 'tmp/jp2openjpeg_12.jp2') @@ -417,21 +347,16 @@ def jp2openjpeg_12(): gdaltest.jp2openjpeg_drv.Delete('tmp/jp2openjpeg_12.jp2') - if gt != (1000, 1, 0, 2000, 0, -1): - gdaltest.post_reason('fail') - print(gt) - return 'fail' - - return 'success' + assert gt == (1000, 1, 0, 2000, 0, -1) ############################################################################### # Check that PAM overrides internal GCPs (#5279) -def jp2openjpeg_13(): +def test_jp2openjpeg_13(): if gdaltest.jp2openjpeg_drv is None: - return 'skip' + pytest.skip() # Create a dataset with GCPs src_ds = gdal.Open('data/rgb_gcp.vrt') @@ -439,24 +364,15 @@ def jp2openjpeg_13(): ds = None src_ds = None - if gdal.VSIStatL('tmp/jp2openjpeg_13.jp2.aux.xml') is not None: - gdaltest.post_reason('fail') - return 'fail' + assert gdal.VSIStatL('tmp/jp2openjpeg_13.jp2.aux.xml') is None ds = gdal.Open('tmp/jp2openjpeg_13.jp2') count = ds.GetGCPCount() gcps = ds.GetGCPs() wkt = ds.GetGCPProjection() - if count != 4: - gdaltest.post_reason('fail') - return 'fail' - if len(gcps) != 4: - gdaltest.post_reason('fail') - return 'fail' - if wkt.find('4326') < 0: - gdaltest.post_reason('fail') - print(wkt) - return 'fail' + assert count == 4 + assert len(gcps) == 4 + assert wkt.find('4326') >= 0 ds = None # Override GCP @@ -475,43 +391,30 @@ def jp2openjpeg_13(): gdaltest.jp2openjpeg_drv.Delete('tmp/jp2openjpeg_13.jp2') - if count != 1: - gdaltest.post_reason('fail') - return 'fail' - if len(gcps) != 1: - gdaltest.post_reason('fail') - return 'fail' - if wkt.find('32631') < 0: - gdaltest.post_reason('fail') - print(wkt) - return 'fail' - - return 'success' + assert count == 1 + assert len(gcps) == 1 + assert wkt.find('32631') >= 0 ############################################################################### # Check that we get GCPs even there's no projection info -def jp2openjpeg_14(): +def test_jp2openjpeg_14(): if gdaltest.jp2openjpeg_drv is None: - return 'skip' + pytest.skip() ds = gdal.Open('data/byte_2gcps.jp2') - if ds.GetGCPCount() != 2: - gdaltest.post_reason('fail') - return 'fail' - - return 'success' + assert ds.GetGCPCount() == 2 ############################################################################### # Test multi-threading reading -def jp2openjpeg_15(): +def test_jp2openjpeg_15(): if gdaltest.jp2openjpeg_drv is None: - return 'skip' + pytest.skip() src_ds = gdal.GetDriverByName('MEM').Create('', 256, 256) src_ds.GetRasterBand(1).Fill(255) @@ -521,33 +424,26 @@ def jp2openjpeg_15(): got_data = ds.ReadRaster() ds = None gdaltest.jp2openjpeg_drv.Delete('/vsimem/jp2openjpeg_15.jp2') - if got_data != data: - return 'fail' - - return 'success' + assert got_data == data ############################################################################### # Test reading PixelIsPoint file (#5437) -def jp2openjpeg_16(): +def test_jp2openjpeg_16(): if gdaltest.jp2openjpeg_drv is None: - return 'skip' + pytest.skip() ds = gdal.Open('data/byte_point.jp2') gt = ds.GetGeoTransform() - if ds.GetMetadataItem('AREA_OR_POINT') != 'Point': - gdaltest.post_reason('did not get AREA_OR_POINT = Point') - return 'fail' + assert ds.GetMetadataItem('AREA_OR_POINT') == 'Point', \ + 'did not get AREA_OR_POINT = Point' ds = None 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') @@ -559,58 +455,46 @@ def jp2openjpeg_16(): 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' - - return 'success' + assert gt == gt_expected, \ + 'did not get expected geotransform with GTIFF_POINT_GEO_IGNORE TRUE' ############################################################################### # Test writing PixelIsPoint file (#5437) -def jp2openjpeg_17(): +def test_jp2openjpeg_17(): if gdaltest.jp2openjpeg_drv is None: - return 'skip' + pytest.skip() src_ds = gdal.Open('data/byte_point.jp2') ds = gdaltest.jp2openjpeg_drv.CreateCopy('/vsimem/jp2openjpeg_17.jp2', src_ds) ds = None src_ds = None - if gdal.VSIStatL('/vsimem/jp2openjpeg_17.jp2.aux.xml') is not None: - gdaltest.post_reason('fail') - return 'fail' + assert gdal.VSIStatL('/vsimem/jp2openjpeg_17.jp2.aux.xml') is None ds = gdal.Open('/vsimem/jp2openjpeg_17.jp2') gt = ds.GetGeoTransform() - if ds.GetMetadataItem('AREA_OR_POINT') != 'Point': - gdaltest.post_reason('did not get AREA_OR_POINT = Point') - return 'fail' + assert ds.GetMetadataItem('AREA_OR_POINT') == 'Point', \ + 'did not get AREA_OR_POINT = Point' ds = None 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.Unlink('/vsimem/jp2openjpeg_17.jp2') - return 'success' - ############################################################################### # Test when using the decode_area API when one dimension of the dataset is not a # multiple of 1024 (#5480) -def jp2openjpeg_18(): +def test_jp2openjpeg_18(): if gdaltest.jp2openjpeg_drv is None: - return 'skip' + pytest.skip() src_ds = gdal.GetDriverByName('Mem').Create('', 2000, 2000) ds = gdaltest.jp2openjpeg_drv.CreateCopy('/vsimem/jp2openjpeg_18.jp2', src_ds, options=['BLOCKXSIZE=2000', 'BLOCKYSIZE=2000']) @@ -619,48 +503,39 @@ def jp2openjpeg_18(): ds = gdal.Open('/vsimem/jp2openjpeg_18.jp2') ds.GetRasterBand(1).Checksum() - if gdal.GetLastErrorMsg() != '': - gdaltest.post_reason('fail') - return 'fail' + assert gdal.GetLastErrorMsg() == '' ds = None gdal.Unlink('/vsimem/jp2openjpeg_18.jp2') - return 'success' - ############################################################################### # Test reading file where GMLJP2 has nul character instead of \n (#5760) -def jp2openjpeg_19(): +def test_jp2openjpeg_19(): if gdaltest.jp2openjpeg_drv is None: - return 'skip' + pytest.skip() ds = gdal.Open('data/byte_gmljp2_with_nul_car.jp2') - if ds.GetProjectionRef() == '': - gdaltest.post_reason('fail') - return 'fail' + assert ds.GetProjectionRef() != '' ds = None - return 'success' - ############################################################################### # Validate GMLJP2 content against schema -def jp2openjpeg_20(): +def test_jp2openjpeg_20(): if gdaltest.jp2openjpeg_drv is None: - return 'skip' + pytest.skip() try: import xmlvalidate except ImportError: - print('Cannot import xmlvalidate') import traceback traceback.print_exc(file=sys.stdout) - return 'skip' + pytest.skip('Cannot import xmlvalidate') try: os.stat('tmp/cache/SCHEMAS_OPENGIS_NET.zip') @@ -671,8 +546,7 @@ def jp2openjpeg_20(): except OSError: url = 'http://schemas.opengis.net/SCHEMAS_OPENGIS_NET.zip' if not gdaltest.download_file(url, 'SCHEMAS_OPENGIS_NET.zip', force_download=True, max_download_duration=20): - print('Cannot get SCHEMAS_OPENGIS_NET.zip') - return 'skip' + pytest.skip('Cannot get SCHEMAS_OPENGIS_NET.zip') try: os.mkdir('tmp/cache/SCHEMAS_OPENGIS_NET') @@ -691,8 +565,7 @@ def jp2openjpeg_20(): if not gdaltest.download_file(xlink_xsd_url, 'SCHEMAS_OPENGIS_NET/xlink.xsd', force_download=True, max_download_duration=10): xlink_xsd_url = 'http://even.rouault.free.fr/xlink.xsd' if not gdaltest.download_file(xlink_xsd_url, 'SCHEMAS_OPENGIS_NET/xlink.xsd', force_download=True, max_download_duration=10): - print('Cannot get xlink.xsd') - return 'skip' + pytest.skip('Cannot get xlink.xsd') try: os.stat('tmp/cache/SCHEMAS_OPENGIS_NET/xml.xsd') @@ -701,8 +574,7 @@ def jp2openjpeg_20(): if not gdaltest.download_file(xlink_xsd_url, 'SCHEMAS_OPENGIS_NET/xml.xsd', force_download=True, max_download_duration=10): xlink_xsd_url = 'http://even.rouault.free.fr/xml.xsd' if not gdaltest.download_file(xlink_xsd_url, 'SCHEMAS_OPENGIS_NET/xml.xsd', force_download=True, max_download_duration=10): - print('Cannot get xml.xsd') - return 'skip' + pytest.skip('Cannot get xml.xsd') xmlvalidate.transform_abs_links_to_ref_links('tmp/cache/SCHEMAS_OPENGIS_NET') @@ -712,19 +584,16 @@ def jp2openjpeg_20(): ds = None gdal.Unlink('/vsimem/jp2openjpeg_20.jp2') - if not xmlvalidate.validate(gmljp2, ogc_schemas_location='tmp/cache/SCHEMAS_OPENGIS_NET'): - return 'fail' - - return 'success' + assert xmlvalidate.validate(gmljp2, ogc_schemas_location='tmp/cache/SCHEMAS_OPENGIS_NET') ############################################################################### # Test YCC=NO creation option -def jp2openjpeg_21(): +def test_jp2openjpeg_21(): if gdaltest.jp2openjpeg_drv is None: - return 'skip' + pytest.skip() src_ds = gdal.Open('data/rgbsmall.tif') out_ds = gdaltest.jp2openjpeg_drv.CreateCopy('/vsimem/jp2openjpeg_21.jp2', src_ds, options=['QUALITY=100', 'REVERSIBLE=YES', 'YCC=NO']) @@ -734,20 +603,16 @@ def jp2openjpeg_21(): gdal.Unlink('/vsimem/jp2openjpeg_21.jp2') # Quite a bit of difference... - if maxdiff > 1: - gdaltest.post_reason('Image too different from reference') - return 'fail' - - return 'success' + assert maxdiff <= 1, 'Image too different from reference' ############################################################################### # Test RGBA support -def jp2openjpeg_22(): +def test_jp2openjpeg_22(): if gdaltest.jp2openjpeg_drv is None: - return 'skip' + pytest.skip() # RGBA src_ds = gdal.Open('../gcore/data/stefan_full_rgba.tif') @@ -755,48 +620,29 @@ def jp2openjpeg_22(): maxdiff = gdaltest.compare_ds(src_ds, out_ds) del out_ds src_ds = None - if gdal.VSIStatL('/vsimem/jp2openjpeg_22.jp2.aux.xml') is not None: - gdaltest.post_reason('fail') - return 'fail' + assert gdal.VSIStatL('/vsimem/jp2openjpeg_22.jp2.aux.xml') is None ds = gdal.Open('/vsimem/jp2openjpeg_22.jp2') - 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_BlueBand: - gdaltest.post_reason('fail') - return 'fail' - if ds.GetRasterBand(4).GetColorInterpretation() != gdal.GCI_AlphaBand: - 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_BlueBand + assert ds.GetRasterBand(4).GetColorInterpretation() == gdal.GCI_AlphaBand ds = None gdal.Unlink('/vsimem/jp2openjpeg_22.jp2') - if maxdiff > 0: - gdaltest.post_reason('Image too different from reference') - return 'fail' + assert maxdiff <= 0, 'Image too different from reference' # RGBA with 1BIT_ALPHA=YES src_ds = gdal.Open('../gcore/data/stefan_full_rgba.tif') out_ds = gdaltest.jp2openjpeg_drv.CreateCopy('/vsimem/jp2openjpeg_22.jp2', src_ds, options=['1BIT_ALPHA=YES']) del out_ds src_ds = None - if gdal.VSIStatL('/vsimem/jp2openjpeg_22.jp2.aux.xml') is not None: - gdaltest.post_reason('fail') - return 'fail' + assert gdal.VSIStatL('/vsimem/jp2openjpeg_22.jp2.aux.xml') is None ds = gdal.OpenEx('/vsimem/jp2openjpeg_22.jp2', open_options=['1BIT_ALPHA_PROMOTION=NO']) fourth_band = ds.GetRasterBand(4) - if fourth_band.GetMetadataItem('NBITS', 'IMAGE_STRUCTURE') != '1': - gdaltest.post_reason('fail') - return 'fail' + assert fourth_band.GetMetadataItem('NBITS', 'IMAGE_STRUCTURE') == '1' ds = None ds = gdal.Open('/vsimem/jp2openjpeg_22.jp2') - if ds.GetRasterBand(4).Checksum() != 23120: - gdaltest.post_reason('fail') - print(ds.GetRasterBand(4).Checksum()) - return 'fail' + assert ds.GetRasterBand(4).Checksum() == 23120 ds = None gdal.Unlink('/vsimem/jp2openjpeg_22.jp2') @@ -805,26 +651,13 @@ def jp2openjpeg_22(): out_ds = gdaltest.jp2openjpeg_drv.CreateCopy('/vsimem/jp2openjpeg_22.jp2', src_ds, options=['YCBCR420=YES']) del out_ds src_ds = None - if gdal.VSIStatL('/vsimem/jp2openjpeg_22.jp2.aux.xml') is not None: - gdaltest.post_reason('fail') - return 'fail' + assert gdal.VSIStatL('/vsimem/jp2openjpeg_22.jp2.aux.xml') is None ds = gdal.Open('/vsimem/jp2openjpeg_22.jp2') - 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_BlueBand: - gdaltest.post_reason('fail') - return 'fail' - if ds.GetRasterBand(4).GetColorInterpretation() != gdal.GCI_AlphaBand: - gdaltest.post_reason('fail') - return 'fail' - if ds.GetRasterBand(1).Checksum() not in [11457, 11450]: - gdaltest.post_reason('fail') - print(ds.GetRasterBand(1).Checksum()) - 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_BlueBand + assert ds.GetRasterBand(4).GetColorInterpretation() == gdal.GCI_AlphaBand + assert ds.GetRasterBand(1).Checksum() in [11457, 11450] ds = None gdal.Unlink('/vsimem/jp2openjpeg_22.jp2') @@ -835,14 +668,10 @@ def jp2openjpeg_22(): maxdiff = gdaltest.compare_ds(src_ds, out_ds) del out_ds src_ds = None - if gdal.VSIStatL('/vsimem/jp2openjpeg_22.jp2.aux.xml') is not None: - gdaltest.post_reason('fail') - return 'fail' + assert gdal.VSIStatL('/vsimem/jp2openjpeg_22.jp2.aux.xml') is None gdal.Unlink('/vsimem/jp2openjpeg_22.jp2') - if maxdiff > 0: - gdaltest.post_reason('Image too different from reference') - return 'fail' + assert maxdiff <= 0, 'Image too different from reference' # RGB,undefined src_ds = gdal.Open('../gcore/data/stefan_full_rgba_photometric_rgb.tif') @@ -850,28 +679,16 @@ def jp2openjpeg_22(): maxdiff = gdaltest.compare_ds(src_ds, out_ds) del out_ds src_ds = None - if gdal.VSIStatL('/vsimem/jp2openjpeg_22.jp2.aux.xml') is not None: - gdaltest.post_reason('fail') - return 'fail' + assert gdal.VSIStatL('/vsimem/jp2openjpeg_22.jp2.aux.xml') is None ds = gdal.Open('/vsimem/jp2openjpeg_22.jp2') - 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_BlueBand: - gdaltest.post_reason('fail') - return 'fail' - if ds.GetRasterBand(4).GetColorInterpretation() != gdal.GCI_Undefined: - 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_BlueBand + assert ds.GetRasterBand(4).GetColorInterpretation() == gdal.GCI_Undefined ds = None gdal.Unlink('/vsimem/jp2openjpeg_22.jp2') - if maxdiff > 0: - gdaltest.post_reason('Image too different from reference') - return 'fail' + assert maxdiff <= 0, 'Image too different from reference' # RGB,undefined with ALPHA=YES src_ds = gdal.Open('../gcore/data/stefan_full_rgba_photometric_rgb.tif') @@ -879,39 +696,25 @@ def jp2openjpeg_22(): maxdiff = gdaltest.compare_ds(src_ds, out_ds) del out_ds src_ds = None - if gdal.VSIStatL('/vsimem/jp2openjpeg_22.jp2.aux.xml') is not None: - gdaltest.post_reason('fail') - return 'fail' + assert gdal.VSIStatL('/vsimem/jp2openjpeg_22.jp2.aux.xml') is None ds = gdal.Open('/vsimem/jp2openjpeg_22.jp2') - 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_BlueBand: - gdaltest.post_reason('fail') - return 'fail' - if ds.GetRasterBand(4).GetColorInterpretation() != gdal.GCI_AlphaBand: - 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_BlueBand + assert ds.GetRasterBand(4).GetColorInterpretation() == gdal.GCI_AlphaBand ds = None gdal.Unlink('/vsimem/jp2openjpeg_22.jp2') - if maxdiff > 0: - gdaltest.post_reason('Image too different from reference') - return 'fail' - - return 'success' + assert maxdiff <= 0, 'Image too different from reference' ############################################################################### # Test NBITS support -def jp2openjpeg_23(): +def test_jp2openjpeg_23(): if gdaltest.jp2openjpeg_drv is None: - return 'skip' + pytest.skip() src_ds = gdal.Open('../gcore/data/uint16.tif') out_ds = gdaltest.jp2openjpeg_drv.CreateCopy('/vsimem/jp2openjpeg_23.jp2', src_ds, options=['NBITS=9', 'QUALITY=100', 'REVERSIBLE=YES']) @@ -919,37 +722,27 @@ def jp2openjpeg_23(): del out_ds src_ds = None ds = gdal.Open('/vsimem/jp2openjpeg_23.jp2') - if ds.GetRasterBand(1).GetMetadataItem('NBITS', 'IMAGE_STRUCTURE') != '9': - gdaltest.post_reason('failure') - return 'fail' + assert ds.GetRasterBand(1).GetMetadataItem('NBITS', 'IMAGE_STRUCTURE') == '9' out_ds = gdaltest.jp2openjpeg_drv.CreateCopy('/vsimem/jp2openjpeg_23_2.jp2', ds) - if out_ds.GetRasterBand(1).GetMetadataItem('NBITS', 'IMAGE_STRUCTURE') != '9': - gdaltest.post_reason('failure') - return 'fail' + assert out_ds.GetRasterBand(1).GetMetadataItem('NBITS', 'IMAGE_STRUCTURE') == '9' del out_ds ds = None - if gdal.VSIStatL('/vsimem/jp2openjpeg_23.jp2.aux.xml') is not None: - gdaltest.post_reason('fail') - return 'fail' + assert gdal.VSIStatL('/vsimem/jp2openjpeg_23.jp2.aux.xml') is None gdal.Unlink('/vsimem/jp2openjpeg_23.jp2') gdal.Unlink('/vsimem/jp2openjpeg_23_2.jp2') - if maxdiff > 1: - gdaltest.post_reason('Image too different from reference') - return 'fail' - - return 'success' + assert maxdiff <= 1, 'Image too different from reference' ############################################################################### # Test Grey+alpha support -def jp2openjpeg_24(): +def test_jp2openjpeg_24(): if gdaltest.jp2openjpeg_drv is None: - return 'skip' + pytest.skip() # Grey+alpha src_ds = gdal.Open('../gcore/data/stefan_full_greyalpha.tif') @@ -957,64 +750,40 @@ def jp2openjpeg_24(): maxdiff = gdaltest.compare_ds(src_ds, out_ds) del out_ds src_ds = None - if gdal.VSIStatL('/vsimem/jp2openjpeg_24.jp2.aux.xml') is not None: - gdaltest.post_reason('fail') - return 'fail' + assert gdal.VSIStatL('/vsimem/jp2openjpeg_24.jp2.aux.xml') is None ds = gdal.Open('/vsimem/jp2openjpeg_24.jp2') - if ds.GetRasterBand(1).GetColorInterpretation() != gdal.GCI_GrayIndex: - gdaltest.post_reason('fail') - return 'fail' - if ds.GetRasterBand(2).GetColorInterpretation() != gdal.GCI_AlphaBand: - gdaltest.post_reason('fail') - return 'fail' + assert ds.GetRasterBand(1).GetColorInterpretation() == gdal.GCI_GrayIndex + assert ds.GetRasterBand(2).GetColorInterpretation() == gdal.GCI_AlphaBand ds = None gdal.Unlink('/vsimem/jp2openjpeg_24.jp2') - if maxdiff > 0: - gdaltest.post_reason('Image too different from reference') - return 'fail' + assert maxdiff <= 0, 'Image too different from reference' # Grey+alpha with 1BIT_ALPHA=YES src_ds = gdal.Open('../gcore/data/stefan_full_greyalpha.tif') out_ds = gdaltest.jp2openjpeg_drv.CreateCopy('/vsimem/jp2openjpeg_24.jp2', src_ds, options=['1BIT_ALPHA=YES']) del out_ds src_ds = None - if gdal.VSIStatL('/vsimem/jp2openjpeg_24.jp2.aux.xml') is not None: - gdaltest.post_reason('fail') - return 'fail' + assert gdal.VSIStatL('/vsimem/jp2openjpeg_24.jp2.aux.xml') is None ds = gdal.OpenEx('/vsimem/jp2openjpeg_24.jp2', open_options=['1BIT_ALPHA_PROMOTION=NO']) - if ds.GetRasterBand(1).GetColorInterpretation() != gdal.GCI_GrayIndex: - gdaltest.post_reason('fail') - return 'fail' - if ds.GetRasterBand(2).GetColorInterpretation() != gdal.GCI_AlphaBand: - gdaltest.post_reason('fail') - return 'fail' - if ds.GetRasterBand(2).GetMetadataItem('NBITS', 'IMAGE_STRUCTURE') != '1': - gdaltest.post_reason('fail') - return 'fail' + assert ds.GetRasterBand(1).GetColorInterpretation() == gdal.GCI_GrayIndex + assert ds.GetRasterBand(2).GetColorInterpretation() == gdal.GCI_AlphaBand + assert ds.GetRasterBand(2).GetMetadataItem('NBITS', 'IMAGE_STRUCTURE') == '1' ds = None ds = gdal.Open('/vsimem/jp2openjpeg_24.jp2') - if ds.GetRasterBand(2).GetMetadataItem('NBITS', 'IMAGE_STRUCTURE') is not None: - gdaltest.post_reason('fail') - print(ds.GetRasterBand(2).GetMetadataItem('NBITS', 'IMAGE_STRUCTURE')) - return 'fail' - if ds.GetRasterBand(2).Checksum() != 23120: - gdaltest.post_reason('fail') - print(ds.GetRasterBand(2).Checksum()) - return 'fail' + assert ds.GetRasterBand(2).GetMetadataItem('NBITS', 'IMAGE_STRUCTURE') is None + assert ds.GetRasterBand(2).Checksum() == 23120 ds = None gdal.Unlink('/vsimem/jp2openjpeg_24.jp2') - return 'success' - ############################################################################### # Test multiband support -def jp2openjpeg_25(): +def test_jp2openjpeg_25(): if gdaltest.jp2openjpeg_drv is None: - return 'skip' + pytest.skip() src_ds = gdal.GetDriverByName('MEM').Create('', 100, 100, 5) src_ds.GetRasterBand(1).Fill(255) @@ -1028,21 +797,13 @@ def jp2openjpeg_25(): del out_ds src_ds = None ds = gdal.Open('/vsimem/jp2openjpeg_25.jp2') - if ds.GetRasterBand(1).GetColorInterpretation() != gdal.GCI_Undefined: - gdaltest.post_reason('fail') - return 'fail' + assert ds.GetRasterBand(1).GetColorInterpretation() == gdal.GCI_Undefined ds = None - if gdal.VSIStatL('/vsimem/jp2openjpeg_25.jp2.aux.xml') is not None: - gdaltest.post_reason('fail') - return 'fail' + assert gdal.VSIStatL('/vsimem/jp2openjpeg_25.jp2.aux.xml') is None gdal.Unlink('/vsimem/jp2openjpeg_25.jp2') - if maxdiff > 0: - gdaltest.post_reason('Image too different from reference') - return 'fail' - - return 'success' + assert maxdiff <= 0, 'Image too different from reference' ############################################################################### @@ -1052,8 +813,7 @@ def validate(filename, expected_gmljp2=True, return_error_count=False, oidoc=Non try: import validate_jp2 except ImportError: - print('Cannot run validate_jp2') - return 'skip' + pytest.skip('Cannot run validate_jp2') try: os.stat('tmp/cache/SCHEMAS_OPENGIS_NET') @@ -1074,17 +834,17 @@ def validate(filename, expected_gmljp2=True, return_error_count=False, oidoc=Non if return_error_count: return (res.error_count, res.warning_count) if res.error_count == 0 and res.warning_count == 0: - return 'success' - return 'fail' + return + pytest.fail() ############################################################################### # Test INSPIRE_TG support -def jp2openjpeg_26(): +def test_jp2openjpeg_26(): if gdaltest.jp2openjpeg_drv is None: - return 'skip' + pytest.skip() src_ds = gdal.GetDriverByName('MEM').Create('', 2048, 2048, 1) sr = osr.SpatialReference() @@ -1097,46 +857,26 @@ def jp2openjpeg_26(): overview_count = out_ds.GetRasterBand(1).GetOverviewCount() # We have 2x2 1024x1024 tiles. Each of them can be reconstructed down to 128x128. # So for full raster the smallest overview is 2*128 - if out_ds.GetRasterBand(1).GetOverview(overview_count - 1).XSize != 2 * 128 or \ - out_ds.GetRasterBand(1).GetOverview(overview_count - 1).YSize != 2 * 128: - print(out_ds.GetRasterBand(1).GetOverview(overview_count - 1).XSize) - print(out_ds.GetRasterBand(1).GetOverview(overview_count - 1).YSize) - gdaltest.post_reason('fail') - return 'fail' + assert (out_ds.GetRasterBand(1).GetOverview(overview_count - 1).XSize == 2 * 128 and \ + out_ds.GetRasterBand(1).GetOverview(overview_count - 1).YSize == 2 * 128) out_ds = None - if gdal.VSIStatL('/vsimem/jp2openjpeg_26.jp2.aux.xml') is not None: - gdaltest.post_reason('fail') - return 'fail' - if validate('/vsimem/jp2openjpeg_26.jp2') == 'fail': - gdaltest.post_reason('fail') - return 'fail' + assert gdal.VSIStatL('/vsimem/jp2openjpeg_26.jp2.aux.xml') is None + assert validate('/vsimem/jp2openjpeg_26.jp2') != 'fail' gdal.Unlink('/vsimem/jp2openjpeg_26.jp2') # Nominal case: untiled out_ds = gdaltest.jp2openjpeg_drv.CreateCopy('/vsimem/jp2openjpeg_26.jp2', src_ds, options=['INSPIRE_TG=YES', 'BLOCKXSIZE=2048', 'BLOCKYSIZE=2048']) overview_count = out_ds.GetRasterBand(1).GetOverviewCount() - if out_ds.GetRasterBand(1).GetOverview(overview_count - 1).XSize != 128 or \ - out_ds.GetRasterBand(1).GetOverview(overview_count - 1).YSize != 128: - print(out_ds.GetRasterBand(1).GetOverview(overview_count - 1).XSize) - print(out_ds.GetRasterBand(1).GetOverview(overview_count - 1).YSize) - gdaltest.post_reason('fail') - return 'fail' + assert (out_ds.GetRasterBand(1).GetOverview(overview_count - 1).XSize == 128 and \ + out_ds.GetRasterBand(1).GetOverview(overview_count - 1).YSize == 128) gdal.ErrorReset() out_ds.GetRasterBand(1).Checksum() - if gdal.GetLastErrorMsg() != '': - gdaltest.post_reason('fail') - return 'fail' + assert gdal.GetLastErrorMsg() == '' out_ds.GetRasterBand(1).GetOverview(0).Checksum() - if gdal.GetLastErrorMsg() != '': - gdaltest.post_reason('fail') - return 'fail' + assert gdal.GetLastErrorMsg() == '' out_ds = None - if gdal.VSIStatL('/vsimem/jp2openjpeg_26.jp2.aux.xml') is not None: - gdaltest.post_reason('fail') - return 'fail' - if validate('/vsimem/jp2openjpeg_26.jp2') == 'fail': - gdaltest.post_reason('fail') - return 'fail' + assert gdal.VSIStatL('/vsimem/jp2openjpeg_26.jp2.aux.xml') is None + assert validate('/vsimem/jp2openjpeg_26.jp2') != 'fail' gdal.Unlink('/vsimem/jp2openjpeg_26.jp2') # Nominal case: RGBA @@ -1146,19 +886,11 @@ def jp2openjpeg_26(): out_ds = gdaltest.jp2openjpeg_drv.CreateCopy('/vsimem/jp2openjpeg_26.jp2', src_ds, options=['INSPIRE_TG=YES', 'ALPHA=YES']) out_ds = None ds = gdal.OpenEx('/vsimem/jp2openjpeg_26.jp2', open_options=['1BIT_ALPHA_PROMOTION=NO']) - if ds.GetRasterBand(4).GetColorInterpretation() != gdal.GCI_AlphaBand: - gdaltest.post_reason('fail') - return 'fail' - if ds.GetRasterBand(4).GetMetadataItem('NBITS', 'IMAGE_STRUCTURE') != '1': - gdaltest.post_reason('fail') - return 'fail' - ds = None - if gdal.VSIStatL('/vsimem/jp2openjpeg_26.jp2.aux.xml') is not None: - gdaltest.post_reason('fail') - return 'fail' - if validate('/vsimem/jp2openjpeg_26.jp2') == 'fail': - gdaltest.post_reason('fail') - return 'fail' + assert ds.GetRasterBand(4).GetColorInterpretation() == gdal.GCI_AlphaBand + assert ds.GetRasterBand(4).GetMetadataItem('NBITS', 'IMAGE_STRUCTURE') == '1' + ds = None + assert gdal.VSIStatL('/vsimem/jp2openjpeg_26.jp2.aux.xml') is None + assert validate('/vsimem/jp2openjpeg_26.jp2') != 'fail' gdal.Unlink('/vsimem/jp2openjpeg_26.jp2') # Warning case: disabling JPX @@ -1166,49 +898,31 @@ def jp2openjpeg_26(): gdal.PushErrorHandler() out_ds = gdaltest.jp2openjpeg_drv.CreateCopy('/vsimem/jp2openjpeg_26.jp2', src_ds, options=['INSPIRE_TG=YES', 'JPX=NO']) gdal.PopErrorHandler() - if gdal.GetLastErrorMsg() == '': - gdaltest.post_reason('fail') - return 'fail' + assert gdal.GetLastErrorMsg() != '' out_ds = None - if gdal.VSIStatL('/vsimem/jp2openjpeg_26.jp2.aux.xml') is not None: - gdaltest.post_reason('fail') - return 'fail' + assert gdal.VSIStatL('/vsimem/jp2openjpeg_26.jp2.aux.xml') is None res = validate('/vsimem/jp2openjpeg_26.jp2', return_error_count=True) - if res != 'skip' and res != (2, 0): - gdaltest.post_reason('fail') - return 'fail' + assert res == 'skip' or res == (2, 0) gdal.Unlink('/vsimem/jp2openjpeg_26.jp2') # Bilevel (1 bit) src_ds = gdal.GetDriverByName('MEM').Create('', 128, 128, 1) src_ds.GetRasterBand(1).SetMetadataItem('NBITS', '1', 'IMAGE_STRUCTURE') out_ds = gdaltest.jp2openjpeg_drv.CreateCopy('/vsimem/jp2openjpeg_26.jp2', src_ds, options=['INSPIRE_TG=YES']) - if out_ds.GetRasterBand(1).GetMetadataItem('NBITS', 'IMAGE_STRUCTURE') != '1': - gdaltest.post_reason('fail') - return 'fail' - ds = None - if gdal.VSIStatL('/vsimem/jp2openjpeg_26.jp2.aux.xml') is not None: - gdaltest.post_reason('fail') - return 'fail' - if validate('/vsimem/jp2openjpeg_26.jp2', expected_gmljp2=False) == 'fail': - gdaltest.post_reason('fail') - return 'fail' + assert out_ds.GetRasterBand(1).GetMetadataItem('NBITS', 'IMAGE_STRUCTURE') == '1' + ds = None + assert gdal.VSIStatL('/vsimem/jp2openjpeg_26.jp2.aux.xml') is None + assert validate('/vsimem/jp2openjpeg_26.jp2', expected_gmljp2=False) != 'fail' gdal.Unlink('/vsimem/jp2openjpeg_26.jp2') # Auto-promotion 12->16 bits src_ds = gdal.GetDriverByName('MEM').Create('', 128, 128, 1, gdal.GDT_UInt16) src_ds.GetRasterBand(1).SetMetadataItem('NBITS', '12', 'IMAGE_STRUCTURE') out_ds = gdaltest.jp2openjpeg_drv.CreateCopy('/vsimem/jp2openjpeg_26.jp2', src_ds, options=['INSPIRE_TG=YES']) - if out_ds.GetRasterBand(1).GetMetadataItem('NBITS', 'IMAGE_STRUCTURE') is not None: - gdaltest.post_reason('fail') - return 'fail' - ds = None - if gdal.VSIStatL('/vsimem/jp2openjpeg_26.jp2.aux.xml') is not None: - gdaltest.post_reason('fail') - return 'fail' - if validate('/vsimem/jp2openjpeg_26.jp2', expected_gmljp2=False) == 'fail': - gdaltest.post_reason('fail') - return 'fail' + assert out_ds.GetRasterBand(1).GetMetadataItem('NBITS', 'IMAGE_STRUCTURE') is None + ds = None + assert gdal.VSIStatL('/vsimem/jp2openjpeg_26.jp2.aux.xml') is None + assert validate('/vsimem/jp2openjpeg_26.jp2', expected_gmljp2=False) != 'fail' gdal.Unlink('/vsimem/jp2openjpeg_26.jp2') src_ds = gdal.GetDriverByName('MEM').Create('', 2048, 2048, 1) @@ -1217,41 +931,31 @@ def jp2openjpeg_26(): gdal.PushErrorHandler() out_ds = gdaltest.jp2openjpeg_drv.CreateCopy('/vsimem/jp2openjpeg_26.jp2', src_ds, options=['INSPIRE_TG=YES', 'BLOCKXSIZE=1536', 'BLOCKYSIZE=1536']) gdal.PopErrorHandler() - if out_ds is not None: - gdaltest.post_reason('fail') - return 'fail' + assert out_ds is None # Error case: non square tile gdal.PushErrorHandler() out_ds = gdaltest.jp2openjpeg_drv.CreateCopy('/vsimem/jp2openjpeg_26.jp2', src_ds, options=['INSPIRE_TG=YES', 'BLOCKXSIZE=512', 'BLOCKYSIZE=128']) gdal.PopErrorHandler() - if out_ds is not None: - gdaltest.post_reason('fail') - return 'fail' + assert out_ds is None # Error case: incompatible PROFILE gdal.PushErrorHandler() out_ds = gdaltest.jp2openjpeg_drv.CreateCopy('/vsimem/jp2openjpeg_26.jp2', src_ds, options=['INSPIRE_TG=YES', 'PROFILE=UNRESTRICTED']) gdal.PopErrorHandler() - if out_ds is not None: - gdaltest.post_reason('fail') - return 'fail' + assert out_ds is None # Error case: valid, but too small number of resolutions regarding PROFILE_1 gdal.PushErrorHandler() out_ds = gdaltest.jp2openjpeg_drv.CreateCopy('/vsimem/jp2openjpeg_26.jp2', src_ds, options=['INSPIRE_TG=YES', 'RESOLUTIONS=1']) gdal.PopErrorHandler() - if out_ds is not None: - gdaltest.post_reason('fail') - return 'fail' + assert out_ds is None # Too big resolution number. Will fallback to default one gdal.PushErrorHandler() out_ds = gdaltest.jp2openjpeg_drv.CreateCopy('/vsimem/jp2openjpeg_26.jp2', src_ds, options=['INSPIRE_TG=YES', 'RESOLUTIONS=100']) gdal.PopErrorHandler() - if out_ds is None: - gdaltest.post_reason('fail') - return 'fail' + assert out_ds is not None out_ds = None gdal.Unlink('/vsimem/jp2openjpeg_26.jp2') @@ -1259,42 +963,32 @@ def jp2openjpeg_26(): gdal.PushErrorHandler() out_ds = gdaltest.jp2openjpeg_drv.CreateCopy('/vsimem/jp2openjpeg_26.jp2', src_ds, options=['INSPIRE_TG=YES', 'NBITS=2']) gdal.PopErrorHandler() - if out_ds is not None: - gdaltest.post_reason('fail') - return 'fail' + assert out_ds is None # Error case: unsupported CODEC (J2K) gdal.PushErrorHandler() out_ds = gdaltest.jp2openjpeg_drv.CreateCopy('/vsimem/jp2openjpeg_26.j2k', src_ds, options=['INSPIRE_TG=YES']) gdal.PopErrorHandler() - if out_ds is not None: - gdaltest.post_reason('fail') - return 'fail' + assert out_ds is None # Error case: invalid CODEBLOCK_WIDTH/HEIGHT gdal.PushErrorHandler() out_ds = gdaltest.jp2openjpeg_drv.CreateCopy('/vsimem/jp2openjpeg_26.jp2', src_ds, options=['INSPIRE_TG=YES', 'CODEBLOCK_WIDTH=128', 'CODEBLOCK_HEIGHT=32']) gdal.PopErrorHandler() - if out_ds is not None: - gdaltest.post_reason('fail') - return 'fail' + assert out_ds is None gdal.PushErrorHandler() out_ds = gdaltest.jp2openjpeg_drv.CreateCopy('/vsimem/jp2openjpeg_26.jp2', src_ds, options=['INSPIRE_TG=YES', 'CODEBLOCK_WIDTH=32', 'CODEBLOCK_HEIGHT=128']) gdal.PopErrorHandler() - if out_ds is not None: - gdaltest.post_reason('fail') - return 'fail' - - return 'success' + assert out_ds is None ############################################################################### # Test CreateCopy() from a JPEG2000 with a 2048x2048 tiling -def jp2openjpeg_27(): +def test_jp2openjpeg_27(): if gdaltest.jp2openjpeg_drv is None: - return 'skip' + pytest.skip() # Test optimization in GDALCopyWholeRasterGetSwathSize() # Not sure how we can check that except looking at logs with CPL_DEBUG=GDAL @@ -1309,8 +1003,6 @@ def jp2openjpeg_27(): gdal.Unlink('/vsimem/jp2openjpeg_27.jp2') gdal.Unlink('/vsimem/jp2openjpeg_27.tif') - return 'success' - ############################################################################### # Test CODEBLOCK_WIDTH/_HEIGHT @@ -1377,10 +1069,10 @@ def jp2openjpeg_test_codeblock(filename, codeblock_width, codeblock_height): return True -def jp2openjpeg_28(): +def test_jp2openjpeg_28(): if gdaltest.jp2openjpeg_drv is None: - return 'skip' + pytest.skip() src_ds = gdal.GetDriverByName('MEM').Create('', 10, 10, 1) @@ -1399,27 +1091,23 @@ def jp2openjpeg_28(): out_ds = gdaltest.jp2openjpeg_drv.CreateCopy('/vsimem/jp2openjpeg_28.jp2', src_ds, options=options) gdal.PopErrorHandler() if warning_expected and gdal.GetLastErrorMsg() == '': - gdaltest.post_reason('warning expected') print(options) - return 'fail' + pytest.fail('warning expected') del out_ds if not jp2openjpeg_test_codeblock('/vsimem/jp2openjpeg_28.jp2', expected_cbkw, expected_cbkh): - gdaltest.post_reason('unexpected codeblock size') print(options) - return 'fail' + pytest.fail('unexpected codeblock size') gdal.Unlink('/vsimem/jp2openjpeg_28.jp2') - return 'success' - ############################################################################### # Test TILEPARTS option -def jp2openjpeg_29(): +def test_jp2openjpeg_29(): if gdaltest.jp2openjpeg_drv is None: - return 'skip' + pytest.skip() src_ds = gdal.GetDriverByName('MEM').Create('', 128, 128, 1) @@ -1439,25 +1127,22 @@ def jp2openjpeg_29(): out_ds = gdaltest.jp2openjpeg_drv.CreateCopy('/vsimem/jp2openjpeg_29.jp2', src_ds, options=options) gdal.PopErrorHandler() if warning_expected and gdal.GetLastErrorMsg() == '': - gdaltest.post_reason('warning expected') print(options) - return 'fail' + pytest.fail('warning expected') # Not sure if that could be easily checked del out_ds # print gdal.GetJPEG2000StructureAsString('/vsimem/jp2openjpeg_29.jp2', ['ALL=YES']) gdal.Unlink('/vsimem/jp2openjpeg_29.jp2') - return 'success' - ############################################################################### # Test color table support -def jp2openjpeg_30(): +def test_jp2openjpeg_30(): if gdaltest.jp2openjpeg_drv is None: - return 'skip' + pytest.skip() src_ds = gdal.GetDriverByName('MEM').Create('', 10, 10, 1) ct = gdal.ColorTable() @@ -1479,22 +1164,17 @@ def jp2openjpeg_30(): out_ds = gdaltest.jp2openjpeg_drv.CreateCopy('/vsimem/jp2openjpeg_30.jp2', src_ds, options=options) gdal.PopErrorHandler() if warning_expected and gdal.GetLastErrorMsg() == '': - gdaltest.post_reason('warning expected') print(options) - return 'fail' + pytest.fail('warning expected') ct = out_ds.GetRasterBand(1).GetRasterColorTable() - if ct.GetCount() != 4 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() == 4 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.' del out_ds - if validate('/vsimem/jp2openjpeg_30.jp2', expected_gmljp2=False) == 'fail': - gdaltest.post_reason('fail') - return 'fail' + assert validate('/vsimem/jp2openjpeg_30.jp2', expected_gmljp2=False) != 'fail' gdal.Unlink('/vsimem/jp2openjpeg_30.jp2') @@ -1508,13 +1188,11 @@ def jp2openjpeg_30(): src_ds.GetRasterBand(1).SetRasterColorTable(ct) out_ds = gdaltest.jp2openjpeg_drv.CreateCopy('/vsimem/jp2openjpeg_30.jp2', src_ds) ct = out_ds.GetRasterBand(1).GetRasterColorTable() - if ct.GetCount() != 4 or \ - ct.GetColorEntry(0) != (0, 0, 0, 0) 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() == 4 and \ + ct.GetColorEntry(0) == (0, 0, 0, 0) 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.' del out_ds gdal.Unlink('/vsimem/jp2openjpeg_30.jp2') @@ -1528,13 +1206,11 @@ def jp2openjpeg_30(): src_ds.GetRasterBand(1).SetRasterColorTable(ct) out_ds = gdaltest.jp2openjpeg_drv.CreateCopy('/vsimem/jp2openjpeg_30.jp2', src_ds, options=['CT_COMPONENTS=3']) ct = out_ds.GetRasterBand(1).GetRasterColorTable() - if ct.GetCount() != 4 or \ - ct.GetColorEntry(0) != (0, 0, 0, 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() == 4 and \ + ct.GetColorEntry(0) == (0, 0, 0, 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.' del out_ds gdal.Unlink('/vsimem/jp2openjpeg_30.jp2') @@ -1546,20 +1222,16 @@ def jp2openjpeg_30(): gdal.PushErrorHandler() out_ds = gdaltest.jp2openjpeg_drv.CreateCopy('/vsimem/jp2openjpeg_30.jp2', src_ds) gdal.PopErrorHandler() - if out_ds is not None: - gdaltest.post_reason('fail') - return 'fail' - - return 'success' + assert out_ds is None ############################################################################### # Test unusual band color interpretation order -def jp2openjpeg_31(): +def test_jp2openjpeg_31(): if gdaltest.jp2openjpeg_drv is None: - return 'skip' + pytest.skip() src_ds = gdal.GetDriverByName('MEM').Create('', 10, 10, 3) src_ds.GetRasterBand(1).SetColorInterpretation(gdal.GCI_GreenBand) @@ -1567,20 +1239,11 @@ def jp2openjpeg_31(): src_ds.GetRasterBand(3).SetColorInterpretation(gdal.GCI_RedBand) out_ds = gdaltest.jp2openjpeg_drv.CreateCopy('/vsimem/jp2openjpeg_31.jp2', src_ds) del out_ds - if gdal.VSIStatL('/vsimem/jp2openjpeg_31.jp2.aux.xml') is not None: - gdaltest.post_reason('fail') - return 'fail' + assert gdal.VSIStatL('/vsimem/jp2openjpeg_31.jp2.aux.xml') is None ds = gdal.Open('/vsimem/jp2openjpeg_31.jp2') - if ds.GetRasterBand(1).GetColorInterpretation() != gdal.GCI_GreenBand: - gdaltest.post_reason('fail') - print(ds.GetRasterBand(1).GetColorInterpretation()) - return 'fail' - if ds.GetRasterBand(2).GetColorInterpretation() != gdal.GCI_BlueBand: - 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_GreenBand + assert ds.GetRasterBand(2).GetColorInterpretation() == gdal.GCI_BlueBand + assert ds.GetRasterBand(3).GetColorInterpretation() == gdal.GCI_RedBand ds = None gdal.Unlink('/vsimem/jp2openjpeg_31.jp2') @@ -1592,57 +1255,40 @@ def jp2openjpeg_31(): src_ds.GetRasterBand(4).SetColorInterpretation(gdal.GCI_RedBand) out_ds = gdaltest.jp2openjpeg_drv.CreateCopy('/vsimem/jp2openjpeg_31.jp2', src_ds) del out_ds - if gdal.VSIStatL('/vsimem/jp2openjpeg_31.jp2.aux.xml') is not None: - gdaltest.post_reason('fail') - return 'fail' + assert gdal.VSIStatL('/vsimem/jp2openjpeg_31.jp2.aux.xml') is None ds = gdal.Open('/vsimem/jp2openjpeg_31.jp2') - if ds.GetRasterBand(1).GetColorInterpretation() != gdal.GCI_AlphaBand: - gdaltest.post_reason('fail') - print(ds.GetRasterBand(1).GetColorInterpretation()) - return 'fail' - if ds.GetRasterBand(2).GetColorInterpretation() != gdal.GCI_GreenBand: - gdaltest.post_reason('fail') - return 'fail' - if ds.GetRasterBand(3).GetColorInterpretation() != gdal.GCI_BlueBand: - gdaltest.post_reason('fail') - return 'fail' - if ds.GetRasterBand(4).GetColorInterpretation() != gdal.GCI_RedBand: - gdaltest.post_reason('fail') - return 'fail' + assert ds.GetRasterBand(1).GetColorInterpretation() == gdal.GCI_AlphaBand + assert ds.GetRasterBand(2).GetColorInterpretation() == gdal.GCI_GreenBand + assert ds.GetRasterBand(3).GetColorInterpretation() == gdal.GCI_BlueBand + assert ds.GetRasterBand(4).GetColorInterpretation() == gdal.GCI_RedBand ds = None gdal.Unlink('/vsimem/jp2openjpeg_31.jp2') - return 'success' - ############################################################################### # Test creation of "XLBoxes" for JP2C -def jp2openjpeg_32(): +def test_jp2openjpeg_32(): if gdaltest.jp2openjpeg_drv is None: - return 'skip' + pytest.skip() src_ds = gdal.GetDriverByName('MEM').Create('', 10, 10, 1) gdal.PushErrorHandler() out_ds = gdaltest.jp2openjpeg_drv.CreateCopy('/vsimem/jp2openjpeg_32.jp2', src_ds, options=['JP2C_XLBOX=YES']) gdal.PopErrorHandler() - if out_ds.GetRasterBand(1).Checksum() != 0: - gdaltest.post_reason('fail') - return 'fail' + assert out_ds.GetRasterBand(1).Checksum() == 0 out_ds = None gdal.Unlink('/vsimem/jp2openjpeg_32.jp2') - return 'success' - ############################################################################### # Test crazy tile size -def jp2openjpeg_33(): +def test_jp2openjpeg_33(): if gdaltest.jp2openjpeg_drv is None: - return 'skip' + pytest.skip() src_ds = gdal.Open("""<VRTDataset rasterXSize="100000" rasterYSize="100000"> <VRTRasterBand dataType="Byte" band="1"> @@ -1653,89 +1299,69 @@ def jp2openjpeg_33(): # https://github.com/uclouvain/openjpeg/issues/493 out_ds = gdaltest.jp2openjpeg_drv.CreateCopy('/vsimem/jp2openjpeg_33.jp2', src_ds, options=['BLOCKXSIZE=100000', 'BLOCKYSIZE=100000', 'RESOLUTIONS=5']) gdal.PopErrorHandler() - if out_ds is not None: - gdaltest.post_reason('fail') - return 'fail' + assert out_ds is None out_ds = None gdal.Unlink('/vsimem/jp2openjpeg_33.jp2') - return 'success' - ############################################################################### # Test opening a file whose dimensions are > 2^31-1 -def jp2openjpeg_34(): +def test_jp2openjpeg_34(): if gdaltest.jp2openjpeg_drv is None: - return 'skip' + pytest.skip() gdal.PushErrorHandler() ds = gdal.Open('data/dimensions_above_31bit.jp2') gdal.PopErrorHandler() - if ds is not None: - gdaltest.post_reason('fail') - return 'fail' - - return 'success' + assert ds is None ############################################################################### # Test opening a truncated file -def jp2openjpeg_35(): +def test_jp2openjpeg_35(): if gdaltest.jp2openjpeg_drv is None: - return 'skip' + pytest.skip() gdal.PushErrorHandler() ds = gdal.Open('data/truncated.jp2') gdal.PopErrorHandler() - if ds is not None: - gdaltest.post_reason('fail') - return 'fail' - - return 'success' + assert ds is None ############################################################################### # Test we cannot create files with more than 16384 bands -def jp2openjpeg_36(): +def test_jp2openjpeg_36(): if gdaltest.jp2openjpeg_drv is None: - return 'skip' + pytest.skip() src_ds = gdal.GetDriverByName('MEM').Create('', 2, 2, 16385) gdal.PushErrorHandler() out_ds = gdaltest.jp2openjpeg_drv.CreateCopy('/vsimem/jp2openjpeg_36.jp2', src_ds) gdal.PopErrorHandler() - if out_ds is not None or gdal.VSIStatL('/vsimem/jp2openjpeg_36.jp2') is not None: - gdaltest.post_reason('fail') - return 'fail' - - return 'success' + assert out_ds is None and gdal.VSIStatL('/vsimem/jp2openjpeg_36.jp2') is None ############################################################################### # Test metadata reading & writing -def jp2openjpeg_37(): +def test_jp2openjpeg_37(): if gdaltest.jp2openjpeg_drv is None: - return 'skip' + pytest.skip() # No metadata src_ds = gdal.GetDriverByName('MEM').Create('', 2, 2) out_ds = gdaltest.jp2openjpeg_drv.CreateCopy('/vsimem/jp2openjpeg_37.jp2', src_ds, options=['WRITE_METADATA=YES']) del out_ds - if gdal.VSIStatL('/vsimem/jp2openjpeg_37.jp2.aux.xml') is not None: - gdaltest.post_reason('fail') - return 'fail' + assert gdal.VSIStatL('/vsimem/jp2openjpeg_37.jp2.aux.xml') is None ds = gdal.Open('/vsimem/jp2openjpeg_37.jp2') - if ds.GetMetadata() != {}: - gdaltest.post_reason('fail') - return 'fail' + assert ds.GetMetadata() == {} gdal.Unlink('/vsimem/jp2openjpeg_37.jp2') # Simple metadata in main domain @@ -1744,18 +1370,12 @@ def jp2openjpeg_37(): src_ds.SetMetadataItem('FOO', 'BAR') out_ds = gdaltest.jp2openjpeg_drv.CreateCopy('/vsimem/jp2openjpeg_37.jp2', src_ds, options=options) del out_ds - if gdal.VSIStatL('/vsimem/jp2openjpeg_37.jp2.aux.xml') is not None: - gdaltest.post_reason('fail') - return 'fail' + assert gdal.VSIStatL('/vsimem/jp2openjpeg_37.jp2.aux.xml') is None ds = gdal.Open('/vsimem/jp2openjpeg_37.jp2') - if ds.GetMetadata() != {'FOO': 'BAR'}: - gdaltest.post_reason('fail') - return 'fail' + assert ds.GetMetadata() == {'FOO': 'BAR'} ds = None - if 'INSPIRE_TG=YES' in options and validate('/vsimem/jp2openjpeg_37.jp2', expected_gmljp2=False) == 'fail': - gdaltest.post_reason('fail') - return 'fail' + assert not ('INSPIRE_TG=YES' in options and validate('/vsimem/jp2openjpeg_37.jp2', expected_gmljp2=False) == 'fail') gdal.Unlink('/vsimem/jp2openjpeg_37.jp2') @@ -1764,15 +1384,10 @@ def jp2openjpeg_37(): src_ds.SetMetadataItem('FOO', 'BAR', 'SOME_DOMAIN') out_ds = gdaltest.jp2openjpeg_drv.CreateCopy('/vsimem/jp2openjpeg_37.jp2', src_ds, options=['WRITE_METADATA=YES']) del out_ds - if gdal.VSIStatL('/vsimem/jp2openjpeg_37.jp2.aux.xml') is not None: - gdaltest.post_reason('fail') - return 'fail' + assert gdal.VSIStatL('/vsimem/jp2openjpeg_37.jp2.aux.xml') is None ds = gdal.Open('/vsimem/jp2openjpeg_37.jp2') md = ds.GetMetadata('SOME_DOMAIN') - if md != {'FOO': 'BAR'}: - gdaltest.post_reason('fail') - print(md) - return 'fail' + assert md == {'FOO': 'BAR'} gdal.Unlink('/vsimem/jp2openjpeg_37.jp2') # Simple metadata in auxiliary XML domain @@ -1780,13 +1395,9 @@ def jp2openjpeg_37(): src_ds.SetMetadata(['<some_arbitrary_xml_box/>'], 'xml:SOME_DOMAIN') out_ds = gdaltest.jp2openjpeg_drv.CreateCopy('/vsimem/jp2openjpeg_37.jp2', src_ds, options=['WRITE_METADATA=YES']) del out_ds - if gdal.VSIStatL('/vsimem/jp2openjpeg_37.jp2.aux.xml') is not None: - gdaltest.post_reason('fail') - return 'fail' + assert gdal.VSIStatL('/vsimem/jp2openjpeg_37.jp2.aux.xml') is None ds = gdal.Open('/vsimem/jp2openjpeg_37.jp2') - if ds.GetMetadata('xml:SOME_DOMAIN')[0] != '<some_arbitrary_xml_box />\n': - gdaltest.post_reason('fail') - return 'fail' + assert ds.GetMetadata('xml:SOME_DOMAIN')[0] == '<some_arbitrary_xml_box />\n' gdal.Unlink('/vsimem/jp2openjpeg_37.jp2') # Special xml:BOX_ metadata domain @@ -1795,13 +1406,9 @@ def jp2openjpeg_37(): src_ds.SetMetadata(['<some_arbitrary_xml_box/>'], 'xml:BOX_1') out_ds = gdaltest.jp2openjpeg_drv.CreateCopy('/vsimem/jp2openjpeg_37.jp2', src_ds, options=options) del out_ds - if gdal.VSIStatL('/vsimem/jp2openjpeg_37.jp2.aux.xml') is not None: - gdaltest.post_reason('fail') - return 'fail' + assert gdal.VSIStatL('/vsimem/jp2openjpeg_37.jp2.aux.xml') is None ds = gdal.Open('/vsimem/jp2openjpeg_37.jp2') - if ds.GetMetadata('xml:BOX_0')[0] != '<some_arbitrary_xml_box/>': - gdaltest.post_reason('fail') - return 'fail' + assert ds.GetMetadata('xml:BOX_0')[0] == '<some_arbitrary_xml_box/>' gdal.Unlink('/vsimem/jp2openjpeg_37.jp2') # Special xml:XMP metadata domain @@ -1810,18 +1417,12 @@ def jp2openjpeg_37(): src_ds.SetMetadata(['<fake_xmp_box/>'], 'xml:XMP') out_ds = gdaltest.jp2openjpeg_drv.CreateCopy('/vsimem/jp2openjpeg_37.jp2', src_ds, options=options) del out_ds - if gdal.VSIStatL('/vsimem/jp2openjpeg_37.jp2.aux.xml') is not None: - gdaltest.post_reason('fail') - return 'fail' + assert gdal.VSIStatL('/vsimem/jp2openjpeg_37.jp2.aux.xml') is None ds = gdal.Open('/vsimem/jp2openjpeg_37.jp2') - if ds.GetMetadata('xml:XMP')[0] != '<fake_xmp_box/>': - gdaltest.post_reason('fail') - return 'fail' + assert ds.GetMetadata('xml:XMP')[0] == '<fake_xmp_box/>' ds = None - if 'INSPIRE_TG=YES' in options and validate('/vsimem/jp2openjpeg_37.jp2', expected_gmljp2=False) == 'fail': - gdaltest.post_reason('fail') - return 'fail' + assert not ('INSPIRE_TG=YES' in options and validate('/vsimem/jp2openjpeg_37.jp2', expected_gmljp2=False) == 'fail') gdal.Unlink('/vsimem/jp2openjpeg_37.jp2') @@ -1831,30 +1432,23 @@ def jp2openjpeg_37(): src_ds.SetMetadata(['<fake_ipr_box/>'], 'xml:IPR') out_ds = gdaltest.jp2openjpeg_drv.CreateCopy('/vsimem/jp2openjpeg_37.jp2', src_ds, options=options) del out_ds - if gdal.VSIStatL('/vsimem/jp2openjpeg_37.jp2.aux.xml') is not None: - gdaltest.post_reason('fail') - return 'fail' + assert gdal.VSIStatL('/vsimem/jp2openjpeg_37.jp2.aux.xml') is None ds = gdal.Open('/vsimem/jp2openjpeg_37.jp2') - if ds.GetMetadata('xml:IPR')[0] != '<fake_ipr_box/>': - gdaltest.post_reason('fail') - return 'fail' + assert ds.GetMetadata('xml:IPR')[0] == '<fake_ipr_box/>' ds = None - if validate('/vsimem/jp2openjpeg_37.jp2', expected_gmljp2=False) == 'fail': - gdaltest.post_reason('fail') - return 'fail' + assert validate('/vsimem/jp2openjpeg_37.jp2', expected_gmljp2=False) != 'fail' gdal.Unlink('/vsimem/jp2openjpeg_37.jp2') - return 'success' - + ############################################################################### # Test non-EPSG SRS (so written with a GML dictionary) -def jp2openjpeg_38(): +def test_jp2openjpeg_38(): if gdaltest.jp2openjpeg_drv is None: - return 'skip' + pytest.skip() # No metadata src_ds = gdal.GetDriverByName('MEM').Create('', 2, 2) @@ -1862,10 +1456,7 @@ def jp2openjpeg_38(): src_ds.SetProjection(wkt) src_ds.SetGeoTransform([0, 60, 0, 0, 0, -60]) out_ds = gdaltest.jp2openjpeg_drv.CreateCopy('/vsimem/jp2openjpeg_38.jp2', src_ds, options=['GeoJP2=NO']) - if out_ds.GetProjectionRef() != wkt: - gdaltest.post_reason('fail') - print(out_ds.GetProjectionRef()) - return 'fail' + assert out_ds.GetProjectionRef() == wkt crsdictionary = out_ds.GetMetadata_List("xml:CRSDictionary.gml")[0] out_ds = None gdal.Unlink('/vsimem/jp2openjpeg_38.jp2') @@ -1884,20 +1475,17 @@ def jp2openjpeg_38(): do_validate = False if do_validate: - if not xmlvalidate.validate(crsdictionary, ogc_schemas_location='tmp/cache/SCHEMAS_OPENGIS_NET'): - print(crsdictionary) - return 'fail' - - return 'success' + assert xmlvalidate.validate(crsdictionary, ogc_schemas_location='tmp/cache/SCHEMAS_OPENGIS_NET') + ############################################################################### # Test GMLJP2OVERRIDE configuration option and DGIWG GMLJP2 -def jp2openjpeg_39(): +def test_jp2openjpeg_39(): if gdaltest.jp2openjpeg_drv is None: - return 'skip' + pytest.skip() # No metadata src_ds = gdal.GetDriverByName('MEM').Create('', 20, 20) @@ -1955,23 +1543,18 @@ def jp2openjpeg_39(): gdal.Unlink('/vsimem/override.gml') del out_ds ds = gdal.Open('/vsimem/jp2openjpeg_39.jp2') - if ds.GetProjectionRef().find('4326') < 0: - gdaltest.post_reason('fail') - print(ds.GetProjectionRef()) - return 'fail' + assert ds.GetProjectionRef().find('4326') >= 0 ds = None gdal.Unlink('/vsimem/jp2openjpeg_39.jp2') - return 'success' - ############################################################################### # Test we can parse GMLJP2 v2.0 -def jp2openjpeg_40(): +def test_jp2openjpeg_40(): if gdaltest.jp2openjpeg_drv is None: - return 'skip' + pytest.skip() # No metadata src_ds = gdal.GetDriverByName('MEM').Create('', 20, 20) @@ -2032,41 +1615,29 @@ def jp2openjpeg_40(): gdal.Unlink('/vsimem/override.gml') del out_ds ds = gdal.Open('/vsimem/jp2openjpeg_40.jp2') - if ds.GetProjectionRef().find('4326') < 0: - gdaltest.post_reason('fail') - print(ds.GetProjectionRef()) - return 'fail' + assert ds.GetProjectionRef().find('4326') >= 0 got_gt = ds.GetGeoTransform() expected_gt = (2, 0.1, 0, 49, 0, -0.1) for i in range(6): - if abs(got_gt[i] - expected_gt[i]) > 1e-5: - gdaltest.post_reason('fail') - print(got_gt) - return 'fail' + assert abs(got_gt[i] - expected_gt[i]) <= 1e-5 ds = None gdal.Unlink('/vsimem/jp2openjpeg_40.jp2') - return 'success' - ############################################################################### # Test USE_SRC_CODESTREAM=YES -def jp2openjpeg_41(): +def test_jp2openjpeg_41(): if gdaltest.jp2openjpeg_drv is None: - return 'skip' + pytest.skip() src_ds = gdal.Open('data/byte.jp2') out_ds = gdaltest.jp2openjpeg_drv.CreateCopy('/vsimem/jp2openjpeg_41.jp2', src_ds, options=['USE_SRC_CODESTREAM=YES', 'PROFILE=PROFILE_1', 'GEOJP2=NO', 'GMLJP2=NO']) - if src_ds.GetRasterBand(1).Checksum() != out_ds.GetRasterBand(1).Checksum(): - gdaltest.post_reason('fail') - return 'fail' + assert src_ds.GetRasterBand(1).Checksum() == out_ds.GetRasterBand(1).Checksum() del out_ds - if gdal.VSIStatL('/vsimem/jp2openjpeg_41.jp2').size != 9923: - gdaltest.post_reason('fail') - return 'fail' + assert gdal.VSIStatL('/vsimem/jp2openjpeg_41.jp2').size == 9923 gdal.Unlink('/vsimem/jp2openjpeg_41.jp2') gdal.Unlink('/vsimem/jp2openjpeg_41.jp2.aux.xml') @@ -2077,9 +1648,7 @@ def jp2openjpeg_41(): options=['USE_SRC_CODESTREAM=YES', 'QUALITY=1']) gdal.PopErrorHandler() del out_ds - if gdal.GetLastErrorMsg() == '': - gdaltest.post_reason('fail') - return 'fail' + assert gdal.GetLastErrorMsg() != '' gdal.Unlink('/vsimem/jp2openjpeg_41.jp2') gdal.Unlink('/vsimem/jp2openjpeg_41.jp2.aux.xml') @@ -2091,21 +1660,17 @@ def jp2openjpeg_41(): options=['USE_SRC_CODESTREAM=YES']) gdal.PopErrorHandler() del out_ds - if gdal.GetLastErrorMsg() == '': - gdaltest.post_reason('fail') - return 'fail' + assert gdal.GetLastErrorMsg() != '' gdal.Unlink('/vsimem/jp2openjpeg_41.jp2') - return 'success' - ############################################################################### # Test update of existing file -def jp2openjpeg_42(): +def test_jp2openjpeg_42(): if gdaltest.jp2openjpeg_drv is None: - return 'skip' + pytest.skip() src_ds = gdal.GetDriverByName('MEM').Create('', 20, 20) gdal.PushErrorHandler() @@ -2121,102 +1686,57 @@ def jp2openjpeg_42(): ds = gdal.Open('/vsimem/jp2openjpeg_42.jp2', gdal.GA_Update) ds.SetMetadataItem('FOO', 'BAR') ds = None - if gdal.VSIStatL('/vsimem/jp2openjpeg_42.jp2.aux.xml') is not None: - gdaltest.post_reason('fail') - return 'fail' + assert gdal.VSIStatL('/vsimem/jp2openjpeg_42.jp2.aux.xml') is None # Add metadata and GCP ds = gdal.Open('/vsimem/jp2openjpeg_42.jp2', gdal.GA_Update) - if ds.GetMetadata() != {'FOO': 'BAR'}: - gdaltest.post_reason('fail') - return 'fail' + assert ds.GetMetadata() == {'FOO': 'BAR'} sr = osr.SpatialReference() sr.ImportFromEPSG(32631) gcps = [gdal.GCP(0, 1, 2, 3, 4)] ds.SetGCPs(gcps, sr.ExportToWkt()) ds = None - if gdal.VSIStatL('/vsimem/jp2openjpeg_42.jp2.aux.xml') is not None: - gdaltest.post_reason('fail') - return 'fail' + assert gdal.VSIStatL('/vsimem/jp2openjpeg_42.jp2.aux.xml') is None # Check we got metadata and GCP, and there's no GMLJP2 box ds = gdal.Open('/vsimem/jp2openjpeg_42.jp2', gdal.GA_Update) - if ds.GetMetadata() != {'FOO': 'BAR'}: - gdaltest.post_reason('fail') - return 'fail' - if ds.GetGCPCount() != 1: - gdaltest.post_reason('fail') - return 'fail' - if len(ds.GetMetadataDomainList()) != 2: - gdaltest.post_reason('fail') - print(ds.GetMetadataDomainList()) - return 'fail' + assert ds.GetMetadata() == {'FOO': 'BAR'} + assert ds.GetGCPCount() == 1 + assert len(ds.GetMetadataDomainList()) == 2 # Unset metadata and GCP ds.SetMetadata(None) ds.SetGCPs([], '') ds = None - if gdal.VSIStatL('/vsimem/jp2openjpeg_42.jp2.aux.xml') is not None: - gdaltest.post_reason('fail') - return 'fail' + assert gdal.VSIStatL('/vsimem/jp2openjpeg_42.jp2.aux.xml') is None # Check we have no longer metadata or GCP ds = gdal.Open('/vsimem/jp2openjpeg_42.jp2', gdal.GA_Update) - if ds.GetMetadata() != {}: - print(ds.GetMetadata()) - gdaltest.post_reason('fail') - return 'fail' - if ds.GetGCPCount() != 0: - gdaltest.post_reason('fail') - return 'fail' - if ds.GetMetadataDomainList() != ['DERIVED_SUBDATASETS']: - gdaltest.post_reason('fail') - print(ds.GetMetadataDomainList()) - return 'fail' + assert ds.GetMetadata() == {} + assert ds.GetGCPCount() == 0 + assert ds.GetMetadataDomainList() == ['DERIVED_SUBDATASETS'] # Add projection and geotransform ds.SetProjection(sr.ExportToWkt()) ds.SetGeoTransform([0, 1, 2, 3, 4, 5]) ds = None - if gdal.VSIStatL('/vsimem/jp2openjpeg_42.jp2.aux.xml') is not None: - gdaltest.post_reason('fail') - return 'fail' + assert gdal.VSIStatL('/vsimem/jp2openjpeg_42.jp2.aux.xml') is None # Check them ds = gdal.Open('/vsimem/jp2openjpeg_42.jp2', gdal.GA_Update) - if ds.GetProjectionRef().find('32631') < 0: - gdaltest.post_reason('fail') - print(ds.GetProjectionRef()) - return 'fail' - if ds.GetGeoTransform() != (0, 1, 2, 3, 4, 5): - gdaltest.post_reason('fail') - print(ds.GetGeoTransform()) - return 'fail' + assert ds.GetProjectionRef().find('32631') >= 0 + assert ds.GetGeoTransform() == (0, 1, 2, 3, 4, 5) # Check that we have a GMLJP2 box - if ds.GetMetadataDomainList() != ['xml:gml.root-instance', 'DERIVED_SUBDATASETS']: - gdaltest.post_reason('fail') - print(ds.GetMetadataDomainList()) - return 'fail' + assert ds.GetMetadataDomainList() == ['xml:gml.root-instance', 'DERIVED_SUBDATASETS'] # Remove projection and geotransform ds.SetProjection('') ds.SetGeoTransform([0, 1, 0, 0, 0, 1]) ds = None - if gdal.VSIStatL('/vsimem/jp2openjpeg_42.jp2.aux.xml') is not None: - gdaltest.post_reason('fail') - return 'fail' + assert gdal.VSIStatL('/vsimem/jp2openjpeg_42.jp2.aux.xml') is None # Check we have no longer anything ds = gdal.Open('/vsimem/jp2openjpeg_42.jp2', gdal.GA_Update) - if ds.GetProjectionRef() != '': - gdaltest.post_reason('fail') - print(ds.GetProjectionRef()) - return 'fail' - if ds.GetGeoTransform() != (0, 1, 0, 0, 0, 1): - gdaltest.post_reason('fail') - print(ds.GetGeoTransform()) - return 'fail' - if ds.GetMetadataDomainList() != ['DERIVED_SUBDATASETS']: - gdaltest.post_reason('fail') - print(ds.GetMetadataDomainList()) - return 'fail' + assert ds.GetProjectionRef() == '' + assert ds.GetGeoTransform() == (0, 1, 0, 0, 0, 1) + assert ds.GetMetadataDomainList() == ['DERIVED_SUBDATASETS'] ds = None # Create file with georef boxes before codestream, and disable GMLJP2 @@ -2230,20 +1750,12 @@ def jp2openjpeg_42(): ds = gdal.Open('/vsimem/jp2openjpeg_42.jp2', gdal.GA_Update) ds.SetGeoTransform([1, 2, 3, 4, 5, 6]) ds = None - if gdal.VSIStatL('/vsimem/jp2openjpeg_42.jp2.aux.xml') is not None: - gdaltest.post_reason('fail') - return 'fail' + assert gdal.VSIStatL('/vsimem/jp2openjpeg_42.jp2.aux.xml') is None # Check it and that we don't have GMLJP2 ds = gdal.Open('/vsimem/jp2openjpeg_42.jp2', gdal.GA_Update) - if ds.GetGeoTransform() != (1, 2, 3, 4, 5, 6): - gdaltest.post_reason('fail') - print(ds.GetGeoTransform()) - return 'fail' - if ds.GetMetadataDomainList() != ['DERIVED_SUBDATASETS']: - gdaltest.post_reason('fail') - print(ds.GetMetadataDomainList()) - return 'fail' + assert ds.GetGeoTransform() == (1, 2, 3, 4, 5, 6) + assert ds.GetMetadataDomainList() == ['DERIVED_SUBDATASETS'] ds = None # Create file with georef boxes before codestream, and disable GeoJP2 @@ -2255,82 +1767,54 @@ def jp2openjpeg_42(): # Modify geotransform ds = gdal.Open('/vsimem/jp2openjpeg_42.jp2', gdal.GA_Update) - if ds.GetGeoTransform() != (2, 3, 0, 4, 0, -5): - gdaltest.post_reason('fail') - print(ds.GetGeoTransform()) - return 'fail' + assert ds.GetGeoTransform() == (2, 3, 0, 4, 0, -5) ds.SetGeoTransform([1, 2, 0, 3, 0, -4]) ds = None - if gdal.VSIStatL('/vsimem/jp2openjpeg_42.jp2.aux.xml') is not None: - gdaltest.post_reason('fail') - return 'fail' + assert gdal.VSIStatL('/vsimem/jp2openjpeg_42.jp2.aux.xml') is None # Check it ds = gdal.Open('/vsimem/jp2openjpeg_42.jp2', gdal.GA_Update) - if ds.GetGeoTransform() != (1, 2, 0, 3, 0, -4): - gdaltest.post_reason('fail') - print(ds.GetGeoTransform()) - return 'fail' - if ds.GetMetadataDomainList() != ['xml:gml.root-instance', 'DERIVED_SUBDATASETS']: - gdaltest.post_reason('fail') - print(ds.GetMetadataDomainList()) - return 'fail' + assert ds.GetGeoTransform() == (1, 2, 0, 3, 0, -4) + assert ds.GetMetadataDomainList() == ['xml:gml.root-instance', 'DERIVED_SUBDATASETS'] # Add GCPs gcps = [gdal.GCP(0, 1, 2, 3, 4)] ds.SetGCPs(gcps, sr.ExportToWkt()) ds = None - if gdal.VSIStatL('/vsimem/jp2openjpeg_42.jp2.aux.xml') is not None: - gdaltest.post_reason('fail') - return 'fail' + assert gdal.VSIStatL('/vsimem/jp2openjpeg_42.jp2.aux.xml') is None # Check it (a GeoJP2 box has been added and GMLJP2 removed) ds = gdal.Open('/vsimem/jp2openjpeg_42.jp2', gdal.GA_Update) - if not ds.GetGCPs(): - gdaltest.post_reason('fail') - return 'fail' - if ds.GetMetadataDomainList() != ['DERIVED_SUBDATASETS']: - gdaltest.post_reason('fail') - print(ds.GetMetadataDomainList()) - return 'fail' + assert ds.GetGCPs() + assert ds.GetMetadataDomainList() == ['DERIVED_SUBDATASETS'] # Add IPR box ds.SetMetadata(['<fake_ipr_box/>'], 'xml:IPR') ds = None - if gdal.VSIStatL('/vsimem/jp2openjpeg_42.jp2.aux.xml') is not None: - gdaltest.post_reason('fail') - return 'fail' + assert gdal.VSIStatL('/vsimem/jp2openjpeg_42.jp2.aux.xml') is None # Check it ds = gdal.Open('/vsimem/jp2openjpeg_42.jp2', gdal.GA_Update) - if ds.GetMetadata('xml:IPR')[0] != '<fake_ipr_box/>': - gdaltest.post_reason('fail') - print(ds.GetMetadata('xml:IPR')) - return 'fail' + assert ds.GetMetadata('xml:IPR')[0] == '<fake_ipr_box/>' ds = None gdal.Unlink('/vsimem/jp2openjpeg_42.jp2') - return 'success' - ############################################################################### # Get structure of a JPEG2000 file -def jp2openjpeg_43(): +def test_jp2openjpeg_43(): ret = gdal.GetJPEG2000StructureAsString('data/byte.jp2', ['ALL=YES']) - if ret is None: - return 'fail' - - return 'success' + assert ret is not None ############################################################################### # Check a file against a OrthoimageryCoverage document -def jp2openjpeg_44(): +def test_jp2openjpeg_44(): if gdaltest.jp2openjpeg_drv is None: - return 'skip' + pytest.skip() src_ds = gdal.Open('data/utm.tif') out_ds = gdaltest.jp2openjpeg_drv.CreateCopy('/vsimem/jp2openjpeg_44.jp2', src_ds, options=['INSPIRE_TG=YES']) @@ -2345,29 +1829,23 @@ def jp2openjpeg_44(): # Test GMLJP2v2 -def jp2openjpeg_45(): +def test_jp2openjpeg_45(): if gdaltest.jp2openjpeg_drv is None: - return 'skip' + pytest.skip() with gdaltest.error_handler(): if ogr.Open('../ogr/data/ionic_wfs.gml') is None: - print('GML read support missing') - return 'skip' + pytest.skip('GML read support missing') if gdal.GetDriverByName('KML') is None and gdal.GetDriverByName('LIBKML') is None: - print('KML support missing') - return 'skip' + pytest.skip('KML support missing') # Test GMLJP2V2_DEF=YES src_ds = gdal.Open('data/byte.tif') out_ds = gdaltest.jp2openjpeg_drv.CreateCopy('/vsimem/jp2openjpeg_45.jp2', src_ds, options=['GMLJP2V2_DEF=YES']) - if out_ds.GetLayerCount() != 0: - gdaltest.post_reason('fail') - return 'fail' - if out_ds.GetLayer(0) is not None: - gdaltest.post_reason('fail') - return 'fail' + assert out_ds.GetLayerCount() == 0 + assert out_ds.GetLayer(0) is None del out_ds ds = gdal.Open('/vsimem/jp2openjpeg_45.jp2') @@ -2430,15 +1908,10 @@ def jp2openjpeg_45(): </gmljp2:featureMember> </gmljp2:GMLJP2CoverageCollection> """ - if gmljp2 != minimal_instance: - gdaltest.post_reason('fail') - print(gmljp2) - return 'fail' + assert gmljp2 == minimal_instance ret = validate('/vsimem/jp2openjpeg_45.jp2', inspire_tg=False) - if ret == 'fail': - gdaltest.post_reason('fail') - return 'fail' + assert ret != 'fail' gdal.Unlink('/vsimem/jp2openjpeg_45.jp2') @@ -2447,10 +1920,7 @@ def jp2openjpeg_45(): del out_ds ds = gdal.Open('/vsimem/jp2openjpeg_45.jp2') gmljp2 = ds.GetMetadata_List("xml:gml.root-instance")[0] - if gmljp2 != minimal_instance: - gdaltest.post_reason('fail') - print(gmljp2) - return 'fail' + assert gmljp2 == minimal_instance ds = None gdal.Unlink('/vsimem/jp2openjpeg_45.jp2') @@ -2459,18 +1929,14 @@ def jp2openjpeg_45(): gdal.PushErrorHandler() out_ds = gdaltest.jp2openjpeg_drv.CreateCopy('/vsimem/jp2openjpeg_45.jp2', src_ds, options=['GMLJP2V2_DEF={']) gdal.PopErrorHandler() - if out_ds is not None: - gdaltest.post_reason('fail') - return 'fail' + assert out_ds is None # Non existing file gdal.ErrorReset() gdal.PushErrorHandler() out_ds = gdaltest.jp2openjpeg_drv.CreateCopy('/vsimem/jp2openjpeg_45.jp2', src_ds, options=['GMLJP2V2_DEF=/vsimem/i_do_not_exist']) gdal.PopErrorHandler() - if out_ds is not None: - gdaltest.post_reason('fail') - return 'fail' + assert out_ds is None # Test JSon conf file as a file gdal.FileFromMemBuffer("/vsimem/conf.json", '{ "root_instance": { "gml_id": "some_gml_id", "crs_url": false } }') @@ -2479,14 +1945,8 @@ def jp2openjpeg_45(): del out_ds ds = gdal.Open('/vsimem/jp2openjpeg_45.jp2') gmljp2 = ds.GetMetadata_List("xml:gml.root-instance")[0] - if gmljp2.find('some_gml_id') < 0: - gdaltest.post_reason('fail') - print(gmljp2) - return 'fail' - if gmljp2.find('urn:ogc:def:crs:EPSG::26711') < 0: - gdaltest.post_reason('fail') - print(gmljp2) - return 'fail' + assert gmljp2.find('some_gml_id') >= 0 + assert gmljp2.find('urn:ogc:def:crs:EPSG::26711') >= 0 ds = None gdal.Unlink('/vsimem/jp2openjpeg_45.jp2') @@ -2498,11 +1958,7 @@ def jp2openjpeg_45(): del out_ds ds = gdal.Open('/vsimem/jp2openjpeg_45.jp2') gmljp2 = ds.GetMetadata_List("xml:gml.root-instance")[0] - if gmljp2.find(predefined[1]) < 0: - gdaltest.post_reason('fail') - print(predefined[0]) - print(gmljp2) - return 'fail' + assert gmljp2.find(predefined[1]) >= 0 ds = None gdal.Unlink('/vsimem/jp2openjpeg_45.jp2') @@ -2514,10 +1970,7 @@ def jp2openjpeg_45(): del out_ds ds = gdal.Open('/vsimem/jp2openjpeg_45.jp2') gmljp2 = ds.GetMetadata_List("xml:gml.root-instance")[0] - if gmljp2.find('<gmlcov:rangeType></gmlcov:rangeType>') < 0: - gdaltest.post_reason('fail') - print(gmljp2) - return 'fail' + assert gmljp2.find('<gmlcov:rangeType></gmlcov:rangeType>') >= 0 ds = None gdal.Unlink('/vsimem/jp2openjpeg_45.jp2') @@ -2537,11 +1990,7 @@ def jp2openjpeg_45(): del out_ds ds = gdal.Open('/vsimem/jp2openjpeg_45.jp2') gmljp2 = ds.GetMetadata_List("xml:gml.root-instance")[0] - if gmljp2.find("custom_datarecord") < 0: - gdaltest.post_reason('fail') - print(predefined[0]) - print(gmljp2) - return 'fail' + assert gmljp2.find("custom_datarecord") >= 0, predefined[0] ds = None gdal.Unlink('/vsimem/jp2openjpeg_45.jp2') @@ -2558,9 +2007,7 @@ def jp2openjpeg_45(): gdal.PushErrorHandler() out_ds = gdaltest.jp2openjpeg_drv.CreateCopy('/vsimem/jp2openjpeg_45.jp2', src_ds, options=['GMLJP2V2_DEF=' + json.dumps(conf)]) gdal.PopErrorHandler() - if out_ds is not None: - gdaltest.post_reason('fail') - return 'fail' + assert out_ds is None conf = { "root_instance": { @@ -2914,17 +2361,11 @@ def jp2openjpeg_45(): # Now do the checks dircontent = gdal.ReadDir('/vsimem/gmljp2') - if dircontent is not None: - gdaltest.post_reason('fail') - print(dircontent) - return 'fail' + assert dircontent is None ds = gdal.Open('/vsimem/jp2openjpeg_45.jp2') gmljp2 = ds.GetMetadata_List("xml:gml.root-instance")[0] - if gmljp2.find('my_GMLJP2RectifiedGridCoverage') < 0: - gdaltest.post_reason('fail') - print(gmljp2) - return 'fail' + assert gmljp2.find('my_GMLJP2RectifiedGridCoverage') >= 0 first_metadata_pos = gmljp2.find("First metadata") second_metadata_pos = gmljp2.find("Second metadata") third_metadata_pos = gmljp2.find("Third metadata") @@ -2946,13 +2387,12 @@ def jp2openjpeg_45(): extension3_pos = gmljp2.find("""<extension3 xmlns="http://undefined_namespace" />""") extension4_pos = gmljp2.find("""<extension4 xmlns="http://undefined_namespace" />""") - if first_metadata_pos < 0 or second_metadata_pos < 0 or third_metadata_pos < 0 or \ - GMLJP2RectifiedGridCoverage_pos < 0 or fourth_metadata_pos < 0 or \ - feature_pos < 0 or myshape_gml_pos < 0 or myshape2_gml_pos < 0 or \ - feature2_pos < 0 or myshape_kml_pos < 0 or empty_kml_pos < 0 or \ - style1_pos < 0 or style2_pos < 0 or style3_pos < 0 or style4_pos < 0 or \ - extension1_pos < 0 or extension2_pos < 0 or extension3_pos < 0 or extension4_pos < 0 or \ - not(first_metadata_pos < second_metadata_pos and + assert (first_metadata_pos >= 0 and second_metadata_pos >= 0 and third_metadata_pos >= 0 and \ + GMLJP2RectifiedGridCoverage_pos >= 0 and fourth_metadata_pos >= 0 and \ + feature_pos >= 0 and myshape_gml_pos >= 0 and myshape2_gml_pos >= 0 and \ + feature2_pos >= 0 and myshape_kml_pos >= 0 and empty_kml_pos >= 0 and \ + style1_pos >= 0 and style2_pos >= 0 and style3_pos >= 0 and style4_pos >= 0 and \ + extension1_pos >= 0 and extension2_pos >= 0 and extension3_pos >= 0 and extension4_pos >= 0 and(first_metadata_pos < second_metadata_pos and second_metadata_pos < third_metadata_pos and third_metadata_pos < GMLJP2RectifiedGridCoverage_pos and GMLJP2RectifiedGridCoverage_pos < fourth_metadata_pos and @@ -2971,65 +2411,37 @@ def jp2openjpeg_45(): style3_pos < style4_pos and style4_pos < extension1_pos and extension1_pos < extension3_pos and - extension3_pos < extension4_pos): - gdaltest.post_reason('fail') - print(gmljp2) - return 'fail' + extension3_pos < extension4_pos)), \ + gmljp2 # print(gmljp2) myshape_gml = ds.GetMetadata_List("xml:myshape.gml")[0] - if myshape_gml.find("""<ogr1:FeatureCollection gml:id="ID_GMLJP2_0_1_aFeatureCollection" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://ogr.maptools.org/1 gmljp2://xml/myshape.xsd" xmlns:ogr1="http://ogr.maptools.org/1" xmlns:gml="http://www.opengis.net/gml/3.2">""") < 0: - gdaltest.post_reason('fail') - print(myshape_gml) - return 'fail' - if myshape_gml.find("""http://www.opengis.net/def/crs/EPSG/0/4326""") < 0: - gdaltest.post_reason('fail') - print(myshape_gml) - return 'fail' + assert myshape_gml.find("""<ogr1:FeatureCollection gml:id="ID_GMLJP2_0_1_aFeatureCollection" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://ogr.maptools.org/1 gmljp2://xml/myshape.xsd" xmlns:ogr1="http://ogr.maptools.org/1" xmlns:gml="http://www.opengis.net/gml/3.2">""") >= 0 + assert myshape_gml.find("""http://www.opengis.net/def/crs/EPSG/0/4326""") >= 0 myshape_xsd = ds.GetMetadata_List("xml:myshape.xsd")[0] - if myshape_xsd.find("""<xs:schema targetNamespace="http://ogr.maptools.org/1" xmlns:ogr1="http://ogr.maptools.org/1" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:gml="http://www.opengis.net/gml/3.2" xmlns:gmlsf="http://www.opengis.net/gmlsf/2.0" elementFormDefault="qualified" version="1.0">""") < 0: - gdaltest.post_reason('fail') - print(myshape_xsd) - return 'fail' + assert myshape_xsd.find("""<xs:schema targetNamespace="http://ogr.maptools.org/1" xmlns:ogr1="http://ogr.maptools.org/1" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:gml="http://www.opengis.net/gml/3.2" xmlns:gmlsf="http://www.opengis.net/gmlsf/2.0" elementFormDefault="qualified" version="1.0">""") >= 0 myshape2_gml = ds.GetMetadata_List("xml:myshape2.gml")[0] - if myshape2_gml.find("""<ogr2:FeatureCollection gml:id="ID_GMLJP2_0_2_aFeatureCollection" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://ogr.maptools.org/ gmljp2://xml/a_schema.xsd" xmlns:ogr2="http://ogr.maptools.org/" xmlns:gml="http://www.opengis.net/gml/3.2">""") < 0: - gdaltest.post_reason('fail') - print(myshape2_gml) - return 'fail' + assert myshape2_gml.find("""<ogr2:FeatureCollection gml:id="ID_GMLJP2_0_2_aFeatureCollection" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://ogr.maptools.org/ gmljp2://xml/a_schema.xsd" xmlns:ogr2="http://ogr.maptools.org/" xmlns:gml="http://www.opengis.net/gml/3.2">""") >= 0 feature2_gml = ds.GetMetadata_List("xml:feature2.gml")[0] - if feature2_gml.find("""<FeatureCollection xmlns:ogr="http://ogr.maptools.org/" xmlns:gml="http://www.opengis.net/gml/3.2" xsi:schemaLocation="http://ogr.maptools.org/ gmljp2://xml/a_schema.xsd" gml:id="ID_GMLJP2_0_3_myFC3">""") < 0: - gdaltest.post_reason('fail') - print(feature2_gml) - return 'fail' + assert feature2_gml.find("""<FeatureCollection xmlns:ogr="http://ogr.maptools.org/" xmlns:gml="http://www.opengis.net/gml/3.2" xsi:schemaLocation="http://ogr.maptools.org/ gmljp2://xml/a_schema.xsd" gml:id="ID_GMLJP2_0_3_myFC3">""") >= 0 feature3_gml = ds.GetMetadata_List("xml:feature3.gml")[0] - if feature3_gml.find("""<FeatureCollection xmlns:ogr="http://ogr.maptools.org/" xmlns:gml="http://www.opengis.net/gml/3.2" xsi:schemaLocation="http://www.opengis.net/gml/3.2 http://schemas.opengis.net/gml/3.2.1/gml.xsd http://ogr.maptools.org/ gmljp2://xml/a_schema.xsd" gml:id="ID_GMLJP2_0_4_myFC4">""") < 0: - gdaltest.post_reason('fail') - print(feature3_gml) - return 'fail' + assert feature3_gml.find("""<FeatureCollection xmlns:ogr="http://ogr.maptools.org/" xmlns:gml="http://www.opengis.net/gml/3.2" xsi:schemaLocation="http://www.opengis.net/gml/3.2 http://schemas.opengis.net/gml/3.2.1/gml.xsd http://ogr.maptools.org/ gmljp2://xml/a_schema.xsd" gml:id="ID_GMLJP2_0_4_myFC4">""") >= 0 myshape2_xsd = ds.GetMetadata_List("xml:a_schema.xsd")[0] - if myshape2_xsd.find("""<xs:schema xmlns:ogr="http://ogr.maptools.org/" """) < 0: - gdaltest.post_reason('fail') - print(myshape2_xsd) - return 'fail' + assert myshape2_xsd.find("""<xs:schema xmlns:ogr="http://ogr.maptools.org/" """) >= 0 duplicated_xsd = ds.GetMetadata_List("xml:duplicated.xsd")[0] - if duplicated_xsd.find("""<xs:schema xmlns:ogr="http://ogr.maptools.org/" """) < 0: - gdaltest.post_reason('fail') - print(myshape2_xsd) - return 'fail' + assert duplicated_xsd.find("""<xs:schema xmlns:ogr="http://ogr.maptools.org/" """) >= 0, \ + myshape2_xsd ds = None ds = ogr.Open('/vsimem/jp2openjpeg_45.jp2') - if ds.GetLayerCount() != 6: - gdaltest.post_reason('fail') - print(ds.GetLayerCount()) - return 'fail' + assert ds.GetLayerCount() == 6 expected_layers = ['FC_GridCoverage_1_myshape', 'FC_CoverageCollection_1_Observation', 'FC_CoverageCollection_2_myshape', @@ -3038,16 +2450,13 @@ def jp2openjpeg_45(): 'Annotation_1_myshape'] for j in range(6): if ds.GetLayer(j).GetName() != expected_layers[j]: - gdaltest.post_reason('fail') for i in range(ds.GetLayerCount()): print(ds.GetLayer(i).GetName()) - return 'fail' + pytest.fail() ds = None ret = validate('/vsimem/jp2openjpeg_45.jp2', inspire_tg=False) - if ret == 'fail': - gdaltest.post_reason('fail') - return 'fail' + assert ret != 'fail' gdal.Unlink('/vsimem/jp2openjpeg_45.jp2') @@ -3057,20 +2466,11 @@ def jp2openjpeg_45(): del out_ds dircontent = gdal.ReadDir('/vsimem/gmljp2') - if dircontent is not None: - gdaltest.post_reason('fail') - print(dircontent) - return 'fail' + assert dircontent is None ds = ogr.Open('/vsimem/jp2openjpeg_45.jp2') - if ds.GetLayerCount() != 1: - gdaltest.post_reason('fail') - print(ds.GetLayerCount()) - return 'fail' - if ds.GetLayer(0).GetName() != 'FC_GridCoverage_1_poly': - gdaltest.post_reason('fail') - print(ds.GetLayer(0).GetName()) - return 'fail' + assert ds.GetLayerCount() == 1 + assert ds.GetLayer(0).GetName() == 'FC_GridCoverage_1_poly' ds = None gdal.Unlink('/vsimem/jp2openjpeg_45.jp2') @@ -3087,19 +2487,15 @@ def jp2openjpeg_45(): out_ds = gdaltest.jp2openjpeg_drv.CreateCopy('/vsimem/jp2openjpeg_45.jp2', src_ds, options=['GMLJP2V2_DEF=' + json.dumps(conf)]) del out_ds if gdal.VSIStatL('/vsimem/jp2openjpeg_45.jp2.aux.xml') is not None: - gdaltest.post_reason('fail') fp = gdal.VSIFOpenL('/vsimem/jp2openjpeg_45.jp2.aux.xml', 'rb') if fp is not None: data = gdal.VSIFReadL(1, 100000, fp).decode('ascii') gdal.VSIFCloseL(fp) print(data) - return 'fail' + pytest.fail() ds = gdal.Open('/vsimem/jp2openjpeg_45.jp2') - if ds.GetMetadata() != {'FOO': 'BAR'}: - gdaltest.post_reason('fail') - print(ds.GetMetadata()) - return 'fail' + assert ds.GetMetadata() == {'FOO': 'BAR'} ds = None gdal.Unlink('/vsimem/jp2openjpeg_45.jp2') @@ -3111,9 +2507,7 @@ def jp2openjpeg_45(): # Nothing should be reported by default ds = ogr.Open('/vsimem/jp2openjpeg_45.jp2') - if ds is not None: - gdaltest.post_reason('fail') - return 'fail' + assert ds is None ds = None # We have to explicitly allow it. @@ -3122,26 +2516,21 @@ def jp2openjpeg_45(): if ds is None: if gdaltest.gdalurlopen('https://raw.githubusercontent.com/OSGeo/gdal/master/autotest/ogr/data/expected_gml_gml32.gml') is None: - return 'skip' - gdaltest.post_reason('fail') - return 'fail' - if ds.GetLayerCount() != 1: - gdaltest.post_reason('fail') - return 'fail' + pytest.skip() + pytest.fail() + assert ds.GetLayerCount() == 1 ds = None gdal.Unlink('/vsimem/jp2openjpeg_45.jp2.aux.xml') - return 'success' - ############################################################################### # Test GMLJP2v2 metadata generator / XPath -def jp2openjpeg_46(): +def test_jp2openjpeg_46(): if gdaltest.jp2openjpeg_drv is None: - return 'skip' + pytest.skip() import json @@ -3172,22 +2561,20 @@ def jp2openjpeg_46(): del out_ds if gdal.GetLastErrorMsg().find('dynamic_metadata not supported') >= 0: gdal.Unlink('/vsimem/jp2openjpeg_46.jp2') - return 'skip' + pytest.skip() # Maybe a conflict with FileGDB libxml2 if gdal.GetLastErrorMsg().find('An error occurred in libxml2') >= 0: gdal.Unlink('/vsimem/jp2openjpeg_46.jp2') - return 'skip' + pytest.skip() ds = gdal.Open('/vsimem/jp2openjpeg_46.jp2') gmljp2 = ds.GetMetadata_List("xml:gml.root-instance")[0] if gmljp2.find("""<gmljp2:metadata>1 str trueX <B>my_value</B> yeah: """) < 0: - gdaltest.post_reason('fail') - print(gmljp2) if gmljp2.find("""<gmljp2:metadata>1 str true""") >= 0: - return 'skip' - return 'fail' + pytest.skip() + pytest.fail(gmljp2) ds = None gdal.Unlink('/vsimem/jp2openjpeg_46.jp2') @@ -3220,11 +2607,7 @@ def jp2openjpeg_46(): gdal.Unlink('/vsimem/jp2openjpeg_46.jp2') - if gmljp2.find('<gmljp2:metadata>') >= 0: - gdaltest.post_reason('fail') - print(invalid_template) - print(gmljp2) - return 'fail' + assert gmljp2.find('<gmljp2:metadata>') < 0, invalid_template # Nonexistent template. gdal.FileFromMemBuffer("/vsimem/source.xml", """<A/>""") @@ -3302,128 +2685,102 @@ def jp2openjpeg_46(): # ds = None gdal.Unlink('/vsimem/jp2openjpeg_46.jp2') - return 'success' - ############################################################################### # Test writing & reading RPC in GeoJP2 box -def jp2openjpeg_47(): +def test_jp2openjpeg_47(): if gdaltest.jp2openjpeg_drv is None: - return 'skip' + pytest.skip() src_ds = gdal.Open('../gcore/data/byte_rpc.tif') out_ds = gdaltest.jp2openjpeg_drv.CreateCopy('/vsimem/jp2openjpeg_47.jp2', src_ds) del out_ds - if gdal.VSIStatL('/vsimem/jp2openjpeg_47.jp2.aux.xml') is not None: - gdaltest.post_reason('fail') - return 'fail' + assert gdal.VSIStatL('/vsimem/jp2openjpeg_47.jp2.aux.xml') is None ds = gdal.Open('/vsimem/jp2openjpeg_47.jp2') - if ds.GetMetadata('RPC') is None: - gdaltest.post_reason('fail') - return 'fail' + assert ds.GetMetadata('RPC') is not None ds = None gdal.Unlink('/vsimem/jp2openjpeg_47.jp2') - return 'success' - ############################################################################### # Test reading a dataset whose tile dimensions are larger than dataset ones -def jp2openjpeg_48(): +def test_jp2openjpeg_48(): if gdaltest.jp2openjpeg_drv is None: - return 'skip' + pytest.skip() ds = gdal.Open('data/byte_tile_2048.jp2') (blockxsize, blockysize) = ds.GetRasterBand(1).GetBlockSize() - if (blockxsize, blockysize) != (20, 20): - gdaltest.post_reason('fail') - print(blockxsize, blockysize) - return 'fail' - if ds.GetRasterBand(1).Checksum() != 4610: - gdaltest.post_reason('fail') - return 'fail' + assert (blockxsize, blockysize) == (20, 20) + assert ds.GetRasterBand(1).Checksum() == 4610 ds = None - return 'success' - ############################################################################### -def jp2openjpeg_online_1(): +def test_jp2openjpeg_online_1(): if gdaltest.jp2openjpeg_drv is None: - return 'skip' + pytest.skip() if not gdaltest.download_file('http://download.osgeo.org/gdal/data/jpeg2000/7sisters200.j2k', '7sisters200.j2k'): - return 'skip' + pytest.skip() # Checksum = 32669 on my PC tst = gdaltest.GDALTest('JP2OpenJPEG', 'tmp/cache/7sisters200.j2k', 1, None, filename_absolute=1) - if tst.testOpen() != 'success': - return 'fail' + tst.testOpen() ds = gdal.Open('tmp/cache/7sisters200.j2k') ds.GetRasterBand(1).Checksum() ds = None - return 'success' - ############################################################################### -def jp2openjpeg_online_2(): +def test_jp2openjpeg_online_2(): if gdaltest.jp2openjpeg_drv is None: - return 'skip' + pytest.skip() if not gdaltest.download_file('http://download.osgeo.org/gdal/data/jpeg2000/gcp.jp2', 'gcp.jp2'): - return 'skip' + pytest.skip() # Checksum = 15621 on my PC tst = gdaltest.GDALTest('JP2OpenJPEG', 'tmp/cache/gcp.jp2', 1, None, filename_absolute=1) - if tst.testOpen() != 'success': - return 'fail' + tst.testOpen() ds = gdal.Open('tmp/cache/gcp.jp2') ds.GetRasterBand(1).Checksum() - if len(ds.GetGCPs()) != 15: - gdaltest.post_reason('bad number of GCP') - return 'fail' + assert len(ds.GetGCPs()) == 15, 'bad number of GCP' 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 ds.GetGCPProjection() != expected_wkt: - gdaltest.post_reason('bad GCP projection') - return 'fail' + assert ds.GetGCPProjection() == expected_wkt, 'bad GCP projection' ds = None - return 'success' - ############################################################################### -def jp2openjpeg_online_3(): +def test_jp2openjpeg_online_3(): if gdaltest.jp2openjpeg_drv is None: - return 'skip' + pytest.skip() if not gdaltest.download_file('http://www.openjpeg.org/samples/Bretagne1.j2k', 'Bretagne1.j2k'): - return 'skip' + pytest.skip() if not gdaltest.download_file('http://www.openjpeg.org/samples/Bretagne1.bmp', 'Bretagne1.bmp'): - return 'skip' + pytest.skip() tst = gdaltest.GDALTest('JP2OpenJPEG', 'tmp/cache/Bretagne1.j2k', 1, None, filename_absolute=1) - if tst.testOpen() != 'success': - return 'fail' + tst.testOpen() ds = gdal.Open('tmp/cache/Bretagne1.j2k') ds_ref = gdal.Open('tmp/cache/Bretagne1.bmp') @@ -3435,29 +2792,24 @@ def jp2openjpeg_online_3(): ds_ref = None # Difference between the image before and after compression - if maxdiff > 17: - gdaltest.post_reason('Image too different from reference') - return 'fail' - - return 'success' + assert maxdiff <= 17, 'Image too different from reference' ############################################################################### -def jp2openjpeg_online_4(): +def test_jp2openjpeg_online_4(): if gdaltest.jp2openjpeg_drv is None: - return 'skip' + pytest.skip() if not gdaltest.download_file('http://www.openjpeg.org/samples/Bretagne2.j2k', 'Bretagne2.j2k'): - return 'skip' + pytest.skip() if not gdaltest.download_file('http://www.openjpeg.org/samples/Bretagne2.bmp', 'Bretagne2.bmp'): - return 'skip' + pytest.skip() tst = gdaltest.GDALTest('JP2OpenJPEG', 'tmp/cache/Bretagne2.j2k', 1, None, filename_absolute=1) - if tst.testOpen() != 'success': - return 'expected_fail' + tst.testOpen() ds = gdal.Open('tmp/cache/Bretagne2.j2k') ds_ref = gdal.Open('tmp/cache/Bretagne2.bmp') @@ -3469,70 +2821,56 @@ def jp2openjpeg_online_4(): ds_ref = None # Difference between the image before and after compression - if maxdiff > 10: - gdaltest.post_reason('Image too different from reference') - return 'fail' - - return 'success' + assert maxdiff <= 10, 'Image too different from reference' ############################################################################### # Try reading JP2OpenJPEG with color table -def jp2openjpeg_online_5(): +def test_jp2openjpeg_online_5(): if gdaltest.jp2openjpeg_drv is None: - return 'skip' + pytest.skip() if not gdaltest.download_file('http://www.gwg.nga.mil/ntb/baseline/software/testfile/Jpeg2000/jp2_09/file9.jp2', 'file9.jp2'): - return 'skip' + pytest.skip() ds = gdal.Open('tmp/cache/file9.jp2') cs1 = ds.GetRasterBand(1).Checksum() - if cs1 != 47664: - gdaltest.post_reason('Did not get expected checksums') - print(cs1) - return 'fail' - if ds.GetRasterBand(1).GetColorTable() is None: - gdaltest.post_reason('Did not get expected color table') - return 'fail' + assert cs1 == 47664, 'Did not get expected checksums' + assert ds.GetRasterBand(1).GetColorTable() is not None, \ + 'Did not get expected color table' ds = None - return 'success' - ############################################################################### # Try reading YCbCr JP2OpenJPEG as RGB -def jp2openjpeg_online_6(): +def test_jp2openjpeg_online_6(): if gdaltest.jp2openjpeg_drv is None: - return 'skip' + pytest.skip() if not gdaltest.download_file('http://www.gwg.nga.mil/ntb/baseline/software/testfile/Jpeg2000/jp2_03/file3.jp2', 'file3.jp2'): - return 'skip' + pytest.skip() ds = gdal.Open('tmp/cache/file3.jp2') cs1 = ds.GetRasterBand(1).Checksum() cs2 = ds.GetRasterBand(2).Checksum() cs3 = ds.GetRasterBand(3).Checksum() - if cs1 != 26140 or cs2 != 32689 or cs3 != 48247: - print(cs1, cs2, cs3) - gdaltest.post_reason('Did not get expected checksums') - return 'fail' + assert cs1 == 26140 and cs2 == 32689 and cs3 == 48247, \ + 'Did not get expected checksums' ds = None - return 'success' - ############################################################################### # Test GDAL_GEOREF_SOURCES -def jp2openjpeg_49(): +def test_jp2openjpeg_49(): if gdaltest.jp2openjpeg_drv is None: - return 'skip' + pytest.skip() tests = [(None, True, True, 'LOCAL_CS["PAM"]', (100.0, 1.0, 0.0, 300.0, 0.0, -1.0)), (None, True, False, 'LOCAL_CS["PAM"]', (100.0, 1.0, 0.0, 300.0, 0.0, -1.0)), @@ -3572,16 +2910,14 @@ def jp2openjpeg_49(): gdal.Unlink('/vsimem/byte_nogeoref.j2w') if gt != expected_gt: - gdaltest.post_reason('Did not get expected gt for %s,copy_pam=%s,copy_worldfile=%s' % (config_option_value, str(copy_pam), str(copy_worldfile))) print('Got ' + str(gt)) print('Expected ' + str(expected_gt)) - return 'fail' + pytest.fail('Did not get expected gt for %s,copy_pam=%s,copy_worldfile=%s' % (config_option_value, str(copy_pam), str(copy_worldfile))) if (expected_srs == '' and srs_wkt != '') or (expected_srs != '' and srs_wkt.find(expected_srs) < 0): - gdaltest.post_reason('Did not get expected SRS for %s,copy_pam=%s,copy_worldfile=%s' % (config_option_value, str(copy_pam), str(copy_worldfile))) print('Got ' + srs_wkt) print('Expected ' + expected_srs) - return 'fail' + pytest.fail('Did not get expected SRS for %s,copy_pam=%s,copy_worldfile=%s' % (config_option_value, str(copy_pam), str(copy_worldfile))) tests = [(None, True, True, 'LOCAL_CS["PAM"]', (100.0, 1.0, 0.0, 300.0, 0.0, -1.0)), (None, True, False, 'LOCAL_CS["PAM"]', (100.0, 1.0, 0.0, 300.0, 0.0, -1.0)), @@ -3629,67 +2965,53 @@ def jp2openjpeg_49(): gdal.Unlink('/vsimem/inconsitant_geojp2_gmljp2.j2w') if gt != expected_gt: - gdaltest.post_reason('Did not get expected gt for %s,copy_pam=%s,copy_worldfile=%s' % (config_option_value, str(copy_pam), str(copy_worldfile))) print('Got ' + str(gt)) print('Expected ' + str(expected_gt)) - return 'fail' + pytest.fail('Did not get expected gt for %s,copy_pam=%s,copy_worldfile=%s' % (config_option_value, str(copy_pam), str(copy_worldfile))) if (expected_srs == '' and srs_wkt != '') or (expected_srs != '' and srs_wkt.find(expected_srs) < 0): - gdaltest.post_reason('Did not get expected SRS for %s,copy_pam=%s,copy_worldfile=%s' % (config_option_value, str(copy_pam), str(copy_worldfile))) print('Got ' + srs_wkt) print('Expected ' + expected_srs) - return 'fail' + pytest.fail('Did not get expected SRS for %s,copy_pam=%s,copy_worldfile=%s' % (config_option_value, str(copy_pam), str(copy_worldfile))) ds = gdal.OpenEx('data/inconsitant_geojp2_gmljp2.jp2', open_options=['GEOREF_SOURCES=PAM,WORLDFILE']) fl = ds.GetFileList() - if set(fl) != set(['data/inconsitant_geojp2_gmljp2.jp2', 'data/inconsitant_geojp2_gmljp2.jp2.aux.xml']): - gdaltest.post_reason('Did not get expected filelist') - print(fl) - return 'fail' + assert set(fl) == set(['data/inconsitant_geojp2_gmljp2.jp2', 'data/inconsitant_geojp2_gmljp2.jp2.aux.xml']), \ + 'Did not get expected filelist' gdal.ErrorReset() with gdaltest.error_handler(): gdal.OpenEx('data/inconsitant_geojp2_gmljp2.jp2', open_options=['GEOREF_SOURCES=unhandled']) - if gdal.GetLastErrorMsg() == '': - gdaltest.post_reason('expected warning') - return 'fail' - - return 'success' + assert gdal.GetLastErrorMsg() != '', 'expected warning' + ############################################################################### # Test opening an image of small dimension with very small tiles (#7012) -def jp2openjpeg_50(): +def test_jp2openjpeg_50(): if gdaltest.jp2openjpeg_drv is None: - return 'skip' + pytest.skip() ds = gdal.Open('data/fake_sent2_preview.jp2') blockxsize, blockysize = ds.GetRasterBand(1).GetBlockSize() - if blockxsize != ds.RasterXSize or blockysize != ds.RasterYSize: - gdaltest.post_reason('expected warning') - print(blockxsize, blockysize) - return 'fail' + assert blockxsize == ds.RasterXSize and blockysize == ds.RasterYSize, \ + 'expected warning' cs = ds.GetRasterBand(1).Checksum() - if cs != 2046: - gdaltest.post_reason('expected warning') - print(cs) - return 'fail' - - return 'success' + assert cs == 2046, 'expected warning' ############################################################################### # Test CODEBLOCK_STYLE -def jp2openjpeg_codeblock_style(): +def test_jp2openjpeg_codeblock_style(): if gdaltest.jp2openjpeg_drv is None: - return 'skip' + pytest.skip() if gdaltest.jp2openjpeg_drv.GetMetadataItem('DMD_CREATIONOPTIONLIST').find('CODEBLOCK_STYLE') < 0: - return 'skip' + pytest.skip() filename = '/vsimem/jp2openjpeg_codeblock_style.jp2' for options in [['CODEBLOCK_STYLE=63', 'REVERSIBLE=YES', 'QUALITY=100'], @@ -3697,43 +3019,32 @@ def jp2openjpeg_codeblock_style(): gdal.ErrorReset() gdaltest.jp2openjpeg_drv.CreateCopy(filename, gdal.Open('data/byte.tif'), options=options) - if gdal.GetLastErrorMsg() != '': - gdaltest.post_reason('fail') - return 'fail' + assert gdal.GetLastErrorMsg() == '' ds = gdal.Open(filename) cs = ds.GetRasterBand(1).Checksum() ds = None - if cs != 4672: - gdaltest.post_reason('fail') - print(cs) - return 'fail' + assert cs == 4672 with gdaltest.error_handler(): gdaltest.jp2openjpeg_drv.CreateCopy(filename, gdal.Open('data/byte.tif'), options=['CODEBLOCK_STYLE=64']) - if gdal.GetLastErrorMsg() == '': - gdaltest.post_reason('fail') - return 'fail' + assert gdal.GetLastErrorMsg() != '' with gdaltest.error_handler(): gdaltest.jp2openjpeg_drv.CreateCopy(filename, gdal.Open('data/byte.tif'), options=['CODEBLOCK_STYLE=UNSUPPORTED']) - if gdal.GetLastErrorMsg() == '': - gdaltest.post_reason('fail') - return 'fail' + assert gdal.GetLastErrorMsg() != '' gdaltest.jp2openjpeg_drv.Delete(filename) - return 'success' - ############################################################################### # Test external overviews -def jp2openjpeg_external_overviews_single_band(): +def test_jp2openjpeg_external_overviews_single_band(): if gdaltest.jp2openjpeg_drv is None: - return 'skip' + pytest.skip() filename = '/vsimem/jp2openjpeg_external_overviews_single_band.jp2' gdaltest.jp2openjpeg_drv.CreateCopy(filename, @@ -3749,20 +3060,16 @@ def jp2openjpeg_external_overviews_single_band(): gdaltest.jp2openjpeg_drv.Delete(filename) - if cs != 28926: - print(cs) - return 'fail' - - return 'success' + assert cs == 28926 ############################################################################### # Test external overviews -def jp2openjpeg_external_overviews_multiple_band(): +def test_jp2openjpeg_external_overviews_multiple_band(): if gdaltest.jp2openjpeg_drv is None: - return 'skip' + pytest.skip() filename = '/vsimem/jp2openjpeg_external_overviews_multiple_band.jp2' gdaltest.jp2openjpeg_drv.CreateCopy(filename, @@ -3778,94 +3085,11 @@ def jp2openjpeg_external_overviews_multiple_band(): gdaltest.jp2openjpeg_drv.Delete(filename) - if cs != [6233, 7706, 26085]: - print(cs) - return 'fail' - - return 'success' + assert cs == [6233, 7706, 26085] ############################################################################### -def jp2openjpeg_cleanup(): +def test_jp2openjpeg_cleanup(): gdaltest.reregister_all_jpeg2000_drivers() - - return 'success' - - -gdaltest_list = [ - jp2openjpeg_1, - jp2openjpeg_2, - jp2openjpeg_3, - jp2openjpeg_4, - jp2openjpeg_4_vsimem, - jp2openjpeg_5, - jp2openjpeg_6, - jp2openjpeg_7, - jp2openjpeg_8, - jp2openjpeg_9, - jp2openjpeg_10, - jp2openjpeg_11, - jp2openjpeg_12, - jp2openjpeg_13, - jp2openjpeg_14, - jp2openjpeg_15, - jp2openjpeg_16, - jp2openjpeg_17, - jp2openjpeg_18, - jp2openjpeg_19, - jp2openjpeg_20, - jp2openjpeg_21, - jp2openjpeg_22, - jp2openjpeg_23, - jp2openjpeg_24, - jp2openjpeg_25, - jp2openjpeg_26, - jp2openjpeg_27, - jp2openjpeg_28, - jp2openjpeg_29, - jp2openjpeg_30, - jp2openjpeg_31, - jp2openjpeg_32, - jp2openjpeg_33, - jp2openjpeg_34, - jp2openjpeg_35, - jp2openjpeg_36, - jp2openjpeg_37, - jp2openjpeg_38, - jp2openjpeg_39, - jp2openjpeg_40, - jp2openjpeg_41, - jp2openjpeg_42, - jp2openjpeg_43, - jp2openjpeg_44, - jp2openjpeg_45, - jp2openjpeg_46, - jp2openjpeg_47, - jp2openjpeg_48, - jp2openjpeg_49, - jp2openjpeg_50, - jp2openjpeg_codeblock_style, - jp2openjpeg_external_overviews_single_band, - jp2openjpeg_external_overviews_multiple_band, - jp2openjpeg_online_1, - jp2openjpeg_online_2, - jp2openjpeg_online_3, - jp2openjpeg_online_4, - jp2openjpeg_online_5, - jp2openjpeg_online_6, - jp2openjpeg_cleanup] - -disabled_gdaltest_list = [ - jp2openjpeg_1, - jp2openjpeg_45, - jp2openjpeg_cleanup] - -if __name__ == '__main__': - - gdaltest.setup_run('jp2openjpeg') - - gdaltest.run_tests(gdaltest_list) - - sys.exit(gdaltest.summarize()) diff --git a/autotest/gdrivers/jpeg.py b/autotest/gdrivers/jpeg.py index bc4b3e05b7a6..08f7d4c7eea4 100755 --- a/autotest/gdrivers/jpeg.py +++ b/autotest/gdrivers/jpeg.py @@ -35,17 +35,17 @@ import shutil import struct -sys.path.append('../pymod') import gdaltest from osgeo import gdal from osgeo import gdalconst +import pytest ############################################################################### # Perform simple read test. -def jpeg_1(): +def test_jpeg_1(): ds = gdal.Open('data/albania.jpg') cs = ds.GetRasterBand(2).Checksum() @@ -69,7 +69,7 @@ def jpeg_1(): # Verify EXIF metadata, color interpretation and image_structure -def jpeg_2(): +def test_jpeg_2(): ds = gdal.Open('data/albania.jpg') @@ -78,44 +78,34 @@ def jpeg_2(): ds.GetFileList() try: - if (md['EXIF_GPSLatitudeRef'] != 'N' or + assert (not (md['EXIF_GPSLatitudeRef'] != 'N' or md['EXIF_GPSLatitude'] != '(41) (1) (22.91)' or md['EXIF_PixelXDimension'] != '361' or md['EXIF_GPSVersionID'] != '0x02 0x00 0x00 0x00' or md['EXIF_ExifVersion'] != '0210' or - md['EXIF_XResolution'] != '(96)'): - print(md) - gdaltest.post_reason('Exif metadata wrong.') - return 'fail' + md['EXIF_XResolution'] != '(96)')), 'Exif metadata wrong.' except KeyError: print(md) - gdaltest.post_reason('Exit metadata apparently missing.') - return 'fail' + pytest.fail('Exit metadata apparently missing.') - if ds.GetRasterBand(3).GetRasterColorInterpretation() != gdal.GCI_BlueBand: - gdaltest.post_reason('Did not get expected color interpretation.') - return 'fail' + assert ds.GetRasterBand(3).GetRasterColorInterpretation() == gdal.GCI_BlueBand, \ + 'Did not get expected color interpretation.' md = ds.GetMetadata('IMAGE_STRUCTURE') - if 'INTERLEAVE' not in md or md['INTERLEAVE'] != 'PIXEL': - gdaltest.post_reason('missing INTERLEAVE metadata') - return 'fail' - if 'COMPRESSION' not in md or md['COMPRESSION'] != 'JPEG': - gdaltest.post_reason('missing INTERLEAVE metadata') - return 'fail' + assert 'INTERLEAVE' in md and md['INTERLEAVE'] == 'PIXEL', \ + 'missing INTERLEAVE metadata' + assert 'COMPRESSION' in md and md['COMPRESSION'] == 'JPEG', \ + 'missing INTERLEAVE metadata' md = ds.GetRasterBand(3).GetMetadata('IMAGE_STRUCTURE') - if 'COMPRESSION' not in md or md['COMPRESSION'] != 'JPEG': - gdaltest.post_reason('missing INTERLEAVE metadata') - return 'fail' - - return 'success' + assert 'COMPRESSION' in md and md['COMPRESSION'] == 'JPEG', \ + 'missing INTERLEAVE metadata' ############################################################################### # Create simple copy and check (greyscale) using progressive option. -def jpeg_3(): +def test_jpeg_3(): ds = gdal.Open('data/byte.tif') @@ -128,23 +118,16 @@ def jpeg_3(): # IJG, MozJPEG expected_cs = [4794, 4787] - if ds.GetRasterBand(1).Checksum() not in expected_cs: - gdaltest.post_reason('Wrong checksum on copied image.') - print(ds.GetRasterBand(1).Checksum()) - return 'fail' + assert ds.GetRasterBand(1).Checksum() in expected_cs, \ + 'Wrong checksum on copied image.' - if ds.GetRasterBand(1).GetRasterColorInterpretation() != gdal.GCI_GrayIndex: - gdaltest.post_reason('Wrong color interpretation.') - print(ds.GetRasterBand(1).GetRasterColorInterpretation()) - return 'fail' + assert ds.GetRasterBand(1).GetRasterColorInterpretation() == gdal.GCI_GrayIndex, \ + 'Wrong color interpretation.' expected_gt = [440720.0, 60.0, 0.0, 3751320.0, 0.0, -60.0] gt = ds.GetGeoTransform() for i in range(6): - if abs(gt[i] - expected_gt[i]) > 1e-6: - gdaltest.post_reason('did not get expected geotransform from PAM') - print(gt) - return 'fail' + assert abs(gt[i] - expected_gt[i]) <= 1e-6, 'did not get expected geotransform from PAM' ds = None @@ -153,17 +136,14 @@ def jpeg_3(): try: os.stat('tmp/byte.wld') except OSError: - gdaltest.post_reason('should have .wld file at that point') - return 'fail' + pytest.fail('should have .wld file at that point') ds = gdal.Open('tmp/byte.jpg') expected_gt = [440720.0, 60.0, 0.0, 3751320.0, 0.0, -60.0] gt = ds.GetGeoTransform() for i in range(6): - if abs(gt[i] - expected_gt[i]) > 1e-6: - gdaltest.post_reason('did not get expected geotransform from .wld') - print(gt) - return 'fail' + assert abs(gt[i] - expected_gt[i]) <= 1e-6, \ + 'did not get expected geotransform from .wld' ds = None ds = gdal.Open('tmp/byte.jpg') @@ -172,52 +152,41 @@ def jpeg_3(): gdal.GetDriverByName('JPEG').Delete('tmp/byte.jpg') - try: + with pytest.raises(OSError, message='did not expect to find .wld file at that point'): os.stat('tmp/byte.wld') - gdaltest.post_reason('did not expect to find .wld file at that point') - return 'fail' - except OSError: - pass - - return 'success' + + ############################################################################### # Verify masked jpeg. -def jpeg_4(): +def test_jpeg_4(): try: gdalconst.GMF_ALL_VALID except AttributeError: - return 'skip' + pytest.skip() ds = gdal.Open('data/masked.jpg') refband = ds.GetRasterBand(1) - if refband.GetMaskFlags() != gdalconst.GMF_PER_DATASET: - gdaltest.post_reason('wrong mask flags') - return 'fail' + assert refband.GetMaskFlags() == gdalconst.GMF_PER_DATASET, 'wrong mask flags' cs = refband.GetMaskBand().Checksum() - if cs != 770: - gdaltest.post_reason('Wrong mask checksum') - print(cs) - return 'fail' - - return 'success' + assert cs == 770, 'Wrong mask checksum' ############################################################################### # Verify CreateCopy() of masked jpeg. -def jpeg_5(): +def test_jpeg_5(): try: gdalconst.GMF_ALL_VALID except AttributeError: - return 'skip' + pytest.skip() ds = gdal.Open('data/masked.jpg') @@ -225,37 +194,28 @@ def jpeg_5(): refband = ds2.GetRasterBand(1) - if refband.GetMaskFlags() != gdalconst.GMF_PER_DATASET: - gdaltest.post_reason('wrong mask flags') - return 'fail' + assert refband.GetMaskFlags() == gdalconst.GMF_PER_DATASET, 'wrong mask flags' cs = refband.GetMaskBand().Checksum() - if cs != 770: - gdaltest.post_reason('Wrong checksum on copied images mask.') - print(cs) - return 'fail' + assert cs == 770, 'Wrong checksum on copied images mask.' refband = None ds2 = None gdal.GetDriverByName('JPEG').Delete('tmp/masked.jpg') - return 'success' - ############################################################################### # Verify ability to open file with corrupt metadata (#1904). Note the file # data/vophead.jpg is truncated to keep the size small, but this should # not affect opening the file which just reads the header. -def jpeg_6(): +def test_jpeg_6(): ds = gdal.Open('data/vophead.jpg') # Because of the optimization in r17446, we shouldn't yet get this error. - if (gdal.GetLastErrorType() == 2 and - gdal.GetLastErrorMsg().find('Ignoring EXIF') != -1): - gdaltest.post_reason('got error too soon.') - return 'fail' + assert (not (gdal.GetLastErrorType() == 2 and + gdal.GetLastErrorMsg().find('Ignoring EXIF') != -1)), 'got error too soon.' with gdaltest.error_handler('CPLQuietErrorHandler'): # Get this warning: @@ -263,25 +223,20 @@ def jpeg_6(): md = ds.GetMetadata() # Did we get an exif related warning? - if (gdal.GetLastErrorType() != 2 or - gdal.GetLastErrorMsg().find('Ignoring EXIF') == -1): - gdaltest.post_reason('did not get expected error.') - return 'fail' + assert (not (gdal.GetLastErrorType() != 2 or + gdal.GetLastErrorMsg().find('Ignoring EXIF') == -1)), \ + 'did not get expected error.' - if len(md) != 1 or md['EXIF_Software'] != 'IrfanView': - gdaltest.post_reason('did not get expected metadata.') - print(md) - return 'fail' + assert len(md) == 1 and md['EXIF_Software'] == 'IrfanView', \ + 'did not get expected metadata.' ds = None - return 'success' - ############################################################################### # Test creating an in memory copy. -def jpeg_7(): +def test_jpeg_7(): ds = gdal.Open('data/byte.tif') @@ -293,73 +248,54 @@ def jpeg_7(): # IJG, MozJPEG expected_cs = [4794, 4787] - if ds.GetRasterBand(1).Checksum() not in expected_cs: - gdaltest.post_reason('Wrong checksum on copied image.') - print(ds.GetRasterBand(1).Checksum()) - return 'fail' + assert ds.GetRasterBand(1).Checksum() in expected_cs, \ + 'Wrong checksum on copied image.' ds = None gdal.GetDriverByName('JPEG').Delete('/vsimem/byte.jpg') - return 'success' - ############################################################################### # Read a CMYK image as a RGB image -def jpeg_8(): +def test_jpeg_8(): ds = gdal.Open('data/rgb_ntf_cmyk.jpg') expected_cs = 20385 - if ds.GetRasterBand(1).Checksum() != expected_cs: - gdaltest.post_reason('Wrong checksum on copied image.') - print(ds.GetRasterBand(1).Checksum()) - return 'fail' + assert ds.GetRasterBand(1).Checksum() == expected_cs, \ + 'Wrong checksum on copied image.' - 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.' expected_cs = 20865 - if ds.GetRasterBand(2).Checksum() != expected_cs: - gdaltest.post_reason('Wrong checksum on copied image.') - print(ds.GetRasterBand(2).Checksum()) - return 'fail' + assert ds.GetRasterBand(2).Checksum() == expected_cs, \ + 'Wrong checksum on copied image.' - if ds.GetRasterBand(2).GetRasterColorInterpretation() != gdal.GCI_GreenBand: - gdaltest.post_reason('Wrong color interpretation.') - print(ds.GetRasterBand(2).GetRasterColorInterpretation()) - return 'fail' + assert ds.GetRasterBand(2).GetRasterColorInterpretation() == gdal.GCI_GreenBand, \ + 'Wrong color interpretation.' expected_cs = 19441 - if ds.GetRasterBand(3).Checksum() != expected_cs: - gdaltest.post_reason('Wrong checksum on copied image.') - print(ds.GetRasterBand(3).Checksum()) - return 'fail' + assert ds.GetRasterBand(3).Checksum() == expected_cs, \ + 'Wrong checksum on copied image.' - if ds.GetRasterBand(3).GetRasterColorInterpretation() != gdal.GCI_BlueBand: - gdaltest.post_reason('Wrong color interpretation.') - print(ds.GetRasterBand(3).GetRasterColorInterpretation()) - return 'fail' + assert ds.GetRasterBand(3).GetRasterColorInterpretation() == gdal.GCI_BlueBand, \ + 'Wrong color interpretation.' md = ds.GetMetadata('IMAGE_STRUCTURE') - if 'SOURCE_COLOR_SPACE' not in md or md['SOURCE_COLOR_SPACE'] != 'CMYK': - gdaltest.post_reason('missing SOURCE_COLOR_SPACE metadata') - return 'fail' - - return 'success' + assert 'SOURCE_COLOR_SPACE' in md and md['SOURCE_COLOR_SPACE'] == 'CMYK', \ + 'missing SOURCE_COLOR_SPACE metadata' ############################################################################### # Read a CMYK image as a CMYK image -def jpeg_9(): +def test_jpeg_9(): gdal.SetConfigOption('GDAL_JPEG_TO_RGB', 'NO') ds = gdal.Open('data/rgb_ntf_cmyk.jpg') @@ -367,69 +303,51 @@ def jpeg_9(): expected_cs = 21187 - if ds.GetRasterBand(1).Checksum() != expected_cs: - gdaltest.post_reason('Wrong checksum on copied image.') - print(ds.GetRasterBand(1).Checksum()) - return 'fail' + assert ds.GetRasterBand(1).Checksum() == expected_cs, \ + 'Wrong checksum on copied image.' - if ds.GetRasterBand(1).GetRasterColorInterpretation() != gdal.GCI_CyanBand: - gdaltest.post_reason('Wrong color interpretation.') - print(ds.GetRasterBand(1).GetRasterColorInterpretation()) - return 'fail' + assert ds.GetRasterBand(1).GetRasterColorInterpretation() == gdal.GCI_CyanBand, \ + 'Wrong color interpretation.' expected_cs = 21054 - if ds.GetRasterBand(2).Checksum() != expected_cs: - gdaltest.post_reason('Wrong checksum on copied image.') - print(ds.GetRasterBand(2).Checksum()) - return 'fail' + assert ds.GetRasterBand(2).Checksum() == expected_cs, \ + 'Wrong checksum on copied image.' - if ds.GetRasterBand(2).GetRasterColorInterpretation() != gdal.GCI_MagentaBand: - gdaltest.post_reason('Wrong color interpretation.') - print(ds.GetRasterBand(2).GetRasterColorInterpretation()) - return 'fail' + assert ds.GetRasterBand(2).GetRasterColorInterpretation() == gdal.GCI_MagentaBand, \ + 'Wrong color interpretation.' expected_cs = 21499 - if ds.GetRasterBand(3).Checksum() != expected_cs: - gdaltest.post_reason('Wrong checksum on copied image.') - print(ds.GetRasterBand(3).Checksum()) - return 'fail' + assert ds.GetRasterBand(3).Checksum() == expected_cs, \ + 'Wrong checksum on copied image.' - if ds.GetRasterBand(3).GetRasterColorInterpretation() != gdal.GCI_YellowBand: - gdaltest.post_reason('Wrong color interpretation.') - print(ds.GetRasterBand(3).GetRasterColorInterpretation()) - return 'fail' + assert ds.GetRasterBand(3).GetRasterColorInterpretation() == gdal.GCI_YellowBand, \ + 'Wrong color interpretation.' expected_cs = 21069 - if ds.GetRasterBand(4).Checksum() != expected_cs: - gdaltest.post_reason('Wrong checksum on copied image.') - print(ds.GetRasterBand(4).Checksum()) - return 'fail' + assert ds.GetRasterBand(4).Checksum() == expected_cs, \ + 'Wrong checksum on copied image.' - if ds.GetRasterBand(4).GetRasterColorInterpretation() != gdal.GCI_BlackBand: - gdaltest.post_reason('Wrong color interpretation.') - print(ds.GetRasterBand(4).GetRasterColorInterpretation()) - return 'fail' - - return 'success' + assert ds.GetRasterBand(4).GetRasterColorInterpretation() == gdal.GCI_BlackBand, \ + 'Wrong color interpretation.' ############################################################################### # Check reading a 12-bit JPEG -def jpeg_10(): +def test_jpeg_10(): if gdaltest.jpeg_version == '9b': # Fails for some reason - return 'skip' + pytest.skip() # Check if JPEG driver supports 12bit JPEG reading/writing drv = gdal.GetDriverByName('JPEG') md = drv.GetMetadata() if md[gdal.DMD_CREATIONDATATYPES].find('UInt16') == -1: sys.stdout.write('(12bit jpeg not available) ... ') - return 'skip' + pytest.skip() try: os.remove('data/12bit_rose_extract.jpg.aux.xml') @@ -437,12 +355,9 @@ def jpeg_10(): pass ds = gdal.Open('data/12bit_rose_extract.jpg') - if ds.GetRasterBand(1).DataType != gdal.GDT_UInt16: - return 'fail' + assert ds.GetRasterBand(1).DataType == gdal.GDT_UInt16 stats = ds.GetRasterBand(1).GetStatistics(0, 1) - if stats[2] < 3613 or stats[2] > 3614: - print(stats) - return 'fail' + assert stats[2] >= 3613 and stats[2] <= 3614 ds = None try: @@ -450,124 +365,105 @@ def jpeg_10(): except OSError: pass - return 'success' - + ############################################################################### # Check creating a 12-bit JPEG -def jpeg_11(): +def test_jpeg_11(): if gdaltest.jpeg_version == '9b': # Fails for some reason - return 'skip' + pytest.skip() # Check if JPEG driver supports 12bit JPEG reading/writing drv = gdal.GetDriverByName('JPEG') md = drv.GetMetadata() if md[gdal.DMD_CREATIONDATATYPES].find('UInt16') == -1: sys.stdout.write('(12bit jpeg not available) ... ') - return 'skip' + pytest.skip() ds = gdal.Open('data/12bit_rose_extract.jpg') out_ds = gdal.GetDriverByName('JPEG').CreateCopy('tmp/jpeg11.jpg', ds) del out_ds ds = gdal.Open('tmp/jpeg11.jpg') - if ds.GetRasterBand(1).DataType != gdal.GDT_UInt16: - return 'fail' + assert ds.GetRasterBand(1).DataType == gdal.GDT_UInt16 stats = ds.GetRasterBand(1).GetStatistics(0, 1) - if stats[2] < 3613 or stats[2] > 3614: - print(stats) - return 'fail' + assert stats[2] >= 3613 and stats[2] <= 3614 ds = None gdal.GetDriverByName('JPEG').Delete('tmp/jpeg11.jpg') - return 'success' - ############################################################################### # Test reading a stored JPEG in ZIP (#3908) -def jpeg_12(): +def test_jpeg_12(): ds = gdal.Open('/vsizip/data/byte_jpg.zip') - if ds is None: - return 'fail' + assert ds is not None gdal.ErrorReset() ds.GetRasterBand(1).Checksum() - if gdal.GetLastErrorMsg() != '': - return 'fail' + assert gdal.GetLastErrorMsg() == '' gdal.ErrorReset() ds.GetRasterBand(1).GetMaskBand().Checksum() - if gdal.GetLastErrorMsg() != '': - return 'fail' + assert gdal.GetLastErrorMsg() == '' ds = None - return 'success' - ############################################################################### # Test writing to /vsistdout/ -def jpeg_13(): +def test_jpeg_13(): src_ds = gdal.Open('data/byte.tif') ds = gdal.GetDriverByName('JPEG').CreateCopy( '/vsistdout_redirect//vsimem/tmp.jpg', src_ds) - if ds.GetRasterBand(1).Checksum() != 0: - return 'fail' + assert ds.GetRasterBand(1).Checksum() == 0 ds.ReadRaster(0, 0, 1, 1) src_ds = None ds = None ds = gdal.Open('/vsimem/tmp.jpg') - if ds is None: - return 'fail' + assert ds is not None gdal.Unlink('/vsimem/tmp.jpg') - return 'success' - ############################################################################### # Test writing to /vsistdout/ -def jpeg_14(): +def test_jpeg_14(): if gdaltest.jpeg_version == '9b': # Fails for some reason - return 'skip' + pytest.skip() # Check if JPEG driver supports 12bit JPEG reading/writing drv = gdal.GetDriverByName('JPEG') md = drv.GetMetadata() if md[gdal.DMD_CREATIONDATATYPES].find('UInt16') == -1: sys.stdout.write('(12bit jpeg not available) ... ') - return 'skip' + pytest.skip() src_ds = gdal.Open('data/12bit_rose_extract.jpg') ds = drv.CreateCopy('/vsistdout_redirect//vsimem/tmp.jpg', src_ds) - if ds.GetRasterBand(1).Checksum() != 0: - return 'fail' + assert ds.GetRasterBand(1).Checksum() == 0 src_ds = None ds = None ds = gdal.Open('/vsimem/tmp.jpg') - if ds is None: - return 'fail' + assert ds is not None gdal.Unlink('/vsimem/tmp.jpg') - return 'success' - ############################################################################### # Test CreateCopy() interruption -def jpeg_15(): +def test_jpeg_15(): tst = gdaltest.GDALTest('JPEG', 'albania.jpg', 2, 17016) @@ -577,24 +473,16 @@ def jpeg_15(): # Test overview support -def jpeg_16(): +def test_jpeg_16(): shutil.copy('data/albania.jpg', 'tmp/albania.jpg') gdal.Unlink('tmp/albania.jpg.ovr') ds = gdal.Open('tmp/albania.jpg') - if ds.GetRasterBand(1).GetOverviewCount() != 1: - gdaltest.post_reason('fail') - return 'fail' - if ds.GetRasterBand(1).GetOverview(-1) is not None: - gdaltest.post_reason('fail') - return 'fail' - if ds.GetRasterBand(1).GetOverview(1) is not None: - gdaltest.post_reason('fail') - return 'fail' - if ds.GetRasterBand(1).GetOverview(0) is None: - gdaltest.post_reason('fail') - return 'fail' + assert ds.GetRasterBand(1).GetOverviewCount() == 1 + assert ds.GetRasterBand(1).GetOverview(-1) is None + assert ds.GetRasterBand(1).GetOverview(1) is None + assert ds.GetRasterBand(1).GetOverview(0) is not None # "Internal" overview cs = ds.GetRasterBand(1).GetOverview(0).Checksum() @@ -602,61 +490,44 @@ def jpeg_16(): expected_cs = 34218 else: expected_cs = 31892 - if cs != expected_cs: - gdaltest.post_reason('fail') - print(cs) - return 'fail' + assert cs == expected_cs # Build external overviews ds.BuildOverviews('NEAR', [2, 4]) - if ds.GetRasterBand(1).GetOverviewCount() != 2: - gdaltest.post_reason('fail') - return 'fail' + assert ds.GetRasterBand(1).GetOverviewCount() == 2 # Check updated checksum cs = ds.GetRasterBand(1).GetOverview(0).Checksum() if gdaltest.jpeg_version in ('8', '9b'): expected_cs = 33698 else: expected_cs = 32460 - if cs != expected_cs: - gdaltest.post_reason('fail') - print(cs) - return 'fail' + assert cs == expected_cs ds = None # Check we are using external overviews ds = gdal.Open('tmp/albania.jpg') - if ds.GetRasterBand(1).GetOverviewCount() != 2: - gdaltest.post_reason('fail') - return 'fail' + assert ds.GetRasterBand(1).GetOverviewCount() == 2 cs = ds.GetRasterBand(1).GetOverview(0).Checksum() if gdaltest.jpeg_version in ('8', '9b'): expected_cs = 33698 else: expected_cs = 32460 - if cs != expected_cs: - gdaltest.post_reason('fail') - print(cs) - return 'fail' + assert cs == expected_cs ds = None - return 'success' - ############################################################################### # Test bogus files -def jpeg_17(): +def test_jpeg_17(): gdal.ErrorReset() with gdaltest.error_handler('CPLQuietErrorHandler'): ds = gdal.Open('data/bogus.jpg') - if (ds is not None or + assert (not (ds is not None or gdal.GetLastErrorType() != gdal.CE_Failure or - gdal.GetLastErrorMsg() == ''): - gdaltest.post_reason('fail') - return 'fail' + gdal.GetLastErrorMsg() == '')) gdal.ErrorReset() ds = gdal.Open('data/byte_corrupted.jpg') @@ -666,9 +537,7 @@ def jpeg_17(): if (gdal.GetLastErrorType() != gdal.CE_Failure or gdal.GetLastErrorMsg() == ''): # libjpeg-turbo 1.4.0 doesn't emit errors... - if cs != 4925: - gdaltest.post_reason('fail') - return 'fail' + assert cs == 4925 gdal.ErrorReset() ds = gdal.Open('data/byte_corrupted2.jpg') @@ -677,10 +546,8 @@ def jpeg_17(): # libjpeg: Corrupt JPEG data: found marker 0x00 instead of RST63 ds.GetRasterBand(1).Checksum() - if (gdal.GetLastErrorType() != gdal.CE_Warning or - gdal.GetLastErrorMsg() == ''): - gdaltest.post_reason('fail') - return 'fail' + assert (not (gdal.GetLastErrorType() != gdal.CE_Warning or + gdal.GetLastErrorMsg() == '')) gdal.ErrorReset() ds = gdal.Open('data/byte_corrupted2.jpg') @@ -691,18 +558,14 @@ def jpeg_17(): ds.GetRasterBand(1).Checksum() gdal.SetConfigOption('GDAL_ERROR_ON_LIBJPEG_WARNING', None) - if (gdal.GetLastErrorType() != gdal.CE_Failure or - gdal.GetLastErrorMsg() == ''): - gdaltest.post_reason('fail') - return 'fail' - - return 'success' + assert (not (gdal.GetLastErrorType() != gdal.CE_Failure or + gdal.GetLastErrorMsg() == '')) ############################################################################### # Test situation where we cause a restart and need to reset scale -def jpeg_18(): +def test_jpeg_18(): height = 1024 width = 1024 src_ds = gdal.GetDriverByName('GTiff').Create('/vsimem/jpeg_18.tif', @@ -721,58 +584,42 @@ def jpeg_18(): line0 = ds.GetRasterBand(1).ReadRaster(0, 0, width, 1) data = struct.unpack('B' * width, line0) - if abs(data[0] - 0) > 10: - return 'fail' + assert abs(data[0] - 0) <= 10 line1023 = ds.GetRasterBand(1).ReadRaster(0, height - 1, width, 1) data = struct.unpack('B' * width, line1023) - if abs(data[0] - 255) > 10: - return 'fail' + assert abs(data[0] - 255) <= 10 line0_ovr1 = ds.GetRasterBand(1).GetOverview(1).ReadRaster(0, 0, int(width / 4), 1) data = struct.unpack('B' * (int(width / 4)), line0_ovr1) - if abs(data[0] - 0) > 10: - return 'fail' + assert abs(data[0] - 0) <= 10 line1023_bis = ds.GetRasterBand(1).ReadRaster(0, height - 1, width, 1) - if line1023_bis == line0 or line1023 != line1023_bis: - gdaltest.post_reason('fail') - return 'fail' + assert line1023_bis != line0 and line1023 == line1023_bis line0_bis = ds.GetRasterBand(1).ReadRaster(0, 0, width, 1) - if line0 != line0_bis: - gdaltest.post_reason('fail') - return 'fail' + assert line0 == line0_bis line255_ovr1 = ds.GetRasterBand(1).GetOverview(1).ReadRaster( 0, int(height / 4) - 1, int(width / 4), 1) data = struct.unpack('B' * int(width / 4), line255_ovr1) - if abs(data[0] - 255) > 10: - return 'fail' + assert abs(data[0] - 255) <= 10 line0_bis = ds.GetRasterBand(1).ReadRaster(0, 0, width, 1) - if line0 != line0_bis: - gdaltest.post_reason('fail') - return 'fail' + assert line0 == line0_bis line0_ovr1_bis = ds.GetRasterBand(1).GetOverview(1).ReadRaster( 0, 0, int(width / 4), 1) - if line0_ovr1 != line0_ovr1_bis: - gdaltest.post_reason('fail') - return 'fail' + assert line0_ovr1 == line0_ovr1_bis line255_ovr1_bis = ds.GetRasterBand(1).GetOverview(1).ReadRaster( 0, int(height / 4) - 1, int(width / 4), 1) - if line255_ovr1 != line255_ovr1_bis: - gdaltest.post_reason('fail') - return 'fail' + assert line255_ovr1 == line255_ovr1_bis gdal.SetCacheMax(oldSize) ds = None gdal.Unlink('/vsimem/jpeg_18.jpg') - return 'success' - ############################################################################### # Test MSB ordering of bits in mask (#5102) -def jpeg_19(): +def test_jpeg_19(): for width, height, iX in [(32, 32, 12), (25, 25, 8), (24, 25, 8)]: src_ds = gdal.GetDriverByName('GTiff').Create('/vsimem/jpeg_19.tif', @@ -811,117 +658,81 @@ def jpeg_19(): gdal.VSIFCloseL(f) if (width, height, iX) == (24, 25, 8): - if data1 != data2: - gdaltest.post_reason('fail') - return 'fail' + assert data1 == data2 else: - if data1 == data2: - gdaltest.post_reason('fail') - return 'fail' + assert data1 != data2 # Check the file with the LSB bit mask order ds = gdal.Open('/vsimem/jpeg_19.jpg') jpg_mask_data = ds.GetRasterBand(1).GetMaskBand().ReadRaster( 0, 0, width, height) ds = None - if tiff_mask_data != jpg_mask_data: - gdaltest.post_reason('fail') - return 'fail' + assert tiff_mask_data == jpg_mask_data # Check the file with the MSB bit mask order ds = gdal.Open('/vsimem/jpeg_19_msb.jpg') jpg_mask_data = ds.GetRasterBand(1).GetMaskBand().ReadRaster( 0, 0, width, height) ds = None - if tiff_mask_data != jpg_mask_data: - gdaltest.post_reason('fail') - return 'fail' + assert tiff_mask_data == jpg_mask_data gdal.GetDriverByName('GTiff').Delete('/vsimem/jpeg_19.tif') gdal.GetDriverByName('JPEG').Delete('/vsimem/jpeg_19.jpg') gdal.GetDriverByName('JPEG').Delete('/vsimem/jpeg_19_msb.jpg') - return 'success' - + ############################################################################### # Test correct GCP reading with PAM (#5352) -def jpeg_20(): +def test_jpeg_20(): src_ds = gdal.Open('data/rgb_gcp.vrt') ds = gdal.GetDriverByName('JPEG').CreateCopy('/vsimem/jpeg_20.jpg', src_ds) ds = None ds = gdal.Open('/vsimem/jpeg_20.jpg') - if ds.GetGCPProjection().find('GEOGCS["WGS 84"') != 0: - gdaltest.post_reason('failure') - print(ds.GetGCPProjection()) - return 'fail' - if ds.GetGCPCount() != 4: - gdaltest.post_reason('failure') - return 'fail' - if len(ds.GetGCPs()) != 4: - gdaltest.post_reason('failure') - return 'fail' + assert ds.GetGCPProjection().find('GEOGCS["WGS 84"') == 0 + assert ds.GetGCPCount() == 4 + assert len(ds.GetGCPs()) == 4 ds = None gdal.GetDriverByName('JPEG').Delete('/vsimem/jpeg_20.jpg') - return 'success' - ############################################################################### # Test implicit and EXIF overviews -def jpeg_21(): +def test_jpeg_21(): ds = gdal.Open('data/black_with_white_exif_ovr.jpg') - if ds.GetRasterBand(1).GetOverviewCount() != 3: - gdaltest.post_reason('failure') - print(ds.GetRasterBand(1).GetOverviewCount()) - return 'fail' + assert ds.GetRasterBand(1).GetOverviewCount() == 3 expected_dim_cs = [[512, 512, 0], [256, 256, 0], [196, 196, 12681]] i = 0 for expected_w, expected_h, expected_cs in expected_dim_cs: ovr = ds.GetRasterBand(1).GetOverview(i) cs = ovr.Checksum() - if (ovr.XSize != expected_w or + assert (not (ovr.XSize != expected_w or ovr.YSize != expected_h or - cs != expected_cs): - gdaltest.post_reason('failure') - print(ovr.XSize) - print(ovr.YSize) - print(cs) - return 'fail' + cs != expected_cs)) i = i + 1 ds = None - return 'success' - ############################################################################### # Test generation of EXIF overviews -def jpeg_22(): +def test_jpeg_22(): src_ds = gdal.GetDriverByName('Mem').Create('', 4096, 2048) src_ds.GetRasterBand(1).Fill(255) ds = gdal.GetDriverByName('JPEG').CreateCopy( '/vsimem/jpeg_22.jpg', src_ds, options=['EXIF_THUMBNAIL=YES']) src_ds = None - if ds.GetRasterBand(1).GetOverviewCount() != 4: - gdaltest.post_reason('failure') - print(ds.GetRasterBand(1).GetOverviewCount()) - return 'fail' + assert ds.GetRasterBand(1).GetOverviewCount() == 4 ovr = ds.GetRasterBand(1).GetOverview(3) cs = ovr.Checksum() - if ovr.XSize != 128 or ovr.YSize != 64 or cs != 34957: - gdaltest.post_reason('failure') - print(ovr.XSize) - print(ovr.YSize) - print(cs) - return 'fail' + assert ovr.XSize == 128 and ovr.YSize == 64 and cs == 34957 ds = None # With 3 bands @@ -931,11 +742,7 @@ def jpeg_22(): '/vsimem/jpeg_22.jpg', src_ds, options=['EXIF_THUMBNAIL=YES']) src_ds = None ovr = ds.GetRasterBand(1).GetOverview(3) - if ovr.XSize != 64 or ovr.YSize != 128: - gdaltest.post_reason('failure') - print(ovr.XSize) - print(ovr.YSize) - return 'fail' + assert ovr.XSize == 64 and ovr.YSize == 128 ds = None # With comment @@ -946,14 +753,8 @@ def jpeg_22(): options=['COMMENT=foo', 'EXIF_THUMBNAIL=YES', 'THUMBNAIL_WIDTH=40']) src_ds = None ovr = ds.GetRasterBand(1).GetOverview(3) - if ds.GetMetadataItem('COMMENT') != 'foo': - gdaltest.post_reason('failure') - return 'fail' - if ovr.XSize != 40 or ovr.YSize != 80: - gdaltest.post_reason('failure') - print(ovr.XSize) - print(ovr.YSize) - return 'fail' + assert ds.GetMetadataItem('COMMENT') == 'foo' + assert ovr.XSize == 40 and ovr.YSize == 80 ds = None src_ds = gdal.GetDriverByName('Mem').Create('', 2048, 4096) @@ -963,11 +764,7 @@ def jpeg_22(): options=['EXIF_THUMBNAIL=YES', 'THUMBNAIL_HEIGHT=60']) src_ds = None ovr = ds.GetRasterBand(1).GetOverview(3) - if ovr.XSize != 30 or ovr.YSize != 60: - gdaltest.post_reason('failure') - print(ovr.XSize) - print(ovr.YSize) - return 'fail' + assert ovr.XSize == 30 and ovr.YSize == 60 ds = None src_ds = gdal.GetDriverByName('Mem').Create('', 2048, 4096) @@ -979,22 +776,16 @@ def jpeg_22(): 'THUMBNAIL_HEIGHT=40']) src_ds = None ovr = ds.GetRasterBand(1).GetOverview(3) - if ovr.XSize != 50 or ovr.YSize != 40: - gdaltest.post_reason('failure') - print(ovr.XSize) - print(ovr.YSize) - return 'fail' + assert ovr.XSize == 50 and ovr.YSize == 40 ds = None gdal.Unlink('/vsimem/jpeg_22.jpg') - return 'success' - ############################################################################### # Test optimized JPEG IRasterIO -def jpeg_23(): +def test_jpeg_23(): ds = gdal.Open('data/albania.jpg') cs = [ds.GetRasterBand(i + 1).Checksum() for i in range(3)] @@ -1004,9 +795,7 @@ def jpeg_23(): '', ds.RasterXSize, ds.RasterYSize, 3) tmp_ds.WriteRaster(0, 0, ds.RasterXSize, ds.RasterYSize, data) got_cs = [tmp_ds.GetRasterBand(i + 1).Checksum() for i in range(3)] - if cs != got_cs: - gdaltest.post_reason('failure') - return 'fail' + assert cs == got_cs # Pixel interleaved data = ds.ReadRaster(0, 0, ds.RasterXSize, ds.RasterYSize, @@ -1016,9 +805,7 @@ def jpeg_23(): tmp_ds.WriteRaster(0, 0, ds.RasterXSize, ds.RasterYSize, data, buf_pixel_space=3, buf_band_space=1) got_cs = [tmp_ds.GetRasterBand(i + 1).Checksum() for i in range(3)] - if cs != got_cs: - gdaltest.post_reason('failure') - return 'fail' + assert cs == got_cs # Pixel interleaved with padding data = ds.ReadRaster(0, 0, ds.RasterXSize, ds.RasterYSize, @@ -1028,18 +815,14 @@ def jpeg_23(): tmp_ds.WriteRaster(0, 0, ds.RasterXSize, ds.RasterYSize, data, buf_pixel_space=4, buf_band_space=1) got_cs = [tmp_ds.GetRasterBand(i + 1).Checksum() for i in range(3)] - if cs != got_cs: - gdaltest.post_reason('failure') - return 'fail' - - return 'success' + assert cs == got_cs ############################################################################### # Test Arithmetic coding (and if not enabled, will trigger error code handling # in CreateCopy()) -def jpeg_24(): +def test_jpeg_24(): has_arithmetic = bool(gdal.GetDriverByName('JPEG').GetMetadataItem( 'DMD_CREATIONOPTIONLIST').find('ARITHMETIC') >= 0) @@ -1055,25 +838,22 @@ def jpeg_24(): if gdal.GetLastErrorMsg().find('Requested feature was omitted at compile time') >= 0: ds = None gdal.Unlink('/vsimem/byte.jpg') - return 'skip' + pytest.skip() expected_cs = 4743 - if ds.GetRasterBand(1).Checksum() != expected_cs: - gdaltest.post_reason('Wrong checksum on copied image.') - print(ds.GetRasterBand(1).Checksum()) - return 'fail' + assert ds.GetRasterBand(1).Checksum() == expected_cs, \ + 'Wrong checksum on copied image.' ds = None gdal.GetDriverByName('JPEG').Delete('/vsimem/byte.jpg') - return 'success' - + ############################################################################### # Test COMMENT -def jpeg_25(): +def test_jpeg_25(): src_ds = gdal.Open('data/byte.tif') ds = gdal.GetDriverByName('JPEG').CreateCopy( @@ -1081,38 +861,32 @@ def jpeg_25(): ds = None ds = gdal.Open('/vsimem/byte.jpg') if ds.GetMetadataItem('COMMENT') != 'my comment': - gdaltest.post_reason('Wrong comment.') print(ds.GetMetadata()) - return 'fail' + pytest.fail('Wrong comment.') ds = None gdal.GetDriverByName('JPEG').Delete('/vsimem/byte.jpg') - return 'success' - ############################################################################### # Test creation error -def jpeg_26(): +def test_jpeg_26(): src_ds = gdal.GetDriverByName('Mem').Create('', 70000, 1) with gdaltest.error_handler(): ds = gdal.GetDriverByName('JPEG').CreateCopy( '/vsimem/jpeg_26.jpg', src_ds) - if ds is not None: - return 'fail' + assert ds is None gdal.Unlink('/vsimem/jpeg_26.jpg') - return 'success' - ############################################################################### # Test reading a file that contains the 2 denial of service # vulnerabilities listed in # http://www.libjpeg-jpeg_26.org/pmwiki/uploads/About/TwoIssueswiththeJPEGStandard.pdf -def jpeg_27(): +def test_jpeg_27(): # Should error out with 'Reading this strip would require # libjpeg to allocate at least...' @@ -1120,9 +894,7 @@ def jpeg_27(): ds = gdal.Open('/vsisubfile/146,/vsizip/../gcore/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 'Scan number... gdal.ErrorReset() @@ -1133,17 +905,14 @@ def jpeg_27(): cs = ds.GetRasterBand(1).Checksum() gdal.SetConfigOption('GDAL_ALLOW_LARGE_LIBJPEG_MEM_ALLOC', None) gdal.SetConfigOption('GDAL_JPEG_MAX_ALLOWED_SCAN_NUMBER', None) - if gdal.GetLastErrorMsg() == '': - gdaltest.post_reason('fail') - return 'fail' - - return 'success' + assert gdal.GetLastErrorMsg() != '' + ############################################################################### # Test writing of EXIF and GPS tags -def jpeg_28(): +def test_jpeg_28(): tmpfilename = '/vsimem/jpeg_28.jpg' @@ -1152,9 +921,7 @@ def jpeg_28(): ds = gdal.GetDriverByName('JPEG').CreateCopy(tmpfilename, src_ds) src_ds = None ds = gdal.Open(tmpfilename) - if ds.GetMetadata(): - gdaltest.post_reason('fail') - return 'fail' + assert not ds.GetMetadata() # EXIF tags only src_ds = gdal.GetDriverByName('MEM').Create('', 1, 1) @@ -1184,16 +951,11 @@ def jpeg_28(): with gdaltest.error_handler(): gdal.GetDriverByName('JPEG').CreateCopy(tmpfilename, src_ds) src_ds = None - if gdal.VSIStatL(tmpfilename + '.aux.xml') is not None: - gdaltest.post_reason('fail') - return 'fail' + assert gdal.VSIStatL(tmpfilename + '.aux.xml') is None ds = gdal.Open(tmpfilename) got_md = ds.GetMetadata() expected_md = {'EXIF_DateTimeDigitized': '0123456789012345678', 'EXIF_DateTimeOriginal': '0123456789012345678', 'EXIF_Orientation': '10', 'EXIF_ApertureValue': '(0)', 'EXIF_YResolution': '(96)', 'EXIF_XResolution': '(96)', 'EXIF_TransferFunction': '0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0', 'EXIF_ExifVersion': '0123', 'EXIF_DateTime': 'dt ', 'EXIF_FlashpixVersion': 'ABCD', 'EXIF_ComponentsConfiguration': '0x1f 0x00 0x00 0x00', 'EXIF_Make': 'make', 'EXIF_StandardOutputSensitivity': '123456789', 'EXIF_ResolutionUnit': '2', 'EXIF_CompressedBitsPerPixel': '(0)', 'EXIF_SpatialFrequencyResponse': '0xab 0xcd', 'EXIF_ISOSpeedRatings': '1 2 3'} - if got_md != expected_md: - gdaltest.post_reason('fail') - print(got_md) - return 'fail' + assert got_md == expected_md # Test SRATIONAL for val in (-1.5, -1, -0.5, 0, 0.5, 1, 1.5): @@ -1201,17 +963,11 @@ def jpeg_28(): src_ds.SetMetadataItem('EXIF_ShutterSpeedValue', str(val)) gdal.GetDriverByName('JPEG').CreateCopy(tmpfilename, src_ds) src_ds = None - if gdal.VSIStatL(tmpfilename + '.aux.xml') is not None: - gdaltest.post_reason('fail') - return 'fail' + assert gdal.VSIStatL(tmpfilename + '.aux.xml') is None ds = gdal.Open(tmpfilename) got_val = ds.GetMetadataItem('EXIF_ShutterSpeedValue') got_val = got_val.replace('(', '').replace(')', '') - if float(got_val) != val: - gdaltest.post_reason('fail') - print(val) - print(ds.GetMetadataItem('EXIF_ShutterSpeedValue')) - return 'fail' + assert float(got_val) == val, ds.GetMetadataItem('EXIF_ShutterSpeedValue') # Test RATIONAL for val in (0, 0.5, 1, 1.5): @@ -1219,17 +975,11 @@ def jpeg_28(): src_ds.SetMetadataItem('EXIF_ApertureValue', str(val)) gdal.GetDriverByName('JPEG').CreateCopy(tmpfilename, src_ds) src_ds = None - if gdal.VSIStatL(tmpfilename + '.aux.xml') is not None: - gdaltest.post_reason('fail') - return 'fail' + assert gdal.VSIStatL(tmpfilename + '.aux.xml') is None ds = gdal.Open(tmpfilename) got_val = ds.GetMetadataItem('EXIF_ApertureValue') got_val = got_val.replace('(', '').replace(')', '') - if float(got_val) != val: - gdaltest.post_reason('fail') - print(val) - print(ds.GetMetadataItem('EXIF_ApertureValue')) - return 'fail' + assert float(got_val) == val, ds.GetMetadataItem('EXIF_ApertureValue') # GPS tags only src_ds = gdal.GetDriverByName('MEM').Create('', 1, 1) @@ -1237,15 +987,10 @@ def jpeg_28(): src_ds.SetMetadataItem('EXIF_GPSLatitude', '49 34 56.5') gdal.GetDriverByName('JPEG').CreateCopy(tmpfilename, src_ds) src_ds = None - if gdal.VSIStatL(tmpfilename + '.aux.xml') is not None: - gdaltest.post_reason('fail') - return 'fail' + assert gdal.VSIStatL(tmpfilename + '.aux.xml') is None ds = gdal.Open(tmpfilename) got_md = ds.GetMetadata() - if got_md != {'EXIF_GPSLatitudeRef': 'N', 'EXIF_GPSLatitude': '(49) (34) (56.5)'}: - gdaltest.post_reason('fail') - print(got_md) - return 'fail' + assert got_md == {'EXIF_GPSLatitudeRef': 'N', 'EXIF_GPSLatitude': '(49) (34) (56.5)'} ds = None # EXIF and GPS tags @@ -1254,15 +999,10 @@ def jpeg_28(): src_ds.SetMetadataItem('EXIF_GPSLatitudeRef', 'N') gdal.GetDriverByName('JPEG').CreateCopy(tmpfilename, src_ds) src_ds = None - if gdal.VSIStatL(tmpfilename + '.aux.xml') is not None: - gdaltest.post_reason('fail') - return 'fail' + assert gdal.VSIStatL(tmpfilename + '.aux.xml') is None ds = gdal.Open(tmpfilename) got_md = ds.GetMetadata() - if got_md != {'EXIF_ExifVersion': '0231', 'EXIF_GPSLatitudeRef': 'N'}: - gdaltest.post_reason('fail') - print(got_md) - return 'fail' + assert got_md == {'EXIF_ExifVersion': '0231', 'EXIF_GPSLatitudeRef': 'N'} ds = None # EXIF and other metadata @@ -1273,15 +1013,10 @@ def jpeg_28(): with gdaltest.error_handler(): gdal.GetDriverByName('JPEG').CreateCopy(tmpfilename, src_ds) src_ds = None - if gdal.VSIStatL(tmpfilename + '.aux.xml') is None: - gdaltest.post_reason('fail') - return 'fail' + assert gdal.VSIStatL(tmpfilename + '.aux.xml') is not None ds = gdal.Open(tmpfilename) got_md = ds.GetMetadata() - if got_md != {'EXIF_ExifVersion': '0231', 'EXIF_invalid': 'foo', 'FOO': 'BAR'}: - gdaltest.post_reason('fail') - print(got_md) - return 'fail' + assert got_md == {'EXIF_ExifVersion': '0231', 'EXIF_invalid': 'foo', 'FOO': 'BAR'} ds = None # Too much content for EXIF @@ -1299,71 +1034,19 @@ def jpeg_28(): gdal.GetDriverByName('JPEG').CreateCopy(tmpfilename, src_ds, options=['EXIF_THUMBNAIL=YES', 'THUMBNAIL_WIDTH=32', 'THUMBNAIL_HEIGHT=32']) src_ds = None - if gdal.VSIStatL(tmpfilename + '.aux.xml') is not None: - gdaltest.post_reason('fail') - return 'fail' + assert gdal.VSIStatL(tmpfilename + '.aux.xml') is None ds = gdal.Open(tmpfilename) got_md = ds.GetMetadata() - if got_md != {'EXIF_ExifVersion': '0231', 'EXIF_GPSLatitudeRef': 'N'}: - gdaltest.post_reason('fail') - print(got_md) - return 'fail' - if ds.GetRasterBand(1).GetOverview(ds.GetRasterBand(1).GetOverviewCount() - 1).XSize != 32: - gdaltest.post_reason('fail') - return 'fail' + assert got_md == {'EXIF_ExifVersion': '0231', 'EXIF_GPSLatitudeRef': 'N'} + assert ds.GetRasterBand(1).GetOverview(ds.GetRasterBand(1).GetOverviewCount() - 1).XSize == 32 ds = None gdal.Unlink(tmpfilename) - return 'success' - ############################################################################### # Cleanup -def jpeg_cleanup(): +def test_jpeg_cleanup(): gdal.Unlink('tmp/albania.jpg') gdal.Unlink('tmp/albania.jpg.ovr') - return 'success' - - -gdaltest_list = [ - jpeg_1, - jpeg_2, - jpeg_3, - jpeg_4, - jpeg_5, - jpeg_6, - jpeg_7, - jpeg_8, - jpeg_9, - jpeg_10, - jpeg_11, - jpeg_12, - jpeg_13, - jpeg_14, - jpeg_15, - jpeg_16, - jpeg_17, - jpeg_18, - jpeg_19, - jpeg_20, - jpeg_21, - jpeg_22, - jpeg_23, - jpeg_24, - jpeg_25, - jpeg_26, - jpeg_27, - jpeg_28, - jpeg_cleanup] - -# gdaltest_list = [ jpeg_28 ] - -if __name__ == '__main__': - - gdaltest.setup_run('jpeg') - - gdaltest.run_tests(gdaltest_list) - - sys.exit(gdaltest.summarize()) diff --git a/autotest/gdrivers/jpeg2000.py b/autotest/gdrivers/jpeg2000.py index 3f2ec599568d..f6ed292ed9e3 100755 --- a/autotest/gdrivers/jpeg2000.py +++ b/autotest/gdrivers/jpeg2000.py @@ -28,12 +28,11 @@ # DEALINGS IN THE SOFTWARE. ############################################################################### -import sys from osgeo import gdal -sys.path.append('../pymod') import gdaltest +import pytest gdaltest.buggy_jasper = None @@ -64,22 +63,20 @@ def is_buggy_jasper(): # Verify we have the driver. -def jpeg2000_1(): +def test_jpeg2000_1(): gdaltest.jpeg2000_drv = gdal.GetDriverByName('JPEG2000') gdaltest.deregister_all_jpeg2000_drivers_but('JPEG2000') - return 'success' - ############################################################################### # Open byte.jp2 -def jpeg2000_2(): +def test_jpeg2000_2(): if gdaltest.jpeg2000_drv is None: - return 'skip' + pytest.skip() srs = """PROJCS["NAD27 / UTM zone 11N", GEOGCS["NAD27", @@ -109,10 +106,10 @@ def jpeg2000_2(): # Open int16.jp2 -def jpeg2000_3(): +def test_jpeg2000_3(): if gdaltest.jpeg2000_drv is None: - return 'skip' + pytest.skip() ds = gdal.Open('data/int16.jp2') ds_ref = gdal.Open('data/int16.tif') @@ -125,40 +122,34 @@ def jpeg2000_3(): ds_ref = None # Quite a bit of difference... - if maxdiff > 6: - gdaltest.post_reason('Image too different from reference') - return 'fail' - - return 'success' + assert maxdiff <= 6, 'Image too different from reference' ############################################################################### # Test copying byte.jp2 -def jpeg2000_4(): +def test_jpeg2000_4(): if gdaltest.jpeg2000_drv is None: - return 'skip' + pytest.skip() tst = gdaltest.GDALTest('JPEG2000', 'byte.jp2', 1, 50054) - if tst.testCreateCopy() != 'success': - return 'fail' + tst.testCreateCopy() # This may fail for a good reason if tst.testCreateCopy(check_gt=1, check_srs=1) != 'success': gdaltest.post_reason('This is an expected failure if Jasper has not the jp2_encode_uuid function') return 'expected_fail' - return 'success' - + ############################################################################### # Test copying int16.jp2 -def jpeg2000_5(): +def test_jpeg2000_5(): if gdaltest.jpeg2000_drv is None: - return 'skip' + pytest.skip() tst = gdaltest.GDALTest('JPEG2000', 'int16.jp2', 1, None) return tst.testCreateCopy() @@ -167,30 +158,27 @@ def jpeg2000_5(): # Test reading ll.jp2 -def jpeg2000_6(): +def test_jpeg2000_6(): if gdaltest.jpeg2000_drv is None: - return 'skip' + pytest.skip() tst = gdaltest.GDALTest('JPEG2000', 'll.jp2', 1, None) - if tst.testOpen() != 'success': - return 'fail' + tst.testOpen() ds = gdal.Open('data/ll.jp2') ds.GetRasterBand(1).Checksum() ds = None - return 'success' - ############################################################################### # Open byte.jp2.gz (test use of the VSIL API) -def jpeg2000_7(): +def test_jpeg2000_7(): if gdaltest.jpeg2000_drv is None: - return 'skip' + pytest.skip() tst = gdaltest.GDALTest('JPEG2000', '/vsigzip/data/byte.jp2.gz', 1, 50054, filename_absolute=1) return tst.testOpen() @@ -199,60 +187,46 @@ def jpeg2000_7(): # Test a JPEG2000 with the 3 bands having 13bit depth and the 4th one 1 bit -def jpeg2000_8(): +def test_jpeg2000_8(): if gdaltest.jpeg2000_drv is None or is_buggy_jasper(): - return 'skip' + pytest.skip() ds = gdal.Open('data/3_13bit_and_1bit.jp2') expected_checksums = [64570, 57277, 56048, 61292] for i in range(4): - if ds.GetRasterBand(i + 1).Checksum() != expected_checksums[i]: - gdaltest.post_reason('unexpected checksum (%d) for band %d' % (expected_checksums[i], i + 1)) - return 'fail' - - if ds.GetRasterBand(1).DataType != gdal.GDT_UInt16: - gdaltest.post_reason('unexpected data type') - return 'fail' + assert ds.GetRasterBand(i + 1).Checksum() == expected_checksums[i], \ + ('unexpected checksum (%d) for band %d' % (expected_checksums[i], i + 1)) - return 'success' + assert ds.GetRasterBand(1).DataType == gdal.GDT_UInt16, 'unexpected data type' ############################################################################### # Check that we can use .j2w world files (#4651) -def jpeg2000_9(): +def test_jpeg2000_9(): if gdaltest.jpeg2000_drv is None: - return 'skip' + pytest.skip() ds = gdal.Open('data/byte_without_geotransform.jp2') geotransform = ds.GetGeoTransform() - if abs(geotransform[0] - 440720) > 0.1 \ - or abs(geotransform[1] - 60) > 0.001 \ - or abs(geotransform[2] - 0) > 0.001 \ - or abs(geotransform[3] - 3751320) > 0.1 \ - or abs(geotransform[4] - 0) > 0.001 \ - or abs(geotransform[5] - -60) > 0.001: - print(geotransform) - gdaltest.post_reason('geotransform differs from expected') - return 'fail' + assert abs(geotransform[0] - 440720) <= 0.1 and abs(geotransform[1] - 60) <= 0.001 and abs(geotransform[2] - 0) <= 0.001 and abs(geotransform[3] - 3751320) <= 0.1 and abs(geotransform[4] - 0) <= 0.001 and abs(geotransform[5] - -60) <= 0.001, \ + 'geotransform differs from expected' ds = None - return 'success' - ############################################################################### # Check writing a file with more than 4 bands (#4686) -def jpeg2000_10(): +def test_jpeg2000_10(): if gdaltest.jpeg2000_drv is None: - return 'skip' + pytest.skip() src_ds = gdal.GetDriverByName('GTiff').Create('/vsimem/jpeg2000_10_src.tif', 128, 128, 5) for i in range(src_ds.RasterCount): @@ -262,40 +236,30 @@ def jpeg2000_10(): ds = None ds = gdal.Open('/vsimem/jpeg2000_10_dst.tif') - if ds is None: - return 'fail' + assert ds is not None for i in range(src_ds.RasterCount): - if ds.GetRasterBand(i + 1).Checksum() != src_ds.GetRasterBand(i + 1).Checksum(): - gdaltest.post_reason('bad checksum for band %d' % (i + 1)) - print(ds.GetRasterBand(i + 1).Checksum()) - print(src_ds.GetRasterBand(i + 1).Checksum()) - return 'fail' + assert ds.GetRasterBand(i + 1).Checksum() == src_ds.GetRasterBand(i + 1).Checksum(), \ + ('bad checksum for band %d' % (i + 1)) ds = None src_ds = None gdal.Unlink('/vsimem/jpeg2000_10_src.tif') gdal.Unlink('/vsimem/jpeg2000_10_dst.tif') - return 'success' - ############################################################################### # Test auto-promotion of 1bit alpha band to 8bit -def jpeg2000_11(): +def test_jpeg2000_11(): if gdaltest.jpeg2000_drv is None or is_buggy_jasper(): - return 'skip' + pytest.skip() ds = gdal.Open('data/stefan_full_rgba_alpha_1bit.jp2') fourth_band = ds.GetRasterBand(4) - if fourth_band.GetMetadataItem('NBITS', 'IMAGE_STRUCTURE') is not None: - return 'fail' + assert fourth_band.GetMetadataItem('NBITS', 'IMAGE_STRUCTURE') is None got_cs = fourth_band.Checksum() - if got_cs != 8527: - gdaltest.post_reason('fail') - print(got_cs) - return 'fail' + assert got_cs == 8527 jp2_bands_data = ds.ReadRaster(0, 0, ds.RasterXSize, ds.RasterYSize) jp2_fourth_band_data = fourth_band.ReadRaster(0, 0, ds.RasterXSize, ds.RasterYSize) fourth_band.ReadRaster(0, 0, ds.RasterXSize, ds.RasterYSize, int(ds.RasterXSize / 16), int(ds.RasterYSize / 16)) @@ -308,100 +272,78 @@ def jpeg2000_11(): # gtiff_fourth_band_subsampled_data = fourth_band.ReadRaster(0,0,ds.RasterXSize,ds.RasterYSize,ds.RasterXSize/16,ds.RasterYSize/16) tmp_ds = None gdal.GetDriverByName('GTiff').Delete('/vsimem/jpeg2000_11.tif') - if got_cs != 8527: - gdaltest.post_reason('fail') - print(got_cs) - return 'fail' + assert got_cs == 8527 - if jp2_bands_data != gtiff_bands_data: - gdaltest.post_reason('fail') - return 'fail' + assert jp2_bands_data == gtiff_bands_data - if jp2_fourth_band_data != gtiff_fourth_band_data: - gdaltest.post_reason('fail') - return 'fail' + assert jp2_fourth_band_data == gtiff_fourth_band_data ds = gdal.OpenEx('data/stefan_full_rgba_alpha_1bit.jp2', open_options=['1BIT_ALPHA_PROMOTION=NO']) fourth_band = ds.GetRasterBand(4) - if fourth_band.GetMetadataItem('NBITS', 'IMAGE_STRUCTURE') != '1': - gdaltest.post_reason('fail') - return 'fail' - - return 'success' + assert fourth_band.GetMetadataItem('NBITS', 'IMAGE_STRUCTURE') == '1' ############################################################################### -def jpeg2000_online_1(): +def test_jpeg2000_online_1(): if gdaltest.jpeg2000_drv is None: - return 'skip' + pytest.skip() if not gdaltest.download_file('http://download.osgeo.org/gdal/data/jpeg2000/7sisters200.j2k', '7sisters200.j2k'): - return 'skip' + pytest.skip() # Checksum = 32669 on my PC tst = gdaltest.GDALTest('JPEG2000', 'tmp/cache/7sisters200.j2k', 1, None, filename_absolute=1) - if tst.testOpen() != 'success': - return 'fail' + tst.testOpen() ds = gdal.Open('tmp/cache/7sisters200.j2k') ds.GetRasterBand(1).Checksum() ds = None - return 'success' - ############################################################################### -def jpeg2000_online_2(): +def test_jpeg2000_online_2(): if gdaltest.jpeg2000_drv is None: - return 'skip' + pytest.skip() if not gdaltest.download_file('http://download.osgeo.org/gdal/data/jpeg2000/gcp.jp2', 'gcp.jp2'): - return 'skip' + pytest.skip() # Checksum = 15621 on my PC tst = gdaltest.GDALTest('JPEG2000', 'tmp/cache/gcp.jp2', 1, None, filename_absolute=1) - if tst.testOpen() != 'success': - return 'fail' + tst.testOpen() ds = gdal.Open('tmp/cache/gcp.jp2') ds.GetRasterBand(1).Checksum() - if len(ds.GetGCPs()) != 15: - gdaltest.post_reason('bad number of GCP') - return 'fail' + assert len(ds.GetGCPs()) == 15, 'bad number of GCP' 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 ds.GetGCPProjection() != expected_wkt: - gdaltest.post_reason('bad GCP projection') - return 'fail' + assert ds.GetGCPProjection() == expected_wkt, 'bad GCP projection' ds = None - return 'success' - ############################################################################### -def jpeg2000_online_3(): +def test_jpeg2000_online_3(): if gdaltest.jpeg2000_drv is None: - return 'skip' + pytest.skip() if not gdaltest.download_file('http://www.openjpeg.org/samples/Bretagne1.j2k', 'Bretagne1.j2k'): - return 'skip' + pytest.skip() if not gdaltest.download_file('http://www.openjpeg.org/samples/Bretagne1.bmp', 'Bretagne1.bmp'): - return 'skip' + pytest.skip() # Checksum = 14443 on my PC tst = gdaltest.GDALTest('JPEG2000', 'tmp/cache/Bretagne1.j2k', 1, None, filename_absolute=1) - if tst.testOpen() != 'success': - return 'fail' + tst.testOpen() ds = gdal.Open('tmp/cache/Bretagne1.j2k') ds_ref = gdal.Open('tmp/cache/Bretagne1.bmp') @@ -413,24 +355,20 @@ def jpeg2000_online_3(): ds_ref = None # Difference between the image before and after compression - if maxdiff > 17: - gdaltest.post_reason('Image too different from reference') - return 'fail' - - return 'success' + assert maxdiff <= 17, 'Image too different from reference' ############################################################################### -def jpeg2000_online_4(): +def test_jpeg2000_online_4(): if gdaltest.jpeg2000_drv is None: - return 'skip' + pytest.skip() if not gdaltest.download_file('http://www.openjpeg.org/samples/Bretagne2.j2k', 'Bretagne2.j2k'): - return 'skip' + pytest.skip() if not gdaltest.download_file('http://www.openjpeg.org/samples/Bretagne2.bmp', 'Bretagne2.bmp'): - return 'skip' + pytest.skip() tst = gdaltest.GDALTest('JPEG2000', 'tmp/cache/Bretagne2.j2k', 1, None, filename_absolute=1) @@ -450,96 +388,56 @@ def jpeg2000_online_4(): ds_ref = None # Difference between the image before and after compression - if maxdiff > 17: - gdaltest.post_reason('Image too different from reference') - return 'fail' - - return 'success' + assert maxdiff <= 17, 'Image too different from reference' ############################################################################### # Try reading JPEG2000 with color table -def jpeg2000_online_5(): +def test_jpeg2000_online_5(): if gdaltest.jpeg2000_drv is None: - return 'skip' + pytest.skip() if not gdaltest.download_file('http://www.gwg.nga.mil/ntb/baseline/software/testfile/Jpeg2000/jp2_09/file9.jp2', 'file9.jp2'): - return 'skip' + pytest.skip() ds = gdal.Open('tmp/cache/file9.jp2') cs1 = ds.GetRasterBand(1).Checksum() cs2 = ds.GetRasterBand(2).Checksum() cs3 = ds.GetRasterBand(3).Checksum() - if cs1 != 48954 or cs2 != 4939 or cs3 != 17734: - print(cs1, cs2, cs3) - gdaltest.post_reason('Did not get expected checksums') - return 'fail' + assert cs1 == 48954 and cs2 == 4939 and cs3 == 17734, \ + 'Did not get expected checksums' ds = None - return 'success' - ############################################################################### # Try reading YCbCr JPEG2000 as RGB -def jpeg2000_online_6(): +def test_jpeg2000_online_6(): if gdaltest.jpeg2000_drv is None: - return 'skip' + pytest.skip() if not gdaltest.download_file('http://www.gwg.nga.mil/ntb/baseline/software/testfile/Jpeg2000/jp2_03/file3.jp2', 'file3.jp2'): - return 'skip' + pytest.skip() ds = gdal.Open('tmp/cache/file3.jp2') cs1 = ds.GetRasterBand(1).Checksum() cs2 = ds.GetRasterBand(2).Checksum() cs3 = ds.GetRasterBand(3).Checksum() - if cs1 != 25337 or cs2 != 28262 or cs3 != 59580: - print(cs1, cs2, cs3) - gdaltest.post_reason('Did not get expected checksums') - return 'fail' + assert cs1 == 25337 and cs2 == 28262 and cs3 == 59580, \ + 'Did not get expected checksums' ds = None - return 'success' - ############################################################################### -def jpeg2000_cleanup(): +def test_jpeg2000_cleanup(): gdaltest.reregister_all_jpeg2000_drivers() - return 'success' - - -gdaltest_list = [ - jpeg2000_1, - jpeg2000_2, - jpeg2000_3, - jpeg2000_4, - jpeg2000_5, - jpeg2000_6, - jpeg2000_7, - jpeg2000_8, - jpeg2000_9, - jpeg2000_10, - jpeg2000_11, - jpeg2000_online_1, - jpeg2000_online_2, - jpeg2000_online_3, - jpeg2000_online_4, - jpeg2000_online_5, - jpeg2000_online_6, - jpeg2000_cleanup] - -if __name__ == '__main__': - - gdaltest.setup_run('jpeg2000') - gdaltest.run_tests(gdaltest_list) - sys.exit(gdaltest.summarize()) diff --git a/autotest/gdrivers/jpeg_profile.py b/autotest/gdrivers/jpeg_profile.py index b7b715641bcf..ce6cc9fa0ccc 100755 --- a/autotest/gdrivers/jpeg_profile.py +++ b/autotest/gdrivers/jpeg_profile.py @@ -31,24 +31,17 @@ # http://sourceforge.net/projects/openicc/files/OpenICC-Profiles/ import os -import sys import base64 -sys.path.append('../pymod') -import gdaltest from osgeo import gdal - -############################################################################### -# When imported build a list of units based on the files available. - -gdaltest_list = [] +import pytest ############################################################################### # Test writing and reading of ICC profile in CreateCopy() -def jpeg_copy_icc(): +def test_jpeg_copy_icc(): f = open('data/sRGB.icc', 'rb') data = f.read() @@ -68,9 +61,7 @@ def jpeg_copy_icc(): ds = None ds2 = None - if md['SOURCE_ICC_PROFILE'] != icc: - gdaltest.post_reason('fail') - return 'fail' + assert md['SOURCE_ICC_PROFILE'] == icc # Check again with dataset from Open() ds2 = gdal.Open('tmp/icc_test.jpg') @@ -78,20 +69,16 @@ def jpeg_copy_icc(): ds = None ds2 = None - if md['SOURCE_ICC_PROFILE'] != icc: - gdaltest.post_reason('fail') - return 'fail' + assert md['SOURCE_ICC_PROFILE'] == icc driver_tiff.Delete('tmp/icc_test.tiff') driver.Delete('tmp/icc_test.jpg') - return 'success' - ############################################################################### # Test writing and reading of ICC profile in CreateCopy() options -def jpeg_copy_options_icc(): +def test_jpeg_copy_options_icc(): f = open('data/sRGB.icc', 'rb') data = f.read() @@ -111,9 +98,7 @@ def jpeg_copy_options_icc(): ds = None ds2 = None - if md['SOURCE_ICC_PROFILE'] != icc: - gdaltest.post_reason('fail') - return 'fail' + assert md['SOURCE_ICC_PROFILE'] == icc # Check again with dataset from Open() ds2 = gdal.Open('tmp/icc_test.jpg') @@ -121,20 +106,16 @@ def jpeg_copy_options_icc(): ds = None ds2 = None - if md['SOURCE_ICC_PROFILE'] != icc: - gdaltest.post_reason('fail') - return 'fail' + assert md['SOURCE_ICC_PROFILE'] == icc driver_tiff.Delete('tmp/icc_test.tiff') driver.Delete('tmp/icc_test.jpg') - return 'success' - ############################################################################### # Test writing and reading of 64K+ ICC profile in CreateCopy() -def jpeg_copy_icc_64K(): +def test_jpeg_copy_icc_64K(): # In JPEG, APP2 chunks can only be 64K, so they would be split up. # It will still work, but need to test that the segmented ICC profile @@ -161,69 +142,40 @@ def jpeg_copy_icc_64K(): comment = ds2.GetMetadataItem('COMMENT') ds2 = None - try: + with pytest.raises(OSError): os.stat('tmp/icc_test.jpg.aux.xml') - gdaltest.post_reason('fail') - return 'fail' - except OSError: - pass + - if comment != 'foo': - gdaltest.post_reason('fail') - return 'fail' + assert comment == 'foo' - if md['SOURCE_ICC_PROFILE'] != icc: - gdaltest.post_reason('fail') - return 'fail' + assert md['SOURCE_ICC_PROFILE'] == icc # Check again with dataset from Open() ds2 = gdal.Open('tmp/icc_test.jpg') md = ds2.GetMetadata("COLOR_PROFILE") ds2 = None - try: + with pytest.raises(OSError): os.stat('tmp/icc_test.jpg.aux.xml') - gdaltest.post_reason('fail') - return 'fail' - except OSError: - pass + - if md['SOURCE_ICC_PROFILE'] != icc: - gdaltest.post_reason('fail') - return 'fail' + assert md['SOURCE_ICC_PROFILE'] == icc # Check again with GetMetadataItem() ds2 = gdal.Open('tmp/icc_test.jpg') source_icc_profile = ds2.GetMetadataItem("SOURCE_ICC_PROFILE", "COLOR_PROFILE") ds2 = None - try: + with pytest.raises(OSError): os.stat('tmp/icc_test.jpg.aux.xml') - gdaltest.post_reason('fail') - return 'fail' - except OSError: - pass + - if source_icc_profile != icc: - gdaltest.post_reason('fail') - return 'fail' + assert source_icc_profile == icc driver_tiff.Delete('tmp/icc_test.tiff') driver.Delete('tmp/icc_test.jpg') - return 'success' - ############################################################################################### -gdaltest_list.append((jpeg_copy_icc)) -gdaltest_list.append((jpeg_copy_options_icc)) -gdaltest_list.append((jpeg_copy_icc_64K)) - -if __name__ == '__main__': - - gdaltest.setup_run('jpeg_profile') - - gdaltest.run_tests(gdaltest_list) - sys.exit(gdaltest.summarize()) diff --git a/autotest/gdrivers/jpegls.py b/autotest/gdrivers/jpegls.py index e518e928da24..39b83ba62f0a 100755 --- a/autotest/gdrivers/jpegls.py +++ b/autotest/gdrivers/jpegls.py @@ -28,20 +28,19 @@ # DEALINGS IN THE SOFTWARE. ############################################################################### -import sys from osgeo import gdal -sys.path.append('../pymod') import gdaltest +import pytest ############################################################################### -def jpegls_1(): +def test_jpegls_1(): if gdal.GetDriverByName('JPEGLS') is None: - return 'skip' + pytest.skip() tst = gdaltest.GDALTest('JPEGLS', 'byte.tif', 1, 4672) return tst.testCreateCopy(vsimem=1) @@ -49,24 +48,14 @@ def jpegls_1(): ############################################################################### -def jpegls_2(): +def test_jpegls_2(): if gdal.GetDriverByName('JPEGLS') is None: - return 'skip' + pytest.skip() tst = gdaltest.GDALTest('JPEGLS', 'int16.tif', 1, 4672) return tst.testCreateCopy(vsimem=1) -gdaltest_list = [ - jpegls_1, - jpegls_2] -if __name__ == '__main__': - - gdaltest.setup_run('JPEGLS') - - gdaltest.run_tests(gdaltest_list) - - sys.exit(gdaltest.summarize()) diff --git a/autotest/gdrivers/jpipkak.py b/autotest/gdrivers/jpipkak.py index c9c6a3d7cf53..14122dec2c2d 100755 --- a/autotest/gdrivers/jpipkak.py +++ b/autotest/gdrivers/jpipkak.py @@ -28,173 +28,127 @@ # DEALINGS IN THE SOFTWARE. ############################################################################### -import sys from osgeo import gdal -sys.path.append('../pymod') import gdaltest +import pytest ############################################################################### # Read test of simple byte reference data. -def jpipkak_1(): +def test_jpipkak_1(): - return 'skip' + pytest.skip() # pylint: disable=unreachable gdaltest.jpipkak_drv = gdal.GetDriverByName('JPIPKAK') if gdaltest.jpipkak_drv is None: - return 'skip' + pytest.skip() ds = gdal.Open('jpip://216.150.195.220/JP2Server/qb_boulder_msi_uint') - if ds is None: - gdaltest.post_reason('failed to open jpip stream.') - return 'fail' + assert ds is not None, 'failed to open jpip stream.' target = ds.GetRasterBand(3).GetOverview(3) stats = target.GetStatistics(0, 1) - if abs(stats[2] - 6791.121) > 1.0 or abs(stats[3] - 3046.536) > 1.0: - print(stats) - gdaltest.post_reason('did not get expected mean/stddev') - return 'fail' - - return 'success' + assert abs(stats[2] - 6791.121) <= 1.0 and abs(stats[3] - 3046.536) <= 1.0, \ + 'did not get expected mean/stddev' ############################################################################### # -def jpipkak_2(): +def test_jpipkak_2(): - return 'skip' + pytest.skip() # pylint: disable=unreachable if gdaltest.jpipkak_drv is None: - return 'skip' + pytest.skip() ds = gdal.Open('jpip://216.150.195.220/JP2Server/qb_boulder_pan_byte') - if ds is None: - gdaltest.post_reason('failed to open jpip stream.') - return 'fail' + assert ds is not None, 'failed to open jpip stream.' wkt = ds.GetProjectionRef() exp_wkt = 'PROJCS["WGS 84 / UTM zone 13N",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"]],PROJECTION["Transverse_Mercator"],PARAMETER["latitude_of_origin",0],PARAMETER["central_meridian",-105],PARAMETER["scale_factor",0.9996],PARAMETER["false_easting",500000],PARAMETER["false_northing",0],UNIT["metre",1,AUTHORITY["EPSG","9001"]],AUTHORITY["EPSG","32613"]]' - if not gdaltest.equal_srs_from_wkt(exp_wkt, wkt): - return 'fail' + assert gdaltest.equal_srs_from_wkt(exp_wkt, wkt) target = ds.GetRasterBand(1).GetOverview(3) stats = target.GetStatistics(0, 1) - if abs(stats[2] - 43.429) > 1.0 or abs(stats[3] - 18.526) > 1.0: - print(stats) - gdaltest.post_reason('did not get expected mean/stddev') - return 'fail' - - return 'success' + assert abs(stats[2] - 43.429) <= 1.0 and abs(stats[3] - 18.526) <= 1.0, \ + 'did not get expected mean/stddev' ############################################################################### # Test an 11bit image. -def jpipkak_3(): +def test_jpipkak_3(): - return 'skip' + pytest.skip() # pylint: disable=unreachable if gdaltest.jpipkak_drv is None: - return 'skip' + pytest.skip() ds = gdal.Open('jpip://216.150.195.220/JP2Server/qb_boulder_pan_11bit') - if ds is None: - gdaltest.post_reason('failed to open jpip stream.') - return 'fail' + assert ds is not None, 'failed to open jpip stream.' target = ds.GetRasterBand(1) stats = target.GetStatistics(0, 1) - if abs(stats[2] - 483.501) > 1.0 or abs(stats[3] - 117.972) > 1.0: - print(stats) - gdaltest.post_reason('did not get expected mean/stddev') - return 'fail' - - return 'success' + assert abs(stats[2] - 483.501) <= 1.0 and abs(stats[3] - 117.972) <= 1.0, \ + 'did not get expected mean/stddev' ############################################################################### # Test a 20bit image, reduced to 16bit during processing. -def jpipkak_4(): +def test_jpipkak_4(): - return 'skip' + pytest.skip() # pylint: disable=unreachable if gdaltest.jpipkak_drv is None: - return 'skip' + pytest.skip() ds = gdal.Open('jpip://216.150.195.220/JP2Server/qb_boulder_pan_20bit') - if ds is None: - gdaltest.post_reason('failed to open jpip stream.') - return 'fail' + assert ds is not None, 'failed to open jpip stream.' target = ds.GetRasterBand(1) stats = target.GetStatistics(0, 1) - if abs(stats[2] - 5333.148) > 1.0 or abs(stats[3] - 2522.023) > 1.0: - print(stats) - gdaltest.post_reason('did not get expected mean/stddev') - return 'fail' - - return 'success' + assert abs(stats[2] - 5333.148) <= 1.0 and abs(stats[3] - 2522.023) <= 1.0, \ + 'did not get expected mean/stddev' ############################################################################### # Test an overview level that will result in multiple fetches with subwindows. -def jpipkak_5(): +def test_jpipkak_5(): - return 'skip' + pytest.skip() # pylint: disable=unreachable if gdaltest.jpipkak_drv is None: - return 'skip' + pytest.skip() ds = gdal.Open('jpip://216.150.195.220/JP2Server/qb_boulder_pan_byte') - if ds is None: - gdaltest.post_reason('failed to open jpip stream.') - return 'fail' + assert ds is not None, 'failed to open jpip stream.' target = ds.GetRasterBand(1).GetOverview(1) stats = target.GetStatistics(0, 1) - if abs(stats[2] - 42.462) > 1.0 or abs(stats[3] - 20.611) > 1.0: - print(stats) - gdaltest.post_reason('did not get expected mean/stddev') - return 'fail' - - return 'success' - - -gdaltest_list = [ - jpipkak_1, - jpipkak_2, - jpipkak_3, - jpipkak_4, - jpipkak_5 -] - -if __name__ == '__main__': + assert abs(stats[2] - 42.462) <= 1.0 and abs(stats[3] - 20.611) <= 1.0, \ + 'did not get expected mean/stddev' - gdaltest.setup_run('jpipkak') - gdaltest.run_tests(gdaltest_list) - sys.exit(gdaltest.summarize()) diff --git a/autotest/gdrivers/kea.py b/autotest/gdrivers/kea.py index d0045a46c1f3..c0587d787168 100755 --- a/autotest/gdrivers/kea.py +++ b/autotest/gdrivers/kea.py @@ -29,28 +29,25 @@ # DEALINGS IN THE SOFTWARE. ############################################################################### -import sys from osgeo import gdal -sys.path.append('../pymod') import gdaltest +import pytest ############################################################################### -def kea_init(): +def test_kea_init(): gdaltest.kea_driver = gdal.GetDriverByName('KEA') - return 'success' - ############################################################################### # Test copying a reference sample with CreateCopy() -def kea_1(): +def test_kea_1(): if gdaltest.kea_driver is None: - return 'skip' + pytest.skip() tst = gdaltest.GDALTest('KEA', 'byte.tif', 1, 4672, options=['IMAGEBLOCKSIZE=15', 'THEMATIC=YES']) return tst.testCreateCopy(check_srs=True, check_gt=1) @@ -59,9 +56,9 @@ def kea_1(): # Test CreateCopy() for various data types -def kea_2(): +def test_kea_2(): if gdaltest.kea_driver is None: - return 'skip' + pytest.skip() src_files = ['byte.tif', 'int16.tif', @@ -73,19 +70,16 @@ def kea_2(): for src_file in src_files: tst = gdaltest.GDALTest('KEA', src_file, 1, 4672) - ret = tst.testCreateCopy(check_minmax=1) - if ret != 'success': - return ret - - return 'success' + tst.testCreateCopy(check_minmax=1) + ############################################################################### # Test Create() for various data types -def kea_3(): +def test_kea_3(): if gdaltest.kea_driver is None: - return 'skip' + pytest.skip() src_files = ['byte.tif', 'int16.tif', @@ -97,38 +91,27 @@ def kea_3(): for src_file in src_files: tst = gdaltest.GDALTest('KEA', src_file, 1, 4672) - ret = tst.testCreate(out_bands=1, check_minmax=1) - if ret != 'success': - return ret - - return 'success' + tst.testCreate(out_bands=1, check_minmax=1) + ############################################################################### # Test Create()/CreateCopy() error cases or limit cases -def kea_4(): +def test_kea_4(): if gdaltest.kea_driver is None: - return 'skip' + pytest.skip() gdal.PushErrorHandler('CPLQuietErrorHandler') ds = gdaltest.kea_driver.Create("/non_existing_path/non_existing_path", 1, 1) gdal.PopErrorHandler() - if ds is not None: - gdaltest.post_reason('fail') - return 'fail' + assert ds is None src_ds = gdaltest.kea_driver.Create('tmp/src.kea', 1, 1, 0) - if src_ds is None: - gdaltest.post_reason('fail') - return 'fail' + assert src_ds is not None ds = gdaltest.kea_driver.CreateCopy("tmp/out.kea", src_ds) - if ds is None: - gdaltest.post_reason('fail') - return 'fail' - if ds.RasterCount != 0: - gdaltest.post_reason('fail') - return 'fail' + assert ds is not None + assert ds.RasterCount == 0 src_ds = None ds = None @@ -141,16 +124,12 @@ def kea_4(): gdal.PushErrorHandler('CPLQuietErrorHandler') ret = ds.SetProjection('a') gdal.PopErrorHandler() - if ret == 0: - gdaltest.post_reason('fail') - return 'fail' + assert ret != 0 gdal.PushErrorHandler('CPLQuietErrorHandler') ret = ds.SetGeoTransform([1, 2, 3, 4, 5, 6]) gdal.PopErrorHandler() - if ret == 0: - gdaltest.post_reason('fail') - return 'fail' + assert ret != 0 # Disabled for now since some of them cause memory leaks or # crash in the HDF5 library finalizer @@ -158,68 +137,52 @@ def kea_4(): gdal.PushErrorHandler('CPLQuietErrorHandler') ret = ds.SetMetadataItem('foo', 'bar') gdal.PopErrorHandler() - if ret == 0: - gdaltest.post_reason('fail') - return 'fail' + assert ret != 0 gdal.PushErrorHandler('CPLQuietErrorHandler') ret = ds.SetMetadata({'foo': 'bar'}) gdal.PopErrorHandler() - if ret == 0: - gdaltest.post_reason('fail') - return 'fail' + assert ret != 0 gdal.PushErrorHandler('CPLQuietErrorHandler') ret = ds.GetRasterBand(1).SetMetadataItem('foo', 'bar') gdal.PopErrorHandler() - if ret == 0: - gdaltest.post_reason('fail') - return 'fail' + assert ret != 0 gdal.PushErrorHandler('CPLQuietErrorHandler') ret = ds.GetRasterBand(1).SetMetadata({'foo': 'bar'}) gdal.PopErrorHandler() - if ret == 0: - gdaltest.post_reason('fail') - return 'fail' + assert ret != 0 gdal.PushErrorHandler('CPLQuietErrorHandler') ret = ds.SetGCPs([], "") gdal.PopErrorHandler() - if ret == 0: - gdaltest.post_reason('fail') - return 'fail' + assert ret != 0 gdal.PushErrorHandler('CPLQuietErrorHandler') ret = ds.AddBand(gdal.GDT_Byte) gdal.PopErrorHandler() - if ret == 0: - gdaltest.post_reason('fail') - return 'fail' + assert ret != 0 ds.GetRasterBand(1).WriteRaster(0, 0, 1, 1, '\0') gdal.ErrorReset() gdal.PushErrorHandler('CPLQuietErrorHandler') ds.FlushCache() gdal.PopErrorHandler() - if ds.GetRasterBand(1).Checksum() != 3: - gdaltest.post_reason('fail') - return 'fail' + assert ds.GetRasterBand(1).Checksum() == 3 ds = None gdaltest.kea_driver.Delete('tmp/src.kea') gdaltest.kea_driver.Delete('tmp/out.kea') - return 'success' - ############################################################################### # Test Create() creation options -def kea_5(): +def test_kea_5(): if gdaltest.kea_driver is None: - return 'skip' + pytest.skip() options = ['IMAGEBLOCKSIZE=15', 'ATTBLOCKSIZE=100', 'MDC_NELMTS=10', 'RDCC_NELMTS=256', 'RDCC_NBYTES=500000', 'RDCC_W0=0.5', @@ -227,38 +190,22 @@ def kea_5(): ds = gdaltest.kea_driver.Create("tmp/out.kea", 100, 100, 3, options=options) ds = None ds = gdal.Open('tmp/out.kea') - if ds.GetRasterBand(1).GetBlockSize() != [15, 15]: - gdaltest.post_reason('fail') - print(ds.GetRasterBand(1).GetBlockSize()) - return 'fail' - if ds.GetRasterBand(1).GetMetadataItem('LAYER_TYPE') != 'thematic': - gdaltest.post_reason('fail') - print(ds.GetRasterBand(1).GetMetadata()) - return 'fail' - if ds.GetRasterBand(1).Checksum() != 0: - gdaltest.post_reason('fail') - print(ds.GetRasterBand(1).Checksum()) - return 'fail' - if ds.GetGeoTransform() != (0, 1, 0, 0, 0, -1): - gdaltest.post_reason('fail') - print(ds.GetGeoTransform()) - return 'fail' - if ds.GetProjectionRef() != '': - gdaltest.post_reason('fail') - print(ds.GetProjectionRef()) - return 'fail' + assert ds.GetRasterBand(1).GetBlockSize() == [15, 15] + assert ds.GetRasterBand(1).GetMetadataItem('LAYER_TYPE') == 'thematic', \ + ds.GetRasterBand(1).GetMetadata() + assert ds.GetRasterBand(1).Checksum() == 0 + assert ds.GetGeoTransform() == (0, 1, 0, 0, 0, -1) + assert ds.GetProjectionRef() == '' ds = None gdaltest.kea_driver.Delete('tmp/out.kea') - return 'success' - ############################################################################### # Test metadata -def kea_6(): +def test_kea_6(): if gdaltest.kea_driver is None: - return 'skip' + pytest.skip() ds = gdaltest.kea_driver.Create("tmp/out.kea", 1, 1, 5) ds.SetMetadata({'foo': 'bar'}) @@ -269,129 +216,61 @@ def kea_6(): ds.GetRasterBand(3).SetMetadata({'LAYER_TYPE': 'athematic'}) ds.GetRasterBand(4).SetMetadataItem('LAYER_TYPE', 'thematic') ds.GetRasterBand(5).SetMetadataItem('LAYER_TYPE', 'athematic') - if ds.SetMetadata({'foo': 'bar'}, 'other_domain') == 0: - gdaltest.post_reason('fail') - return 'fail' - if ds.SetMetadataItem('foo', 'bar', 'other_domain') == 0: - gdaltest.post_reason('fail') - return 'fail' - if ds.GetRasterBand(1).SetMetadata({'foo': 'bar'}, 'other_domain') == 0: - gdaltest.post_reason('fail') - return 'fail' - if ds.GetRasterBand(1).SetMetadataItem('foo', 'bar', 'other_domain') == 0: - gdaltest.post_reason('fail') - return 'fail' + assert ds.SetMetadata({'foo': 'bar'}, 'other_domain') != 0 + assert ds.SetMetadataItem('foo', 'bar', 'other_domain') != 0 + assert ds.GetRasterBand(1).SetMetadata({'foo': 'bar'}, 'other_domain') != 0 + assert ds.GetRasterBand(1).SetMetadataItem('foo', 'bar', 'other_domain') != 0 ds = None ds = gdal.Open('tmp/out.kea') - if ds.GetMetadata('other_domain') != {}: - gdaltest.post_reason('fail') - print(ds.GetMetadata('other_domain')) - return 'fail' - if ds.GetMetadataItem('item', 'other_domain') is not None: - gdaltest.post_reason('fail') - return 'fail' - if ds.GetRasterBand(1).GetMetadata('other_domain') != {}: - gdaltest.post_reason('fail') - return 'fail' - if ds.GetRasterBand(1).GetMetadataItem('item', 'other_domain') is not None: - gdaltest.post_reason('fail') - return 'fail' + assert ds.GetMetadata('other_domain') == {} + assert ds.GetMetadataItem('item', 'other_domain') is None + assert ds.GetRasterBand(1).GetMetadata('other_domain') == {} + assert ds.GetRasterBand(1).GetMetadataItem('item', 'other_domain') is None md = ds.GetMetadata() - if md['foo'] != 'bar': - gdaltest.post_reason('fail') - print(md) - return 'fail' - if ds.GetMetadataItem('foo') != 'bar': - gdaltest.post_reason('fail') - print(ds.GetMetadataItem('foo')) - return 'fail' - if ds.GetMetadataItem('bar') != 'baw': - gdaltest.post_reason('fail') - print(ds.GetMetadataItem('bar')) - return 'fail' - if ds.GetRasterBand(1).GetDescription() != 'desc': - gdaltest.post_reason('fail') - return 'fail' + assert md['foo'] == 'bar' + assert ds.GetMetadataItem('foo') == 'bar' + assert ds.GetMetadataItem('bar') == 'baw' + assert ds.GetRasterBand(1).GetDescription() == 'desc' md = ds.GetRasterBand(1).GetMetadata() - if md['bar'] != 'baz': - gdaltest.post_reason('fail') - print(md) - return 'fail' - if ds.GetRasterBand(1).GetMetadataItem('bar') != 'baz': - gdaltest.post_reason('fail') - print(ds.GetRasterBand(1).GetMetadataItem('bar')) - return 'fail' - if ds.GetRasterBand(2).GetMetadataItem('LAYER_TYPE') != 'thematic': - gdaltest.post_reason('fail') - print(ds.GetRasterBand(2).GetMetadataItem('LAYER_TYPE')) - return 'fail' - if ds.GetRasterBand(3).GetMetadataItem('LAYER_TYPE') != 'athematic': - gdaltest.post_reason('fail') - print(ds.GetRasterBand(3).GetMetadataItem('LAYER_TYPE')) - return 'fail' - if ds.GetRasterBand(4).GetMetadataItem('LAYER_TYPE') != 'thematic': - gdaltest.post_reason('fail') - print(ds.GetRasterBand(4).GetMetadataItem('LAYER_TYPE')) - return 'fail' - if ds.GetRasterBand(5).GetMetadataItem('LAYER_TYPE') != 'athematic': - gdaltest.post_reason('fail') - print(ds.GetRasterBand(5).GetMetadataItem('LAYER_TYPE')) - return 'fail' + assert md['bar'] == 'baz' + assert ds.GetRasterBand(1).GetMetadataItem('bar') == 'baz' + assert ds.GetRasterBand(2).GetMetadataItem('LAYER_TYPE') == 'thematic' + assert ds.GetRasterBand(3).GetMetadataItem('LAYER_TYPE') == 'athematic' + assert ds.GetRasterBand(4).GetMetadataItem('LAYER_TYPE') == 'thematic' + assert ds.GetRasterBand(5).GetMetadataItem('LAYER_TYPE') == 'athematic' out2_ds = gdaltest.kea_driver.CreateCopy('tmp/out2.kea', ds) ds = None - if out2_ds.GetMetadataItem('foo') != 'bar': - gdaltest.post_reason('fail') - print(out2_ds.GetMetadataItem('foo')) - return 'fail' - if out2_ds.GetRasterBand(1).GetMetadataItem('bar') != 'baz': - gdaltest.post_reason('fail') - print(out2_ds.GetRasterBand(1).GetMetadataItem('bar')) - return 'fail' + assert out2_ds.GetMetadataItem('foo') == 'bar' + assert out2_ds.GetRasterBand(1).GetMetadataItem('bar') == 'baz' out2_ds = None gdaltest.kea_driver.Delete('tmp/out.kea') gdaltest.kea_driver.Delete('tmp/out2.kea') - return 'success' - ############################################################################### # Test georef -def kea_7(): +def test_kea_7(): if gdaltest.kea_driver is None: - return 'skip' + pytest.skip() # Geotransform ds = gdaltest.kea_driver.Create("tmp/out.kea", 1, 1) - if ds.GetGCPCount() != 0: - gdaltest.post_reason('fail') - return 'fail' - if ds.SetGeoTransform([1, 2, 3, 4, 5, 6]) != 0: - gdaltest.post_reason('fail') - return 'fail' - if ds.SetProjection('foo') != 0: - gdaltest.post_reason('fail') - return 'fail' + assert ds.GetGCPCount() == 0 + assert ds.SetGeoTransform([1, 2, 3, 4, 5, 6]) == 0 + assert ds.SetProjection('foo') == 0 ds = None ds = gdal.Open('tmp/out.kea') out2_ds = gdaltest.kea_driver.CreateCopy('tmp/out2.kea', ds) ds = None - if out2_ds.GetGCPCount() != 0: - gdaltest.post_reason('fail') - return 'fail' - if out2_ds.GetGeoTransform() != (1, 2, 3, 4, 5, 6): - gdaltest.post_reason('fail') - print(out2_ds.GetGeoTransform()) - return 'fail' - if out2_ds.GetProjectionRef() != 'foo': - gdaltest.post_reason('fail') - print(out2_ds.GetProjectionRef()) - return 'fail' + assert out2_ds.GetGCPCount() == 0 + assert out2_ds.GetGeoTransform() == (1, 2, 3, 4, 5, 6) + assert out2_ds.GetProjectionRef() == 'foo' out2_ds = None gdaltest.kea_driver.Delete('tmp/out.kea') @@ -411,89 +290,65 @@ def kea_7(): out2_ds = gdaltest.kea_driver.CreateCopy('tmp/out2.kea', ds) ds = None - if out2_ds.GetGCPCount() != 2: - gdaltest.post_reason('fail') - return 'fail' - if out2_ds.GetGCPProjection() != 'foo': - gdaltest.post_reason('fail') - return 'fail' + assert out2_ds.GetGCPCount() == 2 + assert out2_ds.GetGCPProjection() == 'foo' got_gcps = out2_ds.GetGCPs() for i in range(2): - if got_gcps[i].GCPX != gcps[i].GCPX or got_gcps[i].GCPY != gcps[i].GCPY or \ - got_gcps[i].GCPZ != gcps[i].GCPZ or got_gcps[i].GCPPixel != gcps[i].GCPPixel or \ - got_gcps[i].GCPLine != gcps[i].GCPLine or got_gcps[i].Id != gcps[i].Id or \ - got_gcps[i].Info != gcps[i].Info: - print(i) - print(got_gcps[i]) - gdaltest.post_reason('fail') - return 'fail' + assert (got_gcps[i].GCPX == gcps[i].GCPX and got_gcps[i].GCPY == gcps[i].GCPY and \ + got_gcps[i].GCPZ == gcps[i].GCPZ and got_gcps[i].GCPPixel == gcps[i].GCPPixel and \ + got_gcps[i].GCPLine == gcps[i].GCPLine and got_gcps[i].Id == gcps[i].Id and \ + got_gcps[i].Info == gcps[i].Info) out2_ds = None gdaltest.kea_driver.Delete('tmp/out.kea') gdaltest.kea_driver.Delete('tmp/out2.kea') - return 'success' - ############################################################################### # Test colortable -def kea_8(): +def test_kea_8(): if gdaltest.kea_driver is None: - return 'skip' + pytest.skip() for i in range(2): ds = gdaltest.kea_driver.Create("tmp/out.kea", 1, 1) - if ds.GetRasterBand(1).GetColorTable() is not None: - gdaltest.post_reason('fail') - return 'fail' - if ds.GetRasterBand(1).SetColorTable(None) == 0: # not allowed by the driver - gdaltest.post_reason('fail') - return 'fail' + assert ds.GetRasterBand(1).GetColorTable() is None + assert ds.GetRasterBand(1).SetColorTable(None) != 0 ct = gdal.ColorTable() ct.SetColorEntry(0, (0, 255, 0, 255)) ct.SetColorEntry(1, (255, 0, 255, 255)) ct.SetColorEntry(2, (0, 0, 255, 255)) - if ds.GetRasterBand(1).SetColorTable(ct) != 0: - gdaltest.post_reason('fail') - return 'fail' + assert ds.GetRasterBand(1).SetColorTable(ct) == 0 if i == 1: # And again - if ds.GetRasterBand(1).SetColorTable(ct) != 0: - gdaltest.post_reason('fail') - return 'fail' + assert ds.GetRasterBand(1).SetColorTable(ct) == 0 ds = None ds = gdal.Open('tmp/out.kea') out2_ds = gdaltest.kea_driver.CreateCopy('tmp/out2.kea', ds) ds = None got_ct = out2_ds.GetRasterBand(1).GetColorTable() - if got_ct.GetCount() != 3: - gdaltest.post_reason('Got wrong color table entry count.') - return 'fail' - if got_ct.GetColorEntry(1) != (255, 0, 255, 255): - gdaltest.post_reason('Got wrong color table entry.') - return 'fail' + assert got_ct.GetCount() == 3, 'Got wrong color table entry count.' + assert got_ct.GetColorEntry(1) == (255, 0, 255, 255), \ + 'Got wrong color table entry.' out2_ds = None gdaltest.kea_driver.Delete('tmp/out.kea') gdaltest.kea_driver.Delete('tmp/out2.kea') - return 'success' - + ############################################################################### # Test color interpretation -def kea_9(): +def test_kea_9(): if gdaltest.kea_driver is None: - return 'skip' + pytest.skip() ds = gdaltest.kea_driver.Create("tmp/out.kea", 1, 1, gdal.GCI_YCbCr_CrBand - gdal.GCI_GrayIndex + 1) - if ds.GetRasterBand(1).GetColorInterpretation() != gdal.GCI_GrayIndex: - gdaltest.post_reason('fail') - return 'fail' + assert ds.GetRasterBand(1).GetColorInterpretation() == gdal.GCI_GrayIndex for i in range(gdal.GCI_GrayIndex, gdal.GCI_YCbCr_CrBand + 1): ds.GetRasterBand(i).SetColorInterpretation(i) ds = None @@ -502,26 +357,21 @@ def kea_9(): out2_ds = gdaltest.kea_driver.CreateCopy('tmp/out2.kea', ds) ds = None for i in range(gdal.GCI_GrayIndex, gdal.GCI_YCbCr_CrBand + 1): - if out2_ds.GetRasterBand(i).GetColorInterpretation() != i: - gdaltest.post_reason('Got wrong color interpretation.') - print(i) - print(out2_ds.GetRasterBand(i).GetColorInterpretation()) - return 'fail' + assert out2_ds.GetRasterBand(i).GetColorInterpretation() == i, \ + 'Got wrong color interpretation.' out2_ds = None gdaltest.kea_driver.Delete('tmp/out.kea') gdaltest.kea_driver.Delete('tmp/out2.kea') - return 'success' - ############################################################################### # Test nodata -def kea_10(): +def test_kea_10(): if gdaltest.kea_driver is None: - return 'skip' + pytest.skip() for (dt, nd, expected_nd) in [(gdal.GDT_Byte, 0, 0), (gdal.GDT_Byte, 1.1, 1.0), @@ -547,95 +397,68 @@ def kea_10(): (gdal.GDT_Float32, 0.5, 0.5), ]: ds = gdaltest.kea_driver.Create("tmp/out.kea", 1, 1, 1, dt) - if ds.GetRasterBand(1).GetNoDataValue() is not None: - gdaltest.post_reason('fail') - return 'fail' + assert ds.GetRasterBand(1).GetNoDataValue() is None ds.GetRasterBand(1).SetNoDataValue(nd) if ds.GetRasterBand(1).GetNoDataValue() != expected_nd: - gdaltest.post_reason('Got wrong nodata.') print(dt) - print(ds.GetRasterBand(1).GetNoDataValue()) - return 'fail' + pytest.fail('Got wrong nodata.') ds = None ds = gdal.Open('tmp/out.kea') out2_ds = gdaltest.kea_driver.CreateCopy('tmp/out2.kea', ds) ds = None if out2_ds.GetRasterBand(1).GetNoDataValue() != expected_nd: - gdaltest.post_reason('Got wrong nodata.') print(dt) - print(out2_ds.GetRasterBand(1).GetNoDataValue()) - return 'fail' + pytest.fail('Got wrong nodata.') out2_ds.GetRasterBand(1).DeleteNoDataValue() out2_ds = None ds = gdal.Open('tmp/out2.kea') - if ds.GetRasterBand(1).GetNoDataValue() is not None: - gdaltest.post_reason('fail') - return 'fail' + assert ds.GetRasterBand(1).GetNoDataValue() is None ds = None gdaltest.kea_driver.Delete('tmp/out.kea') gdaltest.kea_driver.Delete('tmp/out2.kea') - return 'success' - + ############################################################################### # Test AddBand -def kea_11(): +def test_kea_11(): if gdaltest.kea_driver is None: - return 'skip' + pytest.skip() ds = gdaltest.kea_driver.Create("tmp/out.kea", 1, 1, 1, gdal.GDT_Byte) ds = None ds = gdal.Open('tmp/out.kea', gdal.GA_Update) - if ds.AddBand(gdal.GDT_Byte) != 0: - gdaltest.post_reason('fail') - return 'fail' - if ds.AddBand(gdal.GDT_Int16, options=['DEFLATE=9']) != 0: - gdaltest.post_reason('fail') - return 'fail' + assert ds.AddBand(gdal.GDT_Byte) == 0 + assert ds.AddBand(gdal.GDT_Int16, options=['DEFLATE=9']) == 0 ds = None ds = gdal.Open('tmp/out.kea') - if ds.RasterCount != 3: - gdaltest.post_reason('fail') - return 'fail' - if ds.GetRasterBand(2).DataType != gdal.GDT_Byte: - gdaltest.post_reason('fail') - return 'fail' - if ds.GetRasterBand(3).DataType != gdal.GDT_Int16: - gdaltest.post_reason('fail') - return 'fail' + assert ds.RasterCount == 3 + assert ds.GetRasterBand(2).DataType == gdal.GDT_Byte + assert ds.GetRasterBand(3).DataType == gdal.GDT_Int16 ds = None gdaltest.kea_driver.Delete('tmp/out.kea') - return 'success' - ############################################################################### # Test RAT -def kea_12(): +def test_kea_12(): if gdaltest.kea_driver is None: - return 'skip' + pytest.skip() ds = gdaltest.kea_driver.Create("tmp/out.kea", 1, 1, 1, gdal.GDT_Byte) - if ds.GetRasterBand(1).GetDefaultRAT().GetColumnCount() != 0: - gdaltest.post_reason('fail') - return 'fail' - if ds.GetRasterBand(1).SetDefaultRAT(None) == 0: # not allowed by the driver - gdaltest.post_reason('fail') - return 'fail' + assert ds.GetRasterBand(1).GetDefaultRAT().GetColumnCount() == 0 + assert ds.GetRasterBand(1).SetDefaultRAT(None) != 0 rat = ds.GetRasterBand(1).GetDefaultRAT() rat.CreateColumn('col_real_generic', gdal.GFT_Real, gdal.GFU_Generic) - if ds.GetRasterBand(1).SetDefaultRAT(rat) != 0: - gdaltest.post_reason('fail') - return 'fail' + assert ds.GetRasterBand(1).SetDefaultRAT(rat) == 0 rat = ds.GetRasterBand(1).GetDefaultRAT() rat.CreateColumn('col_integer_pixelcount', gdal.GFT_Real, gdal.GFU_PixelCount) rat.CreateColumn('col_string_name', gdal.GFT_String, gdal.GFU_Name) @@ -658,9 +481,7 @@ def kea_12(): rat.SetValueAsInt(0, 3, 123) cloned_rat = rat.Clone() - if ds.GetRasterBand(1).SetDefaultRAT(rat) != 0: - gdaltest.post_reason('fail') - return 'fail' + assert ds.GetRasterBand(1).SetDefaultRAT(rat) == 0 ds = None ds = gdal.Open('tmp/out.kea') @@ -668,50 +489,21 @@ def kea_12(): rat = out2_ds.GetRasterBand(1).GetDefaultRAT() for i in range(7): - if rat.GetColOfUsage(rat.GetUsageOfCol(i)) != i: - gdaltest.post_reason('fail') - print(i) - print(rat.GetColOfUsage(rat.GetUsageOfCol(i))) - return 'fail' - - if cloned_rat.GetNameOfCol(0) != 'col_real_generic': - gdaltest.post_reason('fail') - return 'fail' - if cloned_rat.GetTypeOfCol(0) != gdal.GFT_Real: - gdaltest.post_reason('fail') - return 'fail' - if cloned_rat.GetUsageOfCol(0) != gdal.GFU_Generic: - gdaltest.post_reason('fail') - return 'fail' - if cloned_rat.GetUsageOfCol(1) != gdal.GFU_PixelCount: - gdaltest.post_reason('fail') - return 'fail' - if cloned_rat.GetTypeOfCol(2) != gdal.GFT_String: - gdaltest.post_reason('fail') - return 'fail' - if cloned_rat.GetTypeOfCol(3) != gdal.GFT_Integer: - gdaltest.post_reason('fail') - return 'fail' - - if rat.GetColumnCount() != cloned_rat.GetColumnCount(): - gdaltest.post_reason('fail') - return 'fail' - if rat.GetRowCount() != cloned_rat.GetRowCount(): - gdaltest.post_reason('fail') - return 'fail' + assert rat.GetColOfUsage(rat.GetUsageOfCol(i)) == i + + assert cloned_rat.GetNameOfCol(0) == 'col_real_generic' + assert cloned_rat.GetTypeOfCol(0) == gdal.GFT_Real + assert cloned_rat.GetUsageOfCol(0) == gdal.GFU_Generic + assert cloned_rat.GetUsageOfCol(1) == gdal.GFU_PixelCount + assert cloned_rat.GetTypeOfCol(2) == gdal.GFT_String + assert cloned_rat.GetTypeOfCol(3) == gdal.GFT_Integer + + assert rat.GetColumnCount() == cloned_rat.GetColumnCount() + assert rat.GetRowCount() == cloned_rat.GetRowCount() for i in range(rat.GetColumnCount()): - if rat.GetNameOfCol(i) != cloned_rat.GetNameOfCol(i): - gdaltest.post_reason('fail') - return 'fail' - if rat.GetTypeOfCol(i) != cloned_rat.GetTypeOfCol(i): - gdaltest.post_reason('fail') - return 'fail' - if rat.GetUsageOfCol(i) != cloned_rat.GetUsageOfCol(i): - gdaltest.post_reason('fail') - print(i) - print(rat.GetUsageOfCol(i)) - print(cloned_rat.GetUsageOfCol(i)) - return 'fail' + assert rat.GetNameOfCol(i) == cloned_rat.GetNameOfCol(i) + assert rat.GetTypeOfCol(i) == cloned_rat.GetTypeOfCol(i) + assert rat.GetUsageOfCol(i) == cloned_rat.GetUsageOfCol(i) gdal.PushErrorHandler('CPLQuietErrorHandler') @@ -741,36 +533,17 @@ def kea_12(): gdal.PopErrorHandler() - if rat.GetValueAsDouble(0, 0) != 1.23: - gdaltest.post_reason('fail') - return 'fail' - if rat.GetValueAsInt(0, 0) != 1: - gdaltest.post_reason('fail') - return 'fail' - if rat.GetValueAsString(0, 0) != '1.23': - gdaltest.post_reason('fail') - print(rat.GetValueAsString(0, 0)) - return 'fail' - - if rat.GetValueAsInt(0, 3) != 123: - gdaltest.post_reason('fail') - return 'fail' - if rat.GetValueAsDouble(0, 3) != 123: - gdaltest.post_reason('fail') - return 'fail' - if rat.GetValueAsString(0, 3) != '123': - gdaltest.post_reason('fail') - return 'fail' - - if rat.GetValueAsString(0, 2) != 'foo': - gdaltest.post_reason('fail') - return 'fail' - if rat.GetValueAsInt(0, 2) != 0: - gdaltest.post_reason('fail') - return 'fail' - if rat.GetValueAsDouble(0, 2) != 0: - gdaltest.post_reason('fail') - return 'fail' + assert rat.GetValueAsDouble(0, 0) == 1.23 + assert rat.GetValueAsInt(0, 0) == 1 + assert rat.GetValueAsString(0, 0) == '1.23' + + assert rat.GetValueAsInt(0, 3) == 123 + assert rat.GetValueAsDouble(0, 3) == 123 + assert rat.GetValueAsString(0, 3) == '123' + + assert rat.GetValueAsString(0, 2) == 'foo' + assert rat.GetValueAsInt(0, 2) == 0 + assert rat.GetValueAsDouble(0, 2) == 0 ds = None out2_ds = None @@ -778,15 +551,13 @@ def kea_12(): gdaltest.kea_driver.Delete('tmp/out.kea') gdaltest.kea_driver.Delete('tmp/out2.kea') - return 'success' - ############################################################################### # Test overviews -def kea_13(): +def test_kea_13(): if gdaltest.kea_driver is None: - return 'skip' + pytest.skip() src_ds = gdal.Open('data/byte.tif') ds = gdaltest.kea_driver.CreateCopy("tmp/out.kea", src_ds) @@ -795,103 +566,45 @@ def kea_13(): ds = None ds = gdal.Open('tmp/out.kea') out2_ds = gdaltest.kea_driver.CreateCopy('tmp/out2.kea', ds) # yes CreateCopy() of KEA copies overviews - if out2_ds.GetRasterBand(1).GetOverviewCount() != 1: - gdaltest.post_reason('fail') - return 'fail' - if out2_ds.GetRasterBand(1).GetOverview(0).Checksum() != 1087: - gdaltest.post_reason('fail') - return 'fail' - if out2_ds.GetRasterBand(1).GetOverview(0).GetDefaultRAT() is not None: - gdaltest.post_reason('fail') - return 'fail' - if out2_ds.GetRasterBand(1).GetOverview(0).SetDefaultRAT(None) == 0: - gdaltest.post_reason('fail') - return 'fail' - if out2_ds.GetRasterBand(1).GetOverview(-1) is not None: - gdaltest.post_reason('fail') - return 'fail' - if out2_ds.GetRasterBand(1).GetOverview(1) is not None: - gdaltest.post_reason('fail') - return 'fail' + assert out2_ds.GetRasterBand(1).GetOverviewCount() == 1 + assert out2_ds.GetRasterBand(1).GetOverview(0).Checksum() == 1087 + assert out2_ds.GetRasterBand(1).GetOverview(0).GetDefaultRAT() is None + assert out2_ds.GetRasterBand(1).GetOverview(0).SetDefaultRAT(None) != 0 + assert out2_ds.GetRasterBand(1).GetOverview(-1) is None + assert out2_ds.GetRasterBand(1).GetOverview(1) is None out2_ds = None ds = None gdaltest.kea_driver.Delete('tmp/out.kea') gdaltest.kea_driver.Delete('tmp/out2.kea') - return 'success' - ############################################################################### # Test mask bands -def kea_14(): +def test_kea_14(): if gdaltest.kea_driver is None: - return 'skip' + pytest.skip() ds = gdaltest.kea_driver.Create("tmp/out.kea", 1, 1, 1, gdal.GDT_Byte) - if ds.GetRasterBand(1).GetMaskFlags() != gdal.GMF_ALL_VALID: - gdaltest.post_reason('fail') - return 'fail' - if ds.GetRasterBand(1).GetMaskBand().Checksum() != 3: - print(ds.GetRasterBand(1).GetMaskBand().Checksum()) - gdaltest.post_reason('fail') - return 'fail' + assert ds.GetRasterBand(1).GetMaskFlags() == gdal.GMF_ALL_VALID + assert ds.GetRasterBand(1).GetMaskBand().Checksum() == 3 ds.GetRasterBand(1).CreateMaskBand(0) - if ds.GetRasterBand(1).GetMaskFlags() != 0: - gdaltest.post_reason('fail') - return 'fail' - if ds.GetRasterBand(1).GetMaskBand().Checksum() != 3: - print(ds.GetRasterBand(1).GetMaskBand().Checksum()) - gdaltest.post_reason('fail') - return 'fail' + assert ds.GetRasterBand(1).GetMaskFlags() == 0 + assert ds.GetRasterBand(1).GetMaskBand().Checksum() == 3 ds.GetRasterBand(1).GetMaskBand().Fill(0) - if ds.GetRasterBand(1).GetMaskBand().Checksum() != 0: - print(ds.GetRasterBand(1).GetMaskBand().Checksum()) - gdaltest.post_reason('fail') - return 'fail' + assert ds.GetRasterBand(1).GetMaskBand().Checksum() == 0 ds = None ds = gdal.Open('tmp/out.kea') out2_ds = gdaltest.kea_driver.CreateCopy('tmp/out2.kea', ds) # yes CreateCopy() of KEA copies overviews - if out2_ds.GetRasterBand(1).GetMaskFlags() != 0: - gdaltest.post_reason('fail') - return 'fail' - if out2_ds.GetRasterBand(1).GetMaskBand().Checksum() != 0: - print(out2_ds.GetRasterBand(1).GetMaskBand().Checksum()) - gdaltest.post_reason('fail') - return 'fail' + assert out2_ds.GetRasterBand(1).GetMaskFlags() == 0 + assert out2_ds.GetRasterBand(1).GetMaskBand().Checksum() == 0 out2_ds = None ds = None gdaltest.kea_driver.Delete('tmp/out.kea') gdaltest.kea_driver.Delete('tmp/out2.kea') - return 'success' - - -gdaltest_list = [ - kea_init, - kea_1, - kea_2, - kea_3, - kea_4, - kea_5, - kea_6, - kea_7, - kea_8, - kea_9, - kea_10, - kea_11, - kea_12, - kea_13, - kea_14 -] - -if __name__ == '__main__': - - gdaltest.setup_run('kea') - gdaltest.run_tests(gdaltest_list) - sys.exit(gdaltest.summarize()) diff --git a/autotest/gdrivers/kmlsuperoverlay.py b/autotest/gdrivers/kmlsuperoverlay.py index df16a2f062f4..252c46097674 100755 --- a/autotest/gdrivers/kmlsuperoverlay.py +++ b/autotest/gdrivers/kmlsuperoverlay.py @@ -30,19 +30,18 @@ ############################################################################### import os -import sys import shutil from osgeo import gdal -sys.path.append('../pymod') import gdaltest +import pytest ############################################################################### # Test CreateCopy() to a KMZ file -def kmlsuperoverlay_1(): +def test_kmlsuperoverlay_1(): tst = gdaltest.GDALTest('KMLSUPEROVERLAY', 'small_world.tif', 1, 30111, options=['FORMAT=PNG']) @@ -52,7 +51,7 @@ def kmlsuperoverlay_1(): # Test CreateCopy() to a KML file -def kmlsuperoverlay_2(): +def test_kmlsuperoverlay_2(): tst = gdaltest.GDALTest('KMLSUPEROVERLAY', 'small_world.tif', 1, 30111, options=['FORMAT=PNG']) @@ -62,7 +61,7 @@ def kmlsuperoverlay_2(): # Test CreateCopy() to a KML file -def kmlsuperoverlay_3(): +def test_kmlsuperoverlay_3(): src_ds = gdal.Open('data/utm.tif') ds = gdal.GetDriverByName('KMLSUPEROVERLAY').CreateCopy('tmp/tmp.kml', src_ds) @@ -84,19 +83,16 @@ def kmlsuperoverlay_3(): try: os.remove(filename) except OSError: - gdaltest.post_reason("Missing file: %s" % filename) - return 'fail' + pytest.fail("Missing file: %s" % filename) shutil.rmtree('tmp/0') shutil.rmtree('tmp/1') - return 'success' - ############################################################################### # Test overviews -def kmlsuperoverlay_4(): +def test_kmlsuperoverlay_4(): vrt_xml = """<VRTDataset rasterXSize="800" rasterYSize="400"> <SRS>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"]]</SRS> @@ -146,33 +142,26 @@ def kmlsuperoverlay_4(): src_ds = gdal.Open("/vsimem/src.vrt") ds = gdal.GetDriverByName('KMLSUPEROVERLAY').CreateCopy('/vsimem/kmlsuperoverlay_4.kmz', src_ds, options=['FORMAT=PNG', 'NAME=myname', 'DESCRIPTION=mydescription', 'ALTITUDE=10', 'ALTITUDEMODE=absolute']) - if ds.GetMetadataItem('NAME') != 'myname': - gdaltest.post_reason('fail') - return 'fail' - if ds.GetMetadataItem('DESCRIPTION') != 'mydescription': - gdaltest.post_reason('fail') - return 'fail' + assert ds.GetMetadataItem('NAME') == 'myname' + assert ds.GetMetadataItem('DESCRIPTION') == 'mydescription' if ds.GetRasterBand(1).GetOverviewCount() != 1: - gdaltest.post_reason('fail') ds = None src_ds = None gdal.Unlink("/vsimem/src.vrt") gdal.Unlink("/vsimem/kmlsuperoverlay_4.kmz") - return 'fail' + pytest.fail() if ds.GetRasterBand(1).GetOverview(0).Checksum() != 30111: - gdaltest.post_reason('fail') ds = None src_ds = None gdal.Unlink("/vsimem/src.vrt") gdal.Unlink("/vsimem/kmlsuperoverlay_4.kmz") - return 'fail' + pytest.fail() if ds.GetRasterBand(1).Checksum() != src_ds.GetRasterBand(1).Checksum(): - gdaltest.post_reason('fail') ds = None src_ds = None gdal.Unlink("/vsimem/src.vrt") gdal.Unlink("/vsimem/kmlsuperoverlay_4.kmz") - return 'fail' + pytest.fail() # Test fix for #6311 vrt_ds = gdal.GetDriverByName('VRT').CreateCopy('', ds) @@ -180,12 +169,11 @@ def kmlsuperoverlay_4(): ref_data = ds.ReadRaster(0, 0, 800, 400, 200, 100) vrt_ds = None if got_data != ref_data: - gdaltest.post_reason('fail') ds = None src_ds = None gdal.Unlink("/vsimem/src.vrt") gdal.Unlink("/vsimem/kmlsuperoverlay_4.kmz") - return 'fail' + pytest.fail() ds = None src_ds = None @@ -193,18 +181,16 @@ def kmlsuperoverlay_4(): gdal.Unlink("/vsimem/src.vrt") gdal.Unlink("/vsimem/kmlsuperoverlay_4.kmz") - return 'success' - ############################################################################### # Test that a raster which crosses the anti-meridian will be able to be displayed correctly (#4528) -def kmlsuperoverlay_5(): +def test_kmlsuperoverlay_5(): try: from xml.etree import ElementTree except ImportError: - return 'skip' + pytest.skip() src_ds = gdal.Open("""<VRTDataset rasterXSize="512" rasterYSize="512"> <SRS>PROJCS["WGS 84 / Mercator 41", @@ -254,88 +240,56 @@ def kmlsuperoverlay_5(): east = tag.find('{http://earth.google.com/kml/2.1}east').text west = tag.find('{http://earth.google.com/kml/2.1}west').text - if float(east) < float(west): - gdaltest.post_reason('East is less than west in LatLonAltBox %s, (%s < %s)' % (f, east, west)) - return 'fail' + assert float(east) >= float(west), \ + ('East is less than west in LatLonAltBox %s, (%s < %s)' % (f, east, west)) shutil.rmtree('tmp/0') shutil.rmtree('tmp/1') os.remove('tmp/tmp.kml') - return 'success' - ############################################################################### # Test raster KML with alternate structure (such as http://opentopo.sdsc.edu/files/Haiti/NGA_Haiti_LiDAR2.kmz)) -def kmlsuperoverlay_6(): +def test_kmlsuperoverlay_6(): ds = gdal.Open('data/kmlimage.kmz') - if ds.GetProjectionRef().find('WGS_1984') < 0: - gdaltest.post_reason('failure') - return 'fail' + assert ds.GetProjectionRef().find('WGS_1984') >= 0 got_gt = ds.GetGeoTransform() ref_gt = [1.2554125761846773, 1.6640895429971981e-05, 0.0, 43.452120815728101, 0.0, -1.0762348187666334e-05] for i in range(6): - if abs(got_gt[i] - ref_gt[i]) > 1e-6: - gdaltest.post_reason('failure') - print(got_gt) - return 'fail' + assert abs(got_gt[i] - ref_gt[i]) <= 1e-6 for i in range(4): cs = ds.GetRasterBand(i + 1).Checksum() - if cs != 47673: - print(cs) - gdaltest.post_reason('failure') - return 'fail' - if ds.GetRasterBand(i + 1).GetRasterColorInterpretation() != gdal.GCI_RedBand + i: - gdaltest.post_reason('failure') - return 'fail' - if ds.GetRasterBand(1).GetOverviewCount() != 1: - gdaltest.post_reason('failure') - return 'fail' + assert cs == 47673 + assert ds.GetRasterBand(i + 1).GetRasterColorInterpretation() == gdal.GCI_RedBand + i + assert ds.GetRasterBand(1).GetOverviewCount() == 1 cs = ds.GetRasterBand(1).GetOverview(0).Checksum() - if cs != 61070: - print(cs) - gdaltest.post_reason('failure') - return 'fail' - - return 'success' + assert cs == 61070 ############################################################################### # Test raster KML with single Overlay (such as https://trac.osgeo.org/gdal/ticket/6712) -def kmlsuperoverlay_7(): +def test_kmlsuperoverlay_7(): ds = gdal.Open('data/small_world.kml') - if ds.GetProjectionRef().find('WGS_1984') < 0: - gdaltest.post_reason('failure') - return 'fail' + assert ds.GetProjectionRef().find('WGS_1984') >= 0 got_gt = ds.GetGeoTransform() ref_gt = [-180.0, 0.9, 0.0, 90.0, 0.0, -0.9] for i in range(6): - if abs(got_gt[i] - ref_gt[i]) > 1e-6: - gdaltest.post_reason('failure') - print(got_gt) - return 'fail' + assert abs(got_gt[i] - ref_gt[i]) <= 1e-6 cs = ds.GetRasterBand(1).Checksum() - if cs != 30111: - print(cs) - gdaltest.post_reason('failure') - return 'fail' - if ds.GetRasterBand(1).GetRasterColorInterpretation() != gdal.GCI_RedBand: - gdaltest.post_reason('failure') - return 'fail' - - return 'success' + assert cs == 30111 + assert ds.GetRasterBand(1).GetRasterColorInterpretation() == gdal.GCI_RedBand ############################################################################### # Test that a raster with lots of blank space doesn't have unnecessary child # KML/PNG files in transparent areas -def kmlsuperoverlay_8(): +def test_kmlsuperoverlay_8(): # a large raster with actual data on each end and blank space in between src_ds = gdal.Open("""<VRTDataset rasterXSize="2048" rasterYSize="512"> @@ -418,17 +372,10 @@ def kmlsuperoverlay_8(): del ds src_ds = None - if set(os.listdir('tmp/0/0')) != set(('0.kml', '0.png')): - gdaltest.post_reason('failure') - return 'fail' - if set(os.listdir('tmp/3/1')) != set(('0.jpg', '0.kml', '1.jpg', '1.kml', '2.jpg', '2.kml', '3.jpg', '3.kml', - '4.jpg', '4.kml', '5.jpg', '5.kml', '6.jpg', '6.kml', '7.jpg', '7.kml',)): - gdaltest.post_reason('failure') - return 'fail' - if set(os.listdir('tmp/3/2')) != set(): - # dir should be empty - 3/2 is entirely transparent so we skip generating files. - gdaltest.post_reason('failure') - return 'fail' + assert set(os.listdir('tmp/0/0')) == set(('0.kml', '0.png')) + assert (set(os.listdir('tmp/3/1')) == set(('0.jpg', '0.kml', '1.jpg', '1.kml', '2.jpg', '2.kml', '3.jpg', '3.kml', + '4.jpg', '4.kml', '5.jpg', '5.kml', '6.jpg', '6.kml', '7.jpg', '7.kml',))) + assert set(os.listdir('tmp/3/2')) == set() shutil.rmtree('tmp/0') shutil.rmtree('tmp/1') @@ -436,13 +383,11 @@ def kmlsuperoverlay_8(): shutil.rmtree('tmp/3') os.remove('tmp/tmp.kml') - return 'success' - ############################################################################### # Cleanup -def kmlsuperoverlay_cleanup(): +def test_kmlsuperoverlay_cleanup(): gdal.Unlink('/vsimem/0/0/0.png') gdal.Unlink('/vsimem/0/0/0.kml') @@ -451,24 +396,5 @@ def kmlsuperoverlay_cleanup(): gdal.Unlink('/vsimem/kmlout.kml') gdal.Unlink('/vsimem/kmlout.kmz') - return 'success' - - -gdaltest_list = [ - kmlsuperoverlay_1, - kmlsuperoverlay_2, - kmlsuperoverlay_3, - kmlsuperoverlay_4, - kmlsuperoverlay_5, - kmlsuperoverlay_6, - kmlsuperoverlay_7, - kmlsuperoverlay_8, - kmlsuperoverlay_cleanup] - -if __name__ == '__main__': - - gdaltest.setup_run(' kmlsuperoverlay') - gdaltest.run_tests(gdaltest_list) - sys.exit(gdaltest.summarize()) diff --git a/autotest/gdrivers/kro.py b/autotest/gdrivers/kro.py index 7400cf6af9f1..d194421af6db 100755 --- a/autotest/gdrivers/kro.py +++ b/autotest/gdrivers/kro.py @@ -29,18 +29,17 @@ # DEALINGS IN THE SOFTWARE. ############################################################################### -import sys from osgeo import gdal -sys.path.append('../pymod') import gdaltest +import pytest ############################################################################### # Create 3-band byte -def kro_1(): +def test_kro_1(): tst = gdaltest.GDALTest('KRO', 'rgbsmall.tif', 2, 21053) @@ -50,7 +49,7 @@ def kro_1(): # Create 1-band uint16 -def kro_2(): +def test_kro_2(): tst = gdaltest.GDALTest('KRO', '../../gcore/data/uint16.tif', 1, 4672) @@ -60,7 +59,7 @@ def kro_2(): # Create 1-band float32 -def kro_3(): +def test_kro_3(): tst = gdaltest.GDALTest('KRO', '../../gcore/data/float32.tif', 1, 4672) @@ -70,7 +69,7 @@ def kro_3(): # Create 4-band rgba uint16 -def kro_4(): +def test_kro_4(): tst = gdaltest.GDALTest('KRO', 'rgba16.png', 1, 1886) @@ -80,12 +79,12 @@ def kro_4(): # Test optimized IO -def kro_5(): +def test_kro_5(): # 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('KRO').Create('tmp/kro_5.kro', 100000, 10000, 4) ds = None @@ -96,22 +95,6 @@ def kro_5(): gdal.Unlink('tmp/kro_5.kro') - return 'success' -gdaltest_list = [ - kro_1, - kro_2, - kro_3, - kro_4, - kro_5, -] - -if __name__ == '__main__': - - gdaltest.setup_run('KRO') - - gdaltest.run_tests(gdaltest_list) - - sys.exit(gdaltest.summarize()) diff --git a/autotest/gdrivers/l1b.py b/autotest/gdrivers/l1b.py index 3f76d86f95d0..686043bfac7b 100755 --- a/autotest/gdrivers/l1b.py +++ b/autotest/gdrivers/l1b.py @@ -30,49 +30,56 @@ ############################################################################### import os -import sys -from osgeo import gdal -sys.path.append('../pymod') +import pytest + +from osgeo import gdal import gdaltest ############################################################################### # -class TestL1B(object): - def __init__(self, downloadURL, fileName, checksum, download_size, gcpNumber): - self.downloadURL = downloadURL - self.fileName = fileName - self.checksum = checksum - self.download_size = download_size - self.gcpNumber = gcpNumber - def test(self): - if not gdaltest.download_file(self.downloadURL + '/' + self.fileName, self.fileName, self.download_size): - return 'skip' - ds = gdal.Open('tmp/cache/' + self.fileName) +l1b_list = [ + ('http://download.osgeo.org/gdal/data/l1b', 'n12gac8bit.l1b', 51754, -1, 1938), + ('http://download.osgeo.org/gdal/data/l1b', 'n12gac10bit.l1b', 46039, -1, 1887), + ('http://download.osgeo.org/gdal/data/l1b', 'n12gac10bit_ebcdic.l1b', 46039, -1, 1887), # 2848 + ('http://download.osgeo.org/gdal/data/l1b', 'n14gac16bit.l1b', 42286, -1, 2142), + ('http://download.osgeo.org/gdal/data/l1b', 'n15gac8bit.l1b', 55772, -1, 2091), + ('http://download.osgeo.org/gdal/data/l1b', 'n16gac10bit.l1b', 6749, -1, 2142), + ('http://download.osgeo.org/gdal/data/l1b', 'n17gac16bit.l1b', 61561, -1, 2040), + ('http://www.ncdc.noaa.gov/oa/pod-guide/ncdc/docs/podug/data/avhrr', 'frang.1b', 33700, 30000, 357), # 10 bit guess + ('http://www.ncdc.noaa.gov/oa/pod-guide/ncdc/docs/podug/data/avhrr', 'franh.1b', 56702, 100000, 255), # 10 bit guess + ('http://www.ncdc.noaa.gov/oa/pod-guide/ncdc/docs/podug/data/avhrr', 'calfirel.1b', 55071, 30000, 255), # 16 bit guess + ('http://www.ncdc.noaa.gov/oa/pod-guide/ncdc/docs/podug/data/avhrr', 'rapnzg.1b', 58084, 30000, 612), # 16 bit guess + ('http://www.sat.dundee.ac.uk/testdata/new_noaa/new_klm_format/', 'noaa18.n1b', 50229, 50000, 102), + ('http://www.sat.dundee.ac.uk/testdata/metop', 'noaa1b', 62411, 150000, 408) +] - if ds.GetRasterBand(1).Checksum() != self.checksum: - gdaltest.post_reason('Bad checksum. Expected %d, got %d' % (self.checksum, ds.GetRasterBand(1).Checksum())) - return 'fail' - if len(ds.GetGCPs()) != self.gcpNumber: - gdaltest.post_reason('Bad GCP number. Expected %d, got %d' % (self.gcpNumber, len(ds.GetGCPs()))) - return 'fail' +@pytest.mark.parametrize( + 'downloadURL,fileName,checksum,download_size,gcpNumber', + l1b_list, + ids=[item[1] for item in l1b_list] +) +def test_l1b(downloadURL, fileName, checksum, download_size, gcpNumber): + if not gdaltest.download_file(downloadURL + '/' + fileName, fileName, download_size): + pytest.skip() - return 'success' + ds = gdal.Open('tmp/cache/' + fileName) -############################################################################### -# + assert ds.GetRasterBand(1).Checksum() == checksum + assert len(ds.GetGCPs()) == gcpNumber -def l1b_geoloc(): + +def test_l1b_geoloc(): try: os.stat('tmp/cache/n12gac8bit.l1b') except OSError: - return 'skip' + pytest.skip() ds = gdal.Open('tmp/cache/n12gac8bit.l1b') md = ds.GetMetadata('GEOLOCATION') @@ -86,34 +93,24 @@ def l1b_geoloc(): 'Y_BAND': '2', 'Y_DATASET': 'L1BGCPS_INTERPOL:"tmp/cache/n12gac8bit.l1b"'} for key in expected_md: - if md[key] != expected_md[key]: - print(md) - return 'fail' + assert md[key] == expected_md[key] ds = None ds = gdal.Open('L1BGCPS_INTERPOL:"tmp/cache/n12gac8bit.l1b"') cs = ds.GetRasterBand(1).Checksum() - if cs != 62397: - gdaltest.post_reason('fail') - print(cs) - return 'fail' + assert cs == 62397 cs = ds.GetRasterBand(2).Checksum() - if cs != 52616: - gdaltest.post_reason('fail') - print(cs) - return 'fail' - - return 'success' + assert cs == 52616 ############################################################################### # -def l1b_solar_zenith_angles_before_noaa_15(): +def test_l1b_solar_zenith_angles_before_noaa_15(): try: os.stat('tmp/cache/n12gac10bit.l1b') except OSError: - return 'skip' + pytest.skip() ds = gdal.Open('tmp/cache/n12gac10bit.l1b') md = ds.GetMetadata('SUBDATASETS') @@ -122,29 +119,22 @@ def l1b_solar_zenith_angles_before_noaa_15(): 'SUBDATASET_1_DESC': 'Solar zenith angles' } for key in expected_md: - if md[key] != expected_md[key]: - print(md) - return 'fail' + assert md[key] == expected_md[key] ds = None ds = gdal.Open('L1B_SOLAR_ZENITH_ANGLES:"tmp/cache/n12gac10bit.l1b"') cs = ds.GetRasterBand(1).Checksum() - if cs != 22924: - gdaltest.post_reason('fail') - print(cs) - return 'fail' - - return 'success' + assert cs == 22924 ############################################################################### # -def l1b_metadata_before_noaa_15(): +def test_l1b_metadata_before_noaa_15(): try: os.stat('tmp/cache/n12gac10bit.l1b') except OSError: - return 'skip' + pytest.skip() gdal.SetConfigOption('L1B_FETCH_METADATA', 'YES') gdal.SetConfigOption('L1B_METADATA_DIRECTORY', 'tmp') @@ -155,28 +145,22 @@ def l1b_metadata_before_noaa_15(): f = open('tmp/n12gac10bit.l1b_metadata.csv', 'rb') ln = f.readline().decode('ascii') - if ln != 'SCANLINE,NBLOCKYOFF,YEAR,DAY,MS_IN_DAY,FATAL_FLAG,TIME_ERROR,DATA_GAP,DATA_JITTER,INSUFFICIENT_DATA_FOR_CAL,NO_EARTH_LOCATION,DESCEND,P_N_STATUS,BIT_SYNC_STATUS,SYNC_ERROR,FRAME_SYNC_ERROR,FLYWHEELING,BIT_SLIPPAGE,C3_SBBC,C4_SBBC,C5_SBBC,TIP_PARITY_FRAME_1,TIP_PARITY_FRAME_2,TIP_PARITY_FRAME_3,TIP_PARITY_FRAME_4,TIP_PARITY_FRAME_5,SYNC_ERRORS,CAL_SLOPE_C1,CAL_INTERCEPT_C1,CAL_SLOPE_C2,CAL_INTERCEPT_C2,CAL_SLOPE_C3,CAL_INTERCEPT_C3,CAL_SLOPE_C4,CAL_INTERCEPT_C4,CAL_SLOPE_C5,CAL_INTERCEPT_C5,NUM_SOLZENANGLES_EARTHLOCPNTS\n': - print(ln) - return 'fail' + assert ln == 'SCANLINE,NBLOCKYOFF,YEAR,DAY,MS_IN_DAY,FATAL_FLAG,TIME_ERROR,DATA_GAP,DATA_JITTER,INSUFFICIENT_DATA_FOR_CAL,NO_EARTH_LOCATION,DESCEND,P_N_STATUS,BIT_SYNC_STATUS,SYNC_ERROR,FRAME_SYNC_ERROR,FLYWHEELING,BIT_SLIPPAGE,C3_SBBC,C4_SBBC,C5_SBBC,TIP_PARITY_FRAME_1,TIP_PARITY_FRAME_2,TIP_PARITY_FRAME_3,TIP_PARITY_FRAME_4,TIP_PARITY_FRAME_5,SYNC_ERRORS,CAL_SLOPE_C1,CAL_INTERCEPT_C1,CAL_SLOPE_C2,CAL_INTERCEPT_C2,CAL_SLOPE_C3,CAL_INTERCEPT_C3,CAL_SLOPE_C4,CAL_INTERCEPT_C4,CAL_SLOPE_C5,CAL_INTERCEPT_C5,NUM_SOLZENANGLES_EARTHLOCPNTS\n' ln = f.readline().decode('ascii') - if ln != '3387,0,1998,84,16966146,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0.102000,-4.130000,0.103000,-4.210000,-0.001677,1.667438,-0.157728,156.939636,-0.179833,179.775742,51\n': - print(ln) - return 'fail' + assert ln == '3387,0,1998,84,16966146,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0.102000,-4.130000,0.103000,-4.210000,-0.001677,1.667438,-0.157728,156.939636,-0.179833,179.775742,51\n' f.close() os.unlink('tmp/n12gac10bit.l1b_metadata.csv') - return 'success' - ############################################################################### # -def l1b_angles_after_noaa_15(): +def test_l1b_angles_after_noaa_15(): try: os.stat('tmp/cache/n16gac10bit.l1b') except OSError: - return 'skip' + pytest.skip() ds = gdal.Open('tmp/cache/n16gac10bit.l1b') md = ds.GetMetadata('SUBDATASETS') @@ -185,39 +169,26 @@ def l1b_angles_after_noaa_15(): 'SUBDATASET_1_DESC': 'Solar zenith angles, satellite zenith angles and relative azimuth angles' } for key in expected_md: - if md[key] != expected_md[key]: - print(md) - return 'fail' + assert md[key] == expected_md[key] ds = None ds = gdal.Open('L1B_ANGLES:"tmp/cache/n16gac10bit.l1b"') cs = ds.GetRasterBand(1).Checksum() - if cs != 31487: - gdaltest.post_reason('fail') - print(cs) - return 'fail' + assert cs == 31487 cs = ds.GetRasterBand(2).Checksum() - if cs != 23380: - gdaltest.post_reason('fail') - print(cs) - return 'fail' + assert cs == 23380 cs = ds.GetRasterBand(3).Checksum() - if cs != 64989: - gdaltest.post_reason('fail') - print(cs) - return 'fail' - - return 'success' + assert cs == 64989 ############################################################################### # -def l1b_clouds_after_noaa_15(): +def test_l1b_clouds_after_noaa_15(): try: os.stat('tmp/cache/n16gac10bit.l1b') except OSError: - return 'skip' + pytest.skip() ds = gdal.Open('tmp/cache/n16gac10bit.l1b') md = ds.GetMetadata('SUBDATASETS') @@ -226,29 +197,22 @@ def l1b_clouds_after_noaa_15(): 'SUBDATASET_2_DESC': 'Clouds from AVHRR (CLAVR)' } for key in expected_md: - if md[key] != expected_md[key]: - print(md) - return 'fail' + assert md[key] == expected_md[key] ds = None ds = gdal.Open('L1B_CLOUDS:"tmp/cache/n16gac10bit.l1b"') cs = ds.GetRasterBand(1).Checksum() - if cs != 0: - gdaltest.post_reason('fail') - print(cs) - return 'fail' - - return 'success' + assert cs == 0 ############################################################################### # -def l1b_metadata_after_noaa_15(): +def test_l1b_metadata_after_noaa_15(): try: os.stat('tmp/cache/n16gac10bit.l1b') except OSError: - return 'skip' + pytest.skip() gdal.SetConfigOption('L1B_FETCH_METADATA', 'YES') gdal.SetConfigOption('L1B_METADATA_DIRECTORY', 'tmp') @@ -259,76 +223,26 @@ def l1b_metadata_after_noaa_15(): f = open('tmp/n16gac10bit.l1b_metadata.csv', 'rb') ln = f.readline().decode('ascii') - if ln != 'SCANLINE,NBLOCKYOFF,YEAR,DAY,MS_IN_DAY,SAT_CLOCK_DRIF_DELTA,SOUTHBOUND,SCANTIME_CORRECTED,C3_SELECT,FATAL_FLAG,TIME_ERROR,DATA_GAP,INSUFFICIENT_DATA_FOR_CAL,NO_EARTH_LOCATION,FIRST_GOOD_TIME_AFTER_CLOCK_UPDATE,INSTRUMENT_STATUS_CHANGED,SYNC_LOCK_DROPPED,FRAME_SYNC_ERROR,FRAME_SYNC_DROPPED_LOCK,FLYWHEELING,BIT_SLIPPAGE,TIP_PARITY_ERROR,REFLECTED_SUNLIGHT_C3B,REFLECTED_SUNLIGHT_C4,REFLECTED_SUNLIGHT_C5,RESYNC,P_N_STATUS,BAD_TIME_CAN_BE_INFERRED,BAD_TIME_CANNOT_BE_INFERRED,TIME_DISCONTINUITY,REPEAT_SCAN_TIME,UNCALIBRATED_BAD_TIME,CALIBRATED_FEWER_SCANLINES,UNCALIBRATED_BAD_PRT,CALIBRATED_MARGINAL_PRT,UNCALIBRATED_CHANNELS,NO_EARTH_LOC_BAD_TIME,EARTH_LOC_QUESTIONABLE_TIME,EARTH_LOC_QUESTIONABLE,EARTH_LOC_VERY_QUESTIONABLE,C3B_UNCALIBRATED,C3B_QUESTIONABLE,C3B_ALL_BLACKBODY,C3B_ALL_SPACEVIEW,C3B_MARGINAL_BLACKBODY,C3B_MARGINAL_SPACEVIEW,C4_UNCALIBRATED,C4_QUESTIONABLE,C4_ALL_BLACKBODY,C4_ALL_SPACEVIEW,C4_MARGINAL_BLACKBODY,C4_MARGINAL_SPACEVIEW,C5_UNCALIBRATED,C5_QUESTIONABLE,C5_ALL_BLACKBODY,C5_ALL_SPACEVIEW,C5_MARGINAL_BLACKBODY,C5_MARGINAL_SPACEVIEW,BIT_ERRORS,VIS_OP_CAL_C1_SLOPE_1,VIS_OP_CAL_C1_INTERCEPT_1,VIS_OP_CAL_C1_SLOPE_2,VIS_OP_CAL_C1_INTERCEPT_2,VIS_OP_CAL_C1_INTERSECTION,VIS_TEST_CAL_C1_SLOPE_1,VIS_TEST_CAL_C1_INTERCEPT_1,VIS_TEST_CAL_C1_SLOPE_2,VIS_TEST_CAL_C1_INTERCEPT_2,VIS_TEST_CAL_C1_INTERSECTION,VIS_PRELAUNCH_CAL_C1_SLOPE_1,VIS_PRELAUNCH_CAL_C1_INTERCEPT_1,VIS_PRELAUNCH_CAL_C1_SLOPE_2,VIS_PRELAUNCH_CAL_C1_INTERCEPT_2,VIS_PRELAUNCH_CAL_C1_INTERSECTION,VIS_OP_CAL_C2_SLOPE_1,VIS_OP_CAL_C2_INTERCEPT_1,VIS_OP_CAL_C2_SLOPE_2,VIS_OP_CAL_C2_INTERCEPT_2,VIS_OP_CAL_C2_INTERSECTION,VIS_TEST_CAL_C2_SLOPE_1,VIS_TEST_CAL_C2_INTERCEPT_1,VIS_TEST_CAL_C2_SLOPE_2,VIS_TEST_CAL_C2_INTERCEPT_2,VIS_TEST_CAL_C2_INTERSECTION,VIS_PRELAUNCH_CAL_C2_SLOPE_1,VIS_PRELAUNCH_CAL_C2_INTERCEPT_1,VIS_PRELAUNCH_CAL_C2_SLOPE_2,VIS_PRELAUNCH_CAL_C2_INTERCEPT_2,VIS_PRELAUNCH_CAL_C2_INTERSECTION,VIS_OP_CAL_C3A_SLOPE_1,VIS_OP_CAL_C3A_INTERCEPT_1,VIS_OP_CAL_C3A_SLOPE_2,VIS_OP_CAL_C3A_INTERCEPT_2,VIS_OP_CAL_C3A_INTERSECTION,VIS_TEST_CAL_C3A_SLOPE_1,VIS_TEST_CAL_C3A_INTERCEPT_1,VIS_TEST_CAL_C3A_SLOPE_2,VIS_TEST_CAL_C3A_INTERCEPT_2,VIS_TEST_CAL_C3A_INTERSECTION,VIS_PRELAUNCH_CAL_C3A_SLOPE_1,VIS_PRELAUNCH_CAL_C3A_INTERCEPT_1,VIS_PRELAUNCH_CAL_C3A_SLOPE_2,VIS_PRELAUNCH_CAL_C3A_INTERCEPT_2,VIS_PRELAUNCH_CAL_C3A_INTERSECTION,IR_OP_CAL_C3B_COEFF_1,IR_OP_CAL_C3B_COEFF_2,IR_OP_CAL_C3B_COEFF_3,IR_TEST_CAL_C3B_COEFF_1,IR_TEST_CAL_C3B_COEFF_2,IR_TEST_CAL_C3B_COEFF_3,IR_OP_CAL_C4_COEFF_1,IR_OP_CAL_C4_COEFF_2,IR_OP_CAL_C4_COEFF_3,IR_TEST_CAL_C4_COEFF_1,IR_TEST_CAL_C4_COEFF_2,IR_TEST_CAL_C4_COEFF_3,IR_OP_CAL_C5_COEFF_1,IR_OP_CAL_C5_COEFF_2,IR_OP_CAL_C5_COEFF_3,IR_TEST_CAL_C5_COEFF_1,IR_TEST_CAL_C5_COEFF_2,IR_TEST_CAL_C5_COEFF_3,EARTH_LOC_CORR_TIP_EULER,EARTH_LOC_IND,SPACECRAFT_ATT_CTRL,ATT_SMODE,ATT_PASSIVE_WHEEL_TEST,TIME_TIP_EULER,TIP_EULER_ROLL,TIP_EULER_PITCH,TIP_EULER_YAW,SPACECRAFT_ALT\n': - print(ln) - return 'fail' + assert ln == 'SCANLINE,NBLOCKYOFF,YEAR,DAY,MS_IN_DAY,SAT_CLOCK_DRIF_DELTA,SOUTHBOUND,SCANTIME_CORRECTED,C3_SELECT,FATAL_FLAG,TIME_ERROR,DATA_GAP,INSUFFICIENT_DATA_FOR_CAL,NO_EARTH_LOCATION,FIRST_GOOD_TIME_AFTER_CLOCK_UPDATE,INSTRUMENT_STATUS_CHANGED,SYNC_LOCK_DROPPED,FRAME_SYNC_ERROR,FRAME_SYNC_DROPPED_LOCK,FLYWHEELING,BIT_SLIPPAGE,TIP_PARITY_ERROR,REFLECTED_SUNLIGHT_C3B,REFLECTED_SUNLIGHT_C4,REFLECTED_SUNLIGHT_C5,RESYNC,P_N_STATUS,BAD_TIME_CAN_BE_INFERRED,BAD_TIME_CANNOT_BE_INFERRED,TIME_DISCONTINUITY,REPEAT_SCAN_TIME,UNCALIBRATED_BAD_TIME,CALIBRATED_FEWER_SCANLINES,UNCALIBRATED_BAD_PRT,CALIBRATED_MARGINAL_PRT,UNCALIBRATED_CHANNELS,NO_EARTH_LOC_BAD_TIME,EARTH_LOC_QUESTIONABLE_TIME,EARTH_LOC_QUESTIONABLE,EARTH_LOC_VERY_QUESTIONABLE,C3B_UNCALIBRATED,C3B_QUESTIONABLE,C3B_ALL_BLACKBODY,C3B_ALL_SPACEVIEW,C3B_MARGINAL_BLACKBODY,C3B_MARGINAL_SPACEVIEW,C4_UNCALIBRATED,C4_QUESTIONABLE,C4_ALL_BLACKBODY,C4_ALL_SPACEVIEW,C4_MARGINAL_BLACKBODY,C4_MARGINAL_SPACEVIEW,C5_UNCALIBRATED,C5_QUESTIONABLE,C5_ALL_BLACKBODY,C5_ALL_SPACEVIEW,C5_MARGINAL_BLACKBODY,C5_MARGINAL_SPACEVIEW,BIT_ERRORS,VIS_OP_CAL_C1_SLOPE_1,VIS_OP_CAL_C1_INTERCEPT_1,VIS_OP_CAL_C1_SLOPE_2,VIS_OP_CAL_C1_INTERCEPT_2,VIS_OP_CAL_C1_INTERSECTION,VIS_TEST_CAL_C1_SLOPE_1,VIS_TEST_CAL_C1_INTERCEPT_1,VIS_TEST_CAL_C1_SLOPE_2,VIS_TEST_CAL_C1_INTERCEPT_2,VIS_TEST_CAL_C1_INTERSECTION,VIS_PRELAUNCH_CAL_C1_SLOPE_1,VIS_PRELAUNCH_CAL_C1_INTERCEPT_1,VIS_PRELAUNCH_CAL_C1_SLOPE_2,VIS_PRELAUNCH_CAL_C1_INTERCEPT_2,VIS_PRELAUNCH_CAL_C1_INTERSECTION,VIS_OP_CAL_C2_SLOPE_1,VIS_OP_CAL_C2_INTERCEPT_1,VIS_OP_CAL_C2_SLOPE_2,VIS_OP_CAL_C2_INTERCEPT_2,VIS_OP_CAL_C2_INTERSECTION,VIS_TEST_CAL_C2_SLOPE_1,VIS_TEST_CAL_C2_INTERCEPT_1,VIS_TEST_CAL_C2_SLOPE_2,VIS_TEST_CAL_C2_INTERCEPT_2,VIS_TEST_CAL_C2_INTERSECTION,VIS_PRELAUNCH_CAL_C2_SLOPE_1,VIS_PRELAUNCH_CAL_C2_INTERCEPT_1,VIS_PRELAUNCH_CAL_C2_SLOPE_2,VIS_PRELAUNCH_CAL_C2_INTERCEPT_2,VIS_PRELAUNCH_CAL_C2_INTERSECTION,VIS_OP_CAL_C3A_SLOPE_1,VIS_OP_CAL_C3A_INTERCEPT_1,VIS_OP_CAL_C3A_SLOPE_2,VIS_OP_CAL_C3A_INTERCEPT_2,VIS_OP_CAL_C3A_INTERSECTION,VIS_TEST_CAL_C3A_SLOPE_1,VIS_TEST_CAL_C3A_INTERCEPT_1,VIS_TEST_CAL_C3A_SLOPE_2,VIS_TEST_CAL_C3A_INTERCEPT_2,VIS_TEST_CAL_C3A_INTERSECTION,VIS_PRELAUNCH_CAL_C3A_SLOPE_1,VIS_PRELAUNCH_CAL_C3A_INTERCEPT_1,VIS_PRELAUNCH_CAL_C3A_SLOPE_2,VIS_PRELAUNCH_CAL_C3A_INTERCEPT_2,VIS_PRELAUNCH_CAL_C3A_INTERSECTION,IR_OP_CAL_C3B_COEFF_1,IR_OP_CAL_C3B_COEFF_2,IR_OP_CAL_C3B_COEFF_3,IR_TEST_CAL_C3B_COEFF_1,IR_TEST_CAL_C3B_COEFF_2,IR_TEST_CAL_C3B_COEFF_3,IR_OP_CAL_C4_COEFF_1,IR_OP_CAL_C4_COEFF_2,IR_OP_CAL_C4_COEFF_3,IR_TEST_CAL_C4_COEFF_1,IR_TEST_CAL_C4_COEFF_2,IR_TEST_CAL_C4_COEFF_3,IR_OP_CAL_C5_COEFF_1,IR_OP_CAL_C5_COEFF_2,IR_OP_CAL_C5_COEFF_3,IR_TEST_CAL_C5_COEFF_1,IR_TEST_CAL_C5_COEFF_2,IR_TEST_CAL_C5_COEFF_3,EARTH_LOC_CORR_TIP_EULER,EARTH_LOC_IND,SPACECRAFT_ATT_CTRL,ATT_SMODE,ATT_PASSIVE_WHEEL_TEST,TIME_TIP_EULER,TIP_EULER_ROLL,TIP_EULER_PITCH,TIP_EULER_YAW,SPACECRAFT_ALT\n' ln = f.readline().decode('ascii') - if ln != '3406,0,2003,85,3275054,79,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0.052300,-2.015999,0.152800,-51.910000,499,0.052300,-2.015999,0.152800,-51.910000,498,0.052300,-2.015999,0.152800,-51.910000,498,0.051300,-1.942999,0.151000,-51.770000,500,0.051300,-1.942999,0.151000,-51.770000,500,0.051300,-1.942999,0.151000,-51.770000,500,0.000000,0.000000,0.000000,0.000000,0,0.000000,0.000000,0.000000,0.000000,0,0.000000,0.000000,0.000000,0.000000,0,2.488212,-0.002511,0.000000,2.488212,-0.002511,0.000000,179.546496,-0.188553,0.000008,179.546496,-0.188553,0.000008,195.236384,-0.201709,0.000006,195.236384,-0.201709,0.000006,0,0,0,0,0,608093,-0.021000,-0.007000,0.000000,862.000000\n': - print(ln) - return 'fail' + assert ln == '3406,0,2003,85,3275054,79,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0.052300,-2.015999,0.152800,-51.910000,499,0.052300,-2.015999,0.152800,-51.910000,498,0.052300,-2.015999,0.152800,-51.910000,498,0.051300,-1.942999,0.151000,-51.770000,500,0.051300,-1.942999,0.151000,-51.770000,500,0.051300,-1.942999,0.151000,-51.770000,500,0.000000,0.000000,0.000000,0.000000,0,0.000000,0.000000,0.000000,0.000000,0,0.000000,0.000000,0.000000,0.000000,0,2.488212,-0.002511,0.000000,2.488212,-0.002511,0.000000,179.546496,-0.188553,0.000008,179.546496,-0.188553,0.000008,195.236384,-0.201709,0.000006,195.236384,-0.201709,0.000006,0,0,0,0,0,608093,-0.021000,-0.007000,0.000000,862.000000\n' f.close() os.unlink('tmp/n16gac10bit.l1b_metadata.csv') - return 'success' - ############################################################################### # -def l1b_little_endian(): +def test_l1b_little_endian(): ds = gdal.Open('/vsizip/data/hrpt_little_endian.l1b.zip') - if ds.GetGCPProjection().find('GRS80') < 0: - gdaltest.post_reason('fail') - return 'fail' - if ds.GetRasterBand(1).Checksum() != 14145: - gdaltest.post_reason('fail') - return 'fail' - if ds.GetRasterBand(1).GetMaskFlags() != gdal.GMF_PER_DATASET: - gdaltest.post_reason('fail') - return 'fail' - if ds.GetRasterBand(1).GetMaskBand().Checksum() != 25115: - gdaltest.post_reason('fail') - return 'fail' + assert ds.GetGCPProjection().find('GRS80') >= 0 + assert ds.GetRasterBand(1).Checksum() == 14145 + assert ds.GetRasterBand(1).GetMaskFlags() == gdal.GMF_PER_DATASET + assert ds.GetRasterBand(1).GetMaskBand().Checksum() == 25115 ds = None - return 'success' - - -gdaltest_list = [] - -l1b_list = [('http://download.osgeo.org/gdal/data/l1b', 'n12gac8bit.l1b', 51754, -1, 1938), - ('http://download.osgeo.org/gdal/data/l1b', 'n12gac10bit.l1b', 46039, -1, 1887), - ('http://download.osgeo.org/gdal/data/l1b', 'n12gac10bit_ebcdic.l1b', 46039, -1, 1887), # 2848 - ('http://download.osgeo.org/gdal/data/l1b', 'n14gac16bit.l1b', 42286, -1, 2142), - ('http://download.osgeo.org/gdal/data/l1b', 'n15gac8bit.l1b', 55772, -1, 2091), - ('http://download.osgeo.org/gdal/data/l1b', 'n16gac10bit.l1b', 6749, -1, 2142), - ('http://download.osgeo.org/gdal/data/l1b', 'n17gac16bit.l1b', 61561, -1, 2040), - ('http://www.ncdc.noaa.gov/oa/pod-guide/ncdc/docs/podug/data/avhrr', 'frang.1b', 33700, 30000, 357), # 10 bit guess - ('http://www.ncdc.noaa.gov/oa/pod-guide/ncdc/docs/podug/data/avhrr', 'franh.1b', 56702, 100000, 255), # 10 bit guess - ('http://www.ncdc.noaa.gov/oa/pod-guide/ncdc/docs/podug/data/avhrr', 'calfirel.1b', 55071, 30000, 255), # 16 bit guess - ('http://www.ncdc.noaa.gov/oa/pod-guide/ncdc/docs/podug/data/avhrr', 'rapnzg.1b', 58084, 30000, 612), # 16 bit guess - ('http://www.sat.dundee.ac.uk/testdata/new_noaa/new_klm_format/', 'noaa18.n1b', 50229, 50000, 102), - ('http://www.sat.dundee.ac.uk/testdata/metop', 'noaa1b', 62411, 150000, 408) - ] - -for item in l1b_list: - ut = TestL1B(item[0], item[1], item[2], item[3], item[4]) - gdaltest_list.append((ut.test, item[1])) - -gdaltest_list.append(l1b_geoloc) -gdaltest_list.append(l1b_solar_zenith_angles_before_noaa_15) -gdaltest_list.append(l1b_metadata_before_noaa_15) -gdaltest_list.append(l1b_angles_after_noaa_15) -gdaltest_list.append(l1b_clouds_after_noaa_15) -gdaltest_list.append(l1b_metadata_after_noaa_15) -gdaltest_list.append(l1b_little_endian) - -if __name__ == '__main__': - gdaltest.setup_run('l1b') - gdaltest.run_tests(gdaltest_list) - sys.exit(gdaltest.summarize()) diff --git a/autotest/gdrivers/lan.py b/autotest/gdrivers/lan.py index f27a7d996908..4dde4f7244ec 100755 --- a/autotest/gdrivers/lan.py +++ b/autotest/gdrivers/lan.py @@ -28,9 +28,7 @@ # DEALINGS IN THE SOFTWARE. ############################################################################### -import sys -sys.path.append('../pymod') import gdaltest @@ -38,7 +36,7 @@ # Test reading a - fake - LAN 8 bit dataset -def lan_1(): +def test_lan_1(): tst = gdaltest.GDALTest('LAN', 'fakelan.lan', 1, 10) return tst.testOpen() @@ -47,20 +45,10 @@ def lan_1(): # Test reading a - fake - LAN 4 bit dataset -def lan_2(): +def test_lan_2(): tst = gdaltest.GDALTest('LAN', 'fakelan4bit.lan', 1, 10) return tst.testOpen() -gdaltest_list = [ - lan_1, - lan_2] -if __name__ == '__main__': - - gdaltest.setup_run('lan') - - gdaltest.run_tests(gdaltest_list) - - sys.exit(gdaltest.summarize()) diff --git a/autotest/gdrivers/lcp.py b/autotest/gdrivers/lcp.py index 6ba72b135565..c9922caeea2e 100755 --- a/autotest/gdrivers/lcp.py +++ b/autotest/gdrivers/lcp.py @@ -30,36 +30,31 @@ ############################################################################### import os -import sys from osgeo import gdal -sys.path.append('../pymod') import gdaltest +import pytest ############################################################################### # Test test_FARSITE_UTM12.LCP -def lcp_1(): +def test_lcp_1(): ds = gdal.Open('data/test_FARSITE_UTM12.LCP') - if ds.RasterCount != 8: - gdaltest.post_reason('wrong number of bands') - return 'fail' + assert ds.RasterCount == 8, 'wrong number of bands' - if ds.GetProjectionRef().find('NAD_1983_UTM_Zone_12N') == -1: - gdaltest.post_reason("didn't get expect projection. Got : %s" % (ds.GetProjectionRef())) - return 'fail' + assert ds.GetProjectionRef().find('NAD_1983_UTM_Zone_12N') != -1, \ + ("didn't get expect projection. Got : %s" % (ds.GetProjectionRef())) metadata = [('LATITUDE', '49'), ('LINEAR_UNIT', 'Meters'), ('DESCRIPTION', 'This is a test LCP file created with FARSITE 4.1.054, using data downloaded from the USGS \r\nNational Map for LANDFIRE (2008-05-06). Data were reprojected to UTM zone 12 on NAD83 \r\nusing gdalwarp (GDAL 1.4.2).\r\n')] md = ds.GetMetadata() for item in metadata: - if md[item[0]] != item[1]: - gdaltest.post_reason('wrong metadataitem for dataset. md[\'%s\']=\'%s\', expected \'%s\'' % (item[0], md[item[0]], item[1])) - return 'fail' + assert md[item[0]] == item[1], \ + ('wrong metadataitem for dataset. md[\'%s\']=\'%s\', expected \'%s\'' % (item[0], md[item[0]], item[1])) check_gt = (285807.932887174887583, 30, 0, 5379230.386217921040952, 0, -30) new_gt = ds.GetGeoTransform() @@ -68,8 +63,7 @@ def lcp_1(): print('') print('old = ', check_gt) print('new = ', new_gt) - gdaltest.post_reason('Geotransform differs.') - return 'fail' + pytest.fail('Geotransform differs.') dataPerBand = [(18645, [('ELEVATION_UNIT', '0'), ('ELEVATION_UNIT_NAME', 'Meters'), @@ -124,38 +118,31 @@ def lcp_1(): for i in range(8): band = ds.GetRasterBand(i + 1) - if band.Checksum() != dataPerBand[i][0]: - gdaltest.post_reason('wrong checksum for band %d. Got %d, expected %d' % (i + 1, band.Checksum(), dataPerBand[i][0])) - return 'fail' + assert band.Checksum() == dataPerBand[i][0], \ + ('wrong checksum for band %d. Got %d, expected %d' % (i + 1, band.Checksum(), dataPerBand[i][0])) md = band.GetMetadata() for item in dataPerBand[i][1]: - if md[item[0]] != item[1]: - gdaltest.post_reason('wrong metadataitem for band %d. md[\'%s\']=\'%s\', expected \'%s\'' % (i + 1, item[0], md[item[0]], item[1])) - return 'fail' + assert md[item[0]] == item[1], \ + ('wrong metadataitem for band %d. md[\'%s\']=\'%s\', expected \'%s\'' % (i + 1, item[0], md[item[0]], item[1])) ds = None - return 'success' - ############################################################################### # test test_USGS_LFNM_Alb83.lcp -def lcp_2(): +def test_lcp_2(): ds = gdal.Open('data/test_USGS_LFNM_Alb83.lcp') - if ds.RasterCount != 8: - gdaltest.post_reason('wrong number of bands') - return 'fail' + assert ds.RasterCount == 8, 'wrong number of bands' metadata = [('LATITUDE', '48'), ('LINEAR_UNIT', 'Meters'), ('DESCRIPTION', '')] md = ds.GetMetadata() for item in metadata: - if md[item[0]] != item[1]: - gdaltest.post_reason('wrong metadataitem for dataset. md[\'%s\']=\'%s\', expected \'%s\'' % (item[0], md[item[0]], item[1])) - return 'fail' + assert md[item[0]] == item[1], \ + ('wrong metadataitem for dataset. md[\'%s\']=\'%s\', expected \'%s\'' % (item[0], md[item[0]], item[1])) check_gt = (-1328145, 30, 0, 2961735, 0, -30) new_gt = ds.GetGeoTransform() @@ -164,8 +151,7 @@ def lcp_2(): print('') print('old = ', check_gt) print('new = ', new_gt) - gdaltest.post_reason('Geotransform differs.') - return 'fail' + pytest.fail('Geotransform differs.') dataPerBand = [(28381, [('ELEVATION_UNIT', '0'), ('ELEVATION_UNIT_NAME', 'Meters'), @@ -220,74 +206,57 @@ def lcp_2(): for i in range(8): band = ds.GetRasterBand(i + 1) - if band.Checksum() != dataPerBand[i][0]: - gdaltest.post_reason('wrong checksum for band %d. Got %d, expected %d' % (i + 1, band.Checksum(), dataPerBand[i][0])) - return 'fail' + assert band.Checksum() == dataPerBand[i][0], \ + ('wrong checksum for band %d. Got %d, expected %d' % (i + 1, band.Checksum(), dataPerBand[i][0])) md = band.GetMetadata() for item in dataPerBand[i][1]: - if md[item[0]] != item[1]: - gdaltest.post_reason('wrong metadataitem for band %d. md[\'%s\']=\'%s\', expected \'%s\'' % (i + 1, item[0], md[item[0]], item[1])) - return 'fail' + assert md[item[0]] == item[1], \ + ('wrong metadataitem for band %d. md[\'%s\']=\'%s\', expected \'%s\'' % (i + 1, item[0], md[item[0]], item[1])) ds = None - return 'success' - ############################################################################### # Test for empty prj -def lcp_3(): +def test_lcp_3(): ds = gdal.Open('data/test_USGS_LFNM_Alb83.lcp') - if ds is None: - return 'fail' + assert ds is not None wkt = ds.GetProjection() - if wkt is None: - gdaltest.post_reason('Got None from GetProjection()') - return 'fail' - return 'success' + assert wkt is not None, 'Got None from GetProjection()' ############################################################################### # Test that the prj file isn't added to the sibling list if it isn't there. -def lcp_4(): +def test_lcp_4(): ds = gdal.Open('data/test_USGS_LFNM_Alb83.lcp') - if ds is None: - return 'fail' + assert ds is not None fl = ds.GetFileList() - if len(fl) != 1: - gdaltest.post_reason('Invalid file list') - return 'fail' - return 'success' + assert len(fl) == 1, 'Invalid file list' ############################################################################### # Test for valid prj -def lcp_5(): +def test_lcp_5(): ds = gdal.Open('data/test_FARSITE_UTM12.LCP') - if ds is None: - return 'fail' + assert ds is not None wkt = ds.GetProjection() - if wkt is None or wkt == '': - gdaltest.post_reason('Got invalid wkt from GetProjection()') - return 'fail' - return 'success' + assert not (wkt is None or wkt == ''), 'Got invalid wkt from GetProjection()' ############################################################################### # Test for valid sibling list -def lcp_6(): +def test_lcp_6(): retval = 'success' ds = gdal.Open('data/test_FARSITE_UTM12.LCP') - if ds is None: - return 'fail' + assert ds is not None fl = ds.GetFileList() if len(fl) != 2: gdaltest.post_reason('Invalid file list') @@ -304,21 +273,18 @@ def lcp_6(): # Test create copy that copies data over -def lcp_7(): +def test_lcp_7(): mem_drv = gdal.GetDriverByName('MEM') - if mem_drv is None: - return 'fail' + assert mem_drv is not None lcp_drv = gdal.GetDriverByName('LCP') - if lcp_drv is None: - return 'fail' + assert lcp_drv is not None # Make sure all available band counts work. retval = 'success' co = ['LATITUDE=0', 'LINEAR_UNIT=METER'] for i in [5, 7, 8, 10]: src_ds = mem_drv.Create('/vsimem/lcptest', 10, 20, i, gdal.GDT_Int16) - if src_ds is None: - return 'fail' + assert src_ds is not None dst_ds = lcp_drv.CreateCopy('tmp/lcp_7.lcp', src_ds, False, co) if dst_ds is None: gdaltest.post_reason('Failed to create lcp with %d bands' % i) @@ -340,14 +306,12 @@ def lcp_7(): # Test create copy with invalid bands -def lcp_8(): +def test_lcp_8(): mem_drv = gdal.GetDriverByName('MEM') - if mem_drv is None: - return 'fail' + assert mem_drv is not None lcp_drv = gdal.GetDriverByName('LCP') - if lcp_drv is None: - return 'fail' + assert lcp_drv is not None gdal.PushErrorHandler('CPLQuietErrorHandler') retval = 'success' co = ['LATITUDE=0', 'LINEAR_UNIT=METER'] @@ -376,22 +340,18 @@ def lcp_8(): # Test create copy -def lcp_9(): +def test_lcp_9(): mem_drv = gdal.GetDriverByName('MEM') - if mem_drv is None: - return 'fail' + assert mem_drv is not None lcp_drv = gdal.GetDriverByName('LCP') - if lcp_drv is None: - return 'fail' + assert lcp_drv is not None src_ds = mem_drv.Create('', 10, 20, 10, gdal.GDT_Int16) - if src_ds is None: - return 'fail' + assert src_ds is not None retval = 'success' co = ['LATITUDE=0', 'LINEAR_UNIT=METER'] lcp_ds = lcp_drv.CreateCopy('tmp/lcp_9.lcp', src_ds, False, co) - if lcp_ds is None: - return 'fail' + assert lcp_ds is not None lcp_ds = None for ext in ['lcp', 'lcp.aux.xml']: try: @@ -404,17 +364,14 @@ def lcp_9(): # Test create copy and make sure all unit metadata co work -def lcp_10(): +def test_lcp_10(): mem_drv = gdal.GetDriverByName('MEM') - if mem_drv is None: - return 'fail' + assert mem_drv is not None drv = gdal.GetDriverByName('LCP') - if drv is None: - return 'fail' + assert drv is not None src_ds = mem_drv.Create('/vsimem/', 10, 10, 10, gdal.GDT_Int16) - if src_ds is None: - return 'fail' + assert src_ds is not None retval = 'success' for option in ['METERS', 'FEET']: @@ -444,17 +401,14 @@ def lcp_10(): # Test create copy and make sure all unit metadata co work -def lcp_11(): +def test_lcp_11(): mem_drv = gdal.GetDriverByName('MEM') - if mem_drv is None: - return 'fail' + assert mem_drv is not None drv = gdal.GetDriverByName('LCP') - if drv is None: - return 'fail' + assert drv is not None src_ds = mem_drv.Create('/vsimem/', 10, 10, 10, gdal.GDT_Int16) - if src_ds is None: - return 'fail' + assert src_ds is not None retval = 'success' for option in ['DEGREES', 'PERCENT']: @@ -484,17 +438,14 @@ def lcp_11(): # Test create copy and make sure all unit metadata co work -def lcp_12(): +def test_lcp_12(): mem_drv = gdal.GetDriverByName('MEM') - if mem_drv is None: - return 'fail' + assert mem_drv is not None drv = gdal.GetDriverByName('LCP') - if drv is None: - return 'fail' + assert drv is not None src_ds = mem_drv.Create('/vsimem/', 10, 10, 10, gdal.GDT_Int16) - if src_ds is None: - return 'fail' + assert src_ds is not None retval = 'success' for option in ['GRASS_CATEGORIES', 'AZIMUTH_DEGREES', 'GRASS_DEGREES']: @@ -523,17 +474,14 @@ def lcp_12(): # Test create copy and make sure all unit metadata co work -def lcp_13(): +def test_lcp_13(): mem_drv = gdal.GetDriverByName('MEM') - if mem_drv is None: - return 'fail' + assert mem_drv is not None drv = gdal.GetDriverByName('LCP') - if drv is None: - return 'fail' + assert drv is not None src_ds = mem_drv.Create('/vsimem/', 10, 10, 10, gdal.GDT_Int16) - if src_ds is None: - return 'fail' + assert src_ds is not None retval = 'success' for option in ['PERCENT', 'CATEGORIES']: @@ -563,17 +511,14 @@ def lcp_13(): # Test create copy and make sure all unit metadata co work -def lcp_14(): +def test_lcp_14(): mem_drv = gdal.GetDriverByName('MEM') - if mem_drv is None: - return 'fail' + assert mem_drv is not None drv = gdal.GetDriverByName('LCP') - if drv is None: - return 'fail' + assert drv is not None src_ds = mem_drv.Create('/vsimem/', 10, 10, 10, gdal.GDT_Int16) - if src_ds is None: - return 'fail' + assert src_ds is not None retval = 'success' for option in ['METERS', 'FEET', 'METERS_X_10', 'FEET_X_10']: @@ -603,17 +548,14 @@ def lcp_14(): # Test create copy and make sure all unit metadata co work -def lcp_15(): +def test_lcp_15(): mem_drv = gdal.GetDriverByName('MEM') - if mem_drv is None: - return 'fail' + assert mem_drv is not None drv = gdal.GetDriverByName('LCP') - if drv is None: - return 'fail' + assert drv is not None src_ds = mem_drv.Create('/vsimem/', 10, 10, 10, gdal.GDT_Int16) - if src_ds is None: - return 'fail' + assert src_ds is not None retval = 'success' for option in ['METERS', 'FEET', 'METERS_X_10', 'FEET_X_10']: @@ -643,17 +585,14 @@ def lcp_15(): # Test create copy and make sure all unit metadata co work -def lcp_16(): +def test_lcp_16(): mem_drv = gdal.GetDriverByName('MEM') - if mem_drv is None: - return 'fail' + assert mem_drv is not None drv = gdal.GetDriverByName('LCP') - if drv is None: - return 'fail' + assert drv is not None src_ds = mem_drv.Create('/vsimem/', 10, 10, 10, gdal.GDT_Int16) - if src_ds is None: - return 'fail' + assert src_ds is not None retval = 'success' answers = ['kg/m^3', 'lb/ft^3', 'kg/m^3 x 100', 'lb/ft^3 x 1000', @@ -689,17 +628,14 @@ def lcp_16(): # documentation. Docs say mg/ha * 10 and tn/ac * 10, metadata is not * 10. -def lcp_17(): +def test_lcp_17(): mem_drv = gdal.GetDriverByName('MEM') - if mem_drv is None: - return 'fail' + assert mem_drv is not None drv = gdal.GetDriverByName('LCP') - if drv is None: - return 'fail' + assert drv is not None src_ds = mem_drv.Create('/vsimem/', 10, 10, 10, gdal.GDT_Int16) - if src_ds is None: - return 'fail' + assert src_ds is not None retval = 'success' answers = ['mg/ha', 't/ac x 10'] @@ -730,17 +666,14 @@ def lcp_17(): # Test create copy and make sure creation options work. -def lcp_18(): +def test_lcp_18(): mem_drv = gdal.GetDriverByName('MEM') - if mem_drv is None: - return 'fail' + assert mem_drv is not None drv = gdal.GetDriverByName('LCP') - if drv is None: - return 'fail' + assert drv is not None src_ds = mem_drv.Create('/vsimem/', 10, 10, 10, gdal.GDT_Int16) - if src_ds is None: - return 'fail' + assert src_ds is not None retval = 'success' co = ['LATITUDE=45', 'LINEAR_UNIT=METER'] @@ -764,17 +697,14 @@ def lcp_18(): # Test create copy and make sure creation options work. -def lcp_19(): +def test_lcp_19(): mem_drv = gdal.GetDriverByName('MEM') - if mem_drv is None: - return 'fail' + assert mem_drv is not None drv = gdal.GetDriverByName('LCP') - if drv is None: - return 'fail' + assert drv is not None src_ds = mem_drv.Create('/vsimem/', 10, 10, 10, gdal.GDT_Int16) - if src_ds is None: - return 'fail' + assert src_ds is not None retval = 'success' co = ['LATITUDE=0', 'LINEAR_UNIT=FOOT'] @@ -799,17 +729,14 @@ def lcp_19(): # Test create copy and make sure DESCRIPTION co works -def lcp_20(): +def test_lcp_20(): mem_drv = gdal.GetDriverByName('MEM') - if mem_drv is None: - return 'fail' + assert mem_drv is not None drv = gdal.GetDriverByName('LCP') - if drv is None: - return 'fail' + assert drv is not None src_ds = mem_drv.Create('/vsimem/', 10, 10, 10, gdal.GDT_Int16) - if src_ds is None: - return 'fail' + assert src_ds is not None retval = 'success' desc = 'test description' @@ -834,21 +761,18 @@ def lcp_20(): # Test create copy and make data is copied over via checksums -def lcp_21(): +def test_lcp_21(): try: import random import struct except ImportError: - return 'skip' + pytest.skip() mem_drv = gdal.GetDriverByName('MEM') - if mem_drv is None: - return 'fail' + assert mem_drv is not None drv = gdal.GetDriverByName('LCP') - if drv is None: - return 'fail' + assert drv is not None src_ds = mem_drv.Create('/vsimem/', 3, 3, 10, gdal.GDT_Int16) - if src_ds is None: - return 'fail' + assert src_ds is not None for i in range(10): data = [random.randint(0, 100) for i in range(9)] @@ -878,22 +802,19 @@ def lcp_21(): # Test create copy and make data is copied over via numpy comparison. -def lcp_22(): +def test_lcp_22(): try: import random import struct import numpy except ImportError: - return 'skip' + pytest.skip() mem_drv = gdal.GetDriverByName('MEM') - if mem_drv is None: - return 'fail' + assert mem_drv is not None drv = gdal.GetDriverByName('LCP') - if drv is None: - return 'fail' + assert drv is not None src_ds = mem_drv.Create('/vsimem/', 3, 3, 10, gdal.GDT_Int16) - if src_ds is None: - return 'fail' + assert src_ds is not None for i in range(10): data = [random.randint(0, 100) for i in range(9)] @@ -902,8 +823,7 @@ def lcp_22(): retval = 'success' co = ['LATITUDE=0', 'LINEAR_UNIT=METER'] lcp_ds = drv.CreateCopy('tmp/lcp_22.lcp', src_ds, False, co) - if lcp_ds is None: - return 'fail' + assert lcp_ds is not None retval = 'success' for i in range(10): src_data = src_ds.GetRasterBand(i + 1).ReadAsArray() @@ -925,17 +845,14 @@ def lcp_22(): ############################################################################### # Test create copy and make sure invalid creation options are caught. -def lcp_23(): +def test_lcp_23(): mem_drv = gdal.GetDriverByName('MEM') - if mem_drv is None: - return 'fail' + assert mem_drv is not None drv = gdal.GetDriverByName('LCP') - if drv is None: - return 'fail' + assert drv is not None src_ds = mem_drv.Create('/vsimem/', 10, 10, 10, gdal.GDT_Int16) - if src_ds is None: - return 'fail' + assert src_ds is not None retval = 'success' bad = 'NOT_A_REAL_OPTION' @@ -960,35 +877,4 @@ def lcp_23(): return retval -gdaltest_list = [ - lcp_1, - lcp_2, - lcp_3, - lcp_4, - lcp_5, - lcp_6, - lcp_7, - lcp_8, - lcp_9, - lcp_10, - lcp_11, - lcp_12, - lcp_13, - lcp_14, - lcp_15, - lcp_16, - lcp_17, - lcp_18, - lcp_19, - lcp_20, - lcp_21, - lcp_22, - lcp_23] - -if __name__ == '__main__': - - gdaltest.setup_run('lcp') - - gdaltest.run_tests(gdaltest_list) - - sys.exit(gdaltest.summarize()) + diff --git a/autotest/gdrivers/leveller.py b/autotest/gdrivers/leveller.py index 215e9b90b2bf..bc589655218a 100755 --- a/autotest/gdrivers/leveller.py +++ b/autotest/gdrivers/leveller.py @@ -28,9 +28,7 @@ # DEALINGS IN THE SOFTWARE. ############################################################################### -import sys -sys.path.append('../pymod') import gdaltest @@ -38,20 +36,11 @@ # Perform simple read test. -def leveller_1(): +def test_leveller_1(): tst = gdaltest.GDALTest('Leveller', 'ter6test.ter', 1, 33441) return tst.testOpen() -gdaltest_list = [ - leveller_1] -if __name__ == '__main__': - - gdaltest.setup_run('leveller') - - gdaltest.run_tests(gdaltest_list) - - sys.exit(gdaltest.summarize()) diff --git a/autotest/gdrivers/loslas.py b/autotest/gdrivers/loslas.py index f0e7d19e5dea..33dcbdf466db 100755 --- a/autotest/gdrivers/loslas.py +++ b/autotest/gdrivers/loslas.py @@ -29,24 +29,23 @@ ############################################################################### import os -import sys -sys.path.append('../pymod') import gdaltest +import pytest ############################################################################### -def loslas_online_1(): +def test_loslas_online_1(): if not gdaltest.download_file('http://www.ngs.noaa.gov/PC_PROD/NADCON/NADCON.zip', 'NADCON.zip'): - return 'skip' + pytest.skip() try: os.stat('tmp/cache/NADCON.zip') except OSError: - return 'skip' + pytest.skip() try: gdaltest.unzip('tmp/cache/NADCON', 'tmp/cache/NADCON.zip') @@ -54,7 +53,7 @@ def loslas_online_1(): gdaltest.unzip('tmp/cache/NADCON', 'tmp/cache/NADCON/nadcon.jar') os.stat('tmp/cache/NADCON/grids/wyhpgn.los') except OSError: - return 'skip' + pytest.skip() tst = gdaltest.GDALTest('LOSLAS', 'tmp/cache/NADCON/grids/wyhpgn.los', 1, 0, filename_absolute=1) gt = (-111.625, 0.25, 0.0, 45.625, 0.0, -0.25) @@ -62,15 +61,5 @@ def loslas_online_1(): return tst.testOpen(check_gt=gt, check_stat=stats, check_prj='WGS84') -gdaltest_list = [ - loslas_online_1, -] -if __name__ == '__main__': - - gdaltest.setup_run('LOSLAS') - - gdaltest.run_tests(gdaltest_list) - - sys.exit(gdaltest.summarize()) diff --git a/autotest/gdrivers/mbtiles.py b/autotest/gdrivers/mbtiles.py index 52560bc635d0..4af598b0b7a4 100755 --- a/autotest/gdrivers/mbtiles.py +++ b/autotest/gdrivers/mbtiles.py @@ -33,57 +33,49 @@ from osgeo import gdal from osgeo import ogr -sys.path.append('../pymod') import gdaltest import webserver +import pytest ############################################################################### # Get the mbtiles driver -def mbtiles_1(): +def test_mbtiles_1(): gdaltest.mbtiles_drv = gdal.GetDriverByName('MBTiles') - return 'success' - ############################################################################### # Basic test -def mbtiles_2(): +def test_mbtiles_2(): if gdaltest.mbtiles_drv is None: - return 'skip' + pytest.skip() if gdal.GetDriverByName('JPEG') is None: - return 'skip' + pytest.skip() ds = gdal.OpenEx('data/world_l1.mbtiles', open_options=['USE_BOUNDS=NO']) - if ds is None: - return 'fail' + assert ds is not None - if ds.RasterCount != 4: - gdaltest.post_reason('expected 3 bands') - return 'fail' + assert ds.RasterCount == 4, 'expected 3 bands' - if ds.GetRasterBand(1).GetOverviewCount() != 1: - gdaltest.post_reason('did not get expected overview count') - return 'fail' + assert ds.GetRasterBand(1).GetOverviewCount() == 1, \ + 'did not get expected overview count' expected_cs_tab = [6324, 19386, 45258] expected_cs_tab_jpeg8 = [6016, 13996, 45168] expected_cs_tab_jpeg9b = [6016, 14034, 45168] for i in range(3): cs = ds.GetRasterBand(i + 1).Checksum() - if ds.GetRasterBand(i + 1).GetColorInterpretation() != gdal.GCI_RedBand + i: - gdaltest.post_reason('bad color interpretation') - return 'fail' + assert ds.GetRasterBand(i + 1).GetColorInterpretation() == gdal.GCI_RedBand + i, \ + 'bad color interpretation' expected_cs = expected_cs_tab[i] - if cs != expected_cs and cs != expected_cs_tab_jpeg8[i] and cs != expected_cs_tab_jpeg9b[i]: - gdaltest.post_reason('for band %d, cs = %d, different from expected_cs = %d' % (i + 1, cs, expected_cs)) - return 'fail' + assert cs == expected_cs or cs == expected_cs_tab_jpeg8[i] or cs == expected_cs_tab_jpeg9b[i], \ + ('for band %d, cs = %d, different from expected_cs = %d' % (i + 1, cs, expected_cs)) expected_cs_tab = [16642, 15772, 10029] expected_cs_tab_jpeg8 = [16621, 14725, 8988] @@ -91,312 +83,248 @@ def mbtiles_2(): for i in range(3): cs = ds.GetRasterBand(i + 1).GetOverview(0).Checksum() expected_cs = expected_cs_tab[i] - if cs != expected_cs and cs != expected_cs_tab_jpeg8[i] and cs != expected_cs_tab_jpeg9b[i]: - gdaltest.post_reason('for overview of band %d, cs = %d, different from expected_cs = %d' % (i + 1, cs, expected_cs)) - return 'fail' + assert cs == expected_cs or cs == expected_cs_tab_jpeg8[i] or cs == expected_cs_tab_jpeg9b[i], \ + ('for overview of band %d, cs = %d, different from expected_cs = %d' % (i + 1, cs, expected_cs)) - if ds.GetProjectionRef().find('3857') == -1: - gdaltest.post_reason('projection_ref = %s' % ds.GetProjectionRef()) - return 'fail' + assert ds.GetProjectionRef().find('3857') != -1, \ + ('projection_ref = %s' % ds.GetProjectionRef()) gt = ds.GetGeoTransform() expected_gt = (-20037508.342789244, 78271.516964020484, 0.0, 20037508.342789244, 0.0, -78271.516964020484) for i in range(6): - if abs(gt[i] - expected_gt[i]) > 1e-15: - gdaltest.post_reason('bad gt') - print(gt) - print(expected_gt) - return 'fail' + assert abs(gt[i] - expected_gt[i]) <= 1e-15, 'bad gt' md = ds.GetMetadata() - if md['bounds'] != '-180.0,-85,180,85': - gdaltest.post_reason('bad metadata') - return 'fail' + assert md['bounds'] == '-180.0,-85,180,85', 'bad metadata' ds = None - return 'success' - ############################################################################### # Open a /vsicurl/ DB -def mbtiles_3(): +def test_mbtiles_3(): if gdaltest.mbtiles_drv is None: - return 'skip' + pytest.skip() if gdal.GetDriverByName('HTTP') is None: - return 'skip' + pytest.skip() if sys.platform == 'darwin' and gdal.GetConfigOption('TRAVIS', None) is not None: - print("Hangs on MacOSX Travis sometimes. Not sure why.") - return 'skip' + pytest.skip("Hangs on MacOSX Travis sometimes. Not sure why.") # Check that we have SQLite VFS support gdal.PushErrorHandler('CPLQuietErrorHandler') ds = ogr.GetDriverByName('SQLite').CreateDataSource('/vsimem/mbtiles_3.db') gdal.PopErrorHandler() if ds is None: - return 'skip' + pytest.skip() ds = None gdal.Unlink('/vsimem/mbtiles_3.db') ds = gdal.Open('/vsicurl/http://a.tiles.mapbox.com/v3/mapbox.geography-class.mbtiles') if ds is None: # Just skip. The service isn't perfectly reliable sometimes - return 'skip' + pytest.skip() # long=2,lat=49 in WGS 84 --> x=222638,y=6274861 in Google Mercator locationInfo = ds.GetRasterBand(1).GetMetadataItem('GeoPixel_222638_6274861', 'LocationInfo') if locationInfo is None or locationInfo.find("France") == -1: - gdaltest.post_reason('did not get expected LocationInfo') print(locationInfo) if gdaltest.skip_on_travis(): - return 'skip' - return 'fail' + pytest.skip() + pytest.fail('did not get expected LocationInfo') locationInfo2 = ds.GetRasterBand(1).GetOverview(5).GetMetadataItem('GeoPixel_222638_6274861', 'LocationInfo') if locationInfo2 != locationInfo: - gdaltest.post_reason('did not get expected LocationInfo on overview') print(locationInfo2) if gdaltest.skip_on_travis(): - return 'skip' - return 'fail' - - return 'success' + pytest.skip() + pytest.fail('did not get expected LocationInfo on overview') + ############################################################################### # -def mbtiles_start_webserver(): +def test_mbtiles_start_webserver(): if gdaltest.mbtiles_drv is None: - return 'skip' + pytest.skip() if gdal.GetDriverByName('HTTP') is None: - 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 mbtiles_http_jpeg_three_bands(): +def test_mbtiles_http_jpeg_three_bands(): if gdaltest.mbtiles_drv is None: - return 'skip' + pytest.skip() if gdal.GetDriverByName('HTTP') is None: - return 'skip' + pytest.skip() if gdal.GetDriverByName('JPEG') is None: - return 'skip' + pytest.skip() if gdaltest.webserver_port == 0: - return 'skip' + pytest.skip() handler = webserver.FileHandler( {'/world_l1.mbtiles': open('data/world_l1.mbtiles', 'rb').read()}) with webserver.install_http_handler(handler): ds = gdal.Open('/vsicurl/http://localhost:%d/world_l1.mbtiles' % gdaltest.webserver_port) - if ds is None: - return 'fail' - - return 'success' + assert ds is not None ############################################################################### # -def mbtiles_http_jpeg_single_band(): +def test_mbtiles_http_jpeg_single_band(): if gdaltest.mbtiles_drv is None: - return 'skip' + pytest.skip() if gdal.GetDriverByName('HTTP') is None: - return 'skip' + pytest.skip() if gdal.GetDriverByName('JPEG') is None: - return 'skip' + pytest.skip() if gdaltest.webserver_port == 0: - return 'skip' + pytest.skip() handler = webserver.FileHandler( {'/byte_jpeg.mbtiles': open('data/byte_jpeg.mbtiles', 'rb').read()}) with webserver.install_http_handler(handler): ds = gdal.Open('/vsicurl/http://localhost:%d/byte_jpeg.mbtiles' % gdaltest.webserver_port) - if ds is None: - return 'fail' - - return 'success' + assert ds is not None ############################################################################### # -def mbtiles_http_png(): +def test_mbtiles_http_png(): if gdaltest.mbtiles_drv is None: - return 'skip' + pytest.skip() if gdal.GetDriverByName('HTTP') is None: - return 'skip' + pytest.skip() if gdal.GetDriverByName('PNG') is None: - return 'skip' + pytest.skip() if gdaltest.webserver_port == 0: - return 'skip' + pytest.skip() handler = webserver.FileHandler( {'/byte.mbtiles': open('data/byte.mbtiles', 'rb').read()}) with webserver.install_http_handler(handler): ds = gdal.Open('/vsicurl/http://localhost:%d/byte.mbtiles' % gdaltest.webserver_port) - if ds is None: - return 'fail' - - return 'success' + assert ds is not None ############################################################################### # -def mbtiles_stop_webserver(): +def test_mbtiles_stop_webserver(): if gdaltest.mbtiles_drv is None: - return 'skip' + pytest.skip() if gdal.GetDriverByName('HTTP') is None: - return 'skip' + pytest.skip() if gdaltest.webserver_port != 0: webserver.server_stop(gdaltest.webserver_process, gdaltest.webserver_port) - return 'success' - + ############################################################################### # Basic test without any option -def mbtiles_4(): +def test_mbtiles_4(): if gdaltest.mbtiles_drv is None: - return 'skip' + pytest.skip() if gdal.GetDriverByName('JPEG') is None: - return 'skip' + pytest.skip() ds = gdal.Open('data/world_l1.mbtiles') - if ds is None: - return 'fail' + assert ds is not None - if ds.RasterCount != 4: - gdaltest.post_reason('expected 4 bands') - return 'fail' + assert ds.RasterCount == 4, 'expected 4 bands' - if ds.GetRasterBand(1).GetOverviewCount() != 1: - gdaltest.post_reason('did not get expected overview count') - return 'fail' + assert ds.GetRasterBand(1).GetOverviewCount() == 1, \ + 'did not get expected overview count' - if ds.RasterXSize != 512 or ds.RasterYSize != 510: - gdaltest.post_reason('bad dimensions') - print(ds.RasterXSize) - print(ds.RasterYSize) - return 'fail' + assert ds.RasterXSize == 512 and ds.RasterYSize == 510, 'bad dimensions' gt = ds.GetGeoTransform() expected_gt = (-20037508.342789244, 78271.516964020484, 0.0, 19971868.880408563, 0.0, -78271.516964020484) for i in range(6): - if abs(gt[i] - expected_gt[i]) > 1e-15: - gdaltest.post_reason('bad gt') - print(gt) - print(expected_gt) - return 'fail' + assert abs(gt[i] - expected_gt[i]) <= 1e-15, 'bad gt' ds = None - return 'success' - ############################################################################### # Test write support of a single band dataset -def mbtiles_5(): +def test_mbtiles_5(): if gdaltest.mbtiles_drv is None: - return 'skip' + pytest.skip() if gdal.GetDriverByName('PNG') is None: - return 'skip' + pytest.skip() src_ds = gdal.Open('data/byte.tif') gdaltest.mbtiles_drv.CreateCopy('/vsimem/mbtiles_5.mbtiles', src_ds) src_ds = None ds = gdal.OpenEx('/vsimem/mbtiles_5.mbtiles', open_options=['BAND_COUNT=2']) - if ds.RasterXSize != 19 or ds.RasterYSize != 19: - gdaltest.post_reason('fail') - print(ds.RasterXSize) - print(ds.RasterYSize) - return 'fail' - if ds.RasterCount != 2: - gdaltest.post_reason('fail') - print(ds.RasterCount) - return 'fail' + assert ds.RasterXSize == 19 and ds.RasterYSize == 19 + assert ds.RasterCount == 2 got_gt = ds.GetGeoTransform() expected_gt = (-13095853.550435878, 76.437028285176254, 0.0, 4015708.8887064462, 0.0, -76.437028285176254) for i in range(6): - if abs(expected_gt[i] - got_gt[i]) > 1e-6: - gdaltest.post_reason('fail') - print(got_gt) - print(expected_gt) - return 'fail' + assert abs(expected_gt[i] - got_gt[i]) <= 1e-6 got_cs = ds.GetRasterBand(1).Checksum() - if got_cs != 4118: - gdaltest.post_reason('fail') - print(got_cs) - return 'fail' + assert got_cs == 4118 got_cs = ds.GetRasterBand(2).Checksum() - if got_cs != 4406: - gdaltest.post_reason('fail') - print(got_cs) - return 'fail' + assert got_cs == 4406 got_md = ds.GetMetadata() expected_md = {'ZOOM_LEVEL': '11', 'minzoom': '11', 'maxzoom': '11', 'name': 'mbtiles_5', 'format': 'png', 'bounds': '-117.6420540294745,33.89160566594387,-117.6290077648261,33.90243460427036', 'version': '1.1', 'type': 'overlay', 'description': 'mbtiles_5'} - if set(got_md.keys()) != set(expected_md.keys()): - gdaltest.post_reason('fail') - print(got_md) - return 'fail' + assert set(got_md.keys()) == set(expected_md.keys()) for key in got_md: - if key != 'bounds' and got_md[key] != expected_md[key]: - gdaltest.post_reason('fail') - print(got_md) - return 'fail' + assert key == 'bounds' or got_md[key] == expected_md[key] ds = None gdal.Unlink('/vsimem/mbtiles_5.mbtiles') - return 'success' - ############################################################################### # Test write support with options -def mbtiles_6(): +def test_mbtiles_6(): if gdaltest.mbtiles_drv is None: - return 'skip' + pytest.skip() if gdal.GetDriverByName('JPEG') is None: - return 'skip' + pytest.skip() # Test options src_ds = gdal.Open('data/byte.tif') @@ -413,33 +341,25 @@ def mbtiles_6(): ds = gdal.Open('tmp/mbtiles_6.mbtiles') got_cs = ds.GetRasterBand(1).Checksum() - if got_cs == 0: - gdaltest.post_reason('fail') - print(got_cs) - return 'fail' + assert got_cs != 0 got_md = ds.GetMetadata() expected_md = {'ZOOM_LEVEL': '11', 'minzoom': '11', 'maxzoom': '11', 'format': 'jpg', 'version': 'version', 'type': 'baselayer', 'name': 'name', 'description': 'description'} - if got_md != expected_md: - gdaltest.post_reason('fail') - print(got_md) - return 'fail' + assert got_md == expected_md ds = None gdal.Unlink('tmp/mbtiles_6.mbtiles') - return 'success' - ############################################################################### # Test building overview -def mbtiles_7(): +def test_mbtiles_7(): if gdaltest.mbtiles_drv is None: - return 'skip' + pytest.skip() if gdal.GetDriverByName('PNG') is None: - return 'skip' + pytest.skip() src_ds = gdal.Open('data/small_world.tif') data = src_ds.ReadRaster() @@ -465,20 +385,11 @@ def mbtiles_7(): ds = None ds = gdal.Open('/vsimem/mbtiles_7.mbtiles') - if ds.GetRasterBand(1).GetOverviewCount() != 1: - gdaltest.post_reason('fail') - print(ds.GetRasterBand(1).GetOverviewCount()) - return 'fail' + assert ds.GetRasterBand(1).GetOverviewCount() == 1 expected_ovr_cs = [21179, 22577, 11996, 17849] got_ovr_cs = [ds.GetRasterBand(i + 1).GetOverview(0).Checksum() for i in range(ds.RasterCount)] - if expected_ovr_cs != got_ovr_cs: - gdaltest.post_reason('fail') - print(got_ovr_cs) - return 'fail' - if ds.GetMetadataItem('minzoom') != '0': - gdaltest.post_reason('fail') - print(ds.GetMetadata()) - return 'fail' + assert expected_ovr_cs == got_ovr_cs + assert ds.GetMetadataItem('minzoom') == '0', ds.GetMetadata() ds = None ds = gdal.Open('/vsimem/mbtiles_7.mbtiles', gdal.GA_Update) @@ -486,31 +397,23 @@ def mbtiles_7(): ds = None ds = gdal.Open('/vsimem/mbtiles_7.mbtiles') - if ds.GetRasterBand(1).GetOverviewCount() != 0: - gdaltest.post_reason('fail') - print(ds.GetRasterBand(1).GetOverviewCount()) - return 'fail' - if ds.GetMetadataItem('minzoom') != '1': - gdaltest.post_reason('fail') - print(ds.GetMetadata()) - return 'fail' + assert ds.GetRasterBand(1).GetOverviewCount() == 0 + assert ds.GetMetadataItem('minzoom') == '1', ds.GetMetadata() ds = None gdal.Unlink('/vsimem/mbtiles_7.mbtiles') - return 'success' - ############################################################################### # Single band with 24 bit color table, PNG -def mbtiles_8(): +def test_mbtiles_8(): if gdaltest.mbtiles_drv is None: - return 'skip' + pytest.skip() if gdal.GetDriverByName('PNG') is None: - return 'skip' + pytest.skip() src_ds = gdal.Open('data/small_world_pct.tif') out_ds = gdaltest.mbtiles_drv.CreateCopy('/vsimem/mbtiles_8.mbtiles', src_ds, options=['RESAMPLING=NEAREST']) @@ -520,18 +423,10 @@ def mbtiles_8(): expected_cs = [993, 50461, 64354] out_ds = gdal.Open('/vsimem/mbtiles_8.mbtiles') got_cs = [out_ds.GetRasterBand(i + 1).Checksum() for i in range(3)] - if got_cs != expected_cs: - gdaltest.post_reason('fail') - print('Got %s, expected %s' % (str(got_cs), str(expected_cs))) - return 'fail' + assert got_cs == expected_cs got_ct = out_ds.GetRasterBand(1).GetColorTable() - if got_ct is not None: - gdaltest.post_reason('fail') - return 'fail' - if out_ds.GetRasterBand(1).GetBlockSize() != [256, 256]: - gdaltest.post_reason('fail') - print(out_ds.GetRasterBand(1).GetBlockSize()) - return 'fail' + assert got_ct is None + assert out_ds.GetRasterBand(1).GetBlockSize() == [256, 256] out_ds = None # 512 pixel tiles @@ -543,33 +438,25 @@ def mbtiles_8(): expected_cs = [60844, 7388, 53813] out_ds = gdal.Open('/vsimem/mbtiles_8.mbtiles') got_cs = [out_ds.GetRasterBand(i + 1).Checksum() for i in range(3)] - if got_cs != expected_cs: - gdaltest.post_reason('fail') - print('Got %s, expected %s' % (str(got_cs), str(expected_cs))) - return 'fail' + assert got_cs == expected_cs got_ct = out_ds.GetRasterBand(1).GetColorTable() - if got_ct is not None: - gdaltest.post_reason('fail') - return 'fail' - if out_ds.GetRasterBand(1).GetBlockSize() != [512, 512]: - gdaltest.post_reason('fail') - return 'fail' + assert got_ct is None + assert out_ds.GetRasterBand(1).GetBlockSize() == [512, 512] out_ds = None gdal.Unlink('/vsimem/mbtiles_8.mbtiles') - return 'success' ############################################################################### # Test we are robust to invalid bounds -def mbtiles_9(): +def test_mbtiles_9(): if gdaltest.mbtiles_drv is None: - return 'skip' + pytest.skip() if gdal.GetDriverByName('PNG') is None: - return 'skip' + pytest.skip() src_ds = gdal.Open('data/byte.tif') gdaltest.mbtiles_drv.CreateCopy('/vsimem/mbtiles_9.mbtiles', src_ds, options=['RESAMPLING=NEAREST']) @@ -580,29 +467,23 @@ def mbtiles_9(): with gdaltest.error_handler(): ds = gdal.Open('/vsimem/mbtiles_9.mbtiles') - if ds.RasterXSize != 256 or ds.RasterYSize != 256: - gdaltest.post_reason('fail') - return 'fail' - if abs(ds.GetGeoTransform()[0] - -13110479.091473430395126) > 1e-6: - gdaltest.post_reason('fail') - print(ds.GetGeoTransform()) - return 'fail' + assert ds.RasterXSize == 256 and ds.RasterYSize == 256 + assert abs(ds.GetGeoTransform()[0] - -13110479.091473430395126) <= 1e-6 ds = None gdal.Unlink('/vsimem/mbtiles_9.mbtiles') - return 'success' ############################################################################### # Test compaction of temporary database -def mbtiles_10(): +def test_mbtiles_10(): if gdaltest.mbtiles_drv is None: - return 'skip' + pytest.skip() if gdal.GetDriverByName('PNG') is None: - return 'skip' + pytest.skip() old_val_GPKG_FORCE_TEMPDB_COMPACTION = gdal.GetConfigOption('GPKG_FORCE_TEMPDB_COMPACTION') gdal.SetConfigOption('GPKG_FORCE_TEMPDB_COMPACTION', 'YES') @@ -612,64 +493,51 @@ def mbtiles_10(): ds = gdal.Open('/vsimem/mbtiles_10.mbtiles') cs = ds.GetRasterBand(1).Checksum() - if cs != 29925: - gdaltest.post_reason('fail') - print(cs) - return 'fail' + assert cs == 29925 ds = None gdal.Unlink('/vsimem/mbtiles_10.mbtiles') - return 'success' ############################################################################### # Test opening a .mbtiles.sql file -def mbtiles_11(): +def test_mbtiles_11(): if gdaltest.mbtiles_drv is None: - return 'skip' + pytest.skip() if gdaltest.mbtiles_drv.GetMetadataItem("ENABLE_SQL_SQLITE_FORMAT") != 'YES': - return 'skip' + pytest.skip() if gdal.GetDriverByName('PNG') is None: - return 'skip' + pytest.skip() ds = gdal.Open('data/byte.mbtiles.sql') - if ds.GetRasterBand(1).Checksum() != 4118: - gdaltest.post_reason('validation failed') - return 'fail' - - return 'success' + assert ds.GetRasterBand(1).Checksum() == 4118, 'validation failed' ############################################################################### -def mbtiles_raster_open_in_vector_mode(): +def test_mbtiles_raster_open_in_vector_mode(): if gdaltest.mbtiles_drv is None: - return 'skip' + pytest.skip() ds = ogr.Open('data/byte.mbtiles') - if ds is not None: - return 'fail' - - return 'success' + assert ds is None ############################################################################### -def mbtiles_create(): +def test_mbtiles_create(): if gdaltest.mbtiles_drv is None: - return 'skip' + pytest.skip() filename = '/vsimem/mbtiles_create.mbtiles' gdaltest.mbtiles_drv.Create(filename, 1, 1, 1) with gdaltest.error_handler(): - if gdal.Open(filename) is not None: - gdaltest.post_reason('fail') - return 'fail' + assert gdal.Open(filename) is None # Nominal case gdal.Unlink(filename) @@ -681,24 +549,18 @@ def mbtiles_create(): # Cannot modify geotransform once set" with gdaltest.error_handler(): ret = ds.SetGeoTransform(src_ds.GetGeoTransform()) - if ret == 0: - gdaltest.post_reason('fail') - return 'fail' + assert ret != 0 ds = None ds = gdal.Open('data/byte.mbtiles') # SetGeoTransform() not supported on read-only dataset" with gdaltest.error_handler(): ret = ds.SetGeoTransform(src_ds.GetGeoTransform()) - if ret == 0: - gdaltest.post_reason('fail') - return 'fail' + assert ret != 0 # SetProjection() not supported on read-only dataset with gdaltest.error_handler(): ret = ds.SetProjection(src_ds.GetProjectionRef()) - if ret == 0: - gdaltest.post_reason('fail') - return 'fail' + assert ret != 0 ds = None gdal.Unlink(filename) @@ -706,9 +568,7 @@ def mbtiles_create(): # Only EPSG:3857 supported on MBTiles dataset with gdaltest.error_handler(): ret = ds.SetProjection('LOCAL_CS["foo"]') - if ret == 0: - gdaltest.post_reason('fail') - return 'fail' + assert ret != 0 ds = None gdal.Unlink(filename) @@ -716,9 +576,7 @@ def mbtiles_create(): # Only north-up non rotated geotransform supported with gdaltest.error_handler(): ret = ds.SetGeoTransform([0, 1, 0, 0, 0, 1]) - if ret == 0: - gdaltest.post_reason('fail') - return 'fail' + assert ret != 0 ds = None gdal.Unlink(filename) @@ -726,54 +584,16 @@ def mbtiles_create(): # Could not find an appropriate zoom level that matches raster pixel size with gdaltest.error_handler(): ret = ds.SetGeoTransform([0, 1, 0, 0, 0, -1]) - if ret == 0: - gdaltest.post_reason('fail') - return 'fail' + assert ret != 0 ds = None gdal.Unlink(filename) - return 'success' - ############################################################################### # Cleanup -def mbtiles_cleanup(): +def test_mbtiles_cleanup(): if gdaltest.mbtiles_drv is None: - return 'skip' - - return 'success' - - -gdaltest_list = [ - mbtiles_1, - mbtiles_2, - mbtiles_3, - mbtiles_start_webserver, - mbtiles_http_jpeg_three_bands, - mbtiles_http_jpeg_single_band, - mbtiles_http_png, - mbtiles_stop_webserver, - mbtiles_4, - mbtiles_5, - mbtiles_6, - mbtiles_7, - mbtiles_8, - mbtiles_9, - mbtiles_10, - mbtiles_11, - mbtiles_raster_open_in_vector_mode, - mbtiles_create, - mbtiles_cleanup] - -# gdaltest_list = [ mbtiles_1, mbtiles_create ] - -if __name__ == '__main__': - - gdaltest.setup_run('mbtiles') - - gdaltest.run_tests(gdaltest_list) - - sys.exit(gdaltest.summarize()) + pytest.skip() diff --git a/autotest/gdrivers/mem.py b/autotest/gdrivers/mem.py index 724c874e9ec9..a22eaa2f4564 100755 --- a/autotest/gdrivers/mem.py +++ b/autotest/gdrivers/mem.py @@ -29,19 +29,18 @@ # DEALINGS IN THE SOFTWARE. ############################################################################### -import sys import array from osgeo import gdal -sys.path.append('../pymod') import gdaltest +import pytest ############################################################################### # Create a MEM dataset, and set some data, then test it. -def mem_1(): +def test_mem_1(): ####################################################### # Setup dataset @@ -49,13 +48,9 @@ def mem_1(): gdaltest.mem_ds = drv.Create('mem_1.mem', 50, 3) ds = gdaltest.mem_ds - if ds.GetProjection() != '': - gdaltest.post_reason('projection wrong') - return 'fail' + assert ds.GetProjection() == '', 'projection wrong' - if ds.GetGeoTransform(can_return_null=True) is not None: - gdaltest.post_reason('geotransform wrong') - return 'fail' + assert ds.GetGeoTransform(can_return_null=True) is None, 'geotransform wrong' raw_data = array.array('f', list(range(150))).tostring() ds.WriteRaster(0, 0, 50, 3, raw_data, @@ -83,63 +78,40 @@ def mem_1(): ####################################################### # Verify dataset. - if band.GetNoDataValue() != -1.0: - gdaltest.post_reason('no data is wrong') - return 'fail' + assert band.GetNoDataValue() == -1.0, 'no data is wrong' - if ds.GetProjection() != wkt: - gdaltest.post_reason('projection wrong') - return 'fail' + assert ds.GetProjection() == wkt, 'projection wrong' - if ds.GetGeoTransform() != gt: - gdaltest.post_reason('geotransform wrong') - return 'fail' + assert ds.GetGeoTransform() == gt, 'geotransform wrong' - if band.Checksum() != 1531: - gdaltest.post_reason('checksum wrong') - print(band.Checksum()) - return 'fail' + assert band.Checksum() == 1531, 'checksum wrong' - if ds.GetGCPCount() != 1: - gdaltest.post_reason('GetGCPCount wrong') - return 'fail' + assert ds.GetGCPCount() == 1, 'GetGCPCount wrong' - if len(ds.GetGCPs()) != 1: - gdaltest.post_reason('GetGCPs wrong') - return 'fail' + assert len(ds.GetGCPs()) == 1, 'GetGCPs wrong' - if ds.GetGCPProjection() != wkt_gcp: - gdaltest.post_reason('GetGCPProjection wrong') - return 'fail' + assert ds.GetGCPProjection() == wkt_gcp, 'GetGCPProjection wrong' - if band.DeleteNoDataValue() != 0: - gdaltest.post_reason('wrong return code') - return 'fail' - if band.GetNoDataValue() is not None: - gdaltest.post_reason('got nodata value whereas none was expected') - return 'fail' + assert band.DeleteNoDataValue() == 0, 'wrong return code' + assert band.GetNoDataValue() is None, 'got nodata value whereas none was expected' gdaltest.mem_ds = None - return 'success' - ############################################################################### # Open an in-memory array. -def mem_2(): +def test_mem_2(): gdal.PushErrorHandler('CPLQuietErrorHandler') ds = gdal.Open('MEM:::') gdal.PopErrorHandler() - if ds is not None: - gdaltest.post_reason('opening MEM dataset should have failed.') - return 'fail' + assert ds is None, 'opening MEM dataset should have failed.' try: import ctypes except ImportError: - return 'skip' + pytest.skip() for libname in ['msvcrt', 'libc.so.6']: try: @@ -150,7 +122,7 @@ def mem_2(): break if crt is None: - return 'skip' + pytest.skip() malloc = crt.malloc malloc.argtypes = [ctypes.c_size_t] @@ -165,7 +137,7 @@ def mem_2(): height = 3 p = malloc(width * height * 4) if p is None: - return 'skip' + pytest.skip() float_p = ctypes.cast(p, ctypes.POINTER(ctypes.c_float)) # build ds name. @@ -179,51 +151,43 @@ def mem_2(): ds = gdal.Open(dsname) if ds is None: - gdaltest.post_reason('opening MEM dataset failed.') free(p) - return 'fail' + pytest.fail('opening MEM dataset failed.') chksum = ds.GetRasterBand(1).Checksum() if chksum != 750: - gdaltest.post_reason('checksum failed.') print(chksum) free(p) - return 'fail' + pytest.fail('checksum failed.') ds.GetRasterBand(1).Fill(100.0) ds.FlushCache() if float_p[0] != 100.0: print(float_p[0]) - gdaltest.post_reason('fill seems to have failed.') free(p) - return 'fail' + pytest.fail('fill seems to have failed.') ds = None free(p) - return 'success' - ############################################################################### # Test creating a MEM dataset with the "MEM:::" name -def mem_3(): +def test_mem_3(): drv = gdal.GetDriverByName('MEM') ds = drv.Create('MEM:::', 1, 1, 1) - if ds is None: - return 'fail' + assert ds is not None ds = None - return 'success' - ############################################################################### # Test creating a band interleaved multi-band MEM dataset -def mem_4(): +def test_mem_4(): drv = gdal.GetDriverByName('MEM') @@ -231,29 +195,23 @@ def mem_4(): expected_cs = [0, 0, 0] for i in range(3): cs = ds.GetRasterBand(i + 1).Checksum() - if cs != expected_cs[i]: - gdaltest.post_reason('did not get expected checksum for band %d' % (i + 1)) - print(cs) - return 'fail' + assert cs == expected_cs[i], \ + ('did not get expected checksum for band %d' % (i + 1)) ds.GetRasterBand(1).Fill(255) expected_cs = [57182, 0, 0] for i in range(3): cs = ds.GetRasterBand(i + 1).Checksum() - if cs != expected_cs[i]: - gdaltest.post_reason('did not get expected checksum for band %d after fill' % (i + 1)) - print(cs) - return 'fail' + assert cs == expected_cs[i], \ + ('did not get expected checksum for band %d after fill' % (i + 1)) ds = None - return 'success' - ############################################################################### # Test creating a pixel interleaved multi-band MEM dataset -def mem_5(): +def test_mem_5(): drv = gdal.GetDriverByName('MEM') @@ -261,77 +219,60 @@ def mem_5(): expected_cs = [0, 0, 0] for i in range(3): cs = ds.GetRasterBand(i + 1).Checksum() - if cs != expected_cs[i]: - gdaltest.post_reason('did not get expected checksum for band %d' % (i + 1)) - print(cs) - return 'fail' + assert cs == expected_cs[i], \ + ('did not get expected checksum for band %d' % (i + 1)) ds.GetRasterBand(1).Fill(255) expected_cs = [57182, 0, 0] for i in range(3): cs = ds.GetRasterBand(i + 1).Checksum() - if cs != expected_cs[i]: - gdaltest.post_reason('did not get expected checksum for band %d after fill' % (i + 1)) - print(cs) - return 'fail' + assert cs == expected_cs[i], \ + ('did not get expected checksum for band %d after fill' % (i + 1)) - if ds.GetMetadataItem('INTERLEAVE', 'IMAGE_STRUCTURE') != 'PIXEL': - gdaltest.post_reason('did not get expected INTERLEAVE value') - return 'fail' + assert ds.GetMetadataItem('INTERLEAVE', 'IMAGE_STRUCTURE') == 'PIXEL', \ + 'did not get expected INTERLEAVE value' ds = None - return 'success' - ############################################################################### # Test out-of-memory situations -def mem_6(): +def test_mem_6(): if gdal.GetConfigOption('SKIP_MEM_INTENSIVE_TEST') is not None: - return 'skip' + pytest.skip() drv = gdal.GetDriverByName('MEM') # Multiplication overflow with gdaltest.error_handler(): ds = drv.Create('', 1, 1, 0x7FFFFFFF, gdal.GDT_Float64) - if ds is not None: - gdaltest.post_reason('fail') - return 'fail' + assert ds is None ds = None # Multiplication overflow with gdaltest.error_handler(): ds = drv.Create('', 0x7FFFFFFF, 0x7FFFFFFF, 16) - if ds is not None: - gdaltest.post_reason('fail') - return 'fail' + assert ds is None ds = None # Multiplication overflow with gdaltest.error_handler(): ds = drv.Create('', 0x7FFFFFFF, 0x7FFFFFFF, 1, gdal.GDT_Float64) - if ds is not None: - gdaltest.post_reason('fail') - return 'fail' + assert ds is None ds = None # Out of memory error with gdaltest.error_handler(): ds = drv.Create('', 0x7FFFFFFF, 0x7FFFFFFF, 1, options=['INTERLEAVE=PIXEL']) - if ds is not None: - gdaltest.post_reason('fail') - return 'fail' + assert ds is None ds = None # Out of memory error with gdaltest.error_handler(): ds = drv.Create('', 0x7FFFFFFF, 0x7FFFFFFF, 1) - if ds is not None: - gdaltest.post_reason('fail') - return 'fail' + assert ds is None ds = None # 32 bit overflow on 32-bit builds, or possible out of memory error @@ -343,32 +284,25 @@ def mem_6(): ds = drv.Create('', 0x7FFFFFFF, 0x7FFFFFFF, 0) with gdaltest.error_handler(): ret = ds.AddBand(gdal.GDT_Float64) - if ret == 0: - gdaltest.post_reason('fail') - return 'fail' - - return 'success' + assert ret != 0 ############################################################################### # Test AddBand() -def mem_7(): +def test_mem_7(): drv = gdal.GetDriverByName('MEM') ds = drv.Create('MEM:::', 1, 1, 1) ds.AddBand(gdal.GDT_Byte, []) - if ds.RasterCount != 2: - return 'fail' + assert ds.RasterCount == 2 ds = None - return 'success' - ############################################################################### # Test SetDefaultHistogram() / GetDefaultHistogram() -def mem_8(): +def test_mem_8(): drv = gdal.GetDriverByName('MEM') ds = drv.Create('MEM:::', 1, 1, 1) @@ -378,17 +312,13 @@ def mem_8(): hist = ds.GetRasterBand(1).GetDefaultHistogram(force=0) ds = None - if hist != (1.0, 2.0, 2, [3000000000, 4]): - print(hist) - return 'fail' - - return 'success' + assert hist == (1.0, 2.0, 2, [3000000000, 4]) ############################################################################### # Test RasterIO() -def mem_9(): +def test_mem_9(): # Test IRasterIO(GF_Read,) src_ds = gdal.Open('data/rgbsmall.tif') @@ -399,60 +329,37 @@ def mem_9(): ref_data = src_ds.GetRasterBand(2).ReadRaster(20, 8, 4, 5) got_data = out_ds.GetRasterBand(2).ReadRaster(20, 8, 4, 5) if ref_data != got_data: - print(interleave) import struct print(struct.unpack('B' * 4 * 5, ref_data)) print(struct.unpack('B' * 4 * 5, got_data)) - gdaltest.post_reason('fail') - return 'fail' + pytest.fail(interleave) ref_data = src_ds.GetRasterBand(2).ReadRaster(20, 8, 4, 5, buf_pixel_space=3, buf_line_space=100) got_data = out_ds.GetRasterBand(2).ReadRaster(20, 8, 4, 5, buf_pixel_space=3, buf_line_space=100) - if ref_data != got_data: - print(interleave) - gdaltest.post_reason('fail') - return 'fail' + assert ref_data == got_data, interleave ref_data = src_ds.ReadRaster(20, 8, 4, 5) got_data = out_ds.ReadRaster(20, 8, 4, 5) - if ref_data != got_data: - print(interleave) - gdaltest.post_reason('fail') - return 'fail' + assert ref_data == got_data, interleave ref_data = src_ds.ReadRaster(20, 8, 4, 5, buf_pixel_space=3, buf_band_space=1) got_data = out_ds.ReadRaster(20, 8, 4, 5, buf_pixel_space=3, buf_band_space=1) - if ref_data != got_data: - print(interleave) - gdaltest.post_reason('fail') - return 'fail' + assert ref_data == got_data, interleave out_ds.WriteRaster(20, 8, 4, 5, got_data, buf_pixel_space=3, buf_band_space=1) got_data = out_ds.ReadRaster(20, 8, 4, 5, buf_pixel_space=3, buf_band_space=1) - if ref_data != got_data: - print(interleave) - gdaltest.post_reason('fail') - return 'fail' + assert ref_data == got_data, interleave ref_data = src_ds.ReadRaster(20, 8, 4, 5, buf_pixel_space=3, buf_line_space=100, buf_band_space=1) got_data = out_ds.ReadRaster(20, 8, 4, 5, buf_pixel_space=3, buf_line_space=100, buf_band_space=1) - if ref_data != got_data: - print(interleave) - gdaltest.post_reason('fail') - return 'fail' + assert ref_data == got_data, interleave ref_data = src_ds.ReadRaster(20, 20, 4, 5, buf_type=gdal.GDT_Int32, buf_pixel_space=12, buf_band_space=4) got_data = out_ds.ReadRaster(20, 20, 4, 5, buf_type=gdal.GDT_Int32, buf_pixel_space=12, buf_band_space=4) - if ref_data != got_data: - print(interleave) - gdaltest.post_reason('fail') - return 'fail' + assert ref_data == got_data, interleave out_ds.WriteRaster(20, 20, 4, 5, got_data, buf_type=gdal.GDT_Int32, buf_pixel_space=12, buf_band_space=4) got_data = out_ds.ReadRaster(20, 20, 4, 5, buf_type=gdal.GDT_Int32, buf_pixel_space=12, buf_band_space=4) - if ref_data != got_data: - print(interleave) - gdaltest.post_reason('fail') - return 'fail' + assert ref_data == got_data, interleave # Test IReadBlock ref_data = src_ds.GetRasterBand(1).ReadRaster(0, 10, src_ds.RasterXSize, 1) @@ -460,58 +367,40 @@ def mem_9(): # to make that unnecessary out_ds.FlushCache() got_data = out_ds.GetRasterBand(1).ReadBlock(0, 10) - if ref_data != got_data: - print(interleave) - gdaltest.post_reason('fail') - return 'fail' + assert ref_data == got_data, interleave # Test IRasterIO(GF_Write,) ref_data = src_ds.GetRasterBand(1).ReadRaster(2, 3, 4, 5) out_ds.GetRasterBand(1).WriteRaster(6, 7, 4, 5, ref_data) got_data = out_ds.GetRasterBand(1).ReadRaster(6, 7, 4, 5) - if ref_data != got_data: - gdaltest.post_reason('fail') - return 'fail' + assert ref_data == got_data # Test IRasterIO(GF_Write, change data type) + IWriteBlock() + IRasterIO(GF_Read, change data type) ref_data = src_ds.GetRasterBand(1).ReadRaster(10, 11, 4, 5, buf_type=gdal.GDT_Int32) out_ds.GetRasterBand(1).WriteRaster(10, 11, 4, 5, ref_data, buf_type=gdal.GDT_Int32) got_data = out_ds.GetRasterBand(1).ReadRaster(10, 11, 4, 5, buf_type=gdal.GDT_Int32) - if ref_data != got_data: - print(interleave) - gdaltest.post_reason('fail') - return 'fail' + assert ref_data == got_data, interleave ref_data = src_ds.GetRasterBand(1).ReadRaster(10, 11, 4, 5) got_data = out_ds.GetRasterBand(1).ReadRaster(10, 11, 4, 5) - if ref_data != got_data: - print(interleave) - gdaltest.post_reason('fail') - return 'fail' + assert ref_data == got_data, interleave # Test IRasterIO(GF_Write, resampling) + IWriteBlock() + IRasterIO(GF_Read, resampling) ref_data = src_ds.GetRasterBand(1).ReadRaster(10, 11, 4, 5) ref_data_zoomed = src_ds.GetRasterBand(1).ReadRaster(10, 11, 4, 5, 8, 10) out_ds.GetRasterBand(1).WriteRaster(10, 11, 8, 10, ref_data, 4, 5) got_data = out_ds.GetRasterBand(1).ReadRaster(10, 11, 8, 10) - if ref_data_zoomed != got_data: - print(interleave) - gdaltest.post_reason('fail') - return 'fail' + assert ref_data_zoomed == got_data, interleave got_data = out_ds.GetRasterBand(1).ReadRaster(10, 11, 8, 10, 4, 5) - if ref_data != got_data: - print(interleave) - gdaltest.post_reason('fail') - return 'fail' - - return 'success' + assert ref_data == got_data, interleave + ############################################################################### # Test BuildOverviews() -def mem_10(): +def test_mem_10(): # Error case: building overview on a 0 band dataset ds = gdal.GetDriverByName('MEM').Create('', 1, 1, 0) @@ -520,235 +409,137 @@ def mem_10(): # Requesting overviews when they are not ds = gdal.GetDriverByName('MEM').Create('', 1, 1) - if ds.GetRasterBand(1).GetOverviewCount() != 0: - gdaltest.post_reason('fail') - return 'fail' - if ds.GetRasterBand(1).GetOverview(-1) is not None: - gdaltest.post_reason('fail') - return 'fail' - if ds.GetRasterBand(1).GetOverview(0) is not None: - gdaltest.post_reason('fail') - return 'fail' + assert ds.GetRasterBand(1).GetOverviewCount() == 0 + assert ds.GetRasterBand(1).GetOverview(-1) is None + assert ds.GetRasterBand(1).GetOverview(0) is None # Single band case ds = gdal.GetDriverByName('MEM').CreateCopy('', gdal.Open('data/byte.tif')) for _ in range(2): ret = ds.BuildOverviews('NEAR', [2]) - if ret != 0: - gdaltest.post_reason('fail') - return 'fail' - if ds.GetRasterBand(1).GetOverviewCount() != 1: - gdaltest.post_reason('fail') - return 'fail' + assert ret == 0 + assert ds.GetRasterBand(1).GetOverviewCount() == 1 cs = ds.GetRasterBand(1).GetOverview(0).Checksum() - if cs != 1087: - gdaltest.post_reason('fail') - print(cs) - return 'fail' + assert cs == 1087 ret = ds.BuildOverviews('NEAR', [4]) - if ret != 0: - gdaltest.post_reason('fail') - return 'fail' - if ds.GetRasterBand(1).GetOverviewCount() != 2: - gdaltest.post_reason('fail') - return 'fail' + assert ret == 0 + assert ds.GetRasterBand(1).GetOverviewCount() == 2 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 ret = ds.BuildOverviews('NEAR', [2, 4]) - if ret != 0: - gdaltest.post_reason('fail') - return 'fail' - if ds.GetRasterBand(1).GetOverviewCount() != 2: - gdaltest.post_reason('fail') - return 'fail' + assert ret == 0 + assert ds.GetRasterBand(1).GetOverviewCount() == 2 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 # Test that average in one or several steps give the same result ds.GetRasterBand(1).GetOverview(0).Fill(0) ds.GetRasterBand(1).GetOverview(1).Fill(0) ret = ds.BuildOverviews('AVERAGE', [2, 4]) - if ret != 0: - gdaltest.post_reason('fail') - return 'fail' - if ds.GetRasterBand(1).GetOverviewCount() != 2: - gdaltest.post_reason('fail') - return 'fail' + assert ret == 0 + assert ds.GetRasterBand(1).GetOverviewCount() == 2 cs = ds.GetRasterBand(1).GetOverview(0).Checksum() - if cs != 1152: - gdaltest.post_reason('fail') - print(cs) - return 'fail' + assert cs == 1152 cs = ds.GetRasterBand(1).GetOverview(1).Checksum() - if cs != 240: - gdaltest.post_reason('fail') - print(cs) - return 'fail' + assert cs == 240 ds.GetRasterBand(1).GetOverview(0).Fill(0) ds.GetRasterBand(1).GetOverview(1).Fill(0) ret = ds.BuildOverviews('AVERAGE', [2]) ret = ds.BuildOverviews('AVERAGE', [4]) - if ret != 0: - gdaltest.post_reason('fail') - return 'fail' - if ds.GetRasterBand(1).GetOverviewCount() != 2: - gdaltest.post_reason('fail') - return 'fail' + assert ret == 0 + assert ds.GetRasterBand(1).GetOverviewCount() == 2 cs = ds.GetRasterBand(1).GetOverview(0).Checksum() - if cs != 1152: - gdaltest.post_reason('fail') - print(cs) - return 'fail' + assert cs == 1152 cs = ds.GetRasterBand(1).GetOverview(1).Checksum() - if cs != 240: - gdaltest.post_reason('fail') - print(cs) - return 'fail' + assert cs == 240 ds = None # Multiple band case ds = gdal.GetDriverByName('MEM').CreateCopy('', gdal.Open('data/rgbsmall.tif')) ret = ds.BuildOverviews('NEAR', [2]) - if ret != 0: - gdaltest.post_reason('fail') - return 'fail' + assert ret == 0 cs = ds.GetRasterBand(1).GetOverview(0).Checksum() - if cs != 5057: - gdaltest.post_reason('fail') - print(cs) - return 'fail' + assert cs == 5057 cs = ds.GetRasterBand(2).GetOverview(0).Checksum() - if cs != 5304: - gdaltest.post_reason('fail') - print(cs) - return 'fail' + assert cs == 5304 cs = ds.GetRasterBand(3).GetOverview(0).Checksum() - if cs != 5304: - gdaltest.post_reason('fail') - print(cs) - return 'fail' + assert cs == 5304 ds = None # Clean overviews ds = gdal.GetDriverByName('MEM').CreateCopy('', gdal.Open('data/byte.tif')) ret = ds.BuildOverviews('NEAR', [2]) - if ret != 0: - gdaltest.post_reason('fail') - return 'fail' + assert ret == 0 ret = ds.BuildOverviews('NONE', []) - if ret != 0: - gdaltest.post_reason('fail') - return 'fail' - if ds.GetRasterBand(1).GetOverviewCount() != 0: - gdaltest.post_reason('fail') - return 'fail' + assert ret == 0 + assert ds.GetRasterBand(1).GetOverviewCount() == 0 ds = None - return 'success' - ############################################################################### # Test CreateMaskBand() -def mem_11(): +def test_mem_11(): # Error case: building overview on a 0 band dataset ds = gdal.GetDriverByName('MEM').Create('', 1, 1, 0) - if ds.CreateMaskBand(gdal.GMF_PER_DATASET) == 0: - gdaltest.post_reason('fail') - return 'fail' + assert ds.CreateMaskBand(gdal.GMF_PER_DATASET) != 0 # Per dataset mask on single band dataset ds = gdal.GetDriverByName('MEM').Create('', 1, 1) - if ds.CreateMaskBand(gdal.GMF_PER_DATASET) != 0: - gdaltest.post_reason('fail') - return 'fail' - if ds.GetRasterBand(1).GetMaskFlags() != gdal.GMF_PER_DATASET: - gdaltest.post_reason('fail') - return 'fail' + assert ds.CreateMaskBand(gdal.GMF_PER_DATASET) == 0 + assert ds.GetRasterBand(1).GetMaskFlags() == gdal.GMF_PER_DATASET mask = ds.GetRasterBand(1).GetMaskBand() cs = mask.Checksum() - if cs != 0: - gdaltest.post_reason('fail') - return 'fail' + assert cs == 0 mask.Fill(255) cs = mask.Checksum() - if cs != 3: - gdaltest.post_reason('fail') - return 'fail' + assert cs == 3 # Check that the per dataset mask is shared by all bands ds = gdal.GetDriverByName('MEM').Create('', 1, 1, 2) - if ds.CreateMaskBand(gdal.GMF_PER_DATASET) != 0: - gdaltest.post_reason('fail') - return 'fail' + assert ds.CreateMaskBand(gdal.GMF_PER_DATASET) == 0 mask1 = ds.GetRasterBand(1).GetMaskBand() mask1.Fill(255) mask2 = ds.GetRasterBand(2).GetMaskBand() cs = mask2.Checksum() - if cs != 3: - gdaltest.post_reason('fail') - return 'fail' + assert cs == 3 # Same but call it on band 2 ds = gdal.GetDriverByName('MEM').Create('', 1, 1, 2) - if ds.GetRasterBand(2).CreateMaskBand(gdal.GMF_PER_DATASET) != 0: - gdaltest.post_reason('fail') - return 'fail' + assert ds.GetRasterBand(2).CreateMaskBand(gdal.GMF_PER_DATASET) == 0 mask2 = ds.GetRasterBand(2).GetMaskBand() mask2.Fill(255) mask1 = ds.GetRasterBand(1).GetMaskBand() cs = mask1.Checksum() - if cs != 3: - gdaltest.post_reason('fail') - return 'fail' + assert cs == 3 # Per band masks ds = gdal.GetDriverByName('MEM').Create('', 1, 1, 2) - if ds.GetRasterBand(1).CreateMaskBand(0) != 0: - gdaltest.post_reason('fail') - return 'fail' - if ds.GetRasterBand(2).CreateMaskBand(0) != 0: - gdaltest.post_reason('fail') - return 'fail' + assert ds.GetRasterBand(1).CreateMaskBand(0) == 0 + assert ds.GetRasterBand(2).CreateMaskBand(0) == 0 mask1 = ds.GetRasterBand(1).GetMaskBand() mask2 = ds.GetRasterBand(2).GetMaskBand() mask2.Fill(255) cs1 = mask1.Checksum() cs2 = mask2.Checksum() - if cs1 != 0 or cs2 != 3: - gdaltest.post_reason('fail') - return 'fail' - - return 'success' + assert cs1 == 0 and cs2 == 3 ############################################################################### # Test CreateMaskBand() and overviews. -def mem_12(): +def test_mem_12(): # Test on per-band mask ds = gdal.GetDriverByName('MEM').Create('', 10, 10, 2) @@ -756,17 +547,11 @@ def mem_12(): ds.GetRasterBand(1).GetMaskBand().Fill(127) ds.BuildOverviews('NEAR', [2]) cs = ds.GetRasterBand(1).GetOverview(0).GetMaskBand().Checksum() - if cs != 267: - gdaltest.post_reason('fail') - print(cs) - return 'fail' + assert cs == 267 # Default mask cs = ds.GetRasterBand(2).GetOverview(0).GetMaskBand().Checksum() - if cs != 283: - gdaltest.post_reason('fail') - print(cs) - return 'fail' + assert cs == 283 # Test on per-dataset mask ds = gdal.GetDriverByName('MEM').Create('', 10, 10, 2) @@ -774,105 +559,54 @@ def mem_12(): ds.GetRasterBand(1).GetMaskBand().Fill(127) ds.BuildOverviews('NEAR', [2]) cs = ds.GetRasterBand(1).GetOverview(0).GetMaskBand().Checksum() - if cs != 267: - gdaltest.post_reason('fail') - print(cs) - return 'fail' + assert cs == 267 cs2 = ds.GetRasterBand(2).GetOverview(0).GetMaskBand().Checksum() - if cs2 != cs: - gdaltest.post_reason('fail') - print(cs2) - return 'fail' - - return 'success' + assert cs2 == cs ############################################################################### # Check RAT support -def mem_rat(): +def test_mem_rat(): ds = gdal.GetDriverByName('MEM').Create('', 1, 1) ds.GetRasterBand(1).SetDefaultRAT(gdal.RasterAttributeTable()) - if ds.GetRasterBand(1).GetDefaultRAT() is None: - gdaltest.post_reason('fail') - return 'fail' + assert ds.GetRasterBand(1).GetDefaultRAT() is not None ds.GetRasterBand(1).SetDefaultRAT(None) - if ds.GetRasterBand(1).GetDefaultRAT() is not None: - gdaltest.post_reason('fail') - return 'fail' - - return 'success' + assert ds.GetRasterBand(1).GetDefaultRAT() is None ############################################################################### # Check CategoryNames support -def mem_categorynames(): +def test_mem_categorynames(): ds = gdal.GetDriverByName('MEM').Create('', 1, 1) 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).SetCategoryNames([]) - if ds.GetRasterBand(1).GetCategoryNames() is not None: - gdaltest.post_reason('fail') - return 'fail' - - return 'success' + assert ds.GetRasterBand(1).GetCategoryNames() is None ############################################################################### # Check ColorTable support -def mem_colortable(): +def test_mem_colortable(): ds = gdal.GetDriverByName('MEM').Create('', 1, 1) 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 ############################################################################### # cleanup -def mem_cleanup(): +def test_mem_cleanup(): gdaltest.mem_ds = None - return 'success' - - -gdaltest_list = [ - mem_1, - mem_2, - mem_3, - mem_4, - mem_5, - mem_6, - mem_7, - mem_8, - mem_9, - mem_10, - mem_11, - mem_12, - mem_rat, - mem_categorynames, - mem_colortable, - mem_cleanup] - -if __name__ == '__main__': - - gdaltest.setup_run('mem') - - gdaltest.run_tests(gdaltest_list) - - sys.exit(gdaltest.summarize()) + + + diff --git a/autotest/gdrivers/mff.py b/autotest/gdrivers/mff.py index b928e8454cbf..82e4710acef2 100755 --- a/autotest/gdrivers/mff.py +++ b/autotest/gdrivers/mff.py @@ -28,9 +28,7 @@ # DEALINGS IN THE SOFTWARE. ############################################################################### -import sys -sys.path.append('../pymod') import gdaltest @@ -38,7 +36,7 @@ # Test reading a - fake - MFF dataset -def mff_1(): +def test_mff_1(): tst = gdaltest.GDALTest('MFF', 'fakemff.hdr', 1, 1) return tst.testOpen() @@ -47,7 +45,7 @@ def mff_1(): # Test reading a - fake - tiled MFF dataset -def mff_2(): +def test_mff_2(): tst = gdaltest.GDALTest('MFF', 'fakemfftiled.hdr', 1, 1) return tst.testOpen() @@ -56,21 +54,10 @@ def mff_2(): ############################################################################### # Test reading a MFF file generated by CreateCopy() -def mff_3(): +def test_mff_3(): tst = gdaltest.GDALTest('MFF', 'bytemff.hdr', 1, 4672) return tst.testOpen() -gdaltest_list = [ - mff_1, - mff_2, - mff_3] -if __name__ == '__main__': - - gdaltest.setup_run('mff') - - gdaltest.run_tests(gdaltest_list) - - sys.exit(gdaltest.summarize()) diff --git a/autotest/gdrivers/mff2.py b/autotest/gdrivers/mff2.py index d01771b3a750..943bfb83be50 100755 --- a/autotest/gdrivers/mff2.py +++ b/autotest/gdrivers/mff2.py @@ -28,9 +28,7 @@ # DEALINGS IN THE SOFTWARE. ############################################################################### -import sys -sys.path.append('../pymod') import gdaltest @@ -38,19 +36,10 @@ # Test reading a MFF2 file generated by CreateCopy() -def mff2_1(): +def test_mff2_1(): tst = gdaltest.GDALTest('MFF2', 'bytemff2', 1, 4672) return tst.testOpen() -gdaltest_list = [ - mff2_1] -if __name__ == '__main__': - - gdaltest.setup_run('mff2') - - gdaltest.run_tests(gdaltest_list) - - sys.exit(gdaltest.summarize()) diff --git a/autotest/gdrivers/mg4lidar.py b/autotest/gdrivers/mg4lidar.py index 51c432f169d5..5b1939d6522d 100755 --- a/autotest/gdrivers/mg4lidar.py +++ b/autotest/gdrivers/mg4lidar.py @@ -29,26 +29,25 @@ ############################################################################### import os -import sys -sys.path.append('../pymod') import gdaltest from osgeo import gdal +import pytest ############################################################################### # Test reading a MG4Lidar file # -def mg4lidar_1(): +def test_mg4lidar_1(): drv = gdal.GetDriverByName('MG4Lidar') if drv is None: - return 'skip' + pytest.skip() if not gdaltest.download_file('http://home.gdal.org/tmp/GDAL_MG4Lidar_Src.zip', 'GDAL_MG4Lidar_Src.zip'): - return 'skip' + pytest.skip() try: os.stat('tmp/cache/GDAL_MG4Lidar_Src') @@ -58,53 +57,37 @@ def mg4lidar_1(): try: os.stat('tmp/cache/GDAL_MG4Lidar_Src') except OSError: - return 'skip' + pytest.skip() except OSError: - return 'skip' + pytest.skip() ds = gdal.Open('tmp/cache/GDAL_MG4Lidar_Src/Tetons_200k.view') - if ds is None: - gdaltest.post_reason('could not open dataset') - return 'fail' + assert ds is not None, 'could not open dataset' prj = ds.GetProjectionRef() if prj.find('NAD83 / UTM zone 12N') == -1: gdaltest.post_reason('did not get expected projection') print(prj) - return 'success' + return gt = ds.GetGeoTransform() ref_gt = (504489.919999999983702, 3.078227571115974, 0, 4795848.389999999664724, 0, -3.078259860787739) for i in range(6): - if abs(gt[i] - ref_gt[i]) > 1e-6: - gdaltest.post_reason('did not get expected geotransform') - print(gt) - return 'fail' + assert abs(gt[i] - ref_gt[i]) <= 1e-6, 'did not get expected geotransform' cs = ds.GetRasterBand(1).Checksum() if cs != 13216: gdaltest.post_reason('did not get expected checksum') print(cs) - return 'success' + return cs = ds.GetRasterBand(1).GetOverview(0).Checksum() if cs != 64099: gdaltest.post_reason('did not get expected overview checksum') print(cs) - return 'success' + return ds = None - return 'success' -gdaltest_list = [ - mg4lidar_1] - -if __name__ == '__main__': - - gdaltest.setup_run('mg4lidar') - - gdaltest.run_tests(gdaltest_list) - - sys.exit(gdaltest.summarize()) diff --git a/autotest/gdrivers/mrf.py b/autotest/gdrivers/mrf.py index be480ae7f85e..2b3ed195394e 100755 --- a/autotest/gdrivers/mrf.py +++ b/autotest/gdrivers/mrf.py @@ -28,54 +28,82 @@ # DEALINGS IN THE SOFTWARE. ############################################################################### -import sys import glob -sys.path.append('../pymod') +import pytest + from osgeo import gdal import gdaltest -init_list = [ - ('byte.tif', 1, 4672, None), - ('byte.tif', 1, 4672, ['COMPRESS=DEFLATE']), - ('byte.tif', 1, 4672, ['COMPRESS=NONE']), - ('byte.tif', 1, 4672, ['COMPRESS=LERC']), - ('byte.tif', 1, [4672, 5015], ['COMPRESS=LERC', 'OPTIONS:LERC_PREC=10']), - ('byte.tif', 1, 4672, ['COMPRESS=LERC', 'OPTIONS=V1:YES']), - ('int16.tif', 1, 4672, None), - ('int16.tif', 1, 4672, ['COMPRESS=LERC']), - ('int16.tif', 1, 4672, ['COMPRESS=LERC', 'OPTIONS=V1:YES']), - ('../../gcore/data/uint16.tif', 1, 4672, None), - ('../../gcore/data/uint16.tif', 1, 4672, ['COMPRESS=LERC']), - ('../../gcore/data/uint16.tif', 1, 4672, ['COMPRESS=LERC', 'OPTIONS=V1:YES']), - ('../../gcore/data/int32.tif', 1, 4672, ['COMPRESS=TIF']), - ('../../gcore/data/int32.tif', 1, 4672, ['COMPRESS=LERC']), - ('../../gcore/data/int32.tif', 1, 4672, ['COMPRESS=LERC', 'OPTIONS=V1:YES']), - ('../../gcore/data/uint32.tif', 1, 4672, ['COMPRESS=TIF']), - ('../../gcore/data/uint32.tif', 1, 4672, ['COMPRESS=LERC']), - ('../../gcore/data/uint32.tif', 1, 4672, ['COMPRESS=LERC', 'OPTIONS=V1:YES']), - ('../../gcore/data/float32.tif', 1, 4672, ['COMPRESS=TIF']), - ('../../gcore/data/float32.tif', 1, 4672, ['COMPRESS=LERC']), - ('../../gcore/data/float32.tif', 1, 4672, ['COMPRESS=LERC', 'OPTIONS=V1:YES']), - ('../../gcore/data/float64.tif', 1, 4672, ['COMPRESS=TIF']), - ('../../gcore/data/float64.tif', 1, 4672, ['COMPRESS=LERC']), - ('../../gcore/data/float64.tif', 1, [4672, 5015], ['COMPRESS=LERC', 'OPTIONS:LERC_PREC=10']), - ('../../gcore/data/float64.tif', 1, 4672, ['COMPRESS=LERC', 'OPTIONS=V1:YES']), - ('../../gcore/data/utmsmall.tif', 1, 50054, None), - ('small_world_pct.tif', 1, 14890, ['COMPRESS=PPNG']), - ('byte.tif', 1, [4672, [4603, 4652]], ['COMPRESS=JPEG', 'QUALITY=99']), + +mrf_list = [ + ('byte.tif', 4672, [4672], []), + ('byte.tif', 4672, [4672], ['COMPRESS=DEFLATE']), + ('byte.tif', 4672, [4672], ['COMPRESS=NONE']), + ('byte.tif', 4672, [4672], ['COMPRESS=LERC']), + ('byte.tif', 4672, [5015], ['COMPRESS=LERC', 'OPTIONS:LERC_PREC=10']), + ('byte.tif', 4672, [4672], ['COMPRESS=LERC', 'OPTIONS=V1:YES']), + ('int16.tif', 4672, [4672], []), + ('int16.tif', 4672, [4672], ['COMPRESS=LERC']), + ('int16.tif', 4672, [4672], ['COMPRESS=LERC', 'OPTIONS=V1:YES']), + ('../../gcore/data/uint16.tif', 4672, [4672], []), + ('../../gcore/data/uint16.tif', 4672, [4672], ['COMPRESS=LERC']), + ('../../gcore/data/uint16.tif', 4672, [4672], ['COMPRESS=LERC', 'OPTIONS=V1:YES']), + ('../../gcore/data/int32.tif', 4672, [4672], ['COMPRESS=TIF']), + ('../../gcore/data/int32.tif', 4672, [4672], ['COMPRESS=LERC']), + ('../../gcore/data/int32.tif', 4672, [4672], ['COMPRESS=LERC', 'OPTIONS=V1:YES']), + ('../../gcore/data/uint32.tif', 4672, [4672], ['COMPRESS=TIF']), + ('../../gcore/data/uint32.tif', 4672, [4672], ['COMPRESS=LERC']), + ('../../gcore/data/uint32.tif', 4672, [4672], ['COMPRESS=LERC', 'OPTIONS=V1:YES']), + ('../../gcore/data/float32.tif', 4672, [4672], ['COMPRESS=TIF']), + ('../../gcore/data/float32.tif', 4672, [4672], ['COMPRESS=LERC']), + ('../../gcore/data/float32.tif', 4672, [4672], ['COMPRESS=LERC', 'OPTIONS=V1:YES']), + ('../../gcore/data/float64.tif', 4672, [4672], ['COMPRESS=TIF']), + ('../../gcore/data/float64.tif', 4672, [4672], ['COMPRESS=LERC']), + ('../../gcore/data/float64.tif', 4672, [5015], ['COMPRESS=LERC', 'OPTIONS:LERC_PREC=10']), + ('../../gcore/data/float64.tif', 4672, [4672], ['COMPRESS=LERC', 'OPTIONS=V1:YES']), + ('../../gcore/data/utmsmall.tif', 50054, [50054], []), + ('small_world_pct.tif', 14890, [14890], ['COMPRESS=PPNG']), + ('byte.tif', 4672, [4603, 4652], ['COMPRESS=JPEG', 'QUALITY=99']), # following expected checksums are for: gcc 4.4 debug, mingw/vc9 32-bit, mingw-w64/vc12 64bit, MacOSX - ('rgbsmall.tif', 1, [21212, [21162, 21110, 21155, 21116]], ['COMPRESS=JPEG', 'QUALITY=99']), - ('rgbsmall.tif', 1, [21212, [21266, 21369, 21256, 21495]], ['INTERLEAVE=PIXEL', 'COMPRESS=JPEG', 'QUALITY=99']), - ('rgbsmall.tif', 1, [21212, [21261, 21209, 21254, 21215]], ['INTERLEAVE=PIXEL', 'COMPRESS=JPEG', 'QUALITY=99', 'PHOTOMETRIC=RGB']), - ('rgbsmall.tif', 1, [21212, [21283, 21127, 21278, 21124]], ['INTERLEAVE=PIXEL', 'COMPRESS=JPEG', 'QUALITY=99', 'PHOTOMETRIC=YCC']), - ('12bit_rose_extract.jpg', 1, [30075, [29650, 29680, 29680, 29650]], ['COMPRESS=JPEG']), + ('rgbsmall.tif', 21212, [21162, 21110, 21155, 21116], ['COMPRESS=JPEG', 'QUALITY=99']), + ('rgbsmall.tif', 21212, [21266, 21369, 21256, 21495], ['INTERLEAVE=PIXEL', 'COMPRESS=JPEG', 'QUALITY=99']), + ('rgbsmall.tif', 21212, [21261, 21209, 21254, 21215], ['INTERLEAVE=PIXEL', 'COMPRESS=JPEG', 'QUALITY=99', 'PHOTOMETRIC=RGB']), + ('rgbsmall.tif', 21212, [21283, 21127, 21278, 21124], ['INTERLEAVE=PIXEL', 'COMPRESS=JPEG', 'QUALITY=99', 'PHOTOMETRIC=YCC']), + ('12bit_rose_extract.jpg', 30075, [29650, 29680, 29680, 29650], ['COMPRESS=JPEG']), ] -def mrf_zen_test(): +@pytest.mark.parametrize( + 'src_filename,chksum,chksum_after_reopening,options', + mrf_list, + ids=['{0}-{3}'.format(*r) for r in mrf_list], +) +def test_mrf(src_filename, chksum, chksum_after_reopening, options): + if src_filename == '12bit_rose_extract.jpg': + import jpeg + jpeg.test_jpeg_1() + if gdaltest.jpeg_version == '9b': + pytest.skip() + + with gdaltest.error_handler(): + ds = gdal.Open('data/' + src_filename) + if ds is None: + pytest.skip() + + ds = None + ut = gdaltest.GDALTest('MRF', src_filename, 1, chksum, options=options, chksum_after_reopening=chksum_after_reopening) + + check_minmax = 'COMPRESS=JPEG' not in ut.options + for x in ut.options: + if x.find('OPTIONS:LERC_PREC=') >= 0: + check_minmax = False + return ut.testCreateCopy(check_minmax=check_minmax) + + +def test_mrf_zen_test(): result = 'success' expectedCS = 770 testvrt = ''' @@ -104,13 +132,11 @@ def mrf_zen_test(): result = 'fail' for f in glob.glob('tmp/masked.*'): gdal.Unlink(f) - if result != 'success': - return result return result -def mrf_overview_near_fact_2(): +def test_mrf_overview_near_fact_2(): ref_ds = gdal.Translate('/vsimem/out.tif', 'data/byte.tif') ref_ds.BuildOverviews('NEAR', [2]) @@ -131,12 +157,7 @@ def mrf_overview_near_fact_2(): ds = gdal.Open('/vsimem/out.mrf') cs = ds.GetRasterBand(1).GetOverview(0).Checksum() - if cs != expected_cs: - gdaltest.post_reason('fail') - print(dt) - print(cs) - print(expected_cs) - return 'fail' + assert cs == expected_cs, dt ds = None gdal.Unlink('/vsimem/out.mrf') @@ -145,10 +166,9 @@ def mrf_overview_near_fact_2(): gdal.Unlink('/vsimem/out.ppg') gdal.Unlink('/vsimem/out.til') - return 'success' + - -def mrf_overview_near_with_nodata_fact_2(): +def test_mrf_overview_near_with_nodata_fact_2(): for dt in [gdal.GDT_Byte, gdal.GDT_Int16, gdal.GDT_UInt16, gdal.GDT_Int32, gdal.GDT_UInt32, @@ -165,12 +185,7 @@ def mrf_overview_near_with_nodata_fact_2(): ds = gdal.Open('/vsimem/out.mrf') cs = ds.GetRasterBand(1).GetOverview(0).Checksum() expected_cs = 1117 - if cs != expected_cs: - gdaltest.post_reason('fail') - print(dt) - print(cs) - print(expected_cs) - return 'fail' + assert cs == expected_cs, dt ds = None gdal.Unlink('/vsimem/out.mrf') @@ -179,10 +194,9 @@ def mrf_overview_near_with_nodata_fact_2(): gdal.Unlink('/vsimem/out.ppg') gdal.Unlink('/vsimem/out.til') - return 'success' - + -def mrf_overview_avg_fact_2(): +def test_mrf_overview_avg_fact_2(): for dt in [gdal.GDT_Byte, gdal.GDT_Int16, gdal.GDT_UInt16, gdal.GDT_Int32, gdal.GDT_UInt32, @@ -199,12 +213,7 @@ def mrf_overview_avg_fact_2(): ds = gdal.Open('/vsimem/out.mrf') cs = ds.GetRasterBand(1).GetOverview(0).Checksum() - if cs != expected_cs: - gdaltest.post_reason('fail') - print(dt) - print(cs) - print(expected_cs) - return 'fail' + assert cs == expected_cs, dt ds = None gdal.Unlink('/vsimem/out.mrf') @@ -213,10 +222,9 @@ def mrf_overview_avg_fact_2(): gdal.Unlink('/vsimem/out.ppg') gdal.Unlink('/vsimem/out.til') - return 'success' - + -def mrf_overview_avg_with_nodata_fact_2(): +def test_mrf_overview_avg_with_nodata_fact_2(): for dt in [gdal.GDT_Byte, gdal.GDT_Int16, gdal.GDT_UInt16, gdal.GDT_Int32, gdal.GDT_UInt32, @@ -234,12 +242,7 @@ def mrf_overview_avg_with_nodata_fact_2(): ds = gdal.Open('/vsimem/out.mrf') cs = ds.GetRasterBand(1).GetOverview(0).Checksum() - if cs != expected_cs: - gdaltest.post_reason('fail') - print(dt) - print(cs) - print(expected_cs) - return 'fail' + assert cs == expected_cs, dt ds = None gdal.Unlink('/vsimem/out.mrf') @@ -248,10 +251,9 @@ def mrf_overview_avg_with_nodata_fact_2(): gdal.Unlink('/vsimem/out.ppg') gdal.Unlink('/vsimem/out.til') - return 'success' + - -def mrf_overview_near_fact_3(): +def test_mrf_overview_near_fact_3(): out_ds = gdal.Translate('/vsimem/out.mrf', 'data/byte.tif', format='MRF', @@ -262,11 +264,7 @@ def mrf_overview_near_fact_3(): ds = gdal.Open('/vsimem/out.mrf') cs = ds.GetRasterBand(1).GetOverview(0).Checksum() expected_cs = 478 - if cs != expected_cs: - gdaltest.post_reason('fail') - print(cs) - print(expected_cs) - return 'fail' + assert cs == expected_cs ds = None gdal.Unlink('/vsimem/out.mrf') @@ -275,10 +273,8 @@ def mrf_overview_near_fact_3(): gdal.Unlink('/vsimem/out.ppg') gdal.Unlink('/vsimem/out.til') - return 'success' - -def mrf_overview_avg_fact_3(): +def test_mrf_overview_avg_fact_3(): out_ds = gdal.Translate('/vsimem/out.mrf', 'data/byte.tif', format='MRF', @@ -289,11 +285,7 @@ def mrf_overview_avg_fact_3(): ds = gdal.Open('/vsimem/out.mrf') cs = ds.GetRasterBand(1).GetOverview(0).Checksum() expected_cs = 658 - if cs != expected_cs: - gdaltest.post_reason('fail') - print(cs) - print(expected_cs) - return 'fail' + assert cs == expected_cs ds = None gdal.Unlink('/vsimem/out.mrf') @@ -302,10 +294,8 @@ def mrf_overview_avg_fact_3(): gdal.Unlink('/vsimem/out.ppg') gdal.Unlink('/vsimem/out.til') - return 'success' - -def mrf_overview_avg_with_nodata_fact_3(): +def test_mrf_overview_avg_with_nodata_fact_3(): for dt in [gdal.GDT_Byte, gdal.GDT_Int16, gdal.GDT_UInt16, gdal.GDT_Int32, gdal.GDT_UInt32, @@ -323,12 +313,7 @@ def mrf_overview_avg_with_nodata_fact_3(): ds = gdal.Open('/vsimem/out.mrf') cs = ds.GetRasterBand(1).GetOverview(0).Checksum() - if cs != expected_cs: - gdaltest.post_reason('fail') - print(dt) - print(cs) - print(expected_cs) - return 'fail' + assert cs == expected_cs, dt ds = None gdal.Unlink('/vsimem/out.mrf') @@ -337,10 +322,9 @@ def mrf_overview_avg_with_nodata_fact_3(): gdal.Unlink('/vsimem/out.ppg') gdal.Unlink('/vsimem/out.til') - return 'success' + - -def mrf_overview_partial_block(): +def test_mrf_overview_partial_block(): out_ds = gdal.Translate('/vsimem/out.mrf', 'data/byte.tif', format='MRF', creationOptions=['COMPRESS=NONE', 'BLOCKSIZE=8']) @@ -349,10 +333,7 @@ def mrf_overview_partial_block(): ds = gdal.Open('/vsimem/out.mrf') cs = ds.GetRasterBand(1).GetOverview(0).Checksum() - if cs != 1087: - gdaltest.post_reason('fail') - print(cs) - return 'fail' + assert cs == 1087 ds = None gdal.Unlink('/vsimem/out.mrf') @@ -361,10 +342,8 @@ def mrf_overview_partial_block(): gdal.Unlink('/vsimem/out.ppg') gdal.Unlink('/vsimem/out.til') - return 'success' - -def mrf_overview_near_implicit_level(): +def test_mrf_overview_near_implicit_level(): # We ask only overview level 2, but MRF automatically creates 2 and 4 # so check that 4 is properly initialized @@ -375,24 +354,16 @@ def mrf_overview_near_implicit_level(): ds = gdal.Open('/vsimem/out.mrf') cs = ds.GetRasterBand(1).GetOverview(1).Checksum() - if cs != 328: - gdaltest.post_reason('fail') - print(cs) - return 'fail' + assert cs == 328 ds = None with gdaltest.error_handler(): ds = gdal.Open('/vsimem/out.mrf:MRF:L2') - if ds is not None: - gdaltest.post_reason('fail') - return 'fail' + assert ds is None ds = gdal.Open('/vsimem/out.mrf:MRF:L1') cs = ds.GetRasterBand(1).Checksum() - if cs != 328: - gdaltest.post_reason('fail') - print(cs) - return 'fail' + assert cs == 328 ds = None gdal.Unlink('/vsimem/out.mrf') @@ -401,10 +372,8 @@ def mrf_overview_near_implicit_level(): gdal.Unlink('/vsimem/out.ppg') gdal.Unlink('/vsimem/out.til') - return 'success' - -def mrf_overview_external(): +def test_mrf_overview_external(): gdal.Translate('/vsimem/out.mrf', 'data/byte.tif', format='MRF') ds = gdal.Open('/vsimem/out.mrf') @@ -414,11 +383,7 @@ def mrf_overview_external(): ds = gdal.Open('/vsimem/out.mrf') cs = ds.GetRasterBand(1).GetOverview(0).Checksum() expected_cs = 1087 - if cs != expected_cs: - gdaltest.post_reason('fail') - print(cs) - print(expected_cs) - return 'fail' + assert cs == expected_cs ds = None gdal.Unlink('/vsimem/out.mrf') @@ -428,26 +393,17 @@ def mrf_overview_external(): gdal.Unlink('/vsimem/out.ppg') gdal.Unlink('/vsimem/out.til') - return 'success' - -def mrf_lerc_nodata(): +def test_mrf_lerc_nodata(): gdal.Translate('/vsimem/out.mrf', 'data/byte.tif', format='MRF', noData=107, creationOptions=['COMPRESS=LERC']) ds = gdal.Open('/vsimem/out.mrf') nodata = ds.GetRasterBand(1).GetNoDataValue() - if nodata != 107: - gdaltest.post_reason('fail') - print(nodata) - return 'fail' + assert nodata == 107 cs = ds.GetRasterBand(1).Checksum() expected_cs = 4672 - if cs != expected_cs: - gdaltest.post_reason('fail') - print(cs) - print(expected_cs) - return 'fail' + assert cs == expected_cs ds = None gdal.Unlink('/vsimem/out.mrf') @@ -456,21 +412,15 @@ def mrf_lerc_nodata(): gdal.Unlink('/vsimem/out.lrc') gdal.Unlink('/vsimem/out.til') - return 'success' - -def mrf_lerc_with_huffman(): +def test_mrf_lerc_with_huffman(): gdal.Translate('/vsimem/out.mrf', 'data/small_world.tif', format='MRF', width=5000, height=5000, creationOptions=['COMPRESS=LERC']) ds = gdal.Open('/vsimem/out.mrf') cs = ds.GetRasterBand(1).Checksum() expected_cs = 31204 - if cs != expected_cs: - gdaltest.post_reason('fail') - print(cs) - print(expected_cs) - return 'fail' + assert cs == expected_cs ds = None gdal.Unlink('/vsimem/out.mrf') @@ -479,10 +429,8 @@ def mrf_lerc_with_huffman(): gdal.Unlink('/vsimem/out.lrc') gdal.Unlink('/vsimem/out.til') - return 'success' - -def mrf_cached_source(): +def test_mrf_cached_source(): # Caching MRF gdal.Translate('/vsimem/out.mrf', 'data/byte.tif', format='MRF', @@ -491,11 +439,7 @@ def mrf_cached_source(): with gdaltest.error_handler(): cs = ds.GetRasterBand(1).Checksum() expected_cs = 0 - if cs != expected_cs: - gdaltest.post_reason('fail') - print(cs) - print(expected_cs) - return 'fail' + assert cs == expected_cs ds = None gdal.Unlink('/vsimem/out.mrf') @@ -513,22 +457,14 @@ def mrf_cached_source(): ds = gdal.Open('tmp/out.mrf') cs = ds.GetRasterBand(1).Checksum() expected_cs = 4672 - if cs != expected_cs: - gdaltest.post_reason('fail') - print(cs) - print(expected_cs) - return 'fail' + assert cs == expected_cs ds = None gdal.Unlink('tmp/byte.tif') ds = gdal.Open('tmp/out.mrf') cs = ds.GetRasterBand(1).Checksum() expected_cs = 4672 - if cs != expected_cs: - gdaltest.post_reason('fail') - print(cs) - print(expected_cs) - return 'fail' + assert cs == expected_cs ds = None # Caching MRF in mp_safe mode @@ -557,22 +493,14 @@ def mrf_cached_source(): ds = gdal.Open('tmp/out.mrf') cs = ds.GetRasterBand(1).Checksum() expected_cs = 4672 - if cs != expected_cs: - gdaltest.post_reason('fail') - print(cs) - print(expected_cs) - return 'fail' + assert cs == expected_cs ds = None gdal.Unlink('tmp/byte.tif') ds = gdal.Open('tmp/out.mrf') cs = ds.GetRasterBand(1).Checksum() expected_cs = 4672 - if cs != expected_cs: - gdaltest.post_reason('fail') - print(cs) - print(expected_cs) - return 'fail' + assert cs == expected_cs ds = None # Cloning MRF @@ -593,11 +521,7 @@ def mrf_cached_source(): ds = gdal.Open('tmp/cloning.mrf') cs = ds.GetRasterBand(1).Checksum() expected_cs = 4672 - if cs != expected_cs: - gdaltest.post_reason('fail') - print(cs) - print(expected_cs) - return 'fail' + assert cs == expected_cs ds = None gdal.Unlink('tmp/out.mrf') @@ -609,11 +533,7 @@ def mrf_cached_source(): ds = gdal.Open('tmp/cloning.mrf') cs = ds.GetRasterBand(1).Checksum() expected_cs = 4672 - if cs != expected_cs: - gdaltest.post_reason('fail') - print(cs) - print(expected_cs) - return 'fail' + assert cs == expected_cs ds = None gdal.Unlink('tmp/cloning.mrf') @@ -622,10 +542,8 @@ def mrf_cached_source(): gdal.Unlink('tmp/cloning.ppg') gdal.Unlink('tmp/cloning.til') - return 'success' - -def mrf_versioned(): +def test_mrf_versioned(): gdal.Unlink('/vsimem/out.mrf') gdal.Unlink('/vsimem/out.mrf.aux.xml') @@ -653,38 +571,24 @@ def mrf_versioned(): ds = gdal.Open('/vsimem/out.mrf') cs = ds.GetRasterBand(1).Checksum() expected_cs = 0 - if cs != expected_cs: - gdaltest.post_reason('fail') - print(cs) - print(expected_cs) - return 'fail' + assert cs == expected_cs ds = None ds = gdal.Open('/vsimem/out.mrf:MRF:V0') cs = ds.GetRasterBand(1).Checksum() expected_cs = 0 - if cs != expected_cs: - gdaltest.post_reason('fail') - print(cs) - print(expected_cs) - return 'fail' + assert cs == expected_cs ds = None ds = gdal.Open('/vsimem/out.mrf:MRF:V1') cs = ds.GetRasterBand(1).Checksum() expected_cs = 4672 - if cs != expected_cs: - gdaltest.post_reason('fail') - print(cs) - print(expected_cs) - return 'fail' + assert cs == expected_cs ds = None with gdaltest.error_handler(): ds = gdal.Open('/vsimem/out.mrf:MRF:V2') - if ds is not None: - gdaltest.post_reason('fail') - return 'fail' + assert ds is None gdal.Unlink('/vsimem/out.mrf') gdal.Unlink('/vsimem/out.mrf.aux.xml') @@ -692,10 +596,8 @@ def mrf_versioned(): gdal.Unlink('/vsimem/out.ppg') gdal.Unlink('/vsimem/out.til') - return 'success' - -def mrf_cleanup(): +def test_mrf_cleanup(): files = [ '12bit_rose_extract.jpg.*', @@ -724,79 +626,5 @@ def mrf_cleanup(): gdal.Unlink('/vsimem/out.ppg') gdal.Unlink('/vsimem/out.til') - return 'success' - - -gdaltest_list = [] - - -class myTestCreateCopyWrapper(object): - - def __init__(self, ut): - self.ut = ut - def myTestCreateCopy(self): - check_minmax = 'COMPRESS=JPEG' not in self.ut.options - for x in self.ut.options: - if x.find('OPTIONS:LERC_PREC=') >= 0: - check_minmax = False - return self.ut.testCreateCopy(check_minmax=check_minmax) - -for item in init_list: - src_filename = item[0] - - if src_filename == '12bit_rose_extract.jpg': - import jpeg - jpeg.jpeg_1() - if gdaltest.jpeg_version == '9b': - continue - - with gdaltest.error_handler(): - ds = gdal.Open('data/' + src_filename) - if ds is None: - continue - ds = None - options = [] - if item[3]: - options = item[3] - chksum_param = item[2] - if isinstance(chksum_param, list): - chksum = chksum_param[0] - chksum_after_reopening = chksum_param[1] - else: - chksum = chksum_param - chksum_after_reopening = chksum_param - - ut = gdaltest.GDALTest('MRF', src_filename, item[1], chksum, options=options, chksum_after_reopening=chksum_after_reopening) - if ut is None: - print('MRF tests skipped') - - ut = myTestCreateCopyWrapper(ut) - - gdaltest_list.append((ut.myTestCreateCopy, item[0] + ' ' + str(options))) - -gdaltest_list += [mrf_overview_near_fact_2] -gdaltest_list += [mrf_overview_near_with_nodata_fact_2] -gdaltest_list += [mrf_overview_avg_fact_2] -gdaltest_list += [mrf_overview_avg_with_nodata_fact_2] -gdaltest_list += [mrf_overview_near_fact_3] -gdaltest_list += [mrf_overview_avg_fact_3] -gdaltest_list += [mrf_overview_avg_with_nodata_fact_3] -gdaltest_list += [mrf_overview_partial_block] -gdaltest_list += [mrf_overview_near_implicit_level] -gdaltest_list += [mrf_overview_external] -gdaltest_list += [mrf_lerc_nodata] -gdaltest_list += [mrf_lerc_with_huffman] -gdaltest_list += [mrf_cached_source] -gdaltest_list += [mrf_versioned] -gdaltest_list += [mrf_zen_test] -gdaltest_list += [mrf_cleanup] - -if __name__ == '__main__': - - gdaltest.setup_run('mrf') - - gdaltest.run_tests(gdaltest_list) - - sys.exit(gdaltest.summarize()) diff --git a/autotest/gdrivers/mrsid.py b/autotest/gdrivers/mrsid.py index 576d90932a75..013e4559ce38 100755 --- a/autotest/gdrivers/mrsid.py +++ b/autotest/gdrivers/mrsid.py @@ -30,23 +30,22 @@ ############################################################################### import os -import sys import shutil from osgeo import gdal -sys.path.append('../pymod') import gdaltest +import pytest ############################################################################### # Read a simple byte file, checking projections and geotransform. -def mrsid_1(): +def test_mrsid_1(): gdaltest.mrsid_drv = gdal.GetDriverByName('MrSID') if gdaltest.mrsid_drv is None: - return 'skip' + pytest.skip() tst = gdaltest.GDALTest('MrSID', 'mercator.sid', 1, None) @@ -112,46 +111,40 @@ def mrsid_1(): UNIT["metre",1, AUTHORITY["EPSG","9001"]]]""" - ret = tst.testOpen(check_gt=gt, + tst.testOpen(check_gt=gt, check_stat=(0.0, 255.0, 103.319, 55.153), check_approx_stat=(2.0, 243.0, 103.131, 43.978)) - if ret != 'success': - return ret - ds = gdal.Open('data/mercator.sid') got_prj = ds.GetProjectionRef() ds = None if prj.find('North_American_Datum_1927') == -1 or \ prj.find('Mercator_1SP') == -1: - gdaltest.post_reason('did not get expected projection') print(got_prj) - return 'fail' + pytest.fail('did not get expected projection') if got_prj != prj: print('Warning: did not get exactly expected projection. Got %s' % got_prj) - return 'success' - + ############################################################################### # Do a direct IO to read the image at a resolution for which there is no # builtin overview. Checks for the bug Steve L found in the optimized # RasterIO implementation. -def mrsid_2(): +def test_mrsid_2(): if gdaltest.mrsid_drv is None: - return 'skip' + pytest.skip() ds = gdal.Open('data/mercator.sid') try: data = ds.ReadRaster(0, 0, 515, 515, buf_xsize=10, buf_ysize=10) except: - gdaltest.post_reason('Small overview read failed: ' + gdal.GetLastErrorMsg()) - return 'fail' + pytest.fail('Small overview read failed: ' + gdal.GetLastErrorMsg()) ds = None @@ -167,27 +160,21 @@ def mrsid_2(): mean = float(total) / len(data) - if mean < 95 or mean > 105: - gdaltest.post_reason('image mean out of range.') - return 'fail' - - return 'success' + assert mean >= 95 and mean <= 105, 'image mean out of range.' ############################################################################### # Test overview reading. -def mrsid_3(): +def test_mrsid_3(): if gdaltest.mrsid_drv is None: - return 'skip' + pytest.skip() ds = gdal.Open('data/mercator.sid') band = ds.GetRasterBand(1) - if band.GetOverviewCount() != 4: - gdaltest.post_reason('did not get expected overview count') - return 'fail' + assert band.GetOverviewCount() == 4, 'did not get expected overview count' new_stat = band.GetOverview(3).GetStatistics(0, 1) @@ -199,19 +186,17 @@ def mrsid_3(): print('') print('old = ', check_stat) print('new = ', new_stat) - gdaltest.post_reason('Statistics differ.') - return 'fail' - - return 'success' + pytest.fail('Statistics differ.') + ############################################################################### # Check a new (V3) file which uses a different form for coordinate sys. -def mrsid_4(): +def test_mrsid_4(): if gdaltest.mrsid_drv is None: - return 'skip' + pytest.skip() try: os.remove('data/mercator_new.sid.aux.xml') @@ -254,23 +239,21 @@ def mrsid_4(): # Test JP2MrSID driver -def mrsid_5(): +def test_mrsid_5(): gdaltest.jp2mrsid_drv = gdal.GetDriverByName('JP2MrSID') if gdaltest.jp2mrsid_drv is None: - return 'skip' + pytest.skip() gdaltest.deregister_all_jpeg2000_drivers_but('JP2MrSID') - return 'success' - ############################################################################### # Open byte.jp2 -def mrsid_6(): +def test_mrsid_6(): if gdaltest.jp2mrsid_drv is None: - return 'skip' + pytest.skip() srs = """PROJCS["NAD27 / UTM zone 11N", GEOGCS["NAD27", @@ -300,10 +283,10 @@ def mrsid_6(): ############################################################################### # Open int16.jp2 -def mrsid_7(): +def test_mrsid_7(): if gdaltest.jp2mrsid_drv is None: - return 'skip' + pytest.skip() ds = gdal.Open('data/int16.jp2') ds_ref = gdal.Open('data/int16.tif') @@ -311,27 +294,24 @@ def mrsid_7(): maxdiff = gdaltest.compare_ds(ds, ds_ref) if maxdiff > 5: - gdaltest.post_reason('Image too different from reference') print(ds.GetRasterBand(1).Checksum()) print(ds_ref.GetRasterBand(1).Checksum()) ds = None ds_ref = None - return 'fail' + pytest.fail('Image too different from reference') ds = None ds_ref = None - return 'success' - ############################################################################### # Test PAM override for nodata, coordsys, and geotransform. -def mrsid_8(): +def test_mrsid_8(): if gdaltest.mrsid_drv is None: - return 'skip' + pytest.skip() new_gt = (10000, 50, 0, 20000, 0, -50) new_srs = """PROJCS["OSGB 1936 / British National Grid",GEOGCS["OSGB 1936",DATUM["OSGB_1936",SPHEROID["Airy 1830",6377563.396,299.3249646,AUTHORITY["EPSG","7001"]],AUTHORITY["EPSG","6277"]],PRIMEM["Greenwich",0,AUTHORITY["EPSG","8901"]],UNIT["degree",0.01745329251994328,AUTHORITY["EPSG","9122"]],AUTHORITY["EPSG","4277"]],UNIT["metre",1,AUTHORITY["EPSG","9001"]],PROJECTION["Transverse_Mercator"],PARAMETER["latitude_of_origin",49],PARAMETER["central_meridian",-2],PARAMETER["scale_factor",0.9996012717],PARAMETER["false_easting",400000],PARAMETER["false_northing",-100000],AUTHORITY["EPSG","27700"],AXIS["Easting",EAST],AXIS["Northing",NORTH]]""" @@ -351,33 +331,24 @@ def mrsid_8(): ds = gdal.Open('tmp/mercator.sid') - if new_srs != ds.GetProjectionRef(): - print(ds.GetProjectionRef()) - gdaltest.post_reason('SRS Override failed.') - return 'fail' + assert new_srs == ds.GetProjectionRef(), 'SRS Override failed.' - if new_gt != ds.GetGeoTransform(): - gdaltest.post_reason('Geotransform Override failed.') - return 'fail' + assert new_gt == ds.GetGeoTransform(), 'Geotransform Override failed.' - if ds.GetRasterBand(1).GetNoDataValue() != 255: - gdaltest.post_reason('Nodata override failed.') - return 'fail' + assert ds.GetRasterBand(1).GetNoDataValue() == 255, 'Nodata override failed.' ds = None gdal.GetDriverByName('MrSID').Delete('tmp/mercator.sid') - return 'success' - ############################################################################### # Test VSI*L IO with .sid -def mrsid_9(): +def test_mrsid_9(): if gdaltest.mrsid_drv is None: - return 'skip' + pytest.skip() f = open('data/mercator.sid', 'rb') data = f.read() @@ -388,21 +359,19 @@ def mrsid_9(): gdal.VSIFCloseL(f) ds = gdal.Open('/vsimem/mrsid_9.sid') - if ds is None: - return 'fail' + assert ds is not None ds = None gdal.Unlink('/vsimem/mrsid_9.sid') - return 'success' ############################################################################### # Test VSI*L IO with .jp2 -def mrsid_10(): +def test_mrsid_10(): if gdaltest.jp2mrsid_drv is None: - return 'skip' + pytest.skip() f = open('data/int16.jp2', 'rb') data = f.read() @@ -413,78 +382,63 @@ def mrsid_10(): gdal.VSIFCloseL(f) ds = gdal.Open('/vsimem/mrsid_10.jp2') - if ds is None: - return 'fail' + assert ds is not None ds = None gdal.Unlink('/vsimem/mrsid_10.jp2') - return 'success' ############################################################################### # Check that we can use .j2w world files (#4651) -def mrsid_11(): +def test_mrsid_11(): if gdaltest.jp2mrsid_drv is None: - return 'skip' + pytest.skip() ds = gdal.Open('data/byte_without_geotransform.jp2') geotransform = ds.GetGeoTransform() - if abs(geotransform[0] - 440720) > 0.1 \ - or abs(geotransform[1] - 60) > 0.001 \ - or abs(geotransform[2] - 0) > 0.001 \ - or abs(geotransform[3] - 3751320) > 0.1 \ - or abs(geotransform[4] - 0) > 0.001 \ - or abs(geotransform[5] - -60) > 0.001: - print(geotransform) - gdaltest.post_reason('geotransform differs from expected') - return 'fail' + assert abs(geotransform[0] - 440720) <= 0.1 and abs(geotransform[1] - 60) <= 0.001 and abs(geotransform[2] - 0) <= 0.001 and abs(geotransform[3] - 3751320) <= 0.1 and abs(geotransform[4] - 0) <= 0.001 and abs(geotransform[5] - -60) <= 0.001, \ + 'geotransform differs from expected' ds = None - return 'success' - ############################################################################### -def mrsid_online_1(): +def test_mrsid_online_1(): if gdaltest.jp2mrsid_drv is None: - return 'skip' + pytest.skip() if not gdaltest.download_file('http://download.osgeo.org/gdal/data/jpeg2000/7sisters200.j2k', '7sisters200.j2k'): - return 'skip' + pytest.skip() # Checksum = 29473 on my PC tst = gdaltest.GDALTest('JP2MrSID', 'tmp/cache/7sisters200.j2k', 1, None, filename_absolute=1) - if tst.testOpen() != 'success': - return 'fail' + tst.testOpen() ds = gdal.Open('tmp/cache/7sisters200.j2k') ds.GetRasterBand(1).Checksum() ds = None - return 'success' - ############################################################################### -def mrsid_online_2(): +def test_mrsid_online_2(): if gdaltest.jp2mrsid_drv is None: - return 'skip' + pytest.skip() if not gdaltest.download_file('http://download.osgeo.org/gdal/data/jpeg2000/gcp.jp2', 'gcp.jp2'): - return 'skip' + pytest.skip() # Checksum = 209 on my PC tst = gdaltest.GDALTest('JP2MrSID', 'tmp/cache/gcp.jp2', 1, None, filename_absolute=1) - if tst.testOpen() != 'success': - return 'fail' + tst.testOpen() # The JP2MrSID driver doesn't handle GCPs ds = gdal.Open('tmp/cache/gcp.jp2') @@ -500,26 +454,23 @@ def mrsid_online_2(): ds = None - return 'success' - ############################################################################### -def mrsid_online_3(): +def test_mrsid_online_3(): if gdaltest.jp2mrsid_drv is None: - return 'skip' + pytest.skip() if not gdaltest.download_file('http://www.openjpeg.org/samples/Bretagne1.j2k', 'Bretagne1.j2k'): - return 'skip' + pytest.skip() if not gdaltest.download_file('http://www.openjpeg.org/samples/Bretagne1.bmp', 'Bretagne1.bmp'): - return 'skip' + pytest.skip() # checksum = 14443 on my PC tst = gdaltest.GDALTest('JP2MrSID', 'tmp/cache/Bretagne1.j2k', 1, None, filename_absolute=1) - if tst.testOpen() != 'success': - return 'fail' + tst.testOpen() ds = gdal.Open('tmp/cache/Bretagne1.j2k') ds_ref = gdal.Open('tmp/cache/Bretagne1.bmp') @@ -534,29 +485,26 @@ def mrsid_online_3(): print(ds_ref.GetRasterBand(1).Checksum()) gdaltest.compare_ds(ds, ds_ref, verbose=1) - gdaltest.post_reason('Image too different from reference') - return 'fail' - - return 'success' + pytest.fail('Image too different from reference') + ############################################################################### -def mrsid_online_4(): +def test_mrsid_online_4(): if gdaltest.jp2mrsid_drv is None: - return 'skip' + pytest.skip() if not gdaltest.download_file('http://www.openjpeg.org/samples/Bretagne2.j2k', 'Bretagne2.j2k'): - return 'skip' + pytest.skip() if not gdaltest.download_file('http://www.openjpeg.org/samples/Bretagne2.bmp', 'Bretagne2.bmp'): - return 'skip' + pytest.skip() # Checksum = 53186 on my PC tst = gdaltest.GDALTest('JP2MrSID', 'tmp/cache/Bretagne2.j2k', 1, None, filename_absolute=1) - if tst.testOpen() != 'success': - return 'fail' + tst.testOpen() ds = gdal.Open('tmp/cache/Bretagne2.j2k') ds_ref = gdal.Open('tmp/cache/Bretagne2.bmp') @@ -569,16 +517,14 @@ def mrsid_online_4(): if maxdiff > 1: print(ds.GetRasterBand(1).Checksum()) print(ds_ref.GetRasterBand(1).Checksum()) - gdaltest.post_reason('Image too different from reference') - return 'fail' - - return 'success' + pytest.fail('Image too different from reference') + ############################################################################### # Cleanup. -def mrsid_cleanup(): +def test_mrsid_cleanup(): try: os.remove('data/mercator.sid.aux.xml') @@ -588,31 +534,5 @@ def mrsid_cleanup(): gdaltest.reregister_all_jpeg2000_drivers() - return 'success' - - -gdaltest_list = [ - mrsid_1, - mrsid_2, - mrsid_3, - mrsid_4, - mrsid_5, - mrsid_6, - mrsid_7, - mrsid_8, - mrsid_9, - mrsid_10, - mrsid_11, - mrsid_online_1, - mrsid_online_2, - mrsid_online_3, - mrsid_online_4, - mrsid_cleanup] - -if __name__ == '__main__': - - gdaltest.setup_run('mrsid') - gdaltest.run_tests(gdaltest_list) - sys.exit(gdaltest.summarize()) diff --git a/autotest/gdrivers/ndf.py b/autotest/gdrivers/ndf.py index aebd0e026d45..a968b5ffeafd 100755 --- a/autotest/gdrivers/ndf.py +++ b/autotest/gdrivers/ndf.py @@ -28,9 +28,7 @@ # DEALINGS IN THE SOFTWARE. ############################################################################### -import sys -sys.path.append('../pymod') import gdaltest @@ -38,7 +36,7 @@ # Simple image test of an NLAPS/NDF2 dataset. -def ndf_1(): +def test_ndf_1(): tst = gdaltest.GDALTest('NDF', 'LE7134052000500350.H3', 1, 6510, xoff=0, yoff=0, xsize=15620, ysize=1) @@ -71,13 +69,4 @@ def ndf_1(): check_prj=wkt) -gdaltest_list = [ - ndf_1] -if __name__ == '__main__': - - gdaltest.setup_run('ndf') - - gdaltest.run_tests(gdaltest_list) - - sys.exit(gdaltest.summarize()) diff --git a/autotest/gdrivers/netcdf.py b/autotest/gdrivers/netcdf.py index 347f3bce23af..b6a3422727fd 100755 --- a/autotest/gdrivers/netcdf.py +++ b/autotest/gdrivers/netcdf.py @@ -39,7 +39,8 @@ from osgeo import ogr from osgeo import osr -sys.path.append('../pymod') + +import pytest import gdaltest @@ -55,7 +56,9 @@ # Get netcdf version and test for supported files +@pytest.fixture(autouse=True, scope='module') def netcdf_setup(): + # NOTE: this is also used by netcdf_cf.py gdaltest.netcdf_drv_version = 'unknown' gdaltest.netcdf_drv_has_nc2 = False @@ -66,14 +69,12 @@ def netcdf_setup(): gdaltest.netcdf_drv = gdal.GetDriverByName('NETCDF') if gdaltest.netcdf_drv is None: - print('NOTICE: netcdf not supported, skipping checks') - return 'skip' + pytest.skip('NOTICE: netcdf not supported, skipping checks') # get capabilities from driver metadata = gdaltest.netcdf_drv.GetMetadata() if metadata is None: - print('NOTICE: netcdf metadata not found, skipping checks') - return 'skip' + pytest.skip('NOTICE: netcdf metadata not found, skipping checks') # netcdf library version "3.6.3" of Dec 22 2009 06:10:17 $ # netcdf library version 4.1.1 of Mar 4 2011 12:52:19 $ @@ -100,7 +101,12 @@ def netcdf_setup(): gdaltest.count_opened_files = len(gdaltest.get_opened_files()) - return 'success' + +@pytest.fixture(autouse=True, scope='module') +def netcdf_teardown(): + diff = len(gdaltest.get_opened_files()) - gdaltest.count_opened_files + assert diff == 0, 'Leak of file handles: %d leaked' % diff + ############################################################################### # test file copy @@ -121,15 +127,13 @@ def netcdf_test_copy_timeout(ifile, band, checksum, ofile, opts=None, driver='NE from multiprocessing import Process - result = 'success' - drv = gdal.GetDriverByName(driver) if os.path.exists(ofile): drv.Delete(ofile) if timeout is None: - result = netcdf_test_copy(ifile, band, checksum, ofile, opts, driver) + netcdf_test_copy(ifile, band, checksum, ofile, opts, driver) else: sys.stdout.write('.') @@ -146,9 +150,7 @@ def netcdf_test_copy_timeout(ifile, band, checksum, ofile, opts=None, driver='NE if os.path.exists(ofile): drv.Delete(ofile) print('testCreateCopy() for file %s has reached timeout limit of %d seconds' % (ofile, timeout)) - result = 'fail' - - return result + pytest.fail() ############################################################################### # check support for DEFLATE compression, requires HDF5 and zlib @@ -160,44 +162,34 @@ def netcdf_test_deflate(ifile, checksum, zlevel=1, timeout=None): from multiprocessing import Process Process.is_alive except (ImportError, AttributeError): - print('from multiprocessing import Process failed') - return 'skip' + pytest.skip('from multiprocessing import Process failed') if gdaltest.netcdf_drv is None: - return 'skip' + pytest.skip() if not gdaltest.netcdf_drv_has_nc4: - return 'skip' + pytest.skip() ofile1 = 'tmp/' + os.path.basename(ifile) + '-1.nc' ofile1_opts = ['FORMAT=NC4C', 'COMPRESS=NONE'] ofile2 = 'tmp/' + os.path.basename(ifile) + '-2.nc' ofile2_opts = ['FORMAT=NC4C', 'COMPRESS=DEFLATE', 'ZLEVEL=' + str(zlevel)] - if not os.path.exists(ifile): - gdaltest.post_reason('ifile %s does not exist' % ifile) - return 'fail' - - result1 = netcdf_test_copy_timeout(ifile, 1, checksum, ofile1, ofile1_opts, 'NETCDF', timeout) + assert os.path.exists(ifile), ('ifile %s does not exist' % ifile) - result2 = netcdf_test_copy_timeout(ifile, 1, checksum, ofile2, ofile2_opts, 'NETCDF', timeout) + netcdf_test_copy_timeout(ifile, 1, checksum, ofile1, ofile1_opts, 'NETCDF', timeout) - if result1 == 'fail' or result2 == 'fail': - return 'fail' + netcdf_test_copy_timeout(ifile, 1, checksum, ofile2, ofile2_opts, 'NETCDF', timeout) # make sure compressed file is smaller than uncompressed files try: size1 = os.path.getsize(ofile1) size2 = os.path.getsize(ofile2) except OSError: - gdaltest.post_reason('Error getting file sizes.') - return 'fail' + pytest.fail('Error getting file sizes.') - if size2 >= size1: - gdaltest.post_reason('Compressed file is not smaller than reference, check your netcdf-4, HDF5 and zlib installation') - return 'fail' - - return 'success' + assert size2 < size1, \ + 'Compressed file is not smaller than reference, check your netcdf-4, HDF5 and zlib installation' ############################################################################### # check support for reading attributes (single values and array values) @@ -207,57 +199,40 @@ def netcdf_check_vars(ifile, vals_global=None, vals_band=None): src_ds = gdal.Open(ifile) - if src_ds is None: - gdaltest.post_reason('could not open dataset ' + ifile) - return 'fail' + assert src_ds is not None, ('could not open dataset ' + ifile) metadata_global = src_ds.GetMetadata() - if metadata_global is None: - gdaltest.post_reason('could not get global metadata from ' + ifile) - return 'fail' + assert metadata_global is not None, ('could not get global metadata from ' + ifile) missval = src_ds.GetRasterBand(1).GetNoDataValue() - if missval != 1: - gdaltest.post_reason('got invalid nodata value %s for Band' % str(missval)) - return 'fail' + assert missval == 1, ('got invalid nodata value %s for Band' % str(missval)) metadata_band = src_ds.GetRasterBand(1).GetMetadata() - if metadata_band is None: - gdaltest.post_reason('could not get Band metadata') - return 'fail' + assert metadata_band is not None, 'could not get Band metadata' metadata = metadata_global vals = vals_global if vals is None: vals = dict() for k, v in vals.items(): - if k not in metadata: - gdaltest.post_reason("missing metadata [%s]" % (str(k))) - return 'fail' + assert k in metadata, ("missing metadata [%s]" % (str(k))) # strip { and } as new driver uses these for array values mk = metadata[k].lstrip('{ ').rstrip('} ') - if mk != v: - gdaltest.post_reason("invalid value [%s] for metadata [%s]=[%s]" + assert mk == v, ("invalid value [%s] for metadata [%s]=[%s]" % (str(mk), str(k), str(v))) - return 'fail' metadata = metadata_band vals = vals_band if vals is None: vals = dict() for k, v in vals.items(): - if k not in metadata: - gdaltest.post_reason("missing metadata [%s]" % (str(k))) - return 'fail' + assert k in metadata, ("missing metadata [%s]" % (str(k))) # strip { and } as new driver uses these for array values mk = metadata[k].lstrip('{ ').rstrip('} ') - if mk != v: - gdaltest.post_reason("invalid value [%s] for metadata [%s]=[%s]" + assert mk == v, ("invalid value [%s] for metadata [%s]=[%s]" % (str(mk), str(k), str(v))) - return 'fail' - - return 'success' + ############################################################################### # Netcdf Tests @@ -266,13 +241,10 @@ def netcdf_check_vars(ifile, vals_global=None, vals_band=None): ############################################################################### # Perform simple read test. -def netcdf_1(): - - # setup netcdf environment - netcdf_setup() +def test_netcdf_1(): if gdaltest.netcdf_drv is None: - return 'skip' + pytest.skip() tst = gdaltest.GDALTest('NetCDF', 'NETCDF:"data/bug636.nc":tas', 1, 31621, filename_absolute=1) @@ -280,20 +252,18 @@ def netcdf_1(): # We don't want to gum up the test stream output with the # 'Warning 1: No UNIDATA NC_GLOBAL:Conventions attribute' message. gdal.PushErrorHandler('CPLQuietErrorHandler') - result = tst.testOpen() + tst.testOpen() gdal.PopErrorHandler() - return result - ############################################################################### # Verify a simple createcopy operation. We can't do the trivial gdaltest # operation because the new file will only be accessible via subdatasets. -def netcdf_2(): +def test_netcdf_2(): if gdaltest.netcdf_drv is None: - return 'skip' + pytest.skip() src_ds = gdal.Open('data/byte.tif') @@ -322,51 +292,41 @@ def netcdf_2(): AUTHORITY["EPSG","9001"]], AUTHORITY["EPSG","26711"]]""" - result = tst.testOpen(check_prj=wkt) - - if result != 'success': - return result + tst.testOpen(check_prj=wkt) # Test that in raster-only mode, update isn't supported (not sure what would be missing for that...) with gdaltest.error_handler(): ds = gdal.Open('tmp/netcdf2.nc', gdal.GA_Update) - if ds is not None: - gdaltest.post_reason('fail') - return 'fail' + assert ds is None gdaltest.clean_tmp() - return 'success' - ############################################################################### -def netcdf_3(): +def test_netcdf_3(): if gdaltest.netcdf_drv is None: - return 'skip' + pytest.skip() ds = gdal.Open('data/sombrero.grd') bnd = ds.GetRasterBand(1) minmax = bnd.ComputeRasterMinMax() - if abs(minmax[0] - (-0.675758)) > 0.000001 or abs(minmax[1] - 1.0) > 0.000001: - gdaltest.post_reason('Wrong min or max.') - return 'fail' + assert abs(minmax[0] - (-0.675758)) <= 0.000001 and abs(minmax[1] - 1.0) <= 0.000001, \ + 'Wrong min or max.' bnd = None ds = None - return 'success' - ############################################################################### # In #2582 5dimensional files were causing problems. Verify use ok. -def netcdf_4(): +def test_netcdf_4(): if gdaltest.netcdf_drv is None: - return 'skip' + pytest.skip() tst = gdaltest.GDALTest('NetCDF', 'NETCDF:data/foo_5dimensional.nc:temperature', @@ -386,10 +346,10 @@ def netcdf_4(): # dimension - check handling now on band 7. -def netcdf_5(): +def test_netcdf_5(): if gdaltest.netcdf_drv is None: - return 'skip' + pytest.skip() tst = gdaltest.GDALTest('NetCDF', 'NETCDF:data/foo_5dimensional.nc:temperature', @@ -409,10 +369,10 @@ def netcdf_5(): # 1 standard parallel. -def netcdf_6(): +def test_netcdf_6(): if gdaltest.netcdf_drv is None: - return 'skip' + pytest.skip() ds = gdal.Open('data/cf_lcc1sp.nc') prj = ds.GetProjection() @@ -421,24 +381,20 @@ def netcdf_6(): sr.ImportFromWkt(prj) lat_origin = sr.GetProjParm('latitude_of_origin') - if lat_origin != 25: - gdaltest.post_reason('Latitude of origin does not match expected:\n%f' + assert lat_origin == 25, ('Latitude of origin does not match expected:\n%f' % lat_origin) - return 'fail' ds = None - return 'success' - ############################################################################### # ticket #3324 check spatial reference reading for cf-1.4 lambert conformal # 2 standard parallels. -def netcdf_7(): +def test_netcdf_7(): if gdaltest.netcdf_drv is None: - return 'skip' + pytest.skip() ds = gdal.Open('data/cf_lcc2sp.nc') prj = ds.GetProjection() @@ -448,26 +404,23 @@ def netcdf_7(): std_p1 = sr.GetProjParm('standard_parallel_1') std_p2 = sr.GetProjParm('standard_parallel_2') - if std_p1 != 33.0 or std_p2 != 45.0: - gdaltest.post_reason('Standard Parallels do not match expected:\n%f,%f' + assert std_p1 == 33.0 and std_p2 == 45.0, \ + ('Standard Parallels do not match expected:\n%f,%f' % (std_p1, std_p2)) - return 'fail' ds = None sr = None - return 'success' - ############################################################################### # check for cf convention read of albers equal area # Previous version compared entire wkt, which varies slightly among driver versions # now just look for PROJECTION=Albers_Conic_Equal_Area and some parameters -def netcdf_8(): +def test_netcdf_8(): if gdaltest.netcdf_drv is None: - return 'skip' + pytest.skip() ds = gdal.Open('data/cf_aea2sp_invf.nc') @@ -475,32 +428,25 @@ def netcdf_8(): srs.ImportFromWkt(ds.GetProjection()) proj = srs.GetAttrValue('PROJECTION') - if proj != 'Albers_Conic_Equal_Area': - gdaltest.post_reason('Projection does not match expected : ' + proj) - return 'fail' + assert proj == 'Albers_Conic_Equal_Area', \ + ('Projection does not match expected : ' + proj) param = srs.GetProjParm('latitude_of_center') - if param != 37.5: - gdaltest.post_reason('Got wrong parameter value (%g)' % param) - return 'fail' + assert param == 37.5, ('Got wrong parameter value (%g)' % param) param = srs.GetProjParm('longitude_of_center') - if param != -96: - gdaltest.post_reason('Got wrong parameter value (%g)' % param) - return 'fail' + assert param == -96, ('Got wrong parameter value (%g)' % param) ds = None - return 'success' - ############################################################################### # check to see if projected systems default to wgs84 if no spheroid def -def netcdf_9(): +def test_netcdf_9(): if gdaltest.netcdf_drv is None: - return 'skip' + pytest.skip() ds = gdal.Open('data/cf_no_sphere.nc') @@ -510,24 +456,20 @@ def netcdf_9(): sr.ImportFromWkt(prj) spheroid = sr.GetAttrValue('SPHEROID') - if spheroid != 'WGS 84': - gdaltest.post_reason('Incorrect spheroid read from file\n%s' + assert spheroid == 'WGS 84', ('Incorrect spheroid read from file\n%s' % (spheroid)) - return 'fail' ds = None sr = None - return 'success' - ############################################################################### # check if km pixel size makes it through to gt -def netcdf_10(): +def test_netcdf_10(): if gdaltest.netcdf_drv is None: - return 'skip' + pytest.skip() ds = gdal.Open('data/cf_no_sphere.nc') @@ -546,97 +488,81 @@ def netcdf_10(): sr = osr.SpatialReference() sr.ImportFromWkt(prj) # new driver uses UNIT vattribute instead of scaling values - if not (sr.GetAttrValue("PROJCS|UNIT", 1) == "1000" and gt == gt2): - gdaltest.post_reason('Incorrect geotransform, got ' + str(gt)) - return 'fail' + assert (sr.GetAttrValue("PROJCS|UNIT", 1) == "1000" and gt == gt2), \ + ('Incorrect geotransform, got ' + str(gt)) ds = None - return 'success' - ############################################################################### # check if ll gets caught in km pixel size check -def netcdf_11(): +def test_netcdf_11(): if gdaltest.netcdf_drv is None: - return 'skip' + pytest.skip() ds = gdal.Open('data/cf_geog.nc') gt = ds.GetGeoTransform() - if gt != (-0.5, 1.0, 0.0, 10.5, 0.0, -1.0): - - gdaltest.post_reason('Incorrect geotransform') - return 'fail' + assert gt == (-0.5, 1.0, 0.0, 10.5, 0.0, -1.0), 'Incorrect geotransform' ds = None - return 'success' - ############################################################################### # check for scale/offset set/get. -def netcdf_12(): +def test_netcdf_12(): if gdaltest.netcdf_drv is None: - return 'skip' + pytest.skip() ds = gdal.Open('data/scale_offset.nc') scale = ds.GetRasterBand(1).GetScale() offset = ds.GetRasterBand(1).GetOffset() - if scale != 0.01 or offset != 1.5: - gdaltest.post_reason('Incorrect scale(%f) or offset(%f)' % (scale, offset)) - return 'fail' + assert scale == 0.01 and offset == 1.5, \ + ('Incorrect scale(%f) or offset(%f)' % (scale, offset)) ds = None - return 'success' - ############################################################################### # check for scale/offset = None if no scale or offset is available -def netcdf_13(): +def test_netcdf_13(): if gdaltest.netcdf_drv is None: - return 'skip' + pytest.skip() ds = gdal.Open('data/no_scale_offset.nc') scale = ds.GetRasterBand(1).GetScale() offset = ds.GetRasterBand(1).GetOffset() - if scale is not None or offset is not None: - gdaltest.post_reason('Incorrect scale or offset') - return 'fail' + assert scale is None and offset is None, 'Incorrect scale or offset' ds = None - return 'success' - ############################################################################### # check for scale/offset for two variables -def netcdf_14(): +def test_netcdf_14(): if gdaltest.netcdf_drv is None: - return 'skip' + pytest.skip() ds = gdal.Open('NETCDF:data/two_vars_scale_offset.nc:z') scale = ds.GetRasterBand(1).GetScale() offset = ds.GetRasterBand(1).GetOffset() - if scale != 0.01 or offset != 1.5: - gdaltest.post_reason('Incorrect scale(%f) or offset(%f)' % (scale, offset)) - return 'fail' + assert scale == 0.01 and offset == 1.5, \ + ('Incorrect scale(%f) or offset(%f)' % (scale, offset)) ds = None @@ -648,41 +574,36 @@ def netcdf_14(): scale = ds.GetRasterBand(1).GetScale() offset = ds.GetRasterBand(1).GetOffset() - if scale != 0.1 or offset != 2.5: - gdaltest.post_reason('Incorrect scale(%f) or offset(%f)' % (scale, offset)) - return 'fail' - - return 'success' + assert scale == 0.1 and offset == 2.5, \ + ('Incorrect scale(%f) or offset(%f)' % (scale, offset)) ############################################################################### # check support for netcdf-2 (64 bit) # This test fails in 1.8.1, because the driver does not support NC2 (bug #3890) -def netcdf_15(): +def test_netcdf_15(): if gdaltest.netcdf_drv is None: - return 'skip' + pytest.skip() if gdaltest.netcdf_drv_has_nc2: ds = gdal.Open('data/trmm-nc2.nc') - if ds is None: - return 'fail' + assert ds is not None ds = None - return 'success' + return else: - return 'skip' - - return 'success' + pytest.skip() + ############################################################################### # check support for netcdf-4 -def netcdf_16(): +def test_netcdf_16(): if gdaltest.netcdf_drv is None: - return 'skip' + pytest.skip() ifile = 'data/trmm-nc4.nc' @@ -691,77 +612,65 @@ def netcdf_16(): # test with Open() ds = gdal.Open(ifile) if ds is None: - gdaltest.post_reason('GDAL did not open file') - return 'fail' + pytest.fail('GDAL did not open file') else: name = ds.GetDriver().GetDescription() ds = None # return fail if did not open with the netCDF driver (i.e. HDF5Image) - if name != 'netCDF': - gdaltest.post_reason('netcdf driver did not open file') - return 'fail' + assert name == 'netCDF', 'netcdf driver did not open file' # test with Identify() name = gdal.IdentifyDriver(ifile).GetDescription() - if name != 'netCDF': - gdaltest.post_reason('netcdf driver did not identify file') - return 'fail' + assert name == 'netCDF', 'netcdf driver did not identify file' else: - return 'skip' - - return 'success' + pytest.skip() + ############################################################################### # check support for netcdf-4 - make sure hdf5 is not read by netcdf driver -def netcdf_17(): +def test_netcdf_17(): if gdaltest.netcdf_drv is None: - return 'skip' + pytest.skip() ifile = 'data/groups.h5' # skip test if Hdf5 is not enabled if gdal.GetDriverByName('HDF5') is None and \ gdal.GetDriverByName('HDF5Image') is None: - return 'skip' + pytest.skip() if gdaltest.netcdf_drv_has_nc4: # test with Open() ds = gdal.Open(ifile) if ds is None: - gdaltest.post_reason('GDAL did not open hdf5 file') - return 'fail' + pytest.fail('GDAL did not open hdf5 file') else: name = ds.GetDriver().GetDescription() ds = None # return fail if opened with the netCDF driver - if name == 'netCDF': - gdaltest.post_reason('netcdf driver opened hdf5 file') - return 'fail' + assert name != 'netCDF', 'netcdf driver opened hdf5 file' # test with Identify() name = gdal.IdentifyDriver(ifile).GetDescription() - if name == 'netCDF': - gdaltest.post_reason('netcdf driver was identified for hdf5 file') - return 'fail' + assert name != 'netCDF', 'netcdf driver was identified for hdf5 file' else: - return 'skip' - - return 'success' + pytest.skip() + ############################################################################### # check support for netcdf-4 classic (NC4C) -def netcdf_18(): +def test_netcdf_18(): if gdaltest.netcdf_drv is None: - return 'skip' + pytest.skip() ifile = 'data/trmm-nc4c.nc' @@ -770,35 +679,32 @@ def netcdf_18(): # test with Open() ds = gdal.Open(ifile) if ds is None: - return 'fail' + pytest.fail() else: name = ds.GetDriver().GetDescription() ds = None # return fail if did not open with the netCDF driver (i.e. HDF5Image) - if name != 'netCDF': - return 'fail' + assert name == 'netCDF' # test with Identify() name = gdal.IdentifyDriver(ifile).GetDescription() - if name != 'netCDF': - return 'fail' + assert name == 'netCDF' else: - return 'skip' - - return 'success' + pytest.skip() + ############################################################################### # check support for reading with DEFLATE compression, requires NC4 -def netcdf_19(): +def test_netcdf_19(): if gdaltest.netcdf_drv is None: - return 'skip' + pytest.skip() if not gdaltest.netcdf_drv_has_nc4: - return 'skip' + pytest.skip() tst = gdaltest.GDALTest('NetCDF', 'data/trmm-nc4z.nc', 1, 50235, filename_absolute=1) @@ -811,13 +717,13 @@ def netcdf_19(): # check support for writing with DEFLATE compression, requires NC4 -def netcdf_20(): +def test_netcdf_20(): if gdaltest.netcdf_drv is None: - return 'skip' + pytest.skip() if not gdaltest.netcdf_drv_has_nc4: - return 'skip' + pytest.skip() # simple test with tiny file return netcdf_test_deflate('data/utm.tif', 50235) @@ -826,16 +732,16 @@ def netcdf_20(): ############################################################################### # check support for writing large file with DEFLATE compression # if chunking is not defined properly within the netcdf driver, this test can take 1h -def netcdf_21(): +def test_netcdf_21(): if gdaltest.netcdf_drv is None: - return 'skip' + pytest.skip() if not gdaltest.netcdf_drv_has_nc4: - return 'skip' + pytest.skip() if not gdaltest.run_slow_tests(): - return 'skip' + pytest.skip() bigfile = 'tmp/cache/utm-big.tif' @@ -851,8 +757,7 @@ def netcdf_21(): # create large gtiff if test_cli_utilities.get_gdalwarp_path() is None: - gdaltest.post_reason('gdalwarp not found') - return 'skip' + pytest.skip('gdalwarp not found') warp_cmd = test_cli_utilities.get_gdalwarp_path() +\ ' -q -overwrite -r bilinear -ts 7680 7680 -of gtiff ' +\ @@ -861,12 +766,10 @@ def netcdf_21(): try: (ret, err) = gdaltest.runexternal_out_and_err(warp_cmd) except OSError: - gdaltest.post_reason('gdalwarp execution failed') - return 'fail' + pytest.fail('gdalwarp execution failed') - if (err != '' or ret != ''): - gdaltest.post_reason('gdalwarp returned error\n' + str(ret) + ' ' + str(err)) - return 'fail' + assert not (err != '' or ret != ''), \ + ('gdalwarp returned error\n' + str(ret) + ' ' + str(err)) # test compression of the file, with a conservative timeout of 60 seconds return netcdf_test_deflate(bigfile, 26695, 6, 60) @@ -874,13 +777,13 @@ def netcdf_21(): ############################################################################### # check support for hdf4 -def netcdf_22(): +def test_netcdf_22(): if gdaltest.netcdf_drv is None: - return 'skip' + pytest.skip() if not gdaltest.netcdf_drv_has_hdf4: - return 'skip' + pytest.skip() ifile = 'data/hdifftst2.hdf' @@ -890,18 +793,16 @@ def netcdf_22(): gdal.PopErrorHandler() if ds is None: - gdaltest.post_reason('netcdf driver did not open hdf4 file') - return 'fail' + pytest.fail('netcdf driver did not open hdf4 file') else: ds = None - return 'success' - + ############################################################################### # check support for hdf4 - make sure hdf4 file is not read by netcdf driver -def netcdf_23(): +def test_netcdf_23(): # don't skip if netcdf is not enabled in GDAL # if gdaltest.netcdf_drv is None: @@ -912,39 +813,32 @@ def netcdf_23(): # skip test if Hdf4 is not enabled in GDAL if gdal.GetDriverByName('HDF4') is None and \ gdal.GetDriverByName('HDF4Image') is None: - return 'skip' + pytest.skip() ifile = 'data/hdifftst2.hdf' # test with Open() ds = gdal.Open(ifile) if ds is None: - gdaltest.post_reason('GDAL did not open hdf4 file') - return 'fail' + pytest.fail('GDAL did not open hdf4 file') else: name = ds.GetDriver().GetDescription() ds = None # return fail if opened with the netCDF driver - if name == 'netCDF': - gdaltest.post_reason('netcdf driver opened hdf4 file') - return 'fail' + assert name != 'netCDF', 'netcdf driver opened hdf4 file' # test with Identify() name = gdal.IdentifyDriver(ifile).GetDescription() - if name == 'netCDF': - gdaltest.post_reason('netcdf driver was identified for hdf4 file') - return 'fail' - - return 'success' + assert name != 'netCDF', 'netcdf driver was identified for hdf4 file' ############################################################################### # check support for reading attributes (single values and array values) -def netcdf_24(): +def test_netcdf_24(): if gdaltest.netcdf_drv is None: - return 'skip' + pytest.skip() vals_global = {'NC_GLOBAL#test': 'testval', 'NC_GLOBAL#valid_range_i': '0,255', @@ -966,10 +860,10 @@ def netcdf_24(): def netcdf_24_nc4(): if gdaltest.netcdf_drv is None: - return 'skip' + pytest.skip() if not gdaltest.netcdf_drv_has_nc4: - return 'skip' + pytest.skip() vals_global = {'NC_GLOBAL#test': 'testval', 'NC_GLOBAL#test_string': 'testval_string', @@ -998,14 +892,12 @@ def netcdf_24_nc4(): # check support for writing attributes (single values and array values) -def netcdf_25(): +def test_netcdf_25(): if gdaltest.netcdf_drv is None: - return 'skip' + pytest.skip() - result = netcdf_test_copy('data/nc_vars.nc', 1, None, 'tmp/netcdf_25.nc') - if result != 'success': - return result + netcdf_test_copy('data/nc_vars.nc', 1, None, 'tmp/netcdf_25.nc') vals_global = {'NC_GLOBAL#test': 'testval', 'NC_GLOBAL#valid_range_i': '0,255', @@ -1027,14 +919,12 @@ def netcdf_25(): def netcdf_25_nc4(): if gdaltest.netcdf_drv is None: - return 'skip' + pytest.skip() if not gdaltest.netcdf_drv_has_nc4: - return 'skip' + pytest.skip() - result = netcdf_test_copy('data/nc4_vars.nc', 1, None, 'tmp/netcdf_25_nc4.nc', ['FORMAT=NC4']) - if result != 'success': - return result + netcdf_test_copy('data/nc4_vars.nc', 1, None, 'tmp/netcdf_25_nc4.nc', ['FORMAT=NC4']) vals_global = {'NC_GLOBAL#test': 'testval', 'NC_GLOBAL#test_string': 'testval_string', @@ -1065,64 +955,46 @@ def netcdf_25_nc4(): # depending on y-axis order -def netcdf_26(): +def test_netcdf_26(): if gdaltest.netcdf_drv is None: - return 'skip' + pytest.skip() # test default config test = gdaltest.GDALTest('NETCDF', '../data/int16-nogeo.nc', 1, 4672) gdal.PushErrorHandler('CPLQuietErrorHandler') - result = test.testCreateCopy(check_gt=0, check_srs=0, check_minmax=0) + test.testCreateCopy(check_gt=0, check_srs=0, check_minmax=0) gdal.PopErrorHandler() - if result != 'success': - print('failed create copy without WRITE_BOTTOMUP') - return result - # test WRITE_BOTTOMUP=NO test = gdaltest.GDALTest('NETCDF', '../data/int16-nogeo.nc', 1, 4855, options=['WRITE_BOTTOMUP=NO']) - result = test.testCreateCopy(check_gt=0, check_srs=0, check_minmax=0) + test.testCreateCopy(check_gt=0, check_srs=0, check_minmax=0) - if result != 'success': - print('failed create copy with WRITE_BOTTOMUP=NO') - return result - - return 'success' ############################################################################### # check support for GDAL_NETCDF_BOTTOMUP configuration option -def netcdf_27(): +def test_netcdf_27(): if gdaltest.netcdf_drv is None: - return 'skip' + pytest.skip() # test default config test = gdaltest.GDALTest('NETCDF', '../data/int16-nogeo.nc', 1, 4672) config_bak = gdal.GetConfigOption('GDAL_NETCDF_BOTTOMUP') gdal.SetConfigOption('GDAL_NETCDF_BOTTOMUP', None) - result = test.testOpen() + test.testOpen() gdal.SetConfigOption('GDAL_NETCDF_BOTTOMUP', config_bak) - if result != 'success': - print('failed open without GDAL_NETCDF_BOTTOMUP') - return result - # test GDAL_NETCDF_BOTTOMUP=NO test = gdaltest.GDALTest('NETCDF', '../data/int16-nogeo.nc', 1, 4855) config_bak = gdal.GetConfigOption('GDAL_NETCDF_BOTTOMUP') gdal.SetConfigOption('GDAL_NETCDF_BOTTOMUP', 'NO') - result = test.testOpen() + test.testOpen() gdal.SetConfigOption('GDAL_NETCDF_BOTTOMUP', config_bak) - if result != 'success': - print('failed open with GDAL_NETCDF_BOTTOMUP') - return result - - return 'success' ############################################################################### # check support for writing multi-dimensional files (helper function) @@ -1132,17 +1004,14 @@ def netcdf_test_4dfile(ofile): # test result file has 8 bands and 0 subdasets (instead of 0 bands and 8 subdatasets) ds = gdal.Open(ofile) - if ds is None: - gdaltest.post_reason('open of copy failed') - return 'fail' + assert ds is not None, 'open of copy failed' md = ds.GetMetadata('SUBDATASETS') subds_count = 0 if md is not None: subds_count = len(md) / 2 - if ds.RasterCount != 8 or subds_count != 0: - gdaltest.post_reason('copy has %d bands (expected 8) and has %d subdatasets' + assert ds.RasterCount == 8 and subds_count == 0, \ + ('copy has %d bands (expected 8) and has %d subdatasets' ' (expected 0)' % (ds.RasterCount, subds_count)) - return 'fail' ds = None # get file header with ncdump (if available) @@ -1150,14 +1019,12 @@ def netcdf_test_4dfile(ofile): (ret, err) = gdaltest.runexternal_out_and_err('ncdump -h') except OSError: print('NOTICE: ncdump not found') - return 'success' + return if err is None or 'netcdf library version' not in err: print('NOTICE: ncdump not found') - return 'success' + return (ret, err) = gdaltest.runexternal_out_and_err('ncdump -h ' + ofile) - if ret == '' or err != '': - gdaltest.post_reason('ncdump failed') - return 'fail' + assert ret != '' and err == '', 'ncdump failed' # simple dimension tests using ncdump output err = "" @@ -1174,28 +1041,22 @@ def netcdf_test_4dfile(ofile): # uncomment this to get full header in output # if err != '': # err = err + ret - if err != '': - gdaltest.post_reason(err) - return 'fail' - - return 'success' + assert err == '' ############################################################################### # check support for writing multi-dimensional files using CreateCopy() -def netcdf_28(): +def test_netcdf_28(): if gdaltest.netcdf_drv is None: - return 'skip' + pytest.skip() ifile = 'data/netcdf-4d.nc' ofile = 'tmp/netcdf_28.nc' # copy file - result = netcdf_test_copy(ifile, 0, None, ofile) - if result != 'success': - return 'fail' + netcdf_test_copy(ifile, 0, None, ofile) # test file return netcdf_test_4dfile(ofile) @@ -1210,15 +1071,14 @@ def netcdf_28(): # metadata to netcdf file with SetMetadata() and SetMetadataItem()). -def netcdf_29(): +def test_netcdf_29(): if gdaltest.netcdf_drv is None: - return 'skip' + pytest.skip() # create tif file using gdalwarp if test_cli_utilities.get_gdalwarp_path() is None: - gdaltest.post_reason('gdalwarp not found') - return 'skip' + pytest.skip('gdalwarp not found') ifile = 'data/netcdf-4d.nc' ofile1 = 'tmp/netcdf_29.vrt' @@ -1229,33 +1089,25 @@ def netcdf_29(): try: (ret, err) = gdaltest.runexternal_out_and_err(warp_cmd) except OSError: - gdaltest.post_reason('gdalwarp execution failed') - return 'fail' + pytest.fail('gdalwarp execution failed') - if (err != '' or ret != ''): - gdaltest.post_reason('gdalwarp returned error\n' + str(ret) + ' ' + str(err)) - return 'fail' + assert not (err != '' or ret != ''), \ + ('gdalwarp returned error\n' + str(ret) + ' ' + str(err)) # copy vrt to netcdf, with proper dimension rolling - result = netcdf_test_copy(ofile1, 0, None, ofile) - if result != 'success': - return 'fail' + netcdf_test_copy(ofile1, 0, None, ofile) # test file - result = netcdf_test_4dfile(ofile) - if result == 'fail': - print('test failed - does gdalwarp support metadata copying?') - - return result + netcdf_test_4dfile(ofile) ############################################################################### # check support for file with nan values (bug #4705) -def netcdf_30(): +def test_netcdf_30(): if gdaltest.netcdf_drv is None: - return 'skip' + pytest.skip() tst = gdaltest.GDALTest('NetCDF', 'trmm-nan.nc', 1, 62519) @@ -1272,10 +1124,10 @@ def netcdf_30(): # 1 pixel (in width or height) still unsupported because we can't get the pixel dimensions -def netcdf_31(): +def test_netcdf_31(): if gdaltest.netcdf_drv is None: - return 'skip' + pytest.skip() ds = gdal.Open('data/trmm-2x2.nc') @@ -1285,25 +1137,21 @@ def netcdf_31(): gt1 = (-80.0, 0.25, 0.0, -19.5, 0.0, -0.25) - if gt != gt1: - gdaltest.post_reason('Incorrect geotransform, got ' + str(gt)) - return 'fail' + assert gt == gt1, ('Incorrect geotransform, got ' + str(gt)) ds = None - return 'success' - ############################################################################### # Test NC_UBYTE write/read - netcdf-4 (FORMAT=NC4) only (#5053) -def netcdf_32(): +def test_netcdf_32(): if gdaltest.netcdf_drv is None: - return 'skip' + pytest.skip() if not gdaltest.netcdf_drv_has_nc4: - return 'skip' + pytest.skip() ifile = 'data/byte.tif' ofile = 'tmp/netcdf_32.nc' @@ -1311,30 +1159,22 @@ def netcdf_32(): # gdal.SetConfigOption('CPL_DEBUG', 'ON') # test basic read/write - result = netcdf_test_copy(ifile, 1, 4672, ofile, ['FORMAT=NC4']) - if result != 'success': - return 'fail' - result = netcdf_test_copy(ifile, 1, 4672, ofile, ['FORMAT=NC4C']) - if result != 'success': - return 'fail' - - return 'success' + netcdf_test_copy(ifile, 1, 4672, ofile, ['FORMAT=NC4']) + netcdf_test_copy(ifile, 1, 4672, ofile, ['FORMAT=NC4C']) ############################################################################### # TEST NC_UBYTE metadata read - netcdf-4 (FORMAT=NC4) only (#5053) -def netcdf_33(): +def test_netcdf_33(): if gdaltest.netcdf_drv is None: - return 'skip' + pytest.skip() ifile = 'data/nc_vars.nc' ofile = 'tmp/netcdf_33.nc' - result = netcdf_test_copy(ifile, 1, None, ofile, ['FORMAT=NC4']) - if result != 'success': - return result + netcdf_test_copy(ifile, 1, None, ofile, ['FORMAT=NC4']) return netcdf_check_vars('tmp/netcdf_33.nc') @@ -1343,29 +1183,28 @@ def netcdf_33(): # if chunking is not supported within the netcdf driver, this test can take very long -def netcdf_34(): +def test_netcdf_34(): filename = 'utm-big-chunks.nc' # this timeout is more than enough - on my system takes <1s with fix, about 25 seconds without timeout = 5 if gdaltest.netcdf_drv is None: - return 'skip' + pytest.skip() if not gdaltest.netcdf_drv_has_nc4: - return 'skip' + pytest.skip() if not gdaltest.run_slow_tests(): - return 'skip' + pytest.skip() try: from multiprocessing import Process except ImportError: - print('from multiprocessing import Process failed') - return 'skip' + pytest.skip('from multiprocessing import Process failed') if not gdaltest.download_file('http://download.osgeo.org/gdal/data/netcdf/' + filename, filename): - return 'skip' + pytest.skip() sys.stdout.write('.') sys.stdout.flush() @@ -1383,179 +1222,135 @@ def netcdf_34(): # valgrind detects memory leaks when this occurs (although it should never happen) if proc.is_alive(): proc.terminate() - print('testOpen() for file %s has reached timeout limit of %d seconds' % (filename, timeout)) - return 'fail' - - return 'success' + pytest.fail('testOpen() for file %s has reached timeout limit of %d seconds' % (filename, timeout)) + ############################################################################### # test writing a long metadata > 8196 chars (bug #5113) -def netcdf_35(): +def test_netcdf_35(): if gdaltest.netcdf_drv is None: - return 'skip' + pytest.skip() ifile = 'data/netcdf_fixes.nc' ofile = 'tmp/netcdf_35.nc' # copy file - result = netcdf_test_copy(ifile, 0, None, ofile) - if result != 'success': - return 'fail' + netcdf_test_copy(ifile, 0, None, ofile) # test long metadata is copied correctly ds = gdal.Open(ofile) - if ds is None: - gdaltest.post_reason('open of copy failed') - return 'fail' + assert ds is not None, 'open of copy failed' md = ds.GetMetadata('') - if 'U#bla' not in md: - gdaltest.post_reason('U#bla metadata absent') - return 'fail' + assert 'U#bla' in md, 'U#bla metadata absent' bla = md['U#bla'] - if not len(bla) == 9591: - gdaltest.post_reason('U#bla metadata is of length %d, expecting %d' % (len(bla), 9591)) - return 'fail' - if not bla[-4:] == '_bla': - gdaltest.post_reason('U#bla metadata ends with [%s], expecting [%s]' % (bla[-4:], '_bla')) - return 'fail' - - return 'success' + assert len(bla) == 9591, \ + ('U#bla metadata is of length %d, expecting %d' % (len(bla), 9591)) + assert bla[-4:] == '_bla', \ + ('U#bla metadata ends with [%s], expecting [%s]' % (bla[-4:], '_bla')) ############################################################################### # test for correct geotransform (bug #5114) -def netcdf_36(): +def test_netcdf_36(): if gdaltest.netcdf_drv is None: - return 'skip' + pytest.skip() ifile = 'data/netcdf_fixes.nc' ds = gdal.Open(ifile) - if ds is None: - gdaltest.post_reason('open failed') - return 'fail' + assert ds is not None, 'open failed' gt = ds.GetGeoTransform() - if gt is None: - gdaltest.post_reason('got no GeoTransform') - return 'fail' + assert gt is not None, 'got no GeoTransform' gt_expected = (-3.498749944898817, 0.0025000042385525173, 0.0, 46.61749818589952, 0.0, -0.001666598849826389) - if gt != gt_expected: - gdaltest.post_reason('got GeoTransform %s, expected %s' % (str(gt), str(gt_expected))) - return 'fail' - - return 'success' + assert gt == gt_expected, \ + ('got GeoTransform %s, expected %s' % (str(gt), str(gt_expected))) ############################################################################### # test for correct geotransform with longitude wrap -def netcdf_36_lonwrap(): +def test_netcdf_36_lonwrap(): if gdaltest.netcdf_drv is None: - return 'skip' + pytest.skip() ifile = 'data/nc_lonwrap.nc' ds = gdal.Open(ifile) - if ds is None: - gdaltest.post_reason('open failed') - return 'fail' + assert ds is not None, 'open failed' gt = ds.GetGeoTransform() - if gt is None: - gdaltest.post_reason('got no GeoTransform') - return 'fail' + assert gt is not None, 'got no GeoTransform' gt_expected = (-2.25, 2.5, 0.0, 16.25, 0.0, -2.5) - if gt != gt_expected: - gdaltest.post_reason('got GeoTransform %s, expected %s' % (str(gt), str(gt_expected))) - return 'fail' - - return 'success' + assert gt == gt_expected, \ + ('got GeoTransform %s, expected %s' % (str(gt), str(gt_expected))) ############################################################################### # test for reading gaussian grid (bugs #4513 and #5118) -def netcdf_37(): +def test_netcdf_37(): if gdaltest.netcdf_drv is None: - return 'skip' + pytest.skip() ifile = 'data/reduce-cgcms.nc' gdal.PushErrorHandler('CPLQuietErrorHandler') ds = gdal.Open(ifile) gdal.PopErrorHandler() - if ds is None: - gdaltest.post_reason('open failed') - return 'fail' + assert ds is not None, 'open failed' gt = ds.GetGeoTransform() - if gt is None: - gdaltest.post_reason('got no GeoTransform') - return 'fail' + assert gt is not None, 'got no GeoTransform' gt_expected = (-1.875, 3.75, 0.0, 89.01354337620016, 0.0, -3.7088976406750063) - if gt != gt_expected: - gdaltest.post_reason('got GeoTransform %s, expected %s' % (str(gt), str(gt_expected))) - return 'fail' + assert gt == gt_expected, \ + ('got GeoTransform %s, expected %s' % (str(gt), str(gt_expected))) md = ds.GetMetadata('GEOLOCATION2') - if not md or 'Y_VALUES' not in md: - gdaltest.post_reason('did not get 1D geolocation') - return 'fail' + assert md and 'Y_VALUES' in md, 'did not get 1D geolocation' y_vals = md['Y_VALUES'] - if not y_vals.startswith('{-87.15909455586265,-83.47893666931698,') \ - or not y_vals.endswith(',83.47893666931698,87.15909455586265}'): - gdaltest.post_reason('got incorrect values in 1D geolocation') - return 'fail' - - return 'success' + assert y_vals.startswith('{-87.15909455586265,-83.47893666931698,') and y_vals.endswith(',83.47893666931698,87.15909455586265}'), \ + 'got incorrect values in 1D geolocation' ############################################################################### # test for correct geotransform of projected data in km units (bug #5118) -def netcdf_38(): +def test_netcdf_38(): if gdaltest.netcdf_drv is None: - return 'skip' + pytest.skip() ifile = 'data/bug5118.nc' gdal.PushErrorHandler('CPLQuietErrorHandler') ds = gdal.Open(ifile) gdal.PopErrorHandler() - if ds is None: - gdaltest.post_reason('open failed') - return 'fail' + assert ds is not None, 'open failed' gt = ds.GetGeoTransform() - if gt is None: - gdaltest.post_reason('got no GeoTransform') - return 'fail' + assert gt is not None, 'got no GeoTransform' gt_expected = (-1659.3478178136488, 13.545000861672793, 0.0, 2330.054725283668, 0.0, -13.54499744233631) - if gt != gt_expected: - gdaltest.post_reason('got GeoTransform %s, expected %s' % (str(gt), str(gt_expected))) - return 'fail' - - return 'success' + assert gt == gt_expected, \ + ('got GeoTransform %s, expected %s' % (str(gt), str(gt_expected))) ############################################################################### # Test VRT and NETCDF: -def netcdf_39(): +def test_netcdf_39(): if gdaltest.netcdf_drv is None: - return 'skip' + pytest.skip() shutil.copy('data/two_vars_scale_offset.nc', 'tmp') src_ds = gdal.Open('NETCDF:tmp/two_vars_scale_offset.nc:z') @@ -1569,10 +1364,7 @@ def netcdf_39(): gdal.Unlink('tmp/two_vars_scale_offset.nc') gdal.Unlink('tmp/netcdf_39.vrt') - if cs != 65463: - gdaltest.post_reason('failure') - print(cs) - return 'fail' + assert cs == 65463 shutil.copy('data/two_vars_scale_offset.nc', 'tmp') src_ds = gdal.Open('NETCDF:"tmp/two_vars_scale_offset.nc":z') @@ -1586,10 +1378,7 @@ def netcdf_39(): gdal.Unlink('tmp/two_vars_scale_offset.nc') gdal.Unlink('tmp/netcdf_39.vrt') - if cs != 65463: - gdaltest.post_reason('failure') - print(cs) - return 'fail' + assert cs == 65463 shutil.copy('data/two_vars_scale_offset.nc', 'tmp') src_ds = gdal.Open('NETCDF:"%s/tmp/two_vars_scale_offset.nc":z' % os.getcwd()) @@ -1603,10 +1392,7 @@ def netcdf_39(): gdal.Unlink('tmp/two_vars_scale_offset.nc') gdal.Unlink('tmp/netcdf_39.vrt') - if cs != 65463: - gdaltest.post_reason('failure') - print(cs) - return 'fail' + assert cs == 65463 src_ds = gdal.Open('NETCDF:"%s/data/two_vars_scale_offset.nc":z' % os.getcwd()) out_ds = gdal.GetDriverByName('VRT').CreateCopy('tmp/netcdf_39.vrt', src_ds) @@ -1618,21 +1404,16 @@ def netcdf_39(): ds = None gdal.Unlink('tmp/netcdf_39.vrt') - if cs != 65463: - gdaltest.post_reason('failure') - print(cs) - return 'fail' - - return 'success' + assert cs == 65463 ############################################################################### # Check support of reading of chunked bottom-up files. -def netcdf_40(): +def test_netcdf_40(): if gdaltest.netcdf_drv is None or not gdaltest.netcdf_drv_has_nc4: - return 'skip' + pytest.skip() return netcdf_test_copy('data/bug5291.nc', 0, None, 'tmp/netcdf_40.nc') @@ -1640,32 +1421,24 @@ def netcdf_40(): # Test support for georeferenced file without CF convention -def netcdf_41(): +def test_netcdf_41(): if gdaltest.netcdf_drv is None: - return 'skip' + pytest.skip() with gdaltest.error_handler(): ds = gdal.Open('data/byte_no_cf.nc') - if ds.GetGeoTransform() != (440720, 60, 0, 3751320, 0, -60): - gdaltest.post_reason('failure') - print(ds.GetGeoTransform()) - return 'fail' - if ds.GetProjectionRef().find('26711') < 0: - gdaltest.post_reason('failure') - print(ds.GetGeoTransform()) - return 'fail' - - return 'success' + assert ds.GetGeoTransform() == (440720, 60, 0, 3751320, 0, -60) + assert ds.GetProjectionRef().find('26711') >= 0, ds.GetGeoTransform() ############################################################################### # Test writing & reading GEOLOCATION array -def netcdf_42(): +def test_netcdf_42(): if gdaltest.netcdf_drv is None: - return 'skip' + pytest.skip() src_ds = gdal.GetDriverByName('MEM').Create('', 60, 39, 1) src_ds.SetMetadata([ @@ -1685,7 +1458,7 @@ def netcdf_42(): gdaltest.netcdf_drv.CreateCopy('tmp/netcdf_42.nc', src_ds) ds = gdal.Open('tmp/netcdf_42.nc') - if ds.GetMetadata('GEOLOCATION') != { + assert (ds.GetMetadata('GEOLOCATION') == { 'LINE_OFFSET': '0', 'X_DATASET': 'NETCDF:"tmp/netcdf_42.nc":lon', 'PIXEL_STEP': '1', @@ -1694,39 +1467,28 @@ def netcdf_42(): 'X_BAND': '1', 'LINE_STEP': '1', 'Y_DATASET': 'NETCDF:"tmp/netcdf_42.nc":lat', - 'Y_BAND': '1'}: - gdaltest.post_reason('failure') - print(ds.GetMetadata('GEOLOCATION')) - return 'fail' + 'Y_BAND': '1'}) ds = gdal.Open('NETCDF:"tmp/netcdf_42.nc":lon') - if ds.GetRasterBand(1).Checksum() != 36043: - gdaltest.post_reason('failure') - print(ds.GetRasterBand(1).Checksum()) - return 'fail' + assert ds.GetRasterBand(1).Checksum() == 36043 ds = gdal.Open('NETCDF:"tmp/netcdf_42.nc":lat') - if ds.GetRasterBand(1).Checksum() != 33501: - gdaltest.post_reason('failure') - print(ds.GetRasterBand(1).Checksum()) - return 'fail' - - return 'success' + assert ds.GetRasterBand(1).Checksum() == 33501 ############################################################################### # Test reading GEOLOCATION array from geotransform (non default) -def netcdf_43(): +def test_netcdf_43(): if gdaltest.netcdf_drv is None: - return 'skip' + pytest.skip() src_ds = gdal.Open('data/byte.tif') gdaltest.netcdf_drv.CreateCopy('tmp/netcdf_43.nc', src_ds, options=['WRITE_LONLAT=YES']) ds = gdal.Open('tmp/netcdf_43.nc') - if ds.GetMetadata('GEOLOCATION') != { + assert (ds.GetMetadata('GEOLOCATION') == { 'LINE_OFFSET': '0', 'X_DATASET': 'NETCDF:"tmp/netcdf_43.nc":lon', 'PIXEL_STEP': '1', @@ -1735,52 +1497,39 @@ def netcdf_43(): 'X_BAND': '1', 'LINE_STEP': '1', 'Y_DATASET': 'NETCDF:"tmp/netcdf_43.nc":lat', - 'Y_BAND': '1'}: - gdaltest.post_reason('failure') - print(ds.GetMetadata('GEOLOCATION')) - return 'fail' - - return 'success' + 'Y_BAND': '1'}) ############################################################################### # Test NC_USHORT/UINT read/write - netcdf-4 only (#6337) -def netcdf_44(): +def test_netcdf_44(): if gdaltest.netcdf_drv is None: - return 'skip' + pytest.skip() if not gdaltest.netcdf_drv_has_nc4: - return 'skip' + pytest.skip() for f, md5 in ('data/ushort.nc', 18), ('data/uint.nc', 10): - if (netcdf_test_copy(f, 1, md5, 'tmp/netcdf_44.nc', ['FORMAT=NC4']) != - 'success'): - return 'fail' - - return 'success' + netcdf_test_copy(f, 1, md5, 'tmp/netcdf_44.nc', ['FORMAT=NC4']) ############################################################################### # Test reading a vector NetCDF 3 file -def netcdf_45(): +def test_netcdf_45(): if gdaltest.netcdf_drv is None: - return 'skip' + pytest.skip() # Test that a vector cannot be opened in raster-only mode ds = gdal.OpenEx('data/test_ogr_nc3.nc', gdal.OF_RASTER) - if ds is not None: - gdaltest.post_reason('fail') - return 'fail' + assert ds is None # Test that a raster cannot be opened in vector-only mode ds = gdal.OpenEx('data/cf-bug636.nc', gdal.OF_VECTOR) - if ds is not None: - gdaltest.post_reason('fail') - return 'fail' + assert ds is None ds = gdal.OpenEx('data/test_ogr_nc3.nc', gdal.OF_VECTOR) @@ -1796,10 +1545,7 @@ def netcdf_45(): "POINT (1 2)",,,,,,,,,,,,,,,,,,,, ,,,,,,,,,,,,,,,,,,,, """ - if content != expected_content: - gdaltest.post_reason('failure') - print(content) - return 'fail' + assert content == expected_content fp = gdal.VSIFOpenL('/vsimem/netcdf_45.csvt', 'rb') if fp is not None: @@ -1807,54 +1553,43 @@ def netcdf_45(): gdal.VSIFCloseL(fp) expected_content = """WKT,Integer,Integer,Real,Real,String(1),String(3),String,Date,DateTime,DateTime,Integer64,Integer64,Integer(Boolean),Integer(Boolean),Real(Float32),Real(Float32),Integer(Int16),Integer(Int16),Real,Integer """ - if content != expected_content: - gdaltest.post_reason('failure') - print(content) - return 'fail' + assert content == expected_content gdal.Unlink('/vsimem/netcdf_45.csv') gdal.Unlink('/vsimem/netcdf_45.csvt') gdal.Unlink('/vsimem/netcdf_45.prj') - return 'success' - ############################################################################### # Test reading a vector NetCDF 3 file -def netcdf_46(): +def test_netcdf_46(): if gdaltest.netcdf_drv is None: - return 'skip' + pytest.skip() if test_cli_utilities.get_test_ogrsf_path() is None: - return 'skip' + pytest.skip() ret = gdaltest.runexternal(test_cli_utilities.get_test_ogrsf_path() + ' -ro data/test_ogr_nc3.nc') - if ret.find('INFO') == -1 or ret.find('ERROR') != -1: - print(ret) - return 'fail' - - return 'success' + assert ret.find('INFO') != -1 and ret.find('ERROR') == -1 ############################################################################### # Test reading a vector NetCDF 4 file -def netcdf_47(): +def test_netcdf_47(): if gdaltest.netcdf_drv is None: - return 'skip' + pytest.skip() if not gdaltest.netcdf_drv_has_nc4: - return 'skip' + pytest.skip() # Test that a vector cannot be opened in raster-only mode with gdaltest.error_handler(): ds = gdal.OpenEx('data/test_ogr_nc4.nc', gdal.OF_RASTER) - if ds is not None: - gdaltest.post_reason('fail') - return 'fail' + assert ds is None ds = gdal.OpenEx('data/test_ogr_nc4.nc', gdal.OF_VECTOR) @@ -1870,10 +1605,7 @@ def netcdf_47(): "POINT (1 2)",,,,,,,,,,,,,,,,,,,,,,,,,,, ,,,,,,,,,,,,,,,,,,,,,,,,,,, """ - if content != expected_content: - gdaltest.post_reason('failure') - print(content) - return 'fail' + assert content == expected_content fp = gdal.VSIFOpenL('/vsimem/netcdf_47.csvt', 'rb') if fp is not None: @@ -1881,46 +1613,35 @@ def netcdf_47(): gdal.VSIFCloseL(fp) expected_content = """WKT,Integer,Integer,Real,Real,String(3),String,Date,DateTime,DateTime,Integer64,Integer64,Integer(Boolean),Integer(Boolean),Real(Float32),Real(Float32),Integer(Int16),Integer(Int16),Real,Integer,Integer,Integer,Integer,Integer,Integer64,Integer64,Real,Real """ - if content != expected_content: - gdaltest.post_reason('failure') - print(content) - return 'fail' + assert content == expected_content gdal.Unlink('/vsimem/netcdf_47.csv') gdal.Unlink('/vsimem/netcdf_47.csvt') gdal.Unlink('/vsimem/netcdf_47.prj') - return 'success' - ############################################################################### # Test reading a vector NetCDF 3 file without any geometry -def netcdf_48(): +def test_netcdf_48(): if gdaltest.netcdf_drv is None: - return 'skip' + pytest.skip() with gdaltest.error_handler(): ds = gdal.OpenEx('data/test_ogr_no_xyz_var.nc', gdal.OF_VECTOR) lyr = ds.GetLayer(0) - if lyr.GetGeomType() != ogr.wkbNone: - gdaltest.post_reason('failure') - return 'fail' + assert lyr.GetGeomType() == ogr.wkbNone f = lyr.GetNextFeature() - if f['int32'] != 1: - gdaltest.post_reason('failure') - return 'fail' - - return 'success' + assert f['int32'] == 1 ############################################################################### # Test reading a vector NetCDF 3 file with X,Y,Z vars as float -def netcdf_49(): +def test_netcdf_49(): if gdaltest.netcdf_drv is None: - return 'skip' + pytest.skip() with gdaltest.error_handler(): ds = gdal.OpenEx('data/test_ogr_xyz_float.nc', gdal.OF_VECTOR) @@ -1935,23 +1656,18 @@ def netcdf_49(): "POINT (1 2)", ,, """ - if content != expected_content: - gdaltest.post_reason('failure') - print(content) - return 'fail' + assert content == expected_content gdal.Unlink('/vsimem/netcdf_49.csv') - return 'success' - ############################################################################### # Test creating a vector NetCDF 3 file with WKT geometry field -def netcdf_50(): +def test_netcdf_50(): if gdaltest.netcdf_drv is None: - return 'skip' + pytest.skip() ds = gdal.OpenEx('../ogr/data/poly.shp', gdal.OF_VECTOR) out_ds = gdal.VectorTranslate('tmp/netcdf_50.nc', ds, format='netCDF', layerCreationOptions=['WKT_DEFAULT_WIDTH=1']) @@ -1965,42 +1681,29 @@ def netcdf_50(): out_f.SetFID(-1) src_json = src_f.ExportToJson() out_json = out_f.ExportToJson() - if src_json != out_json: - gdaltest.post_reason('failure') - print(src_json) - print(out_json) - return 'fail' + assert src_json == out_json out_ds = None out_ds = gdal.OpenEx('tmp/netcdf_50.nc', gdal.OF_VECTOR) out_lyr = out_ds.GetLayer(0) srs = out_lyr.GetSpatialRef().ExportToWkt() - if srs.find('PROJCS["OSGB 1936') < 0: - gdaltest.post_reason('failure') - print(srs) - return 'fail' + assert srs.find('PROJCS["OSGB 1936') >= 0 out_f = out_lyr.GetNextFeature() out_f.SetFID(-1) out_json = out_f.ExportToJson() - if src_json != out_json: - gdaltest.post_reason('failure') - print(src_json) - print(out_json) - return 'fail' + assert src_json == out_json out_ds = None gdal.Unlink('tmp/netcdf_50.nc') - return 'success' - ############################################################################### # Test creating a vector NetCDF 3 file with X,Y,Z fields -def netcdf_51(): +def test_netcdf_51(): if gdaltest.netcdf_drv is None: - return 'skip' + pytest.skip() ds = gdal.OpenEx('data/test_ogr_nc3.nc', gdal.OF_VECTOR) # Test autogrow of string fields @@ -2020,10 +1723,7 @@ def netcdf_51(): "POINT Z (1 2 0)",,,,,,,,,,,,,,,,,,,, ,,,,,,,,,,,,,,,,,,,, """ - if content != expected_content: - gdaltest.post_reason('failure') - print(content) - return 'fail' + assert content == expected_content fp = gdal.VSIFOpenL('/vsimem/netcdf_51.csvt', 'rb') if fp is not None: @@ -2031,42 +1731,30 @@ def netcdf_51(): gdal.VSIFCloseL(fp) expected_content = """WKT,Integer,Integer,Real,Real,String(1),String(3),String,Date,DateTime,DateTime,Integer64,Integer64,Integer(Boolean),Integer(Boolean),Real(Float32),Real(Float32),Integer(Int16),Integer(Int16),Real,Integer """ - if content != expected_content: - gdaltest.post_reason('failure') - print(content) - return 'fail' + assert content == expected_content ds = gdal.OpenEx('tmp/netcdf_51.nc', gdal.OF_VECTOR | gdal.OF_UPDATE) lyr = ds.GetLayer(0) lyr.CreateField(ogr.FieldDefn('extra', ogr.OFTInteger)) lyr.CreateField(ogr.FieldDefn('extra_str', ogr.OFTString)) f = lyr.GetNextFeature() - if f is None: - gdaltest.post_reason('failure') - return 'fail' + assert f is not None f['extra'] = 5 f['extra_str'] = 'foobar' - if lyr.CreateFeature(f) != 0: - gdaltest.post_reason('failure') - return 'fail' + assert lyr.CreateFeature(f) == 0 ds = None ds = gdal.OpenEx('tmp/netcdf_51.nc', gdal.OF_VECTOR) lyr = ds.GetLayer(0) f = lyr.GetFeature(lyr.GetFeatureCount()) - if f['int32'] != 1 or f['extra'] != 5 or f['extra_str'] != 'foobar': - gdaltest.post_reason('failure') - return 'fail' + assert f['int32'] == 1 and f['extra'] == 5 and f['extra_str'] == 'foobar' f = None ds = None import netcdf_cf - if netcdf_cf.netcdf_cf_setup() == 'success' and \ - gdaltest.netcdf_cf_method is not None: - result_cf = netcdf_cf.netcdf_cf_check_file('tmp/netcdf_51.nc', 'auto', False) - if result_cf != 'success': - gdaltest.post_reason('failure') - return 'fail' + netcdf_cf.netcdf_cf_setup() + if gdaltest.netcdf_cf_method is not None: + netcdf_cf.netcdf_cf_check_file('tmp/netcdf_51.nc', 'auto', False) gdal.Unlink('tmp/netcdf_51.nc') gdal.Unlink('tmp/netcdf_51.csv') @@ -2075,16 +1763,14 @@ def netcdf_51(): gdal.Unlink('/vsimem/netcdf_51.csvt') gdal.Unlink('/vsimem/netcdf_51.prj') - return 'success' - ############################################################################### # Test creating a vector NetCDF 3 file with X,Y,Z fields with WRITE_GDAL_TAGS=NO -def netcdf_51_no_gdal_tags(): +def test_netcdf_51_no_gdal_tags(): if gdaltest.netcdf_drv is None: - return 'skip' + pytest.skip() ds = gdal.OpenEx('data/test_ogr_nc3.nc', gdal.OF_VECTOR) gdal.VectorTranslate('tmp/netcdf_51_no_gdal_tags.nc', ds, format='netCDF', datasetCreationOptions=['WRITE_GDAL_TAGS=NO']) @@ -2103,10 +1789,7 @@ def netcdf_51_no_gdal_tags(): "POINT Z (1 2 0)",,,,,,,,,,,,,,,,,,,, ,,,,,,,,,,,,,,,,,,,, """ - if content != expected_content: - gdaltest.post_reason('failure') - print(content) - return 'fail' + assert content == expected_content fp = gdal.VSIFOpenL('/vsimem/netcdf_51_no_gdal_tags.csvt', 'rb') if fp is not None: @@ -2114,10 +1797,7 @@ def netcdf_51_no_gdal_tags(): gdal.VSIFCloseL(fp) expected_content = """WKT,Integer,Integer,Real,Real,String(1),String(3),String(10),Date,DateTime,DateTime,Real,Real,Integer,Integer,Real(Float32),Real(Float32),Integer(Int16),Integer(Int16),Real,Integer """ - if content != expected_content: - gdaltest.post_reason('failure') - print(content) - return 'fail' + assert content == expected_content gdal.Unlink('tmp/netcdf_51_no_gdal_tags.nc') gdal.Unlink('tmp/netcdf_51_no_gdal_tags.csv') @@ -2126,19 +1806,17 @@ def netcdf_51_no_gdal_tags(): gdal.Unlink('/vsimem/netcdf_51_no_gdal_tags.csvt') gdal.Unlink('/vsimem/netcdf_51_no_gdal_tags.prj') - return 'success' - ############################################################################### # Test creating a vector NetCDF 4 file with X,Y,Z fields -def netcdf_52(): +def test_netcdf_52(): if gdaltest.netcdf_drv is None: - return 'skip' + pytest.skip() if not gdaltest.netcdf_drv_has_nc4: - return 'skip' + pytest.skip() ds = gdal.OpenEx('data/test_ogr_nc4.nc', gdal.OF_VECTOR) gdal.VectorTranslate('tmp/netcdf_52.nc', ds, format='netCDF', datasetCreationOptions=['FORMAT=NC4']) @@ -2157,10 +1835,7 @@ def netcdf_52(): "POINT Z (1 2 0)",,,,,,,,,,,,,,,,,,,,,,,,,,, ,,,,,,,,,,,,,,,,,,,,,,,,,,, """ - if content != expected_content: - gdaltest.post_reason('failure') - print(content) - return 'fail' + assert content == expected_content fp = gdal.VSIFOpenL('/vsimem/netcdf_52.csvt', 'rb') if fp is not None: @@ -2168,40 +1843,28 @@ def netcdf_52(): gdal.VSIFCloseL(fp) expected_content = """WKT,Integer,Integer,Real,Real,String(3),String,Date,DateTime,DateTime,Integer64,Integer64,Integer(Boolean),Integer(Boolean),Real(Float32),Real(Float32),Integer(Int16),Integer(Int16),Real,Integer,Integer,Integer,Integer,Integer,Integer64,Integer64,Real,Real """ - if content != expected_content: - gdaltest.post_reason('failure') - print(content) - return 'fail' + assert content == expected_content ds = gdal.OpenEx('tmp/netcdf_52.nc', gdal.OF_VECTOR | gdal.OF_UPDATE) lyr = ds.GetLayer(0) lyr.CreateField(ogr.FieldDefn('extra', ogr.OFTInteger)) f = lyr.GetNextFeature() - if f is None: - gdaltest.post_reason('failure') - return 'fail' + assert f is not None f['extra'] = 5 - if lyr.CreateFeature(f) != 0: - gdaltest.post_reason('failure') - return 'fail' + assert lyr.CreateFeature(f) == 0 ds = None ds = gdal.OpenEx('tmp/netcdf_52.nc', gdal.OF_VECTOR) lyr = ds.GetLayer(0) f = lyr.GetFeature(lyr.GetFeatureCount()) - if f['int32'] != 1 or f['extra'] != 5: - gdaltest.post_reason('failure') - return 'fail' + assert f['int32'] == 1 and f['extra'] == 5 f = None ds = None import netcdf_cf - if netcdf_cf.netcdf_cf_setup() == 'success' and \ - gdaltest.netcdf_cf_method is not None: - result_cf = netcdf_cf.netcdf_cf_check_file('tmp/netcdf_52.nc', 'auto', False) - if result_cf != 'success': - gdaltest.post_reason('failure') - return 'fail' + netcdf_cf.netcdf_cf_setup() + if gdaltest.netcdf_cf_method is not None: + netcdf_cf.netcdf_cf_check_file('tmp/netcdf_52.nc', 'auto', False) gdal.Unlink('tmp/netcdf_52.nc') gdal.Unlink('tmp/netcdf_52.csv') @@ -2210,19 +1873,17 @@ def netcdf_52(): gdal.Unlink('/vsimem/netcdf_52.csvt') gdal.Unlink('/vsimem/netcdf_52.prj') - return 'success' - ############################################################################### # Test creating a vector NetCDF 4 file with WKT geometry field -def netcdf_53(): +def test_netcdf_53(): if gdaltest.netcdf_drv is None: - return 'skip' + pytest.skip() if not gdaltest.netcdf_drv_has_nc4: - return 'skip' + pytest.skip() ds = gdal.OpenEx('../ogr/data/poly.shp', gdal.OF_VECTOR) out_ds = gdal.VectorTranslate('tmp/netcdf_53.nc', ds, format='netCDF', datasetCreationOptions=['FORMAT=NC4']) @@ -2236,61 +1897,44 @@ def netcdf_53(): out_f.SetFID(-1) src_json = src_f.ExportToJson() out_json = out_f.ExportToJson() - if src_json != out_json: - gdaltest.post_reason('failure') - print(src_json) - print(out_json) - return 'fail' + assert src_json == out_json out_ds = None out_ds = gdal.OpenEx('tmp/netcdf_53.nc', gdal.OF_VECTOR) out_lyr = out_ds.GetLayer(0) srs = out_lyr.GetSpatialRef().ExportToWkt() - if srs.find('PROJCS["OSGB 1936') < 0: - gdaltest.post_reason('failure') - print(srs) - return 'fail' + assert srs.find('PROJCS["OSGB 1936') >= 0 out_f = out_lyr.GetNextFeature() out_f.SetFID(-1) out_json = out_f.ExportToJson() - if src_json != out_json: - gdaltest.post_reason('failure') - print(src_json) - print(out_json) - return 'fail' + assert src_json == out_json out_ds = None gdal.Unlink('tmp/netcdf_53.nc') - return 'success' - ############################################################################### # Test appending to a vector NetCDF 4 file with unusual types (ubyte, ushort...) -def netcdf_54(): +def test_netcdf_54(): if gdaltest.netcdf_drv is None: - return 'skip' + pytest.skip() if not gdaltest.netcdf_drv_has_nc4: - return 'skip' + pytest.skip() shutil.copy('data/test_ogr_nc4.nc', 'tmp/netcdf_54.nc') ds = gdal.OpenEx('tmp/netcdf_54.nc', gdal.OF_VECTOR | gdal.OF_UPDATE) lyr = ds.GetLayer(0) f = lyr.GetNextFeature() - if f is None: - gdaltest.post_reason('failure') - return 'fail' + assert f is not None f['int32'] += 1 f.SetFID(-1) f.ExportToJson() src_json = f.ExportToJson() - if lyr.CreateFeature(f) != 0: - gdaltest.post_reason('failure') - return 'fail' + assert lyr.CreateFeature(f) == 0 ds = None ds = gdal.OpenEx('tmp/netcdf_54.nc', gdal.OF_VECTOR) @@ -2303,41 +1947,31 @@ def netcdf_54(): gdal.Unlink('tmp/netcdf_54.nc') - if src_json != out_json: - gdaltest.post_reason('failure') - print(src_json) - print(out_json) - return 'fail' - - return 'success' + assert src_json == out_json ############################################################################### # Test auto-grow of bidimensional char variables in a vector NetCDF 4 file -def netcdf_55(): +def test_netcdf_55(): if gdaltest.netcdf_drv is None: - return 'skip' + pytest.skip() if not gdaltest.netcdf_drv_has_nc4: - return 'skip' + pytest.skip() shutil.copy('data/test_ogr_nc4.nc', 'tmp/netcdf_55.nc') ds = gdal.OpenEx('tmp/netcdf_55.nc', gdal.OF_VECTOR | gdal.OF_UPDATE) lyr = ds.GetLayer(0) f = lyr.GetNextFeature() - if f is None: - gdaltest.post_reason('failure') - return 'fail' + assert f is not None f['twodimstringchar'] = 'abcd' f.SetFID(-1) f.ExportToJson() src_json = f.ExportToJson() - if lyr.CreateFeature(f) != 0: - gdaltest.post_reason('failure') - return 'fail' + assert lyr.CreateFeature(f) == 0 ds = None ds = gdal.OpenEx('tmp/netcdf_55.nc', gdal.OF_VECTOR) @@ -2350,22 +1984,16 @@ def netcdf_55(): gdal.Unlink('tmp/netcdf_55.nc') - if src_json != out_json: - gdaltest.post_reason('failure') - print(src_json) - print(out_json) - return 'fail' - - return 'success' + assert src_json == out_json ############################################################################### # Test truncation of bidimensional char variables and WKT in a vector NetCDF 3 file -def netcdf_56(): +def test_netcdf_56(): if gdaltest.netcdf_drv is None: - return 'skip' + pytest.skip() ds = ogr.GetDriverByName('netCDF').CreateDataSource('tmp/netcdf_56.nc') # Test auto-grow of WKT field @@ -2376,32 +2004,27 @@ def netcdf_56(): f.SetGeometry(ogr.CreateGeometryFromWkt('POINT (1 2)')) with gdaltest.error_handler(): ret = lyr.CreateFeature(f) - if ret != 0: - gdaltest.post_reason('failure') - return 'fail' + assert ret == 0 ds = None ds = gdal.OpenEx('tmp/netcdf_56.nc', gdal.OF_VECTOR) lyr = ds.GetLayer(0) f = lyr.GetFeature(lyr.GetFeatureCount()) if f['txt'] != '01234' or f.GetGeometryRef() is not None: - gdaltest.post_reason('failure') f.DumpReadable() - return 'fail' + pytest.fail() ds = None gdal.Unlink('tmp/netcdf_56.nc') - return 'success' - ############################################################################### # Test one layer per file creation -def netcdf_57(): +def test_netcdf_57(): if gdaltest.netcdf_drv is None: - return 'skip' + pytest.skip() try: shutil.rmtree('tmp/netcdf_57') @@ -2410,17 +2033,13 @@ def netcdf_57(): with gdaltest.error_handler(): ds = ogr.GetDriverByName('netCDF').CreateDataSource('/not_existing_dir/invalid_subdir', options=['MULTIPLE_LAYERS=SEPARATE_FILES']) - if ds is not None: - gdaltest.post_reason('failure') - return 'fail' + assert ds is None open('tmp/netcdf_57', 'wb').close() with gdaltest.error_handler(): ds = ogr.GetDriverByName('netCDF').CreateDataSource('/not_existing_dir/invalid_subdir', options=['MULTIPLE_LAYERS=SEPARATE_FILES']) - if ds is not None: - gdaltest.post_reason('failure') - return 'fail' + assert ds is None os.unlink('tmp/netcdf_57') @@ -2437,26 +2056,22 @@ def netcdf_57(): ds = ogr.Open('tmp/netcdf_57/lyr%d.nc' % ilayer) lyr = ds.GetLayer(0) f = lyr.GetNextFeature() - if f['lyr_id'] != ilayer: - gdaltest.post_reason('failure') - return 'fail' + assert f['lyr_id'] == ilayer ds = None shutil.rmtree('tmp/netcdf_57') - return 'success' - ############################################################################### # Test one layer per group (NC4) -def netcdf_58(): +def test_netcdf_58(): if gdaltest.netcdf_drv is None: - return 'skip' + pytest.skip() if not gdaltest.netcdf_drv_has_nc4: - return 'skip' + pytest.skip() ds = ogr.GetDriverByName('netCDF').CreateDataSource('tmp/netcdf_58.nc', options=['FORMAT=NC4', 'MULTIPLE_LAYERS=SEPARATE_GROUPS']) for ilayer in range(2): @@ -2472,32 +2087,26 @@ def netcdf_58(): for ilayer in range(2): lyr = ds.GetLayer(ilayer) f = lyr.GetNextFeature() - if f['lyr_id'] != 'lyr_%d' % ilayer: - gdaltest.post_reason('failure') - return 'fail' + assert f['lyr_id'] == 'lyr_%d' % ilayer ds = None gdal.Unlink('tmp/netcdf_58.nc') - return 'success' - ############################################################################### # check for UnitType set/get. -def netcdf_59(): +def test_netcdf_59(): if gdaltest.netcdf_drv is None: - return 'skip' + pytest.skip() # get ds = gdal.Open('data/unittype.nc') unit = ds.GetRasterBand(1).GetUnitType() - if unit != 'm/s': - gdaltest.post_reason('Incorrect unit(%s)' % unit) - return 'fail' + assert unit == 'm/s', ('Incorrect unit(%s)' % unit) ds = None @@ -2511,21 +2120,17 @@ def netcdf_59(): # http://cfconventions.org/cf-conventions/v1.6.0/cf-conventions.html#_indexed_ragged_array_representation_of_profiles -def netcdf_60(): +def test_netcdf_60(): if gdaltest.netcdf_drv is None: - return 'skip' + pytest.skip() # Test that a vector cannot be opened in raster-only mode ds = gdal.OpenEx('data/profile.nc', gdal.OF_RASTER) - if ds is not None: - gdaltest.post_reason('fail') - return 'fail' + assert ds is None ds = gdal.OpenEx('data/profile.nc', gdal.OF_VECTOR) - if ds is None: - gdaltest.post_reason('fail') - return 'fail' + assert ds is not None with gdaltest.error_handler(): gdal.VectorTranslate('/vsimem/netcdf_60.csv', ds, format='CSV', layerCreationOptions=['LINEFORMAT=LF', 'GEOMETRY=AS_WKT', 'STRING_QUOTING=IF_NEEDED']) @@ -2540,23 +2145,18 @@ def netcdf_60(): "POINT Z (2 49 200)",1,3,Palo Alto,baw "POINT Z (3 50 100)",2,4,Santa Fe,baz2 """ - if content != expected_content: - gdaltest.post_reason('failure') - print(content) - return 'fail' + assert content == expected_content gdal.Unlink('/vsimem/netcdf_60.csv') - return 'success' - ############################################################################### # Test appending to a "Indexed ragged array representation of profiles" v1.6.0 H3.5 -def netcdf_61(): +def test_netcdf_61(): if gdaltest.netcdf_drv is None: - return 'skip' + pytest.skip() shutil.copy('data/profile.nc', 'tmp/netcdf_61.nc') ds = gdal.VectorTranslate('tmp/netcdf_61.nc', 'data/profile.nc', accessMode='append') @@ -2576,24 +2176,19 @@ def netcdf_61(): "POINT Z (2 49 200)",1,3,Palo Alto,baw "POINT Z (3 50 100)",2,4,Santa Fe,baz2 """ - if content != expected_content: - gdaltest.post_reason('failure') - print(content) - return 'fail' + assert content == expected_content gdal.Unlink('/vsimem/netcdf_61.csv') gdal.Unlink('/vsimem/netcdf_61.nc') - return 'success' - ############################################################################### # Test creating a "Indexed ragged array representation of profiles" v1.6.0 H3.5 -def netcdf_62(): +def test_netcdf_62(): if gdaltest.netcdf_drv is None: - return 'skip' + pytest.skip() ds = gdal.VectorTranslate('tmp/netcdf_62.nc', 'data/profile.nc', format='netCDF', layerCreationOptions=['FEATURE_TYPE=PROFILE', 'PROFILE_DIM_INIT_SIZE=1', 'PROFILE_VARIABLES=station']) gdal.VectorTranslate('/vsimem/netcdf_62.csv', ds, format='CSV', layerCreationOptions=['LINEFORMAT=LF', 'GEOMETRY=AS_WKT', 'STRING_QUOTING=IF_NEEDED']) @@ -2609,20 +2204,15 @@ def netcdf_62(): "POINT Z (2 49 200)",1,3,Palo Alto,baw "POINT Z (3 50 100)",2,4,Santa Fe,baz2 """ - if content != expected_content: - gdaltest.post_reason('failure') - print(content) - return 'fail' + assert content == expected_content gdal.Unlink('/vsimem/netcdf_62.csv') - return 'success' - -def netcdf_62_ncdump_check(): +def test_netcdf_62_ncdump_check(): if gdaltest.netcdf_drv is None: - return 'skip' + pytest.skip() # get file header with ncdump (if available) try: @@ -2631,50 +2221,41 @@ def netcdf_62_ncdump_check(): err = None if err is not None and 'netcdf library version' in err: (ret, err) = gdaltest.runexternal_out_and_err('ncdump -h tmp/netcdf_62.nc') - if ret.find('profile = 2') < 0 or \ - ret.find('record = UNLIMITED') < 0 or \ - ret.find('profile:cf_role = "profile_id"') < 0 or \ - ret.find('parentIndex:instance_dimension = "profile"') < 0 or \ - ret.find(':featureType = "profile"') < 0 or \ - ret.find('char station(profile') < 0 or \ - ret.find('char foo(record') < 0: - gdaltest.post_reason('failure') - print(ret) - return 'fail' + assert (ret.find('profile = 2') >= 0 and \ + ret.find('record = UNLIMITED') >= 0 and \ + ret.find('profile:cf_role = "profile_id"') >= 0 and \ + ret.find('parentIndex:instance_dimension = "profile"') >= 0 and \ + ret.find(':featureType = "profile"') >= 0 and \ + ret.find('char station(profile') >= 0 and \ + ret.find('char foo(record') >= 0) else: - return 'skip' + pytest.skip() - return 'success' + - -def netcdf_62_cf_check(): +def test_netcdf_62_cf_check(): if gdaltest.netcdf_drv is None: - return 'skip' + pytest.skip() import netcdf_cf - if netcdf_cf.netcdf_cf_setup() == 'success' and \ - gdaltest.netcdf_cf_method is not None: - result_cf = netcdf_cf.netcdf_cf_check_file('tmp/netcdf_62.nc', 'auto', False) - if result_cf != 'success': - gdaltest.post_reason('failure') - return 'fail' + netcdf_cf.netcdf_cf_setup() + if gdaltest.netcdf_cf_method is not None: + netcdf_cf.netcdf_cf_check_file('tmp/netcdf_62.nc', 'auto', False) gdal.Unlink('/vsimem/netcdf_62.nc') - return 'success' - ############################################################################### # Test creating a NC4 "Indexed ragged array representation of profiles" v1.6.0 H3.5 -def netcdf_63(): +def test_netcdf_63(): if gdaltest.netcdf_drv is None: - return 'skip' + pytest.skip() if not gdaltest.netcdf_drv_has_nc4: - return 'skip' + pytest.skip() shutil.copy('data/profile.nc', 'tmp/netcdf_63.nc') ds = gdal.VectorTranslate('tmp/netcdf_63.nc', 'data/profile.nc', format='netCDF', datasetCreationOptions=['FORMAT=NC4'], layerCreationOptions=['FEATURE_TYPE=PROFILE', 'USE_STRING_IN_NC4=NO', 'STRING_DEFAULT_WIDTH=1']) @@ -2691,23 +2272,18 @@ def netcdf_63(): "POINT Z (2 49 200)",1,3,Palo Alto,baw "POINT Z (3 50 100)",2,4,Santa Fe,baz2 """ - if content != expected_content: - gdaltest.post_reason('failure') - print(content) - return 'fail' + assert content == expected_content gdal.Unlink('/vsimem/netcdf_63.csv') - return 'success' - -def netcdf_63_ncdump_check(): +def test_netcdf_63_ncdump_check(): if gdaltest.netcdf_drv is None: - return 'skip' + pytest.skip() if not gdaltest.netcdf_drv_has_nc4: - return 'skip' + pytest.skip() # get file header with ncdump (if available) try: @@ -2716,32 +2292,27 @@ def netcdf_63_ncdump_check(): err = None if err is not None and 'netcdf library version' in err: (ret, err) = gdaltest.runexternal_out_and_err('ncdump -h tmp/netcdf_63.nc') - if ret.find('profile = UNLIMITED') < 0 or \ - ret.find('record = UNLIMITED') < 0 or \ - ret.find('profile:cf_role = "profile_id"') < 0 or \ - ret.find('parentIndex:instance_dimension = "profile"') < 0 or \ - ret.find(':featureType = "profile"') < 0 or \ - ret.find('char station(record') < 0: - gdaltest.post_reason('failure') - print(ret) - return 'fail' + assert (ret.find('profile = UNLIMITED') >= 0 and \ + ret.find('record = UNLIMITED') >= 0 and \ + ret.find('profile:cf_role = "profile_id"') >= 0 and \ + ret.find('parentIndex:instance_dimension = "profile"') >= 0 and \ + ret.find(':featureType = "profile"') >= 0 and \ + ret.find('char station(record') >= 0) else: gdal.Unlink('/vsimem/netcdf_63.nc') - return 'skip' + pytest.skip() gdal.Unlink('/vsimem/netcdf_63.nc') - return 'success' - ############################################################################### # Test creating a "Indexed ragged array representation of profiles" v1.6.0 H3.5 # but without a profile field. -def netcdf_64(): +def test_netcdf_64(): if gdaltest.netcdf_drv is None: - return 'skip' + pytest.skip() gdal.VectorTranslate('tmp/netcdf_64.nc', 'data/profile.nc', format='netCDF', selectFields=['id,station,foo'], layerCreationOptions=['FEATURE_TYPE=PROFILE', 'PROFILE_DIM_NAME=profile_dim', 'PROFILE_DIM_INIT_SIZE=1']) gdal.VectorTranslate('/vsimem/netcdf_64.csv', 'tmp/netcdf_64.nc', format='CSV', layerCreationOptions=['LINEFORMAT=LF', 'GEOMETRY=AS_WKT', 'STRING_QUOTING=IF_NEEDED']) @@ -2757,28 +2328,23 @@ def netcdf_64(): "POINT Z (2 49 200)",0,3,Palo Alto,baw "POINT Z (3 50 100)",1,4,Santa Fe,baz2 """ - if content != expected_content: - gdaltest.post_reason('failure') - print(content) - return 'fail' + assert content == expected_content gdal.Unlink('/vsimem/netcdf_64.csv') gdal.Unlink('/vsimem/netcdf_64.nc') - return 'success' - ############################################################################### # Test creating a NC4 file with empty string fields / WKT fields # (they must be filled as empty strings to avoid crashes in netcdf lib) -def netcdf_65(): +def test_netcdf_65(): if gdaltest.netcdf_drv is None: - return 'skip' + pytest.skip() if not gdaltest.netcdf_drv_has_nc4: - return 'skip' + pytest.skip() ds = ogr.GetDriverByName('netCDF').CreateDataSource('tmp/netcdf_65.nc', options=['FORMAT=NC4']) lyr = ds.CreateLayer('test') @@ -2791,24 +2357,21 @@ def netcdf_65(): lyr = ds.GetLayer(0) f = lyr.GetNextFeature() if f['str'] != '': - gdaltest.post_reason('failure') f.DumpReadable() - return 'fail' + pytest.fail() ds = None gdal.Unlink('tmp/netcdf_65.nc') - return 'success' - ############################################################################### # Test creating a "Indexed ragged array representation of profiles" v1.6.0 H3.5 # from a config file -def netcdf_66(): +def test_netcdf_66(): if gdaltest.netcdf_drv is None: - return 'skip' + pytest.skip() # First trying with no so good configs @@ -2898,20 +2461,15 @@ def netcdf_66(): "POINT Z (2 49 200)",1,3,Palo Alto,baw "POINT Z (3 50 100)",2,4,Santa Fe,baz2 """ - if content != expected_content: - gdaltest.post_reason('failure') - print(content) - return 'fail' + assert content == expected_content gdal.Unlink('/vsimem/netcdf_66.csv') - return 'success' - -def netcdf_66_ncdump_check(): +def test_netcdf_66_ncdump_check(): if gdaltest.netcdf_drv is None: - return 'skip' + pytest.skip() # get file header with ncdump (if available) try: @@ -2920,42 +2478,37 @@ def netcdf_66_ncdump_check(): err = None if err is not None and 'netcdf library version' in err: (ret, err) = gdaltest.runexternal_out_and_err('ncdump -h tmp/netcdf_66.nc') - if ret.find('char my_station(obs, my_station_max_width)') < 0 or \ - ret.find('my_station:long_name = "my station attribute"') < 0 or \ - ret.find('lon:my_extra_lon_attribute = "foo"') < 0 or \ - ret.find('lat:long_name') >= 0 or \ - ret.find('id:my_extra_attribute = 5.23') < 0 or \ - ret.find('profile:cf_role = "profile_id"') < 0 or \ - ret.find('parentIndex:instance_dimension = "profile"') < 0 or \ - ret.find(':featureType = "profile"') < 0: - gdaltest.post_reason('failure') - print(ret) - return 'fail' + assert (ret.find('char my_station(obs, my_station_max_width)') >= 0 and \ + ret.find('my_station:long_name = "my station attribute"') >= 0 and \ + ret.find('lon:my_extra_lon_attribute = "foo"') >= 0 and \ + ret.find('lat:long_name') < 0 and \ + ret.find('id:my_extra_attribute = 5.23') >= 0 and \ + ret.find('profile:cf_role = "profile_id"') >= 0 and \ + ret.find('parentIndex:instance_dimension = "profile"') >= 0 and \ + ret.find(':featureType = "profile"') >= 0) else: gdal.Unlink('/vsimem/netcdf_66.nc') - return 'skip' + pytest.skip() gdal.Unlink('/vsimem/netcdf_66.nc') - return 'success' - ############################################################################### # ticket #5950: optimize IReadBlock() and CheckData() handling of partial # blocks in the x axischeck for partial block reading. -def netcdf_67(): +def test_netcdf_67(): if gdaltest.netcdf_drv is None: - return 'skip' + pytest.skip() if not gdaltest.netcdf_drv_has_nc4: - return 'skip' + pytest.skip() try: import numpy except ImportError: - return 'skip' + pytest.skip() # disable bottom-up mode to use the real file's blocks size gdal.SetConfigOption('GDAL_NETCDF_BOTTOMUP', 'NO') @@ -2966,152 +2519,120 @@ def netcdf_67(): # so for the moment compare the full image ds = gdal.Open('data/partial_block_ticket5950.nc', gdal.GA_ReadOnly) ref = numpy.arange(1, 10).reshape((3, 3)) - if numpy.array_equal(ds.GetRasterBand(1).ReadAsArray(), ref): - result = 'success' - else: - result = 'fail' + if not numpy.array_equal(ds.GetRasterBand(1).ReadAsArray(), ref): + pytest.fail() ds = None gdal.SetConfigOption('GDAL_NETCDF_BOTTOMUP', None) - return result - ############################################################################### # Test reading SRS from srid attribute (#6613) -def netcdf_68(): +def test_netcdf_68(): if gdaltest.netcdf_drv is None: - return 'skip' + pytest.skip() ds = gdal.Open('data/srid.nc') wkt = ds.GetProjectionRef() - if wkt.find('6933') < 0: - gdaltest.post_reason('failure') - print(wkt) - return 'fail' - - return 'success' + assert wkt.find('6933') >= 0 ############################################################################### # Test opening a dataset with a 1D variable with 0 record (#6645) -def netcdf_69(): +def test_netcdf_69(): if gdaltest.netcdf_drv is None: - return 'skip' + pytest.skip() ds = gdal.Open('data/test6645.nc') - if ds is None: - return 'fail' - - return 'success' + assert ds is not None ############################################################################### # Test that we don't erroneously identify non-longitude axis as longitude (#6759) -def netcdf_70(): +def test_netcdf_70(): if gdaltest.netcdf_drv is None: - return 'skip' + pytest.skip() ds = gdal.Open('data/test6759.nc') gt = ds.GetGeoTransform() expected_gt = [304250.0, 250.0, 0.0, 4952500.0, 0.0, -250.0] - if max(abs(gt[i] - expected_gt[i]) for i in range(6)) > 1e-3: - print(gt) - return 'fail' - - return 'success' + assert max(abs(gt[i] - expected_gt[i]) for i in range(6)) <= 1e-3 ############################################################################### # Test that we take into account x and y offset and scaling # (https://github.com/OSGeo/gdal/pull/200) -def netcdf_71(): +def test_netcdf_71(): if gdaltest.netcdf_drv is None: - return 'skip' + pytest.skip() ds = gdal.Open('data/test_coord_scale_offset.nc') gt = ds.GetGeoTransform() expected_gt = (-690769.999174516, 1015.8812500000931, 0.0, 2040932.1838741193, 0.0, 1015.8812499996275) - if max(abs(gt[i] - expected_gt[i]) for i in range(6)) > 1e-3: - print(gt) - return 'fail' - - return 'success' + assert max(abs(gt[i] - expected_gt[i]) for i in range(6)) <= 1e-3 ############################################################################### # test int64 attributes / dim -def netcdf_72(): +def test_netcdf_72(): if gdaltest.netcdf_drv is None: - return 'skip' + pytest.skip() if not gdaltest.netcdf_drv_has_nc4: - return 'skip' + pytest.skip() ds = gdal.Open('data/int64dim.nc') mdi = ds.GetRasterBand(1).GetMetadataItem('NETCDF_DIM_TIME') - if mdi != '123456789012': - print(mdi) - return 'fail' - - return 'success' + assert mdi == '123456789012' ############################################################################### # test geostationary with radian units (https://github.com/OSGeo/gdal/pull/220) -def netcdf_73(): +def test_netcdf_73(): if gdaltest.netcdf_drv is None: - return 'skip' + pytest.skip() ds = gdal.Open('data/geos_rad.nc') gt = ds.GetGeoTransform() expected_gt = (-5979486.362104082, 1087179.4077774752, 0.0, -5979487.123448145, 0.0, 1087179.4077774752) - if max([abs(gt[i] - expected_gt[i]) for i in range(6)]) > 1: - print(gt) - return 'fail' - - return 'success' + assert max([abs(gt[i] - expected_gt[i]) for i in range(6)]) <= 1 ############################################################################### # test geostationary with microradian units (https://github.com/OSGeo/gdal/pull/220) -def netcdf_74(): +def test_netcdf_74(): if gdaltest.netcdf_drv is None: - return 'skip' + pytest.skip() ds = gdal.Open('data/geos_microradian.nc') gt = ds.GetGeoTransform() expected_gt = (-5739675.119757546, 615630.8078590936, 0.0, -1032263.7666924844, 0.0, 615630.8078590936) - if max([abs(gt[i] - expected_gt[i]) for i in range(6)]) > 1: - print(gt) - return 'fail' - - return 'success' + assert max([abs(gt[i] - expected_gt[i]) for i in range(6)]) <= 1 ############################################################################### # test opening a ncdump file -def netcdf_75(): +def test_netcdf_75(): if gdaltest.netcdf_drv is None: - return 'skip' + pytest.skip() if gdaltest.netcdf_drv.GetMetadataItem("ENABLE_NCDUMP") != 'YES': - return 'skip' + pytest.skip() tst = gdaltest.GDALTest('NetCDF', 'byte.nc.txt', 1, 4672) @@ -3141,100 +2662,78 @@ def netcdf_75(): # test opening a vector ncdump file -def netcdf_76(): +def test_netcdf_76(): if gdaltest.netcdf_drv is None: - return 'skip' + pytest.skip() if gdaltest.netcdf_drv.GetMetadataItem("ENABLE_NCDUMP") != 'YES': - return 'skip' + pytest.skip() ds = ogr.Open('data/poly.nc.txt') lyr = ds.GetLayer(0) f = lyr.GetNextFeature() if f is None or f.GetGeometryRef() is None: f.DumpReadable() - return 'fail' - - return 'success' + pytest.fail() + ############################################################################### # test opening a raster file that used to be confused with a vector file (#6974) -def netcdf_77(): +def test_netcdf_77(): if gdaltest.netcdf_drv is None: - return 'skip' + pytest.skip() ds = gdal.Open('data/fake_Oa01_radiance.nc') subdatasets = ds.GetMetadata('SUBDATASETS') - if len(subdatasets) != 2 * 2: - gdaltest.post_reason('fail') - print(subdatasets) - return 'fail' + assert len(subdatasets) == 2 * 2 ds = gdal.Open('NETCDF:"data/fake_Oa01_radiance.nc":Oa01_radiance') - if ds.GetMetadata('GEOLOCATION'): - gdaltest.post_reason('fail') - return 'fail' - - return 'success' + assert not ds.GetMetadata('GEOLOCATION') ############################################################################### # test we handle correctly valid_range={0,255} for a byte dataset with # negative nodata value -def netcdf_78(): +def test_netcdf_78(): if gdaltest.netcdf_drv is None: - return 'skip' + pytest.skip() ds = gdal.Open('data/byte_with_valid_range.nc') - if ds.GetRasterBand(1).GetNoDataValue() != 240: - gdaltest.post_reason('fail') - return 'fail' + assert ds.GetRasterBand(1).GetNoDataValue() == 240 data = ds.GetRasterBand(1).ReadRaster() data = struct.unpack('B' * 4, data) - if data != (128, 129, 126, 127): - gdaltest.post_reason('fail') - print(data) - return 'fail' - - return 'success' + assert data == (128, 129, 126, 127) ############################################################################### # test we handle correctly _Unsigned="true" for a byte dataset with # negative nodata value -def netcdf_79(): +def test_netcdf_79(): if gdaltest.netcdf_drv is None: - return 'skip' + pytest.skip() ds = gdal.Open('data/byte_with_neg_fillvalue_and_unsigned_hint.nc') - if ds.GetRasterBand(1).GetNoDataValue() != 240: - gdaltest.post_reason('fail') - return 'fail' + assert ds.GetRasterBand(1).GetNoDataValue() == 240 data = ds.GetRasterBand(1).ReadRaster() data = struct.unpack('B' * 4, data) - if data != (128, 129, 126, 127): - gdaltest.post_reason('fail') - print(data) - return 'fail' - - return 'success' + assert data == (128, 129, 126, 127) ############################################################################### # Test creating and opening with accent -def netcdf_80(): +def test_netcdf_80(): if gdaltest.netcdf_drv is None: - return 'skip' + pytest.skip() test = gdaltest.GDALTest('NETCDF', '../data/byte.tif', 1, 4672) return test.testCreateCopy(new_filename='test\xc3\xa9.nc', check_gt=0, check_srs=0, check_minmax=0) @@ -3243,34 +2742,24 @@ def netcdf_80(): # netCDF file in rotated_pole projection -def netcdf_81(): +def test_netcdf_81(): if gdaltest.netcdf_drv is None: - return 'skip' + pytest.skip() ds = gdal.Open('data/rotated_pole.nc') - if ds.RasterXSize != 137 or ds.RasterYSize != 108: - gdaltest.post_reason('Did not get expected dimensions') - print(ds.RasterXSize) - print(ds.RasterYSize) - return 'fail' + assert ds.RasterXSize == 137 and ds.RasterYSize == 108, \ + 'Did not get expected dimensions' projection = ds.GetProjectionRef() expected_projection = """PROJCS["unnamed",GEOGCS["unknown",DATUM["unknown",SPHEROID["Spheroid",6367470,594.3130483479559]],PRIMEM["Greenwich",0],UNIT["degree",0.0174532925199433]],PROJECTION["Rotated_pole"],EXTENSION["PROJ4","+proj=ob_tran +o_proj=longlat +lon_0=18 +o_lon_p=0 +o_lat_p=39.25 +a=6367470 +b=6367470 +to_meter=0.0174532925199 +wktext"]]""" - if projection != expected_projection: - gdaltest.post_reason('Did not get expected projection') - print(projection) - return 'fail' + assert projection == expected_projection, 'Did not get expected projection' gt = ds.GetGeoTransform() expected_gt = (-35.47, 0.44, 0.0, 23.65, 0.0, -0.44) - if max([abs(gt[i] - expected_gt[i]) for i in range(6)]) > 1e-3: - gdaltest.post_reason('Did not get expected geotransform') - print(gt) - return 'fail' - - return 'success' + assert max([abs(gt[i] - expected_gt[i]) for i in range(6)]) <= 1e-3, \ + 'Did not get expected geotransform' ############################################################################### # netCDF file with extra dimensions that are oddly indexed (1D variable @@ -3278,10 +2767,10 @@ def netcdf_81(): # 1D variable, several corresponding variables) -def netcdf_82(): +def test_netcdf_82(): if gdaltest.netcdf_drv is None: - return 'skip' + pytest.skip() with gdaltest.error_handler(): ds = gdal.Open('data/oddly_indexed_extra_dims.nc') @@ -3294,10 +2783,7 @@ def netcdf_82(): 'y#standard_name': 'projection_y_coordinate', 'NETCDF_DIM_extra_dim_with_var_of_different_name_DEF': '{2,6}' } - if md != expected_md: - gdaltest.post_reason('Did not get expected metadata') - print(md) - return 'fail' + assert md == expected_md, 'Did not get expected metadata' md = ds.GetRasterBand(1).GetMetadata() expected_md = { @@ -3306,22 +2792,17 @@ def netcdf_82(): 'NETCDF_DIM_extra_dim_without_variable': '1', 'NETCDF_VARNAME': 'data' } - if md != expected_md: - gdaltest.post_reason('Did not get expected metadata') - print(md) - return 'fail' - - return 'success' + assert md == expected_md, 'Did not get expected metadata' ############################################################################### -def netcdf_uffd(): +def test_netcdf_uffd(): if gdaltest.netcdf_drv is None: - return 'skip' + pytest.skip() if uffd_compare('orog_CRCM1.nc') is None: - return 'skip' + pytest.skip() netcdf_files = [ 'orog_CRCM1.nc', @@ -3332,24 +2813,9 @@ def netcdf_uffd(): 'reduce-cgcms.nc' ] for netcdf_file in netcdf_files: - if uffd_compare(netcdf_file) is not True: - return 'fail' - - return 'success' - - -def netcdf_postcheck(): - - if gdaltest.netcdf_drv is None: - return 'skip' - - diff = len(gdaltest.get_opened_files()) - gdaltest.count_opened_files - if diff != 0: - gdaltest.post_reason('Leak of file handles: %d leaked' % diff) - return 'fail' - - return 'success' + assert uffd_compare(netcdf_file) is True + ############################################################################### @@ -3357,144 +2823,55 @@ def netcdf_postcheck(): # main tests list -gdaltest_list = [ - netcdf_1, - netcdf_2, - netcdf_3, - netcdf_4, - netcdf_5, - netcdf_6, - netcdf_7, - netcdf_8, - netcdf_9, - netcdf_10, - netcdf_11, - netcdf_12, - netcdf_13, - netcdf_14, - netcdf_15, - netcdf_16, - netcdf_17, - netcdf_18, - netcdf_19, - netcdf_20, - netcdf_21, - netcdf_22, - netcdf_23, - netcdf_24, - netcdf_25, - netcdf_26, - netcdf_27, - netcdf_28, - netcdf_29, - netcdf_30, - netcdf_31, - netcdf_32, - netcdf_33, - netcdf_34, - netcdf_35, - netcdf_36, - netcdf_36_lonwrap, - netcdf_37, - netcdf_38, - netcdf_39, - netcdf_40, - netcdf_41, - netcdf_42, - netcdf_43, - netcdf_44, - netcdf_45, - netcdf_46, - netcdf_47, - netcdf_48, - netcdf_49, - netcdf_50, - netcdf_51, - netcdf_51_no_gdal_tags, - netcdf_52, - netcdf_53, - netcdf_54, - netcdf_55, - netcdf_56, - netcdf_57, - netcdf_58, - netcdf_59, - netcdf_60, - netcdf_61, - netcdf_62, - netcdf_62_ncdump_check, - netcdf_62_cf_check, - netcdf_63, - netcdf_63_ncdump_check, - netcdf_64, - netcdf_65, - netcdf_66, - netcdf_66_ncdump_check, - netcdf_67, - netcdf_68, - netcdf_69, - netcdf_70, - netcdf_71, - netcdf_72, - netcdf_73, - netcdf_74, - netcdf_75, - netcdf_76, - netcdf_77, - netcdf_78, - netcdf_79, - netcdf_80, - netcdf_81, - netcdf_82, - netcdf_uffd, -] ############################################################################### # basic file creation tests init_list = [ - ('byte.tif', 1, 4672, None, []), - ('byte_signed.tif', 1, 4672, None, ['PIXELTYPE=SIGNEDBYTE']), - ('int16.tif', 1, 4672, None, []), - ('int32.tif', 1, 4672, None, []), - ('float32.tif', 1, 4672, None, []), - ('float64.tif', 1, 4672, None, []) + ('byte.tif', 4672, []), + ('byte_signed.tif', 4672, ['PIXELTYPE=SIGNEDBYTE']), + ('int16.tif', 4672, []), + ('int32.tif', 4672, []), + ('float32.tif', 4672, []), + ('float64.tif', 4672, []) ] -# Some tests we don't need to do for each type. -item = init_list[0] -ut = gdaltest.GDALTest('netcdf', item[0], item[1], item[2], options=item[4]) -# test geotransform and projection -gdaltest_list.append((ut.testSetGeoTransform, item[0])) -gdaltest_list.append((ut.testSetProjection, item[0])) +# Some tests we don't need to do for each type. -# SetMetadata() not supported -# gdaltest_list.append( (ut.testSetMetadata, item[0]) ) +@pytest.mark.parametrize( + 'testfunction', [ + 'testSetGeoTransform', + 'testSetProjection', + # SetMetadata() not supported + # 'testSetMetadata' + ] +) +@pytest.mark.require_driver('netcdf') +def test_netcdf_functions_1(testfunction): + ut = gdaltest.GDALTest('netcdf', 'byte.tif', 1, 4672, options=[]) + getattr(ut, testfunction)() -# gdaltest_list = [ netcdf_1, netcdf_82 ] # Others we do for each pixel type. -for item in init_list: - ut = gdaltest.GDALTest('netcdf', item[0], item[1], item[2], options=item[4]) - 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])) -gdaltest_list.append(netcdf_postcheck) +@pytest.mark.parametrize( + 'filename,checksum,options', + init_list, + ids=[tup[0].split('.')[0] for tup in init_list], +) +@pytest.mark.parametrize( + 'testfunction', [ + 'testCreateCopy', + 'testCreate', + 'testSetNoDataValue' + ] +) +@pytest.mark.require_driver('netcdf') +def test_netcdf_functions_2(filename, checksum, options, testfunction): + ut = gdaltest.GDALTest('netcdf', filename, 1, checksum, options=options) + getattr(ut, testfunction)() ############################################################################### # other tests -if __name__ == '__main__': - - gdaltest.setup_run('netcdf') - - gdaltest.run_tests(gdaltest_list) - - # make sure we cleanup - gdaltest.clean_tmp() - - sys.exit(gdaltest.summarize()) diff --git a/autotest/gdrivers/netcdf_cf.py b/autotest/gdrivers/netcdf_cf.py index 87276857a1e8..e5aa99c9d3b4 100755 --- a/autotest/gdrivers/netcdf_cf.py +++ b/autotest/gdrivers/netcdf_cf.py @@ -30,15 +30,14 @@ ############################################################################### import os -import sys import imp # for netcdf_cf_setup() -from netcdf import netcdf_setup, netcdf_test_copy +from gdrivers.netcdf import netcdf_setup, netcdf_test_copy # noqa from osgeo import gdal from osgeo import osr -sys.path.append('../pymod') import gdaltest +import pytest ############################################################################### # Netcdf CF compliance Functions @@ -57,12 +56,11 @@ def netcdf_cf_setup(): # if netcdf is not supported, skip detection if gdaltest.netcdf_drv is None: - return 'skip' + pytest.skip() # skip if on windows if os.name != 'posix': - print('NOTICE: will skip CF checks because OS is not posix!') - return 'skip' + pytest.skip('NOTICE: will skip CF checks because OS is not posix!') # try local method cdms2_installed = False @@ -99,17 +97,17 @@ def netcdf_cf_setup(): gdaltest.netcdf_cf_method = 'local' gdaltest.netcdf_cf_files = files print('NOTICE: netcdf CF compliance checks: using local checker script') - return 'success' + return # skip http method if GDAL_DOWNLOAD_TEST_DATA and GDAL_RUN_SLOW_TESTS are not defined if not gdaltest.download_test_data(): print('NOTICE: skipping netcdf CF compliance checks') print('to enable remote http checker script, define GDAL_DOWNLOAD_TEST_DATA=YES') - return 'success' + return if not gdaltest.run_slow_tests(): print('NOTICE: skipping netcdf CF compliance checks') - return 'success' + return # http method with curl, should use python module but easier for now success = False @@ -128,13 +126,12 @@ def netcdf_cf_setup(): gdaltest.netcdf_cf_method = 'http' print('NOTICE: netcdf CF compliance checks: using remote HTTP ' 'checker script, consider installing cdms2 locally') - return 'success' + return if gdaltest.netcdf_cf_method is None: print('NOTICE: skipping netcdf CF compliance checks') - return 'success' - + ############################################################################### # build a command used to check ifile @@ -166,29 +163,25 @@ def netcdf_cf_check_file(ifile, version='auto', silent=True): gdaltest.netcdf_cf_check_error = '' if not os.path.exists(ifile): - return 'skip' + pytest.skip() output_all = '' command = netcdf_cf_get_command(ifile, version='auto') if command is None or command == '': - gdaltest.post_reason('no suitable method found, skipping') - return 'skip' + pytest.skip('no suitable method found, skipping') try: if gdaltest.netcdf_cf_method == 'http': print('calling ' + command) (ret, err) = gdaltest.runexternal_out_and_err(command) except OSError: - gdaltest.post_reason('ERROR with command - ' + command) - return 'fail' + pytest.fail('ERROR with command - ' + command) # There should be a ERRORS detected summary if 'ERRORS detected' not in ret: - gdaltest.post_reason('ERROR with command - ' + command) - print(ret) print(err) - return 'fail' + pytest.fail('ERROR with command - ' + command) output_all = ret output_err = '' @@ -374,14 +367,12 @@ def netcdf_cfproj_testcopy(projTuples, origTiff, interFormats, inPath, outPath, (_, err) = gdaltest.runexternal_out_and_err('ncdump -h') except OSError: # nothing is supported as ncdump not found - print('NOTICE: netcdf version not found') - return 'skip' + pytest.skip('NOTICE: netcdf version not found') i = err.find('netcdf library version ') # version not found if i == -1: - print('NOTICE: netcdf version not found') - return 'skip' + pytest.skip('NOTICE: netcdf version not found') if not os.path.exists(outPath): os.makedirs(outPath) @@ -557,14 +548,12 @@ def netcdf_cfproj_test_cf(proj, projNc): ############################################################################### # test copy and CF compliance for lat/lon (no datum, no GEOGCS) file, tif->nc->tif -def netcdf_cf_1(): - +def test_netcdf_cf_1(netcdf_setup): # noqa # setup netcdf and netcdf_cf environment - netcdf_setup() netcdf_cf_setup() if gdaltest.netcdf_drv is None: - return 'skip' + pytest.skip() # tst1 = gdaltest.GDALTest( 'NETCDF', 'trmm.tif', 1, 14 ) # result = tst1.testCreateCopy(check_gt=1, check_srs=1, new_filename='tmp/netcdf_cf_1.nc', delete_copy = 0) @@ -579,16 +568,16 @@ def netcdf_cf_1(): result_cf = netcdf_cf_check_file('tmp/netcdf_18.nc', 'auto', False) if result != 'fail' and result_cf != 'fail': - return 'success' - return 'fail' + return + pytest.fail() ############################################################################### # test copy and CF compliance for lat/lon (no datum, no GEOGCS) file, nc->nc -def netcdf_cf_2(): +def test_netcdf_cf_2(): if gdaltest.netcdf_drv is None: - return 'skip' + pytest.skip() result = netcdf_test_copy('data/trmm.nc', 1, 14, 'tmp/netcdf_cf_2.nc') @@ -597,17 +586,17 @@ def netcdf_cf_2(): result_cf = netcdf_cf_check_file('tmp/netcdf_cf_2.nc', 'auto', False) if result != 'fail' and result_cf != 'fail': - return 'success' - return 'fail' + return + pytest.fail() ############################################################################### # test copy and CF compliance for lat/lon (W*S84) file, tif->nc->tif # note: this test fails in trunk (before r23246) -def netcdf_cf_3(): +def test_netcdf_cf_3(): if gdaltest.netcdf_drv is None: - return 'skip' + pytest.skip() result = 'success' result_cf = 'success' @@ -624,17 +613,17 @@ def netcdf_cf_3(): result_cf = netcdf_cf_check_file('tmp/netcdf_cf_3.nc', 'auto', False) if result != 'fail' and result_cf != 'fail': - return 'success' - return 'fail' + return + pytest.fail() ############################################################################### # test support for various CF projections -def netcdf_cf_4(): +def test_netcdf_cf_4(): if gdaltest.netcdf_drv is None: - return 'skip' + pytest.skip() result = netcdf_cfproj_testcopy(netcdf_cfproj_tuples, 'melb-small.tif', netcdf_cfproj_int_fmt_maps, @@ -648,10 +637,10 @@ def netcdf_cf_4(): # test support for PS variants (bug #2893) -def netcdf_cf_5(): +def test_netcdf_cf_5(): if gdaltest.netcdf_drv is None: - return 'skip' + pytest.skip() ifiles = ['NETCDF:data/orog_CRCM1.nc:orog', 'NETCDF:data/orog_CRCM2.nc:orog'] for ifile in ifiles: @@ -661,31 +650,11 @@ def netcdf_cf_5(): sr.ImportFromWkt(prj) lat_origin = sr.GetProjParm('latitude_of_origin') - if lat_origin != 60: - gdaltest.post_reason('Latitude of origin in %s does not match expected: %f' + assert lat_origin == 60, ('Latitude of origin in %s does not match expected: %f' % (ifile, lat_origin)) - return 'fail' - - return 'success' + ############################################################################### -gdaltest_list = [ - netcdf_cf_1, - netcdf_cf_2, - netcdf_cf_3, - netcdf_cf_4, - netcdf_cf_5, - None] - -if __name__ == '__main__': - - gdaltest.setup_run('netcdf_cf') - - gdaltest.run_tests(gdaltest_list) - - # make sure we cleanup - gdaltest.clean_tmp() - sys.exit(gdaltest.summarize()) diff --git a/autotest/gdrivers/netcdf_cfchecks.py b/autotest/gdrivers/netcdf_cfchecks.py index 35a5e2b99264..01a5a28211ef 100755 --- a/autotest/gdrivers/netcdf_cfchecks.py +++ b/autotest/gdrivers/netcdf_cfchecks.py @@ -2615,11 +2615,3 @@ def getargs(arglist): # Main Program # -------------------------- -if __name__ == '__main__': - - (badc, coards, uploader, useFileName, standardName, areaTypes, udunitsDat, version, files) = getargs(sys.argv) - - inst = CFChecker(uploader=uploader, useFileName=useFileName, badc=badc, coards=coards, cfStandardNamesXML=standardName, cfAreaTypesXML=areaTypes, udunitsDat=udunitsDat, version=version) - for f in files: - rc = inst.checker(f) - sys.exit(rc) diff --git a/autotest/gdrivers/ngsgeoid.py b/autotest/gdrivers/ngsgeoid.py index d56e02b5ebd7..1561d239b810 100755 --- a/autotest/gdrivers/ngsgeoid.py +++ b/autotest/gdrivers/ngsgeoid.py @@ -28,9 +28,7 @@ # DEALINGS IN THE SOFTWARE. ############################################################################### -import sys -sys.path.append('../pymod') import gdaltest @@ -38,7 +36,7 @@ # Test opening a little endian file -def ngsgeoid_1(): +def test_ngsgeoid_1(): tst = gdaltest.GDALTest('NGSGEOID', 'g2009u01_le_truncated.bin', 1, 65534) return tst.testOpen(check_gt=(229.99166666666667, 0.016666666666670001, 0.0, 40.00833333333334, 0.0, -0.016666666666670001), check_prj='WGS84') @@ -47,21 +45,10 @@ def ngsgeoid_1(): # Test opening a big endian file -def ngsgeoid_2(): +def test_ngsgeoid_2(): tst = gdaltest.GDALTest('NGSGEOID', 'g2009u01_be_truncated.bin', 1, 65534) return tst.testOpen(check_gt=(229.99166666666667, 0.016666666666670001, 0.0, 40.00833333333334, 0.0, -0.016666666666670001), check_prj='WGS84') -gdaltest_list = [ - ngsgeoid_1, - ngsgeoid_2 -] -if __name__ == '__main__': - - gdaltest.setup_run('ngsgeoid') - - gdaltest.run_tests(gdaltest_list) - - sys.exit(gdaltest.summarize()) diff --git a/autotest/gdrivers/nitf.py b/autotest/gdrivers/nitf.py index bc298f89ded1..4d434e74a052 100755 --- a/autotest/gdrivers/nitf.py +++ b/autotest/gdrivers/nitf.py @@ -39,15 +39,23 @@ from osgeo import gdal from osgeo import osr -sys.path.append('../pymod') import gdaltest +import pytest ############################################################################### # Write/Read test of simple byte reference data. -def nitf_1(): +@pytest.fixture(scope='module') +def not_jpeg_9b(): + import jpeg + jpeg.test_jpeg_1() + if gdaltest.jpeg_version == '9b': + pytest.skip() + + +def test_nitf_1(): tst = gdaltest.GDALTest('NITF', 'byte.tif', 1, 4672) return tst.testCreateCopy() @@ -56,7 +64,7 @@ def nitf_1(): # Write/Read test of simple 16bit reference data. -def nitf_2(): +def test_nitf_2(): tst = gdaltest.GDALTest('NITF', 'int16.tif', 1, 4672) return tst.testCreateCopy() @@ -65,7 +73,7 @@ def nitf_2(): # Write/Read RGB image with lat/long georeferencing, and verify. -def nitf_3(): +def test_nitf_3(): tst = gdaltest.GDALTest('NITF', 'rgbsmall.tif', 3, 21349) return tst.testCreateCopy() @@ -113,13 +121,11 @@ def nitf_create(creation_options, set_inverted_color_interp=True, createcopy=Fal ds = None - return 'success' - ############################################################################### # Test direction creation of an non-compressed NITF file. -def nitf_4(): +def test_nitf_4(): return nitf_create(['ICORDS=G']) @@ -132,58 +138,37 @@ def nitf_check_created_file(checksum1, checksum2, checksum3, set_inverted_color_ chksum = ds.GetRasterBand(1).Checksum() chksum_expect = checksum1 - if chksum != chksum_expect: - gdaltest.post_reason('Did not get expected chksum for band 1') - print(chksum, chksum_expect) - return 'fail' + assert chksum == chksum_expect, 'Did not get expected chksum for band 1' chksum = ds.GetRasterBand(2).Checksum() chksum_expect = checksum2 - if chksum != chksum_expect: - gdaltest.post_reason('Did not get expected chksum for band 2') - print(chksum, chksum_expect) - return 'fail' + assert chksum == chksum_expect, 'Did not get expected chksum for band 2' chksum = ds.GetRasterBand(3).Checksum() chksum_expect = checksum3 - if chksum != chksum_expect: - gdaltest.post_reason('Did not get expected chksum for band 3') - print(chksum, chksum_expect) - return 'fail' + assert chksum == chksum_expect, 'Did not get expected chksum for band 3' geotransform = ds.GetGeoTransform() - if abs(geotransform[0] - 100) > 0.1 \ - or abs(geotransform[1] - 0.1) > 0.001 \ - or abs(geotransform[2] - 0) > 0.001 \ - or abs(geotransform[3] - 30.0) > 0.1 \ - or abs(geotransform[4] - 0) > 0.001 \ - or abs(geotransform[5] - -0.1) > 0.001: - print(geotransform) - gdaltest.post_reason('geotransform differs from expected') - return 'fail' + assert abs(geotransform[0] - 100) <= 0.1 and abs(geotransform[1] - 0.1) <= 0.001 and abs(geotransform[2] - 0) <= 0.001 and abs(geotransform[3] - 30.0) <= 0.1 and abs(geotransform[4] - 0) <= 0.001 and abs(geotransform[5] - -0.1) <= 0.001, \ + 'geotransform differs from expected' if set_inverted_color_interp: - if ds.GetRasterBand(1).GetRasterColorInterpretation() != gdal.GCI_BlueBand: - gdaltest.post_reason('Got wrong color interpretation.') - return 'fail' + assert ds.GetRasterBand(1).GetRasterColorInterpretation() == gdal.GCI_BlueBand, \ + 'Got wrong color interpretation.' - if ds.GetRasterBand(2).GetRasterColorInterpretation() != gdal.GCI_GreenBand: - gdaltest.post_reason('Got wrong color interpretation.') - return 'fail' + assert ds.GetRasterBand(2).GetRasterColorInterpretation() == gdal.GCI_GreenBand, \ + 'Got wrong color interpretation.' - if ds.GetRasterBand(3).GetRasterColorInterpretation() != gdal.GCI_RedBand: - gdaltest.post_reason('Got wrong color interpretation.') - return 'fail' + assert ds.GetRasterBand(3).GetRasterColorInterpretation() == gdal.GCI_RedBand, \ + 'Got wrong color interpretation.' ds = None - return 'success' - ############################################################################### # Verify file created by nitf_4() -def nitf_5(): +def test_nitf_5(): return nitf_check_created_file(32498, 42602, 38982) @@ -191,7 +176,7 @@ def nitf_5(): # Read existing NITF file. Verifies the new adjusted IGEOLO interp. -def nitf_6(): +def test_nitf_6(): tst = gdaltest.GDALTest('NITF', 'rgb.ntf', 3, 21349) return tst.testOpen(check_prj='WGS84', @@ -202,7 +187,7 @@ def nitf_6(): # NITF in-memory. -def nitf_7(): +def test_nitf_7(): tst = gdaltest.GDALTest('NITF', 'rgbsmall.tif', 3, 21349) return tst.testCreateCopy(vsimem=1) @@ -211,42 +196,25 @@ def nitf_7(): # Verify we can open an NSIF file, and get metadata including BLOCKA. -def nitf_8(): +def test_nitf_8(): ds = gdal.Open('data/fake_nsif.ntf') chksum = ds.GetRasterBand(1).Checksum() chksum_expect = 12033 - if chksum != chksum_expect: - gdaltest.post_reason('Did not get expected chksum for band 1') - print(chksum, chksum_expect) - return 'fail' + assert chksum == chksum_expect, 'Did not get expected chksum for band 1' md = ds.GetMetadata() - if md['NITF_FHDR'] != 'NSIF01.00': - gdaltest.post_reason('Got wrong FHDR value') - return 'fail' - - if md['NITF_BLOCKA_BLOCK_INSTANCE_01'] != '01' \ - or md['NITF_BLOCKA_BLOCK_COUNT'] != '01' \ - or md['NITF_BLOCKA_N_GRAY_01'] != '00000' \ - or md['NITF_BLOCKA_L_LINES_01'] != '01000' \ - or md['NITF_BLOCKA_LAYOVER_ANGLE_01'] != '000' \ - or md['NITF_BLOCKA_SHADOW_ANGLE_01'] != '000' \ - or md['NITF_BLOCKA_FRLC_LOC_01'] != '+41.319331+020.078400' \ - or md['NITF_BLOCKA_LRLC_LOC_01'] != '+41.317083+020.126072' \ - or md['NITF_BLOCKA_LRFC_LOC_01'] != '+41.281634+020.122570' \ - or md['NITF_BLOCKA_FRFC_LOC_01'] != '+41.283881+020.074924': - gdaltest.post_reason('BLOCKA metadata has unexpected value.') - return 'fail' - - return 'success' + assert md['NITF_FHDR'] == 'NSIF01.00', 'Got wrong FHDR value' + + assert md['NITF_BLOCKA_BLOCK_INSTANCE_01'] == '01' and md['NITF_BLOCKA_BLOCK_COUNT'] == '01' and md['NITF_BLOCKA_N_GRAY_01'] == '00000' and md['NITF_BLOCKA_L_LINES_01'] == '01000' and md['NITF_BLOCKA_LAYOVER_ANGLE_01'] == '000' and md['NITF_BLOCKA_SHADOW_ANGLE_01'] == '000' and md['NITF_BLOCKA_FRLC_LOC_01'] == '+41.319331+020.078400' and md['NITF_BLOCKA_LRLC_LOC_01'] == '+41.317083+020.126072' and md['NITF_BLOCKA_LRFC_LOC_01'] == '+41.281634+020.122570' and md['NITF_BLOCKA_FRFC_LOC_01'] == '+41.283881+020.074924', \ + 'BLOCKA metadata has unexpected value.' ############################################################################### # Create and read a JPEG encoded NITF file. -def nitf_9(): +def test_nitf_9(): src_ds = gdal.Open('data/rgbsmall.tif') ds = gdal.GetDriverByName('NITF').CreateCopy('tmp/nitf9.ntf', src_ds, @@ -259,31 +227,23 @@ def nitf_9(): (exp_mean, exp_stddev) = (65.9532, 46.9026375565) (mean, stddev) = ds.GetRasterBand(1).ComputeBandStats() - if abs(exp_mean - mean) > 0.1 or abs(exp_stddev - stddev) > 0.1: - print(mean, stddev) - gdaltest.post_reason('did not get expected mean or standard dev.') - return 'fail' + assert abs(exp_mean - mean) <= 0.1 and abs(exp_stddev - stddev) <= 0.1, \ + 'did not get expected mean or standard dev.' md = ds.GetMetadata('IMAGE_STRUCTURE') - if md['COMPRESSION'] != 'JPEG': - gdaltest.post_reason('Did not get expected compression value.') - return 'fail' - - return 'success' + assert md['COMPRESSION'] == 'JPEG', 'Did not get expected compression value.' ############################################################################### # For esoteric reasons, createcopy from jpeg compressed nitf files can be # tricky. Verify this is working. -def nitf_10(): +def test_nitf_10(): src_ds = gdal.Open('tmp/nitf9.ntf') expected_cs = src_ds.GetRasterBand(2).Checksum() src_ds = None - if expected_cs != 22296 and expected_cs != 22259: - gdaltest.post_reason('fail') - return 'fail' + assert expected_cs == 22296 or expected_cs == 22259 tst = gdaltest.GDALTest('NITF', '../tmp/nitf9.ntf', 2, expected_cs) return tst.testCreateCopy() @@ -292,7 +252,7 @@ def nitf_10(): # Test 1bit file ... conveniently very small and easy to include! (#1854) -def nitf_11(): +def test_nitf_11(): # From http://www.gwg.nga.mil/ntb/baseline/software/testfile/Nitfv2_1/i_3034c.ntf tst = gdaltest.GDALTest('NITF', 'i_3034c.ntf', 1, 170) @@ -302,7 +262,7 @@ def nitf_11(): # Verify that TRE and CGM access via the metadata domain works. -def nitf_12(): +def test_nitf_12(): ds = gdal.Open('data/fake_nsif.ntf') @@ -324,29 +284,22 @@ def nitf_12(): expectedBlockA = '010000001000000000 +41.319331+020.078400+41.317083+020.126072+41.281634+020.122570+41.283881+020.074924 ' - if mdTRE['BLOCKA'] != expectedBlockA: - gdaltest.post_reason('did not find expected BLOCKA from metadata.') - return 'fail' - - if blockA != expectedBlockA: - gdaltest.post_reason('did not find expected BLOCKA from metadata item.') - return 'fail' + assert mdTRE['BLOCKA'] == expectedBlockA, \ + 'did not find expected BLOCKA from metadata.' - if mdCGM['SEGMENT_COUNT'] != '0': - gdaltest.post_reason('did not find expected SEGMENT_COUNT from metadata.') - return 'fail' + assert blockA == expectedBlockA, 'did not find expected BLOCKA from metadata item.' - if segmentCount != '0': - gdaltest.post_reason('did not find expected SEGMENT_COUNT from metadata item.') - return 'fail' + assert mdCGM['SEGMENT_COUNT'] == '0', \ + 'did not find expected SEGMENT_COUNT from metadata.' - return 'success' + assert segmentCount == '0', \ + 'did not find expected SEGMENT_COUNT from metadata item.' ############################################################################### # Test creation of an NITF file in UTM Zone 11, Southern Hemisphere. -def nitf_13(): +def test_nitf_13(): drv = gdal.GetDriverByName('NITF') ds = drv.Create('tmp/test_13.ntf', 200, 100, 1, gdal.GDT_Byte, ['ICORDS=S']) @@ -363,48 +316,32 @@ def nitf_13(): ds = None - return 'success' - ############################################################################### # Verify previous file -def nitf_14(): +def test_nitf_14(): ds = gdal.Open('tmp/test_13.ntf') chksum = ds.GetRasterBand(1).Checksum() chksum_expect = 55964 - if chksum != chksum_expect: - gdaltest.post_reason('Did not get expected chksum for band 1') - print(chksum, chksum_expect) - return 'fail' + assert chksum == chksum_expect, 'Did not get expected chksum for band 1' geotransform = ds.GetGeoTransform() - if abs(geotransform[0] - 400000) > .1 \ - or abs(geotransform[1] - 10) > 0.001 \ - or abs(geotransform[2] - 0) > 0.001 \ - or abs(geotransform[3] - 6000000) > .1 \ - or abs(geotransform[4] - 0) > 0.001 \ - or abs(geotransform[5] - -10) > 0.001: - print(geotransform) - gdaltest.post_reason('geotransform differs from expected') - return 'fail' + assert abs(geotransform[0] - 400000) <= .1 and abs(geotransform[1] - 10) <= 0.001 and abs(geotransform[2] - 0) <= 0.001 and abs(geotransform[3] - 6000000) <= .1 and abs(geotransform[4] - 0) <= 0.001 and abs(geotransform[5] - -10) <= 0.001, \ + 'geotransform differs from expected' prj = ds.GetProjectionRef() - if prj.find('UTM Zone 11, Southern Hemisphere') == -1: - print(prj) - gdaltest.post_reason('Coordinate system not UTM Zone 11, Southern Hemisphere') - return 'fail' + assert prj.find('UTM Zone 11, Southern Hemisphere') != -1, \ + 'Coordinate system not UTM Zone 11, Southern Hemisphere' ds = None - return 'success' - ############################################################################### # Test creating an in memory copy. -def nitf_15(): +def test_nitf_15(): tst = gdaltest.GDALTest('NITF', 'byte.tif', 1, 4672) @@ -414,7 +351,7 @@ def nitf_15(): # Checks a 1-bit mono with mask table having (0x00) black as transparent with white arrow. -def nitf_16(): +def test_nitf_16(): # From http://www.gwg.nga.mil/ntb/baseline/software/testfile/Nitfv2_1/ns3034d.nsf tst = gdaltest.GDALTest('NITF', 'ns3034d.nsf', 1, 170) @@ -425,7 +362,7 @@ def nitf_16(): # Checks a 1-bit RGB/LUT (green arrow) with a mask table (pad pixels having value of 0x00) # and a transparent pixel value of 1 being mapped to green by the LUT -def nitf_17(): +def test_nitf_17(): # From http://www.gwg.nga.mil/ntb/baseline/software/testfile/Nitfv2_1/i_3034f.ntf tst = gdaltest.GDALTest('NITF', 'i_3034f.ntf', 1, 170) @@ -435,7 +372,7 @@ def nitf_17(): # Test NITF file without image segment -def nitf_18(): +def test_nitf_18(): # Shut up the warning about missing image segment gdal.PushErrorHandler('CPLQuietErrorHandler') @@ -443,16 +380,13 @@ def nitf_18(): ds = gdal.Open("data/U_0006A.NTF") gdal.PopErrorHandler() - if ds.RasterCount != 0: - return 'fail' - - return 'success' + assert ds.RasterCount == 0 ############################################################################### # Test BILEVEL (C1) decompression -def nitf_19(): +def test_nitf_19(): # From http://www.gwg.nga.mil/ntb/baseline/software/testfile/Nitfv2_0/U_1050A.NTF tst = gdaltest.GDALTest('NITF', 'U_1050A.NTF', 1, 65024) @@ -463,7 +397,7 @@ def nitf_19(): ############################################################################### # Test NITF file consisting only of an header -def nitf_20(): +def test_nitf_20(): # Shut up the warning about file either corrupt or empty gdal.PushErrorHandler('CPLQuietErrorHandler') @@ -471,10 +405,7 @@ def nitf_20(): ds = gdal.Open("data/U_0002A.NTF") gdal.PopErrorHandler() - if ds is not None: - return 'fail' - - return 'success' + assert ds is None ############################################################################### @@ -482,7 +413,7 @@ def nitf_20(): # # See also nitf_35 for writing TEXT segments. -def nitf_21(): +def test_nitf_21(): # Shut up the warning about missing image segment gdal.PushErrorHandler('CPLQuietErrorHandler') @@ -498,21 +429,15 @@ def nitf_21(): ds = None - if mdTEXT['DATA_0'] != 'A': - gdaltest.post_reason('did not find expected DATA_0 from metadata.') - return 'fail' + assert mdTEXT['DATA_0'] == 'A', 'did not find expected DATA_0 from metadata.' - if data0 != 'A': - gdaltest.post_reason('did not find expected DATA_0 from metadata item.') - return 'fail' - - return 'success' + assert data0 == 'A', 'did not find expected DATA_0 from metadata item.' ############################################################################### # Write/Read test of simple int32 reference data. -def nitf_22(): +def test_nitf_22(): tst = gdaltest.GDALTest('NITF', '../../gcore/data/int32.tif', 1, 4672) return tst.testCreateCopy() @@ -521,7 +446,7 @@ def nitf_22(): # Write/Read test of simple float32 reference data. -def nitf_23(): +def test_nitf_23(): tst = gdaltest.GDALTest('NITF', '../../gcore/data/float32.tif', 1, 4672) return tst.testCreateCopy() @@ -530,7 +455,7 @@ def nitf_23(): # Write/Read test of simple float64 reference data. -def nitf_24(): +def test_nitf_24(): tst = gdaltest.GDALTest('NITF', '../../gcore/data/float64.tif', 1, 4672) return tst.testCreateCopy() @@ -539,7 +464,7 @@ def nitf_24(): # Write/Read test of simple uint16 reference data. -def nitf_25(): +def test_nitf_25(): tst = gdaltest.GDALTest('NITF', '../../gcore/data/uint16.tif', 1, 4672) return tst.testCreateCopy() @@ -548,7 +473,7 @@ def nitf_25(): # Write/Read test of simple uint32 reference data. -def nitf_26(): +def test_nitf_26(): tst = gdaltest.GDALTest('NITF', '../../gcore/data/uint32.tif', 1, 4672) return tst.testCreateCopy() @@ -557,10 +482,9 @@ def nitf_26(): # Test Create() with IC=NC compression, and multi-blocks -def nitf_27(): +def test_nitf_27(): - if nitf_create(['ICORDS=G', 'IC=NC', 'BLOCKXSIZE=10', 'BLOCKYSIZE=10']) != 'success': - return 'fail' + nitf_create(['ICORDS=G', 'IC=NC', 'BLOCKXSIZE=10', 'BLOCKYSIZE=10']) return nitf_check_created_file(32498, 42602, 38982) @@ -568,15 +492,15 @@ def nitf_27(): ############################################################################### # Test Create() with IC=C8 compression with the JP2ECW driver -def nitf_28_jp2ecw(): +def test_nitf_28_jp2ecw(): gdaltest.nitf_28_jp2ecw_is_ok = False if gdal.GetDriverByName('JP2ECW') is None: - return 'skip' + pytest.skip() import ecw if not ecw.has_write_support(): - return 'skip' + pytest.skip() # Deregister other potential conflicting JPEG2000 drivers gdaltest.deregister_all_jpeg2000_drivers_but('JP2ECW') @@ -608,13 +532,13 @@ def nitf_28_jp2ecw(): # Test reading the previously create file with the JP2MrSID driver -def nitf_28_jp2mrsid(): +def test_nitf_28_jp2mrsid(): if not gdaltest.nitf_28_jp2ecw_is_ok: - return 'skip' + pytest.skip() jp2mrsid_drv = gdal.GetDriverByName('JP2MrSID') if jp2mrsid_drv is None: - return 'skip' + pytest.skip() # Deregister other potential conflicting JPEG2000 drivers gdaltest.deregister_all_jpeg2000_drivers_but('JP2MrSID') @@ -629,13 +553,13 @@ def nitf_28_jp2mrsid(): ############################################################################### # Test reading the previously create file with the JP2KAK driver -def nitf_28_jp2kak(): +def test_nitf_28_jp2kak(): if not gdaltest.nitf_28_jp2ecw_is_ok: - return 'skip' + pytest.skip() jp2kak_drv = gdal.GetDriverByName('JP2KAK') if jp2kak_drv is None: - return 'skip' + pytest.skip() # Deregister other potential conflicting JPEG2000 drivers gdaltest.deregister_all_jpeg2000_drivers_but('JP2KAK') @@ -650,13 +574,13 @@ def nitf_28_jp2kak(): # Test reading the previously create file with the JP2KAK driver -def nitf_28_jp2openjpeg(): +def test_nitf_28_jp2openjpeg(): if not gdaltest.nitf_28_jp2ecw_is_ok: - return 'skip' + pytest.skip() drv = gdal.GetDriverByName('JP2OpenJPEG') if drv is None: - return 'skip' + pytest.skip() # Deregister other potential conflicting JPEG2000 drivers gdaltest.deregister_all_jpeg2000_drivers_but('JP2OpenJPEG') @@ -671,10 +595,10 @@ def nitf_28_jp2openjpeg(): # Test Create() with IC=C8 compression with the JP2OpenJPEG driver -def nitf_28_jp2openjpeg_bis(): +def test_nitf_28_jp2openjpeg_bis(): drv = gdal.GetDriverByName('JP2OpenJPEG') if drv is None: - return 'skip' + pytest.skip() # Deregister other potential conflicting JPEG2000 drivers gdaltest.deregister_all_jpeg2000_drivers_but('JP2OpenJPEG') @@ -704,7 +628,7 @@ def nitf_28_jp2openjpeg_bis(): # Test Create() with a LUT -def nitf_29(): +def test_nitf_29(): drv = gdal.GetDriverByName('NITF') @@ -724,13 +648,11 @@ def nitf_29(): ds = gdal.Open('tmp/test_29.ntf') ct = ds.GetRasterBand(1).GetRasterColorTable() - if ct.GetCount() != 129 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() == 129 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.' new_ds = drv.CreateCopy('tmp/test_29_copy.ntf', ds) del new_ds @@ -739,51 +661,32 @@ def nitf_29(): ds = gdal.Open('tmp/test_29_copy.ntf') ct = ds.GetRasterBand(1).GetRasterColorTable() - if ct.GetCount() != 130 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() == 130 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.' ds = None - return 'success' - ############################################################################### # Verify we can write a file with BLOCKA TRE and read it back properly. -def nitf_30(): +def test_nitf_30(): src_ds = gdal.Open('data/fake_nsif.ntf') ds = gdal.GetDriverByName('NITF').CreateCopy('tmp/nitf30.ntf', src_ds) chksum = ds.GetRasterBand(1).Checksum() chksum_expect = 12033 - if chksum != chksum_expect: - gdaltest.post_reason('Did not get expected chksum for band 1') - print(chksum, chksum_expect) - return 'fail' + assert chksum == chksum_expect, 'Did not get expected chksum for band 1' md = ds.GetMetadata() - if md['NITF_FHDR'] != 'NSIF01.00': - gdaltest.post_reason('Got wrong FHDR value') - return 'fail' + assert md['NITF_FHDR'] == 'NSIF01.00', 'Got wrong FHDR value' - if md['NITF_BLOCKA_BLOCK_INSTANCE_01'] != '01' \ - or md['NITF_BLOCKA_BLOCK_COUNT'] != '01' \ - or md['NITF_BLOCKA_N_GRAY_01'] != '00000' \ - or md['NITF_BLOCKA_L_LINES_01'] != '01000' \ - or md['NITF_BLOCKA_LAYOVER_ANGLE_01'] != '000' \ - or md['NITF_BLOCKA_SHADOW_ANGLE_01'] != '000' \ - or md['NITF_BLOCKA_FRLC_LOC_01'] != '+41.319331+020.078400' \ - or md['NITF_BLOCKA_LRLC_LOC_01'] != '+41.317083+020.126072' \ - or md['NITF_BLOCKA_LRFC_LOC_01'] != '+41.281634+020.122570' \ - or md['NITF_BLOCKA_FRFC_LOC_01'] != '+41.283881+020.074924': - gdaltest.post_reason('BLOCKA metadata has unexpected value.') - return 'fail' + assert md['NITF_BLOCKA_BLOCK_INSTANCE_01'] == '01' and md['NITF_BLOCKA_BLOCK_COUNT'] == '01' and md['NITF_BLOCKA_N_GRAY_01'] == '00000' and md['NITF_BLOCKA_L_LINES_01'] == '01000' and md['NITF_BLOCKA_LAYOVER_ANGLE_01'] == '000' and md['NITF_BLOCKA_SHADOW_ANGLE_01'] == '000' and md['NITF_BLOCKA_FRLC_LOC_01'] == '+41.319331+020.078400' and md['NITF_BLOCKA_LRLC_LOC_01'] == '+41.317083+020.126072' and md['NITF_BLOCKA_LRFC_LOC_01'] == '+41.281634+020.122570' and md['NITF_BLOCKA_FRFC_LOC_01'] == '+41.283881+020.074924', \ + 'BLOCKA metadata has unexpected value.' ds = None @@ -807,19 +710,8 @@ def nitf_30(): ds = None gdal.GetDriverByName('NITF').Delete('/vsimem/nitf30_override.ntf') - if md['NITF_BLOCKA_BLOCK_INSTANCE_01'] != '01' \ - or md['NITF_BLOCKA_BLOCK_COUNT'] != '01' \ - or md['NITF_BLOCKA_N_GRAY_01'] != '00000' \ - or md['NITF_BLOCKA_L_LINES_01'] != '01000' \ - or md['NITF_BLOCKA_LAYOVER_ANGLE_01'] != '000' \ - or md['NITF_BLOCKA_SHADOW_ANGLE_01'] != '000' \ - or md['NITF_BLOCKA_FRLC_LOC_01'] != '+42.319331+020.078400' \ - or md['NITF_BLOCKA_LRLC_LOC_01'] != '+42.317083+020.126072' \ - or md['NITF_BLOCKA_LRFC_LOC_01'] != '+42.281634+020.122570' \ - or md['NITF_BLOCKA_FRFC_LOC_01'] != '+42.283881+020.074924': - gdaltest.post_reason('BLOCKA metadata has unexpected value.') - print(md) - return 'fail' + assert md['NITF_BLOCKA_BLOCK_INSTANCE_01'] == '01' and md['NITF_BLOCKA_BLOCK_COUNT'] == '01' and md['NITF_BLOCKA_N_GRAY_01'] == '00000' and md['NITF_BLOCKA_L_LINES_01'] == '01000' and md['NITF_BLOCKA_LAYOVER_ANGLE_01'] == '000' and md['NITF_BLOCKA_SHADOW_ANGLE_01'] == '000' and md['NITF_BLOCKA_FRLC_LOC_01'] == '+42.319331+020.078400' and md['NITF_BLOCKA_LRLC_LOC_01'] == '+42.317083+020.126072' and md['NITF_BLOCKA_LRFC_LOC_01'] == '+42.281634+020.122570' and md['NITF_BLOCKA_FRFC_LOC_01'] == '+42.283881+020.074924', \ + 'BLOCKA metadata has unexpected value.' # Test overriding src BLOCKA metadata with TRE=BLOCKA= creation option gdal.GetDriverByName('NITF').CreateCopy('/vsimem/nitf30_override.ntf', src_ds, @@ -830,19 +722,8 @@ def nitf_30(): ds = None gdal.GetDriverByName('NITF').Delete('/vsimem/nitf30_override.ntf') - if md['NITF_BLOCKA_BLOCK_INSTANCE_01'] != '01' \ - or md['NITF_BLOCKA_BLOCK_COUNT'] != '01' \ - or md['NITF_BLOCKA_N_GRAY_01'] != '00000' \ - or md['NITF_BLOCKA_L_LINES_01'] != '01000' \ - or md['NITF_BLOCKA_LAYOVER_ANGLE_01'] != '000' \ - or md['NITF_BLOCKA_SHADOW_ANGLE_01'] != '000' \ - or md['NITF_BLOCKA_FRLC_LOC_01'] != '+42.319331+020.078400' \ - or md['NITF_BLOCKA_LRLC_LOC_01'] != '+42.317083+020.126072' \ - or md['NITF_BLOCKA_LRFC_LOC_01'] != '+42.281634+020.122570' \ - or md['NITF_BLOCKA_FRFC_LOC_01'] != '+42.283881+020.074924': - gdaltest.post_reason('BLOCKA metadata has unexpected value.') - print(md) - return 'fail' + assert md['NITF_BLOCKA_BLOCK_INSTANCE_01'] == '01' and md['NITF_BLOCKA_BLOCK_COUNT'] == '01' and md['NITF_BLOCKA_N_GRAY_01'] == '00000' and md['NITF_BLOCKA_L_LINES_01'] == '01000' and md['NITF_BLOCKA_LAYOVER_ANGLE_01'] == '000' and md['NITF_BLOCKA_SHADOW_ANGLE_01'] == '000' and md['NITF_BLOCKA_FRLC_LOC_01'] == '+42.319331+020.078400' and md['NITF_BLOCKA_LRLC_LOC_01'] == '+42.317083+020.126072' and md['NITF_BLOCKA_LRFC_LOC_01'] == '+42.281634+020.122570' and md['NITF_BLOCKA_FRFC_LOC_01'] == '+42.283881+020.074924', \ + 'BLOCKA metadata has unexpected value.' # Test that gdal_translate -ullr doesn't propagate BLOCKA gdal.Translate('/vsimem/nitf30_no_src_md.ntf', src_ds, format='NITF', outputBounds=[2, 49, 3, 50]) @@ -850,9 +731,8 @@ def nitf_30(): md = ds.GetMetadata() ds = None gdal.GetDriverByName('NITF').Delete('/vsimem/nitf30_no_src_md.ntf') - if 'NITF_BLOCKA_BLOCK_INSTANCE_01' in md: - gdaltest.post_reason('unexpectdly found BLOCKA metadata.') - return 'fail' + assert 'NITF_BLOCKA_BLOCK_INSTANCE_01' not in md, \ + 'unexpectdly found BLOCKA metadata.' # Test USE_SRC_NITF_METADATA=NO gdal.GetDriverByName('NITF').CreateCopy('/vsimem/nitf30_no_src_md.ntf', src_ds, @@ -861,45 +741,33 @@ def nitf_30(): md = ds.GetMetadata() ds = None gdal.GetDriverByName('NITF').Delete('/vsimem/nitf30_no_src_md.ntf') - if 'NITF_BLOCKA_BLOCK_INSTANCE_01' in md: - gdaltest.post_reason('unexpectdly found BLOCKA metadata.') - return 'fail' - - return 'success' + assert 'NITF_BLOCKA_BLOCK_INSTANCE_01' not in md, \ + 'unexpectdly found BLOCKA metadata.' ############################################################################### # Verify we can write a file with a custom TRE and read it back properly. -def nitf_31(): +def test_nitf_31(): - if nitf_create(['TRE=CUSTOM= Test TRE1\\0MORE', + nitf_create(['TRE=CUSTOM= Test TRE1\\0MORE', 'TRE=TOTEST=SecondTRE', - 'ICORDS=G']) != 'success': - return 'fail' + 'ICORDS=G']) ds = gdal.Open('tmp/test_create.ntf') md = ds.GetMetadata('TRE') - if len(md) != 2: - gdaltest.post_reason('Did not get expected TRE count') - print(md) - return 'fail' + assert len(md) == 2, 'Did not get expected TRE count' # Check that the leading space in the CUSTOM metadata item is preserved (#3088, #3204) try: - if ds.GetMetadataItem('CUSTOM', 'TRE') != ' Test TRE1\\0MORE': - gdaltest.post_reason('Did not get expected TRE contents') - print(ds.GetMetadataItem('CUSTOM', 'TRE')) - return 'fail' + assert ds.GetMetadataItem('CUSTOM', 'TRE') == ' Test TRE1\\0MORE', \ + 'Did not get expected TRE contents' except: pass - if md['CUSTOM'] != ' Test TRE1\\0MORE' \ - or md['TOTEST'] != 'SecondTRE': - gdaltest.post_reason('Did not get expected TRE contents') - print(md) - return 'fail' + assert md['CUSTOM'] == ' Test TRE1\\0MORE' and md['TOTEST'] == 'SecondTRE', \ + 'Did not get expected TRE contents' ds = None return nitf_check_created_file(32498, 42602, 38982) @@ -908,10 +776,9 @@ def nitf_31(): ############################################################################### # Test Create() with ICORDS=D -def nitf_32(): +def test_nitf_32(): - if nitf_create(['ICORDS=D']) != 'success': - return 'fail' + nitf_create(['ICORDS=D']) return nitf_check_created_file(32498, 42602, 38982) @@ -919,17 +786,16 @@ def nitf_32(): ############################################################################### # Test Create() with ICORDS=D and a consistent BLOCKA -def nitf_33(): +def test_nitf_33(): - if nitf_create(['ICORDS=D', + nitf_create(['ICORDS=D', 'BLOCKA_BLOCK_COUNT=01', 'BLOCKA_BLOCK_INSTANCE_01=01', 'BLOCKA_L_LINES_01=100', 'BLOCKA_FRLC_LOC_01=+29.950000+119.950000', 'BLOCKA_LRLC_LOC_01=+20.050000+119.950000', 'BLOCKA_LRFC_LOC_01=+20.050000+100.050000', - 'BLOCKA_FRFC_LOC_01=+29.950000+100.050000']) != 'success': - return 'fail' + 'BLOCKA_FRFC_LOC_01=+29.950000+100.050000']) return nitf_check_created_file(32498, 42602, 38982) @@ -937,7 +803,7 @@ def nitf_33(): ############################################################################### # Test CreateCopy() of a 16bit image with tiling -def nitf_34(): +def test_nitf_34(): tst = gdaltest.GDALTest('NITF', 'n43.dt0', 1, 49187, options=['BLOCKSIZE=64']) return tst.testCreateCopy() @@ -946,7 +812,7 @@ def nitf_34(): # Test CreateCopy() writing file with a text segment. -def nitf_35(): +def test_nitf_35(): src_ds = gdal.Open('data/text_md.vrt') ds = gdal.GetDriverByName('NITF').CreateCopy('tmp/nitf_35.ntf', src_ds) @@ -959,30 +825,23 @@ def nitf_35(): with a newline.""" md = ds.GetMetadata('TEXT') - if md['DATA_0'] != exp_text: - gdaltest.post_reason('Did not get expected TEXT metadata.') - print(md) - return 'fail' + assert md['DATA_0'] == exp_text, 'Did not get expected TEXT metadata.' exp_text = """Also, a second text segment is created.""" md = ds.GetMetadata('TEXT') - if md['DATA_1'] != exp_text: - gdaltest.post_reason('Did not get expected TEXT metadata.') - print(md) - return 'fail' + assert md['DATA_1'] == exp_text, 'Did not get expected TEXT metadata.' ds = None gdal.GetDriverByName('NITF').Delete('tmp/nitf_35.ntf') - return 'success' ############################################################################### # Create and read a JPEG encoded NITF file (C3) with several blocks # Check that statistics are persisted (#3985) -def nitf_36(): +def test_nitf_36(): src_ds = gdal.Open('data/rgbsmall.tif') ds = gdal.GetDriverByName('NITF').CreateCopy('tmp/nitf36.ntf', src_ds, @@ -992,55 +851,43 @@ def nitf_36(): ds = gdal.Open('tmp/nitf36.ntf') - if ds.GetRasterBand(1).GetMinimum() is not None: - gdaltest.post_reason('Did not expect to have minimum value at that point.') - return 'fail' + assert ds.GetRasterBand(1).GetMinimum() is None, \ + 'Did not expect to have minimum value at that point.' (_, _, mean, stddev) = ds.GetRasterBand(1).GetStatistics(False, False) - if stddev >= 0: - gdaltest.post_reason('Did not expect to have statistics at that point.') - return 'fail' + assert stddev < 0, 'Did not expect to have statistics at that point.' (exp_mean, exp_stddev) = (65.4208, 47.254550335) (_, _, mean, stddev) = ds.GetRasterBand(1).GetStatistics(False, True) - if abs(exp_mean - mean) > 0.1 or abs(exp_stddev - stddev) > 0.1: - print(mean, stddev) - gdaltest.post_reason('did not get expected mean or standard dev.') - return 'fail' + assert abs(exp_mean - mean) <= 0.1 and abs(exp_stddev - stddev) <= 0.1, \ + 'did not get expected mean or standard dev.' md = ds.GetMetadata('IMAGE_STRUCTURE') - if md['COMPRESSION'] != 'JPEG': - gdaltest.post_reason('Did not get expected compression value.') - return 'fail' + assert md['COMPRESSION'] == 'JPEG', 'Did not get expected compression value.' ds = None # Check that statistics are persisted (#3985) ds = gdal.Open('tmp/nitf36.ntf') - if ds.GetRasterBand(1).GetMinimum() is None: - gdaltest.post_reason('Should have minimum value at that point.') - return 'fail' + assert ds.GetRasterBand(1).GetMinimum() is not None, \ + 'Should have minimum value at that point.' (_, _, mean, stddev) = ds.GetRasterBand(1).GetStatistics(False, False) - if abs(exp_mean - mean) > 0.1 or abs(exp_stddev - stddev) > 0.1: - print(mean, stddev) - gdaltest.post_reason('Should have statistics at that point.') - return 'fail' + assert abs(exp_mean - mean) <= 0.1 and abs(exp_stddev - stddev) <= 0.1, \ + 'Should have statistics at that point.' ds = None - return 'success' - ############################################################################### # Create and read a NITF file with 69999 bands -def nitf_37(): +def test_nitf_37(): try: if int(gdal.VersionInfo('VERSION_NUM')) < 1700: - return 'skip' + pytest.skip() except: # OG-python bindings don't have gdal.VersionInfo. Too bad, but let's hope that GDAL's version isn't too old ! pass @@ -1049,17 +896,14 @@ def nitf_37(): ds = None ds = gdal.Open('tmp/nitf37.ntf') - if ds.RasterCount != 69999: - return 'fail' + assert ds.RasterCount == 69999 ds = None - return 'success' - ############################################################################### # Create and read a NITF file with 999 images -def nitf_38(): +def test_nitf_38(): ds = gdal.Open('data/byte.tif') nXSize = ds.RasterXSize @@ -1079,23 +923,16 @@ def nitf_38(): ds = None ds = gdal.Open('NITF_IM:0:tmp/nitf38.ntf') - if ds.GetRasterBand(1).Checksum() != 0: - return 'fail' + assert ds.GetRasterBand(1).Checksum() == 0 ds = None ds = gdal.Open('NITF_IM:998:tmp/nitf38.ntf') cs = ds.GetRasterBand(1).Checksum() - if cs != expected_cs: - print(cs) - gdaltest.post_reason('bad checksum for image of 998th subdataset') - return 'fail' + assert cs == expected_cs, 'bad checksum for image of 998th subdataset' # Check the overview cs = ds.GetRasterBand(1).GetOverview(0).Checksum() - if cs != 1087: - print(cs) - gdaltest.post_reason('bad checksum for overview of image of 998th subdataset') - return 'fail' + assert cs == 1087, 'bad checksum for overview of image of 998th subdataset' out_ds = gdal.GetDriverByName('VRT').CreateCopy('tmp/nitf38.vrt', ds) out_ds = None @@ -1106,10 +943,7 @@ def nitf_38(): ds = None gdal.Unlink('tmp/nitf38.vrt') - if cs != expected_cs: - gdaltest.post_reason('failure') - print(cs) - return 'fail' + assert cs == expected_cs ds = gdal.Open('NITF_IM:998:%s/tmp/nitf38.ntf' % os.getcwd()) out_ds = gdal.GetDriverByName('VRT').CreateCopy('%s/tmp/nitf38.vrt' % os.getcwd(), ds) @@ -1121,10 +955,7 @@ def nitf_38(): ds = None gdal.Unlink('tmp/nitf38.vrt') - if cs != expected_cs: - gdaltest.post_reason('failure') - print(cs) - return 'fail' + assert cs == expected_cs ds = gdal.Open('NITF_IM:998:%s/tmp/nitf38.ntf' % os.getcwd()) out_ds = gdal.GetDriverByName('VRT').CreateCopy('tmp/nitf38.vrt', ds) @@ -1136,18 +967,13 @@ def nitf_38(): ds = None gdal.Unlink('tmp/nitf38.vrt') - if cs != expected_cs: - gdaltest.post_reason('failure') - print(cs) - return 'fail' - - return 'success' + assert cs == expected_cs ############################################################################### # Create and read a JPEG encoded NITF file (M3) with several blocks -def nitf_39(): +def test_nitf_39(): src_ds = gdal.Open('data/rgbsmall.tif') ds = gdal.GetDriverByName('NITF').CreateCopy('tmp/nitf39.ntf', src_ds, @@ -1160,30 +986,24 @@ def nitf_39(): (exp_mean, exp_stddev) = (65.4208, 47.254550335) (mean, stddev) = ds.GetRasterBand(1).ComputeBandStats() - if abs(exp_mean - mean) > 0.1 or abs(exp_stddev - stddev) > 0.1: - print(mean, stddev) - gdaltest.post_reason('did not get expected mean or standard dev.') - return 'fail' + assert abs(exp_mean - mean) <= 0.1 and abs(exp_stddev - stddev) <= 0.1, \ + 'did not get expected mean or standard dev.' md = ds.GetMetadata('IMAGE_STRUCTURE') - if md['COMPRESSION'] != 'JPEG': - gdaltest.post_reason('Did not get expected compression value.') - return 'fail' + assert md['COMPRESSION'] == 'JPEG', 'Did not get expected compression value.' ds = None - return 'success' - ############################################################################### # Create a 10 GB NITF file -def nitf_40(): +def test_nitf_40(): # 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() width = 99000 height = 99000 @@ -1199,8 +1019,7 @@ def nitf_40(): # Check that we can fetch it at the right value ds = gdal.Open('tmp/nitf40.ntf') - if ds.GetRasterBand(1).ReadRaster(x, y, 1, 1) != data: - return 'fail' + assert ds.GetRasterBand(1).ReadRaster(x, y, 1, 1) == data ds = None # Check that it is indeed at a very far offset, and that the NITF driver @@ -1225,29 +1044,19 @@ def nitf_40(): fd.close() val = struct.unpack('B' * 1, bytes_read)[0] - if val != 123: - gdaltest.post_reason('Bad value at offset %d : %d' % (offset, val)) - return 'fail' - - return 'success' + assert val == 123, ('Bad value at offset %d : %d' % (offset, val)) ############################################################################### # Check reading a 12-bit JPEG compressed NITF -def nitf_41(): - - import jpeg - jpeg.jpeg_1() - if gdaltest.jpeg_version == '9b': - return 'skip' - +def test_nitf_41(not_jpeg_9b): # Check if JPEG driver supports 12bit JPEG reading/writing jpg_drv = gdal.GetDriverByName('JPEG') md = jpg_drv.GetMetadata() if md[gdal.DMD_CREATIONDATATYPES].find('UInt16') == -1: sys.stdout.write('(12bit jpeg not available) ... ') - return 'skip' + pytest.skip() try: os.remove('data/U_4017A.NTF.aux.xml') @@ -1255,12 +1064,9 @@ def nitf_41(): pass ds = gdal.Open('data/U_4017A.NTF') - if ds.GetRasterBand(1).DataType != gdal.GDT_UInt16: - return 'fail' + assert ds.GetRasterBand(1).DataType == gdal.GDT_UInt16 stats = ds.GetRasterBand(1).GetStatistics(0, 1) - if stats[2] < 2385 or stats[2] > 2386: - print(stats) - return 'fail' + assert stats[2] >= 2385 and stats[2] <= 2386 ds = None try: @@ -1268,39 +1074,29 @@ def nitf_41(): except OSError: pass - return 'success' ############################################################################### # Check creating a 12-bit JPEG compressed NITF -def nitf_42(): - - if gdaltest.jpeg_version == '9b': - return 'skip' - +def test_nitf_42(not_jpeg_9b): # Check if JPEG driver supports 12bit JPEG reading/writing jpg_drv = gdal.GetDriverByName('JPEG') md = jpg_drv.GetMetadata() if md[gdal.DMD_CREATIONDATATYPES].find('UInt16') == -1: sys.stdout.write('(12bit jpeg not available) ... ') - return 'skip' + pytest.skip() ds = gdal.Open('data/U_4017A.NTF') out_ds = gdal.GetDriverByName('NITF').CreateCopy('tmp/nitf42.ntf', ds, options=['IC=C3', 'FHDR=NITF02.10']) del out_ds ds = gdal.Open('tmp/nitf42.ntf') - if ds.GetRasterBand(1).DataType != gdal.GDT_UInt16: - return 'fail' + assert ds.GetRasterBand(1).DataType == gdal.GDT_UInt16 stats = ds.GetRasterBand(1).GetStatistics(0, 1) - if stats[2] < 2385 or stats[2] > 2386: - print(stats) - return 'fail' + assert stats[2] >= 2385 and stats[2] <= 2386 ds = None - return 'success' - ############################################################################### # Test CreateCopy() in IC=C8 with various JPEG2000 drivers @@ -1313,7 +1109,7 @@ def nitf_43(driver_to_test, options): jp2_drv = None if jp2_drv is None: - return 'skip' + pytest.skip() # Deregister other potential conflicting JPEG2000 drivers gdaltest.deregister_all_jpeg2000_drivers_but(driver_to_test) @@ -1341,25 +1137,25 @@ def nitf_43(driver_to_test, options): return ret -def nitf_43_jasper(): +def test_nitf_43_jasper(): return nitf_43('JPEG2000', ['IC=C8']) -def nitf_43_jp2ecw(): +def test_nitf_43_jp2ecw(): import ecw if not ecw.has_write_support(): - return 'skip' + pytest.skip() return nitf_43('JP2ECW', ['IC=C8', 'TARGET=0']) -def nitf_43_jp2kak(): +def test_nitf_43_jp2kak(): return nitf_43('JP2KAK', ['IC=C8', 'QUALITY=100']) ############################################################################### # Check creating a monoblock 10000x1 image (ticket #3263) -def nitf_44(): +def test_nitf_44(): out_ds = gdal.GetDriverByName('NITF').Create('tmp/nitf44.ntf', 10000, 1) out_ds.GetRasterBand(1).Fill(255) @@ -1369,20 +1165,16 @@ def nitf_44(): if 'GetBlockSize' in dir(gdal.Band): (blockx, _) = ds.GetRasterBand(1).GetBlockSize() - if blockx != 10000: - return 'fail' + assert blockx == 10000 - if ds.GetRasterBand(1).Checksum() != 57182: - return 'fail' + assert ds.GetRasterBand(1).Checksum() == 57182 ds = None - return 'success' - ############################################################################### # Check overviews on a JPEG compressed subdataset -def nitf_45(): +def test_nitf_45(): try: os.remove('tmp/nitf45.ntf.aux.xml') @@ -1398,15 +1190,10 @@ def nitf_45(): ds = gdal.Open('NITF_IM:1:tmp/nitf45.ntf') cs = ds.GetRasterBand(1).GetOverview(0).Checksum() - if cs != 1086: - print(cs) - gdaltest.post_reason('did not get expected checksum for overview of subdataset') - return 'fail' + assert cs == 1086, 'did not get expected checksum for overview of subdataset' ds = None - return 'success' - ############################################################################### # Check overviews on a JPEG2000 compressed subdataset @@ -1415,7 +1202,7 @@ def nitf_46(driver_to_test): jp2_drv = gdal.GetDriverByName(driver_to_test) if jp2_drv is None: - return 'skip' + pytest.skip() # Deregister other potential conflicting JPEG2000 drivers gdaltest.deregister_all_jpeg2000_drivers_but(driver_to_test) @@ -1469,7 +1256,7 @@ def nitf_46_jp2kak(): return nitf_46('JP2KAK') -def nitf_46_jasper(): +def test_nitf_46_jasper(): return nitf_46('JPEG2000') @@ -1480,30 +1267,24 @@ def nitf_46_openjpeg(): # Check reading of rsets. -def nitf_47(): +def test_nitf_47(): ds = gdal.Open('data/rset.ntf.r0') band = ds.GetRasterBand(2) - if band.GetOverviewCount() != 2: - gdaltest.post_reason('did not get the expected number of rset overviews.') - return 'fail' + assert band.GetOverviewCount() == 2, \ + 'did not get the expected number of rset overviews.' cs = band.GetOverview(1).Checksum() - if cs != 1297: - print(cs) - gdaltest.post_reason('did not get expected checksum for overview of subdataset') - return 'fail' + assert cs == 1297, 'did not get expected checksum for overview of subdataset' ds = None - return 'success' - ############################################################################### # Check building of standard overviews in place of rset overviews. -def nitf_48(): +def test_nitf_48(): try: os.remove('tmp/rset.ntf.r0') @@ -1522,15 +1303,11 @@ def nitf_48(): ds = None ds = gdal.Open('tmp/rset.ntf.r0') - if ds.GetRasterBand(1).GetOverviewCount() != 1: - gdaltest.post_reason('did not get the expected number of rset overviews.') - return 'fail' + assert ds.GetRasterBand(1).GetOverviewCount() == 1, \ + 'did not get the expected number of rset overviews.' cs = ds.GetRasterBand(1).GetOverview(0).Checksum() - if cs != 2328: - print(cs) - gdaltest.post_reason('did not get expected checksum for overview of subdataset') - return 'fail' + assert cs == 2328, 'did not get expected checksum for overview of subdataset' ds = None @@ -1542,13 +1319,12 @@ def nitf_48(): except OSError: pass - return 'success' - + ############################################################################### # Test TEXT and CGM creation options with CreateCopy() (#3376) -def nitf_49(): +def test_nitf_49(): options = ["TEXT=DATA_0=COUCOU", "TEXT=HEADER_0=ABC", # This content is invalid but who cares here @@ -1573,26 +1349,24 @@ def nitf_49(): 'HEADER_0' not in md or md['HEADER_0'].find('ABC ') == -1: gdaltest.post_reason('did not get expected TEXT metadata') print(md) - return 'success' + return md = ds2.GetMetadata('CGM') if 'SEGMENT_COUNT' not in md or md['SEGMENT_COUNT'] != '1' or \ 'SEGMENT_0_DATA' not in md or md['SEGMENT_0_DATA'] != 'XYZ': gdaltest.post_reason('did not get expected CGM metadata') print(md) - return 'success' + return src_ds = None ds = None ds2 = None - return 'success' - ############################################################################### # Test TEXT and CGM creation options with Create() (#3376) -def nitf_50(): +def test_nitf_50(): options = [ # "IC=C8", "TEXT=DATA_0=COUCOU", @@ -1631,24 +1405,22 @@ def nitf_50(): 'HEADER_0' not in md or md['HEADER_0'].find('ABC ') == -1: gdaltest.post_reason('did not get expected TEXT metadata') print(md) - return 'success' + return md = ds.GetMetadata('CGM') if 'SEGMENT_COUNT' not in md or md['SEGMENT_COUNT'] != '1' or \ 'SEGMENT_0_DATA' not in md or md['SEGMENT_0_DATA'] != 'XYZ': gdaltest.post_reason('did not get expected CGM metadata') print(md) - return 'success' + return ds = None - return 'success' - ############################################################################### # Test reading very small images with NBPP < 8 or NBPP == 12 -def nitf_51(): +def test_nitf_51(): for xsize in range(1, 9): for nbpp in [1, 2, 3, 4, 5, 6, 7, 12]: ds = gdal.GetDriverByName('NITF').Create('tmp/nitf51.ntf', xsize, 1) @@ -1679,18 +1451,15 @@ def nitf_51(): for i in range(xsize): if arr[i] != (1 << nbpp) - 1: - gdaltest.post_reason('did not get expected data') print('xsize = %d, nbpp = %d' % (xsize, nbpp)) - print(arr) - return 'fail' - - return 'success' + pytest.fail('did not get expected data') + ############################################################################### # Test reading GeoSDE TREs -def nitf_52(): +def test_nitf_52(): # Create a fake NITF file with GeoSDE TREs (probably not conformant, but enough to test GDAL code) ds = gdal.GetDriverByName('NITF').Create('tmp/nitf52.ntf', 1, 1, options=['FILE_TRE=GEOPSB=01234567890123456789012345678901234567890123456789012345678901234567890123456789012345EURM ', @@ -1703,23 +1472,17 @@ def nitf_52(): gt = ds.GetGeoTransform() ds = None - if wkt != """PROJCS["unnamed",GEOGCS["EUROPEAN 1950, Mean (3 Param)",DATUM["EUROPEAN 1950, Mean (3 Param)",SPHEROID["International 1924 ",6378388,297],TOWGS84[-87,-98,-121,0,0,0,0]],PRIMEM["Greenwich",0],UNIT["degree",0.0174532925199433]],PROJECTION["Albers_Conic_Equal_Area"],PARAMETER["standard_parallel_1",0],PARAMETER["standard_parallel_2",0],PARAMETER["latitude_of_center",0],PARAMETER["longitude_of_center",0],PARAMETER["false_easting",0],PARAMETER["false_northing",0]]""": - gdaltest.post_reason('did not get expected SRS') - print(wkt) - return 'fail' - - if gt != (100000.0, 10.0, 0.0, 5000000.0, 0.0, -10.0): - gdaltest.post_reason('did not get expected geotransform') - print(gt) - return 'fail' + assert wkt == """PROJCS["unnamed",GEOGCS["EUROPEAN 1950, Mean (3 Param)",DATUM["EUROPEAN 1950, Mean (3 Param)",SPHEROID["International 1924 ",6378388,297],TOWGS84[-87,-98,-121,0,0,0,0]],PRIMEM["Greenwich",0],UNIT["degree",0.0174532925199433]],PROJECTION["Albers_Conic_Equal_Area"],PARAMETER["standard_parallel_1",0],PARAMETER["standard_parallel_2",0],PARAMETER["latitude_of_center",0],PARAMETER["longitude_of_center",0],PARAMETER["false_easting",0],PARAMETER["false_northing",0]]""", \ + 'did not get expected SRS' - return 'success' + assert gt == (100000.0, 10.0, 0.0, 5000000.0, 0.0, -10.0), \ + 'did not get expected geotransform' ############################################################################### # Test reading UTM MGRS -def nitf_53(): +def test_nitf_53(): ds = gdal.GetDriverByName('NITF').Create('tmp/nitf53.ntf', 2, 2, options=['ICORDS=N']) ds = None @@ -1741,23 +1504,17 @@ def nitf_53(): gt = ds.GetGeoTransform() ds = None - if wkt.find("""PROJCS["UTM Zone 31, Northern Hemisphere",GEOGCS["WGS 84""") != 0: - gdaltest.post_reason('did not get expected SRS') - print(wkt) - return 'fail' + assert wkt.find("""PROJCS["UTM Zone 31, Northern Hemisphere",GEOGCS["WGS 84""") == 0, \ + 'did not get expected SRS' - if gt != (205000.0, 10000.0, 0.0, 5445000.0, 0.0, -10000.0): - gdaltest.post_reason('did not get expected geotransform') - print(gt) - return 'fail' - - return 'success' + assert gt == (205000.0, 10000.0, 0.0, 5445000.0, 0.0, -10000.0), \ + 'did not get expected geotransform' ############################################################################### # Test reading RPC00B -def nitf_54(): +def test_nitf_54(): # Create a fake NITF file with RPC00B TRE (probably not conformant, but enough to test GDAL code) RPC00B = '100000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000' @@ -1769,17 +1526,13 @@ def nitf_54(): md = ds.GetMetadata('RPC') ds = None - if md is None or 'HEIGHT_OFF' not in md: - print(md) - return 'fail' - - return 'success' + assert md is not None and 'HEIGHT_OFF' in md ############################################################################### # Test reading ICHIPB -def nitf_55(): +def test_nitf_55(): # Create a fake NITF file with ICHIPB TRE (probably not conformant, but enough to test GDAL code) ICHIPB = '00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000' @@ -1791,17 +1544,13 @@ def nitf_55(): md = ds.GetMetadata() ds = None - if md is None or 'ICHIP_SCALE_FACTOR' not in md: - print(md) - return 'fail' - - return 'success' + assert md is not None and 'ICHIP_SCALE_FACTOR' in md ############################################################################### # Test reading USE00A -def nitf_56(): +def test_nitf_56(): # Create a fake NITF file with USE00A TRE (probably not conformant, but enough to test GDAL code) USE00A = '00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000' @@ -1813,17 +1562,13 @@ def nitf_56(): md = ds.GetMetadata() ds = None - if md is None or 'NITF_USE00A_ANGLE_TO_NORTH' not in md: - print(md) - return 'fail' - - return 'success' + assert md is not None and 'NITF_USE00A_ANGLE_TO_NORTH' in md ############################################################################### # Test reading GEOLOB -def nitf_57(): +def test_nitf_57(): # Create a fake NITF file with GEOLOB TRE GEOLOB = '000000360000000360-180.000000000090.000000000000' @@ -1838,15 +1583,14 @@ def nitf_57(): if gt != (-180.0, 1.0, 0.0, 90.0, 0.0, -1.0): gdaltest.post_reason('did not get expected geotransform') print(gt) - return 'success' - - return 'success' + return + ############################################################################### # Test reading STDIDC -def nitf_58(): +def test_nitf_58(): # Create a fake NITF file with STDIDC TRE (probably not conformant, but enough to test GDAL code) STDIDC = '00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000' @@ -1858,17 +1602,13 @@ def nitf_58(): md = ds.GetMetadata() ds = None - if md is None or 'NITF_STDIDC_ACQUISITION_DATE' not in md: - print(md) - return 'fail' - - return 'success' + assert md is not None and 'NITF_STDIDC_ACQUISITION_DATE' in md ############################################################################### # Test reading IMRFCA and IMASDA -def nitf_read_IMRFCA_IMASDA(): +def test_nitf_read_IMRFCA_IMASDA(): # Create a fake NITF file with fake IMRFCA and IMASDA TRE IMRFCA = '0' * 1760 @@ -1880,10 +1620,7 @@ def nitf_read_IMRFCA_IMASDA(): md = ds.GetMetadata('RPC') ds = None gdal.Unlink(tmpfile) - if md is None or md == {}: - gdaltest.post_reason('fail') - print(md) - return 'fail' + assert not (md is None or md == {}) # Only IMRFCA gdal.GetDriverByName('NITF').Create(tmpfile, 1, 1, options=['TRE=IMRFCA=' + IMRFCA]) @@ -1891,10 +1628,7 @@ def nitf_read_IMRFCA_IMASDA(): md = ds.GetMetadata('RPC') ds = None gdal.Unlink(tmpfile) - if md != {}: - gdaltest.post_reason('fail') - print(md) - return 'fail' + assert md == {} # Only IMASDA gdal.GetDriverByName('NITF').Create(tmpfile, 1, 1, options=['TRE=IMASDA=' + IMASDA]) @@ -1902,10 +1636,7 @@ def nitf_read_IMRFCA_IMASDA(): md = ds.GetMetadata('RPC') ds = None gdal.Unlink(tmpfile) - if md != {}: - gdaltest.post_reason('fail') - print(md) - return 'fail' + assert md == {} # Too short IMRFCA with gdaltest.error_handler(): @@ -1914,10 +1645,7 @@ def nitf_read_IMRFCA_IMASDA(): md = ds.GetMetadata('RPC') ds = None gdal.Unlink(tmpfile) - if md != {}: - gdaltest.post_reason('fail') - print(md) - return 'fail' + assert md == {} # Too short IMASDA with gdaltest.error_handler(): @@ -1926,18 +1654,13 @@ def nitf_read_IMRFCA_IMASDA(): md = ds.GetMetadata('RPC') ds = None gdal.Unlink(tmpfile) - if md != {}: - gdaltest.post_reason('fail') - print(md) - return 'fail' - - return 'success' + assert md == {} ############################################################################### # Test georeferencing through .nfw and .hdr files -def nitf_59(): +def test_nitf_59(): shutil.copyfile('data/nitf59.nfw', 'tmp/nitf59.nfw') shutil.copyfile('data/nitf59.hdr', 'tmp/nitf59.hdr') @@ -1949,23 +1672,17 @@ def nitf_59(): gt = ds.GetGeoTransform() ds = None - if wkt.find("""PROJCS["UTM Zone 31, Northern Hemisphere",GEOGCS["WGS 84""") != 0: - gdaltest.post_reason('did not get expected SRS') - print(wkt) - return 'fail' + assert wkt.find("""PROJCS["UTM Zone 31, Northern Hemisphere",GEOGCS["WGS 84""") == 0, \ + 'did not get expected SRS' - if gt != (149999.5, 1.0, 0.0, 4500000.5, 0.0, -1.0): - gdaltest.post_reason('did not get expected geotransform') - print(gt) - return 'fail' - - return 'success' + assert gt == (149999.5, 1.0, 0.0, 4500000.5, 0.0, -1.0), \ + 'did not get expected geotransform' ############################################################################### # Test reading CADRG polar tile georeferencing (#2940) -def nitf_60(): +def test_nitf_60(): # Shut down errors because the file is truncated gdal.PushErrorHandler('CPLQuietErrorHandler') @@ -1975,25 +1692,19 @@ def nitf_60(): gt = ds.GetGeoTransform() ds = None - if wkt != """PROJCS["unnamed",GEOGCS["unnamed ellipse",DATUM["unknown",SPHEROID["unnamed",6378137,0]],PRIMEM["Greenwich",0],UNIT["degree",0.0174532925199433]],PROJECTION["Azimuthal_Equidistant"],PARAMETER["latitude_of_center",90],PARAMETER["longitude_of_center",0],PARAMETER["false_easting",0],PARAMETER["false_northing",0],UNIT["Meter",1]]""": - gdaltest.post_reason('did not get expected SRS') - print(wkt) - return 'fail' + assert wkt == """PROJCS["unnamed",GEOGCS["unnamed ellipse",DATUM["unknown",SPHEROID["unnamed",6378137,0]],PRIMEM["Greenwich",0],UNIT["degree",0.0174532925199433]],PROJECTION["Azimuthal_Equidistant"],PARAMETER["latitude_of_center",90],PARAMETER["longitude_of_center",0],PARAMETER["false_easting",0],PARAMETER["false_northing",0],UNIT["Meter",1]]""", \ + 'did not get expected SRS' ref_gt = [1036422.8453166834, 149.94543479697344, 0.0, 345474.28177222813, 0.0, -149.94543479697404] for i in range(6): - if abs(gt[i] - ref_gt[i]) > 1e-6: - gdaltest.post_reason('did not get expected geotransform') - print(gt) - return 'fail' - - return 'success' + assert abs(gt[i] - ref_gt[i]) <= 1e-6, 'did not get expected geotransform' + ############################################################################### # Test reading TRE from DE segment -def nitf_61(): +def test_nitf_61(): # Derived from http://www.gwg.nga.mil/ntb/baseline/software/testfile/rsm/SampleFiles/FrameSet1/NITF_Files/i_6130a.zip # but hand edited to have just 1x1 imagery @@ -2002,22 +1713,15 @@ def nitf_61(): xml_tre = ds.GetMetadata('xml:TRE')[0] ds = None - if md is None or 'RSMDCA' not in md or 'RSMECA' not in md or 'RSMPCA' not in md or 'RSMIDA' not in md: - print(md) - return 'fail' - - if xml_tre.find('<tre name="RSMDCA"') == -1: - gdaltest.post_reason('did not get expected xml:TRE') - print(xml_tre[0]) - return 'fail' + assert md is not None and 'RSMDCA' in md and 'RSMECA' in md and 'RSMPCA' in md and 'RSMIDA' in md - return 'success' + assert xml_tre.find('<tre name="RSMDCA"') != -1, 'did not get expected xml:TRE' ############################################################################### # Test creating & reading image comments -def nitf_62(): +def test_nitf_62(): # 80+1 characters comments = '012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678ZA' @@ -2031,17 +1735,15 @@ def nitf_62(): got_comments = md['NITF_IMAGE_COMMENTS'] if len(got_comments) != 160 or got_comments.find(comments) == -1: - gdaltest.post_reason('did not get expected comments') print("'%s'" % got_comments) - return 'fail' - - return 'success' + pytest.fail('did not get expected comments') + ############################################################################### # Test NITFReadImageLine() and NITFWriteImageLine() when nCols < nBlockWidth (#3551) -def nitf_63(): +def test_nitf_63(): ds = gdal.GetDriverByName('NITF').Create('tmp/nitf63.ntf', 50, 25, 3, gdal.GDT_Int16, options=['BLOCKXSIZE=256']) ds = None @@ -2059,9 +1761,7 @@ def nitf_63(): ds = gdal.Open('tmp/nitf63.ntf', gdal.GA_Update) md = ds.GetMetadata() - if md['NITF_IMODE'] != 'P': - gdaltest.post_reason('wrong IMODE') - return 'fail' + assert md['NITF_IMODE'] == 'P', 'wrong IMODE' ds.GetRasterBand(1).Fill(0) ds.GetRasterBand(2).Fill(127) ds.GetRasterBand(3).Fill(255) @@ -2073,17 +1773,14 @@ def nitf_63(): cs3 = ds.GetRasterBand(3).Checksum() ds = None - if cs1 != 0 or cs2 != 14186 or cs3 != 15301: - gdaltest.post_reason('did not get expected checksums : (%d, %d, %d) instead of (0, 14186, 15301)' % (cs1, cs2, cs3)) - return 'fail' - - return 'success' + assert cs1 == 0 and cs2 == 14186 and cs3 == 15301, \ + ('did not get expected checksums : (%d, %d, %d) instead of (0, 14186, 15301)' % (cs1, cs2, cs3)) ############################################################################### # Test SDE_TRE creation option -def nitf_64(): +def test_nitf_64(): src_ds = gdal.GetDriverByName('GTiff').Create('/vsimem/nitf_64.tif', 256, 256, 1) src_ds.SetGeoTransform([2.123456789, 0.123456789, 0, 49.123456789, 0, -0.123456789]) @@ -2099,10 +1796,8 @@ def nitf_64(): expected_gt = (2.123270588235294, 0.12345882352941177, 0.0, 49.123729411764707, 0.0, -0.12345882352941176) got_gt = ds.GetGeoTransform() for i in range(6): - if abs(expected_gt[i] - got_gt[i]) > 1e-10: - gdaltest.post_reason('did not get expected GT in ICORDS=D mode') - print(got_gt) - return 'fail' + assert abs(expected_gt[i] - got_gt[i]) <= 1e-10, \ + 'did not get expected GT in ICORDS=D mode' ds = None ds = gdal.GetDriverByName('NITF').CreateCopy('/vsimem/nitf_64.ntf', src_ds, options=['ICORDS=G']) @@ -2113,10 +1808,8 @@ def nitf_64(): expected_gt = (2.1235495642701521, 0.12345642701525053, 0.0, 49.123394880174288, 0.0, -0.12345642701525052) got_gt = ds.GetGeoTransform() for i in range(6): - if abs(expected_gt[i] - got_gt[i]) > 1e-10: - gdaltest.post_reason('did not get expected GT in ICORDS=G mode') - print(got_gt) - return 'fail' + assert abs(expected_gt[i] - got_gt[i]) <= 1e-10, \ + 'did not get expected GT in ICORDS=G mode' ds = None ds = gdal.GetDriverByName('NITF').CreateCopy('/vsimem/nitf_64.ntf', src_ds, options=['SDE_TRE=YES']) @@ -2127,23 +1820,19 @@ def nitf_64(): expected_gt = (2.123456789, 0.1234567901234568, 0.0, 49.123456789000002, 0.0, -0.12345679012345678) got_gt = ds.GetGeoTransform() for i in range(6): - if abs(expected_gt[i] - got_gt[i]) > 1e-10: - gdaltest.post_reason('did not get expected GT in SDE_TRE mode') - print(got_gt) - return 'fail' + assert abs(expected_gt[i] - got_gt[i]) <= 1e-10, \ + 'did not get expected GT in SDE_TRE mode' ds = None src_ds = None gdal.Unlink('/vsimem/nitf_64.tif') gdal.Unlink('/vsimem/nitf_64.ntf') - return 'success' - ############################################################################### # Test creating an image with block_width = image_width > 8192 (#3922) -def nitf_65(): +def test_nitf_65(): ds = gdal.GetDriverByName('NITF').Create('/vsimem/nitf_65.ntf', 10000, 100, options=['BLOCKXSIZE=10000']) ds = None @@ -2155,17 +1844,13 @@ def nitf_65(): gdal.Unlink('/vsimem/nitf_65.ntf') - if block_xsize != 10000: - print(block_xsize) - return 'fail' - - return 'success' + assert block_xsize == 10000 ############################################################################### # Test creating an image with block_height = image_height > 8192 (#3922) -def nitf_66(): +def test_nitf_66(): ds = gdal.GetDriverByName('NITF').Create('/vsimem/nitf_66.ntf', 100, 10000, options=['BLOCKYSIZE=10000', 'BLOCKXSIZE=50']) ds = None @@ -2177,17 +1862,13 @@ def nitf_66(): gdal.Unlink('/vsimem/nitf_66.ntf') - if block_ysize != 10000: - print(block_ysize) - return 'fail' - - return 'success' + assert block_ysize == 10000 ############################################################################### # Test that we don't use scanline access in illegal cases (#3926) -def nitf_67(): +def test_nitf_67(): src_ds = gdal.Open('data/byte.tif') gdal.PushErrorHandler('CPLQuietErrorHandler') @@ -2203,37 +1884,27 @@ def nitf_67(): gdal.Unlink('/vsimem/nitf_67.ntf') gdal.Unlink('/vsimem/nitf_67.ntf.aux.xml') - if cs != 4672: - print(cs) - return 'fail' - - return 'success' + assert cs == 4672 ############################################################################### # Test reading NITF_METADATA domain -def nitf_68(): +def test_nitf_68(): ds = gdal.Open('data/rgb.ntf') - if len(ds.GetMetadata('NITF_METADATA')) != 2: - print(ds.GetMetadata('NITF_METADATA')) - return 'fail' + assert len(ds.GetMetadata('NITF_METADATA')) == 2 ds = None ds = gdal.Open('data/rgb.ntf') - if not ds.GetMetadataItem('NITFFileHeader', 'NITF_METADATA'): - print(ds.GetMetadataItem('NITFFileHeader', 'NITF_METADATA')) - return 'fail' + assert ds.GetMetadataItem('NITFFileHeader', 'NITF_METADATA') ds = None - return 'success' - ############################################################################### # Test SetGCPs() support -def nitf_69(): +def test_nitf_69(): vrt_txt = """<VRTDataset rasterXSize="20" rasterYSize="20"> <GCPList Projection='GEOGCS["WGS 84",DATUM["WGS_1984",SPHEROID["WGS 84",6378137,298.257223563,AUTHORITY["EPSG","7030"]],AUTHORITY["EPSG","6326"]],PRIMEM["Greenwich",0,AUTHORITY["EPSG","8901"]],UNIT["degree",0.0174532925199433,AUTHORITY["EPSG","9122"]],AUTHORITY["EPSG","4326"]]'> @@ -2279,40 +1950,30 @@ def nitf_69(): # Check # Upper-left - if abs(got_gcps[0].GCPPixel - 0.5) > 1e-5 or abs(got_gcps[0].GCPLine - 0.5) > 1e-5 or \ - abs(got_gcps[0].GCPX - 2) > 1e-5 or abs(got_gcps[0].GCPY - 49) > 1e-5: - gdaltest.post_reason('wrong gcp') - print(got_gcps[0]) - return 'fail' + assert (abs(got_gcps[0].GCPPixel - 0.5) <= 1e-5 and abs(got_gcps[0].GCPLine - 0.5) <= 1e-5 and \ + abs(got_gcps[0].GCPX - 2) <= 1e-5 and abs(got_gcps[0].GCPY - 49) <= 1e-5), \ + 'wrong gcp' # Upper-right - if abs(got_gcps[1].GCPPixel - 19.5) > 1e-5 or abs(got_gcps[1].GCPLine - 0.5) > 1e-5 or \ - abs(got_gcps[1].GCPX - 3) > 1e-5 or abs(got_gcps[1].GCPY - 49.5) > 1e-5: - gdaltest.post_reason('wrong gcp') - print(got_gcps[1]) - return 'fail' + assert (abs(got_gcps[1].GCPPixel - 19.5) <= 1e-5 and abs(got_gcps[1].GCPLine - 0.5) <= 1e-5 and \ + abs(got_gcps[1].GCPX - 3) <= 1e-5 and abs(got_gcps[1].GCPY - 49.5) <= 1e-5), \ + 'wrong gcp' # Lower-right - if abs(got_gcps[2].GCPPixel - 19.5) > 1e-5 or abs(got_gcps[2].GCPLine - 19.5) > 1e-5 or \ - abs(got_gcps[2].GCPX - 3) > 1e-5 or abs(got_gcps[2].GCPY - 48) > 1e-5: - gdaltest.post_reason('wrong gcp') - print(got_gcps[2]) - return 'fail' + assert (abs(got_gcps[2].GCPPixel - 19.5) <= 1e-5 and abs(got_gcps[2].GCPLine - 19.5) <= 1e-5 and \ + abs(got_gcps[2].GCPX - 3) <= 1e-5 and abs(got_gcps[2].GCPY - 48) <= 1e-5), \ + 'wrong gcp' # Lower-left - if abs(got_gcps[3].GCPPixel - 0.5) > 1e-5 or abs(got_gcps[3].GCPLine - 19.5) > 1e-5 or \ - abs(got_gcps[3].GCPX - 2) > 1e-5 or abs(got_gcps[3].GCPY - 48) > 1e-5: - gdaltest.post_reason('wrong gcp') - print(got_gcps[3]) - return 'fail' - - return 'success' + assert (abs(got_gcps[3].GCPPixel - 0.5) <= 1e-5 and abs(got_gcps[3].GCPLine - 19.5) <= 1e-5 and \ + abs(got_gcps[3].GCPX - 2) <= 1e-5 and abs(got_gcps[3].GCPY - 48) <= 1e-5), \ + 'wrong gcp' ############################################################################### # Create and read a JPEG encoded NITF file with NITF dimensions != JPEG dimensions -def nitf_70(): +def test_nitf_70(): src_ds = gdal.Open('data/rgbsmall.tif') @@ -2337,18 +1998,13 @@ def nitf_70(): gdal.GetDriverByName('NITF').Delete('tmp/nitf_70.ntf') gdal.GetDriverByName('GTiff').Delete('tmp/nitf_70.tif') - if cs != cs_ref: - print(cs) - print(cs_ref) - return 'fail' - - return 'success' + assert cs == cs_ref ############################################################################### # Test reading ENGRDA TRE (#6285) -def nitf_71(): +def test_nitf_71(): ds = gdal.GetDriverByName('NITF').Create('/vsimem/nitf_71.ntf', 1, 1, options=['TRE=ENGRDA=0123456789012345678900210012345678901230123X01200000002XY01X01230123X01200000001X']) ds = None @@ -2390,11 +2046,7 @@ def nitf_71(): </tre> </tres> """ - if data != expected_data: - print(data) - return 'fail' - - return 'success' + assert data == expected_data ############################################################################### # Test writing and reading RPC00B @@ -2405,27 +2057,19 @@ def compare_rpc(src_md, md): for key in src_md: if key == 'ERR_BIAS' or key == 'ERR_RAND': continue - if key not in md: - gdaltest.post_reason('fail: %s missing' % key) - print(md) - return 'fail' + assert key in md, ('fail: %s missing' % key) if 'COEFF' in key: expected = [float(v) for v in src_md[key].strip().split(' ')] found = [float(v) for v in md[key].strip().split(' ')] if expected != found: - gdaltest.post_reason('fail: %s value is not the one expected' % key) print(md) - print(found) - print(expected) - return 'fail' + pytest.fail('fail: %s value is not the one expected' % key) elif float(src_md[key]) != float(md[key]): - gdaltest.post_reason('fail: %s value is not the one expected' % key) print(md) - return 'fail' - return 'success' + pytest.fail('fail: %s value is not the one expected' % key) + - -def nitf_72(): +def test_nitf_72(): src_ds = gdal.GetDriverByName('MEM').Create('', 1, 1) # Use full precision @@ -2452,17 +2096,14 @@ def nitf_72(): gdal.GetDriverByName('NITF').CreateCopy('/vsimem/nitf_72.ntf', src_ds) - if gdal.GetLastErrorMsg() != '': - gdaltest.post_reason('fail: did not expect warning') - return 'fail' + assert gdal.GetLastErrorMsg() == '', 'fail: did not expect warning' if gdal.VSIStatL('/vsimem/nitf_72.ntf.aux.xml') is not None: - gdaltest.post_reason('fail: PAM file not expected') f = gdal.VSIFOpenL('/vsimem/nitf_72.ntf.aux.xml', 'rb') data = gdal.VSIFReadL(1, 10000, f) gdal.VSIFCloseL(f) print(str(data)) - return 'fail' + pytest.fail('fail: PAM file not expected') ds = gdal.Open('/vsimem/nitf_72.ntf') md = ds.GetMetadata('RPC') @@ -2471,14 +2112,10 @@ def nitf_72(): gdal.GetDriverByName('NITF').Delete('/vsimem/nitf_72.ntf') - if not compare_rpc(src_md, md): - return 'fail' + compare_rpc(src_md, md) expected_RPC00B_max_precision = '11234.562345.6734567845678-89.8765-179.1234-987698765467890-12.3456-123.4567-1234+0.000000E+0+9.876543E+9+9.876543E-9-9.876543E+9-9.876543E-9+0.000000E+0+9.876543E+9+9.876543E-9-9.876543E+9-9.876543E-9+0.000000E+0+9.876543E+9+9.876543E-9-9.876543E+9-9.876543E-9+0.000000E+0+9.876543E+9+9.876543E-9-9.876543E+9-9.876543E-9+1.000000E+0+9.876543E+9+9.876543E-9-9.876543E+9-9.876543E-9+0.000000E+0+9.876543E+9+9.876543E-9-9.876543E+9-9.876543E-9+0.000000E+0+9.876543E+9+9.876543E-9-9.876543E+9-9.876543E-9+0.000000E+0+9.876543E+9+9.876543E-9-9.876543E+9-9.876543E-9+2.000000E+0+9.876543E+9+9.876543E-9-9.876543E+9-9.876543E-9+0.000000E+0+9.876543E+9+9.876543E-9-9.876543E+9-9.876543E-9+0.000000E+0+9.876543E+9+9.876543E-9-9.876543E+9-9.876543E-9+0.000000E+0+9.876543E+9+9.876543E-9-9.876543E+9-9.876543E-9+3.000000E+0+9.876543E+9+9.876543E-9-9.876543E+9-9.876543E-9+0.000000E+0+9.876543E+9+9.876543E-9-9.876543E+9-9.876543E-9+0.000000E+0+9.876543E+9+9.876543E-9-9.876543E+9-9.876543E-9+0.000000E+0+9.876543E+9+9.876543E-9-9.876543E+9-9.876543E-9' - if RPC00B != expected_RPC00B_max_precision: - gdaltest.post_reason('fail: did not get expected RPC00B') - print(RPC00B) - return 'fail' + assert RPC00B == expected_RPC00B_max_precision, 'fail: did not get expected RPC00B' # Test without ERR_BIAS and ERR_RAND src_ds = gdal.GetDriverByName('MEM').Create('', 1, 1) @@ -2489,17 +2126,14 @@ def nitf_72(): gdal.GetDriverByName('NITF').CreateCopy('/vsimem/nitf_72.ntf', src_ds) - if gdal.GetLastErrorMsg() != '': - gdaltest.post_reason('fail: did not expect warning') - return 'fail' + assert gdal.GetLastErrorMsg() == '', 'fail: did not expect warning' if gdal.VSIStatL('/vsimem/nitf_72.ntf.aux.xml') is not None: - gdaltest.post_reason('fail: PAM file not expected') f = gdal.VSIFOpenL('/vsimem/nitf_72.ntf.aux.xml', 'rb') data = gdal.VSIFReadL(1, 10000, f) gdal.VSIFCloseL(f) print(str(data)) - return 'fail' + pytest.fail('fail: PAM file not expected') ds = gdal.Open('/vsimem/nitf_72.ntf') md = ds.GetMetadata('RPC') @@ -2507,10 +2141,7 @@ def nitf_72(): ds = None expected_RPC00B = '10000.000000.0034567845678-89.8765-179.1234-987698765467890-12.3456-123.4567-1234+0.000000E+0+9.876543E+9+9.876543E-9-9.876543E+9-9.876543E-9+0.000000E+0+9.876543E+9+9.876543E-9-9.876543E+9-9.876543E-9+0.000000E+0+9.876543E+9+9.876543E-9-9.876543E+9-9.876543E-9+0.000000E+0+9.876543E+9+9.876543E-9-9.876543E+9-9.876543E-9+1.000000E+0+9.876543E+9+9.876543E-9-9.876543E+9-9.876543E-9+0.000000E+0+9.876543E+9+9.876543E-9-9.876543E+9-9.876543E-9+0.000000E+0+9.876543E+9+9.876543E-9-9.876543E+9-9.876543E-9+0.000000E+0+9.876543E+9+9.876543E-9-9.876543E+9-9.876543E-9+2.000000E+0+9.876543E+9+9.876543E-9-9.876543E+9-9.876543E-9+0.000000E+0+9.876543E+9+9.876543E-9-9.876543E+9-9.876543E-9+0.000000E+0+9.876543E+9+9.876543E-9-9.876543E+9-9.876543E-9+0.000000E+0+9.876543E+9+9.876543E-9-9.876543E+9-9.876543E-9+3.000000E+0+9.876543E+9+9.876543E-9-9.876543E+9-9.876543E-9+0.000000E+0+9.876543E+9+9.876543E-9-9.876543E+9-9.876543E-9+0.000000E+0+9.876543E+9+9.876543E-9-9.876543E+9-9.876543E-9+0.000000E+0+9.876543E+9+9.876543E-9-9.876543E+9-9.876543E-9' - if RPC00B != expected_RPC00B: - gdaltest.post_reason('fail: did not get expected RPC00B') - print(RPC00B) - return 'fail' + assert RPC00B == expected_RPC00B, 'fail: did not get expected RPC00B' # Test that direct RPC00B copy works src_nitf_ds = gdal.Open('/vsimem/nitf_72.ntf') @@ -2521,10 +2152,7 @@ def nitf_72(): md = ds.GetMetadata('RPC') RPC00B = ds.GetMetadataItem('RPC00B', 'TRE') ds = None - if RPC00B != expected_RPC00B: - gdaltest.post_reason('fail: did not get expected RPC00B') - print(RPC00B) - return 'fail' + assert RPC00B == expected_RPC00B, 'fail: did not get expected RPC00B' gdal.GetDriverByName('NITF').Delete('/vsimem/nitf_72.ntf') gdal.GetDriverByName('NITF').Delete('/vsimem/nitf_72_copy.ntf') @@ -2532,9 +2160,8 @@ def nitf_72(): # Test that RPC00B = NO works gdal.GetDriverByName('NITF').CreateCopy('/vsimem/nitf_72.ntf', src_ds, options=['RPC00B=NO']) - if gdal.VSIStatL('/vsimem/nitf_72.ntf.aux.xml') is None: - gdaltest.post_reason('fail: PAM file was expected') - return 'fail' + assert gdal.VSIStatL('/vsimem/nitf_72.ntf.aux.xml') is not None, \ + 'fail: PAM file was expected' ds = gdal.Open('/vsimem/nitf_72.ntf') md = ds.GetMetadata('RPC') @@ -2542,10 +2169,7 @@ def nitf_72(): ds = None gdal.GetDriverByName('NITF').Delete('/vsimem/nitf_72.ntf') - if RPC00B is not None: - gdaltest.post_reason('fail: did not expect RPC00B') - print(RPC00B) - return 'fail' + assert RPC00B is None, 'fail: did not expect RPC00B' src_ds = gdal.GetDriverByName('MEM').Create('', 1, 1) # Test padding @@ -2571,17 +2195,14 @@ def nitf_72(): gdal.GetDriverByName('NITF').CreateCopy('/vsimem/nitf_72.ntf', src_ds) - if gdal.GetLastErrorMsg() != '': - gdaltest.post_reason('fail: did not expect warning') - return 'fail' + assert gdal.GetLastErrorMsg() == '', 'fail: did not expect warning' if gdal.VSIStatL('/vsimem/nitf_72.ntf.aux.xml') is not None: - gdaltest.post_reason('fail: PAM file not expected') f = gdal.VSIFOpenL('/vsimem/nitf_72.ntf.aux.xml', 'rb') data = gdal.VSIFReadL(1, 10000, f) gdal.VSIFCloseL(f) print(str(data)) - return 'fail' + pytest.fail('fail: PAM file not expected') ds = gdal.Open('/vsimem/nitf_72.ntf') md = ds.GetMetadata('RPC') @@ -2590,14 +2211,10 @@ def nitf_72(): gdal.GetDriverByName('NITF').Delete('/vsimem/nitf_72.ntf') - if not compare_rpc(src_md, md): - return 'fail' + compare_rpc(src_md, md) expected_RPC00B = '10123.000234.0000345604567+08.0000+017.0000+098709876506789+12.0000+109.0000+0034+0.000000E+0+9.870000E+9+9.876543E-9-9.876543E+9-9.876543E-9+0.000000E+0+9.876543E+9+9.876543E-9-9.876543E+9-9.876543E-9+0.000000E+0+9.876543E+9+9.876543E-9-9.876543E+9-9.876543E-9+0.000000E+0+9.876543E+9+9.876543E-9-9.876543E+9-9.876543E-9+1.000000E+0+9.876543E+9+9.876543E-9-9.876543E+9-9.876543E-9+0.000000E+0+9.876543E+9+9.876543E-9-9.876543E+9-9.876543E-9+0.000000E+0+9.876543E+9+9.876543E-9-9.876543E+9-9.876543E-9+0.000000E+0+9.876543E+9+9.876543E-9-9.876543E+9-9.876543E-9+2.000000E+0+9.876543E+9+9.876543E-9-9.876543E+9-9.876543E-9+0.000000E+0+9.876543E+9+9.876543E-9-9.876543E+9-9.876543E-9+0.000000E+0+9.876543E+9+9.876543E-9-9.876543E+9-9.876543E-9+0.000000E+0+9.876543E+9+9.876543E-9-9.876543E+9-9.876543E-9+3.000000E+0+9.876543E+9+9.876543E-9-9.876543E+9-9.876543E-9+0.000000E+0+9.876543E+9+9.876543E-9-9.876543E+9-9.876543E-9+0.000000E+0+9.876543E+9+9.876543E-9-9.876543E+9-9.876543E-9+0.000000E+0+9.876543E+9+9.876543E-9-9.876543E+9-9.876543E-9' - if RPC00B != expected_RPC00B: - gdaltest.post_reason('fail: did not get expected RPC00B') - print(RPC00B) - return 'fail' + assert RPC00B == expected_RPC00B, 'fail: did not get expected RPC00B' # Test loss of precision for key in ('LINE_OFF', 'SAMP_OFF', 'LAT_OFF', 'LONG_OFF', 'HEIGHT_OFF', 'LINE_SCALE', 'SAMP_SCALE', 'LAT_SCALE', 'LONG_SCALE', 'HEIGHT_SCALE'): @@ -2612,18 +2229,13 @@ def nitf_72(): with gdaltest.error_handler(): ds = gdal.GetDriverByName('NITF').CreateCopy('/vsimem/nitf_72.ntf', src_ds) - if ds is None: - gdaltest.post_reason('fail: expected a dataset') - return 'fail' + assert ds is not None, 'fail: expected a dataset' ds = None - if gdal.GetLastErrorMsg() == '': - gdaltest.post_reason('fail: expected a warning') - return 'fail' + assert gdal.GetLastErrorMsg() != '', 'fail: expected a warning' - if gdal.VSIStatL('/vsimem/nitf_72.ntf.aux.xml') is None: - gdaltest.post_reason('fail: PAM file was expected') - return 'fail' + assert gdal.VSIStatL('/vsimem/nitf_72.ntf.aux.xml') is not None, \ + 'fail: PAM file was expected' gdal.Unlink('/vsimem/nitf_72.ntf.aux.xml') ds = gdal.Open('/vsimem/nitf_72.ntf') @@ -2633,10 +2245,8 @@ def nitf_72(): gdal.GetDriverByName('NITF').Delete('/vsimem/nitf_72.ntf') - if RPC00B != expected_RPC00B_max_precision: - gdaltest.post_reason('fail: did not get expected RPC00B') - print(RPC00B) - return 'fail' + assert RPC00B == expected_RPC00B_max_precision, \ + 'fail: did not get expected RPC00B' # Test loss of precision on coefficient lines src_ds = gdal.GetDriverByName('MEM').Create('', 1, 1) @@ -2646,18 +2256,13 @@ def nitf_72(): with gdaltest.error_handler(): ds = gdal.GetDriverByName('NITF').CreateCopy('/vsimem/nitf_72.ntf', src_ds) - if ds is None: - gdaltest.post_reason('fail: expected a dataset') - return 'fail' + assert ds is not None, 'fail: expected a dataset' ds = None - if gdal.GetLastErrorMsg() == '': - gdaltest.post_reason('fail: expected a warning') - return 'fail' + assert gdal.GetLastErrorMsg() != '', 'fail: expected a warning' - if gdal.VSIStatL('/vsimem/nitf_72.ntf.aux.xml') is None: - gdaltest.post_reason('fail: PAM file was expected') - return 'fail' + assert gdal.VSIStatL('/vsimem/nitf_72.ntf.aux.xml') is not None, \ + 'fail: PAM file was expected' gdal.Unlink('/vsimem/nitf_72.ntf.aux.xml') ds = gdal.Open('/vsimem/nitf_72.ntf') @@ -2668,23 +2273,18 @@ def nitf_72(): gdal.GetDriverByName('NITF').Delete('/vsimem/nitf_72.ntf') expected_RPC00B = '11234.562345.6734567845678-89.8765-179.1234-987698765467890-12.3456-123.4567-1234+0.000000E+0+0.000000E+0+9.876543E-9-9.876543E+9-9.876543E-9+0.000000E+0+9.876543E+9+9.876543E-9-9.876543E+9-9.876543E-9+0.000000E+0+9.876543E+9+9.876543E-9-9.876543E+9-9.876543E-9+0.000000E+0+9.876543E+9+9.876543E-9-9.876543E+9-9.876543E-9+1.000000E+0+9.876543E+9+9.876543E-9-9.876543E+9-9.876543E-9+0.000000E+0+9.876543E+9+9.876543E-9-9.876543E+9-9.876543E-9+0.000000E+0+9.876543E+9+9.876543E-9-9.876543E+9-9.876543E-9+0.000000E+0+9.876543E+9+9.876543E-9-9.876543E+9-9.876543E-9+2.000000E+0+9.876543E+9+9.876543E-9-9.876543E+9-9.876543E-9+0.000000E+0+9.876543E+9+9.876543E-9-9.876543E+9-9.876543E-9+0.000000E+0+9.876543E+9+9.876543E-9-9.876543E+9-9.876543E-9+0.000000E+0+9.876543E+9+9.876543E-9-9.876543E+9-9.876543E-9+3.000000E+0+9.876543E+9+9.876543E-9-9.876543E+9-9.876543E-9+0.000000E+0+9.876543E+9+9.876543E-9-9.876543E+9-9.876543E-9+0.000000E+0+9.876543E+9+9.876543E-9-9.876543E+9-9.876543E-9+0.000000E+0+9.876543E+9+9.876543E-9-9.876543E+9-9.876543E-9' - if RPC00B != expected_RPC00B: - gdaltest.post_reason('fail: did not get expected RPC00B') - print(RPC00B) - return 'fail' + assert RPC00B == expected_RPC00B, 'fail: did not get expected RPC00B' # Test RPCTXT creation option with gdaltest.error_handler(): gdal.GetDriverByName('NITF').CreateCopy('/vsimem/nitf_72.ntf', src_ds, options=['RPCTXT=YES']) - if gdal.VSIStatL('/vsimem/nitf_72.ntf.aux.xml') is None: - gdaltest.post_reason('fail: PAM file was expected') - return 'fail' + assert gdal.VSIStatL('/vsimem/nitf_72.ntf.aux.xml') is not None, \ + 'fail: PAM file was expected' gdal.Unlink('/vsimem/nitf_72.ntf.aux.xml') - if gdal.VSIStatL('/vsimem/nitf_72_RPC.TXT') is None: - gdaltest.post_reason('fail: rpc.txt file was expected') - return 'fail' + assert gdal.VSIStatL('/vsimem/nitf_72_RPC.TXT') is not None, \ + 'fail: rpc.txt file was expected' ds = gdal.Open('/vsimem/nitf_72.ntf') md = ds.GetMetadata('RPC') @@ -2692,19 +2292,13 @@ def nitf_72(): fl = ds.GetFileList() ds = None - if '/vsimem/nitf_72_RPC.TXT' not in fl: - gdaltest.post_reason('fail: _RPC.TXT file not reported in file list') - print(fl) - return 'fail' + assert '/vsimem/nitf_72_RPC.TXT' in fl, \ + 'fail: _RPC.TXT file not reported in file list' # Check that we get full precision from the _RPC.TXT file - if not compare_rpc(src_md, md): - return 'fail' + compare_rpc(src_md, md) - if RPC00B != expected_RPC00B: - gdaltest.post_reason('fail: did not get expected RPC00B') - print(RPC00B) - return 'fail' + assert RPC00B == expected_RPC00B, 'fail: did not get expected RPC00B' # Test out of range for key in ('LINE_OFF', 'SAMP_OFF', 'LAT_OFF', 'LONG_OFF', 'HEIGHT_OFF', 'LINE_SCALE', 'SAMP_SCALE', 'LAT_SCALE', 'LONG_SCALE', 'HEIGHT_SCALE'): @@ -2719,9 +2313,7 @@ def nitf_72(): with gdaltest.error_handler(): ds = gdal.GetDriverByName('NITF').CreateCopy('/vsimem/nitf_72.ntf', src_ds) - if ds is not None: - gdaltest.post_reason('fail: expected failure for %s' % key) - return 'fail' + assert ds is None, ('fail: expected failure for %s' % key) # Test out of rangeon coefficient lines src_ds = gdal.GetDriverByName('MEM').Create('', 1, 1) @@ -2731,29 +2323,24 @@ def nitf_72(): with gdaltest.error_handler(): ds = gdal.GetDriverByName('NITF').CreateCopy('/vsimem/nitf_72.ntf', src_ds) - if ds is not None: - gdaltest.post_reason('fail: expected failure') - return 'fail' - - return 'success' + assert ds is None, 'fail: expected failure' ############################################################################### # Test case for https://bugs.chromium.org/p/oss-fuzz/issues/detail?id=1525 -def nitf_73(): +def test_nitf_73(): with gdaltest.error_handler(): gdal.Open('data/oss_fuzz_1525.ntf') - return 'success' - + ############################################################################### # Test cases for CCLSTA # - Simple case -def nitf_74(): +def test_nitf_74(): ds = gdal.GetDriverByName('NITF').Create('/vsimem/nitf_74.ntf', 1, 1, options=['FILE_TRE=CCINFA=0012AS 17ge:GENC:3:3-5:AUS00000']) ds = None @@ -2780,16 +2367,12 @@ def nitf_74(): </tre> </tres> """ - if data != expected_data: - print(data) - return 'fail' - - return 'success' + assert data == expected_data # - TABLE AG.2 case -def nitf_75(): +def test_nitf_75(): listing_AG1 = """<?xml version="1.0" encoding="UTF-8"?> <genc:GeopoliticalEntityEntry @@ -2978,34 +2561,26 @@ def nitf_75(): </tres> """ - if data != expected_data: - print(data) - return 'fail' - - return 'success' + assert data == expected_data ############################################################################### # Test reading C4 compressed file -def nitf_read_C4(): +def test_nitf_read_C4(): ds = gdal.Open('data/RPFTOC01.ON2') cs = ds.GetRasterBand(1).Checksum() - if cs != 53599: - print(cs) - return 'fail' - - return 'success' + assert cs == 53599 ############################################################################### # Test NITF21_CGM_ANNO_Uncompressed_unmasked.ntf for bug #1313 and #1714 -def nitf_online_1(): +def test_nitf_online_1(): if not gdaltest.download_file('http://download.osgeo.org/gdal/data/nitf/bugs/NITF21_CGM_ANNO_Uncompressed_unmasked.ntf', 'NITF21_CGM_ANNO_Uncompressed_unmasked.ntf'): - return 'skip' + pytest.skip() tst = gdaltest.GDALTest('NITF', 'tmp/cache/NITF21_CGM_ANNO_Uncompressed_unmasked.ntf', 1, 13123, filename_absolute=1) @@ -3020,29 +2595,25 @@ def nitf_online_1(): # Test NITF file with multiple images -def nitf_online_2(): +def test_nitf_online_2(): if not gdaltest.download_file('http://download.osgeo.org/gdal/data/nitf/nitf1.1/U_0001a.ntf', 'U_0001a.ntf'): - return 'skip' + pytest.skip() ds = gdal.Open('tmp/cache/U_0001a.ntf') md = ds.GetMetadata('SUBDATASETS') - if 'SUBDATASET_1_NAME' not in md: - gdaltest.post_reason('missing SUBDATASET_1_NAME metadata') - return 'fail' + assert 'SUBDATASET_1_NAME' in md, 'missing SUBDATASET_1_NAME metadata' ds = None - return 'success' - ############################################################################### # Test ARIDPCM (C2) image -def nitf_online_3(): +def test_nitf_online_3(): if not gdaltest.download_file('http://download.osgeo.org/gdal/data/nitf/nitf1.1/U_0001a.ntf', 'U_0001a.ntf'): - return 'skip' + pytest.skip() tst = gdaltest.GDALTest('NITF', 'NITF_IM:3:tmp/cache/U_0001a.ntf', 1, 23463, filename_absolute=1) @@ -3052,19 +2623,16 @@ def nitf_online_3(): # Test Vector Quantization (VQ) (C4) file -def nitf_online_4(): +def test_nitf_online_4(): if not gdaltest.download_file('http://download.osgeo.org/gdal/data/nitf/cadrg/001zc013.on1', '001zc013.on1'): - return 'skip' + pytest.skip() # check that the RPF attribute metadata was carried through. ds = gdal.Open('tmp/cache/001zc013.on1') md = ds.GetMetadata() - if md['NITF_RPF_CurrencyDate'] != '19950720' \ - or md['NITF_RPF_ProductionDate'] != '19950720' \ - or md['NITF_RPF_SignificantDate'] != '19890629': - gdaltest.post_reason('RPF attribute metadata not captured (#3413)') - return 'fail' + assert md['NITF_RPF_CurrencyDate'] == '19950720' and md['NITF_RPF_ProductionDate'] == '19950720' and md['NITF_RPF_SignificantDate'] == '19890629', \ + 'RPF attribute metadata not captured (#3413)' ds = None @@ -3076,10 +2644,10 @@ def nitf_online_4(): # Test Vector Quantization (VQ) (M4) file -def nitf_online_5(): +def test_nitf_online_5(): if not gdaltest.download_file('http://download.osgeo.org/gdal/data/nitf/cadrg/overview.ovr', 'overview.ovr'): - return 'skip' + pytest.skip() tst = gdaltest.GDALTest('NITF', 'tmp/cache/overview.ovr', 1, 60699, filename_absolute=1) @@ -3089,10 +2657,10 @@ def nitf_online_5(): # Test a JPEG compressed, single blocked 2048x2048 mono image -def nitf_online_6(): +def test_nitf_online_6(): if not gdaltest.download_file('http://download.osgeo.org/gdal/data/nitf/nitf2.0/U_4001b.ntf', 'U_4001b.ntf'): - return 'skip' + pytest.skip() tst = gdaltest.GDALTest('NITF', 'tmp/cache/U_4001b.ntf', 1, 60030, filename_absolute=1) @@ -3102,42 +2670,37 @@ def nitf_online_6(): ############################################################################### # Test all combinations of IMODE (S,P,B,R) for an image with 6 bands whose 3 are RGB -def nitf_online_7(): +def test_nitf_online_7(): for filename in ['ns3228b.nsf', 'i_3228c.ntf', 'ns3228d.nsf', 'i_3228e.ntf']: if not gdaltest.download_file('http://www.gwg.nga.mil/ntb/baseline/software/testfile/Nitfv2_1/' + filename, filename): - return 'skip' + pytest.skip() ds = gdal.Open('tmp/cache/' + filename) - if ds.RasterCount != 6: - return 'fail' + assert ds.RasterCount == 6 checksums = [48385, 48385, 40551, 54223, 48385, 33094] colorInterpretations = [gdal.GCI_Undefined, gdal.GCI_Undefined, gdal.GCI_RedBand, gdal.GCI_BlueBand, gdal.GCI_Undefined, gdal.GCI_GreenBand] for i in range(6): cs = ds.GetRasterBand(i + 1).Checksum() - if cs != checksums[i]: - gdaltest.post_reason('got checksum %d for image %s' + assert cs == checksums[i], ('got checksum %d for image %s' % (cs, filename)) - return 'fail' - if ds.GetRasterBand(i + 1).GetRasterColorInterpretation() != colorInterpretations[i]: - gdaltest.post_reason('got wrong color interp for image %s' + assert ds.GetRasterBand(i + 1).GetRasterColorInterpretation() == colorInterpretations[i], \ + ('got wrong color interp for image %s' % filename) - return 'fail' ds = None - return 'success' - + ############################################################################### # Test JPEG-compressed multi-block mono-band image with a data mask subheader (IC=M3, IMODE=B) -def nitf_online_8(): +def test_nitf_online_8(): if not gdaltest.download_file('http://www.gwg.nga.mil/ntb/baseline/software/testfile/Nitfv2_1/ns3301j.nsf', 'ns3301j.nsf'): - return 'skip' + pytest.skip() tst = gdaltest.GDALTest('NITF', 'tmp/cache/ns3301j.nsf', 1, 56861, filename_absolute=1) @@ -3147,10 +2710,10 @@ def nitf_online_8(): ############################################################################### # Test JPEG-compressed multi-block mono-band image without a data mask subheader (IC=C3, IMODE=B) -def nitf_online_9(): +def test_nitf_online_9(): if not gdaltest.download_file('http://www.gwg.nga.mil/ntb/baseline/software/testfile/Nitfv2_1/ns3304a.nsf', 'ns3304a.nsf'): - return 'skip' + pytest.skip() tst = gdaltest.GDALTest('NITF', 'tmp/cache/ns3304a.nsf', 1, 32419, filename_absolute=1) @@ -3160,10 +2723,10 @@ def nitf_online_9(): ############################################################################### # Verify that CGM access on a file with 8 CGM segments -def nitf_online_10(): +def test_nitf_online_10(): if not gdaltest.download_file('http://www.gwg.nga.mil/ntb/baseline/software/testfile/Nitfv2_1/ns3119b.nsf', 'ns3119b.nsf'): - return 'skip' + pytest.skip() # Shut up the warning about missing image segment gdal.PushErrorHandler('CPLQuietErrorHandler') @@ -3174,9 +2737,7 @@ def nitf_online_10(): ds = None - if mdCGM['SEGMENT_COUNT'] != '8': - gdaltest.post_reason('wrong SEGMENT_COUNT.') - return 'fail' + assert mdCGM['SEGMENT_COUNT'] == '8', 'wrong SEGMENT_COUNT.' tab = [ ('SEGMENT_0_SLOC_ROW', '0'), @@ -3206,20 +2767,17 @@ def nitf_online_10(): ] for item in tab: - if mdCGM[item[0]] != item[1]: - gdaltest.post_reason('wrong value for %s.' % item[0]) - return 'fail' - - return 'success' + assert mdCGM[item[0]] == item[1], ('wrong value for %s.' % item[0]) + ############################################################################### # 5 text files -def nitf_online_11(): +def test_nitf_online_11(): if not gdaltest.download_file('http://download.osgeo.org/gdal/data/nitf/nitf2.0/U_1122a.ntf', 'U_1122a.ntf'): - return 'skip' + pytest.skip() ds = gdal.Open('tmp/cache/U_1122a.ntf') @@ -3227,32 +2785,25 @@ def nitf_online_11(): ds = None - if mdTEXT['DATA_0'] != 'This is test text file 01.\r\n': - gdaltest.post_reason('did not find expected DATA_0 from metadata.') - return 'fail' - if mdTEXT['DATA_1'] != 'This is test text file 02.\r\n': - gdaltest.post_reason('did not find expected DATA_1 from metadata.') - return 'fail' - if mdTEXT['DATA_2'] != 'This is test text file 03.\r\n': - gdaltest.post_reason('did not find expected DATA_2 from metadata.') - return 'fail' - if mdTEXT['DATA_3'] != 'This is test text file 04.\r\n': - gdaltest.post_reason('did not find expected DATA_3 from metadata.') - return 'fail' - if mdTEXT['DATA_4'] != 'This is test text file 05.\r\n': - gdaltest.post_reason('did not find expected DATA_4 from metadata.') - return 'fail' - - return 'success' + assert mdTEXT['DATA_0'] == 'This is test text file 01.\r\n', \ + 'did not find expected DATA_0 from metadata.' + assert mdTEXT['DATA_1'] == 'This is test text file 02.\r\n', \ + 'did not find expected DATA_1 from metadata.' + assert mdTEXT['DATA_2'] == 'This is test text file 03.\r\n', \ + 'did not find expected DATA_2 from metadata.' + assert mdTEXT['DATA_3'] == 'This is test text file 04.\r\n', \ + 'did not find expected DATA_3 from metadata.' + assert mdTEXT['DATA_4'] == 'This is test text file 05.\r\n', \ + 'did not find expected DATA_4 from metadata.' ############################################################################### # Test 12 bit uncompressed image. -def nitf_online_12(): +def test_nitf_online_12(): if not gdaltest.download_file('http://download.osgeo.org/gdal/data/nitf/bugs/i_3430a.ntf', 'i_3430a.ntf'): - return 'skip' + pytest.skip() tst = gdaltest.GDALTest('NITF', 'tmp/cache/i_3430a.ntf', 1, 38647, filename_absolute=1) @@ -3263,10 +2814,10 @@ def nitf_online_12(): ############################################################################### # Test complex relative graphic/image attachment. -def nitf_online_13(): +def test_nitf_online_13(): if not gdaltest.download_file('http://download.osgeo.org/gdal/data/nitf/u_3054a.ntf', 'u_3054a.ntf'): - return 'skip' + pytest.skip() # Shut up the warning about missing image segment ds = gdal.Open('NITF_IM:2:tmp/cache/u_3054a.ntf') @@ -3276,9 +2827,7 @@ def nitf_online_13(): ds = None - if mdCGM['SEGMENT_COUNT'] != '3': - gdaltest.post_reason('wrong SEGMENT_COUNT.') - return 'fail' + assert mdCGM['SEGMENT_COUNT'] == '3', 'wrong SEGMENT_COUNT.' tab = [ ('SEGMENT_2_SLOC_ROW', '0'), @@ -3290,9 +2839,7 @@ def nitf_online_13(): ] for item in tab: - if mdCGM[item[0]] != item[1]: - gdaltest.post_reason('wrong value for %s.' % item[0]) - return 'fail' + assert mdCGM[item[0]] == item[1], ('wrong value for %s.' % item[0]) tab = [ ('NITF_IDLVL', '3'), @@ -3304,44 +2851,35 @@ def nitf_online_13(): ] for item in tab: - if md[item[0]] != item[1]: - gdaltest.post_reason('wrong value for %s, got %s instead of %s.' + assert md[item[0]] == item[1], ('wrong value for %s, got %s instead of %s.' % (item[0], md[item[0]], item[1])) - return 'fail' - return 'success' ############################################################################### # Check reading a 12-bit JPEG compressed NITF (multi-block) -def nitf_online_14(): +def test_nitf_online_14(not_jpeg_9b): if not gdaltest.download_file('http://download.osgeo.org/gdal/data/nitf/nitf2.0/U_4020h.ntf', 'U_4020h.ntf'): - return 'skip' + pytest.skip() try: os.remove('tmp/cache/U_4020h.ntf.aux.xml') except OSError: pass - if gdaltest.jpeg_version == '9b': - return 'skip' - # Check if JPEG driver supports 12bit JPEG reading/writing jpg_drv = gdal.GetDriverByName('JPEG') md = jpg_drv.GetMetadata() if md[gdal.DMD_CREATIONDATATYPES].find('UInt16') == -1: sys.stdout.write('(12bit jpeg not available) ... ') - return 'skip' + pytest.skip() ds = gdal.Open('tmp/cache/U_4020h.ntf') - if ds.GetRasterBand(1).DataType != gdal.GDT_UInt16: - return 'fail' + assert ds.GetRasterBand(1).DataType == gdal.GDT_UInt16 stats = ds.GetRasterBand(1).GetStatistics(0, 1) - if stats[2] < 2607 or stats[2] > 2608: - print(stats) - return 'fail' + assert stats[2] >= 2607 and stats[2] <= 2608 ds = None try: @@ -3349,20 +2887,19 @@ def nitf_online_14(): except OSError: pass - return 'success' - + ############################################################################### # Test opening a IC=C8 NITF file with the various JPEG2000 drivers def nitf_online_15(driver_to_test, expected_cs=1054): if not gdaltest.download_file('http://www.gwg.nga.mil/ntb/baseline/software/testfile/Jpeg2000/p0_01/p0_01a.ntf', 'p0_01a.ntf'): - return 'skip' + pytest.skip() jp2_drv = gdal.GetDriverByName(driver_to_test) if jp2_drv is None: - return 'skip' + pytest.skip() # Deregister other potential conflicting JPEG2000 drivers gdaltest.deregister_all_jpeg2000_drivers_but(driver_to_test) @@ -3380,23 +2917,23 @@ def nitf_online_15(driver_to_test, expected_cs=1054): return ret -def nitf_online_15_jp2ecw(): +def test_nitf_online_15_jp2ecw(): return nitf_online_15('JP2ECW') -def nitf_online_15_jp2mrsid(): +def test_nitf_online_15_jp2mrsid(): return nitf_online_15('JP2MrSID') -def nitf_online_15_jp2kak(): +def test_nitf_online_15_jp2kak(): return nitf_online_15('JP2KAK') -def nitf_online_15_jasper(): +def test_nitf_online_15_jasper(): return nitf_online_15('JPEG2000') -def nitf_online_15_openjpeg(): +def test_nitf_online_15_openjpeg(): return nitf_online_15('JP2OpenJPEG') ############################################################################### @@ -3406,12 +2943,12 @@ def nitf_online_15_openjpeg(): def nitf_online_16(driver_to_test): if not gdaltest.download_file('http://www.gwg.nga.mil/ntb/baseline/software/testfile/Jpeg2000/jp2_09/file9_jp2_2places.ntf', 'file9_jp2_2places.ntf'): - return 'skip' + pytest.skip() jp2_drv = gdal.GetDriverByName(driver_to_test) if jp2_drv is None: - return 'skip' + pytest.skip() # Deregister other potential conflicting JPEG2000 drivers gdaltest.deregister_all_jpeg2000_drivers_but(driver_to_test) @@ -3441,23 +2978,23 @@ def nitf_online_16(driver_to_test): return ret -def nitf_online_16_jp2ecw(): +def test_nitf_online_16_jp2ecw(): return nitf_online_16('JP2ECW') -def nitf_online_16_jp2mrsid(): +def test_nitf_online_16_jp2mrsid(): return nitf_online_16('JP2MrSID') -def nitf_online_16_jp2kak(): +def test_nitf_online_16_jp2kak(): return nitf_online_16('JP2KAK') -def nitf_online_16_jasper(): +def test_nitf_online_16_jasper(): return nitf_online_16('JPEG2000') -def nitf_online_16_openjpeg(): +def test_nitf_online_16_openjpeg(): return nitf_online_16('JP2OpenJPEG') ############################################################################### @@ -3467,12 +3004,12 @@ def nitf_online_16_openjpeg(): def nitf_online_17(driver_to_test): if not gdaltest.download_file('http://www.gwg.nga.mil/ntb/baseline/software/testfile/Jpeg2000/jp2_09/file9_j2c.ntf', 'file9_j2c.ntf'): - return 'skip' + pytest.skip() jp2_drv = gdal.GetDriverByName(driver_to_test) if jp2_drv is None: - return 'skip' + pytest.skip() # Deregister other potential conflicting JPEG2000 drivers gdaltest.deregister_all_jpeg2000_drivers_but(driver_to_test) @@ -3495,32 +3032,32 @@ def nitf_online_17(driver_to_test): return ret -def nitf_online_17_jp2ecw(): +def test_nitf_online_17_jp2ecw(): return nitf_online_17('JP2ECW') -def nitf_online_17_jp2mrsid(): +def test_nitf_online_17_jp2mrsid(): return nitf_online_17('JP2MrSID') -def nitf_online_17_jp2kak(): +def test_nitf_online_17_jp2kak(): return nitf_online_17('JP2KAK') -def nitf_online_17_jasper(): +def test_nitf_online_17_jasper(): return nitf_online_17('JPEG2000') -def nitf_online_17_openjpeg(): +def test_nitf_online_17_openjpeg(): return nitf_online_17('JP2OpenJPEG') ############################################################################### # Test polar stereographic CADRG tile. -def nitf_online_18(): +def test_nitf_online_18(): if not gdaltest.download_file('http://download.osgeo.org/gdal/data/nitf/bugs/bug3337.ntf', 'bug3337.ntf'): - return 'skip' + pytest.skip() ds = gdal.Open('tmp/cache/bug3337.ntf') @@ -3529,48 +3066,34 @@ def nitf_online_18(): # If we have functioning coordinate transformer. if prj[:6] == 'PROJCS': - if prj.find('Azimuthal_Equidistant') == -1: - gdaltest.post_reason('wrong projection?') - return 'fail' + assert prj.find('Azimuthal_Equidistant') != -1, 'wrong projection?' expected_gt = (-1669792.3618991028, 724.73626818537502, 0.0, -556597.45396636717, 0.0, -724.73626818537434) - if not gdaltest.geotransform_equals(gt, expected_gt, 1.0): - gdaltest.post_reason('did not get expected geotransform.') - return 'fail' + assert gdaltest.geotransform_equals(gt, expected_gt, 1.0), \ + 'did not get expected geotransform.' # If we do not have a functioning coordinate transformer. else: - if prj != '' \ - or not gdaltest.geotransform_equals(gt, (0, 1, 0, 0, 0, 1), 0.00000001): - print(gt) - print(prj) - gdaltest.post_reason('did not get expected empty gt/projection') - return 'fail' + assert prj == '' and gdaltest.geotransform_equals(gt, (0, 1, 0, 0, 0, 1), 0.00000001), \ + 'did not get expected empty gt/projection' prj = ds.GetGCPProjection() - if prj[:6] != 'GEOGCS': - gdaltest.post_reason('did not get expected geographic srs') - return 'fail' + assert prj[:6] == 'GEOGCS', 'did not get expected geographic srs' gcps = ds.GetGCPs() gcp3 = gcps[3] - if gcp3.GCPPixel != 0 or gcp3.GCPLine != 1536 \ - or abs(gcp3.GCPX + 45) > 0.0000000001 \ - or abs(gcp3.GCPY - 68.78679656) > 0.00000001: - gdaltest.post_reason('did not get expected gcp.') - return 'fail' + assert gcp3.GCPPixel == 0 and gcp3.GCPLine == 1536 and abs(gcp3.GCPX + 45) <= 0.0000000001 and abs(gcp3.GCPY - 68.78679656) <= 0.00000001, \ + 'did not get expected gcp.' ds = None - return 'success' - ############################################################################### # Test CADRG tile crossing dateline (#3383) -def nitf_online_19(): +def test_nitf_online_19(): if not gdaltest.download_file('http://download.osgeo.org/gdal/data/nitf/0000M033.GN3', '0000M033.GN3'): - return 'skip' + pytest.skip() tst = gdaltest.GDALTest('NITF', 'tmp/cache/0000M033.GN3', 1, 38928, filename_absolute=1) @@ -3584,55 +3107,46 @@ def nitf_online_19(): # smaller than really available -def nitf_online_20(): +def test_nitf_online_20(): if not gdaltest.download_file('http://download.osgeo.org/gdal/data/nitf/0000M033.GN3', '0000M033.GN3'): - return 'skip' + pytest.skip() # check that the RPF attribute metadata was carried through. # Special case where the reported size of the attribute subsection is # smaller than really available ds = gdal.Open('tmp/cache/0000M033.GN3') md = ds.GetMetadata() - if md['NITF_RPF_CurrencyDate'] != '19941201' \ - or md['NITF_RPF_ProductionDate'] != '19980511' \ - or md['NITF_RPF_SignificantDate'] != '19850305': - gdaltest.post_reason('RPF attribute metadata not captured (#3413)') - return 'fail' - - return 'success' + assert md['NITF_RPF_CurrencyDate'] == '19941201' and md['NITF_RPF_ProductionDate'] == '19980511' and md['NITF_RPF_SignificantDate'] == '19850305', \ + 'RPF attribute metadata not captured (#3413)' ############################################################################### # Check that we can read NITF header located in STREAMING_FILE_HEADER DE # segment when header at beginning of file is incomplete -def nitf_online_21(): +def test_nitf_online_21(): if not gdaltest.download_file('http://www.gwg.nga.mil/ntb/baseline/software/testfile/Nitfv2_1/ns3321a.nsf', 'ns3321a.nsf'): - return 'skip' + pytest.skip() ds = gdal.Open('tmp/cache/ns3321a.nsf') md = ds.GetMetadata() ds = None # If we get NS3321A, it means we are not exploiting the header from the STREAMING_FILE_HEADER DE segment - if md['NITF_OSTAID'] != 'I_3321A': - gdaltest.post_reason('did not get expected OSTAID value') - print(md['NITF_OSTAID']) - return 'fail' - - return 'success' + assert md['NITF_OSTAID'] == 'I_3321A', \ + 'did not get expected OSTAID value' ############################################################################### # Test fix for #3002 (reconcile NITF file with LA segments) # -def nitf_online_22(): +def test_nitf_online_22(): if not gdaltest.download_file('http://www.gwg.nga.mil/ntb/baseline/software/testfile/Nitfv1_1/U_0001C.NTF', 'U_0001C.NTF'): - return 'skip' + pytest.skip() ds = gdal.Open('NITF_IM:1:tmp/cache/U_0001C.NTF') md = ds.GetMetadata() @@ -3648,10 +3162,8 @@ def nitf_online_22(): ] for item in tab: - if md[item[0]] != item[1]: - gdaltest.post_reason('(1) wrong value for %s, got %s instead of %s.' + assert md[item[0]] == item[1], ('(1) wrong value for %s, got %s instead of %s.' % (item[0], md[item[0]], item[1])) - return 'fail' ds = gdal.Open('NITF_IM:2:tmp/cache/U_0001C.NTF') md = ds.GetMetadata() @@ -3667,10 +3179,8 @@ def nitf_online_22(): ] for item in tab: - if md[item[0]] != item[1]: - gdaltest.post_reason('(2) wrong value for %s, got %s instead of %s.' + assert md[item[0]] == item[1], ('(2) wrong value for %s, got %s instead of %s.' % (item[0], md[item[0]], item[1])) - return 'fail' ds = gdal.Open('NITF_IM:3:tmp/cache/U_0001C.NTF') md = ds.GetMetadata() @@ -3686,10 +3196,8 @@ def nitf_online_22(): ] for item in tab: - if md[item[0]] != item[1]: - gdaltest.post_reason('(3) wrong value for %s, got %s instead of %s.' + assert md[item[0]] == item[1], ('(3) wrong value for %s, got %s instead of %s.' % (item[0], md[item[0]], item[1])) - return 'fail' ds = gdal.Open('NITF_IM:4:tmp/cache/U_0001C.NTF') md = ds.GetMetadata() @@ -3705,21 +3213,18 @@ def nitf_online_22(): ] for item in tab: - if md[item[0]] != item[1]: - gdaltest.post_reason('(4) wrong value for %s, got %s instead of %s.' + assert md[item[0]] == item[1], ('(4) wrong value for %s, got %s instead of %s.' % (item[0], md[item[0]], item[1])) - return 'fail' - - return 'success' + ############################################################################### # Test reading a M4 compressed file (fixed for #3848) -def nitf_online_23(): +def test_nitf_online_23(): if not gdaltest.download_file('http://download.osgeo.org/gdal/data/nitf/nitf2.0/U_3058b.ntf', 'U_3058b.ntf'): - return 'skip' + pytest.skip() tst = gdaltest.GDALTest('NITF', 'tmp/cache/U_3058b.ntf', 1, 44748, filename_absolute=1) @@ -3729,68 +3234,55 @@ def nitf_online_23(): # Test reading ECRG frames -def nitf_online_24(): +def test_nitf_online_24(): if not gdaltest.download_file('http://www.falconview.org/trac/FalconView/downloads/17', 'ECRG_Sample.zip'): - return 'skip' + pytest.skip() try: os.stat('tmp/cache/ECRG_Sample.zip') except OSError: - return 'skip' + pytest.skip() oldval = gdal.GetConfigOption('NITF_OPEN_UNDERLYING_DS') gdal.SetConfigOption('NITF_OPEN_UNDERLYING_DS', 'NO') ds = gdal.Open('/vsizip/tmp/cache/ECRG_Sample.zip/ECRG_Sample/EPF/clfc/2/000000009s0013.lf2') gdal.SetConfigOption('NITF_OPEN_UNDERLYING_DS', oldval) - if ds is None: - return 'fail' + assert ds is not None xml_tre = ds.GetMetadata('xml:TRE')[0] ds = None - if xml_tre.find('<tre name="GEOPSB"') == -1 or \ + assert (not (xml_tre.find('<tre name="GEOPSB"') == -1 or \ xml_tre.find('<tre name="J2KLRA"') == -1 or \ xml_tre.find('<tre name="GEOLOB"') == -1 or \ xml_tre.find('<tre name="BNDPLB"') == -1 or \ xml_tre.find('<tre name="ACCPOB"') == -1 or \ - xml_tre.find('<tre name="SOURCB"') == -1: - gdaltest.post_reason('did not get expected xml:TRE') - print(xml_tre) - return 'fail' - - return 'success' + xml_tre.find('<tre name="SOURCB"') == -1)), 'did not get expected xml:TRE' ############################################################################### # Test reading a HRE file -def nitf_online_25(): +def test_nitf_online_25(): if not gdaltest.download_file('http://www.gwg.nga.mil/ntb/baseline/docs/HRE_spec/Case1_HRE10G324642N1170747W_Uxx.hr5', 'Case1_HRE10G324642N1170747W_Uxx.hr5'): - return 'skip' + pytest.skip() tst = gdaltest.GDALTest('NITF', 'tmp/cache/Case1_HRE10G324642N1170747W_Uxx.hr5', 1, 7099, filename_absolute=1) - ret = tst.testOpen() - if ret != 'success': - return ret + tst.testOpen() ds = gdal.Open('tmp/cache/Case1_HRE10G324642N1170747W_Uxx.hr5') xml_tre = ds.GetMetadata('xml:TRE')[0] ds = None - if xml_tre.find('<tre name="PIAPRD"') == -1: - gdaltest.post_reason('did not get expected xml:TRE') - print(xml_tre) - return 'fail' - - return 'success' + assert xml_tre.find('<tre name="PIAPRD"') != -1, 'did not get expected xml:TRE' ############################################################################### # Cleanup. -def nitf_cleanup(): +def test_nitf_cleanup(): try: gdal.GetDriverByName('NITF').Delete('tmp/test_create.ntf') except RuntimeError: @@ -3937,143 +3429,3 @@ def nitf_cleanup(): gdal.GetDriverByName('NITF').Delete('tmp/nitf63.ntf') except RuntimeError: pass - - return 'success' - - -gdaltest_list = [ - nitf_1, - nitf_2, - nitf_3, - nitf_4, - nitf_5, - nitf_6, - nitf_7, - nitf_8, - nitf_9, - nitf_10, - nitf_11, - nitf_12, - nitf_13, - nitf_14, - nitf_15, - nitf_16, - nitf_17, - nitf_18, - nitf_19, - nitf_20, - nitf_21, - nitf_22, - nitf_23, - nitf_24, - nitf_25, - nitf_26, - nitf_27, - nitf_28_jp2ecw, - nitf_28_jp2mrsid, - nitf_28_jp2kak, - nitf_28_jp2openjpeg, - nitf_28_jp2openjpeg_bis, - nitf_29, - nitf_30, - nitf_31, - nitf_32, - nitf_33, - nitf_34, - nitf_35, - nitf_36, - nitf_37, - nitf_38, - nitf_39, - nitf_40, - nitf_41, - nitf_42, - nitf_43_jasper, - nitf_43_jp2ecw, - nitf_43_jp2kak, - nitf_44, - nitf_45, - # nitf_46_jp2ecw, - # nitf_46_jp2mrsid, - # nitf_46_jp2kak, - nitf_46_jasper, - # nitf_46_openjpeg, - nitf_47, - nitf_48, - nitf_49, - nitf_50, - nitf_51, - nitf_52, - nitf_53, - nitf_54, - nitf_55, - nitf_56, - nitf_57, - nitf_58, - nitf_read_IMRFCA_IMASDA, - nitf_59, - nitf_60, - nitf_61, - nitf_62, - nitf_63, - nitf_64, - nitf_65, - nitf_66, - nitf_67, - nitf_68, - nitf_69, - nitf_70, - nitf_71, - nitf_72, - nitf_73, - nitf_74, - nitf_75, - nitf_read_C4, - nitf_online_1, - nitf_online_2, - nitf_online_3, - nitf_online_4, - nitf_online_5, - nitf_online_6, - nitf_online_7, - nitf_online_8, - nitf_online_9, - nitf_online_10, - nitf_online_11, - nitf_online_12, - nitf_online_13, - nitf_online_14, - nitf_online_15_jp2ecw, - nitf_online_15_jp2mrsid, - nitf_online_15_jp2kak, - nitf_online_15_jasper, - nitf_online_15_openjpeg, - nitf_online_16_jp2ecw, - nitf_online_16_jp2mrsid, - nitf_online_16_jp2kak, - nitf_online_16_jasper, - nitf_online_16_openjpeg, - nitf_online_17_jp2ecw, - nitf_online_17_jp2mrsid, - nitf_online_17_jp2kak, - nitf_online_17_jasper, - nitf_online_17_openjpeg, - nitf_online_18, - nitf_online_19, - nitf_online_20, - nitf_online_21, - nitf_online_22, - nitf_online_23, - nitf_online_24, - nitf_online_25, - nitf_cleanup] - -# gdaltest_list = [ nitf_72 ] - -if __name__ == '__main__': - - gdaltest.setup_run('nitf') - - gdaltest.run_tests(gdaltest_list) - - sys.exit(gdaltest.summarize()) diff --git a/autotest/gdrivers/ntv1.py b/autotest/gdrivers/ntv1.py index 5491ea21eb3f..778742de9a6e 100755 --- a/autotest/gdrivers/ntv1.py +++ b/autotest/gdrivers/ntv1.py @@ -38,22 +38,12 @@ # Open a little-endian NTv2 grid -def ntv1_1(): +def test_ntv1_1(): tst = gdaltest.GDALTest('NTV1', 'ntv1_can_truncated.dat', 1, 65532) gt = (-44.375, 0.25, 0.0, 40.375, 0.0, -0.25) return tst.testOpen(check_gt=gt, check_prj='WGS84') -gdaltest_list = [ - ntv1_1, -] -if __name__ == '__main__': - - gdaltest.setup_run('NTV1') - - gdaltest.run_tests(gdaltest_list) - - sys.exit(gdaltest.summarize()) diff --git a/autotest/gdrivers/ntv2.py b/autotest/gdrivers/ntv2.py index f69080ea5717..560e5c1ed49a 100755 --- a/autotest/gdrivers/ntv2.py +++ b/autotest/gdrivers/ntv2.py @@ -29,18 +29,17 @@ ############################################################################### import os -import sys -sys.path.append('../pymod') from osgeo import gdal import gdaltest +import pytest ############################################################################### # Open a little-endian NTv2 grid -def ntv2_1(): +def test_ntv2_1(): tst = gdaltest.GDALTest('NTV2', 'test_ntv2_le.gsb', 2, 10) gt = (-5.52, 7.8, 0.0, 52.05, 0.0, -5.55) @@ -50,7 +49,7 @@ def ntv2_1(): # Open a big-endian NTv2 grid -def ntv2_2(): +def test_ntv2_2(): tst = gdaltest.GDALTest('NTV2', 'test_ntv2_be.gsb', 2, 10) gt = (-5.52, 7.8, 0.0, 52.05, 0.0, -5.55) @@ -60,7 +59,7 @@ def ntv2_2(): # Test creating a little-endian NTv2 grid -def ntv2_3(): +def test_ntv2_3(): tst = gdaltest.GDALTest('NTV2', 'test_ntv2_le.gsb', 2, 10, options=['ENDIANNESS=LE']) return tst.testCreateCopy(vsimem=1) @@ -69,7 +68,7 @@ def ntv2_3(): # Test creating a big-endian NTv2 grid -def ntv2_4(): +def test_ntv2_4(): tst = gdaltest.GDALTest('NTV2', 'test_ntv2_le.gsb', 2, 10, options=['ENDIANNESS=BE']) return tst.testCreateCopy(vsimem=1) @@ -78,80 +77,60 @@ def ntv2_4(): # Test appending to a little-endian NTv2 grid -def ntv2_5(): +def test_ntv2_5(): src_ds = gdal.Open('data/test_ntv2_le.gsb') gdal.GetDriverByName('NTv2').Create('/vsimem/ntv2_5.gsb', 1, 1, 4, gdal.GDT_Float32, options=['ENDIANNESS=LE']) ds = gdal.GetDriverByName('NTv2').CreateCopy('/vsimem/ntv2_5.gsb', src_ds, options=['APPEND_SUBDATASET=YES']) - if ds.GetRasterBand(2).Checksum() != 10: - gdaltest.post_reason('fail') - print(ds.GetRasterBand(2).Checksum()) - return 'fail' + assert ds.GetRasterBand(2).Checksum() == 10 ds = None ds = gdal.Open('NTv2:1:/vsimem/ntv2_5.gsb') - if ds.GetRasterBand(2).Checksum() != 10: - gdaltest.post_reason('fail') - print(ds.GetRasterBand(2).Checksum()) - return 'fail' + assert ds.GetRasterBand(2).Checksum() == 10 ds = None gdal.GetDriverByName('NTv2').Delete('/vsimem/ntv2_5.gsb') - return 'success' - ############################################################################### # Test appending to a big-endian NTv2 grid -def ntv2_6(): +def test_ntv2_6(): src_ds = gdal.Open('data/test_ntv2_le.gsb') gdal.GetDriverByName('NTv2').Create('/vsimem/ntv2_6.gsb', 1, 1, 4, gdal.GDT_Float32, options=['ENDIANNESS=BE']) ds = gdal.GetDriverByName('NTv2').CreateCopy('/vsimem/ntv2_6.gsb', src_ds, options=['APPEND_SUBDATASET=YES']) - if ds.GetRasterBand(2).Checksum() != 10: - gdaltest.post_reason('fail') - print(ds.GetRasterBand(2).Checksum()) - return 'fail' + assert ds.GetRasterBand(2).Checksum() == 10 ds = None ds = gdal.Open('NTv2:1:/vsimem/ntv2_6.gsb') - if ds.GetRasterBand(2).Checksum() != 10: - gdaltest.post_reason('fail') - print(ds.GetRasterBand(2).Checksum()) - return 'fail' + assert ds.GetRasterBand(2).Checksum() == 10 ds = None gdal.GetDriverByName('NTv2').Delete('/vsimem/ntv2_6.gsb') - return 'success' - ############################################################################### # Test creating a file with invalid filename -def ntv2_7(): +def test_ntv2_7(): with gdaltest.error_handler(): ds = gdal.GetDriverByName('NTv2').Create('/does/not/exist.gsb', 1, 1, 4, gdal.GDT_Float32) - if ds is not None: - return 'fail' + assert ds is None with gdaltest.error_handler(): ds = gdal.GetDriverByName('NTv2').Create('/does/not/exist.gsb', 1, 1, 4, gdal.GDT_Float32, options=['APPEND_SUBDATASET=YES']) - if ds is not None: - return 'fail' - - return 'success' + assert ds is None ############################################################################### -def ntv2_online_1(): +def test_ntv2_online_1(): if not gdaltest.download_file('http://download.osgeo.org/proj/nzgd2kgrid0005.gsb', 'nzgd2kgrid0005.gsb'): - return 'skip' + pytest.skip() try: os.stat('tmp/cache/nzgd2kgrid0005.gsb') except OSError: - return 'skip' + pytest.skip() tst = gdaltest.GDALTest('NTV2', 'tmp/cache/nzgd2kgrid0005.gsb', 1, 54971, filename_absolute=1) gt = (165.95, 0.1, 0.0, -33.95, 0.0, -0.1) @@ -160,12 +139,12 @@ def ntv2_online_1(): ############################################################################### -def ntv2_online_2(): +def test_ntv2_online_2(): try: os.stat('tmp/cache/nzgd2kgrid0005.gsb') except OSError: - return 'skip' + pytest.skip() tst = gdaltest.GDALTest('NTV2', 'tmp/cache/nzgd2kgrid0005.gsb', 1, 54971, filename_absolute=1) return tst.testCreateCopy(vsimem=1) @@ -173,35 +152,16 @@ def ntv2_online_2(): ############################################################################### -def ntv2_online_3(): +def test_ntv2_online_3(): try: os.stat('tmp/cache/nzgd2kgrid0005.gsb') except OSError: - return 'skip' + pytest.skip() tst = gdaltest.GDALTest('NTV2', 'tmp/cache/nzgd2kgrid0005.gsb', 1, 54971, filename_absolute=1) return tst.testCreate(vsimem=1, out_bands=4) -gdaltest_list = [ - ntv2_1, - ntv2_2, - ntv2_3, - ntv2_4, - ntv2_5, - ntv2_6, - ntv2_7, - ntv2_online_1, - ntv2_online_2, - ntv2_online_3, -] - - -if __name__ == '__main__': - - gdaltest.setup_run('NTV2') - gdaltest.run_tests(gdaltest_list) - sys.exit(gdaltest.summarize()) diff --git a/autotest/gdrivers/nwt_grc.py b/autotest/gdrivers/nwt_grc.py index e7121c1956d1..993fbb7d0249 100755 --- a/autotest/gdrivers/nwt_grc.py +++ b/autotest/gdrivers/nwt_grc.py @@ -28,9 +28,7 @@ # DEALINGS IN THE SOFTWARE. ############################################################################### -import sys -sys.path.append('../pymod') import gdaltest @@ -38,19 +36,10 @@ # Test a GRC dataset -def nwt_grc_1(): +def test_nwt_grc_1(): tst = gdaltest.GDALTest('NWT_GRC', 'nwt_grc.grc', 1, 46760) return tst.testOpen() -gdaltest_list = [ - nwt_grc_1] -if __name__ == '__main__': - - gdaltest.setup_run('nwt_grc') - - gdaltest.run_tests(gdaltest_list) - - sys.exit(gdaltest.summarize()) diff --git a/autotest/gdrivers/nwt_grd.py b/autotest/gdrivers/nwt_grd.py index db951d68d14c..4b3cbbbab89a 100755 --- a/autotest/gdrivers/nwt_grd.py +++ b/autotest/gdrivers/nwt_grd.py @@ -28,10 +28,8 @@ # DEALINGS IN THE SOFTWARE. ############################################################################### -import sys import shutil -sys.path.append('../pymod') from osgeo import gdal import gdaltest @@ -40,22 +38,19 @@ # Test a GRD dataset with three bands + Z -def nwt_grd_1(): +def test_nwt_grd_1(): tst1 = gdaltest.GDALTest('NWT_GRD', 'nwt_grd.grd', 1, 28093) - status1 = tst1.testOpen() + tst1.testOpen() tst2 = gdaltest.GDALTest('NWT_GRD', 'nwt_grd.grd', 2, 33690) - status2 = tst2.testOpen() + tst2.testOpen() tst3 = gdaltest.GDALTest('NWT_GRD', 'nwt_grd.grd', 3, 20365) - status3 = tst3.testOpen() + tst3.testOpen() tst4 = gdaltest.GDALTest('NWT_GRD', 'nwt_grd.grd', 4, 25856) - status4 = tst4.testOpen() - if status1 == 'success' and status2 == 'success' and status3 == 'success' and status4 == 'success': - return 'success' - return 'fail' + tst4.testOpen() -def nwt_grd_2(): +def test_nwt_grd_2(): """ Test writing a GRD via CreateCopy """ @@ -67,13 +62,4 @@ def nwt_grd_2(): return ret -gdaltest_list = [ - nwt_grd_1, nwt_grd_2] -if __name__ == '__main__': - - gdaltest.setup_run('nwt_grd') - - gdaltest.run_tests(gdaltest_list) - - sys.exit(gdaltest.summarize()) diff --git a/autotest/gdrivers/ozi.py b/autotest/gdrivers/ozi.py index c509f4243cac..6582ebc7efbe 100755 --- a/autotest/gdrivers/ozi.py +++ b/autotest/gdrivers/ozi.py @@ -29,21 +29,20 @@ ############################################################################### import os -import sys from osgeo import gdal -sys.path.append('../pymod') import gdaltest +import pytest ############################################################################### # Test reading OZF2 file -def ozi_online_1(): +def test_ozi_online_1(): if not gdaltest.download_file('http://www.oziexplorer2.com/maps/Europe2001_setup.exe', 'Europe2001_setup.exe'): - return 'skip' + pytest.skip() try: os.stat('tmp/cache/Europe 2001_OZF.map') @@ -53,13 +52,12 @@ def ozi_online_1(): try: os.stat('tmp/cache/Europe 2001_OZF.map') except OSError: - return 'skip' + pytest.skip() except: - return 'skip' + pytest.skip() ds = gdal.Open('tmp/cache/Europe 2001_OZF.map') - if ds is None: - return 'fail' + assert ds is not None if False: # pylint: disable=using-constant-test gt = ds.GetGeoTransform() @@ -67,52 +65,24 @@ def ozi_online_1(): expected_gt = (-1841870.2731215316, 3310.9550245520159, -13.025246304875619, 8375316.4662204208, -16.912440131236657, -3264.1162527118681) for i in range(6): - if abs(gt[i] - expected_gt[i]) > 1e-7: - gdaltest.post_reason('bad geotransform') - print(gt) - print(expected_gt) - return 'fail' + assert abs(gt[i] - expected_gt[i]) <= 1e-7, 'bad geotransform' else: gcps = ds.GetGCPs() - if len(gcps) != 4: - gdaltest.post_reason('did not get expected gcp count.') - print(len(gcps)) - return 'fail' + assert len(gcps) == 4, 'did not get expected gcp count.' gcp0 = gcps[0] - if gcp0.GCPPixel != 61 or gcp0.GCPLine != 436 \ - or abs(gcp0.GCPX - (-1653990.4525324)) > 0.001 \ - or abs(gcp0.GCPY - 6950885.0402214) > 0.001: - gdaltest.post_reason('did not get expected gcp.') - print(gcp0) - return 'fail' + assert gcp0.GCPPixel == 61 and gcp0.GCPLine == 436 and abs(gcp0.GCPX - (-1653990.4525324)) <= 0.001 and abs(gcp0.GCPY - 6950885.0402214) <= 0.001, \ + 'did not get expected gcp.' wkt = ds.GetGCPProjection() expected_wkt = 'PROJCS["unnamed",GEOGCS["WGS 84",DATUM["WGS_1984",SPHEROID["WGS 84",6378137,298.257223563,AUTHORITY["EPSG","7030"]],AUTHORITY["EPSG","6326"]],PRIMEM["Greenwich",0,AUTHORITY["EPSG","8901"]],UNIT["degree",0.0174532925199433,AUTHORITY["EPSG","9122"]],AUTHORITY["EPSG","4326"]],PROJECTION["Lambert_Conformal_Conic_2SP"],PARAMETER["standard_parallel_1",40],PARAMETER["standard_parallel_2",56],PARAMETER["latitude_of_origin",4],PARAMETER["central_meridian",10],PARAMETER["false_easting",0],PARAMETER["false_northing",0],UNIT["Meter",1]]' - if wkt != expected_wkt: - gdaltest.post_reason('bad WKT') - print(wkt) - return 'fail' + assert wkt == expected_wkt, 'bad WKT' cs = ds.GetRasterBand(1).Checksum() - if cs != 16025: - gdaltest.post_reason('bad checksum') - print(cs) - return 'fail' + assert cs == 16025, 'bad checksum' - return 'success' -gdaltest_list = [ - ozi_online_1] - -if __name__ == '__main__': - - gdaltest.setup_run('OZI') - - gdaltest.run_tests(gdaltest_list) - - sys.exit(gdaltest.summarize()) diff --git a/autotest/gdrivers/paux.py b/autotest/gdrivers/paux.py index 865507441bd3..82f295b06ebe 100755 --- a/autotest/gdrivers/paux.py +++ b/autotest/gdrivers/paux.py @@ -28,9 +28,7 @@ # DEALINGS IN THE SOFTWARE. ############################################################################### -import sys -sys.path.append('../pymod') from osgeo import gdal import gdaltest @@ -39,7 +37,7 @@ # Read test of simple byte reference data. -def paux_1(): +def test_paux_1(): tst = gdaltest.GDALTest('PAux', 'small16.raw', 2, 12816) return tst.testOpen() @@ -48,7 +46,7 @@ def paux_1(): # Test copying. -def paux_2(): +def test_paux_2(): tst = gdaltest.GDALTest('PAux', 'byte.tif', 1, 4672) @@ -58,7 +56,7 @@ def paux_2(): # Test /vsimem based. -def paux_3(): +def test_paux_3(): tst = gdaltest.GDALTest('PAux', 'byte.tif', 1, 4672) @@ -68,22 +66,9 @@ def paux_3(): # Cleanup. -def paux_cleanup(): +def test_paux_cleanup(): gdaltest.clean_tmp() gdal.Unlink('/vsimem/byte.tif.tst.aux.xml') - return 'success' -gdaltest_list = [ - paux_1, - paux_2, - paux_3, - paux_cleanup] -if __name__ == '__main__': - - gdaltest.setup_run('paux') - - gdaltest.run_tests(gdaltest_list) - - sys.exit(gdaltest.summarize()) diff --git a/autotest/gdrivers/pcidsk.py b/autotest/gdrivers/pcidsk.py index 9247c1cf3a8b..c94bd9789292 100755 --- a/autotest/gdrivers/pcidsk.py +++ b/autotest/gdrivers/pcidsk.py @@ -30,19 +30,18 @@ # DEALINGS IN THE SOFTWARE. ############################################################################### -import sys from osgeo import gdal from osgeo import ogr -sys.path.append('../pymod') import gdaltest +import pytest ############################################################################### # Read test of floating point reference data. -def pcidsk_1(): +def test_pcidsk_1(): tst = gdaltest.GDALTest('PCIDSK', 'utm.pix', 1, 39576) return tst.testOpen() @@ -51,7 +50,7 @@ def pcidsk_1(): # Test lossless copying (16, multiband) via Create(). -def pcidsk_2(): +def test_pcidsk_2(): tst = gdaltest.GDALTest('PCIDSK', 'rgba16.png', 2, 2042) @@ -61,7 +60,7 @@ def pcidsk_2(): # Test copying of georeferencing and projection. -def pcidsk_3(): +def test_pcidsk_3(): tst = gdaltest.GDALTest('PCIDSK', 'utm.pix', 1, 39576) @@ -71,34 +70,28 @@ def pcidsk_3(): # Test overview reading. -def pcidsk_4(): +def test_pcidsk_4(): ds = gdal.Open('data/utm.pix') band = ds.GetRasterBand(1) - if band.GetOverviewCount() != 1: - gdaltest.post_reason('did not get expected overview count') - return 'fail' + assert band.GetOverviewCount() == 1, 'did not get expected overview count' cs = band.GetOverview(0).Checksum() - if cs != 8368: - gdaltest.post_reason('wrong overview checksum (%d)' % cs) - return 'fail' - - return 'success' + assert cs == 8368, ('wrong overview checksum (%d)' % cs) ############################################################################### # Test writing metadata to a newly created file. -def pcidsk_5(): +def test_pcidsk_5(): # Are we using the new PCIDSK SDK based driver? driver = gdal.GetDriverByName('PCIDSK') col = driver.GetMetadataItem('DMD_CREATIONOPTIONLIST') if col.find('COMPRESSION') == -1: gdaltest.pcidsk_new = 0 - return 'skip' + pytest.skip() else: gdaltest.pcidsk_new = 1 @@ -132,16 +125,15 @@ def pcidsk_5(): print(mdalt) gdaltest.post_reason('file alt domain metadata broken. ') - return 'success' - + ############################################################################### # Test writing metadata to a band. -def pcidsk_6(): +def test_pcidsk_6(): if gdaltest.pcidsk_new == 0: - return 'skip' + pytest.skip() # Write out some metadata to the default and non-default domain and # using the set and single methods. @@ -168,16 +160,15 @@ def pcidsk_6(): print(mdalt) gdaltest.post_reason('channel alt domain metadata broken. ') - return 'success' - + ############################################################################### # Test creating a color table and reading it back. -def pcidsk_7(): +def test_pcidsk_7(): if gdaltest.pcidsk_new == 0: - return 'skip' + pytest.skip() # Write out some metadata to the default and non-default domain and # using the set and single methods. @@ -185,9 +176,7 @@ def pcidsk_7(): ct = band.GetColorTable() - if ct is not None: - gdaltest.post_reason('Got color table unexpectedly.') - return 'fail' + assert ct is None, 'Got color table unexpectedly.' ct = gdal.ColorTable() ct.SetColorEntry(0, (0, 255, 0, 255)) @@ -197,9 +186,8 @@ def pcidsk_7(): ct = band.GetColorTable() - if ct.GetColorEntry(1) != (255, 0, 255, 255): - gdaltest.post_reason('Got wrong color table entry immediately.') - return 'fail' + assert ct.GetColorEntry(1) == (255, 0, 255, 255), \ + 'Got wrong color table entry immediately.' ct = None band = None @@ -212,33 +200,22 @@ def pcidsk_7(): ct = band.GetColorTable() - if ct.GetColorEntry(1) != (255, 0, 255, 255): - gdaltest.post_reason('Got wrong color table entry after reopen.') - return 'fail' - - if band.GetColorInterpretation() != gdal.GCI_PaletteIndex: - gdaltest.post_reason('Not a palette?') - return 'fail' + assert ct.GetColorEntry(1) == (255, 0, 255, 255), \ + 'Got wrong color table entry after reopen.' - if band.SetColorTable(None) != 0: - gdaltest.post_reason('SetColorTable failed.') - return 'fail' + assert band.GetColorInterpretation() == gdal.GCI_PaletteIndex, 'Not a palette?' - if band.GetColorTable() is not None: - gdaltest.post_reason('color table still exists!') - return 'fail' + assert band.SetColorTable(None) == 0, 'SetColorTable failed.' - if band.GetColorInterpretation() != gdal.GCI_Undefined: - gdaltest.post_reason('Paletted?') - return 'fail' + assert band.GetColorTable() is None, 'color table still exists!' - return 'success' + assert band.GetColorInterpretation() == gdal.GCI_Undefined, 'Paletted?' ############################################################################### # Test FILE interleaving. -def pcidsk_8(): +def test_pcidsk_8(): tst = gdaltest.GDALTest('PCIDSK', 'rgba16.png', 2, 2042, options=['INTERLEAVING=FILE']) @@ -253,11 +230,11 @@ def pcidsk_8(): def pcidsk_9(): if gdaltest.pcidsk_new == 0: - return 'skip' + pytest.skip() ogr_drv = ogr.GetDriverByName('PCIDSK') if ogr_drv is None: - return 'skip' + pytest.skip() ds = ogr_drv.CreateDataSource('/vsimem/pcidsk_9.pix') ds.CreateLayer('foo') @@ -266,21 +243,18 @@ def pcidsk_9(): gdal.PushErrorHandler('CPLQuietErrorHandler') ds = gdal.Open('/vsimem/pcidsk_9.pix') gdal.PopErrorHandler() - if ds is not None: - return 'fail' + assert ds is None ds = None gdal.Unlink('/vsimem/pcidsk_9.pix') - return 'success' - ############################################################################### # Test overview creation. -def pcidsk_10(): +def test_pcidsk_10(): if gdaltest.pcidsk_new == 0: - return 'skip' + pytest.skip() src_ds = gdal.Open('data/byte.tif') ds = gdal.GetDriverByName('PCIDSK').CreateCopy('/vsimem/pcidsk_10.pix', src_ds) @@ -292,28 +266,22 @@ def pcidsk_10(): band = ds.GetRasterBand(1) ds.BuildOverviews('NEAR', [2]) - if band.GetOverviewCount() != 1: - gdaltest.post_reason('did not get expected overview count') - return 'fail' + assert band.GetOverviewCount() == 1, 'did not get expected overview count' cs = band.GetOverview(0).Checksum() - if cs != 1087: - gdaltest.post_reason('wrong overview checksum (%d)' % cs) - return 'fail' + assert cs == 1087, ('wrong overview checksum (%d)' % cs) ds = None gdal.GetDriverByName('PCIDSK').Delete('/vsimem/pcidsk_10.pix') - return 'success' - ############################################################################### # Test INTERLEAVING=TILED interleaving. -def pcidsk_11(): +def test_pcidsk_11(): if gdaltest.pcidsk_new == 0: - return 'skip' + pytest.skip() tst = gdaltest.GDALTest('PCIDSK', 'rgba16.png', 2, 2042, options=['INTERLEAVING=TILED', 'TILESIZE=32']) @@ -324,9 +292,9 @@ def pcidsk_11(): # Test INTERLEAVING=TILED interleaving and COMPRESSION=RLE -def pcidsk_12(): +def test_pcidsk_12(): if gdaltest.pcidsk_new == 0: - return 'skip' + pytest.skip() tst = gdaltest.GDALTest('PCIDSK', 'rgba16.png', 2, 2042, options=['INTERLEAVING=TILED', 'TILESIZE=32', 'COMPRESSION=RLE']) @@ -337,12 +305,12 @@ def pcidsk_12(): # Test INTERLEAVING=TILED interleaving and COMPRESSION=JPEG -def pcidsk_13(): +def test_pcidsk_13(): if gdaltest.pcidsk_new == 0: - return 'skip' + pytest.skip() if gdal.GetDriverByName('JPEG') is None: - return 'skip' + pytest.skip() src_ds = gdal.Open('data/byte.tif') ds = gdal.GetDriverByName('PCIDSK').CreateCopy('/vsimem/pcidsk_13.pix', src_ds, options=['INTERLEAVING=TILED', 'COMPRESSION=JPEG']) @@ -359,20 +327,15 @@ def pcidsk_13(): gdal.GetDriverByName('PCIDSK').Delete('/vsimem/pcidsk_13.pix') - if cs != 4645: - gdaltest.post_reason('bad checksum') - print(cs) - return 'fail' - - return 'success' + assert cs == 4645, 'bad checksum' ############################################################################### # Test SetDescription() -def pcidsk_14(): +def test_pcidsk_14(): if gdaltest.pcidsk_new == 0: - return 'skip' + pytest.skip() ds = gdal.GetDriverByName('PCIDSK').Create('/vsimem/pcidsk_14.pix', 1, 1) band = ds.GetRasterBand(1).SetDescription('mydescription') @@ -388,20 +351,15 @@ def pcidsk_14(): gdal.GetDriverByName('PCIDSK').Delete('/vsimem/pcidsk_14.pix') - if desc != 'mydescription': - gdaltest.post_reason('bad description') - print(desc) - return 'fail' - - return 'success' + assert desc == 'mydescription', 'bad description' ############################################################################### # Test mixed raster and vector -def pcidsk_15(): +def test_pcidsk_15(): if gdaltest.pcidsk_new == 0: - return 'skip' + pytest.skip() # One raster band and vector layer ds = gdal.GetDriverByName('PCIDSK').Create('/vsimem/pcidsk_15.pix', 1, 1) @@ -409,24 +367,16 @@ def pcidsk_15(): ds = None ds = gdal.Open('/vsimem/pcidsk_15.pix') - if ds.RasterCount != 1: - gdaltest.post_reason('fail') - return 'fail' - if ds.GetLayerCount() != 1: - gdaltest.post_reason('fail') - return 'fail' + assert ds.RasterCount == 1 + assert ds.GetLayerCount() == 1 ds2 = gdal.GetDriverByName('PCIDSK').CreateCopy('/vsimem/pcidsk_15_2.pix', ds) ds2 = None ds = None ds = gdal.Open('/vsimem/pcidsk_15_2.pix') - if ds.RasterCount != 1: - gdaltest.post_reason('fail') - return 'fail' - if ds.GetLayerCount() != 1: - gdaltest.post_reason('fail') - return 'fail' + assert ds.RasterCount == 1 + assert ds.GetLayerCount() == 1 ds = None # One vector layer only @@ -435,24 +385,16 @@ def pcidsk_15(): ds = None ds = gdal.OpenEx('/vsimem/pcidsk_15.pix') - if ds.RasterCount != 0: - gdaltest.post_reason('fail') - return 'fail' - if ds.GetLayerCount() != 1: - gdaltest.post_reason('fail') - return 'fail' + assert ds.RasterCount == 0 + assert ds.GetLayerCount() == 1 ds2 = gdal.GetDriverByName('PCIDSK').CreateCopy('/vsimem/pcidsk_15_2.pix', ds) ds2 = None ds = None ds = gdal.OpenEx('/vsimem/pcidsk_15_2.pix') - if ds.RasterCount != 0: - gdaltest.post_reason('fail') - return 'fail' - if ds.GetLayerCount() != 1: - gdaltest.post_reason('fail') - return 'fail' + assert ds.RasterCount == 0 + assert ds.GetLayerCount() == 1 ds = None # Zero raster band and vector layer @@ -460,85 +402,64 @@ def pcidsk_15(): ds = None ds = gdal.OpenEx('/vsimem/pcidsk_15.pix') - if ds.RasterCount != 0: - gdaltest.post_reason('fail') - return 'fail' - if ds.GetLayerCount() != 0: - gdaltest.post_reason('fail') - return 'fail' + assert ds.RasterCount == 0 + assert ds.GetLayerCount() == 0 ds2 = gdal.GetDriverByName('PCIDSK').CreateCopy('/vsimem/pcidsk_15_2.pix', ds) del ds2 ds = None ds = gdal.OpenEx('/vsimem/pcidsk_15_2.pix') - if ds.RasterCount != 0: - gdaltest.post_reason('fail') - return 'fail' - if ds.GetLayerCount() != 0: - gdaltest.post_reason('fail') - return 'fail' + assert ds.RasterCount == 0 + assert ds.GetLayerCount() == 0 ds = None gdal.GetDriverByName('PCIDSK').Delete('/vsimem/pcidsk_15.pix') gdal.GetDriverByName('PCIDSK').Delete('/vsimem/pcidsk_15_2.pix') - return 'success' - ############################################################################### -def pcidsk_external_ovr(): +def test_pcidsk_external_ovr(): gdal.Translate('/vsimem/test.pix', 'data/byte.tif', format='PCIDSK') ds = gdal.Open('/vsimem/test.pix') ds.BuildOverviews('NEAR', [2]) ds = None - if gdal.VSIStatL('/vsimem/test.pix.ovr') is None: - gdaltest.post_reason('fail') - return 'fail' + assert gdal.VSIStatL('/vsimem/test.pix.ovr') is not None ds = gdal.Open('/vsimem/test.pix') - if ds.GetRasterBand(1).GetOverviewCount() != 1: - gdaltest.post_reason('fail') - return 'fail' + assert ds.GetRasterBand(1).GetOverviewCount() == 1 ds = None gdal.GetDriverByName('PCIDSK').Delete('/vsimem/test.pix') - return 'success' - ############################################################################### -def pcidsk_external_ovr_rrd(): +def test_pcidsk_external_ovr_rrd(): gdal.Translate('/vsimem/test.pix', 'data/byte.tif', format='PCIDSK') ds = gdal.Open('/vsimem/test.pix', gdal.GA_Update) with gdaltest.config_option('USE_RRD', 'YES'): ds.BuildOverviews('NEAR', [2]) ds = None - if gdal.VSIStatL('/vsimem/test.aux') is None: - gdaltest.post_reason('fail') - return 'fail' + assert gdal.VSIStatL('/vsimem/test.aux') is not None ds = gdal.Open('/vsimem/test.pix') - if ds.GetRasterBand(1).GetOverviewCount() != 1: - return 'fail' + assert ds.GetRasterBand(1).GetOverviewCount() == 1 ds = None gdal.GetDriverByName('PCIDSK').Delete('/vsimem/test.pix') - return 'success' - ############################################################################### # Check various items from a modern irvine.pix -def pcidsk_online_1(): +def test_pcidsk_online_1(): if gdaltest.pcidsk_new == 0: - return 'skip' + pytest.skip() if not gdaltest.download_file('http://download.osgeo.org/gdal/data/pcidsk/sdk_testsuite/irvine_gcp2.pix', 'irvine_gcp2.pix'): - return 'skip' + pytest.skip() ds = gdal.Open('tmp/cache/irvine_gcp2.pix') @@ -554,59 +475,23 @@ def pcidsk_online_1(): return 'false' band = ds.GetRasterBand(20) - if band.GetDescription() != 'Training site for type 2 crop': - gdaltest.post_reason('did not get expected band 20 description') - return 'fail' + assert band.GetDescription() == 'Training site for type 2 crop', \ + 'did not get expected band 20 description' exp_checksum = 2057 checksum = band.Checksum() - if exp_checksum != checksum: - print(checksum) - gdaltest.post_reason('did not get right bitmap checksum.') - return 'fail' + assert exp_checksum == checksum, 'did not get right bitmap checksum.' md = band.GetMetadata('IMAGE_STRUCTURE') - if md['NBITS'] != '1': - gdaltest.post_reason('did not get expected NBITS=1 metadata.') - return 'fail' - - return 'success' + assert md['NBITS'] == '1', 'did not get expected NBITS=1 metadata.' ############################################################################### # Cleanup. -def pcidsk_cleanup(): +def test_pcidsk_cleanup(): gdaltest.pcidsk_ds = None gdaltest.clean_tmp() - return 'success' - - -gdaltest_list = [ - pcidsk_1, - pcidsk_2, - pcidsk_3, - pcidsk_4, - pcidsk_5, - pcidsk_6, - pcidsk_7, - pcidsk_8, - # pcidsk_9, - pcidsk_10, - pcidsk_11, - pcidsk_12, - pcidsk_13, - pcidsk_14, - pcidsk_15, - pcidsk_external_ovr, - pcidsk_external_ovr_rrd, - pcidsk_online_1, - pcidsk_cleanup] - -if __name__ == '__main__': - - gdaltest.setup_run('pcidsk') - - gdaltest.run_tests(gdaltest_list) - - sys.exit(gdaltest.summarize()) + + + diff --git a/autotest/gdrivers/pcraster.py b/autotest/gdrivers/pcraster.py index 0b11c8067f11..d567bf1068c8 100755 --- a/autotest/gdrivers/pcraster.py +++ b/autotest/gdrivers/pcraster.py @@ -28,23 +28,22 @@ # DEALINGS IN THE SOFTWARE. ############################################################################### -import sys from osgeo import gdal -sys.path.append('../pymod') import gdaltest +import pytest ############################################################################### # Perform simple read test. -def pcraster_1(): +def test_pcraster_1(): gdaltest.pcraster_drv = gdal.GetDriverByName('PCRaster') if gdaltest.pcraster_drv is None: - return 'skip' + pytest.skip() tst = gdaltest.GDALTest('PCRaster', 'ldd.map', 1, 4528) return tst.testOpen() @@ -53,37 +52,21 @@ def pcraster_1(): # Verify some auxiliary data. -def pcraster_2(): +def test_pcraster_2(): if gdaltest.pcraster_drv is None: - return 'skip' + pytest.skip() ds = gdal.Open('data/ldd.map') gt = ds.GetGeoTransform() - if gt[0] != 182140.0 or gt[1] != 10 or gt[2] != 0 \ - or gt[3] != 327880.0 or gt[4] != 0 or gt[5] != -10: - gdaltest.post_reason('PCRaster geotransform wrong.') - return 'fail' + assert gt[0] == 182140.0 and gt[1] == 10 and gt[2] == 0 and gt[3] == 327880.0 and gt[4] == 0 and gt[5] == -10, \ + 'PCRaster geotransform wrong.' band1 = ds.GetRasterBand(1) - if band1.GetNoDataValue() != 255: - gdaltest.post_reason('PCRaster NODATA value wrong or missing.') - return 'fail' + assert band1.GetNoDataValue() == 255, 'PCRaster NODATA value wrong or missing.' - return 'success' -gdaltest_list = [ - pcraster_1, - pcraster_2] - -if __name__ == '__main__': - - gdaltest.setup_run('pcraster') - - gdaltest.run_tests(gdaltest_list) - - sys.exit(gdaltest.summarize()) diff --git a/autotest/gdrivers/pdf.py b/autotest/gdrivers/pdf.py index 7292fa72a9b6..77db876508b8 100755 --- a/autotest/gdrivers/pdf.py +++ b/autotest/gdrivers/pdf.py @@ -34,29 +34,52 @@ from osgeo import gdal from osgeo import ogr from osgeo import osr - -sys.path.append('../pymod') -sys.path.append('../osr') +import pytest import gdaltest import ogrtest + +pytestmark = pytest.mark.require_driver('PDF') + ############################################################################### # Test driver presence -def pdf_init(): +@pytest.fixture( + params=['POPPLER', 'PODOFO', 'PDFIUM'] +) +def poppler_or_pdfium_or_podofo(request): + """ + Runs tests with all three backends. + """ + backend = request.param + gdaltest.pdf_drv = gdal.GetDriverByName('PDF') + + md = gdaltest.pdf_drv.GetMetadata() + if 'HAVE_%s' % backend not in md: + pytest.skip() + + with gdaltest.config_option('GDAL_PDF_LIB', backend): + yield backend + +@pytest.fixture( + params=['POPPLER', 'PDFIUM'] +) +def poppler_or_pdfium(request): + """ + Runs tests with poppler or pdfium, but not podofo + """ + backend = request.param gdaltest.pdf_drv = gdal.GetDriverByName('PDF') - if gdaltest.pdf_drv is None: - return 'skip' md = gdaltest.pdf_drv.GetMetadata() - if 'HAVE_POPPLER' not in md and 'HAVE_PODOFO' not in md and 'HAVE_PDFIUM' not in md: - gdaltest.pdf_drv = None - return 'skip' + if 'HAVE_%s' % backend not in md: + pytest.skip() - return 'success' + with gdaltest.config_option('GDAL_PDF_LIB', backend): + yield backend ############################################################################### # Returns True if we run with poppler @@ -112,27 +135,19 @@ def pdf_checksum_available(): # Test OGC best practice geospatial PDF -def pdf_online_1(): - - if gdaltest.pdf_drv is None: - return 'skip' - +def test_pdf_online_1(poppler_or_pdfium): if not gdaltest.download_file('http://www.agc.army.mil/GeoPDFgallery/Imagery/Cherrydale_eDOQQ_1m_0_033_R1C1.pdf', 'Cherrydale_eDOQQ_1m_0_033_R1C1.pdf'): - return 'skip' + pytest.skip() try: os.stat('tmp/cache/Cherrydale_eDOQQ_1m_0_033_R1C1.pdf') except OSError: - return 'skip' + pytest.skip() ds = gdal.Open('tmp/cache/Cherrydale_eDOQQ_1m_0_033_R1C1.pdf') - if ds is None: - return 'fail' + assert ds is not None - if ds.RasterXSize != 1241: - gdaltest.post_reason('bad dimensions') - print(ds.RasterXSize) - return 'fail' + assert ds.RasterXSize == 1241, 'bad dimensions' gt = ds.GetGeoTransform() wkt = ds.GetProjectionRef() @@ -149,41 +164,26 @@ def pdf_online_1(): # The remote file has been updated... other_expected_gt = (-77.112328333299928, 9.1666560000165691e-06, 0.0, 38.897842488371978, 0.0, -9.1666560000046903e-06) for j in range(6): - if abs(gt[j] - other_expected_gt[j]) > 1e-15: - gdaltest.post_reason('bad geotransform') - print(gt) - print(other_expected_gt) - return 'fail' + assert abs(gt[j] - other_expected_gt[j]) <= 1e-15, 'bad geotransform' - if wkt.find('GEOGCS["WGS 84"') != 0: - gdaltest.post_reason('bad WKT') - print(wkt) - return 'fail' + assert wkt.find('GEOGCS["WGS 84"') == 0, 'bad WKT' if pdf_checksum_available(): cs = ds.GetRasterBand(1).Checksum() - if cs == 0: - gdaltest.post_reason('bad checksum') - return 'fail' - - return 'success' + assert cs != 0, 'bad checksum' + ############################################################################### -def pdf_online_2(): - - if gdaltest.pdf_drv is None: - return 'skip' - +def test_pdf_online_2(poppler_or_pdfium): try: os.stat('tmp/cache/Cherrydale_eDOQQ_1m_0_033_R1C1.pdf') except OSError: - return 'skip' + pytest.skip() ds = gdal.Open('PDF:1:tmp/cache/Cherrydale_eDOQQ_1m_0_033_R1C1.pdf') - if ds is None: - return 'fail' + assert ds is not None gt = ds.GetGeoTransform() wkt = ds.GetProjectionRef() @@ -200,32 +200,19 @@ def pdf_online_2(): # The remote file has been updated... other_expected_gt = (-77.112328333299928, 9.1666560000165691e-06, 0.0, 38.897842488371978, 0.0, -9.1666560000046903e-06) for j in range(6): - if abs(gt[j] - other_expected_gt[j]) > 1e-15: - gdaltest.post_reason('bad geotransform') - print(gt) - print(other_expected_gt) - return 'fail' - - if wkt.find('GEOGCS["WGS 84"') != 0: - print(wkt) - return 'fail' + assert abs(gt[j] - other_expected_gt[j]) <= 1e-15, 'bad geotransform' - return 'success' + assert wkt.find('GEOGCS["WGS 84"') == 0 ############################################################################### # Test Adobe style geospatial pdf -def pdf_1(): - - if gdaltest.pdf_drv is None: - return 'skip' - +def test_pdf_1(poppler_or_pdfium): gdal.SetConfigOption('GDAL_PDF_DPI', '200') ds = gdal.Open('data/adobe_style_geospatial.pdf') gdal.SetConfigOption('GDAL_PDF_DPI', None) - if ds is None: - return 'fail' + assert ds is not None gt = ds.GetGeoTransform() wkt = ds.GetProjectionRef() @@ -236,25 +223,15 @@ def pdf_1(): expected_gt = (333274.61654367246, 31.764802242655662, 0.0, 4940391.7593506984, 0.0, -31.794745501708238) for i in range(6): - if abs(gt[i] - expected_gt[i]) > 1e-6: - gdaltest.post_reason('bad geotransform') - print(gt) - print(expected_gt) - return 'fail' + assert abs(gt[i] - expected_gt[i]) <= 1e-6, 'bad geotransform' expected_wkt = 'PROJCS["WGS_1984_UTM_Zone_20N",GEOGCS["GCS_WGS_1984",DATUM["WGS_1984",SPHEROID["WGS_84",6378137.0,298.257223563]],PRIMEM["Greenwich",0.0],UNIT["Degree",0.0174532925199433]],PROJECTION["Transverse_Mercator"],PARAMETER["False_Easting",500000.0],PARAMETER["False_Northing",0.0],PARAMETER["Central_Meridian",-63.0],PARAMETER["Scale_Factor",0.9996],PARAMETER["Latitude_Of_Origin",0.0],UNIT["Meter",1.0]]' - if wkt != expected_wkt: - gdaltest.post_reason('bad WKT') - print(wkt) - return 'fail' + assert wkt == expected_wkt, 'bad WKT' if pdf_checksum_available(): cs = ds.GetRasterBand(1).Checksum() # if cs != 17740 and cs != 19346: - if cs == 0: - gdaltest.post_reason('bad checksum') - print(cs) - return 'fail' + assert cs != 0, 'bad checksum' neatline = ds.GetMetadataItem('NEATLINE') got_geom = ogr.CreateGeometryFromWkt(neatline) @@ -264,21 +241,15 @@ def pdf_1(): expected_geom = ogr.CreateGeometryFromWkt('POLYGON ((338304.150125828920864 4896673.639421294443309,338304.177293475600891 4933414.799376524984837,382774.271384406310972 4933414.546264361590147,382774.767329963855445 4896674.273581005632877,338304.150125828920864 4896673.639421294443309))') if ogrtest.check_feature_geometry(got_geom, expected_geom) != 0: - gdaltest.post_reason('bad neatline') print(neatline) - return 'fail' - - return 'success' + pytest.fail('bad neatline') + ############################################################################### # Test write support with ISO32000 geo encoding -def pdf_iso32000(): - - if gdaltest.pdf_drv is None: - return 'skip' - +def test_pdf_iso32000(poppler_or_pdfium_or_podofo): tst = gdaltest.GDALTest('PDF', 'byte.tif', 1, None) ret = tst.testCreateCopy(check_minmax=0, check_gt=1, check_srs=True, check_checksum_not_null=pdf_checksum_available()) @@ -288,11 +259,7 @@ def pdf_iso32000(): # Test write support with ISO32000 geo encoding, with DPI=300 -def pdf_iso32000_dpi_300(): - - if gdaltest.pdf_drv is None: - return 'skip' - +def test_pdf_iso32000_dpi_300(poppler_or_pdfium): tst = gdaltest.GDALTest('PDF', 'byte.tif', 1, None, options=['DPI=300']) ret = tst.testCreateCopy(check_minmax=0, check_gt=1, check_srs=True, check_checksum_not_null=pdf_checksum_available()) @@ -302,11 +269,7 @@ def pdf_iso32000_dpi_300(): # Test write support with OGC_BP geo encoding -def pdf_ogcbp(): - - if gdaltest.pdf_drv is None: - return 'skip' - +def test_pdf_ogcbp(poppler_or_pdfium_or_podofo): gdal.SetConfigOption('GDAL_PDF_OGC_BP_WRITE_WKT', 'FALSE') tst = gdaltest.GDALTest('PDF', 'byte.tif', 1, None, options=['GEO_ENCODING=OGC_BP']) ret = tst.testCreateCopy(check_minmax=0, check_gt=1, check_srs=True, check_checksum_not_null=pdf_checksum_available()) @@ -318,11 +281,7 @@ def pdf_ogcbp(): # Test write support with OGC_BP geo encoding, with DPI=300 -def pdf_ogcbp_dpi_300(): - - if gdaltest.pdf_drv is None: - return 'skip' - +def test_pdf_ogcbp_dpi_300(poppler_or_pdfium): gdal.SetConfigOption('GDAL_PDF_OGC_BP_WRITE_WKT', 'FALSE') tst = gdaltest.GDALTest('PDF', 'byte.tif', 1, None, options=['GEO_ENCODING=OGC_BP', 'DPI=300']) ret = tst.testCreateCopy(check_minmax=0, check_gt=1, check_srs=True, check_checksum_not_null=pdf_checksum_available()) @@ -331,11 +290,7 @@ def pdf_ogcbp_dpi_300(): return ret -def pdf_ogcbp_lcc(): - - if gdaltest.pdf_drv is None: - return 'skip' - +def test_pdf_ogcbp_lcc(poppler_or_pdfium): wkt = """PROJCS["NAD83 / Utah North", GEOGCS["NAD83", DATUM["North_American_Datum_1983", @@ -371,21 +326,15 @@ def pdf_ogcbp_lcc(): sr1 = osr.SpatialReference(wkt) sr2 = osr.SpatialReference(out_wkt) if sr1.IsSame(sr2) == 0: - gdaltest.post_reason('wrong wkt') print(sr2.ExportToPrettyWkt()) - return 'fail' - - return 'success' + pytest.fail('wrong wkt') + ############################################################################### # Test no compression -def pdf_no_compression(): - - if gdaltest.pdf_drv is None: - return 'skip' - +def test_pdf_no_compression(poppler_or_pdfium): tst = gdaltest.GDALTest('PDF', 'byte.tif', 1, None, options=['COMPRESS=NONE']) ret = tst.testCreateCopy(check_minmax=0, check_gt=0, check_srs=None, check_checksum_not_null=pdf_checksum_available()) @@ -395,18 +344,16 @@ def pdf_no_compression(): # Test compression methods -def pdf_jpeg_compression(filename='byte.tif'): - - if gdaltest.pdf_drv is None: - return 'skip' - +def _test_pdf_jpeg_compression(filename): if gdal.GetDriverByName('JPEG') is None: - return 'skip' + pytest.skip() tst = gdaltest.GDALTest('PDF', filename, 1, None, options=['COMPRESS=JPEG']) - ret = tst.testCreateCopy(check_minmax=0, check_gt=0, check_srs=None, check_checksum_not_null=pdf_checksum_available()) + tst.testCreateCopy(check_minmax=0, check_gt=0, check_srs=None, check_checksum_not_null=pdf_checksum_available()) - return ret + +def test_pdf_jpeg_compression(poppler_or_pdfium): + _test_pdf_jpeg_compression('byte.tif') def pdf_get_J2KDriver(drv_name): @@ -421,18 +368,14 @@ def pdf_get_J2KDriver(drv_name): def pdf_jpx_compression(filename, drv_name=None): - - if gdaltest.pdf_drv is None: - return 'skip' - if drv_name is None: if pdf_get_J2KDriver('JP2KAK') is None and \ pdf_get_J2KDriver('JP2ECW') is None and \ pdf_get_J2KDriver('JP2OpenJpeg') is None and \ pdf_get_J2KDriver('JPEG2000') is None: - return 'skip' + pytest.skip() elif pdf_get_J2KDriver(drv_name) is None: - return 'skip' + pytest.skip() if drv_name is None: options = ['COMPRESS=JPEG2000'] @@ -445,32 +388,32 @@ def pdf_jpx_compression(filename, drv_name=None): return ret -def pdf_jp2_auto_compression(): +def test_pdf_jp2_auto_compression(poppler_or_pdfium): return pdf_jpx_compression('utm.tif') -def pdf_jp2kak_compression(): +def test_pdf_jp2kak_compression(poppler_or_pdfium): return pdf_jpx_compression('utm.tif', 'JP2KAK') -def pdf_jp2ecw_compression(): +def test_pdf_jp2ecw_compression(poppler_or_pdfium): return pdf_jpx_compression('utm.tif', 'JP2ECW') -def pdf_jp2openjpeg_compression(): +def test_pdf_jp2openjpeg_compression(poppler_or_pdfium): return pdf_jpx_compression('utm.tif', 'JP2OpenJpeg') -def pdf_jpeg2000_compression(): +def test_pdf_jpeg2000_compression(poppler_or_pdfium): return pdf_jpx_compression('utm.tif', 'JPEG2000') -def pdf_jp2ecw_compression_rgb(): +def test_pdf_jp2ecw_compression_rgb(poppler_or_pdfium): return pdf_jpx_compression('rgbsmall.tif', 'JP2ECW') -def pdf_jpeg_compression_rgb(): - return pdf_jpeg_compression('rgbsmall.tif') +def test_pdf_jpeg_compression_rgb(poppler_or_pdfium): + return _test_pdf_jpeg_compression('rgbsmall.tif') ############################################################################### # Test RGBA @@ -478,11 +421,8 @@ def pdf_jpeg_compression_rgb(): def pdf_rgba_default_compression(options_param=None): options_param = [] if options_param is None else options_param - if gdaltest.pdf_drv is None: - return 'skip' - if not pdf_checksum_available(): - return 'skip' + pytest.skip() src_ds = gdal.Open('../gcore/data/stefan_full_rgba.tif') out_ds = gdaltest.pdf_drv.CreateCopy('tmp/rgba.pdf', src_ds, options=options_param) @@ -514,18 +454,13 @@ def pdf_rgba_default_compression(options_param=None): gdal.GetDriverByName('PDF').Delete('tmp/rgba.pdf') if cs4 < 0: - return 'skip' + pytest.skip() - if content.find('Type = dictionary, Num = 3, Gen = 0') != 0 or \ - content.find(' Type = dictionary, Num = 3, Gen = 0') < 0: - gdaltest.post_reason('wrong object dump') - print(content) - return 'fail' + assert (content.find('Type = dictionary, Num = 3, Gen = 0') == 0 and \ + content.find(' Type = dictionary, Num = 3, Gen = 0') >= 0), \ + 'wrong object dump' - if cs4 == 0: - gdaltest.post_reason('wrong checksum') - print(cs4) - return 'fail' + assert cs4 != 0, 'wrong checksum' if cs1 != src_cs1 or cs2 != src_cs2 or cs3 != src_cs3 or cs4 != src_cs4: print(cs1) @@ -537,36 +472,27 @@ def pdf_rgba_default_compression(options_param=None): print(src_cs3) print(src_cs4) - return 'success' - + -def pdf_rgba_default_compression_tiled(): +def test_pdf_rgba_default_compression_tiled(poppler_or_pdfium_or_podofo): return pdf_rgba_default_compression(['BLOCKXSIZE=32', 'BLOCKYSIZE=32']) -def pdf_jpeg_compression_rgba(): - return pdf_jpeg_compression('../../gcore/data/stefan_full_rgba.tif') +def test_pdf_jpeg_compression_rgba(poppler_or_pdfium): + return _test_pdf_jpeg_compression('../../gcore/data/stefan_full_rgba.tif') ############################################################################### # Test PREDICTOR=2 -def pdf_predictor_2(): - - if gdaltest.pdf_drv is None: - return 'skip' - +def test_pdf_predictor_2(poppler_or_pdfium): tst = gdaltest.GDALTest('PDF', 'utm.tif', 1, None, options=['PREDICTOR=2']) ret = tst.testCreateCopy(check_minmax=0, check_gt=0, check_srs=None, check_checksum_not_null=pdf_checksum_available()) return ret -def pdf_predictor_2_rgb(): - - if gdaltest.pdf_drv is None: - return 'skip' - +def test_pdf_predictor_2_rgb(poppler_or_pdfium): tst = gdaltest.GDALTest('PDF', 'rgbsmall.tif', 1, None, options=['PREDICTOR=2']) ret = tst.testCreateCopy(check_minmax=0, check_gt=0, check_srs=None, check_checksum_not_null=pdf_checksum_available()) @@ -576,22 +502,14 @@ def pdf_predictor_2_rgb(): # Test tiling -def pdf_tiled(): - - if gdaltest.pdf_drv is None: - return 'skip' - +def test_pdf_tiled(poppler_or_pdfium): tst = gdaltest.GDALTest('PDF', 'utm.tif', 1, None, options=['COMPRESS=DEFLATE', 'TILED=YES']) ret = tst.testCreateCopy(check_minmax=0, check_gt=0, check_srs=None, check_checksum_not_null=pdf_checksum_available()) return ret -def pdf_tiled_128(): - - if gdaltest.pdf_drv is None: - return 'skip' - +def test_pdf_tiled_128(poppler_or_pdfium): tst = gdaltest.GDALTest('PDF', 'utm.tif', 1, None, options=['BLOCKXSIZE=128', 'BLOCKYSIZE=128']) ret = tst.testCreateCopy(check_minmax=0, check_gt=0, check_srs=None, check_checksum_not_null=pdf_checksum_available()) @@ -601,13 +519,9 @@ def pdf_tiled_128(): # Test raster with color table -def pdf_color_table(): - - if gdaltest.pdf_drv is None: - return 'skip' - +def test_pdf_color_table(poppler_or_pdfium): if gdal.GetDriverByName('GIF') is None: - return 'skip' + pytest.skip() tst = gdaltest.GDALTest('PDF', 'bug407.gif', 1, None) ret = tst.testCreateCopy(check_minmax=0, check_gt=0, check_srs=None, check_checksum_not_null=pdf_checksum_available()) @@ -618,18 +532,14 @@ def pdf_color_table(): # Test XMP support -def pdf_xmp(): - - if gdaltest.pdf_drv is None: - return 'skip' - +def test_pdf_xmp(poppler_or_pdfium): src_ds = gdal.Open('data/adobe_style_geospatial_with_xmp.pdf') gdaltest.pdf_drv.CreateCopy('tmp/pdf_xmp.pdf', src_ds, options=['WRITE_INFO=NO']) out_ds = gdal.Open('tmp/pdf_xmp.pdf') if out_ds is None: # Some Poppler versions cannot re-open the file gdal.GetDriverByName('PDF').Delete('tmp/pdf_xmp.pdf') - return 'skip' + pytest.skip() ref_md = src_ds.GetMetadata('xml:XMP') got_md = out_ds.GetMetadata('xml:XMP') @@ -639,27 +549,15 @@ def pdf_xmp(): gdal.GetDriverByName('PDF').Delete('tmp/pdf_xmp.pdf') - if ref_md[0] != got_md[0]: - gdaltest.post_reason('fail') - print(got_md[0]) - return 'fail' + assert ref_md[0] == got_md[0] - if len(base_md) != 2: # NEATLINE and DPI - gdaltest.post_reason('fail') - print(base_md) - return 'fail' - - return 'success' + assert len(base_md) == 2 ############################################################################### # Test Info -def pdf_info(): - - if gdaltest.pdf_drv is None: - return 'skip' - +def test_pdf_info(poppler_or_pdfium): try: val = '\xc3\xa9'.decode('UTF-8') except: @@ -687,27 +585,18 @@ def pdf_info(): gdal.GetDriverByName('PDF').Delete('tmp/pdf_info.pdf') gdal.GetDriverByName('PDF').Delete('tmp/pdf_info_2.pdf') - if md['AUTHOR'] != val or \ - md['CREATOR'] != 'creator' or \ - md['KEYWORDS'] != 'keywords' or \ - md['PRODUCER'] != 'producer' or \ - md['SUBJECT'] != 'subject' or \ - md['TITLE'] != 'title': - gdaltest.post_reason("metadata doesn't match") - print(md) - return 'fail' - - return 'success' + assert (md['AUTHOR'] == val and \ + md['CREATOR'] == 'creator' and \ + md['KEYWORDS'] == 'keywords' and \ + md['PRODUCER'] == 'producer' and \ + md['SUBJECT'] == 'subject' and \ + md['TITLE'] == 'title'), "metadata doesn't match" ############################################################################### # Check SetGeoTransform() / SetProjection() -def pdf_update_gt(): - - if gdaltest.pdf_drv is None: - return 'skip' - +def test_pdf_update_gt(poppler_or_pdfium_or_podofo): src_ds = gdal.Open('data/byte.tif') ds = gdaltest.pdf_drv.CreateCopy('tmp/pdf_update_gt.pdf', src_ds) ds = None @@ -721,9 +610,7 @@ def pdf_update_gt(): ds.SetGeoTransform([2, 1, 0, 49, 0, -1]) ds = None - if os.path.exists('tmp/pdf_update_gt.pdf.aux.xml'): - gdaltest.post_reason('fail') - return 'fail' + assert not os.path.exists('tmp/pdf_update_gt.pdf.aux.xml') # Check geotransform ds = gdal.Open('tmp/pdf_update_gt.pdf') @@ -732,10 +619,7 @@ def pdf_update_gt(): expected_gt = [2, 1, 0, 49, 0, -1] for i in range(6): - if abs(gt[i] - expected_gt[i]) > 1e-8: - gdaltest.post_reason('did not get expected gt') - print(gt) - return 'fail' + assert abs(gt[i] - expected_gt[i]) <= 1e-8, 'did not get expected gt' # Clear geotransform ds = gdal.Open('tmp/pdf_update_gt.pdf', gdal.GA_Update) @@ -749,10 +633,7 @@ def pdf_update_gt(): expected_gt = [0.0, 1.0, 0.0, 0.0, 0.0, 1.0] for i in range(6): - if abs(gt[i] - expected_gt[i]) > 1e-8: - gdaltest.post_reason('did not get expected gt') - print(gt) - return 'fail' + assert abs(gt[i] - expected_gt[i]) <= 1e-8, 'did not get expected gt' # Set geotransform again ds = gdal.Open('tmp/pdf_update_gt.pdf', gdal.GA_Update) @@ -767,24 +648,15 @@ def pdf_update_gt(): expected_gt = [3, 1, 0, 50, 0, -1] for i in range(6): - if abs(gt[i] - expected_gt[i]) > 1e-8: - gdaltest.post_reason('did not get expected gt') - print(gt) - return 'fail' + assert abs(gt[i] - expected_gt[i]) <= 1e-8, 'did not get expected gt' gdaltest.pdf_drv.Delete('tmp/pdf_update_gt.pdf') - return 'success' - ############################################################################### # Check SetMetadataItem() for Info -def pdf_update_info(): - - if gdaltest.pdf_drv is None: - return 'skip' - +def test_pdf_update_info(poppler_or_pdfium_or_podofo): src_ds = gdal.Open('data/byte.tif') ds = gdaltest.pdf_drv.CreateCopy('tmp/pdf_update_info.pdf', src_ds) ds = None @@ -800,10 +672,7 @@ def pdf_update_info(): author = ds.GetMetadataItem('AUTHOR') ds = None - if author != 'author': - gdaltest.post_reason('did not get expected metadata') - print(author) - return 'fail' + assert author == 'author', 'did not get expected metadata' # Update info ds = gdal.Open('tmp/pdf_update_info.pdf', gdal.GA_Update) @@ -815,10 +684,7 @@ def pdf_update_info(): author = ds.GetMetadataItem('AUTHOR') ds = None - if author != 'author2': - gdaltest.post_reason('did not get expected metadata') - print(author) - return 'fail' + assert author == 'author2', 'did not get expected metadata' # Clear info ds = gdal.Open('tmp/pdf_update_info.pdf', gdal.GA_Update) @@ -827,33 +693,23 @@ def pdf_update_info(): # Check PAM doesn't exist if os.path.exists('tmp/pdf_update_info.pdf.aux.xml'): - gdaltest.post_reason('did not expected .aux.xml') print(author) - return 'fail' + pytest.fail('did not expected .aux.xml') # Check ds = gdal.Open('tmp/pdf_update_info.pdf') author = ds.GetMetadataItem('AUTHOR') ds = None - if author is not None: - gdaltest.post_reason('did not get expected metadata') - print(author) - return 'fail' + assert author is None, 'did not get expected metadata' gdaltest.pdf_drv.Delete('tmp/pdf_update_info.pdf') - return 'success' - ############################################################################### # Check SetMetadataItem() for xml:XMP -def pdf_update_xmp(): - - if gdaltest.pdf_drv is None: - return 'skip' - +def test_pdf_update_xmp(poppler_or_pdfium_or_podofo): src_ds = gdal.Open('data/byte.tif') ds = gdaltest.pdf_drv.CreateCopy('tmp/pdf_update_xmp.pdf', src_ds) ds = None @@ -869,10 +725,7 @@ def pdf_update_xmp(): xmp = ds.GetMetadata('xml:XMP')[0] ds = None - if xmp != "<?xpacket begin='a'/><a/>": - gdaltest.post_reason('did not get expected metadata') - print(xmp) - return 'fail' + assert xmp == "<?xpacket begin='a'/><a/>", 'did not get expected metadata' # Update info ds = gdal.Open('tmp/pdf_update_xmp.pdf', gdal.GA_Update) @@ -884,15 +737,11 @@ def pdf_update_xmp(): xmp = ds.GetMetadata('xml:XMP')[0] ds = None - if xmp != "<?xpacket begin='a'/><a_updated/>": - gdaltest.post_reason('did not get expected metadata') - print(xmp) - return 'fail' + assert xmp == "<?xpacket begin='a'/><a_updated/>", 'did not get expected metadata' # Check PAM doesn't exist - if os.path.exists('tmp/pdf_update_xmp.pdf.aux.xml'): - gdaltest.post_reason('did not expected .aux.xml') - return 'fail' + assert not os.path.exists('tmp/pdf_update_xmp.pdf.aux.xml'), \ + 'did not expected .aux.xml' # Clear info ds = gdal.Open('tmp/pdf_update_xmp.pdf', gdal.GA_Update) @@ -904,24 +753,16 @@ def pdf_update_xmp(): xmp = ds.GetMetadata('xml:XMP') ds = None - if xmp is not None: - gdaltest.post_reason('did not get expected metadata') - print(xmp) - return 'fail' + assert xmp is None, 'did not get expected metadata' gdaltest.pdf_drv.Delete('tmp/pdf_update_xmp.pdf') - return 'success' - ############################################################################### # Check SetGCPs() but with GCPs that resolve to a geotransform -def pdf_update_gcps(dpi=300): - - if gdaltest.pdf_drv is None: - return 'skip' - +def _pdf_update_gcps(poppler_or_pdfium): + dpi = 300 out_filename = 'tmp/pdf_update_gcps.pdf' src_ds = gdal.Open('data/byte.tif') @@ -983,26 +824,14 @@ def pdf_update_gcps(dpi=300): ds = None - if got_wkt == '': - gdaltest.post_reason('did not expect null GetProjectionRef') - print(got_wkt) - return 'fail' + assert got_wkt != '', 'did not expect null GetProjectionRef' - if got_gcp_wkt != '': - gdaltest.post_reason('did not expect non null GetGCPProjection') - print(got_gcp_wkt) - return 'fail' + assert got_gcp_wkt == '', 'did not expect non null GetGCPProjection' for i in range(6): - if abs(got_gt[i] - src_gt[i]) > 1e-8: - gdaltest.post_reason('did not get expected gt') - print(got_gt) - return 'fail' + assert abs(got_gt[i] - src_gt[i]) <= 1e-8, 'did not get expected gt' - if got_gcp_count != 0: - gdaltest.post_reason('did not expect GCPs') - print(got_gcp_count) - return 'fail' + assert got_gcp_count == 0, 'did not expect GCPs' got_geom = ogr.CreateGeometryFromWkt(got_neatline) expected_lr = ogr.Geometry(ogr.wkbLinearRing) @@ -1013,37 +842,29 @@ def pdf_update_gcps(dpi=300): expected_geom.AddGeometry(expected_lr) if ogrtest.check_feature_geometry(got_geom, expected_geom, max_error=max_error) != 0: - gdaltest.post_reason('bad neatline') print('got : %s' % got_neatline) print('expected : %s' % expected_geom.ExportToWkt()) - return 'fail' + pytest.fail('bad neatline') gdaltest.pdf_drv.Delete(out_filename) - return 'success' - -def pdf_update_gcps_iso32000(): +def test_pdf_update_gcps_iso32000(poppler_or_pdfium): gdal.SetConfigOption('GDAL_PDF_GEO_ENCODING', None) - ret = pdf_update_gcps() - return ret + _pdf_update_gcps(poppler_or_pdfium) -def pdf_update_gcps_ogc_bp(): +def test_pdf_update_gcps_ogc_bp(poppler_or_pdfium): gdal.SetConfigOption('GDAL_PDF_GEO_ENCODING', 'OGC_BP') - ret = pdf_update_gcps() + _pdf_update_gcps(poppler_or_pdfium) gdal.SetConfigOption('GDAL_PDF_GEO_ENCODING', None) - return ret ############################################################################### # Check SetGCPs() but with GCPs that do *not* resolve to a geotransform -def pdf_set_5_gcps_ogc_bp(dpi=300): - - if gdaltest.pdf_drv is None: - return 'skip' - +def test_pdf_set_5_gcps_ogc_bp(poppler_or_pdfium): + dpi = 300 out_filename = 'tmp/pdf_set_5_gcps_ogc_bp.pdf' src_ds = gdal.Open('data/byte.tif') @@ -1104,37 +925,22 @@ def pdf_set_5_gcps_ogc_bp(dpi=300): got_neatline = ds.GetMetadataItem('NEATLINE') ds = None - if got_wkt != '': - gdaltest.post_reason('did not expect non null GetProjectionRef') - print(got_wkt) - return 'fail' + assert got_wkt == '', 'did not expect non null GetProjectionRef' - if got_gcp_wkt == '': - gdaltest.post_reason('did not expect null GetGCPProjection') - print(got_gcp_wkt) - return 'fail' + assert got_gcp_wkt != '', 'did not expect null GetGCPProjection' expected_gt = [0, 1, 0, 0, 0, 1] for i in range(6): - if abs(got_gt[i] - expected_gt[i]) > 1e-8: - gdaltest.post_reason('did not get expected gt') - print(got_gt) - return 'fail' + assert abs(got_gt[i] - expected_gt[i]) <= 1e-8, 'did not get expected gt' - if got_gcp_count != len(gcp): - gdaltest.post_reason('did not get expected GCP count') - print(got_gcp_count) - return 'fail' + assert got_gcp_count == len(gcp), 'did not get expected GCP count' for i in range(got_gcp_count): - if abs(got_gcps[i].GCPX - vrt_gcps[i].GCPX) > 1e-5 or \ - abs(got_gcps[i].GCPY - vrt_gcps[i].GCPY) > 1e-5 or \ - abs(got_gcps[i].GCPPixel - vrt_gcps[i].GCPPixel) > 1e-5 or \ - abs(got_gcps[i].GCPLine - vrt_gcps[i].GCPLine) > 1e-5: - gdaltest.post_reason('did not get expected GCP (%d)' % i) - print(got_gcps[i]) - print(vrt_gcps[i]) - return 'fail' + assert (abs(got_gcps[i].GCPX - vrt_gcps[i].GCPX) <= 1e-5 and \ + abs(got_gcps[i].GCPY - vrt_gcps[i].GCPY) <= 1e-5 and \ + abs(got_gcps[i].GCPPixel - vrt_gcps[i].GCPPixel) <= 1e-5 and \ + abs(got_gcps[i].GCPLine - vrt_gcps[i].GCPLine) <= 1e-5), \ + ('did not get expected GCP (%d)' % i) got_geom = ogr.CreateGeometryFromWkt(got_neatline) # Not sure this is really what we want, but without any geotransform, we cannot @@ -1142,24 +948,17 @@ def pdf_set_5_gcps_ogc_bp(dpi=300): expected_geom = ogr.CreateGeometryFromWkt('POLYGON ((2 8,2 10,2 18,16 18,16 8,2 8))') if ogrtest.check_feature_geometry(got_geom, expected_geom) != 0: - gdaltest.post_reason('bad neatline') print('got : %s' % got_neatline) print('expected : %s' % expected_geom.ExportToWkt()) - return 'fail' + pytest.fail('bad neatline') gdaltest.pdf_drv.Delete(out_filename) - return 'success' - ############################################################################### # Check NEATLINE support -def pdf_set_neatline(geo_encoding, dpi=300): - - if gdaltest.pdf_drv is None: - return 'skip' - +def _pdf_set_neatline(pdf_backend, geo_encoding, dpi=300): out_filename = 'tmp/pdf_set_neatline.pdf' if geo_encoding == 'ISO32000': @@ -1188,20 +987,15 @@ def pdf_set_neatline(geo_encoding, dpi=300): ds = None for i in range(6): - if abs(got_gt[i] - expected_gt[i]) > 1e-7: - gdaltest.post_reason('did not get expected gt') - print(got_gt) - print(expected_gt) - return 'fail' + assert abs(got_gt[i] - expected_gt[i]) <= 1e-7, 'did not get expected gt' got_geom = ogr.CreateGeometryFromWkt(got_neatline) expected_geom = ogr.CreateGeometryFromWkt(neatline) if ogrtest.check_feature_geometry(got_geom, expected_geom, max_error=max_error) != 0: - gdaltest.post_reason('bad neatline') print('got : %s' % got_neatline) print('expected : %s' % expected_geom.ExportToWkt()) - return 'fail' + pytest.fail('bad neatline') # Test SetMetadataItem() ds = gdal.Open(out_filename, gdal.GA_Update) @@ -1223,42 +1017,33 @@ def pdf_set_neatline(geo_encoding, dpi=300): gdal.SetConfigOption('GDAL_PDF_GEO_ENCODING', None) for i in range(6): - if (expected_gt[i] == 0 and abs(got_gt[i] - expected_gt[i]) > 1e-7) or \ - (expected_gt[i] != 0 and abs((got_gt[i] - expected_gt[i]) / expected_gt[i]) > 1e-7): - gdaltest.post_reason('did not get expected gt') - print(got_gt) - return 'fail' + assert (not (expected_gt[i] == 0 and abs(got_gt[i] - expected_gt[i]) > 1e-7) or \ + (expected_gt[i] != 0 and abs((got_gt[i] - expected_gt[i]) / expected_gt[i]) > 1e-7)), \ + 'did not get expected gt' got_geom = ogr.CreateGeometryFromWkt(got_neatline) expected_geom = ogr.CreateGeometryFromWkt(neatline) if ogrtest.check_feature_geometry(got_geom, expected_geom, max_error=max_error) != 0: - gdaltest.post_reason('bad neatline') print('got : %s' % got_neatline) print('expected : %s' % expected_geom.ExportToWkt()) - return 'fail' + pytest.fail('bad neatline') gdaltest.pdf_drv.Delete(out_filename) - return 'success' +def test_pdf_set_neatline_iso32000(poppler_or_pdfium): + return _pdf_set_neatline(poppler_or_pdfium, 'ISO32000') -def pdf_set_neatline_iso32000(): - return pdf_set_neatline('ISO32000') - -def pdf_set_neatline_ogc_bp(): - return pdf_set_neatline('OGC_BP') +def test_pdf_set_neatline_ogc_bp(poppler_or_pdfium): + return _pdf_set_neatline(poppler_or_pdfium, 'OGC_BP') ############################################################################### # Check that we can generate identical file -def pdf_check_identity_iso32000(): - - if gdaltest.pdf_drv is None: - return 'skip' - +def test_pdf_check_identity_iso32000(poppler_or_pdfium): out_filename = 'tmp/pdf_check_identity_iso32000.pdf' src_ds = gdal.Open('data/test_pdf.vrt') @@ -1276,21 +1061,13 @@ def pdf_check_identity_iso32000(): gdaltest.pdf_drv.Delete(out_filename) - if data_ref != data_got: - gdaltest.post_reason('content does not match reference content') - return 'fail' - - return 'success' + assert data_ref == data_got, 'content does not match reference content' ############################################################################### # Check that we can generate identical file -def pdf_check_identity_ogc_bp(): - - if gdaltest.pdf_drv is None: - return 'skip' - +def test_pdf_check_identity_ogc_bp(poppler_or_pdfium): out_filename = 'tmp/pdf_check_identity_ogc_bp.pdf' src_ds = gdal.Open('data/test_pdf.vrt') @@ -1310,23 +1087,15 @@ def pdf_check_identity_ogc_bp(): gdaltest.pdf_drv.Delete(out_filename) - if data_ref != data_got: - gdaltest.post_reason('content does not match reference content') - return 'fail' - - return 'success' + assert data_ref == data_got, 'content does not match reference content' ############################################################################### # Check layers support -def pdf_layers(): - - if gdaltest.pdf_drv is None: - return 'skip' - +def test_pdf_layers(poppler_or_pdfium): if not pdf_is_poppler() and not pdf_is_pdfium(): - return 'skip' + pytest.skip() ds = gdal.Open('data/adobe_style_geospatial.pdf') layers = ds.GetMetadata_List('LAYERS') @@ -1334,13 +1103,11 @@ def pdf_layers(): ds = None # if layers != ['LAYER_00_INIT_STATE=ON', 'LAYER_00_NAME=New_Data_Frame', 'LAYER_01_INIT_STATE=ON', 'LAYER_01_NAME=New_Data_Frame.Graticule', 'LAYER_02_INIT_STATE=ON', 'LAYER_02_NAME=Layers', 'LAYER_03_INIT_STATE=ON', 'LAYER_03_NAME=Layers.Measured_Grid', 'LAYER_04_INIT_STATE=ON', 'LAYER_04_NAME=Layers.Graticule']: - if layers != ['LAYER_00_NAME=New_Data_Frame', 'LAYER_01_NAME=New_Data_Frame.Graticule', 'LAYER_02_NAME=Layers', 'LAYER_03_NAME=Layers.Measured_Grid', 'LAYER_04_NAME=Layers.Graticule']: - gdaltest.post_reason('did not get expected layers') - print(layers) - return 'fail' + assert layers == ['LAYER_00_NAME=New_Data_Frame', 'LAYER_01_NAME=New_Data_Frame.Graticule', 'LAYER_02_NAME=Layers', 'LAYER_03_NAME=Layers.Measured_Grid', 'LAYER_04_NAME=Layers.Graticule'], \ + 'did not get expected layers' if not pdf_checksum_available(): - return 'skip' + pytest.skip() # Turn a layer off gdal.SetConfigOption('GDAL_PDF_LAYERS_OFF', 'New_Data_Frame') @@ -1349,9 +1116,7 @@ def pdf_layers(): ds = None gdal.SetConfigOption('GDAL_PDF_LAYERS_OFF', None) - if cs2 == cs1: - gdaltest.post_reason('did not get expected checksum') - return 'fail' + assert cs2 != cs1, 'did not get expected checksum' # Turn the other layer on gdal.SetConfigOption('GDAL_PDF_LAYERS', 'Layers') @@ -1361,30 +1126,20 @@ def pdf_layers(): gdal.SetConfigOption('GDAL_PDF_LAYERS', None) # So the end result must be identical - if cs3 != cs2: - gdaltest.post_reason('did not get expected checksum') - return 'fail' + assert cs3 == cs2, 'did not get expected checksum' # Turn another sublayer on ds = gdal.OpenEx('data/adobe_style_geospatial.pdf', open_options=['LAYERS=Layers.Measured_Grid']) cs4 = ds.GetRasterBand(1).Checksum() ds = None - if cs4 == cs1 or cs4 == cs2: - gdaltest.post_reason('did not get expected checksum') - return 'fail' - - return 'success' + assert not (cs4 == cs1 or cs4 == cs2), 'did not get expected checksum' ############################################################################### # Test MARGIN, EXTRA_STREAM, EXTRA_LAYER_NAME and EXTRA_IMAGES options -def pdf_custom_layout(): - - if gdaltest.pdf_drv is None: - return 'skip' - +def test_pdf_custom_layout(poppler_or_pdfium): js = """button = app.alert({cMsg: 'This file was generated by GDAL. Do you want to visit its website ?', cTitle: 'Question', nIcon:2, nType:2}); if (button == 4) app.launchURL('http://gdal.org/');""" @@ -1413,22 +1168,15 @@ def pdf_custom_layout(): gdal.GetDriverByName('PDF').Delete('tmp/pdf_custom_layout.pdf') if pdf_is_poppler() or pdf_is_pdfium(): - if layers != ['LAYER_00_NAME=byte_tif', 'LAYER_01_NAME=Footpage_and_logo']: - gdaltest.post_reason('did not get expected layers') - print(layers) - return 'fail' - - return 'success' + assert layers == ['LAYER_00_NAME=byte_tif', 'LAYER_01_NAME=Footpage_and_logo'], \ + 'did not get expected layers' + ############################################################################### # Test CLIPPING_EXTENT, EXTRA_RASTERS, EXTRA_RASTERS_LAYER_NAME, OFF_LAYERS, EXCLUSIVE_LAYERS options -def pdf_extra_rasters(): - - if gdaltest.pdf_drv is None: - return 'skip' - +def test_pdf_extra_rasters(poppler_or_pdfium): subbyte = """<VRTDataset rasterXSize="10" rasterYSize="10"> <SRS>PROJCS["NAD27 / UTM zone 11N",GEOGCS["NAD27",DATUM["North_American_Datum_1927",SPHEROID["Clarke 1866",6378206.4,294.9786982139006,AUTHORITY["EPSG","7008"]],AUTHORITY["EPSG","6267"]],PRIMEM["Greenwich",0],UNIT["degree",0.0174532925199433],AUTHORITY["EPSG","4267"]],PROJECTION["Transverse_Mercator"],PARAMETER["latitude_of_origin",0],PARAMETER["central_meridian",-117],PARAMETER["scale_factor",0.9996],PARAMETER["false_easting",500000],PARAMETER["false_northing",0],UNIT["metre",1,AUTHORITY["EPSG","9001"]],AUTHORITY["EPSG","26711"]]</SRS> <GeoTransform> 4.4102000000000000e+05, 6.0000000000000000e+01, 0.0000000000000000e+00, 3.7510200000000000e+06, 0.0000000000000000e+00, -6.0000000000000000e+01</GeoTransform> @@ -1480,26 +1228,16 @@ def pdf_extra_rasters(): os.unlink('tmp/subbyte.vrt') if pdf_is_poppler() or pdf_is_pdfium(): - if layers != ['LAYER_00_NAME=byte_tif', 'LAYER_01_NAME=subbyte']: - gdaltest.post_reason('did not get expected layers') - print(layers) - return 'fail' - if pdf_is_poppler() and (cs != 7926 and cs != 8177 and cs != 8174 and cs != 8165): - gdaltest.post_reason('bad checksum') - print(cs) - return 'fail' - - return 'success' + assert layers == ['LAYER_00_NAME=byte_tif', 'LAYER_01_NAME=subbyte'], \ + 'did not get expected layers' + assert not (pdf_is_poppler() and (cs != 7926 and cs != 8177 and cs != 8174 and cs != 8165)), \ + 'bad checksum' ############################################################################### # Test adding a OGR datasource -def pdf_write_ogr(): - - if gdaltest.pdf_drv is None: - return 'skip' - +def test_pdf_write_ogr(poppler_or_pdfium): f = gdal.VSIFOpenL('tmp/test.csv', 'wb') data = """id,foo,WKT,style 1,bar,"MULTIPOLYGON (((440720 3751320,440720 3750120,441020 3750120,441020 3751320,440720 3751320),(440800 3751200,440900 3751200,440900 3751000,440800 3751000,440800 3751200)),((441720 3751320,441720 3750120,441920 3750120,441920 3751320,441720 3751320)))", @@ -1564,17 +1302,11 @@ def pdf_write_ogr(): # print('Checksum %s: %d' % (rendering_options[i], cs_tab[i]) ) for j in range(i + 1, len(rendering_options)): if cs_tab[i] == cs_tab[j] and cs_tab[i] >= 0 and cs_tab[j] >= 0: - gdaltest.post_reason('fail') print('Checksum %s: %d' % (roi, cs_tab[i])) - print('Checksum %s: %d' % (rendering_options[j], cs_tab[j])) - return 'fail' + pytest.fail('Checksum %s: %d' % (rendering_options[j], cs_tab[j])) # And test that RASTER,VECTOR,TEXT is the default rendering - if abs(cs_tab[len(rendering_options) - 1]) != cs_ref: - gdaltest.post_reason('fail') - print(cs_ref) - print(cs_tab[len(rendering_options) - 1]) - return 'fail' + assert abs(cs_tab[len(rendering_options) - 1]) == cs_ref gdal.GetDriverByName('PDF').Delete('tmp/pdf_write_ogr.pdf') @@ -1582,32 +1314,21 @@ def pdf_write_ogr(): gdal.Unlink('tmp/test.vrt') if pdf_is_poppler() or pdf_is_pdfium(): - if layers != ['LAYER_00_NAME=A_Layer', 'LAYER_01_NAME=A_Layer.Text']: - gdaltest.post_reason('did not get expected layers') - print(layers) - return 'fail' + assert layers == ['LAYER_00_NAME=A_Layer', 'LAYER_01_NAME=A_Layer.Text'], \ + 'did not get expected layers' # Should have filtered out id = 4 - if feature_count != 3: - gdaltest.post_reason('did not get expected feature count') - print(feature_count) - return 'fail' - - return 'success' + assert feature_count == 3, 'did not get expected feature count' ############################################################################### # Test adding a OGR datasource with reprojection of OGR SRS to GDAL SRS -def pdf_write_ogr_with_reprojection(): - - if gdaltest.pdf_drv is None: - return 'skip' - - import osr_ct - osr_ct.osr_ct_1() +def test_pdf_write_ogr_with_reprojection(poppler_or_pdfium): + from osr import osr_ct + osr_ct.test_osr_ct_1() if gdaltest.have_proj4 == 0: - return 'skip' + pytest.skip() f = gdal.VSIFOpenL('tmp/test.csv', 'wb') data = """WKT,id @@ -1654,24 +1375,15 @@ def pdf_write_ogr_with_reprojection(): gdal.Unlink('tmp/test.vrt') # Should have filtered out id = 6 - if feature_count != 5: - gdaltest.post_reason('did not get expected feature count') - print(feature_count) - return 'fail' - - return 'success' + assert feature_count == 5, 'did not get expected feature count' ############################################################################### # Test direct copy of source JPEG file -def pdf_jpeg_direct_copy(): - - if gdaltest.pdf_drv is None: - return 'skip' - +def test_pdf_jpeg_direct_copy(poppler_or_pdfium): if gdal.GetDriverByName('JPEG') is None: - return 'skip' + pytest.skip() src_ds = gdal.Open('data/byte_with_xmp.jpg') ds = gdaltest.pdf_drv.CreateCopy('tmp/pdf_jpeg_direct_copy.pdf', src_ds, options=['XMP=NO']) @@ -1680,15 +1392,9 @@ def pdf_jpeg_direct_copy(): ds = gdal.Open('tmp/pdf_jpeg_direct_copy.pdf') # No XMP at PDF level - if ds.GetMetadata('xml:XMP') is not None: - gdaltest.post_reason('failed') - return 'fail' - if ds.RasterXSize != 20: - gdaltest.post_reason('failed') - return 'fail' - if pdf_checksum_available() and ds.GetRasterBand(1).Checksum() == 0: - gdaltest.post_reason('failed') - return 'fail' + assert ds.GetMetadata('xml:XMP') is None + assert ds.RasterXSize == 20 + assert not (pdf_checksum_available() and ds.GetRasterBand(1).Checksum() == 0) ds = None # But we can find the original XMP from the JPEG file ! @@ -1699,23 +1405,15 @@ def pdf_jpeg_direct_copy(): gdal.Unlink('tmp/pdf_jpeg_direct_copy.pdf') - if offset == -1: - gdaltest.post_reason('failed') - return 'fail' - - return 'success' + assert offset != -1 ############################################################################### # Test direct copy of source JPEG file within VRT file -def pdf_jpeg_in_vrt_direct_copy(): - - if gdaltest.pdf_drv is None: - return 'skip' - +def test_pdf_jpeg_in_vrt_direct_copy(poppler_or_pdfium): if gdal.GetDriverByName('JPEG') is None: - return 'skip' + pytest.skip() src_ds = gdal.Open("""<VRTDataset rasterXSize="20" rasterYSize="20"> <SRS>PROJCS["NAD27 / UTM zone 11N",GEOGCS["NAD27",DATUM["North_American_Datum_1927",SPHEROID["Clarke 1866",6378206.4,294.9786982139006,AUTHORITY["EPSG","7008"]],AUTHORITY["EPSG","6267"]],PRIMEM["Greenwich",0],UNIT["degree",0.0174532925199433],AUTHORITY["EPSG","4267"]],PROJECTION["Transverse_Mercator"],PARAMETER["latitude_of_origin",0],PARAMETER["central_meridian",-117],PARAMETER["scale_factor",0.9996],PARAMETER["false_easting",500000],PARAMETER["false_northing",0],UNIT["metre",1,AUTHORITY["EPSG","9001"]],AUTHORITY["EPSG","26711"]]</SRS> @@ -1736,15 +1434,9 @@ def pdf_jpeg_in_vrt_direct_copy(): ds = gdal.Open('tmp/pdf_jpeg_in_vrt_direct_copy.pdf') # No XMP at PDF level - if ds.GetMetadata('xml:XMP') is not None: - gdaltest.post_reason('failed') - return 'fail' - if ds.RasterXSize != 20: - gdaltest.post_reason('failed') - return 'fail' - if pdf_checksum_available() and ds.GetRasterBand(1).Checksum() == 0: - gdaltest.post_reason('failed') - return 'fail' + assert ds.GetMetadata('xml:XMP') is None + assert ds.RasterXSize == 20 + assert not (pdf_checksum_available() and ds.GetRasterBand(1).Checksum() == 0) ds = None # But we can find the original XMP from the JPEG file ! @@ -1755,21 +1447,17 @@ def pdf_jpeg_in_vrt_direct_copy(): gdal.Unlink('tmp/pdf_jpeg_in_vrt_direct_copy.pdf') - if offset == -1: - gdaltest.post_reason('failed') - return 'fail' - - return 'success' + assert offset != -1 ############################################################################### # Test reading georeferencing attached to an image, and not to the page (#4695) -def pdf_georef_on_image(src_filename='data/byte.tif'): - - if gdaltest.pdf_drv is None: - return 'skip' - +@pytest.mark.parametrize( + 'src_filename', + ['data/byte.tif', 'data/rgbsmall.tif'] +) +def pdf_georef_on_image(src_filename, pdf_backend): src_ds = gdal.Open(src_filename) gdal.SetConfigOption('GDAL_PDF_WRITE_GEOREF_ON_IMAGE', 'YES') out_ds = gdaltest.pdf_drv.CreateCopy('tmp/pdf_georef_on_image.pdf', src_ds, options=['MARGIN=10', 'GEO_ENCODING=NONE']) @@ -1795,31 +1483,16 @@ def pdf_georef_on_image(src_filename='data/byte.tif'): gdal.GetDriverByName('PDF').Delete('tmp/pdf_georef_on_image.pdf') - if got_wkt == '': - gdaltest.post_reason('did not get projection') - return 'fail' + assert got_wkt != '', 'did not get projection' - if pdf_checksum_available() and src_cs != got_cs: - gdaltest.post_reason('did not get same checksum') - print(src_cs) - print(got_cs) - return 'fail' + assert not pdf_checksum_available() or src_cs == got_cs, 'did not get same checksum' - return 'success' - - -def pdf_georef_on_image_rgb(): - return pdf_georef_on_image('data/rgbsmall.tif') ############################################################################### # Test writing a PDF that hits Acrobat limits in term of page dimensions (#5412) -def pdf_write_huge(): - - if gdaltest.pdf_drv is None: - return 'skip' - +def test_pdf_write_huge(poppler_or_pdfium): if pdf_is_poppler() or pdf_is_pdfium(): tmp_filename = '/vsimem/pdf_write_huge.pdf' else: @@ -1830,16 +1503,9 @@ def pdf_write_huge(): ds = gdaltest.pdf_drv.CreateCopy(tmp_filename, src_ds) ds = None ds = gdal.Open(tmp_filename) - if int(ds.GetMetadataItem('DPI')) != 96: - gdaltest.post_reason('failure') - print(ds.GetMetadataItem('DPI')) - return 'fail' - if ds.RasterXSize != src_ds.RasterXSize or \ - ds.RasterYSize != src_ds.RasterYSize: - gdaltest.post_reason('failure') - print(ds.RasterXSize) - print(ds.RasterYSize) - return 'fail' + assert int(ds.GetMetadataItem('DPI')) == 96 + assert (ds.RasterXSize == src_ds.RasterXSize and \ + ds.RasterYSize == src_ds.RasterYSize) ds = None gdal.ErrorReset() @@ -1847,15 +1513,10 @@ def pdf_write_huge(): ds = gdaltest.pdf_drv.CreateCopy(tmp_filename, src_ds, options=['DPI=72']) gdal.PopErrorHandler() msg = gdal.GetLastErrorMsg() - if msg == '': - gdaltest.post_reason('failure') - return 'fail' + assert msg != '' ds = None ds = gdal.Open(tmp_filename) - if int(ds.GetMetadataItem('DPI')) != 72: - gdaltest.post_reason('failure') - print(ds.GetMetadataItem('DPI')) - return 'fail' + assert int(ds.GetMetadataItem('DPI')) == 72 ds = None src_ds = None @@ -1867,34 +1528,23 @@ def pdf_write_huge(): ds = gdaltest.pdf_drv.CreateCopy(tmp_filename, src_ds, options=[option]) gdal.PopErrorHandler() msg = gdal.GetLastErrorMsg() - if msg == '': - gdaltest.post_reason('failure') - return 'fail' + assert msg != '' ds = None ds = gdal.Open(tmp_filename) - if int(ds.GetMetadataItem('DPI')) != 72: - gdaltest.post_reason('failure') - print(ds.GetMetadataItem('DPI')) - return 'fail' + assert int(ds.GetMetadataItem('DPI')) == 72 ds = None src_ds = None gdal.Unlink(tmp_filename) - return 'success' - ############################################################################### # Test creating overviews -def pdf_overviews(): - - if gdaltest.pdf_drv is None: - return 'skip' - +def test_pdf_overviews(poppler_or_pdfium): if not pdf_is_poppler() and not pdf_is_pdfium(): - return 'skip' + pytest.skip() tmp_filename = '/vsimem/pdf_overviews.pdf' src_ds = gdal.GetDriverByName('MEM').Create('', 1024, 1024, 3) @@ -1908,69 +1558,45 @@ def pdf_overviews(): ds.GetRasterBand(1).GetOverview(-1) ds.GetRasterBand(1).GetOverview(10) if before >= 1: - if not pdf_is_pdfium(): - gdaltest.post_reason('No overview expected at this point!') - return 'fail' + assert pdf_is_pdfium(), 'No overview expected at this point!' cs = ds.GetRasterBand(1).GetOverview(0).Checksum() - if cs != 5934: - gdaltest.post_reason('failure') - print(cs) - return 'fail' + assert cs == 5934 elif pdf_is_pdfium(): - gdaltest.post_reason('Overview expected at this point!') - return 'fail' + pytest.fail('Overview expected at this point!') ds.BuildOverviews('NONE', [2]) after = ds.GetRasterBand(1).GetOverviewCount() - if after != 1: - gdaltest.post_reason('failure') - print(after) - return 'fail' + assert after == 1 cs = ds.GetRasterBand(1).GetOverview(0).Checksum() - if cs != 0: - gdaltest.post_reason('failure') - print(cs) - return 'fail' + assert cs == 0 ds = None gdaltest.pdf_drv.Delete(tmp_filename) - return 'success' - ############################################################################### # Test password -def pdf_password(): - - if gdaltest.pdf_drv is None: - return 'skip' - +def test_pdf_password(poppler_or_pdfium_or_podofo): # User password of this test file is user_password and owner password is # owner_password # No password with gdaltest.error_handler(): ds = gdal.Open('data/byte_enc.pdf') - if ds is not None: - gdaltest.post_reason('fail') - return 'fail' + assert ds is None # Wrong password with gdaltest.error_handler(): ds = gdal.OpenEx('data/byte_enc.pdf', open_options=['USER_PWD=wrong_password']) - if ds is not None: - gdaltest.post_reason('fail') - return 'fail' + assert ds is None # Correct password ds = gdal.OpenEx('data/byte_enc.pdf', open_options=['USER_PWD=user_password']) - if ds is None: - gdaltest.post_reason('fail') - return 'fail' + assert ds is not None import test_cli_utilities if test_cli_utilities.get_gdal_translate_path() is None: - return 'skip' + pytest.skip() # Test ASK_INTERACTIVE with wrong password cmd_line = test_cli_utilities.get_gdal_translate_path() + ' data/byte_enc.pdf /vsimem/out.tif -q -oo USER_PWD=ASK_INTERACTIVE < tmp/password.txt' @@ -1980,29 +1606,19 @@ def pdf_password(): open('tmp/password.txt', 'wb').write('wrong_password'.encode('ASCII')) ret = os.system(cmd_line) os.unlink('tmp/password.txt') - if ret == 0: - gdaltest.post_reason('fail') - return 'fail' + assert ret != 0 # Test ASK_INTERACTIVE with correct password open('tmp/password.txt', 'wb').write('user_password'.encode('ASCII')) ret = os.system(cmd_line) os.unlink('tmp/password.txt') - if ret != 0: - gdaltest.post_reason('fail') - return 'fail' - - return 'success' + assert ret == 0 ############################################################################### # Test multi page support -def pdf_multipage(): - - if gdaltest.pdf_drv is None: - return 'skip' - +def test_pdf_multipage(poppler_or_pdfium_or_podofo): # byte_and_rgbsmall_2pages.pdf was generated with : # 1) gdal_translate gcore/data/byte.tif byte.pdf -of PDF # 2) gdal_translate gcore/data/rgbsmall.tif rgbsmall.pdf -of PDF @@ -2011,216 +1627,61 @@ def pdf_multipage(): ds = gdal.Open('data/byte_and_rgbsmall_2pages.pdf') subdatasets = ds.GetSubDatasets() expected_subdatasets = [('PDF:1:data/byte_and_rgbsmall_2pages.pdf', 'Page 1 of data/byte_and_rgbsmall_2pages.pdf'), ('PDF:2:data/byte_and_rgbsmall_2pages.pdf', 'Page 2 of data/byte_and_rgbsmall_2pages.pdf')] - if subdatasets != expected_subdatasets: - gdaltest.post_reason('did not get expected subdatasets') - print(subdatasets) - print(expected_subdatasets) - return 'fail' + assert subdatasets == expected_subdatasets, 'did not get expected subdatasets' ds = None ds = gdal.Open('PDF:1:data/byte_and_rgbsmall_2pages.pdf') - if ds.RasterXSize != 20: - gdaltest.post_reason('wrong width') - print(ds.RasterXSize) - return 'fail' + assert ds.RasterXSize == 20, 'wrong width' ds2 = gdal.Open('PDF:2:data/byte_and_rgbsmall_2pages.pdf') - if ds2.RasterXSize != 50: - gdaltest.post_reason('wrong width') - print(ds2.RasterXSize) - return 'fail' + assert ds2.RasterXSize == 50, 'wrong width' with gdaltest.error_handler(): ds3 = gdal.Open('PDF:0:data/byte_and_rgbsmall_2pages.pdf') - if ds3 is not None: - gdaltest.post_reason('fail') - return 'fail' + assert ds3 is None with gdaltest.error_handler(): ds3 = gdal.Open('PDF:3:data/byte_and_rgbsmall_2pages.pdf') - if ds3 is not None: - gdaltest.post_reason('fail') - return 'fail' + assert ds3 is None with gdaltest.error_handler(): ds = gdal.Open('PDF:1:/does/not/exist.pdf') - if ds is not None: - gdaltest.post_reason('fail') - return 'fail' - - return 'success' + assert ds is None ############################################################################### # Test PAM metadata support -def pdf_metadata(): - - if gdaltest.pdf_drv is None: - return 'skip' - +def test_pdf_metadata(poppler_or_pdfium): gdal.Translate('tmp/pdf_metadata.pdf', 'data/byte.tif', format='PDF', metadataOptions=['FOO=BAR']) ds = gdal.Open('tmp/pdf_metadata.pdf') md = ds.GetMetadata() - if 'FOO' not in md: - gdaltest.post_reason('fail') - print(md) - return 'fail' + assert 'FOO' in md ds = None ds = gdal.Open('tmp/pdf_metadata.pdf') - if ds.GetMetadataItem('FOO') != 'BAR': - gdaltest.post_reason('fail') - return 'fail' + assert ds.GetMetadataItem('FOO') == 'BAR' ds = None gdal.GetDriverByName('PDF').Delete('tmp/pdf_metadata.pdf') - return 'success' - ############################################################################### # Test PAM georef support -def pdf_pam_georef(): - - if gdaltest.pdf_drv is None: - return 'skip' - +def test_pdf_pam_georef(poppler_or_pdfium): src_ds = gdal.Open('data/byte.tif') # Default behaviour should result in no PAM file gdaltest.pdf_drv.CreateCopy('tmp/pdf_pam_georef.pdf', src_ds) - if os.path.exists('tmp/pdf_pam_georef.pdf.aux.xml'): - gdaltest.post_reason('fail') - return 'fail' + assert not os.path.exists('tmp/pdf_pam_georef.pdf.aux.xml') # Now disable internal georeferencing, so georef should go to PAM gdaltest.pdf_drv.CreateCopy('tmp/pdf_pam_georef.pdf', src_ds, options=['GEO_ENCODING=NONE']) - if not os.path.exists('tmp/pdf_pam_georef.pdf.aux.xml'): - gdaltest.post_reason('fail') - return 'fail' + assert os.path.exists('tmp/pdf_pam_georef.pdf.aux.xml') ds = gdal.Open('tmp/pdf_pam_georef.pdf') - if ds.GetGeoTransform() != src_ds.GetGeoTransform(): - gdaltest.post_reason('fail') - return 'fail' - if ds.GetProjectionRef() != src_ds.GetProjectionRef(): - gdaltest.post_reason('fail') - return 'fail' + assert ds.GetGeoTransform() == src_ds.GetGeoTransform() + assert ds.GetProjectionRef() == src_ds.GetProjectionRef() ds = None gdal.GetDriverByName('PDF').Delete('tmp/pdf_pam_georef.pdf') - - return 'success' - - -gdaltest_list_for_full_backend = [ - pdf_online_1, - pdf_online_2, - pdf_1, - pdf_iso32000, - pdf_iso32000_dpi_300, - pdf_ogcbp, - pdf_ogcbp_dpi_300, - pdf_ogcbp_lcc, - pdf_no_compression, - pdf_jpeg_compression, - pdf_jp2_auto_compression, - pdf_jp2kak_compression, - pdf_jp2ecw_compression, - pdf_jp2openjpeg_compression, - pdf_jpeg2000_compression, - pdf_jp2ecw_compression_rgb, - pdf_jpeg_compression_rgb, - pdf_rgba_default_compression, - pdf_rgba_default_compression_tiled, - pdf_jpeg_compression_rgba, - pdf_predictor_2, - pdf_predictor_2_rgb, - pdf_tiled, - pdf_tiled_128, - pdf_color_table, - pdf_xmp, - pdf_info, - pdf_update_gt, - pdf_update_info, - pdf_update_xmp, - pdf_update_gcps_iso32000, - pdf_update_gcps_ogc_bp, - pdf_set_5_gcps_ogc_bp, - pdf_set_neatline_iso32000, - pdf_set_neatline_ogc_bp, - pdf_check_identity_iso32000, - pdf_check_identity_ogc_bp, - pdf_layers, - pdf_custom_layout, - pdf_extra_rasters, - pdf_write_ogr, - pdf_write_ogr_with_reprojection, - pdf_jpeg_direct_copy, - pdf_jpeg_in_vrt_direct_copy, - pdf_georef_on_image, - pdf_georef_on_image_rgb, - pdf_write_huge, - pdf_overviews, - pdf_password, - pdf_multipage, - pdf_metadata, - pdf_pam_georef] - -gdaltest_list_for_short_backend = [ - pdf_iso32000, - pdf_ogcbp, - pdf_update_gt, - pdf_update_info, - pdf_update_xmp, - pdf_rgba_default_compression_tiled, - pdf_password, - pdf_multipage -] - - -def pdf_run_all(): - gdaltest.run_tests([pdf_init]) - - if gdaltest.pdf_drv is not None: - if pdf_is_poppler(): - print('Using poppler') - elif pdf_is_pdfium(): - print('Using pdfium') - else: - print('Using podofo') - - gdaltest.run_tests(gdaltest_list_for_full_backend) - - if gdal.GetConfigOption('GDAL_PDF_LIB') is None: - # Switch from pdfium to poppler if both are available - if gdaltest.pdf_drv is not None: - md = gdaltest.pdf_drv.GetMetadata() - if 'HAVE_POPPLER' in md and 'HAVE_PDFIUM' in md: - gdal.SetConfigOption("GDAL_PDF_LIB", "POPPLER") - print('Using poppler now') - gdaltest.run_tests(gdaltest_list_for_full_backend) - - # Switch from poppler/pdfium to podofo if both are available - if gdaltest.pdf_drv is not None: - md = gdaltest.pdf_drv.GetMetadata() - if ('HAVE_POPPLER' in md or 'HAVE_PDFIUM' in md) and 'HAVE_PODOFO' in md: - gdal.SetConfigOption("GDAL_PDF_LIB", "PODOFO") - print('Using podofo now') - gdaltest.pdf_is_checksum_available = None - gdaltest.run_tests(gdaltest_list_for_short_backend) - - return 'success' - - -gdaltest_list = [pdf_run_all] -# gdaltest_list = [ pdf_init, pdf_metadata ] - -if __name__ == '__main__': - - gdaltest.setup_run('PDF') - - gdaltest.run_tests(gdaltest_list) - - sys.exit(gdaltest.summarize()) diff --git a/autotest/gdrivers/pds.py b/autotest/gdrivers/pds.py index cafaf8e92775..f1a90d508c1e 100755 --- a/autotest/gdrivers/pds.py +++ b/autotest/gdrivers/pds.py @@ -30,35 +30,33 @@ ############################################################################### import os -import sys from osgeo import gdal -sys.path.append('../pymod') import gdaltest +import pytest ############################################################################### # Read a truncated and modified version of http://download.osgeo.org/gdal/data/pds/mc02.img -def pds_1(): +def test_pds_1(): tst = gdaltest.GDALTest('PDS', 'mc02_truncated.img', 1, 47151) expected_prj = """PROJCS["SIMPLE_CYLINDRICAL "MARS"",GEOGCS["GCS_"MARS"",DATUM["D_"MARS"",SPHEROID[""MARS"",3396000,0]],PRIMEM["Reference_Meridian",0],UNIT["degree",0.0174532925199433]],PROJECTION["Equirectangular"],PARAMETER["latitude_of_origin",0],PARAMETER["central_meridian",0],PARAMETER["false_easting",0],PARAMETER["false_northing",0],PARAMETER["pseudo_standard_parallel_1",0]]""" expected_gt = (-10668384.903788566589355, 926.115274429321289, 0, 3852176.483988761901855, 0, -926.115274429321289) gdal.SetConfigOption('PDS_SampleProjOffset_Shift', '-0.5') gdal.SetConfigOption('PDS_LineProjOffset_Shift', '-0.5') - ret = tst.testOpen(check_prj=expected_prj, + tst.testOpen(check_prj=expected_prj, check_gt=expected_gt) gdal.SetConfigOption('PDS_SampleProjOffset_Shift', None) gdal.SetConfigOption('PDS_LineProjOffset_Shift', None) - return ret ############################################################################### # Read a truncated and modified version of ftp://pdsimage2.wr.usgs.gov/cdroms/magellan/mg_1103/fl78n018/fl73n003.img -def pds_2(): +def test_pds_2(): tst = gdaltest.GDALTest('PDS', 'fl73n003_truncated.img', 1, 34962) expected_prj = """PROJCS["SINUSOIDAL VENUS", @@ -74,34 +72,26 @@ def pds_2(): expected_gt = (587861.55900404998, 75.000002980232239, 0.0, -7815243.4746123618, 0.0, -75.000002980232239) gdal.SetConfigOption('PDS_SampleProjOffset_Shift', '-0.5') gdal.SetConfigOption('PDS_LineProjOffset_Shift', '-0.5') - ret = tst.testOpen(check_prj=expected_prj, + tst.testOpen(check_prj=expected_prj, check_gt=expected_gt) gdal.SetConfigOption('PDS_SampleProjOffset_Shift', None) gdal.SetConfigOption('PDS_LineProjOffset_Shift', None) - if ret != 'success': - return 'fail' ds = gdal.Open('data/fl73n003_truncated.img') - if ds.GetRasterBand(1).GetNoDataValue() != 7: - return 'fail' - if ds.GetRasterBand(1).GetScale() != 0.2: - return 'fail' - if ds.GetRasterBand(1).GetOffset() != -20.2: - return 'fail' + assert ds.GetRasterBand(1).GetNoDataValue() == 7 + assert ds.GetRasterBand(1).GetScale() == 0.2 + assert ds.GetRasterBand(1).GetOffset() == -20.2 # Per #3939 we would also like to test a dataset with MISSING_CONSTANT. ds = gdal.Open('data/fl73n003_alt_truncated.img') - if ds.GetRasterBand(1).GetNoDataValue() != 7: - return 'fail' - - return 'success' + assert ds.GetRasterBand(1).GetNoDataValue() == 7 ############################################################################### # Read a truncated and modified version of ftp://pdsimage2.wr.usgs.gov/cdroms/messenger/MSGRMDS_1001/DATA/2004_232/EN0001426030M.IMG # 16bits image -def pds_3(): +def test_pds_3(): # Shut down warning about missing projection gdal.PushErrorHandler('CPLQuietErrorHandler') @@ -109,37 +99,32 @@ def pds_3(): tst = gdaltest.GDALTest('PDS', 'EN0001426030M_truncated.IMG', 1, 1367) gt_expected = (0, 1, 0, 0, 0, 1) - if tst.testOpen(check_gt=gt_expected) != 'success': - return 'fail' + tst.testOpen(check_gt=gt_expected) ds = gdal.Open('data/EN0001426030M_truncated.IMG') - if ds.GetRasterBand(1).GetNoDataValue() != 0: - return 'fail' + assert ds.GetRasterBand(1).GetNoDataValue() == 0 gdal.PopErrorHandler() - return 'success' - ############################################################################### # Read a hacked example of reading a detached file with an offset #3177. -def pds_4(): +def test_pds_4(): tst = gdaltest.GDALTest('PDS', 'pds_3177.lbl', 1, 3418) gt_expected = (6119184.3590369327, 1.0113804322107001, 0.0, -549696.39009125973, 0.0, -1.0113804322107001) gdal.SetConfigOption('PDS_SampleProjOffset_Shift', '-0.5') gdal.SetConfigOption('PDS_LineProjOffset_Shift', '-0.5') - ret = tst.testOpen(check_gt=gt_expected) + tst.testOpen(check_gt=gt_expected) gdal.SetConfigOption('PDS_SampleProjOffset_Shift', None) gdal.SetConfigOption('PDS_LineProjOffset_Shift', None) - return ret ############################################################################### # Read a hacked example of reading a detached file with an offset #3355. -def pds_5(): +def test_pds_5(): tst = gdaltest.GDALTest('PDS', 'pds_3355.lbl', 1, 2748) return tst.testOpen() @@ -149,7 +134,7 @@ def pds_5(): # driver mostly intended to support jpeg2000 files with PDS labels. -def pds_6(): +def test_pds_6(): if os.path.exists('data/byte.tif.aux.xml'): os.unlink('data/byte.tif.aux.xml') @@ -160,34 +145,27 @@ def pds_6(): gdal.SetConfigOption('PDS_SampleProjOffset_Shift', '-0.5') gdal.SetConfigOption('PDS_LineProjOffset_Shift', '-0.5') - ret = tst.testOpen(check_gt=gt_expected) + tst.testOpen(check_gt=gt_expected) gdal.SetConfigOption('PDS_SampleProjOffset_Shift', None) gdal.SetConfigOption('PDS_LineProjOffset_Shift', None) - if ret != 'success': - return 'fail' ds = gdal.Open('data/ESP_013951_1955_RED.LBL') - if len(ds.GetFileList()) != 2: - gdaltest.post_reason('failed to get expected file list.') - print(ds.GetFileList()) - return 'fail' + assert len(ds.GetFileList()) == 2, 'failed to get expected file list.' expected_wkt = 'PROJCS["EQUIRECTANGULAR MARS",GEOGCS["GCS_MARS",DATUM["D_MARS",SPHEROID["MARS_localRadius",3394839.8133163,0]],PRIMEM["Reference_Meridian",0],UNIT["degree",0.0174532925199433]],PROJECTION["Equirectangular"],PARAMETER["latitude_of_origin",0],PARAMETER["central_meridian",180],PARAMETER["standard_parallel_1",15],PARAMETER["false_easting",0],PARAMETER["false_northing",0]]' wkt = ds.GetProjection() if expected_wkt != wkt: print('Got: ', wkt) print('Exp: ', expected_wkt) - gdaltest.post_reason('did not get expected coordinate system.') - return 'fail' - - return 'success' + pytest.fail('did not get expected coordinate system.') + ############################################################################### # Read an uncompressed image via the PDS label. (#3943) -def pds_7(): +def test_pds_7(): tst = gdaltest.GDALTest('PDS', 'LDEM_4.LBL', 1, 50938, 0, 0, 1440, 2) @@ -207,21 +185,17 @@ def pds_7(): gdal.SetConfigOption('PDS_SampleProjOffset_Shift', '-0.5') gdal.SetConfigOption('PDS_LineProjOffset_Shift', '-0.5') - ret = tst.testOpen(check_prj=prj_expected, + tst.testOpen(check_prj=prj_expected, check_gt=gt_expected) gdal.SetConfigOption('PDS_SampleProjOffset_Shift', None) gdal.SetConfigOption('PDS_LineProjOffset_Shift', None) - if ret != 'success': - return 'fail' - - return 'success' ############################################################################### # Test applying adjustment offsets via configuration variables for the # geotransform (#3940) -def pds_8(): +def test_pds_8(): # values for MAGELLAN FMAP data. gdal.SetConfigOption('PDS_SampleProjOffset_Shift', '1.5') @@ -248,33 +222,25 @@ def pds_8(): # an hexadecimal floating point value (#3939) -def pds_9(): +def test_pds_9(): # Derived from http://pdsimage.wr.usgs.gov/data/co-v_e_j_s-radar-3-sbdr-v1.0/CORADR_0035/DATA/BIDR/BIEQI49N071_D035_T00AS01_V02.LBL tst = gdaltest.GDALTest('PDS', 'PDS_WITH_ZIP_IMG.LBL', 1, 0) - if tst.testOpen() != 'success': - return 'fail' + tst.testOpen() ds = gdal.Open('data/PDS_WITH_ZIP_IMG.LBL') got_nd = ds.GetRasterBand(1).GetNoDataValue() expected_nd = -3.40282265508890445e+38 - if abs((got_nd - expected_nd) / expected_nd) > 1e-5: - gdaltest.post_reason('fail') - print(got_nd) - return 'fail' - - if not ds.GetProjectionRef(): - gdaltest.post_reason('fail') - return 'fail' + assert abs((got_nd - expected_nd) / expected_nd) <= 1e-5 - return 'success' + assert ds.GetProjectionRef() ############################################################################### # Test PDS label with nested arrays (#6970) -def pds_10(): +def test_pds_10(): gdal.FileFromMemBuffer('/vsimem/pds_10', """PDS_VERSION_ID = "PDS3" @@ -299,15 +265,10 @@ def pds_10(): ds = gdal.Open('/vsimem/pds_10') - if ds.GetMetadataItem('NOTE') != '((1,2,3))': - gdaltest.post_reason('fail') - print(ds.GetMetadataItem('NOTE')) - return 'fail' + assert ds.GetMetadataItem('NOTE') == '((1,2,3))' - if ds.GetMetadataItem('PRODUCT_ID') != '({1,2},{3,4})': - gdaltest.post_reason('fail') - print(ds.GetMetadataItem('NOTE')) - return 'fail' + assert ds.GetMetadataItem('PRODUCT_ID') == '({1,2},{3,4})', \ + ds.GetMetadataItem('NOTE') gdal.FileFromMemBuffer('/vsimem/pds_10', """PDS_VERSION_ID = "PDS3" @@ -331,15 +292,13 @@ def pds_10(): gdal.Unlink('/vsimem/pds_10') - return 'success' - ############################################################################### # Read a hacked example of reading an image where the line offset is not # a multiple of the record size # https://github.com/OSGeo/gdal/issues/955 -def pds_line_offset_not_multiple_of_record(): +def test_pds_line_offset_not_multiple_of_record(): tst = gdaltest.GDALTest('PDS', 'pds/map_000_038_truncated.lbl', 1, 14019) return tst.testOpen() @@ -350,30 +309,10 @@ def pds_line_offset_not_multiple_of_record(): # Test ability of using OBJECT = FILE section to support CRISM # as well as BAND_STORAGE_TYPE = LINE_INTERLEAVED -def pds_band_storage_type_line_interleaved(): +def test_pds_band_storage_type_line_interleaved(): tst = gdaltest.GDALTest('PDS', 'pds/hsp00017ba0_01_ra218s_trr3_truncated.lbl', 1, 364) return tst.testOpen() -gdaltest_list = [ - pds_1, - pds_2, - pds_3, - pds_4, - pds_5, - pds_6, - pds_7, - pds_8, - pds_9, - pds_10, - pds_line_offset_not_multiple_of_record, - pds_band_storage_type_line_interleaved] - -if __name__ == '__main__': - - gdaltest.setup_run('pds') - - gdaltest.run_tests(gdaltest_list) - sys.exit(gdaltest.summarize()) diff --git a/autotest/gdrivers/pds4.py b/autotest/gdrivers/pds4.py index 415bf4365ea4..b911ba36eefb 100755 --- a/autotest/gdrivers/pds4.py +++ b/autotest/gdrivers/pds4.py @@ -31,14 +31,13 @@ import contextlib import os import struct -import sys -sys.path.append('../pymod') from osgeo import gdal from osgeo import ogr from osgeo import osr import gdaltest +import pytest ############################################################################### # Validate XML file against schemas @@ -47,41 +46,39 @@ def validate_xml(filename): if ogr.GetDriverByName('GMLAS') is None: - return 'skip' + pytest.skip() if not gdaltest.download_file('https://pds.nasa.gov/pds4/pds/v1/PDS4_PDS_1800.xsd', 'pds.nasa.gov_pds4_pds_v1_PDS4_PDS_1800.xsd', force_download=True): - return 'skip' + pytest.skip() if not gdaltest.download_file('https://pds.nasa.gov/pds4/disp/v1/PDS4_DISP_1800.xsd', 'pds.nasa.gov_pds4_disp_v1_PDS4_DISP_1800.xsd', force_download=True): - return 'skip' + pytest.skip() if not gdaltest.download_file('https://pds.nasa.gov/pds4/pds/v1/PDS4_PDS_1700.xsd', 'pds.nasa.gov_pds4_pds_v1_PDS4_PDS_1700.xsd', force_download=True): - return 'skip' + pytest.skip() if not gdaltest.download_file('https://pds.nasa.gov/pds4/cart/v1/PDS4_CART_1700.xsd', 'pds.nasa.gov_pds4_cart_v1_PDS4_CART_1700.xsd', force_download=True): - return 'skip' + pytest.skip() ds = gdal.OpenEx('GMLAS:' + filename, open_options=[ 'VALIDATE=YES', 'FAIL_IF_VALIDATION_ERROR=YES', 'CONFIG_FILE=<Configuration><AllowRemoteSchemaDownload>false</AllowRemoteSchemaDownload><SchemaCache><Directory>tmp/cache</Directory></SchemaCache></Configuration>']) - if ds is None: - return 'fail' - return 'success' + assert ds is not None ############################################################################### # Perform simple read test on PDS4 dataset. -def pds4_1(): +def test_pds4_1(): srs = """PROJCS["Transverse Mercator Earth", GEOGCS["GCS_Earth", DATUM["D_North_American_Datum_1927", @@ -122,7 +119,7 @@ def hide_substitution_warnings_error_handler(): # Test CreateCopy() with defaults -def pds4_2(): +def test_pds4_2(): tst = gdaltest.GDALTest('PDS4', 'rgbsmall.tif', 2, 21053) with hide_substitution_warnings_error_handler(): @@ -133,7 +130,7 @@ def pds4_2(): # Test CreateCopy() with explicit INTERLEAVE=BSQ -def pds4_3(): +def test_pds4_3(): tst = gdaltest.GDALTest('PDS4', 'rgbsmall.tif', 2, 21053, options=['INTERLEAVE=BSQ']) with hide_substitution_warnings_error_handler(): @@ -144,7 +141,7 @@ def pds4_3(): # Test CreateCopy() with explicit INTERLEAVE=BIP -def pds4_4(): +def test_pds4_4(): tst = gdaltest.GDALTest('PDS4', 'rgbsmall.tif', 2, 21053, options=['INTERLEAVE=BIP']) with hide_substitution_warnings_error_handler(): @@ -155,7 +152,7 @@ def pds4_4(): # Test CreateCopy() with explicit INTERLEAVE=BIL -def pds4_5(): +def test_pds4_5(): tst = gdaltest.GDALTest('PDS4', 'rgbsmall.tif', 2, 21053, options=['INTERLEAVE=BIL']) with hide_substitution_warnings_error_handler(): @@ -166,7 +163,7 @@ def pds4_5(): # Test CreateCopy() with explicit INTERLEAVE=BSQ and IMAGE_FORMAT=GEOTIFF -def pds4_6(): +def test_pds4_6(): tst = gdaltest.GDALTest('PDS4', 'rgbsmall.tif', 2, 21053, options=['INTERLEAVE=BSQ', 'IMAGE_FORMAT=GEOTIFF']) with hide_substitution_warnings_error_handler(): @@ -177,7 +174,7 @@ def pds4_6(): # Test CreateCopy() with explicit INTERLEAVE=BIP and IMAGE_FORMAT=GEOTIFF -def pds4_7(): +def test_pds4_7(): tst = gdaltest.GDALTest('PDS4', 'rgbsmall.tif', 2, 21053, options=['INTERLEAVE=BIP', 'IMAGE_FORMAT=GEOTIFF']) with hide_substitution_warnings_error_handler(): @@ -188,7 +185,7 @@ def pds4_7(): # Test SRS support -def pds4_8(): +def test_pds4_8(): filename = '/vsimem/out.xml' for proj4 in ['+proj=eqc +lat_ts=43.75 +lat_0=10 +lon_0=-112.5 +x_0=0 +y_0=0 +a=2439400 +b=2439400 +units=m +no_defs', @@ -210,21 +207,14 @@ def pds4_8(): ds = None ret = validate_xml(filename) - if ret == 'fail': - gdaltest.post_reason('validation of file for %s failed' % proj4) - return 'fail' + assert ret != 'fail', ('validation of file for %s failed' % proj4) ds = gdal.Open(filename) wkt = ds.GetProjectionRef() sr = osr.SpatialReference() sr.SetFromUserInput(wkt) got_proj4 = sr.ExportToProj4().strip() - if got_proj4 != proj4: - gdaltest.post_reason('got %s, expected %s' % (got_proj4, proj4)) - print('') - print(got_proj4) - print(proj4) - return 'fail' + assert got_proj4 == proj4, '' # longlat doesn't roundtrip as such ds = gdal.GetDriverByName('PDS4').Create(filename, 1, 1) @@ -240,43 +230,26 @@ def pds4_8(): sr.SetFromUserInput(wkt) got_proj4 = sr.ExportToProj4().strip() proj4 = '+proj=eqc +lat_ts=0 +lat_0=0 +lon_0=0 +x_0=0 +y_0=0 +a=2439400 +b=2439400 +units=m +no_defs' - if got_proj4 != proj4: - gdaltest.post_reason('got %s, expected %s' % (got_proj4, proj4)) - print('') - print(got_proj4) - print(proj4) - return 'fail' + assert got_proj4 == proj4, '' got_gt = ds.GetGeoTransform() expected_gt = (85151.12354629935, 42575.561773149675, 0.0, 2086202.5268843342, 0.0, -85151.12354629935) - if max([abs(got_gt[i] - expected_gt[i]) for i in range(6)]) > 1: - gdaltest.post_reason('fail') - print('') - print(got_gt) - print(expected_gt) - return 'fail' + assert max([abs(got_gt[i] - expected_gt[i]) for i in range(6)]) <= 1, '' ds = None gdal.GetDriverByName('PDS4').Delete(filename) - return 'success' ############################################################################### # Test nodata / mask -def pds4_9(): +def test_pds4_9(): ds = gdal.Open('data/byte_pds4.xml') ndv = ds.GetRasterBand(1).GetNoDataValue() - if ndv != 74: - gdaltest.post_reason('fail') - print(ndv) - return 'fail' + assert ndv == 74 cs = ds.GetRasterBand(1).GetMaskBand().Checksum() - if cs != 4800: - gdaltest.post_reason('fail') - print(cs) - return 'fail' + assert cs == 4800 ds = None filename = '/vsimem/out.xml' @@ -285,22 +258,14 @@ def pds4_9(): gdal.Translate(filename, 'data/byte_pds4.xml', format='PDS4') ret = validate_xml(filename) - if ret == 'fail': - gdaltest.post_reason('validation failed') - return 'fail' + assert ret != 'fail', 'validation failed' ds = gdal.Open(filename) ndv = ds.GetRasterBand(1).GetNoDataValue() - if ndv != 74: - gdaltest.post_reason('fail') - print(ndv) - return 'fail' + assert ndv == 74 cs = ds.GetRasterBand(1).GetMaskBand().Checksum() - if cs != 4800: - gdaltest.post_reason('fail') - print(cs) - return 'fail' + assert cs == 4800 ds = None @@ -313,28 +278,17 @@ def pds4_9(): creationOptions=['IMAGE_FORMAT=' + frmt]) ret = validate_xml(filename) - if ret == 'fail': - gdaltest.post_reason('validation failed') - return 'fail' + assert ret != 'fail', 'validation failed' ds = gdal.Open(filename) ndv = ds.GetRasterBand(1).GetNoDataValue() - if ndv != 75: - gdaltest.post_reason('fail') - print(ndv) - return 'fail' + assert ndv == 75 flag = ds.GetRasterBand(1).GetMaskFlags() - if flag != 0: - gdaltest.post_reason('fail') - print(flag) - return 'fail' + assert flag == 0 cs = ds.GetRasterBand(1).GetMaskBand().Checksum() - if cs != 4833: - gdaltest.post_reason('fail') - print(cs) - return 'fail' + assert cs == 4833 ds = None @@ -346,17 +300,11 @@ def pds4_9(): 'IMAGE_FORMAT=' + frmt]) ret = validate_xml(filename) - if ret == 'fail': - gdaltest.post_reason('validation failed') - return 'fail' + assert ret != 'fail', 'validation failed' ds = gdal.Open(filename) ndv = ds.GetRasterBand(1).GetNoDataValue() - if ndv != 74: - gdaltest.post_reason('fail') - print(frmt) - print(ndv) - return 'fail' + assert ndv == 74, frmt ds = None @@ -369,11 +317,7 @@ def pds4_9(): ds = gdal.Open(filename) cs = ds.GetRasterBand(1).Checksum() - if cs != 1: - gdaltest.post_reason('fail') - print(frmt) - print(cs) - return 'fail' + assert cs == 1, frmt ds = None # Test setting nodata and then explicit Fill() @@ -386,11 +330,7 @@ def pds4_9(): ds = gdal.Open(filename) cs = ds.GetRasterBand(1).Checksum() - if cs != 1: - gdaltest.post_reason('fail') - print(frmt) - print(cs) - return 'fail' + assert cs == 1, frmt ds = None template = '/vsimem/template.xml' @@ -449,16 +389,11 @@ def pds4_9(): ds = gdal.Open(filename) ndv = ds.GetRasterBand(1).GetNoDataValue() - if ndv != 10: - gdaltest.post_reason('fail') - print(ndv) - return 'fail' + assert ndv == 10 ds = None ret = validate_xml(filename) - if ret == 'fail': - gdaltest.post_reason('validation failed') - return 'fail' + assert ret != 'fail', 'validation failed' # Special_Constants with just saturated_constant gdal.FileFromMemBuffer(template, """ @@ -516,27 +451,20 @@ def pds4_9(): ds = gdal.Open(filename) ndv = ds.GetRasterBand(1).GetNoDataValue() - if ndv != 10: - gdaltest.post_reason('fail') - print(ndv) - return 'fail' + assert ndv == 10 ds = None ret = validate_xml(filename) - if ret == 'fail': - gdaltest.post_reason('validation failed') - return 'fail' + assert ret != 'fail', 'validation failed' gdal.GetDriverByName('PDS4').Delete(filename) gdal.Unlink(template) - return 'success' - ############################################################################### # Test scale / offset -def pds4_10(): +def test_pds4_10(): filename = '/vsimem/out.xml' filename2 = '/vsimem/out2.xml' @@ -551,27 +479,20 @@ def pds4_10(): ds = gdal.Open(filename2) scale = ds.GetRasterBand(1).GetScale() - if scale != 2: - gdaltest.post_reason('fail') - print(scale) - return 'fail' + assert scale == 2 offset = ds.GetRasterBand(1).GetOffset() - if offset != 3: - gdaltest.post_reason('fail') - print(offset) - return 'fail' + assert offset == 3 ds = None gdal.GetDriverByName('PDS4').Delete(filename) gdal.GetDriverByName('PDS4').Delete(filename2) - return 'success' - + ############################################################################### # Test various data types -def pds4_11(): +def test_pds4_11(): filename = '/vsimem/out.xml' for (dt, data) in [(gdal.GDT_Byte, struct.pack('B', 255)), @@ -590,33 +511,20 @@ def pds4_11(): with gdaltest.config_option('PDS4_FORCE_MASK', 'YES'): ds = gdal.Open(filename) - if ds.GetRasterBand(1).DataType != dt: - gdaltest.post_reason('fail') - print(ds.GetRasterBand(1).DataType) - print(dt) - return 'fail' + assert ds.GetRasterBand(1).DataType == dt got_data = ds.GetRasterBand(1).ReadRaster(0, 0, 1, 1) - if got_data != data: - gdaltest.post_reason('fail') - print(dt) - return 'fail' + assert got_data == data, dt cs = ds.GetRasterBand(1).GetMaskBand().Checksum() - if cs != 3: - gdaltest.post_reason('fail') - print(dt) - print(cs) - return 'fail' + assert cs == 3, dt ds = None gdal.GetDriverByName('PDS4').Delete(filename) - return 'success' - ############################################################################### # Test various creation options -def pds4_12(): +def test_pds4_12(): filename = '/vsimem/out.xml' ds = gdal.GetDriverByName('PDS4').Create(filename, 1, 1, @@ -641,48 +549,22 @@ def pds4_12(): if f: data = gdal.VSIFReadL(1, 10000, f).decode('ascii') gdal.VSIFCloseL(f) - if data.find('<logical_identifier>logical_identifier</logical_identifier>') < 0: - gdaltest.post_reason('fail') - print(data) - return 'fail' - if data.find('<cart:west_bounding_coordinate unit="deg">1</cart:west_bounding_coordinate>') < 0: - gdaltest.post_reason('fail') - print(data) - return 'fail' - if data.find('<cart:east_bounding_coordinate unit="deg">3</cart:east_bounding_coordinate>') < 0: - gdaltest.post_reason('fail') - print(data) - return 'fail' - if data.find('<cart:north_bounding_coordinate unit="deg">4</cart:north_bounding_coordinate>') < 0: - gdaltest.post_reason('fail') - print(data) - return 'fail' - if data.find('<cart:south_bounding_coordinate unit="deg">2</cart:south_bounding_coordinate>') < 0: - gdaltest.post_reason('fail') - print(data) - return 'fail' - if data.find('<cart:latitude_type>planetographic</cart:latitude_type>') < 0: - gdaltest.post_reason('fail') - print(data) - return 'fail' - if data.find('<cart:longitude_direction>Positive West</cart:longitude_direction>') < 0: - gdaltest.post_reason('fail') - print(data) - return 'fail' - if data.find('<file_name>myimage.raw</file_name>') < 0: - gdaltest.post_reason('fail') - print(data) - return 'fail' + assert data.find('<logical_identifier>logical_identifier</logical_identifier>') >= 0 + assert data.find('<cart:west_bounding_coordinate unit="deg">1</cart:west_bounding_coordinate>') >= 0 + assert data.find('<cart:east_bounding_coordinate unit="deg">3</cart:east_bounding_coordinate>') >= 0 + assert data.find('<cart:north_bounding_coordinate unit="deg">4</cart:north_bounding_coordinate>') >= 0 + assert data.find('<cart:south_bounding_coordinate unit="deg">2</cart:south_bounding_coordinate>') >= 0 + assert data.find('<cart:latitude_type>planetographic</cart:latitude_type>') >= 0 + assert data.find('<cart:longitude_direction>Positive West</cart:longitude_direction>') >= 0 + assert data.find('<file_name>myimage.raw</file_name>') >= 0 gdal.GetDriverByName('PDS4').Delete(filename) - return 'success' - ############################################################################### # Test subdatasets -def pds4_13(): +def test_pds4_13(): ds = gdal.Open('data/byte_pds4_multi_sds.xml') subds = ds.GetSubDatasets() @@ -692,85 +574,57 @@ def pds4_13(): 'Image file byte_pds4.img, array second_sds'), ('PDS4:data/byte_pds4_multi_sds.xml:2:1', 'Image file byte_pds4.img, array third_sds')] - if subds != expected_subds: - gdaltest.post_reason('fail') - print(subds) - return 'fail' + assert subds == expected_subds ds = gdal.Open('PDS4:data/byte_pds4_multi_sds.xml:1:1') cs = ds.GetRasterBand(1).Checksum() - if cs != 2315: - gdaltest.post_reason('fail') - print(cs) - return 'fail' + assert cs == 2315 ds = gdal.Open('PDS4:data/byte_pds4_multi_sds.xml:1:2') cs = ds.GetRasterBand(1).Checksum() - if cs != 2302: - gdaltest.post_reason('fail') - print(cs) - return 'fail' + assert cs == 2302 ds = gdal.Open('PDS4:data/byte_pds4_multi_sds.xml:2:1') cs = ds.GetRasterBand(1).Checksum() - if cs != 3496: - gdaltest.post_reason('fail') - print(cs) - return 'fail' + assert cs == 3496 ds = gdal.Open(os.path.join(os.getcwd(), 'data', 'byte_pds4_multi_sds.xml')) subds_name = ds.GetSubDatasets()[0][0] ds = gdal.Open(subds_name) - if ds is None: - gdaltest.post_reason('fail') - return 'fail' + assert ds is not None with gdaltest.error_handler(): ds = gdal.Open('PDS4:c:\do_not\exist.xml:1:1') - if ds is not None: - gdaltest.post_reason('fail') - return 'fail' + assert ds is None with gdaltest.error_handler(): ds = gdal.Open('PDS4:i_do_not_exist.xml') - if ds is not None: - gdaltest.post_reason('fail') - return 'fail' + assert ds is None with gdaltest.error_handler(): ds = gdal.Open('PDS4:i_do_not_exist.xml:1:1') - if ds is not None: - gdaltest.post_reason('fail') - return 'fail' + assert ds is None with gdaltest.error_handler(): ds = gdal.Open('PDS4:data/byte_pds4_multi_sds.xml:3:1') - if ds is not None: - gdaltest.post_reason('fail') - return 'fail' + assert ds is None with gdaltest.error_handler(): ds = gdal.Open('PDS4:data/byte_pds4_multi_sds.xml:1:3') - if ds is not None: - gdaltest.post_reason('fail') - return 'fail' - - return 'success' + assert ds is None ############################################################################### # Test error cases -def pds4_14(): +def test_pds4_14(): filename = '/vsimem/test.xml' gdal.FileFromMemBuffer(filename, "Product_Observational http://pds.nasa.gov/pds4/pds/v1") with gdaltest.error_handler(): ds = gdal.Open(filename) - if ds is not None: - gdaltest.post_reason('fail') - return 'fail' + assert ds is None gdal.FileFromMemBuffer(filename, """ <Product_Observational xmlns="http://pds.nasa.gov/pds4/pds/v1"> @@ -842,9 +696,7 @@ def pds4_14(): </Product_Observational>""") with gdaltest.error_handler(): ds = gdal.Open(filename) - if ds is not None: - gdaltest.post_reason('fail') - return 'fail' + assert ds is None gdal.FileFromMemBuffer(filename, """ <Product_Observational xmlns="http://pds.nasa.gov/pds4/pds/v1"> @@ -878,9 +730,7 @@ def pds4_14(): </Product_Observational>""") with gdaltest.error_handler(): ds = gdal.Open(filename) - if ds is not None: - gdaltest.post_reason('fail') - return 'fail' + assert ds is None gdal.FileFromMemBuffer(filename, """ <Product_Observational xmlns="http://pds.nasa.gov/pds4/pds/v1"> @@ -909,9 +759,7 @@ def pds4_14(): </Product_Observational>""") with gdaltest.error_handler(): ds = gdal.Open(filename) - if ds is not None: - gdaltest.post_reason('fail') - return 'fail' + assert ds is None gdal.FileFromMemBuffer(filename, """ <Product_Observational xmlns="http://pds.nasa.gov/pds4/pds/v1"> @@ -940,9 +788,7 @@ def pds4_14(): </Product_Observational>""") with gdaltest.error_handler(): ds = gdal.Open(filename) - if ds is not None: - gdaltest.post_reason('fail') - return 'fail' + assert ds is None gdal.FileFromMemBuffer(filename, """ <Product_Observational xmlns="http://pds.nasa.gov/pds4/pds/v1"> @@ -971,9 +817,7 @@ def pds4_14(): </Product_Observational>""") with gdaltest.error_handler(): ds = gdal.Open(filename) - if ds is not None: - gdaltest.post_reason('fail') - return 'fail' + assert ds is None gdal.Unlink(filename) @@ -981,35 +825,27 @@ def pds4_14(): with gdaltest.error_handler(): ds = gdal.GetDriverByName('PDS4').Create('/vsimem/out.xml', 1, 1, options=['INTERLEAVE=INVALID']) - if ds is not None: - gdaltest.post_reason('fail') - return 'fail' + assert ds is None # INTERLEAVE=BIL not supported for GeoTIFF in PDS4 with gdaltest.error_handler(): ds = gdal.GetDriverByName('PDS4').Create('/vsimem/out.xml', 1, 1, options=['INTERLEAVE=BIL', 'IMAGE_FORMAT=GEOTIFF']) - if ds is not None: - gdaltest.post_reason('fail') - return 'fail' + assert ds is None # Cannot create GeoTIFF file with gdaltest.error_handler(): ds = gdal.GetDriverByName('PDS4').Create('/i/do_not/exist.xml', 1, 1, options=['IMAGE_FORMAT=GEOTIFF']) - if ds is not None: - gdaltest.post_reason('fail') - return 'fail' + assert ds is None gdal.Translate('/vsimem/test.tif', 'data/byte.tif') # Output file has same name as input file with gdaltest.error_handler(): ds = gdal.Translate('/vsimem/test.xml', '/vsimem/test.tif', format='PDS4', creationOptions=['IMAGE_FORMAT=GEOTIFF']) - if ds is not None: - gdaltest.post_reason('fail') - return 'fail' + assert ds is None gdal.Unlink('/vsimem/test.tif') template = '/vsimem/template.xml' @@ -1021,10 +857,7 @@ def pds4_14(): gdal.ErrorReset() with gdaltest.error_handler(): ds = None - if gdal.GetLastErrorMsg() != 'Cannot find Product_Observational element in template': - gdaltest.post_reason('fail') - print(gdal.GetLastErrorMsg()) - return 'fail' + assert gdal.GetLastErrorMsg() == 'Cannot find Product_Observational element in template' # Missing Target_Identification gdal.FileFromMemBuffer(template, """ @@ -1041,10 +874,7 @@ def pds4_14(): gdal.ErrorReset() with gdaltest.error_handler(): ds = None - if gdal.GetLastErrorMsg() != 'Cannot find Target_Identification element in template': - gdaltest.post_reason('fail') - print(gdal.GetLastErrorMsg()) - return 'fail' + assert gdal.GetLastErrorMsg() == 'Cannot find Target_Identification element in template' # Missing Observation_Area gdal.FileFromMemBuffer(template, """ @@ -1057,10 +887,7 @@ def pds4_14(): gdal.ErrorReset() with gdaltest.error_handler(): ds = None - if gdal.GetLastErrorMsg() != 'Cannot find Observation_Area in template': - gdaltest.post_reason('fail') - print(gdal.GetLastErrorMsg()) - return 'fail' + assert gdal.GetLastErrorMsg() == 'Cannot find Observation_Area in template' # Unexpected content found after Observation_Area in template gdal.FileFromMemBuffer(template, """ @@ -1076,22 +903,17 @@ def pds4_14(): gdal.ErrorReset() with gdaltest.error_handler(): ds = None - if gdal.GetLastErrorMsg() != 'Unexpected content found after Observation_Area in template': - gdaltest.post_reason('fail') - print(gdal.GetLastErrorMsg()) - return 'fail' + assert gdal.GetLastErrorMsg() == 'Unexpected content found after Observation_Area in template' gdal.Unlink(template) gdal.Unlink(filename) gdal.Unlink('/vsimem/test.img') - return 'success' - ############################################################################### # Test Create() without geospatial info but from a geospatial enabled template -def pds4_15(): +def test_pds4_15(): filename = '/vsimem/out.xml' with hide_substitution_warnings_error_handler(): @@ -1099,28 +921,21 @@ def pds4_15(): options=['TEMPLATE=data/byte_pds4.xml']) ret = validate_xml(filename) - if ret == 'fail': - gdaltest.post_reason('validation failed') - return 'fail' + assert ret != 'fail', 'validation failed' f = gdal.VSIFOpenL(filename, 'rb') if f: data = gdal.VSIFReadL(1, 10000, f).decode('ascii') gdal.VSIFCloseL(f) - if data.find('<cart:Cartography>') >= 0: - gdaltest.post_reason('fail') - print(data) - return 'fail' + assert data.find('<cart:Cartography>') < 0 gdal.GetDriverByName('PDS4').Delete(filename) - return 'success' - ############################################################################### # Test Create() with geospatial info but from a template without Discipline_Area -def pds4_16(): +def test_pds4_16(): template = '/vsimem/template.xml' filename = '/vsimem/out.xml' @@ -1178,37 +993,24 @@ def pds4_16(): ds = None ret = validate_xml(filename) - if ret == 'fail': - gdaltest.post_reason('validation failed') - return 'fail' + assert ret != 'fail', 'validation failed' f = gdal.VSIFOpenL(filename, 'rb') if f: data = gdal.VSIFReadL(1, 10000, f).decode('ascii') gdal.VSIFCloseL(f) - if data.find('http://pds.nasa.gov/pds4/pds/v1 https://pds.nasa.gov/pds4/pds/v1/PDS4_PDS_1800.xsd http://pds.nasa.gov/pds4/cart/v1 https://pds.nasa.gov/pds4/cart/v1/PDS4_CART_1700.xsd"') < 0: - gdaltest.post_reason('fail') - print(data) - return 'fail' - if data.find('xmlns:cart="http://pds.nasa.gov/pds4/cart/v1"') < 0: - gdaltest.post_reason('fail') - print(data) - return 'fail' - if data.find('<cart:Cartography>') < 0: - gdaltest.post_reason('fail') - print(data) - return 'fail' + assert data.find('http://pds.nasa.gov/pds4/pds/v1 https://pds.nasa.gov/pds4/pds/v1/PDS4_PDS_1800.xsd http://pds.nasa.gov/pds4/cart/v1 https://pds.nasa.gov/pds4/cart/v1/PDS4_CART_1700.xsd"') >= 0 + assert data.find('xmlns:cart="http://pds.nasa.gov/pds4/cart/v1"') >= 0 + assert data.find('<cart:Cartography>') >= 0 gdal.GetDriverByName('PDS4').Delete(filename) gdal.Unlink(template) - return 'success' - ############################################################################### # Test ARRAY_TYPE creation option -def pds4_17(): +def test_pds4_17(): filename = '/vsimem/out.xml' @@ -1216,57 +1018,43 @@ def pds4_17(): gdal.GetDriverByName('PDS4').Create(filename, 1, 1, 1, options=['ARRAY_TYPE=Array_2D']) ret = validate_xml(filename) - if ret == 'fail': - gdaltest.post_reason('validation failed') - return 'fail' + assert ret != 'fail', 'validation failed' f = gdal.VSIFOpenL(filename, 'rb') if f: data = gdal.VSIFReadL(1, 10000, f).decode('ascii') gdal.VSIFCloseL(f) - if data.find('<Array_2D>') < 0 or data.find('<axes>2</axes>') < 0 or \ - data.find('<axis_name>Band</axis_name>') >= 0 or \ - data.find('<sequence_number>3</sequence_number>') >= 0: - gdaltest.post_reason('fail') - print(data) - return 'fail' + assert (data.find('<Array_2D>') >= 0 and data.find('<axes>2</axes>') >= 0 and \ + data.find('<axis_name>Band</axis_name>') < 0 and \ + data.find('<sequence_number>3</sequence_number>') < 0) gdal.GetDriverByName('PDS4').Delete(filename) # Test multi-band creation with Array_2D with gdaltest.error_handler(): ds = gdal.GetDriverByName('PDS4').Create(filename, 1, 1, 2, options=['ARRAY_TYPE=Array_2D']) - if ds is not None: - gdaltest.post_reason('expected failure') - return 'fail' + assert ds is None, 'expected failure' # Test multi-band creation with Array_3D_Spectrum with gdaltest.error_handler(): gdal.GetDriverByName('PDS4').Create(filename, 1, 1, 2, options=['ARRAY_TYPE=Array_3D_Spectrum']) ret = validate_xml(filename) - if ret == 'fail': - gdaltest.post_reason('validation failed') - return 'fail' + assert ret != 'fail', 'validation failed' f = gdal.VSIFOpenL(filename, 'rb') if f: data = gdal.VSIFReadL(1, 10000, f).decode('ascii') gdal.VSIFCloseL(f) - if data.find('<Array_3D_Spectrum>') < 0 or data.find('<axes>3</axes>') < 0: - gdaltest.post_reason('fail') - print(data) - return 'fail' + assert data.find('<Array_3D_Spectrum>') >= 0 and data.find('<axes>3</axes>') >= 0 gdal.GetDriverByName('PDS4').Delete(filename) - return 'success' - ############################################################################### # Test RADII creation option -def pds4_18(): +def test_pds4_18(): filename = '/vsimem/out.xml' @@ -1282,42 +1070,11 @@ def pds4_18(): if f: data = gdal.VSIFReadL(1, 10000, f).decode('ascii') gdal.VSIFCloseL(f) - if data.find('<cart:semi_major_radius unit="m">1</cart:semi_major_radius>') < 0 or \ - data.find('<cart:semi_minor_radius unit="m">1</cart:semi_minor_radius>') < 0 or \ - data.find('<cart:polar_radius unit="m">2</cart:polar_radius>') < 0: - gdaltest.post_reason('fail') - print(data) - return 'fail' + assert (data.find('<cart:semi_major_radius unit="m">1</cart:semi_major_radius>') >= 0 and \ + data.find('<cart:semi_minor_radius unit="m">1</cart:semi_minor_radius>') >= 0 and \ + data.find('<cart:polar_radius unit="m">2</cart:polar_radius>') >= 0) gdal.GetDriverByName('PDS4').Delete(filename) - return 'success' - - -gdaltest_list = [ - pds4_1, - pds4_2, - pds4_3, - pds4_4, - pds4_5, - pds4_6, - pds4_7, - pds4_8, - pds4_9, - pds4_10, - pds4_11, - pds4_12, - pds4_13, - pds4_14, - pds4_15, - pds4_16, - pds4_17, - pds4_18] - -if __name__ == '__main__': - - gdaltest.setup_run('pds4') - gdaltest.run_tests(gdaltest_list) - sys.exit(gdaltest.summarize()) diff --git a/autotest/gdrivers/plmosaic.py b/autotest/gdrivers/plmosaic.py index c9f5c28a35b9..7c859ae35b25 100755 --- a/autotest/gdrivers/plmosaic.py +++ b/autotest/gdrivers/plmosaic.py @@ -30,76 +30,67 @@ ############################################################################### import os -import sys import shutil import struct -sys.path.append('../pymod') from osgeo import gdal import gdaltest +import pytest ############################################################################### # Find PLMosaic driver -def plmosaic_1(): +def test_plmosaic_1(): gdaltest.plmosaic_drv = gdal.GetDriverByName('PLMosaic') if gdaltest.plmosaic_drv is not None: - return 'success' - return 'skip' + return + pytest.skip() ############################################################################### # Error: no API_KEY -def plmosaic_2(): +def test_plmosaic_2(): if gdaltest.plmosaic_drv is None: - return 'skip' + pytest.skip() gdal.PushErrorHandler() gdal.SetConfigOption('PL_URL', '/vsimem/root') ds = gdal.OpenEx('PLMosaic:', gdal.OF_RASTER) gdal.SetConfigOption('PL_URL', None) gdal.PopErrorHandler() - if ds is not None: - gdaltest.post_reason('fail') - return 'fail' - - return 'success' + assert ds is None ############################################################################### # Error case: invalid root URL -def plmosaic_3(): +def test_plmosaic_3(): if gdaltest.plmosaic_drv is None: - return 'skip' + pytest.skip() gdal.PushErrorHandler() gdal.SetConfigOption('PL_URL', '/vsimem/does_not_exist/') ds = gdal.OpenEx('PLMosaic:', gdal.OF_RASTER, open_options=['API_KEY=foo']) gdal.SetConfigOption('PL_URL', None) gdal.PopErrorHandler() - if ds is not None: - gdaltest.post_reason('fail') - return 'fail' - - return 'success' + assert ds is None ############################################################################### # Error case: invalid JSON -def plmosaic_4(): +def test_plmosaic_4(): if gdaltest.plmosaic_drv is None: - return 'skip' + pytest.skip() gdal.FileFromMemBuffer('/vsimem/root', """{""") @@ -108,20 +99,16 @@ def plmosaic_4(): ds = gdal.OpenEx('PLMosaic:', gdal.OF_RASTER, open_options=['API_KEY=foo']) gdal.SetConfigOption('PL_URL', None) gdal.PopErrorHandler() - if ds is not None: - gdaltest.post_reason('fail') - return 'fail' - - return 'success' + assert ds is None ############################################################################### # Error case: not a JSON dictionary -def plmosaic_5(): +def test_plmosaic_5(): if gdaltest.plmosaic_drv is None: - return 'skip' + pytest.skip() gdal.FileFromMemBuffer('/vsimem/root', """null""") @@ -130,20 +117,16 @@ def plmosaic_5(): ds = gdal.OpenEx('PLMosaic:', gdal.OF_RASTER, open_options=['API_KEY=foo']) gdal.SetConfigOption('PL_URL', None) gdal.PopErrorHandler() - if ds is not None: - gdaltest.post_reason('fail') - return 'fail' - - return 'success' + assert ds is None ############################################################################### # Error case: missing "mosaics" element -def plmosaic_6(): +def test_plmosaic_6(): if gdaltest.plmosaic_drv is None: - return 'skip' + pytest.skip() gdal.FileFromMemBuffer('/vsimem/root', """{}""") @@ -152,20 +135,16 @@ def plmosaic_6(): ds = gdal.OpenEx('PLMosaic:', gdal.OF_RASTER, open_options=['API_KEY=foo']) gdal.SetConfigOption('PL_URL', None) gdal.PopErrorHandler() - if ds is not None: - gdaltest.post_reason('fail') - return 'fail' - - return 'success' + assert ds is None ############################################################################### # Valid root but no mosaics -def plmosaic_7(): +def test_plmosaic_7(): if gdaltest.plmosaic_drv is None: - return 'skip' + pytest.skip() gdal.FileFromMemBuffer('/vsimem/root', """{ "mosaics": [], @@ -174,21 +153,17 @@ def plmosaic_7(): gdal.SetConfigOption('PL_URL', '/vsimem/root') ds = gdal.OpenEx('PLMosaic:', gdal.OF_RASTER, open_options=['API_KEY=foo']) gdal.SetConfigOption('PL_URL', None) - if ds is not None: - gdaltest.post_reason('fail') - return 'fail' + assert ds is None ds = None - return 'success' - ############################################################################### # Valid root with 2 mosaics -def plmosaic_8(): +def test_plmosaic_8(): if gdaltest.plmosaic_drv is None: - return 'skip' + pytest.skip() gdal.FileFromMemBuffer('/vsimem/root', """{ "_links" : { "_next": "/vsimem/root/?page=2" }, @@ -231,43 +206,33 @@ def plmosaic_8(): gdal.SetConfigOption('PL_URL', '/vsimem/root') ds = gdal.OpenEx('PLMosaic:', gdal.OF_RASTER, open_options=['API_KEY=foo']) gdal.SetConfigOption('PL_URL', None) - if ds.GetMetadata("SUBDATASETS") != {'SUBDATASET_2_NAME': 'PLMOSAIC:mosaic=another_mosaic_name', 'SUBDATASET_2_DESC': 'Mosaic another_mosaic_name', 'SUBDATASET_1_NAME': 'PLMOSAIC:mosaic=my_mosaic_name', 'SUBDATASET_1_DESC': 'Mosaic my_mosaic_name'}: - gdaltest.post_reason('fail') - print(ds.GetMetadata("SUBDATASETS")) - return 'fail' + assert ds.GetMetadata("SUBDATASETS") == {'SUBDATASET_2_NAME': 'PLMOSAIC:mosaic=another_mosaic_name', 'SUBDATASET_2_DESC': 'Mosaic another_mosaic_name', 'SUBDATASET_1_NAME': 'PLMOSAIC:mosaic=my_mosaic_name', 'SUBDATASET_1_DESC': 'Mosaic my_mosaic_name'} ds = None - return 'success' - ############################################################################### # Error case: invalid mosaic -def plmosaic_9(): +def test_plmosaic_9(): if gdaltest.plmosaic_drv is None: - return 'skip' + pytest.skip() gdal.PushErrorHandler() gdal.SetConfigOption('PL_URL', '/vsimem/root') ds = gdal.OpenEx('PLMosaic:', gdal.OF_RASTER, open_options=['API_KEY=foo', 'MOSAIC=does_not_exist']) gdal.SetConfigOption('PL_URL', None) gdal.PopErrorHandler() - if ds is not None or gdal.GetLastErrorMsg().find('/vsimem/root/?name__is=does_not_exist') < 0: - gdaltest.post_reason('fail') - print(gdal.GetLastErrorMsg()) - return 'fail' - - return 'success' + assert ds is None and gdal.GetLastErrorMsg().find('/vsimem/root/?name__is=does_not_exist') >= 0 ############################################################################### # Invalid mosaic definition: invalid JSON -def plmosaic_9bis(): +def test_plmosaic_9bis(): if gdaltest.plmosaic_drv is None: - return 'skip' + pytest.skip() gdal.FileFromMemBuffer('/vsimem/root/?name__is=my_mosaic', """{""") gdal.SetConfigOption('PL_URL', '/vsimem/root') @@ -275,21 +240,16 @@ def plmosaic_9bis(): ds = gdal.OpenEx('PLMosaic:', gdal.OF_RASTER, open_options=['API_KEY=foo', 'MOSAIC=my_mosaic']) gdal.PopErrorHandler() gdal.SetConfigOption('PL_URL', None) - if ds is not None or gdal.GetLastErrorMsg().find('JSON parsing error') < 0: - gdaltest.post_reason('fail') - print(gdal.GetLastErrorMsg()) - return 'fail' - - return 'success' + assert ds is None and gdal.GetLastErrorMsg().find('JSON parsing error') >= 0 ############################################################################### # Invalid mosaic definition: JSON without mosaics array -def plmosaic_9ter(): +def test_plmosaic_9ter(): if gdaltest.plmosaic_drv is None: - return 'skip' + pytest.skip() gdal.FileFromMemBuffer('/vsimem/root/?name__is=my_mosaic', """{}""") gdal.SetConfigOption('PL_URL', '/vsimem/root') @@ -297,21 +257,16 @@ def plmosaic_9ter(): ds = gdal.OpenEx('PLMosaic:', gdal.OF_RASTER, open_options=['API_KEY=foo', 'MOSAIC=my_mosaic']) gdal.PopErrorHandler() gdal.SetConfigOption('PL_URL', None) - if ds is not None or gdal.GetLastErrorMsg().find('No mosaic my_mosaic') < 0: - gdaltest.post_reason('fail') - print(gdal.GetLastErrorMsg()) - return 'fail' - - return 'success' + assert ds is None and gdal.GetLastErrorMsg().find('No mosaic my_mosaic') >= 0 ############################################################################### # Invalid mosaic definition: missing parameters -def plmosaic_10(): +def test_plmosaic_10(): if gdaltest.plmosaic_drv is None: - return 'skip' + pytest.skip() gdal.FileFromMemBuffer('/vsimem/root/?name__is=my_mosaic', """{ "mosaics": [{ @@ -324,21 +279,16 @@ def plmosaic_10(): ds = gdal.OpenEx('PLMosaic:', gdal.OF_RASTER, open_options=['API_KEY=foo', 'MOSAIC=my_mosaic']) gdal.PopErrorHandler() gdal.SetConfigOption('PL_URL', None) - if ds is not None or gdal.GetLastErrorMsg().find('Missing required parameter') < 0: - gdaltest.post_reason('fail') - print(gdal.GetLastErrorMsg()) - return 'fail' - - return 'success' + assert ds is None and gdal.GetLastErrorMsg().find('Missing required parameter') >= 0 ############################################################################### # Invalid mosaic definition: unsupported projection -def plmosaic_11(): +def test_plmosaic_11(): if gdaltest.plmosaic_drv is None: - return 'skip' + pytest.skip() gdal.FileFromMemBuffer('/vsimem/root/?name__is=my_mosaic', """{ "mosaics": [{ @@ -357,21 +307,16 @@ def plmosaic_11(): ds = gdal.OpenEx('PLMosaic:', gdal.OF_RASTER, open_options=['API_KEY=foo', 'MOSAIC=my_mosaic']) gdal.PopErrorHandler() gdal.SetConfigOption('PL_URL', None) - if ds is not None or gdal.GetLastErrorMsg().find('Unsupported coordinate_system') < 0: - gdaltest.post_reason('fail') - print(gdal.GetLastErrorMsg()) - return 'fail' - - return 'success' + assert ds is None and gdal.GetLastErrorMsg().find('Unsupported coordinate_system') >= 0 ############################################################################### # Invalid mosaic definition: unsupported datatype -def plmosaic_12(): +def test_plmosaic_12(): if gdaltest.plmosaic_drv is None: - return 'skip' + pytest.skip() gdal.FileFromMemBuffer('/vsimem/root/?name__is=my_mosaic', """{ "mosaics": [{ @@ -390,21 +335,16 @@ def plmosaic_12(): ds = gdal.OpenEx('PLMosaic:', gdal.OF_RASTER, open_options=['API_KEY=foo', 'MOSAIC=my_mosaic']) gdal.PopErrorHandler() gdal.SetConfigOption('PL_URL', None) - if ds is not None or gdal.GetLastErrorMsg().find('Unsupported data_type') < 0: - gdaltest.post_reason('fail') - print(gdal.GetLastErrorMsg()) - return 'fail' - - return 'success' + assert ds is None and gdal.GetLastErrorMsg().find('Unsupported data_type') >= 0 ############################################################################### # Invalid mosaic definition: unsupported resolution -def plmosaic_13(): +def test_plmosaic_13(): if gdaltest.plmosaic_drv is None: - return 'skip' + pytest.skip() gdal.FileFromMemBuffer('/vsimem/root/?name__is=my_mosaic', """{ "mosaics": [{ @@ -423,21 +363,16 @@ def plmosaic_13(): ds = gdal.OpenEx('PLMosaic:', gdal.OF_RASTER, open_options=['API_KEY=foo', 'MOSAIC=my_mosaic']) gdal.PopErrorHandler() gdal.SetConfigOption('PL_URL', None) - if ds is not None or gdal.GetLastErrorMsg().find('Unsupported resolution') < 0: - gdaltest.post_reason('fail') - print(gdal.GetLastErrorMsg()) - return 'fail' - - return 'success' + assert ds is None and gdal.GetLastErrorMsg().find('Unsupported resolution') >= 0 ############################################################################### # Invalid mosaic definition: unsupported quad_size -def plmosaic_14(): +def test_plmosaic_14(): if gdaltest.plmosaic_drv is None: - return 'skip' + pytest.skip() gdal.FileFromMemBuffer('/vsimem/root/?name__is=my_mosaic', """{ "mosaics": [{ @@ -456,21 +391,16 @@ def plmosaic_14(): ds = gdal.OpenEx('PLMosaic:', gdal.OF_RASTER, open_options=['API_KEY=foo', 'MOSAIC=my_mosaic']) gdal.PopErrorHandler() gdal.SetConfigOption('PL_URL', None) - if ds is not None or gdal.GetLastErrorMsg().find('Unsupported quad_size') < 0: - gdaltest.post_reason('fail') - print(gdal.GetLastErrorMsg()) - return 'fail' - - return 'success' + assert ds is None and gdal.GetLastErrorMsg().find('Unsupported quad_size') >= 0 ############################################################################### # Nearly valid mosaic definition. Warning about invalid links.tiles -def plmosaic_15(): +def test_plmosaic_15(): if gdaltest.plmosaic_drv is None: - return 'skip' + pytest.skip() gdal.FileFromMemBuffer('/vsimem/root/?name__is=my_mosaic', """{ "mosaics": [{ @@ -495,29 +425,19 @@ def plmosaic_15(): ds = gdal.OpenEx('PLMosaic:', gdal.OF_RASTER, open_options=['API_KEY=foo', 'MOSAIC=my_mosaic', 'CACHE_PATH=tmp']) gdal.PopErrorHandler() gdal.SetConfigOption('PL_URL', None) - if gdal.GetLastErrorMsg().find('Invalid _links.tiles') < 0: - gdaltest.post_reason('fail') - print(gdal.GetLastErrorMsg()) - return 'fail' - if ds.GetRasterBand(1).GetOverviewCount() != 0: - gdaltest.post_reason('fail') - print(ds.GetRasterBand(1).GetOverviewCount()) - return 'fail' - if ds.GetRasterBand(1).GetOverview(0) is not None: - gdaltest.post_reason('fail') - return 'fail' + assert gdal.GetLastErrorMsg().find('Invalid _links.tiles') >= 0 + assert ds.GetRasterBand(1).GetOverviewCount() == 0 + assert ds.GetRasterBand(1).GetOverview(0) is None ds = None - return 'success' - ############################################################################### # Valid mosaic definition -def plmosaic_16(): +def test_plmosaic_16(): if gdaltest.plmosaic_drv is None: - return 'skip' + pytest.skip() try: shutil.rmtree('tmp/plmosaic_cache') @@ -563,82 +483,42 @@ def plmosaic_16(): ds = gdal.OpenEx('PLMosaic:api_key=foo,unsupported_option=val', gdal.OF_RASTER) gdal.PopErrorHandler() gdal.SetConfigOption('PL_URL', None) - if ds is not None or gdal.GetLastErrorMsg().find('Unsupported option unsupported_option') < 0: - gdaltest.post_reason('fail') - print(gdal.GetLastErrorMsg()) - return 'fail' + assert ds is None and gdal.GetLastErrorMsg().find('Unsupported option unsupported_option') >= 0 gdal.SetConfigOption('PL_URL', '/vsimem/root') ds = gdal.OpenEx('PLMosaic:', gdal.OF_RASTER, open_options=['API_KEY=foo']) gdal.SetConfigOption('PL_URL', None) - if ds.GetMetadata("SUBDATASETS") != {}: - gdaltest.post_reason('fail') - print(ds.GetMetadata("SUBDATASETS")) - return 'fail' - if ds.GetMetadata() != {'LAST_ACQUIRED': 'last_date', 'NAME': 'my_mosaic', 'FIRST_ACQUIRED': 'first_date'}: - gdaltest.post_reason('fail') - print(ds.GetMetadata()) - return 'fail' + assert ds.GetMetadata("SUBDATASETS") == {} + assert ds.GetMetadata() == {'LAST_ACQUIRED': 'last_date', 'NAME': 'my_mosaic', 'FIRST_ACQUIRED': 'first_date'} ds = None - return 'success' - ############################################################################### # Open with explicit MOSAIC dataset open option -def plmosaic_17(): +def test_plmosaic_17(): if gdaltest.plmosaic_drv is None: - return 'skip' + pytest.skip() gdal.SetConfigOption('PL_URL', '/vsimem/root') ds = gdal.OpenEx('PLMosaic:', gdal.OF_RASTER, open_options=['API_KEY=foo', 'MOSAIC=my_mosaic', 'CACHE_PATH=tmp']) gdal.SetConfigOption('PL_URL', None) - if ds is None: - gdaltest.post_reason('fail') - return 'fail' - if ds.GetMetadata() != {'LAST_ACQUIRED': 'last_date', 'NAME': 'my_mosaic', 'FIRST_ACQUIRED': 'first_date'}: - gdaltest.post_reason('fail') - print(ds.GetMetadata()) - return 'fail' - if ds.GetProjectionRef().find('3857') < 0: - gdaltest.post_reason('fail') - print(ds.GetProjectionRef()) - return 'fail' - if ds.RasterXSize != 8388608: - gdaltest.post_reason('fail') - print(ds.RasterXSize) - return 'fail' - if ds.RasterYSize != 8388608: - gdaltest.post_reason('fail') - print(ds.RasterYSize) - return 'fail' + assert ds is not None + assert ds.GetMetadata() == {'LAST_ACQUIRED': 'last_date', 'NAME': 'my_mosaic', 'FIRST_ACQUIRED': 'first_date'} + assert ds.GetProjectionRef().find('3857') >= 0 + assert ds.RasterXSize == 8388608 + assert ds.RasterYSize == 8388608 got_gt = ds.GetGeoTransform() expected_gt = (-20037508.34, 4.7773142671600004, 0.0, 20037508.34, 0.0, -4.7773142671600004) for i in range(6): - if abs(got_gt[i] - expected_gt[i]) > 1e-8: - gdaltest.post_reason('fail') - print(ds.GetGeoTransform()) - return 'fail' - if ds.GetMetadataItem('INTERLEAVE', 'IMAGE_STRUCTURE') != 'PIXEL': - gdaltest.post_reason('fail') - print(ds.GetMetadata('IMAGE_STRUCTURE')) - print(ds.GetMetadataItem('INTERLEAVE', 'IMAGE_STRUCTURE')) - return 'fail' - if ds.GetRasterBand(1).GetOverviewCount() != 15: - gdaltest.post_reason('fail') - print(ds.GetRasterBand(1).GetOverviewCount()) - return 'fail' - if ds.GetRasterBand(1).GetOverview(-1) is not None: - gdaltest.post_reason('fail') - return 'fail' - if ds.GetRasterBand(1).GetOverview(ds.GetRasterBand(1).GetOverviewCount()) is not None: - gdaltest.post_reason('fail') - return 'fail' - if ds.GetRasterBand(1).GetOverview(0) is None: - gdaltest.post_reason('fail') - return 'fail' + assert abs(got_gt[i] - expected_gt[i]) <= 1e-8, ds.GetGeoTransform() + assert ds.GetMetadataItem('INTERLEAVE', 'IMAGE_STRUCTURE') == 'PIXEL', \ + ds.GetMetadata('IMAGE_STRUCTURE') + assert ds.GetRasterBand(1).GetOverviewCount() == 15 + assert ds.GetRasterBand(1).GetOverview(-1) is None + assert ds.GetRasterBand(1).GetOverview(ds.GetRasterBand(1).GetOverviewCount()) is None + assert ds.GetRasterBand(1).GetOverview(0) is not None try: shutil.rmtree('tmp/plmosaic_cache') @@ -648,21 +528,15 @@ def plmosaic_17(): for i in range(12): # Read at one nonexistent position. ds.GetRasterBand(1).ReadRaster(4096 * i, 0, 1, 1) - if gdal.GetLastErrorMsg() != '': - gdaltest.post_reason('fail') - return 'fail' + assert gdal.GetLastErrorMsg() == '' for i in range(11, -1, -1): # Again in the same quad, but in different block, to test cache ds.GetRasterBand(1).ReadRaster(4096 * i + 256, 0, 1, 1) - if gdal.GetLastErrorMsg() != '': - gdaltest.post_reason('fail') - return 'fail' + assert gdal.GetLastErrorMsg() == '' for i in range(12): # Again in the same quad, but in different block, to test cache ds.GetRasterBand(1).ReadRaster(4096 * i + 512, 256, 1, 1) - if gdal.GetLastErrorMsg() != '': - gdaltest.post_reason('fail') - return 'fail' + assert gdal.GetLastErrorMsg() == '' ds.FlushCache() @@ -695,10 +569,7 @@ def plmosaic_17(): val = ds.GetRasterBand(1).ReadRaster(0, 0, 1, 1) val = struct.unpack('B', val)[0] - if val != 255: - gdaltest.post_reason('fail') - print(val) - return 'fail' + assert val == 255 os.stat('tmp/plmosaic_cache/my_mosaic/my_mosaic_0-2047.tif') @@ -712,10 +583,7 @@ def plmosaic_17(): tmp_ds = None val = ds.GetRasterBand(1).ReadRaster(0, 0, 1, 1) val = struct.unpack('B', val)[0] - if val != 255: - gdaltest.post_reason('fail') - print(val) - return 'fail' + assert val == 255 ds = None @@ -728,10 +596,7 @@ def plmosaic_17(): val = ds.GetRasterBand(1).ReadRaster(0, 0, 1, 1) val = struct.unpack('B', val)[0] - if val != 255: - gdaltest.post_reason('fail') - print(val) - return 'fail' + assert val == 255 ds = None # Read again from file cache but the metatile has changed in between @@ -746,21 +611,16 @@ def plmosaic_17(): val = ds.ReadRaster(0, 0, 1, 1) val = struct.unpack('B' * 4, val) - if val != (254, 0, 0, 0): - gdaltest.post_reason('fail') - print(val) - return 'fail' - - return 'success' + assert val == (254, 0, 0, 0) ############################################################################### # Test location info -def plmosaic_18(): +def test_plmosaic_18(): if gdaltest.plmosaic_drv is None: - return 'skip' + pytest.skip() shutil.rmtree('tmp/plmosaic_cache') @@ -769,17 +629,11 @@ def plmosaic_18(): gdal.SetConfigOption('PL_URL', None) ret = ds.GetRasterBand(1).GetMetadataItem('Pixel_0_0', 'LocationInfo') - if ret != """<LocationInfo /> -""": - gdaltest.post_reason('fail') - print(ret) - return 'fail' + assert ret == """<LocationInfo /> +""" old_ret = ret ret = ds.GetRasterBand(1).GetMetadataItem('Pixel_0_0', 'LocationInfo') - if ret != old_ret: - gdaltest.post_reason('fail') - print(ret) - return 'fail' + assert ret == old_ret gdal.FileFromMemBuffer('/vsimem/root/my_mosaic_id/quads/0-2047/items', """{ "items": [ @@ -790,29 +644,24 @@ def plmosaic_18(): ds.FlushCache() ret = ds.GetRasterBand(1).GetMetadataItem('Pixel_0_0', 'LocationInfo') - if ret != """<LocationInfo> + assert ret == """<LocationInfo> <Scenes> <Scene> <link>foo</link> </Scene> </Scenes> </LocationInfo> -""": - gdaltest.post_reason('fail') - print(ret) - return 'fail' +""" ds = None - return 'success' - ############################################################################### # Try error in saving in cache -def plmosaic_19(): +def test_plmosaic_19(): if gdaltest.plmosaic_drv is None: - return 'skip' + pytest.skip() gdal.SetConfigOption('PL_URL', '/vsimem/root') ds = gdal.OpenEx('PLMosaic:', gdal.OF_RASTER, open_options=['API_KEY=foo', 'MOSAIC=my_mosaic', 'CACHE_PATH=/does_not_exist']) @@ -821,58 +670,42 @@ def plmosaic_19(): val = ds.ReadRaster(0, 0, 1, 1) gdal.PopErrorHandler() val = struct.unpack('B' * 4, val) - if val != (254, 0, 0, 0): - gdaltest.post_reason('fail') - print(val) - return 'fail' + assert val == (254, 0, 0, 0) val = ds.ReadRaster(256, 0, 1, 1) val = struct.unpack('B' * 4, val) - if val != (254, 0, 0, 0): - gdaltest.post_reason('fail') - print(val) - return 'fail' + assert val == (254, 0, 0, 0) ds = None - return 'success' - ############################################################################### # Try disabling cache -def plmosaic_20(): +def test_plmosaic_20(): if gdaltest.plmosaic_drv is None: - return 'skip' + pytest.skip() gdal.SetConfigOption('PL_URL', '/vsimem/root') ds = gdal.OpenEx('PLMosaic:', gdal.OF_RASTER, open_options=['API_KEY=foo', 'MOSAIC=my_mosaic', 'CACHE_PATH=']) gdal.SetConfigOption('PL_URL', None) val = ds.ReadRaster(0, 0, 1, 1) val = struct.unpack('B' * 4, val) - if val != (254, 0, 0, 0): - gdaltest.post_reason('fail') - print(val) - return 'fail' + assert val == (254, 0, 0, 0) val = ds.ReadRaster(256, 0, 1, 1) val = struct.unpack('B' * 4, val) - if val != (254, 0, 0, 0): - gdaltest.post_reason('fail') - print(val) - return 'fail' + assert val == (254, 0, 0, 0) ds = None - return 'success' - ############################################################################### # Try use_tiles -def plmosaic_21(): +def test_plmosaic_21(): if gdaltest.plmosaic_drv is None: - return 'skip' + pytest.skip() gdal.SetConfigOption('PL_URL', '/vsimem/root') ds = gdal.OpenEx('PLMosaic:', gdal.OF_RASTER, open_options=['API_KEY=foo', 'MOSAIC=my_mosaic', 'CACHE_PATH=', 'USE_TILES=YES']) @@ -882,25 +715,19 @@ def plmosaic_21(): gdal.PushErrorHandler() ds.ReadRaster(256, 512, 1, 1) gdal.PopErrorHandler() - if gdal.GetLastErrorMsg() == '': - gdaltest.post_reason('fail') - return 'fail' + assert gdal.GetLastErrorMsg() != '' gdal.ErrorReset() gdal.PushErrorHandler() ds.GetRasterBand(1).ReadRaster(256, 512, 1, 1) gdal.PopErrorHandler() - if gdal.GetLastErrorMsg() == '': - gdaltest.post_reason('fail') - return 'fail' + assert gdal.GetLastErrorMsg() != '' gdal.ErrorReset() gdal.PushErrorHandler() ds.GetRasterBand(1).ReadBlock(1, 2) gdal.PopErrorHandler() - if gdal.GetLastErrorMsg() == '': - gdaltest.post_reason('fail') - return 'fail' + assert gdal.GetLastErrorMsg() != '' gdal.FileFromMemBuffer('/vsimem/root/?name__is=mosaic_uint16', """{ "mosaics": [{ @@ -928,10 +755,7 @@ def plmosaic_21(): ds = gdal.OpenEx('PLMosaic:', gdal.OF_RASTER, open_options=['API_KEY=foo', 'MOSAIC=mosaic_uint16', 'CACHE_PATH=', 'USE_TILES=YES']) gdal.SetConfigOption('PL_URL', None) gdal.PopErrorHandler() - if gdal.GetLastErrorMsg().find('Cannot use tile API for full resolution data on non Byte mosaic') < 0: - gdaltest.post_reason('fail') - print(gdal.GetLastErrorMsg()) - return 'fail' + assert gdal.GetLastErrorMsg().find('Cannot use tile API for full resolution data on non Byte mosaic') >= 0 gdal.FileFromMemBuffer('/vsimem/root/?name__is=mosaic_without_tiles', """{ "mosaics": [{ @@ -956,21 +780,16 @@ def plmosaic_21(): ds = gdal.OpenEx('PLMosaic:', gdal.OF_RASTER, open_options=['API_KEY=foo', 'MOSAIC=mosaic_without_tiles', 'CACHE_PATH=', 'USE_TILES=YES']) gdal.SetConfigOption('PL_URL', None) gdal.PopErrorHandler() - if gdal.GetLastErrorMsg().find('Cannot find tile definition, so use_tiles will be ignored') < 0: - gdaltest.post_reason('fail') - print(gdal.GetLastErrorMsg()) - return 'fail' - - return 'success' + assert gdal.GetLastErrorMsg().find('Cannot find tile definition, so use_tiles will be ignored') >= 0 ############################################################################### # Valid mosaic definition with bbox -def plmosaic_with_bbox(): +def test_plmosaic_with_bbox(): if gdaltest.plmosaic_drv is None: - return 'skip' + pytest.skip() try: shutil.rmtree('tmp/plmosaic_cache') @@ -1020,21 +839,12 @@ def plmosaic_with_bbox(): gdal.SetConfigOption('PL_URL', '/vsimem/root') ds = gdal.OpenEx('PLMosaic:', gdal.OF_RASTER, open_options=['API_KEY=foo']) gdal.SetConfigOption('PL_URL', None) - if ds.RasterXSize != 233472: - gdaltest.post_reason('fail') - print(ds.RasterXSize) - return 'fail' - if ds.RasterYSize != 286720: - gdaltest.post_reason('fail') - print(ds.RasterYSize) - return 'fail' + assert ds.RasterXSize == 233472 + assert ds.RasterYSize == 286720 got_gt = ds.GetGeoTransform() expected_gt = (-11134123.286585508, 4.77731426716, 0.0, 4872401.930333553, 0.0, -4.77731426716) for i in range(6): - if abs(got_gt[i] - expected_gt[i]) > 1e-8: - gdaltest.post_reason('fail') - print(got_gt) - return 'fail' + assert abs(got_gt[i] - expected_gt[i]) <= 1e-8 # Good GeoTIFF tmp_ds = gdal.GetDriverByName('GTiff').Create('/vsimem/root/my_mosaic_id/quads/455-1272/full', 4096, 4096, 4, options=['INTERLEAVE=BAND', 'SPARSE_OK=YES']) @@ -1043,10 +853,7 @@ def plmosaic_with_bbox(): val = ds.GetRasterBand(1).ReadRaster(0, 0, 1, 1) val = struct.unpack('B', val)[0] - if val != 125: - gdaltest.post_reason('fail') - print(val) - return 'fail' + assert val == 125 gdal.FileFromMemBuffer('/vsimem/root/my_mosaic_id/quads/455-1272/items', """{ "items": [ @@ -1055,28 +862,23 @@ def plmosaic_with_bbox(): }""") ret = ds.GetRasterBand(1).GetMetadataItem('Pixel_0_0', 'LocationInfo') - if ret != """<LocationInfo> + assert ret == """<LocationInfo> <Scenes> <Scene> <link>bar</link> </Scene> </Scenes> </LocationInfo> -""": - gdaltest.post_reason('fail') - print(ret) - return 'fail' - - return 'success' +""" ############################################################################### # -def plmosaic_cleanup(): +def test_plmosaic_cleanup(): if gdaltest.plmosaic_drv is None: - return 'skip' + pytest.skip() gdal.Unlink('/vsimem/root_no_mosaics') gdal.Unlink('/vsimem/root') @@ -1097,40 +899,6 @@ def plmosaic_cleanup(): except OSError: pass - return 'success' - - -gdaltest_list = [ - plmosaic_1, - plmosaic_2, - plmosaic_3, - plmosaic_4, - plmosaic_5, - plmosaic_6, - plmosaic_7, - plmosaic_8, - plmosaic_9, - plmosaic_9bis, - plmosaic_9ter, - plmosaic_10, - plmosaic_11, - plmosaic_12, - plmosaic_13, - plmosaic_14, - plmosaic_15, - plmosaic_16, - plmosaic_17, - plmosaic_18, - plmosaic_19, - plmosaic_20, - plmosaic_21, - plmosaic_with_bbox, - plmosaic_cleanup] - -if __name__ == '__main__': - - gdaltest.setup_run('plmosaic') - - gdaltest.run_tests(gdaltest_list) - - sys.exit(gdaltest.summarize()) + + + diff --git a/autotest/gdrivers/png.py b/autotest/gdrivers/png.py index 338d9148f4f4..69b73eb852fc 100755 --- a/autotest/gdrivers/png.py +++ b/autotest/gdrivers/png.py @@ -30,18 +30,17 @@ ############################################################################### import os -import sys from osgeo import gdal -sys.path.append('../pymod') import gdaltest +import pytest ############################################################################### # Read test of simple byte reference data. -def png_1(): +def test_png_1(): tst = gdaltest.GDALTest('PNG', 'test.png', 1, 57921) return tst.testOpen() @@ -50,7 +49,7 @@ def png_1(): # Test lossless copying. -def png_2(): +def test_png_2(): tst = gdaltest.GDALTest('PNG', 'test.png', 1, 57921) @@ -60,21 +59,16 @@ def png_2(): # Verify the geotransform, colormap, and nodata setting for test file. -def png_3(): +def test_png_3(): ds = gdal.Open('data/test.png') cm = ds.GetRasterBand(1).GetRasterColorTable() - if cm.GetCount() != 16 \ - or cm.GetColorEntry(0) != (255, 255, 255, 0) \ - or cm.GetColorEntry(1) != (255, 255, 208, 255): - gdaltest.post_reason('Wrong colormap entries') - return 'fail' + assert cm.GetCount() == 16 and cm.GetColorEntry(0) == (255, 255, 255, 0) and cm.GetColorEntry(1) == (255, 255, 208, 255), \ + 'Wrong colormap entries' cm = None - if int(ds.GetRasterBand(1).GetNoDataValue()) != 0: - gdaltest.post_reason('Wrong nodata value.') - return 'fail' + assert int(ds.GetRasterBand(1).GetNoDataValue()) == 0, 'Wrong nodata value.' # This geotransform test is also verifying the fix for bug 1414, as # the world file is in a mixture of numeric representations for the @@ -87,17 +81,14 @@ def png_3(): if abs(gt[i] - gt_expected[i]) > 0.0001: print('expected:', gt_expected) print('got:', gt) + pytest.fail('Mixed locale world file read improperly.') - gdaltest.post_reason('Mixed locale world file read improperly.') - return 'fail' - - return 'success' - + ############################################################################### # Test RGB mode creation and reading. -def png_4(): +def test_png_4(): tst = gdaltest.GDALTest('PNG', 'rgb.ntf', 3, 21349) @@ -107,7 +98,7 @@ def png_4(): # Test RGBA 16bit read support. -def png_5(): +def test_png_5(): tst = gdaltest.GDALTest('PNG', 'rgba16.png', 3, 1815) return tst.testOpen() @@ -116,7 +107,7 @@ def png_5(): # Test RGBA 16bit mode creation and reading. -def png_6(): +def test_png_6(): tst = gdaltest.GDALTest('PNG', 'rgba16.png', 4, 4873) @@ -127,7 +118,7 @@ def png_6(): # This is handled via the tRNS block in PNG. -def png_7(): +def test_png_7(): drv = gdal.GetDriverByName('PNG') srcds = gdal.Open('data/tbbn2c16.png') @@ -139,41 +130,31 @@ def png_7(): md = dstds.GetMetadata() dstds = None - if md['NODATA_VALUES'] != '32639 32639 32639': - gdaltest.post_reason('NODATA_VALUES wrong') - return 'fail' + assert md['NODATA_VALUES'] == '32639 32639 32639', 'NODATA_VALUES wrong' dstds = None drv.Delete('tmp/png7.png') - return 'success' - ############################################################################### # Test PNG file with broken IDAT chunk. This poor man test of clean # recovery from errors caused by reading broken file.. -def png_8(): +def test_png_8(): drv = gdal.GetDriverByName('PNG') ds_src = gdal.Open('data/idat_broken.png') md = ds_src.GetMetadata() - if md: - gdaltest.post_reason('metadata list not expected') - return 'fail' + assert not md, 'metadata list not expected' # Number of bands has been preserved - if ds_src.RasterCount != 4: - gdaltest.post_reason('wrong number of bands') - return 'fail' + assert ds_src.RasterCount == 4, 'wrong number of bands' # No reading is performed, so we expect valid reference b = ds_src.GetRasterBand(1) - if b is None: - gdaltest.post_reason('band 1 is missing') - return 'fail' + assert b is not None, 'band 1 is missing' # We're not interested in returned value but internal state of GDAL. gdal.PushErrorHandler('CPLQuietErrorHandler') @@ -181,9 +162,7 @@ def png_8(): err = gdal.GetLastErrorNo() gdal.PopErrorHandler() - if err == 0: - gdaltest.post_reason('error condition expected') - return 'fail' + assert err != 0, 'error condition expected' gdal.PushErrorHandler('CPLQuietErrorHandler') ds_dst = drv.CreateCopy('tmp/idat_broken.png', ds_src) @@ -191,23 +170,17 @@ def png_8(): gdal.PopErrorHandler() ds_src = None - if err == 0: - gdaltest.post_reason('error condition expected') - return 'fail' + assert err != 0, 'error condition expected' - if ds_dst is not None: - gdaltest.post_reason('dataset not expected') - return 'fail' + assert ds_dst is None, 'dataset not expected' os.remove('tmp/idat_broken.png') - return 'success' - ############################################################################### # Test creating an in memory copy. -def png_9(): +def test_png_9(): tst = gdaltest.GDALTest('PNG', 'byte.tif', 1, 4672) @@ -217,30 +190,25 @@ def png_9(): # Test writing to /vsistdout/ -def png_10(): +def test_png_10(): src_ds = gdal.Open('data/byte.tif') ds = gdal.GetDriverByName('PNG').CreateCopy('/vsistdout_redirect//vsimem/tmp.png', src_ds) - if ds.GetRasterBand(1).Checksum() != 0: - return 'fail' + assert ds.GetRasterBand(1).Checksum() == 0 src_ds = None ds = None ds = gdal.Open('/vsimem/tmp.png') - if ds is None: - return 'fail' - if ds.GetRasterBand(1).Checksum() != 4672: - return 'fail' + assert ds is not None + assert ds.GetRasterBand(1).Checksum() == 4672 gdal.Unlink('/vsimem/tmp.png') - return 'success' - ############################################################################### # Test CreateCopy() interruption -def png_11(): +def test_png_11(): tst = gdaltest.GDALTest('PNG', 'byte.tif', 1, 4672) @@ -252,7 +220,7 @@ def png_11(): # Test optimized IRasterIO -def png_12(): +def test_png_12(): ds = gdal.Open('../gcore/data/stefan_full_rgba.png') cs = [ds.GetRasterBand(i + 1).Checksum() for i in range(ds.RasterCount)] @@ -261,35 +229,27 @@ def png_12(): tmp_ds = gdal.GetDriverByName('Mem').Create('', ds.RasterXSize, ds.RasterYSize, ds.RasterCount) tmp_ds.WriteRaster(0, 0, ds.RasterXSize, ds.RasterYSize, data) got_cs = [tmp_ds.GetRasterBand(i + 1).Checksum() for i in range(ds.RasterCount)] - if cs != got_cs: - gdaltest.post_reason('failure') - return 'fail' + assert cs == got_cs # Pixel interleaved data = ds.ReadRaster(0, 0, ds.RasterXSize, ds.RasterYSize, buf_pixel_space=ds.RasterCount, buf_band_space=1) tmp_ds = gdal.GetDriverByName('Mem').Create('', ds.RasterXSize, ds.RasterYSize, ds.RasterCount) tmp_ds.WriteRaster(0, 0, ds.RasterXSize, ds.RasterYSize, data, buf_pixel_space=ds.RasterCount, buf_band_space=1) got_cs = [tmp_ds.GetRasterBand(i + 1).Checksum() for i in range(ds.RasterCount)] - if cs != got_cs: - gdaltest.post_reason('failure') - return 'fail' + assert cs == got_cs # Pixel interleaved with padding data = ds.ReadRaster(0, 0, ds.RasterXSize, ds.RasterYSize, buf_pixel_space=5, buf_band_space=1) tmp_ds = gdal.GetDriverByName('Mem').Create('', ds.RasterXSize, ds.RasterYSize, ds.RasterCount) tmp_ds.WriteRaster(0, 0, ds.RasterXSize, ds.RasterYSize, data, buf_pixel_space=5, buf_band_space=1) got_cs = [tmp_ds.GetRasterBand(i + 1).Checksum() for i in range(ds.RasterCount)] - if cs != got_cs: - gdaltest.post_reason('failure') - return 'fail' - - return 'success' + assert cs == got_cs ############################################################################### # Test metadata -def png_13(): +def test_png_13(): src_ds = gdal.GetDriverByName('MEM').Create('', 1, 1) src_ds.SetMetadataItem('foo', 'bar') @@ -297,23 +257,17 @@ def png_13(): src_ds.SetMetadataItem('DESCRIPTION', 'will be overridden by creation option') out_ds = gdal.GetDriverByName('PNG').CreateCopy('/vsimem/tmp.png', src_ds, options=['WRITE_METADATA_AS_TEXT=YES', 'DESCRIPTION=my desc']) md = out_ds.GetMetadata() - if len(md) != 3 or md['foo'] != 'bar' or md['Copyright'] != 'copyright value' or md['Description'] != 'my desc': - gdaltest.post_reason('failure') - print(md) - return 'fail' + assert len(md) == 3 and md['foo'] == 'bar' and md['Copyright'] == 'copyright value' and md['Description'] == 'my desc' out_ds = None # check that no PAM file is created - if gdal.VSIStatL('/vsimem/tmp.png.aux.xml') == 0: - gdaltest.post_reason('failure') - return 'fail' + assert gdal.VSIStatL('/vsimem/tmp.png.aux.xml') != 0 gdal.Unlink('/vsimem/tmp.png') - return 'success' ############################################################################### # Test support for nbits < 8 -def png_14(): +def test_png_14(): src_ds = gdal.Open('../gcore/data/oddsize1bit.tif') expected_cs = src_ds.GetRasterBand(1).Checksum() @@ -323,30 +277,19 @@ def png_14(): nbits = out_ds.GetRasterBand(1).GetMetadataItem('NBITS', 'IMAGE_STRUCTURE') gdal.Unlink('/vsimem/tmp.png') - if cs != expected_cs: - gdaltest.post_reason('failure') - print(cs) - return 'fail' + assert cs == expected_cs - if nbits != '1': - gdaltest.post_reason('failure') - print(nbits) - return 'fail' + assert nbits == '1' # check that no PAM file is created - if gdal.VSIStatL('/vsimem/tmp.png.aux.xml') == 0: - gdaltest.post_reason('failure') - return 'fail' + assert gdal.VSIStatL('/vsimem/tmp.png.aux.xml') != 0 # Test explicit NBITS gdal.GetDriverByName('PNG').CreateCopy('/vsimem/tmp.png', src_ds, options=['NBITS=2']) out_ds = gdal.Open('/vsimem/tmp.png') nbits = out_ds.GetRasterBand(1).GetMetadataItem('NBITS', 'IMAGE_STRUCTURE') gdal.Unlink('/vsimem/tmp.png') - if nbits != '2': - gdaltest.post_reason('failure') - print(nbits) - return 'fail' + assert nbits == '2' # Test (wrong) explicit NBITS with gdaltest.error_handler(): @@ -354,35 +297,7 @@ def png_14(): out_ds = gdal.Open('/vsimem/tmp.png') nbits = out_ds.GetRasterBand(1).GetMetadataItem('NBITS', 'IMAGE_STRUCTURE') gdal.Unlink('/vsimem/tmp.png') - if nbits is not None: - gdaltest.post_reason('failure') - print(nbits) - return 'fail' - - return 'success' - - -gdaltest_list = [ - png_1, - png_2, - png_3, - png_4, - png_5, - png_6, - png_7, - png_8, - png_9, - png_10, - png_11, - png_12, - png_13, - png_14 -] - -if __name__ == '__main__': - - gdaltest.setup_run('png') - - gdaltest.run_tests(gdaltest_list) - - sys.exit(gdaltest.summarize()) + assert nbits is None + + + diff --git a/autotest/gdrivers/png_profile.py b/autotest/gdrivers/png_profile.py index 806e04a44c4c..94613ec89f52 100755 --- a/autotest/gdrivers/png_profile.py +++ b/autotest/gdrivers/png_profile.py @@ -31,24 +31,17 @@ # http://sourceforge.net/projects/openicc/files/OpenICC-Profiles/ import os -import sys import base64 -sys.path.append('../pymod') -import gdaltest from osgeo import gdal - -############################################################################### -# When imported build a list of units based on the files available. - -gdaltest_list = [] +import pytest ############################################################################### # Test writing and reading of ICC profile in CreateCopy() -def png_copy_icc(): +def test_png_copy_icc(): f = open('data/sRGB.icc', 'rb') data = f.read() @@ -68,54 +61,37 @@ def png_copy_icc(): ds = None ds2 = None - if md['SOURCE_ICC_PROFILE'] != icc: - gdaltest.post_reason('fail') - return 'fail' + assert md['SOURCE_ICC_PROFILE'] == icc - try: + with pytest.raises(OSError): os.stat('tmp/icc_test.png.aux.xml') - gdaltest.post_reason('fail') - return 'fail' - except OSError: - pass + # Check again with dataset from Open() ds2 = gdal.Open('tmp/icc_test.png') md = ds2.GetMetadata("COLOR_PROFILE") ds2 = None - try: + with pytest.raises(OSError): os.stat('tmp/icc_test.png.aux.xml') - gdaltest.post_reason('fail') - return 'fail' - except OSError: - pass + - if md['SOURCE_ICC_PROFILE'] != icc: - gdaltest.post_reason('fail') - return 'fail' + assert md['SOURCE_ICC_PROFILE'] == icc # Check again with GetMetadataItem() ds2 = gdal.Open('tmp/icc_test.png') source_icc_profile = ds2.GetMetadataItem("SOURCE_ICC_PROFILE", "COLOR_PROFILE") ds2 = None - try: + with pytest.raises(OSError): os.stat('tmp/icc_test.png.aux.xml') - gdaltest.post_reason('fail') - return 'fail' - except OSError: - pass + - if source_icc_profile != icc: - gdaltest.post_reason('fail') - return 'fail' + assert source_icc_profile == icc driver_tiff.Delete('tmp/icc_test.tiff') driver.Delete('tmp/icc_test.png') - return 'success' - def cvtTuple2String(t): return str(t).lstrip('([').rstrip(')]') @@ -124,7 +100,7 @@ def cvtTuple2String(t): # Test writing and reading of ICC profile in CreateCopy() options -def png_copy_options_icc(): +def test_png_copy_options_icc(): f = open('data/sRGB.icc', 'rb') data = f.read() @@ -144,9 +120,7 @@ def png_copy_options_icc(): ds = None ds2 = None - if md['SOURCE_ICC_PROFILE'] != icc: - gdaltest.post_reason('fail') - return 'fail' + assert md['SOURCE_ICC_PROFILE'] == icc # Check again with dataset from Open() ds2 = gdal.Open('tmp/icc_test.png') @@ -154,20 +128,16 @@ def png_copy_options_icc(): ds = None ds2 = None - if md['SOURCE_ICC_PROFILE'] != icc: - gdaltest.post_reason('fail') - return 'fail' + assert md['SOURCE_ICC_PROFILE'] == icc driver_tiff.Delete('tmp/icc_test.tiff') driver.Delete('tmp/icc_test.png') - return 'success' - ############################################################################### # Test writing and reading of ICC colorimetric data from options -def png_copy_options_colorimetric_data(): +def test_png_copy_options_colorimetric_data(): # sRGB values source_primaries = [(0.64, 0.33, 1.0), (0.3, 0.6, 1.0), (0.15, 0.06, 1.0)] source_whitepoint = (0.31271, 0.32902, 1.0) @@ -191,9 +161,7 @@ def png_copy_options_colorimetric_data(): source_whitepoint2 = eval('(' + md['SOURCE_WHITEPOINT'] + ')') for i in range(0, 3): - if abs(source_whitepoint2[i] - source_whitepoint[i]) > 0.0001: - gdaltest.post_reason('fail') - return 'fail' + assert abs(source_whitepoint2[i] - source_whitepoint[i]) <= 0.0001 source_primaries2 = [ eval('(' + md['SOURCE_PRIMARIES_RED'] + ')'), @@ -202,13 +170,9 @@ def png_copy_options_colorimetric_data(): for j in range(0, 3): for i in range(0, 3): - if abs(source_primaries2[j][i] - source_primaries[j][i]) > 0.0001: - gdaltest.post_reason('fail') - return 'fail' + assert abs(source_primaries2[j][i] - source_primaries[j][i]) <= 0.0001 - if float(md['PNG_GAMMA']) != 1.5: - gdaltest.post_reason('fail') - return 'fail' + assert float(md['PNG_GAMMA']) == 1.5 # Check again with dataset from Open() ds2 = gdal.Open('tmp/icc_test.png') @@ -219,9 +183,7 @@ def png_copy_options_colorimetric_data(): source_whitepoint2 = eval('(' + md['SOURCE_WHITEPOINT'] + ')') for i in range(0, 3): - if abs(source_whitepoint2[i] - source_whitepoint[i]) > 0.0001: - gdaltest.post_reason('fail') - return 'fail' + assert abs(source_whitepoint2[i] - source_whitepoint[i]) <= 0.0001 source_primaries2 = [ eval('(' + md['SOURCE_PRIMARIES_RED'] + ')'), @@ -230,24 +192,18 @@ def png_copy_options_colorimetric_data(): for j in range(0, 3): for i in range(0, 3): - if abs(source_primaries2[j][i] - source_primaries[j][i]) > 0.0001: - gdaltest.post_reason('fail') - return 'fail' + assert abs(source_primaries2[j][i] - source_primaries[j][i]) <= 0.0001 - if float(md['PNG_GAMMA']) != 1.5: - gdaltest.post_reason('fail') - return 'fail' + assert float(md['PNG_GAMMA']) == 1.5 driver_tiff.Delete('tmp/icc_test.tiff') driver.Delete('tmp/icc_test.png') - return 'success' - ############################################################################### # Test writing and reading of ICC colorimetric data in the file -def png_copy_colorimetric_data(): +def test_png_copy_colorimetric_data(): # sRGB values source_primaries = [(0.64, 0.33, 1.0), (0.3, 0.6, 1.0), (0.15, 0.06, 1.0)] source_whitepoint = (0.31271, 0.32902, 1.0) @@ -274,9 +230,7 @@ def png_copy_colorimetric_data(): source_whitepoint2 = eval('(' + md['SOURCE_WHITEPOINT'] + ')') for i in range(0, 3): - if abs(source_whitepoint2[i] - source_whitepoint[i]) > 0.0001: - gdaltest.post_reason('fail') - return 'fail' + assert abs(source_whitepoint2[i] - source_whitepoint[i]) <= 0.0001 source_primaries2 = [ eval('(' + md['SOURCE_PRIMARIES_RED'] + ')'), @@ -285,13 +239,9 @@ def png_copy_colorimetric_data(): for j in range(0, 3): for i in range(0, 3): - if abs(source_primaries2[j][i] - source_primaries[j][i]) > 0.0001: - gdaltest.post_reason('fail') - return 'fail' + assert abs(source_primaries2[j][i] - source_primaries[j][i]) <= 0.0001 - if float(md['PNG_GAMMA']) != 1.5: - gdaltest.post_reason('fail') - return 'fail' + assert float(md['PNG_GAMMA']) == 1.5 # Check again with dataset from Open() ds2 = gdal.Open('tmp/icc_test.png') @@ -302,9 +252,7 @@ def png_copy_colorimetric_data(): source_whitepoint2 = eval('(' + md['SOURCE_WHITEPOINT'] + ')') for i in range(0, 3): - if abs(source_whitepoint2[i] - source_whitepoint[i]) > 0.0001: - gdaltest.post_reason('fail') - return 'fail' + assert abs(source_whitepoint2[i] - source_whitepoint[i]) <= 0.0001 source_primaries2 = [ eval('(' + md['SOURCE_PRIMARIES_RED'] + ')'), @@ -313,24 +261,18 @@ def png_copy_colorimetric_data(): for j in range(0, 3): for i in range(0, 3): - if abs(source_primaries2[j][i] - source_primaries[j][i]) > 0.0001: - gdaltest.post_reason('fail') - return 'fail' + assert abs(source_primaries2[j][i] - source_primaries[j][i]) <= 0.0001 - if float(md['PNG_GAMMA']) != 1.5: - gdaltest.post_reason('fail') - return 'fail' + assert float(md['PNG_GAMMA']) == 1.5 driver_tiff.Delete('tmp/icc_test.tiff') driver.Delete('tmp/icc_test.png') - return 'success' - ############################################################################### # Test sRGB -def png_sRGB(): +def test_png_sRGB(): # Create dummy file options = ['SOURCE_ICC_PROFILE_NAME=sRGB'] @@ -344,9 +286,7 @@ def png_sRGB(): ds = None ds2 = None - if md['SOURCE_ICC_PROFILE_NAME'] != 'sRGB': - gdaltest.post_reason('fail') - return 'fail' + assert md['SOURCE_ICC_PROFILE_NAME'] == 'sRGB' # Check again with dataset from Open() ds2 = gdal.Open('tmp/icc_test.png') @@ -354,28 +294,12 @@ def png_sRGB(): ds = None ds2 = None - if md['SOURCE_ICC_PROFILE_NAME'] != 'sRGB': - gdaltest.post_reason('fail') - return 'fail' + assert md['SOURCE_ICC_PROFILE_NAME'] == 'sRGB' driver_tiff.Delete('tmp/icc_test.tiff') driver.Delete('tmp/icc_test.png') - return 'success' - ############################################################################ -gdaltest_list.append((png_copy_icc)) -gdaltest_list.append((png_copy_options_icc)) -gdaltest_list.append((png_copy_options_colorimetric_data)) -gdaltest_list.append((png_copy_colorimetric_data)) -gdaltest_list.append((png_sRGB)) - -if __name__ == '__main__': - - gdaltest.setup_run('png_profile') - - gdaltest.run_tests(gdaltest_list) - sys.exit(gdaltest.summarize()) diff --git a/autotest/gdrivers/pnm.py b/autotest/gdrivers/pnm.py index 5c24a6870985..d4b245a43c80 100755 --- a/autotest/gdrivers/pnm.py +++ b/autotest/gdrivers/pnm.py @@ -28,9 +28,7 @@ # DEALINGS IN THE SOFTWARE. ############################################################################### -import sys -sys.path.append('../pymod') import gdaltest @@ -38,7 +36,7 @@ # Read Test grayscale (PGM) -def pnm_1(): +def test_pnm_1(): tst = gdaltest.GDALTest('PNM', 'byte.pgm', 1, 4672) @@ -48,7 +46,7 @@ def pnm_1(): # Write Test grayscale (PGM) -def pnm_2(): +def test_pnm_2(): tst = gdaltest.GDALTest('PNM', 'byte.pgm', 1, 4672) @@ -58,7 +56,7 @@ def pnm_2(): # Read Test RGB (PPM) -def pnm_3(): +def test_pnm_3(): tst = gdaltest.GDALTest('PNM', 'rgbsmall.ppm', 2, 21053) @@ -68,25 +66,12 @@ def pnm_3(): # Write Test RGB (PPM) -def pnm_4(): +def test_pnm_4(): tst = gdaltest.GDALTest('PNM', 'rgbsmall.ppm', 2, 21053) return tst.testCreateCopy() -gdaltest_list = [ - pnm_1, - pnm_2, - pnm_3, - pnm_4 -] -if __name__ == '__main__': - - gdaltest.setup_run('ppm') - - gdaltest.run_tests(gdaltest_list) - - sys.exit(gdaltest.summarize()) diff --git a/autotest/gdrivers/postgisraster.py b/autotest/gdrivers/postgisraster.py index 01f402e7a70b..52f1edef70a3 100755 --- a/autotest/gdrivers/postgisraster.py +++ b/autotest/gdrivers/postgisraster.py @@ -31,14 +31,13 @@ # DEALINGS IN THE SOFTWARE. ############################################################################### -import sys from osgeo import gdal from osgeo import ogr from osgeo import osr -sys.path.append('../pymod') import gdaltest +import pytest # # To initialize the required PostGISRaster DB instance, run data/load_postgisraster_test_data.sh @@ -49,14 +48,14 @@ # -def postgisraster_init(): +def test_postgisraster_init(): gdaltest.postgisrasterDriver = gdal.GetDriverByName('PostGISRaster') if gdaltest.postgisrasterDriver is None: - return 'skip' + pytest.skip() if gdal.GetConfigOption('APPVEYOR'): gdaltest.postgisrasterDriver = None - return 'skip' + pytest.skip() val = gdal.GetConfigOption('GDAL_PG_CONNECTION_STRING', None) if val is not None: @@ -72,7 +71,7 @@ def postgisraster_init(): ds = ogr.Open(gdaltest.postgisraster_connection_string, update=1) if ds is None: gdaltest.postgisrasterDriver = None - return 'skip' + pytest.skip() sr = osr.SpatialReference() sr.ImportFromEPSG(26711) @@ -101,47 +100,44 @@ def postgisraster_init(): gdaltest.postgisrasterDriver = None if gdaltest.postgisrasterDriver is None: - return 'skip' - - return 'success' + pytest.skip() + ############################################################################### # -def postgisraster_test_open_error1(): +def test_postgisraster_test_open_error1(): if gdaltest.postgisrasterDriver is None: - return 'skip' + pytest.skip() with gdaltest.error_handler(): ds = gdal.Open(gdaltest.postgisraster_connection_string + "table='nonexistent'") if ds is None: - return 'success' - return 'fail' + return + pytest.fail() ############################################################################### # -def postgisraster_test_open_error2(): +def test_postgisraster_test_open_error2(): if gdaltest.postgisrasterDriver is None: - return 'skip' + pytest.skip() # removed mode, as it defaults to one raster per row with gdaltest.error_handler(): ds = gdal.Open(gdaltest.postgisraster_connection_string + "table='utm'") - if ds is None: - return 'fail' - return 'success' + assert ds is not None ############################################################################### # -def postgisraster_compare_utm(): +def test_postgisraster_compare_utm(): if gdaltest.postgisrasterDriver is None: - return 'skip' + pytest.skip() src_ds = gdal.Open('data/utm.tif') with gdaltest.error_handler(): @@ -151,15 +147,15 @@ def postgisraster_compare_utm(): dst_ds = gdal.Open(dst_ds.GetMetadata('SUBDATASETS')['SUBDATASET_1_NAME']) diff = gdaltest.compare_ds(src_ds, dst_ds, width=100, height=100, verbose=1) - return 'success' if diff == 0 else 'fail' + assert diff == 0 ############################################################################### # -def postgisraster_compare_small_world(): +def test_postgisraster_compare_small_world(): if gdaltest.postgisrasterDriver is None: - return 'skip' + pytest.skip() src_ds = gdal.Open('data/small_world.tif') with gdaltest.error_handler(): @@ -169,15 +165,15 @@ def postgisraster_compare_small_world(): dst_ds = gdal.Open(dst_ds.GetMetadata('SUBDATASETS')['SUBDATASET_1_NAME']) diff = gdaltest.compare_ds(src_ds, dst_ds, width=40, height=20, verbose=1) - return 'success' if diff == 0 else 'fail' + assert diff == 0 ############################################################################### # -def postgisraster_test_utm_open(): +def test_postgisraster_test_utm_open(): if gdaltest.postgisrasterDriver is None: - return 'skip' + pytest.skip() # First open tif file src_ds = gdal.Open('data/utm.tif') @@ -200,9 +196,9 @@ def postgisraster_test_utm_open(): # -def postgisraster_test_small_world_open_b1(): +def test_postgisraster_test_small_world_open_b1(): if gdaltest.postgisrasterDriver is None: - return 'skip' + pytest.skip() # First open tif file src_ds = gdal.Open('data/small_world.tif') @@ -225,9 +221,9 @@ def postgisraster_test_small_world_open_b1(): # -def postgisraster_test_small_world_open_b2(): +def test_postgisraster_test_small_world_open_b2(): if gdaltest.postgisrasterDriver is None: - return 'skip' + pytest.skip() # First open tif file src_ds = gdal.Open('data/small_world.tif') @@ -250,9 +246,9 @@ def postgisraster_test_small_world_open_b2(): # -def postgisraster_test_small_world_open_b3(): +def test_postgisraster_test_small_world_open_b3(): if gdaltest.postgisrasterDriver is None: - return 'skip' + pytest.skip() # First open tif file src_ds = gdal.Open('data/small_world.tif') @@ -273,21 +269,21 @@ def postgisraster_test_small_world_open_b3(): return tst.testOpen(check_prj=prj, check_gt=gt, skip_checksum=True) -def postgisraster_test_create_copy_bad_conn_string(): +def test_postgisraster_test_create_copy_bad_conn_string(): if gdaltest.postgisrasterDriver is None: - return 'skip' + pytest.skip() with gdaltest.error_handler(): src_ds = gdal.Open(gdaltest.postgisraster_connection_string + "table='small_world'") new_ds = gdaltest.postgisrasterDriver.CreateCopy("bogus connection string", src_ds, strict=True) - return 'success' if new_ds is None else 'fail' + assert new_ds is None -def postgisraster_test_create_copy_no_dbname(): +def test_postgisraster_test_create_copy_no_dbname(): if gdaltest.postgisrasterDriver is None: - return 'skip' + pytest.skip() with gdaltest.error_handler(): src_ds = gdal.Open(gdaltest.postgisraster_connection_string + "table='small_world'") @@ -298,12 +294,12 @@ def postgisraster_test_create_copy_no_dbname(): new_ds = gdaltest.postgisrasterDriver.CreateCopy("PG: no database name", src_ds, strict=True, options=options) - return 'success' if new_ds is None else 'fail' + assert new_ds is None -def postgisraster_test_create_copy_no_tablename(): +def test_postgisraster_test_create_copy_no_tablename(): if gdaltest.postgisrasterDriver is None: - return 'skip' + pytest.skip() with gdaltest.error_handler(): src_ds = gdal.Open(gdaltest.postgisraster_connection_string + "table='small_world'") @@ -314,36 +310,35 @@ def postgisraster_test_create_copy_no_tablename(): new_ds = gdaltest.postgisrasterDriver.CreateCopy(gdaltest.postgisraster_connection_string, src_ds, strict=True, options=options) - return 'success' if new_ds is None else 'fail' + assert new_ds is None -def postgisraster_test_create_copy_and_delete(): +def test_postgisraster_test_create_copy_and_delete(): """ Test the "CreateCopy" implementation. What to do when we're done? Why, test "Delete", of course! """ if gdaltest.postgisrasterDriver is None: - return 'skip' + pytest.skip() with gdaltest.error_handler(): src_ds = gdal.Open(gdaltest.postgisraster_connection_string + "table='small_world'") new_ds = gdaltest.postgisrasterDriver.CreateCopy(gdaltest.postgisraster_connection_string + "table='small_world_copy'", src_ds, strict=True) - if new_ds is None: - return 'fail' + assert new_ds is not None deleted = gdaltest.postgisrasterDriver.Delete(gdaltest.postgisraster_connection_string + "table='small_world_copy'") - return 'fail' if deleted else 'success' + assert not deleted -def postgisraster_test_create_copy_and_delete_phases(): +def test_postgisraster_test_create_copy_and_delete_phases(): """ Create a copy of the dataset, then delete it in phases. """ if gdaltest.postgisrasterDriver is None: - return 'skip' + pytest.skip() with gdaltest.error_handler(): src_ds = gdal.Open(gdaltest.postgisraster_connection_string + "table='small_world'") @@ -358,83 +353,67 @@ def postgisraster_test_create_copy_and_delete_phases(): src_ds = None if new_ds is None: - gdaltest.post_reason('No new dataset was created during copy.') - return 'fail' + pytest.fail('No new dataset was created during copy.') elif len(src_md) != len(new_md): - gdaltest.post_reason('Metadata differs between new and old rasters.') - return 'fail' + pytest.fail('Metadata differs between new and old rasters.') ds = gdal.Open(gdaltest.postgisraster_connection_string + "table='small_world_copy' mode=2") cs = [ds.GetRasterBand(i + 1).Checksum() for i in range(3)] - if cs != [30111, 32302, 40026]: - gdaltest.post_reason('fail') - print(cs) - return 'fail' + assert cs == [30111, 32302, 40026] ds = None # should delete all raster parts over 50 deleted = gdaltest.postgisrasterDriver.Delete(gdaltest.postgisraster_connection_string + "table='small_world_copy' where='rid>50'") - if deleted: - gdaltest.post_reason('Delete returned an error.') - return 'fail' + assert not deleted, 'Delete returned an error.' src_ds = gdal.Open(gdaltest.postgisraster_connection_string + "table='small_world_copy'") src_md = src_ds.GetMetadata('SUBDATASETS').keys() if src_ds is None: - gdaltest.post_reason('Could not open reduced dataset (1).') - return 'fail' + pytest.fail('Could not open reduced dataset (1).') elif len(src_md) != 100: # The length of the metadata contains two pcs of # information per raster, so 50 rasters remaining = 100 keys - gdaltest.post_reason( - 'Expected 100 keys of metadata for 50 subdataset rasters.') print(len(src_md)) - return 'fail' + pytest.fail( + 'Expected 100 keys of metadata for 50 subdataset rasters.') # done with src src_ds = None deleted = gdaltest.postgisrasterDriver.Delete(gdaltest.postgisraster_connection_string + "table='small_world_copy' where='rid<=25'") - if deleted: - gdaltest.post_reason('Delete returned an error.') - return 'fail' + assert not deleted, 'Delete returned an error.' src_ds = gdal.Open(gdaltest.postgisraster_connection_string + "table='small_world_copy'") src_md = src_ds.GetMetadata('SUBDATASETS').keys() if src_ds is None: - gdaltest.post_reason('Could not open reduced dataset (2).') - return 'fail' + pytest.fail('Could not open reduced dataset (2).') elif len(src_md) != 50: # The length of the metadata contains two pcs of # information per raster, so 25 rasters remaining = 50 keys - gdaltest.post_reason('Expected 50 keys of metadata for 25 subdataset rasters.') print(len(src_md)) - return 'fail' + pytest.fail('Expected 50 keys of metadata for 25 subdataset rasters.') # done with src src_ds = None deleted = gdaltest.postgisrasterDriver.Delete(gdaltest.postgisraster_connection_string + "table='small_world_copy'") - if deleted: - gdaltest.post_reason('Delete returned an error.') - return 'fail' + assert not deleted, 'Delete returned an error.' - return 'success' + - -def postgisraster_test_norid(): +def test_postgisraster_test_norid(): """ Test the ability to connect to a data source if it has no 'rid' column. """ if gdaltest.postgisrasterDriver is None: - return 'skip' + pytest.skip() with gdaltest.error_handler(): src_ds = gdal.Open(gdaltest.postgisraster_connection_string + "table='small_world_noid'") @@ -446,28 +425,21 @@ def postgisraster_test_norid(): if k[-4:] == 'NAME': # Ensure the subdataset has upperleftx and upperlefty coords, # as there is no unique key on the table - if src_md[k].find('ST_UpperLeftX') < 0 or src_md[k].find('ST_UpperLeftY') < 0: - print(src_md[k]) - return 'fail' + assert src_md[k].find('ST_UpperLeftX') >= 0 and src_md[k].find('ST_UpperLeftY') >= 0 with gdaltest.error_handler(): ds = gdal.Open(gdaltest.postgisraster_connection_string + "table='small_world_noid' mode=2") cs = [ds.GetRasterBand(i + 1).Checksum() for i in range(3)] - if cs != [30111, 32302, 40026]: - gdaltest.post_reason('fail') - print(cs) - return 'fail' - - return 'success' + assert cs == [30111, 32302, 40026] -def postgisraster_test_serial(): +def test_postgisraster_test_serial(): """ Test the ability to connect to a data source if it has no primary key, but uses a sequence instead. """ if gdaltest.postgisrasterDriver is None: - return 'skip' + pytest.skip() with gdaltest.error_handler(): src_ds = gdal.Open(gdaltest.postgisraster_connection_string + "table='small_world_serial'") @@ -481,28 +453,21 @@ def postgisraster_test_serial(): if k[-4:] == 'NAME': # Ensure the subdataset has upperleftx and upperlefty coords, # as there is no unique key on the table - if not re.search("where='\"serialid\" = \d+'", src_md[k]): - print(k, ':', src_md[k]) - return 'fail' + assert re.search("where='\"serialid\" = \d+'", src_md[k]), (k, ':', src_md[k]) with gdaltest.error_handler(): ds = gdal.Open(gdaltest.postgisraster_connection_string + "table='small_world_serial' mode=2") cs = [ds.GetRasterBand(i + 1).Checksum() for i in range(3)] - if cs != [30111, 32302, 40026]: - gdaltest.post_reason('fail') - print(cs) - return 'fail' + assert cs == [30111, 32302, 40026] - return 'success' - -def postgisraster_test_unique(): +def test_postgisraster_test_unique(): """ Test the ability to connect to a data source if it has no primary key, but uses a unique constraint instead. """ if gdaltest.postgisrasterDriver is None: - return 'skip' + pytest.skip() with gdaltest.error_handler(): src_ds = gdal.Open(gdaltest.postgisraster_connection_string + "table='small_world_unique'") @@ -516,59 +481,42 @@ def postgisraster_test_unique(): if k[-4:] == 'NAME': # Ensure the subdataset has upperleftx and upperlefty coords, # as there is no unique key on the table - if not re.search("where='\"uniq\" = \d+'", src_md[k]): - print(k, ':', src_md[k]) - return 'fail' + assert re.search("where='\"uniq\" = \d+'", src_md[k]), (k, ':', src_md[k]) with gdaltest.error_handler(): ds = gdal.Open(gdaltest.postgisraster_connection_string + "table='small_world_unique' mode=2") cs = [ds.GetRasterBand(i + 1).Checksum() for i in range(3)] - if cs != [30111, 32302, 40026]: - gdaltest.post_reason('fail') - print(cs) - return 'fail' - - return 'success' + assert cs == [30111, 32302, 40026] -def postgisraster_test_constraint(): +def test_postgisraster_test_constraint(): if gdaltest.postgisrasterDriver is None: - return 'skip' + pytest.skip() ds = gdal.Open(gdaltest.postgisraster_connection_string + "table='small_world_constraint' mode=2") cs = [ds.GetRasterBand(i + 1).Checksum() for i in range(3)] - if cs != [30111, 32302, 40026]: - gdaltest.post_reason('fail') - print(cs) - return 'fail' + assert cs == [30111, 32302, 40026] - return 'success' - -def postgisraster_test_constraint_with_spi(): +def test_postgisraster_test_constraint_with_spi(): if gdaltest.postgisrasterDriver is None: - return 'skip' + pytest.skip() ds = gdal.Open(gdaltest.postgisraster_connection_string + "table='small_world_constraint_with_spi' mode=2") cs = [ds.GetRasterBand(i + 1).Checksum() for i in range(3)] - if cs != [30111, 32302, 40026]: - gdaltest.post_reason('fail') - print(cs) - return 'fail' - - return 'success' + assert cs == [30111, 32302, 40026] -def postgisraster_test_outdb(): +def test_postgisraster_test_outdb(): if gdaltest.postgisrasterDriver is None: - return 'skip' + pytest.skip() # For some reason fails with # ERROR 1: PostGISRasterRasterBand::IRasterIO(): ERROR: rt_band_load_offline_data: Cannot open offline raster: /home/travis/build/rouault/gdal/autotest/gdrivers/data/small_world.tif # See https://api.travis-ci.org/v3/job/428972866/log.txt if gdaltest.is_travis_branch('ubuntu_1804'): - return 'skip' + pytest.skip() ds = ogr.Open(gdaltest.postgisraster_connection_string_without_schema) sql_lyr = ds.ExecuteSQL('SHOW postgis.enable_outdb_rasters') @@ -579,95 +527,41 @@ def postgisraster_test_outdb(): ds = gdal.Open(gdaltest.postgisraster_connection_string + "table='small_world_outdb_constraint' mode=2") cs = [ds.GetRasterBand(i + 1).Checksum() for i in range(3)] expected_cs = [30111, 32302, 40026] if has_guc else [0, 0, 0] - if cs != expected_cs: - gdaltest.post_reason('fail') - print(cs) - return 'fail' + assert cs == expected_cs - return 'success' - -def postgisraster_test_outdb_client_side(): +def test_postgisraster_test_outdb_client_side(): if gdaltest.postgisrasterDriver is None: - return 'skip' + pytest.skip() ds = gdal.Open(gdaltest.postgisraster_connection_string + "table='small_world_outdb_constraint' mode=2 outdb_resolution=client_side") cs = [ds.GetRasterBand(i + 1).Checksum() for i in range(3)] - if cs != [30111, 32302, 40026]: - gdaltest.post_reason('fail') - print(cs) - return 'fail' - - return 'success' + assert cs == [30111, 32302, 40026] -def postgisraster_test_outdb_client_side_force_ireadblock(): +def test_postgisraster_test_outdb_client_side_force_ireadblock(): if gdaltest.postgisrasterDriver is None: - return 'skip' + pytest.skip() ds = gdal.Open(gdaltest.postgisraster_connection_string + "table='small_world_outdb_constraint' mode=2 outdb_resolution=client_side") with gdaltest.SetCacheMax(0): cs = [ds.GetRasterBand(i + 1).Checksum() for i in range(3)] - if cs != [30111, 32302, 40026]: - gdaltest.post_reason('fail') - print(cs) - return 'fail' + assert cs == [30111, 32302, 40026] - return 'success' - -def postgisraster_test_outdb_client_side_if_possible(): +def test_postgisraster_test_outdb_client_side_if_possible(): if gdaltest.postgisrasterDriver is None: - return 'skip' + pytest.skip() ds = gdal.Open(gdaltest.postgisraster_connection_string + "table='small_world_outdb_constraint' mode=2 outdb_resolution=client_side_if_possible") cs = [ds.GetRasterBand(i + 1).Checksum() for i in range(3)] - if cs != [30111, 32302, 40026]: - gdaltest.post_reason('fail') - print(cs) - return 'fail' - - return 'success' + assert cs == [30111, 32302, 40026] -def postgisraster_cleanup(): +def test_postgisraster_cleanup(): gdal.Unlink('data/small_world.tif.aux.xml') gdal.Unlink('data/utm.tif.aux.xml') - return 'success' - - -gdaltest_list = [ - postgisraster_init, - postgisraster_test_open_error1, - postgisraster_test_open_error2, - postgisraster_compare_utm, - postgisraster_compare_small_world, - postgisraster_test_utm_open, - postgisraster_test_small_world_open_b1, - postgisraster_test_small_world_open_b2, - postgisraster_test_small_world_open_b3, - postgisraster_test_create_copy_bad_conn_string, - postgisraster_test_create_copy_no_dbname, - postgisraster_test_create_copy_no_tablename, - postgisraster_test_create_copy_and_delete, - postgisraster_test_create_copy_and_delete_phases, - postgisraster_test_norid, - postgisraster_test_serial, - postgisraster_test_unique, - postgisraster_test_constraint, - postgisraster_test_constraint_with_spi, - postgisraster_test_outdb, - postgisraster_test_outdb_client_side, - postgisraster_test_outdb_client_side_force_ireadblock, - postgisraster_test_outdb_client_side_if_possible, - postgisraster_cleanup] - -if __name__ == '__main__': - - gdaltest.setup_run('WKTRASTER') - - gdaltest.run_tests(gdaltest_list) - - sys.exit(gdaltest.summarize()) + + diff --git a/autotest/gdrivers/prf.py b/autotest/gdrivers/prf.py index 03338af0339c..18d056238c2f 100755 --- a/autotest/gdrivers/prf.py +++ b/autotest/gdrivers/prf.py @@ -24,82 +24,62 @@ # DEALINGS IN THE SOFTWARE. ############################################################################### -import sys -sys.path.append('../pymod') import gdaltest from osgeo import gdal +import pytest ############################################################################### -def prf_1(): +def test_prf_1(): tst = gdaltest.GDALTest('prf', './PRF/ph.prf', 1, 43190) return tst.testOpen(check_gt=(1, 2, 3, -7, 5, 6)) -def prf_2(): +def test_prf_2(): ds = gdal.Open('./data/PRF/dem.x-dem') - if ds.RasterXSize != 4330: - gdaltest.post_reason('Invalid dataset width') - return 'fail' + assert ds.RasterXSize == 4330, 'Invalid dataset width' - if ds.RasterYSize != 4663: - gdaltest.post_reason('Invalid dataset height') - return 'fail' + assert ds.RasterYSize == 4663, 'Invalid dataset height' unittype = ds.GetRasterBand(1).GetUnitType() - if unittype != 'm': - gdaltest.post_reason('Failed to read elevation units from x-dem') - print(unittype) - return 'fail' + assert unittype == 'm', 'Failed to read elevation units from x-dem' datatype = ds.GetRasterBand(1).DataType - if datatype != gdal.GDT_Float32: - gdaltest.post_reason('Failed to read datatype') - return 'fail' + assert datatype == gdal.GDT_Float32, 'Failed to read datatype' expectedOvCount = 1 if ds.GetRasterBand(1).GetOverviewCount() != expectedOvCount: - gdaltest.post_reason('did not get expected number of overviews') print('Overview count must be %d' % expectedOvCount) print('But GetOverviewCount returned %d' % ds.GetRasterBand(1).GetOverviewCount()) - return 'fail' + pytest.fail('did not get expected number of overviews') overview = ds.GetRasterBand(1).GetOverview(0) - if overview.XSize != 1082: - gdaltest.post_reason('Invalid dataset width %d' % overview.XSize) - return 'fail' - if overview.YSize != 1165: - gdaltest.post_reason('Invalid dataset height %d' % overview.YSize) - return 'fail' + assert overview.XSize == 1082, ('Invalid dataset width %d' % overview.XSize) + assert overview.YSize == 1165, ('Invalid dataset height %d' % overview.YSize) ds = None - return 'success' - -def prf_3(): +def test_prf_3(): ds = gdal.Open('./data/PRF/ph.prf') expectedOvCount = 0 if ds.GetRasterBand(1).GetOverviewCount() != expectedOvCount: - gdaltest.post_reason('did not get expected number of overviews') print('Overview count must be %d' % expectedOvCount) print('But GetOverviewCount returned %d' % ds.GetRasterBand(1).GetOverviewCount()) - return 'fail' + pytest.fail('did not get expected number of overviews') ds = None - return 'success' - -def prf_4(): +def test_prf_4(): tst = gdaltest.GDALTest('prf', './PRF/dem.x-dem', 1, 0) return tst.testOpen(check_gt=(1.5, 1.0, 0.0, 9329.0, 0.0, -2.0)) @@ -108,17 +88,4 @@ def prf_4(): ############################################################################### -gdaltest_list = [ - prf_1, - prf_2, - prf_3, - prf_4 -] - -if __name__ == '__main__': - - gdaltest.setup_run('prf') - - gdaltest.run_tests(gdaltest_list) - sys.exit(gdaltest.summarize()) diff --git a/autotest/gdrivers/r.py b/autotest/gdrivers/r.py index a5f1b5e168bf..17e2257c4918 100755 --- a/autotest/gdrivers/r.py +++ b/autotest/gdrivers/r.py @@ -28,9 +28,7 @@ # DEALINGS IN THE SOFTWARE. ############################################################################### -import sys -sys.path.append('../pymod') import gdaltest @@ -38,7 +36,7 @@ # Perform simple read test on an ascii file. -def r_1(): +def test_r_1(): tst = gdaltest.GDALTest('R', 'r_test.asc', 2, 202) @@ -48,7 +46,7 @@ def r_1(): # Perform a simple read test on a binary (uncompressed) file. -def r_2(): +def test_r_2(): tst = gdaltest.GDALTest('R', 'r_test.rdb', 1, 202) return tst.testOpen() @@ -57,7 +55,7 @@ def r_2(): # Verify a simple createcopy operation with 16bit data. -def r_3(): +def test_r_3(): tst = gdaltest.GDALTest('R', 'byte.tif', 1, 4672, options=['ASCII=YES']) @@ -67,7 +65,7 @@ def r_3(): # Test creating a compressed binary stream and reading it back. -def r_4(): +def test_r_4(): tst = gdaltest.GDALTest('R', 'byte.tif', 1, 4672) return tst.testCreateCopy(new_filename='tmp/r_4.rda') @@ -75,16 +73,4 @@ def r_4(): ############################################################################### -gdaltest_list = [ - r_1, - r_2, - r_3, - r_4] -if __name__ == '__main__': - - gdaltest.setup_run('r') - - gdaltest.run_tests(gdaltest_list) - - sys.exit(gdaltest.summarize()) diff --git a/autotest/gdrivers/rasdaman.py b/autotest/gdrivers/rasdaman.py index 5b32473bd5f4..2d34da99eb6c 100755 --- a/autotest/gdrivers/rasdaman.py +++ b/autotest/gdrivers/rasdaman.py @@ -28,12 +28,11 @@ # DEALINGS IN THE SOFTWARE. ############################################################################### -import sys from osgeo import gdal -sys.path.append('../pymod') import gdaltest +import pytest # # The rasdaman DB must be created like this : @@ -46,10 +45,10 @@ # -def rasdaman_1(): +def test_rasdaman_1(): gdaltest.rasdamanDriver = gdal.GetDriverByName('RASDAMAN') if gdaltest.rasdamanDriver is None: - return 'skip' + pytest.skip() try: ds = gdal.Open("rasdaman:query='select a[$x_lo:$x_hi,$y_lo:$y_hi] from rgb as a'") @@ -60,48 +59,33 @@ def rasdaman_1(): gdaltest.rasdamanDriver = None if gdaltest.rasdamanDriver is None: - return 'skip' + pytest.skip() cs = ds.GetRasterBand(1).Checksum() - if cs != 61774: - gdaltest.post_reason('did not get expected checksum') - return 'fail' - - return 'success' + assert cs == 61774, 'did not get expected checksum' ############################################################################### # Test opening a non existing collection -def rasdaman_2(): +def test_rasdaman_2(): if gdaltest.rasdamanDriver is None: - return 'skip' + pytest.skip() ds = gdal.Open("rasdaman:query='select a[$x_lo:$x_hi,$y_lo:$y_hi] from notexisting as a'") - return 'success' if ds is None else 'fail' + assert ds is None ############################################################################### # Test syntax error -def rasdaman_3(): +def test_rasdaman_3(): if gdaltest.rasdamanDriver is None: - return 'skip' + pytest.skip() ds = gdal.Open("rasdaman:query='select'") - return 'success' if ds is None else 'fail' - - -gdaltest_list = [ - rasdaman_1, - rasdaman_2, - rasdaman_3] - -if __name__ == '__main__': + assert ds is None - gdaltest.setup_run('RASDAMAN') - gdaltest.run_tests(gdaltest_list) - sys.exit(gdaltest.summarize()) diff --git a/autotest/gdrivers/rasterlite.py b/autotest/gdrivers/rasterlite.py index de6f39c269d3..370baad9de1e 100755 --- a/autotest/gdrivers/rasterlite.py +++ b/autotest/gdrivers/rasterlite.py @@ -30,19 +30,18 @@ ############################################################################### import os -import sys from osgeo import gdal from osgeo import ogr -sys.path.append('../pymod') import gdaltest +import pytest ############################################################################### # Get the rasterlite driver -def rasterlite_1(): +def test_rasterlite_1(): gdaltest.rasterlite_drv = gdal.GetDriverByName('RASTERLITE') gdaltest.epsilon_drv = gdal.GetDriverByName('EPSILON') @@ -52,16 +51,14 @@ def rasterlite_1(): # w.r.t system/OS crashes, unless you know what you are doing. gdal.SetConfigOption('OGR_SQLITE_SYNCHRONOUS', 'OFF') - return 'success' - ############################################################################### # Test opening a rasterlite DB without overviews -def rasterlite_2(): +def test_rasterlite_2(): if gdaltest.rasterlite_drv is None: - return 'skip' + pytest.skip() # Test if SQLite3 supports rtrees try: @@ -78,186 +75,143 @@ def rasterlite_2(): pass if gdal.GetLastErrorMsg().find('rtree') != -1: gdaltest.rasterlite_drv = None - gdaltest.post_reason('Please upgrade your sqlite3 library to be able to read Rasterlite DBs (needs rtree support)!') - return 'skip' + pytest.skip('Please upgrade your sqlite3 library to be able to read Rasterlite DBs (needs rtree support)!') gdal.ErrorReset() ds = gdal.Open('data/rasterlite.sqlite') if ds is None: if gdal.GetLastErrorMsg().find('unsupported file format') != -1: gdaltest.rasterlite_drv = None - gdaltest.post_reason('Please upgrade your sqlite3 library to be able to read Rasterlite DBs!') - return 'skip' - return 'fail' + pytest.skip('Please upgrade your sqlite3 library to be able to read Rasterlite DBs!') + pytest.fail() - if ds.RasterCount != 3: - gdaltest.post_reason('expected 3 bands') - return 'fail' + assert ds.RasterCount == 3, 'expected 3 bands' - if ds.GetRasterBand(1).GetOverviewCount() != 0: - gdaltest.post_reason('did not expect overview') - return 'fail' + assert ds.GetRasterBand(1).GetOverviewCount() == 0, 'did not expect overview' cs = ds.GetRasterBand(1).Checksum() expected_cs = 11746 - if cs != expected_cs and cs != 11751: - gdaltest.post_reason('for band 1, cs = %d, different from expected_cs = %d' % (cs, expected_cs)) - return 'fail' + assert cs == expected_cs or cs == 11751, \ + ('for band 1, cs = %d, different from expected_cs = %d' % (cs, expected_cs)) cs = ds.GetRasterBand(2).Checksum() expected_cs = 19843 - if cs != expected_cs and cs != 20088 and cs != 20083: - gdaltest.post_reason('for band 2, cs = %d, different from expected_cs = %d' % (cs, expected_cs)) - return 'fail' + assert cs == expected_cs or cs == 20088 or cs == 20083, \ + ('for band 2, cs = %d, different from expected_cs = %d' % (cs, expected_cs)) cs = ds.GetRasterBand(3).Checksum() expected_cs = 48911 - if cs != expected_cs and cs != 47978: - gdaltest.post_reason('for band 3, cs = %d, different from expected_cs = %d' % (cs, expected_cs)) - return 'fail' + assert cs == expected_cs or cs == 47978, \ + ('for band 3, cs = %d, different from expected_cs = %d' % (cs, expected_cs)) - if ds.GetProjectionRef().find('WGS_1984') == -1: - gdaltest.post_reason('projection_ref = %s' % ds.GetProjectionRef()) - return 'fail' + assert ds.GetProjectionRef().find('WGS_1984') != -1, \ + ('projection_ref = %s' % ds.GetProjectionRef()) gt = ds.GetGeoTransform() expected_gt = (-180.0, 360. / ds.RasterXSize, 0.0, 90.0, 0.0, -180. / ds.RasterYSize) for i in range(6): - if abs(gt[i] - expected_gt[i]) > 1e-15: - print(gt) - print(expected_gt) - return 'fail' + assert abs(gt[i] - expected_gt[i]) <= 1e-15 ds = None - return 'success' - ############################################################################### # Test opening a rasterlite DB with overviews -def rasterlite_3(): +def test_rasterlite_3(): if gdaltest.rasterlite_drv is None: - return 'skip' + pytest.skip() ds = gdal.Open('RASTERLITE:data/rasterlite_pyramids.sqlite,table=test') - if ds.RasterCount != 3: - gdaltest.post_reason('expected 3 bands') - return 'fail' + assert ds.RasterCount == 3, 'expected 3 bands' - if ds.GetRasterBand(1).GetOverviewCount() != 1: - gdaltest.post_reason('expected 1 overview') - return 'fail' + assert ds.GetRasterBand(1).GetOverviewCount() == 1, 'expected 1 overview' cs = ds.GetRasterBand(1).GetOverview(0).Checksum() expected_cs = 59551 - if cs != expected_cs and cs != 59833: - gdaltest.post_reason('for overview of band 1, cs = %d, different from expected_cs = %d' % (cs, expected_cs)) - return 'fail' + assert cs == expected_cs or cs == 59833, \ + ('for overview of band 1, cs = %d, different from expected_cs = %d' % (cs, expected_cs)) cs = ds.GetRasterBand(2).GetOverview(0).Checksum() expected_cs = 59603 - if cs != expected_cs and cs != 59588: - gdaltest.post_reason('for overview of band 2, cs = %d, different from expected_cs = %d' % (cs, expected_cs)) - return 'fail' + assert cs == expected_cs or cs == 59588, \ + ('for overview of band 2, cs = %d, different from expected_cs = %d' % (cs, expected_cs)) cs = ds.GetRasterBand(3).GetOverview(0).Checksum() expected_cs = 42173 - if cs != expected_cs and cs != 42361: - gdaltest.post_reason('for overview of band 3, cs = %d, different from expected_cs = %d' % (cs, expected_cs)) - return 'fail' + assert cs == expected_cs or cs == 42361, \ + ('for overview of band 3, cs = %d, different from expected_cs = %d' % (cs, expected_cs)) ds = None - return 'success' - ############################################################################### # Test opening a rasterlite DB with color table and user-defined spatial extent -def rasterlite_4(): +def test_rasterlite_4(): if gdaltest.rasterlite_drv is None: - return 'skip' + pytest.skip() ds = gdal.Open('RASTERLITE:data/rasterlite_pct.sqlite,minx=0,miny=0,maxx=180,maxy=90') - if ds.RasterCount != 1: - gdaltest.post_reason('expected 1 band') - return 'fail' + assert ds.RasterCount == 1, 'expected 1 band' - if ds.RasterXSize != 169 or ds.RasterYSize != 85: - print(ds.RasterXSize) - print(ds.RasterYSize) - return 'fail' + assert ds.RasterXSize == 169 and ds.RasterYSize == 85 ct = ds.GetRasterBand(1).GetRasterColorTable() - if ct is None: - gdaltest.post_reason('did not get color table') - return 'fail' + assert ct is not None, 'did not get color table' cs = ds.GetRasterBand(1).Checksum() expected_cs = 36473 - if cs != expected_cs: - gdaltest.post_reason('for band 1, cs = %d, different from expected_cs = %d' % (cs, expected_cs)) - return 'fail' + assert cs == expected_cs, \ + ('for band 1, cs = %d, different from expected_cs = %d' % (cs, expected_cs)) ds = None - return 'success' - ############################################################################### # Test opening a rasterlite DB with color table and do color table expansion -def rasterlite_5(): +def test_rasterlite_5(): if gdaltest.rasterlite_drv is None: - return 'skip' + pytest.skip() ds = gdal.Open('RASTERLITE:data/rasterlite_pct.sqlite,bands=3') - if ds.RasterCount != 3: - gdaltest.post_reason('expected 3 bands') - return 'fail' + assert ds.RasterCount == 3, 'expected 3 bands' ct = ds.GetRasterBand(1).GetRasterColorTable() - if ct is not None: - gdaltest.post_reason('did not expect color table') - return 'fail' + assert ct is None, 'did not expect color table' cs = ds.GetRasterBand(1).Checksum() expected_cs = 506 - if cs != expected_cs: - gdaltest.post_reason('for band 1, cs = %d, different from expected_cs = %d' % (cs, expected_cs)) - return 'fail' + assert cs == expected_cs, \ + ('for band 1, cs = %d, different from expected_cs = %d' % (cs, expected_cs)) cs = ds.GetRasterBand(2).Checksum() expected_cs = 3842 - if cs != expected_cs: - gdaltest.post_reason('for band 2, cs = %d, different from expected_cs = %d' % (cs, expected_cs)) - return 'fail' + assert cs == expected_cs, \ + ('for band 2, cs = %d, different from expected_cs = %d' % (cs, expected_cs)) cs = ds.GetRasterBand(3).Checksum() expected_cs = 59282 - if cs != expected_cs: - gdaltest.post_reason('for band 3, cs = %d, different from expected_cs = %d' % (cs, expected_cs)) - return 'fail' + assert cs == expected_cs, \ + ('for band 3, cs = %d, different from expected_cs = %d' % (cs, expected_cs)) ds = None - return 'success' - ############################################################################### # Test CreateCopy() -def rasterlite_6(): +def test_rasterlite_6(): if gdaltest.rasterlite_drv is None: - return 'skip' + pytest.skip() # Test first if spatialite is available gdal.PushErrorHandler('CPLQuietErrorHandler') @@ -270,7 +224,7 @@ def rasterlite_6(): if sql_lyr is None: gdaltest.has_spatialite = False ogr_ds = None - return 'skip' + pytest.skip() gdaltest.has_spatialite = True ogr_ds.ReleaseResultSet(sql_lyr) @@ -279,108 +233,87 @@ def rasterlite_6(): # Test now CreateCopy() src_ds = gdal.Open('data/byte.tif') ds = gdal.GetDriverByName('RASTERLITE').CreateCopy('RASTERLITE:tmp/byte.sqlite,table=byte', src_ds) - if ds is None: - return 'fail' + assert ds is not None - if ds.GetRasterBand(1).Checksum() != src_ds.GetRasterBand(1).Checksum(): - gdaltest.post_reason('Wrong checksum') - print(ds.GetRasterBand(1).Checksum()) - return 'fail' + assert ds.GetRasterBand(1).Checksum() == src_ds.GetRasterBand(1).Checksum(), \ + 'Wrong checksum' gt = ds.GetGeoTransform() expected_gt = src_ds.GetGeoTransform() for i in range(6): - if abs(gt[i] - expected_gt[i] > 1e-5): - gdaltest.post_reason('Expected : %s\nGot : %s' % (expected_gt, gt)) - return 'fail' + assert not abs(gt[i] - expected_gt[i] > 1e-5), \ + ('Expected : %s\nGot : %s' % (expected_gt, gt)) - if ds.GetProjectionRef().find('NAD27 / UTM zone 11N') == -1: - gdaltest.post_reason('Wrong SRS') - return 'fail' + assert ds.GetProjectionRef().find('NAD27 / UTM zone 11N') != -1, 'Wrong SRS' src_ds = None ds = None - return 'success' - ############################################################################### # Test BuildOverviews() -def rasterlite_7(): +def test_rasterlite_7(): if gdaltest.rasterlite_drv is None: - return 'skip' + pytest.skip() if gdaltest.has_spatialite is False: - return 'skip' + pytest.skip() ds = gdal.Open('tmp/byte.sqlite', gdal.GA_Update) # Resampling method is not taken into account ds.BuildOverviews('NEAREST', overviewlist=[2, 4]) - if ds.GetRasterBand(1).GetOverview(0).Checksum() != 1192: - gdaltest.post_reason('Wrong checksum for overview 0') - print(ds.GetRasterBand(1).GetOverview(0).Checksum()) - return 'fail' + assert ds.GetRasterBand(1).GetOverview(0).Checksum() == 1192, \ + 'Wrong checksum for overview 0' - if ds.GetRasterBand(1).GetOverview(1).Checksum() != 233: - gdaltest.post_reason('Wrong checksum for overview 1') - print(ds.GetRasterBand(1).GetOverview(1).Checksum()) - return 'fail' + assert ds.GetRasterBand(1).GetOverview(1).Checksum() == 233, \ + 'Wrong checksum for overview 1' # Reopen and test ds = None ds = gdal.Open('tmp/byte.sqlite') - if ds.GetRasterBand(1).GetOverview(0).Checksum() != 1192: - gdaltest.post_reason('Wrong checksum for overview 0') - print(ds.GetRasterBand(1).GetOverview(0).Checksum()) - return 'fail' + assert ds.GetRasterBand(1).GetOverview(0).Checksum() == 1192, \ + 'Wrong checksum for overview 0' - if ds.GetRasterBand(1).GetOverview(1).Checksum() != 233: - gdaltest.post_reason('Wrong checksum for overview 1') - print(ds.GetRasterBand(1).GetOverview(1).Checksum()) - return 'fail' - - return 'success' + assert ds.GetRasterBand(1).GetOverview(1).Checksum() == 233, \ + 'Wrong checksum for overview 1' ############################################################################### # Test CleanOverviews() -def rasterlite_8(): +def test_rasterlite_8(): if gdaltest.rasterlite_drv is None: - return 'skip' + pytest.skip() if gdaltest.has_spatialite is False: - return 'skip' + pytest.skip() ds = gdal.Open('tmp/byte.sqlite', gdal.GA_Update) ds.BuildOverviews(overviewlist=[]) - if ds.GetRasterBand(1).GetOverviewCount() != 0: - return 'fail' - - return 'success' + assert ds.GetRasterBand(1).GetOverviewCount() == 0 ############################################################################### # Create a rasterlite dataset with EPSILON tiles -def rasterlite_9(): +def test_rasterlite_9(): if gdaltest.rasterlite_drv is None: - return 'skip' + pytest.skip() if gdaltest.has_spatialite is False: - return 'skip' + pytest.skip() if gdaltest.epsilon_drv is None: - return 'skip' + pytest.skip() tst = gdaltest.GDALTest('RASTERLITE', 'byte.tif', 1, 4866, options=['DRIVER=EPSILON']) @@ -390,16 +323,16 @@ def rasterlite_9(): # Create a rasterlite dataset with EPSILON tiles -def rasterlite_10(): +def test_rasterlite_10(): if gdaltest.rasterlite_drv is None: - return 'skip' + pytest.skip() if gdaltest.has_spatialite is False: - return 'skip' + pytest.skip() if gdaltest.epsilon_drv is None: - return 'skip' + pytest.skip() tst = gdaltest.GDALTest('RASTERLITE', 'rgbsmall.tif', 1, 23189, options=['DRIVER=EPSILON']) @@ -409,13 +342,13 @@ def rasterlite_10(): # Test BuildOverviews() with AVERAGE resampling -def rasterlite_11(): +def test_rasterlite_11(): if gdaltest.rasterlite_drv is None: - return 'skip' + pytest.skip() if gdaltest.has_spatialite is False: - return 'skip' + pytest.skip() ds = gdal.Open('tmp/byte.sqlite', gdal.GA_Update) @@ -428,65 +361,53 @@ def rasterlite_11(): ds = None ds = gdal.Open('tmp/byte.sqlite') - if ds.GetRasterBand(1).GetOverview(0).Checksum() != 1152: - gdaltest.post_reason('Wrong checksum for overview 0') - print(ds.GetRasterBand(1).GetOverview(0).Checksum()) - return 'fail' + assert ds.GetRasterBand(1).GetOverview(0).Checksum() == 1152, \ + 'Wrong checksum for overview 0' - if ds.GetRasterBand(1).GetOverview(1).Checksum() != 215: - gdaltest.post_reason('Wrong checksum for overview 1') - print(ds.GetRasterBand(1).GetOverview(1).Checksum()) - return 'fail' - - return 'success' + assert ds.GetRasterBand(1).GetOverview(1).Checksum() == 215, \ + 'Wrong checksum for overview 1' ############################################################################### # Test opening a .rasterlite file -def rasterlite_12(): +def test_rasterlite_12(): if gdaltest.rasterlite_drv is None: - return 'skip' + pytest.skip() if gdaltest.has_spatialite is False: - return 'skip' + pytest.skip() ds = gdal.Open('data/byte.rasterlite') - if ds.GetRasterBand(1).Checksum() != 4672: - gdaltest.post_reason('validation failed') - return 'fail' - return 'success' + assert ds.GetRasterBand(1).Checksum() == 4672, 'validation failed' ############################################################################### # Test opening a .rasterlite.sql file -def rasterlite_13(): +def test_rasterlite_13(): if gdaltest.rasterlite_drv is None: - return 'skip' + pytest.skip() if gdaltest.has_spatialite is False: - return 'skip' + pytest.skip() if gdaltest.rasterlite_drv.GetMetadataItem("ENABLE_SQL_SQLITE_FORMAT") != 'YES': - return 'skip' + pytest.skip() ds = gdal.Open('data/byte.rasterlite.sql') - if ds.GetRasterBand(1).Checksum() != 4672: - gdaltest.post_reason('validation failed') - return 'fail' - return 'success' + assert ds.GetRasterBand(1).Checksum() == 4672, 'validation failed' ############################################################################### # Cleanup -def rasterlite_cleanup(): +def test_rasterlite_cleanup(): if gdaltest.rasterlite_drv is None: - return 'skip' + pytest.skip() try: os.remove('tmp/spatialite_test.db') @@ -508,29 +429,6 @@ def rasterlite_cleanup(): except OSError: pass - return 'success' - - -gdaltest_list = [ - rasterlite_1, - rasterlite_2, - rasterlite_3, - rasterlite_4, - rasterlite_5, - rasterlite_6, - rasterlite_7, - rasterlite_8, - rasterlite_9, - rasterlite_10, - rasterlite_11, - rasterlite_12, - rasterlite_13, - rasterlite_cleanup] - -if __name__ == '__main__': - - gdaltest.setup_run('rasterlite') + - gdaltest.run_tests(gdaltest_list) - sys.exit(gdaltest.summarize()) diff --git a/autotest/gdrivers/rda.py b/autotest/gdrivers/rda.py index 4a857ff71619..7831308c736b 100755 --- a/autotest/gdrivers/rda.py +++ b/autotest/gdrivers/rda.py @@ -31,21 +31,20 @@ import os import struct -import sys import json -sys.path.append('../pymod') from osgeo import gdal import gdaltest import webserver +import pytest ############################################################################### # Find RDA driver -def rda_test_presence(): +def test_rda_test_presence(): gdaltest.rda_drv = gdal.GetDriverByName('RDA') @@ -53,70 +52,57 @@ def rda_test_presence(): gdal.SetConfigOption('GDBX_CONFIG_FILE', '') if gdaltest.rda_drv is None: - 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 rda_bad_connection_string(): +def test_rda_bad_connection_string(): if gdaltest.rda_drv is None: - return 'skip' + pytest.skip() # Bad json with gdaltest.error_handler(): ds = gdal.Open('graph-id node-id') - if ds is not None: - gdaltest.post_reason('fail') - return 'fail' + assert ds is None # Missing graph-id with gdaltest.error_handler(): ds = gdal.Open('"graph-id node-id"') - if ds is not None: - gdaltest.post_reason('fail') - return 'fail' + assert ds is None # Missing node-id with gdaltest.error_handler(): ds = gdal.Open('{"graph-id": "node-id"}') - if ds is not None: - gdaltest.post_reason('fail') - return 'fail' - - return 'success' + assert ds is None ############################################################################### -def rda_missing_credentials(): +def test_rda_missing_credentials(): if gdaltest.rda_drv is None: - return 'skip' + pytest.skip() with gdaltest.error_handler(): ds = gdal.Open('{"graph-id":"foo","node-id":"bar"}') - if ds is not None: - gdaltest.post_reason('fail') - return 'fail' - - return 'success' + assert ds is None ############################################################################### -def rda_failed_authentication(): +def test_rda_failed_authentication(): if gdaltest.rda_drv is None: - return 'skip' + pytest.skip() if gdaltest.webserver_port == 0: - return 'skip' + pytest.skip() # invalid characters in env variable with gdaltest.config_options({'GBDX_AUTH_URL': '\\', @@ -125,9 +111,7 @@ def rda_failed_authentication(): 'GBDX_PASSWORD': 'password'}): with gdaltest.error_handler(): ds = gdal.Open('{"graph-id":"foo","node-id":"bar"}') - if ds is not None: - gdaltest.post_reason('fail') - return 'fail' + assert ds is None # invalid URL with gdaltest.config_options({'GBDX_AUTH_URL': '/vsimem/auth_url', @@ -135,9 +119,7 @@ def rda_failed_authentication(): 'GBDX_PASSWORD': 'password'}): with gdaltest.error_handler(): ds = gdal.Open('{"graph-id":"foo","node-id":"bar"}') - if ds is not None: - gdaltest.post_reason('fail') - return 'fail' + assert ds is None # 404 handler = webserver.SequentialHandler() @@ -148,9 +130,7 @@ def rda_failed_authentication(): 'GBDX_PASSWORD': 'password'}): with gdaltest.error_handler(): ds = gdal.Open('{"graph-id":"foo","node-id":"bar"}') - if ds is not None: - gdaltest.post_reason('fail') - return 'fail' + assert ds is None # Invalid json handler = webserver.SequentialHandler() @@ -161,9 +141,7 @@ def rda_failed_authentication(): 'GBDX_PASSWORD': 'password'}): with gdaltest.error_handler(): ds = gdal.Open('{"graph-id":"foo","node-id":"bar"}') - if ds is not None: - gdaltest.post_reason('fail') - return 'fail' + assert ds is None # No access token handler = webserver.SequentialHandler() @@ -174,21 +152,17 @@ def rda_failed_authentication(): 'GBDX_PASSWORD': 'password'}): with gdaltest.error_handler(): ds = gdal.Open('{"graph-id":"foo","node-id":"bar"}') - if ds is not None: - gdaltest.post_reason('fail') - return 'fail' - - return 'success' + assert ds is None ############################################################################### -def rda_error_metadata(): +def test_rda_error_metadata(): if gdaltest.rda_drv is None: - return 'skip' + pytest.skip() if gdaltest.webserver_port == 0: - return 'skip' + pytest.skip() # 404 handler = webserver.SequentialHandler() @@ -202,9 +176,7 @@ def rda_error_metadata(): 'GBDX_PASSWORD': 'password'}): with gdaltest.error_handler(): ds = gdal.Open('{"graph-id":"foo","node-id":"bar"}') - if ds is not None: - gdaltest.post_reason('fail') - return 'fail' + assert ds is None # 404 with payload handler = webserver.SequentialHandler() @@ -218,9 +190,7 @@ def rda_error_metadata(): 'GBDX_PASSWORD': 'password'}): with gdaltest.error_handler(): ds = gdal.Open('{"graph-id":"foo","node-id":"bar"}') - if ds is not None: - gdaltest.post_reason('fail') - return 'fail' + assert ds is None # invalid json handler = webserver.SequentialHandler() @@ -234,9 +204,7 @@ def rda_error_metadata(): 'GBDX_PASSWORD': 'password'}): with gdaltest.error_handler(): ds = gdal.Open('{"graph-id":"foo","node-id":"bar"}') - if ds is not None: - gdaltest.post_reason('fail') - return 'fail' + assert ds is None # a lot of missing elements handler = webserver.SequentialHandler() @@ -248,9 +216,7 @@ def rda_error_metadata(): 'GBDX_PASSWORD': 'password'}): with gdaltest.error_handler(): ds = gdal.Open('{"graph-id":"foo","node-id":"bar"}') - if ds is not None: - gdaltest.post_reason('fail') - return 'fail' + assert ds is None # Bad dataType handler = webserver.SequentialHandler() @@ -285,9 +251,7 @@ def rda_error_metadata(): 'GBDX_PASSWORD': 'password'}): with gdaltest.error_handler(): ds = gdal.Open('{"graph-id":"foo","node-id":"bar"}') - if ds is not None: - gdaltest.post_reason('fail') - return 'fail' + assert ds is None # Huge numBands handler = webserver.SequentialHandler() @@ -322,9 +286,7 @@ def rda_error_metadata(): 'GBDX_PASSWORD': 'password'}): with gdaltest.error_handler(): ds = gdal.Open('{"graph-id":"foo","node-id":"bar"}') - if ds is not None: - gdaltest.post_reason('fail') - return 'fail' + assert ds is None # Invalid dataset dimensions handler = webserver.SequentialHandler() @@ -359,21 +321,17 @@ def rda_error_metadata(): 'GBDX_PASSWORD': 'password'}): with gdaltest.error_handler(): ds = gdal.Open('{"graph-id":"foo","node-id":"bar"}') - if ds is not None: - gdaltest.post_reason('fail') - return 'fail' - - return 'success' + assert ds is None ############################################################################### -def rda_graph_nominal(): +def test_rda_graph_nominal(): if gdaltest.rda_drv is None: - return 'skip' + pytest.skip() if gdaltest.webserver_port == 0: - return 'skip' + pytest.skip() handler = webserver.SequentialHandler() metadata_json = {"imageMetadata": { @@ -420,18 +378,10 @@ def rda_graph_nominal(): with webserver.install_http_handler(handler): with gdaltest.config_options(config_options): ds = gdal.Open('{"graph-id":"foo","node-id":"bar","options":{"delete-on-close":false}}') - if ds is None: - gdaltest.post_reason('fail') - return 'fail' - if ds.RasterCount != 3: - gdaltest.post_reason('fail') - return 'fail' - if ds.RasterXSize != 320: - gdaltest.post_reason('fail') - return 'fail' - if ds.RasterYSize != 300: - gdaltest.post_reason('fail') - return 'fail' + assert ds is not None + assert ds.RasterCount == 3 + assert ds.RasterXSize == 320 + assert ds.RasterYSize == 300 expected_md = { 'SENSOR_NAME': 'SENSOR_NAME', 'CLOUD_COVER': '1.2', @@ -444,17 +394,10 @@ def rda_graph_nominal(): 'SAT_ELEVATION': '5.2' } got_md = ds.GetMetadata() - if got_md != expected_md: - gdaltest.post_reason('fail') - print(got_md) - return 'fail' - if ds.GetRasterBand(1).GetColorInterpretation() != gdal.GCI_RedBand: - gdaltest.post_reason('fail') - return 'fail' - - if ds.GetProjectionRef() != '': - gdaltest.post_reason('fail') - return 'fail' + assert got_md == expected_md + assert ds.GetRasterBand(1).GetColorInterpretation() == gdal.GCI_RedBand + + assert ds.GetProjectionRef() == '' ds = None @@ -464,18 +407,10 @@ def rda_graph_nominal(): with open('tmp/rda_test1.dgrda', "w") as fd: fd.write('{"graph-id":"foo","node-id":"bar","options":{"delete-on-close":false}}') ds = gdal.Open('tmp/rda_test1.dgrda') - if ds is None: - gdaltest.post_reason('fail') - return 'fail' - if ds.RasterCount != 3: - gdaltest.post_reason('fail') - return 'fail' - if ds.RasterXSize != 320: - gdaltest.post_reason('fail') - return 'fail' - if ds.RasterYSize != 300: - gdaltest.post_reason('fail') - return 'fail' + assert ds is not None + assert ds.RasterCount == 3 + assert ds.RasterXSize == 320 + assert ds.RasterYSize == 300 expected_md = { 'SENSOR_NAME': 'SENSOR_NAME', 'CLOUD_COVER': '1.2', @@ -488,17 +423,10 @@ def rda_graph_nominal(): 'SAT_ELEVATION': '5.2' } got_md = ds.GetMetadata() - if got_md != expected_md: - gdaltest.post_reason('fail') - print(got_md) - return 'fail' - if ds.GetRasterBand(1).GetColorInterpretation() != gdal.GCI_RedBand: - gdaltest.post_reason('fail') - return 'fail' - - if ds.GetProjectionRef() != '': - gdaltest.post_reason('fail') - return 'fail' + assert got_md == expected_md + assert ds.GetRasterBand(1).GetColorInterpretation() == gdal.GCI_RedBand + + assert ds.GetProjectionRef() == '' try: os.remove('tmp/rda_test1.dgrda') @@ -509,12 +437,8 @@ def rda_graph_nominal(): # Retry without any network setup to test caching with gdaltest.config_options(config_options): ds = gdal.Open('{"graph-id":"foo","node-id":"bar","options":{"delete-on-close":false}}') - if ds is None: - gdaltest.post_reason('fail') - return 'fail' - if ds.RasterCount != 3: - gdaltest.post_reason('fail') - return 'fail' + assert ds is not None + assert ds.RasterCount == 3 gdal.RmdirRecursive('/vsimem/cache_dir') @@ -527,18 +451,11 @@ def rda_graph_nominal(): with webserver.install_http_handler(handler): with gdaltest.config_options(config_options): ds = gdal.Open('{"graph-id":"foo","node-id":"bar","options":{"delete-on-close":false}}') - if ds is None: - gdaltest.post_reason('fail') - return 'fail' - if ds.GetProjectionRef().find('32631') < 0: - gdaltest.post_reason('fail') - return 'fail' + assert ds is not None + assert ds.GetProjectionRef().find('32631') >= 0 got_gt = ds.GetGeoTransform() - if got_gt != (125.0, 1.0, 0.0, 462.0, 0.0, 2.0): - gdaltest.post_reason('fail') - print(got_gt) - return 'fail' + assert got_gt == (125.0, 1.0, 0.0, 462.0, 0.0, 2.0) ds = None @@ -546,10 +463,7 @@ def rda_graph_nominal(): with gdaltest.config_options(config_options): ds = gdal.Open('{"graph-id":"foo","node-id":"bar","options":{"delete-on-close":false}}') got_gt = ds.GetGeoTransform() - if got_gt != (125.0, 1.0, 0.0, 462.0, 0.0, 2.0): - gdaltest.post_reason('fail') - print(got_gt) - return 'fail' + assert got_gt == (125.0, 1.0, 0.0, 462.0, 0.0, 2.0) gdal.RmdirRecursive('/vsimem/cache_dir') @@ -562,12 +476,8 @@ def rda_graph_nominal(): with webserver.install_http_handler(handler): with gdaltest.config_options(config_options): ds = gdal.Open('{"graph-id":"foo","node-id":"bar","options":{"delete-on-close":false}}') - if ds is None: - gdaltest.post_reason('fail') - return 'fail' - if ds.GetMetadata('RPC') != {}: - gdaltest.post_reason('fail') - return 'fail' + assert ds is not None + assert ds.GetMetadata('RPC') == {} gdal.RmdirRecursive('/vsimem/cache_dir') @@ -582,12 +492,8 @@ def rda_graph_nominal(): with webserver.install_http_handler(handler): with gdaltest.config_options(config_options): ds = gdal.Open('{"graph-id":"foo","node-id":"bar","options":{"delete-on-close":false}}') - if ds is None: - gdaltest.post_reason('fail') - return 'fail' - if ds.GetMetadata('RPC') != {}: - gdaltest.post_reason('fail') - return 'fail' + assert ds is not None + assert ds.GetMetadata('RPC') == {} tile_ds = gdal.GetDriverByName('GTiff').Create('/vsimem/tile_00.tif', 256, 256, 3) tile_ds.GetRasterBand(1).Fill(255) @@ -636,44 +542,26 @@ def rda_graph_nominal(): handler.add('GET', '/rda_api/tile/foo/bar/1/1.tif', 200, {}, tile11_data) with webserver.install_http_handler(handler): cs = [ds.GetRasterBand(i + 1).Checksum() for i in range(3)] - if cs != [54287, 50451, 21110]: - gdaltest.post_reason('fail') - print(cs) - return 'fail' + assert cs == [54287, 50451, 21110] # Retry without any network setup to test caching with gdaltest.config_options(config_options): ds = gdal.Open('{"graph-id":"foo","node-id":"bar","options":{"delete-on-close":false}}') cs = [ds.GetRasterBand(i + 1).Checksum() for i in range(3)] - if cs != [54287, 50451, 21110]: - gdaltest.post_reason('fail') - print(cs) - return 'fail' + assert cs == [54287, 50451, 21110] data = struct.unpack('B' * (320 * 300 * 3), ds.ReadRaster()) - if data[0] != 255: - gdaltest.post_reason('fail') - return 'fail' + assert data[0] == 255 - if data[0 + 320 * 300] != 250: - gdaltest.post_reason('fail') - return 'fail' + assert data[0 + 320 * 300] == 250 - if data[0 + 320 * 300 * 2] != 245: - gdaltest.post_reason('fail') - return 'fail' + assert data[0 + 320 * 300 * 2] == 245 - if data[319] != 240: - gdaltest.post_reason('fail') - return 'fail' + assert data[319] == 240 - if data[320 * 299] != 225: - gdaltest.post_reason('fail') - return 'fail' + assert data[320 * 299] == 225 - if data[320 * 299 + 319] != 210: - gdaltest.post_reason('fail') - return 'fail' + assert data[320 * 299 + 319] == 210 ds = None @@ -727,21 +615,15 @@ def rda_graph_nominal(): data = ds.GetRasterBand(1).ReadBlock(0, 0) data = struct.unpack('B' * (256 * 256), data) - if data[0] != 255: - gdaltest.post_reason('fail') - return 'fail' - if data[256 * (256 - 2)] != 225: - gdaltest.post_reason('fail') - return 'fail' + assert data[0] == 255 + assert data[256 * (256 - 2)] == 225 # Try IReadBlock() when data for other bands is already cached ds.GetRasterBand(1).FlushCache() data = ds.GetRasterBand(1).ReadBlock(0, 0) data = struct.unpack('B' * (256 * 256), data) - if data[0] != 255: - gdaltest.post_reason('fail') - return 'fail' + assert data[0] == 255 gdal.RmdirRecursive('/vsimem/cache_dir') @@ -756,23 +638,19 @@ def rda_graph_nominal(): ds = gdal.Open('{"graph-id":"foo","node-id":"bar","options":{"delete-on-close":false}}') with gdaltest.error_handler(): data = ds.GetRasterBand(1).ReadBlock(0, 0) - if data is not None: - gdaltest.post_reason('fail') - return 'fail' + assert data is None gdal.RmdirRecursive('/vsimem/cache_dir') - return 'success' - ############################################################################### -def rda_template_nominal(): +def test_rda_template_nominal(): if gdaltest.rda_drv is None: - return 'skip' + pytest.skip() if gdaltest.webserver_port == 0: - return 'skip' + pytest.skip() handler = webserver.SequentialHandler() metadata_json = {"imageMetadata": { @@ -811,33 +689,19 @@ def rda_template_nominal(): with webserver.install_http_handler(handler): with gdaltest.config_options(config_options): ds = gdal.Open('{"template-id": "foo","params": [{"nodeId": "bar"}],"options":{"delete-on-close":false}}') - if ds is None: - gdaltest.post_reason('fail') - return 'fail' - if ds.RasterCount != 3: - gdaltest.post_reason('fail') - return 'fail' - if ds.RasterXSize != 320: - gdaltest.post_reason('fail') - return 'fail' - if ds.RasterYSize != 300: - gdaltest.post_reason('fail') - return 'fail' - if ds.GetProjectionRef() != '': - gdaltest.post_reason('fail') - return 'fail' + assert ds is not None + assert ds.RasterCount == 3 + assert ds.RasterXSize == 320 + assert ds.RasterYSize == 300 + assert ds.GetProjectionRef() == '' ds = None # Retry without any network setup to test caching with gdaltest.config_options(config_options): ds = gdal.Open('{"template-id": "foo","params": [{"nodeId": "bar"}],"options":{"delete-on-close":false}}') - if ds is None: - gdaltest.post_reason('fail') - return 'fail' - if ds.RasterCount != 3: - gdaltest.post_reason('fail') - return 'fail' + assert ds is not None + assert ds.RasterCount == 3 gdal.RmdirRecursive('/vsimem/cache_dir') @@ -850,18 +714,11 @@ def rda_template_nominal(): with webserver.install_http_handler(handler): with gdaltest.config_options(config_options): ds = gdal.Open('{"template-id": "foo","params": [{"nodeId": "bar"}],"options":{"delete-on-close":false}}') - if ds is None: - gdaltest.post_reason('fail') - return 'fail' - if ds.GetProjectionRef().find('32631') < 0: - gdaltest.post_reason('fail') - return 'fail' + assert ds is not None + assert ds.GetProjectionRef().find('32631') >= 0 got_gt = ds.GetGeoTransform() - if got_gt != (125.0, 1.0, 0.0, 462.0, 0.0, 2.0): - gdaltest.post_reason('fail') - print(got_gt) - return 'fail' + assert got_gt == (125.0, 1.0, 0.0, 462.0, 0.0, 2.0) ds = None @@ -869,10 +726,7 @@ def rda_template_nominal(): with gdaltest.config_options(config_options): ds = gdal.Open('{"template-id": "foo","params": [{"nodeId": "bar"}],"options":{"delete-on-close":false}}') got_gt = ds.GetGeoTransform() - if got_gt != (125.0, 1.0, 0.0, 462.0, 0.0, 2.0): - gdaltest.post_reason('fail') - print(got_gt) - return 'fail' + assert got_gt == (125.0, 1.0, 0.0, 462.0, 0.0, 2.0) gdal.RmdirRecursive('/vsimem/cache_dir') @@ -928,91 +782,39 @@ def rda_template_nominal(): ds = gdal.Open('{"template-id": "foo","params": [{"nodeId": "bar"}],"options":{"delete-on-close":false}}') cs = [ds.GetRasterBand(i + 1).Checksum() for i in range(3)] - if cs != [54287, 50451, 21110]: - gdaltest.post_reason('fail') - print(cs) - return 'fail' + assert cs == [54287, 50451, 21110] # Retry without any network setup to test caching with gdaltest.config_options(config_options): ds = gdal.Open('{"template-id": "foo","params": [{"nodeId": "bar"}],"options":{"delete-on-close":false}}') cs = [ds.GetRasterBand(i + 1).Checksum() for i in range(3)] - if cs != [54287, 50451, 21110]: - gdaltest.post_reason('fail') - print(cs) - return 'fail' + assert cs == [54287, 50451, 21110] data = struct.unpack('B' * (320 * 300 * 3), ds.ReadRaster()) - if data[0] != 255: - gdaltest.post_reason('fail') - return 'fail' + assert data[0] == 255 - if data[0 + 320 * 300] != 250: - gdaltest.post_reason('fail') - return 'fail' + assert data[0 + 320 * 300] == 250 - if data[0 + 320 * 300 * 2] != 245: - gdaltest.post_reason('fail') - return 'fail' + assert data[0 + 320 * 300 * 2] == 245 - if data[319] != 240: - gdaltest.post_reason('fail') - return 'fail' + assert data[319] == 240 - if data[320 * 299] != 225: - gdaltest.post_reason('fail') - return 'fail' + assert data[320 * 299] == 225 - if data[320 * 299 + 319] != 210: - gdaltest.post_reason('fail') - return 'fail' + assert data[320 * 299 + 319] == 210 ds = None gdal.RmdirRecursive('/vsimem/cache_dir') - # - # # Test ReadBlock directly - # handler = webserver.SequentialHandler() - # handler.add('POST', '/auth_url', 200, {}, '{"access_token": "token", "expires_in": 3600}') - # handler.add('GET', '/rda_api/metadata/foo/bar/metadata.json', 200, {}, json.dumps(metadata_json)) - # handler.add('GET', '/rda_api/tile/foo/bar/0/0.tif', 200, {}, tile00_data) - # handler.add('GET', '/rda_api/tile/foo/bar/1/0.tif', 200, {}, tile01_data) - # handler.add('GET', '/rda_api/tile/foo/bar/0/1.tif', 200, {}, tile10_data) - # handler.add('GET', '/rda_api/tile/foo/bar/1/1.tif', 200, {}, tile11_data) - # with webserver.install_http_handler(handler): - # with gdaltest.config_options(config_options): - # ds = gdal.Open('{"graph-id":"foo","node-id":"bar","options":{"delete-on-close":false}}') - # data = ds.GetRasterBand(1).ReadBlock(0,0) - # - # data = struct.unpack('B' * (256 * 256), data) - # if data[0] != 255: - # gdaltest.post_reason('fail') - # return 'fail' - # if data[256*(256-2)] != 225: - # gdaltest.post_reason('fail') - # return 'fail' - # - # # Try IReadBlock() when data for other bands is already cached - # ds.GetRasterBand(1).FlushCache() - # data = ds.GetRasterBand(1).ReadBlock(0,0) - # data = struct.unpack('B' * (256 * 256), data) - # if data[0] != 255: - # gdaltest.post_reason('fail') - # return 'fail' - # - # gdal.RmdirRecursive('/vsimem/cache_dir') - - return 'success' - ############################################################################### -def rda_template_image_reference_nominal(): +def test_rda_template_image_reference_nominal(): if gdaltest.rda_drv is None: - return 'skip' + pytest.skip() if gdaltest.webserver_port == 0: - return 'skip' + pytest.skip() handler = webserver.SequentialHandler() metadata_json = {"imageMetadata": { @@ -1051,33 +853,19 @@ def rda_template_image_reference_nominal(): with webserver.install_http_handler(handler): with gdaltest.config_options(config_options): ds = gdal.Open('{"templateId": "foo", "nodeId": "bar", "parameters": {"p1": "baz"},"options":{"delete-on-close":false}}') - if ds is None: - gdaltest.post_reason('fail') - return 'fail' - if ds.RasterCount != 3: - gdaltest.post_reason('fail') - return 'fail' - if ds.RasterXSize != 320: - gdaltest.post_reason('fail') - return 'fail' - if ds.RasterYSize != 300: - gdaltest.post_reason('fail') - return 'fail' - if ds.GetProjectionRef() != '': - gdaltest.post_reason('fail') - return 'fail' + assert ds is not None + assert ds.RasterCount == 3 + assert ds.RasterXSize == 320 + assert ds.RasterYSize == 300 + assert ds.GetProjectionRef() == '' ds = None # Retry without any network setup to test caching with gdaltest.config_options(config_options): ds = gdal.Open('{"templateId": "foo", "nodeId": "bar", "parameters": {"p1": "baz"},"options":{"delete-on-close":false}}') - if ds is None: - gdaltest.post_reason('fail') - return 'fail' - if ds.RasterCount != 3: - gdaltest.post_reason('fail') - return 'fail' + assert ds is not None + assert ds.RasterCount == 3 gdal.RmdirRecursive('/vsimem/cache_dir') @@ -1090,18 +878,11 @@ def rda_template_image_reference_nominal(): with webserver.install_http_handler(handler): with gdaltest.config_options(config_options): ds = gdal.Open('{"templateId": "foo", "nodeId": "bar", "parameters": {"p1": "baz"},"options":{"delete-on-close":false}}') - if ds is None: - gdaltest.post_reason('fail') - return 'fail' - if ds.GetProjectionRef().find('32631') < 0: - gdaltest.post_reason('fail') - return 'fail' + assert ds is not None + assert ds.GetProjectionRef().find('32631') >= 0 got_gt = ds.GetGeoTransform() - if got_gt != (125.0, 1.0, 0.0, 462.0, 0.0, 2.0): - gdaltest.post_reason('fail') - print(got_gt) - return 'fail' + assert got_gt == (125.0, 1.0, 0.0, 462.0, 0.0, 2.0) ds = None @@ -1109,10 +890,7 @@ def rda_template_image_reference_nominal(): with gdaltest.config_options(config_options): ds = gdal.Open('{"templateId": "foo", "nodeId": "bar", "parameters": {"p1": "baz"},"options":{"delete-on-close":false}}') got_gt = ds.GetGeoTransform() - if got_gt != (125.0, 1.0, 0.0, 462.0, 0.0, 2.0): - gdaltest.post_reason('fail') - print(got_gt) - return 'fail' + assert got_gt == (125.0, 1.0, 0.0, 462.0, 0.0, 2.0) gdal.RmdirRecursive('/vsimem/cache_dir') @@ -1168,58 +946,38 @@ def rda_template_image_reference_nominal(): ds = gdal.Open('{"templateId": "foo", "nodeId": "bar", "parameters": {"p1": "baz"},"options":{"delete-on-close":false}}') cs = [ds.GetRasterBand(i + 1).Checksum() for i in range(3)] - if cs != [54287, 50451, 21110]: - gdaltest.post_reason('fail') - print(cs) - return 'fail' + assert cs == [54287, 50451, 21110] # Retry without any network setup to test caching with gdaltest.config_options(config_options): ds = gdal.Open('{"templateId": "foo", "nodeId": "bar", "parameters": {"p1": "baz"},"options":{"delete-on-close":false}}') cs = [ds.GetRasterBand(i + 1).Checksum() for i in range(3)] - if cs != [54287, 50451, 21110]: - gdaltest.post_reason('fail') - print(cs) - return 'fail' + assert cs == [54287, 50451, 21110] data = struct.unpack('B' * (320 * 300 * 3), ds.ReadRaster()) - if data[0] != 255: - gdaltest.post_reason('fail') - return 'fail' + assert data[0] == 255 - if data[0 + 320 * 300] != 250: - gdaltest.post_reason('fail') - return 'fail' + assert data[0 + 320 * 300] == 250 - if data[0 + 320 * 300 * 2] != 245: - gdaltest.post_reason('fail') - return 'fail' + assert data[0 + 320 * 300 * 2] == 245 - if data[319] != 240: - gdaltest.post_reason('fail') - return 'fail' + assert data[319] == 240 - if data[320 * 299] != 225: - gdaltest.post_reason('fail') - return 'fail' + assert data[320 * 299] == 225 - if data[320 * 299 + 319] != 210: - gdaltest.post_reason('fail') - return 'fail' + assert data[320 * 299 + 319] == 210 ds = None gdal.RmdirRecursive('/vsimem/cache_dir') - return 'success' - -def rda_read_gbdx_config(): +def test_rda_read_gbdx_config(): if gdaltest.rda_drv is None: - return 'skip' + pytest.skip() if gdaltest.webserver_port == 0: - return 'skip' + pytest.skip() gdal.RmdirRecursive('/vsimem/cache_dir') @@ -1263,22 +1021,19 @@ def rda_read_gbdx_config(): with webserver.install_http_handler(handler): with gdaltest.config_options(config_options): ds = gdal.Open('{"graph-id":"foo","node-id":"bar","options":{"delete-on-close":false}}') - if ds is None: - return 'fail' + assert ds is not None gdal.Unlink('/vsimem/.gbdx-config') - return 'success' - ############################################################################### -def rda_download_queue(): +def test_rda_download_queue(): if gdaltest.rda_drv is None: - return 'skip' + pytest.skip() if gdaltest.webserver_port == 0: - return 'skip' + pytest.skip() gdal.RmdirRecursive('/vsimem/cache_dir') @@ -1343,21 +1098,17 @@ def rda_download_queue(): handler = webserver.SequentialHandler() with webserver.install_http_handler(handler): data = ds.ReadRaster(0, 1, 4, 2) - if data != ref_data: - gdaltest.post_reason('fail') - return 'fail' - - return 'success' + assert data == ref_data ############################################################################### -def rda_rpc(): +def test_rda_rpc(): if gdaltest.rda_drv is None: - return 'skip' + pytest.skip() if gdaltest.webserver_port == 0: - return 'skip' + pytest.skip() gdal.RmdirRecursive('/vsimem/cache_dir') @@ -1403,9 +1154,7 @@ def rda_rpc(): with gdaltest.config_options(config_options): ds = gdal.Open('{"graph-id":"foo","node-id":"bar","options":{"delete-on-close":false}}') md = ds.GetMetadata('RPC') - if md != {}: - gdaltest.post_reason('fail') - return 'fail' + assert md == {} gdal.RmdirRecursive('/vsimem/cache_dir') @@ -1420,9 +1169,7 @@ def rda_rpc(): ds = gdal.Open('{"graph-id":"foo","node-id":"bar","options":{"delete-on-close":false}}') with gdaltest.error_handler(): md = ds.GetMetadata('RPC') - if md != {}: - gdaltest.post_reason('fail') - return 'fail' + assert md == {} gdal.RmdirRecursive('/vsimem/cache_dir') @@ -1438,36 +1185,28 @@ def rda_rpc(): expected_md = {'HEIGHT_OFF': '151', 'SAMP_OFF': '13775', 'LINE_NUM_COEFF': '0.00346238799999999984 -0.00331988499999999985 -1.00417299999999998 -0.000569458199999999968 0.00138283000000000004 1.97361499999999982e-06 0.000360684200000000019 -0.000828726199999999967 -0.00134833700000000002 3.39903600000000002e-07 -1.43147900000000003e-06 1.05879399999999997e-06 2.70590600000000004e-05 -9.73226600000000015e-08 -2.98801499999999988e-05 -0.000120552999999999996 -2.95605399999999987e-05 2.81748900000000025e-07 0 -1.66303899999999993e-08', 'LONG_OFF': '2.19589999999999996', 'MIN_LAT': '48.6908414600000015', 'MAX_LONG': '2.31489579000000001', 'LINE_SCALE': '13314', 'SAMP_NUM_COEFF': '-0.0036275840000000001 1.01546899999999996 -0.0016947380000000001 -0.0107358999999999996 -0.00195866699999999987 0.000532514199999999951 -0.000400355199999999985 0.00366687099999999993 0.0002035126 -5.42788399999999972e-06 -1.176796e-06 -1.53613099999999988e-05 -6.90779199999999995e-05 -1.67062600000000002e-05 7.90828899999999939e-05 -4.44276200000000027e-06 1.14346699999999995e-07 3.32255499999999999e-06 8.62453100000000019e-07 1.74167099999999993e-07', 'LONG_SCALE': '0.120300000000000004', 'SAMP_DEN_COEFF': '1 -3.70703199999999978e-05 0.00197828100000000014 -0.000580411299999999963 -4.49799400000000022e-05 -2.65957199999999999e-06 9.73095999999999941e-07 -1.25065499999999997e-05 4.71401100000000002e-05 -1.69761699999999998e-05 -6.04184799999999996e-08 0 2.17301699999999993e-07 5.60807800000000004e-08 -2.6601939999999999e-07 -2.02055599999999998e-07 -6.34738299999999952e-08 1.32195600000000006e-08 -8.62653499999999976e-08 1.90874699999999984e-08', 'MIN_LONG': '2.07724377999999987', 'SAMP_SCALE': '13776', 'MAX_LAT': '48.8406507799999972', 'LAT_SCALE': '0.0749999999999999972', 'LAT_OFF': '48.7657000000000025', 'LINE_OFF': '13313', 'LINE_DEN_COEFF': '1 0.00139346600000000011 0.002175939 0.000361590300000000006 1.18845299999999999e-05 -5.55040999999999947e-07 -2.20758000000000013e-06 1.68834400000000011e-05 -6.33621000000000011e-05 2.9116880000000001e-05 -2.33314100000000006e-08 1.36765299999999997e-07 1.00699499999999992e-06 8.29065599999999946e-08 -7.30275400000000041e-07 -0.0001959288 2.55592200000000014e-08 2.07427299999999992e-08 6.76678700000000044e-07 2.106776e-08', 'HEIGHT_SCALE': '500'} for key in expected_md: if not key.endswith('_COEFF'): - if abs(float(expected_md[key]) - float(md[key])) > 1e-8 * abs(float(expected_md[key])): - gdaltest.post_reason('fail') - print(key, md) - return 'fail' + assert abs(float(expected_md[key]) - float(md[key])) <= 1e-8 * abs(float(expected_md[key])) else: expected_vals = [float(v) for v in expected_md[key].split(' ')] got_vals = [float(v) for v in md[key].split(' ')] for x in range(20): - if abs(expected_vals[x] - got_vals[x]) > 1e-8 * abs(expected_vals[x]): - gdaltest.post_reason('fail') - print(key, md) - return 'fail' + assert abs(expected_vals[x] - got_vals[x]) <= 1e-8 * abs(expected_vals[x]), (key, md) ds = None gdal.RmdirRecursive('/vsimem/cache_dir') - return 'success' - ############################################################################### -def rda_real_cache_dir(): +def test_rda_real_cache_dir(): if gdaltest.rda_drv is None: - return 'skip' + pytest.skip() if gdaltest.webserver_port == 0: - return 'skip' + pytest.skip() home = gdal.GetConfigOption('HOME', gdal.GetConfigOption('USERPROFILE', None)) if home is None: - return 'skip' + pytest.skip() gdal.RmdirRecursive('/vsimem/cache_dir') @@ -1516,8 +1255,7 @@ def rda_real_cache_dir(): with gdaltest.config_options(config_options): gdal.Open('{"graph-id":"foo","node-id":"bar","options":{"delete-on-close":false}}') - if not os.path.exists(cached_file): - return 'fail' + assert os.path.exists(cached_file) gdal.RmdirRecursive(os.path.join(home, '.gdal', 'rda_cache', 'foo')) handler = webserver.SequentialHandler() @@ -1528,8 +1266,7 @@ def rda_real_cache_dir(): with gdaltest.config_options(config_options): gdal.Open('{"graph-id":"foo","node-id":"bar"}') - if os.path.exists(os.path.join(home, '.gdal', 'rda_cache', 'foo')): - return 'fail' + assert not os.path.exists(os.path.join(home, '.gdal', 'rda_cache', 'foo')) # 493 = 0755 gdal.MkdirRecursive(os.path.join(home, '.gdal', 'rda_cache', 'foo', 'baz'), 493) @@ -1542,22 +1279,19 @@ def rda_real_cache_dir(): with gdaltest.config_options(config_options): gdal.Open('{"graph-id":"foo","node-id":"bar"}') - if not os.path.exists(os.path.join(home, '.gdal', 'rda_cache', 'foo', 'baz')): - return 'fail' + assert os.path.exists(os.path.join(home, '.gdal', 'rda_cache', 'foo', 'baz')) gdal.RmdirRecursive(os.path.join(home, '.gdal', 'rda_cache', 'foo')) - return 'success' - ############################################################################### -def rda_real_expired_authentication(): +def test_rda_real_expired_authentication(): if gdaltest.rda_drv is None: - return 'skip' + pytest.skip() if gdaltest.webserver_port == 0: - return 'skip' + pytest.skip() gdal.RmdirRecursive('/vsimem/cache_dir') @@ -1608,17 +1342,16 @@ def rda_real_expired_authentication(): with gdaltest.config_options(config_options): gdal.Open('{"graph-id":"foo","node-id":"bar"}') - return 'success' - + ############################################################################### -def rda_bad_tile(): +def test_rda_bad_tile(): if gdaltest.rda_drv is None: - return 'skip' + pytest.skip() if gdaltest.webserver_port == 0: - return 'skip' + pytest.skip() gdal.RmdirRecursive('/vsimem/cache_dir') @@ -1672,9 +1405,7 @@ def rda_bad_tile(): ds = gdal.Open('{"graph-id":"foo","node-id":"bar"}') with gdaltest.error_handler(): data = ds.ReadRaster() - if data is not None: - gdaltest.post_reason('fail') - return 'fail' + assert data is None ds = None gdal.RmdirRecursive('/vsimem/cache_dir') @@ -1688,9 +1419,7 @@ def rda_bad_tile(): ds = gdal.Open('{"graph-id":"foo","node-id":"bar"}') with gdaltest.error_handler(): data = ds.GetRasterBand(1).ReadBlock(0, 0) - if data is not None: - gdaltest.post_reason('fail') - return 'fail' + assert data is None ds = None gdal.RmdirRecursive('/vsimem/cache_dir') @@ -1704,9 +1433,7 @@ def rda_bad_tile(): ds = gdal.Open('{"graph-id":"foo","node-id":"bar"}') with gdaltest.error_handler(): data = ds.ReadRaster() - if data is not None: - gdaltest.post_reason('fail') - return 'fail' + assert data is None ds = None gdal.RmdirRecursive('/vsimem/cache_dir') @@ -1720,51 +1447,22 @@ def rda_bad_tile(): ds = gdal.Open('{"graph-id":"foo","node-id":"bar"}') with gdaltest.error_handler(): data = ds.GetRasterBand(1).ReadBlock(0, 0) - if data is not None: - gdaltest.post_reason('fail') - return 'fail' + assert data is None ds = None - return 'success' - ############################################################################### # -def rda_cleanup(): +def test_rda_cleanup(): if gdaltest.rda_drv is None: - return 'skip' + pytest.skip() if gdaltest.webserver_port != 0: webserver.server_stop(gdaltest.webserver_process, gdaltest.webserver_port) gdal.RmdirRecursive('/vsimem/cache_dir') - return 'success' - - -gdaltest_list = [ - rda_test_presence, - rda_bad_connection_string, - rda_missing_credentials, - rda_failed_authentication, - rda_error_metadata, - rda_graph_nominal, - rda_template_nominal, - rda_template_image_reference_nominal, - rda_read_gbdx_config, - rda_download_queue, - rda_rpc, - rda_real_cache_dir, - rda_real_expired_authentication, - rda_bad_tile, - rda_cleanup] - -if __name__ == '__main__': - - gdaltest.setup_run('RDA') - gdaltest.run_tests(gdaltest_list) - sys.exit(gdaltest.summarize()) diff --git a/autotest/gdrivers/rik.py b/autotest/gdrivers/rik.py index a44f5f8bf94b..f8467fe62dbd 100755 --- a/autotest/gdrivers/rik.py +++ b/autotest/gdrivers/rik.py @@ -29,25 +29,24 @@ ############################################################################### import os -import sys from osgeo import gdal -sys.path.append('../pymod') import gdaltest +import pytest ############################################################################### # Test a RIK map # Data downloaded from : http://www.lantmateriet.se/upload/filer/kartor/programvaror/sverige500_swe99.zip -def rik_online_1(): +def test_rik_online_1(): if gdal.GetDriverByName('RIK') is None: - return 'skip' + pytest.skip() if not gdaltest.download_file('http://www.lantmateriet.se/upload/filer/kartor/programvaror/sverige500_swe99.zip', 'sverige500_swe99.zip'): - return 'skip' + pytest.skip() try: os.stat('tmp/cache/sverige500_swe99.rik') @@ -62,7 +61,7 @@ def rik_online_1(): outfile.close() file_to_test = 'tmp/cache/sverige500_swe99.rik' except OSError: - return 'skip' + pytest.skip() tst = gdaltest.GDALTest('RIK', file_to_test, 1, 17162, filename_absolute=1) return tst.testOpen() @@ -71,28 +70,17 @@ def rik_online_1(): # Test a LZW compressed RIK dataset -def rik_online_2(): +def test_rik_online_2(): if gdal.GetDriverByName('RIK') is None: - return 'skip' + pytest.skip() if not gdaltest.download_file('http://trac.osgeo.org/gdal/raw-attachment/ticket/3674/ab-del.rik', 'ab-del.rik'): - return 'skip' + pytest.skip() tst = gdaltest.GDALTest('RIK', 'tmp/cache/ab-del.rik', 1, 44974, filename_absolute=1) return tst.testOpen() -gdaltest_list = [ - rik_online_1, - rik_online_2 -] -if __name__ == '__main__': - - gdaltest.setup_run('RIK') - - gdaltest.run_tests(gdaltest_list) - - sys.exit(gdaltest.summarize()) diff --git a/autotest/gdrivers/rl2.py b/autotest/gdrivers/rl2.py index 34bcc334e875..895943b9cfc5 100755 --- a/autotest/gdrivers/rl2.py +++ b/autotest/gdrivers/rl2.py @@ -29,226 +29,151 @@ # DEALINGS IN THE SOFTWARE. ############################################################################### -import sys from osgeo import gdal, ogr -sys.path.append('../pymod') import gdaltest +import pytest ############################################################################### # Get the rl2 driver -def rl2_1(): +def test_rl2_1(): gdaltest.rl2_drv = gdal.GetDriverByName('SQLite') if gdaltest.rl2_drv is None: - return 'skip' + pytest.skip() if gdaltest.rl2_drv.GetMetadataItem('DCAP_RASTER') is None: gdaltest.rl2_drv = None - return 'skip' - - return 'success' + pytest.skip() + ############################################################################### # Test opening a rl2 DB gray level -def rl2_2(): +def test_rl2_2(): if gdaltest.rl2_drv is None: - return 'skip' + pytest.skip() ds = gdal.Open('data/byte.rl2') - if ds.RasterCount != 1: - gdaltest.post_reason('expected 1 band') - return 'fail' + assert ds.RasterCount == 1, 'expected 1 band' - if ds.GetRasterBand(1).GetOverviewCount() != 0: - gdaltest.post_reason('did not expect overview') - return 'fail' + assert ds.GetRasterBand(1).GetOverviewCount() == 0, 'did not expect overview' cs = ds.GetRasterBand(1).Checksum() - if cs != 4672: - gdaltest.post_reason('fail') - print(cs) - return 'fail' + assert cs == 4672 gt = ds.GetGeoTransform() expected_gt = (440720.0, 60.0, 0.0, 3751320.0, 0.0, -60.0) for i in range(6): - if abs(gt[i] - expected_gt[i]) > 1e-15: - print(gt) - print(expected_gt) - return 'fail' + assert abs(gt[i] - expected_gt[i]) <= 1e-15 wkt = ds.GetProjectionRef() - if wkt.find('26711') < 0: - gdaltest.post_reason('fail') - return 'fail' + assert wkt.find('26711') >= 0 - if ds.GetRasterBand(1).GetColorInterpretation() != gdal.GCI_GrayIndex: - gdaltest.post_reason('fail') - return 'fail' + assert ds.GetRasterBand(1).GetColorInterpretation() == gdal.GCI_GrayIndex - if ds.GetRasterBand(1).GetMinimum() != 74: - gdaltest.post_reason('fail') - return 'fail' + assert ds.GetRasterBand(1).GetMinimum() == 74 - 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 not None: - gdaltest.post_reason('fail') - return 'fail' + assert ds.GetRasterBand(1).GetOverview(0) is None subds = ds.GetSubDatasets() expected_subds = [] - if subds != expected_subds: - gdaltest.post_reason('fail') - return 'fail' + assert subds == expected_subds gdal.SetConfigOption('RL2_SHOW_ALL_PYRAMID_LEVELS', 'YES') ds = gdal.Open('data/byte.rl2') gdal.SetConfigOption('RL2_SHOW_ALL_PYRAMID_LEVELS', None) cs = ds.GetRasterBand(1).GetOverview(0).Checksum() - if cs != 1087: - gdaltest.post_reason('fail') - print(cs) - return 'fail' - - return 'success' + assert cs == 1087 ############################################################################### # Test opening a rl2 DB gray level -def rl2_3(): +def test_rl2_3(): if gdaltest.rl2_drv is None: - return 'skip' + pytest.skip() ds = gdal.Open('data/small_world.rl2') - if ds.GetRasterBand(1).GetColorInterpretation() != gdal.GCI_RedBand: - gdaltest.post_reason('fail') - return 'fail' + assert ds.GetRasterBand(1).GetColorInterpretation() == gdal.GCI_RedBand ds.GetRasterBand(1).GetNoDataValue() cs = ds.GetRasterBand(1).Checksum() - if cs != 25550: - gdaltest.post_reason('fail') - print(cs) - return 'fail' + assert cs == 25550 cs = ds.GetRasterBand(2).Checksum() - if cs != 28146: - gdaltest.post_reason('fail') - print(cs) - return 'fail' + assert cs == 28146 - if ds.GetRasterBand(1).GetOverviewCount() != 2: - gdaltest.post_reason('fail') - return 'fail' + assert ds.GetRasterBand(1).GetOverviewCount() == 2 cs = ds.GetRasterBand(1).GetOverview(1).Checksum() - if cs != 51412: - gdaltest.post_reason('fail') - print(cs) - return 'fail' + assert cs == 51412 subds = ds.GetSubDatasets() expected_subds = [('RASTERLITE2:data/small_world.rl2:small_world:1:world_west', 'Coverage small_world, section world_west / 1'), ('RASTERLITE2:data/small_world.rl2:small_world:2:world_east', 'Coverage small_world, section world_east / 2')] - if subds != expected_subds: - gdaltest.post_reason('fail') - print(subds) - return 'fail' + assert subds == expected_subds ds = gdal.Open('RASTERLITE2:data/small_world.rl2:small_world:1:world_west') cs = ds.GetRasterBand(1).Checksum() - if cs != 3721: - gdaltest.post_reason('fail') - print(cs) - return 'fail' + assert cs == 3721 - if ds.GetRasterBand(1).GetOverviewCount() != 1: - gdaltest.post_reason('fail') - return 'fail' + assert ds.GetRasterBand(1).GetOverviewCount() == 1 cs = ds.GetRasterBand(1).GetOverview(0).Checksum() - if cs != 35686: - gdaltest.post_reason('fail') - print(cs) - return 'fail' - - return 'success' + assert cs == 35686 ############################################################################### # Test opening a rl2 DB paletted -def rl2_4(): +def test_rl2_4(): if gdaltest.rl2_drv is None: - return 'skip' + pytest.skip() ds = gdal.Open('data/small_world_pct.rl2') - if ds.GetRasterBand(1).GetColorInterpretation() != gdal.GCI_PaletteIndex: - gdaltest.post_reason('fail') - return 'fail' + assert ds.GetRasterBand(1).GetColorInterpretation() == gdal.GCI_PaletteIndex cs = ds.GetRasterBand(1).Checksum() - if cs != 14890: - gdaltest.post_reason('fail') - print(cs) - return 'fail' + assert cs == 14890 pct = ds.GetRasterBand(1).GetColorTable() - if pct.GetCount() != 256: - gdaltest.post_reason('fail') - return 'fail' - if pct.GetColorEntry(1) != (176, 184, 176, 255): - gdaltest.post_reason('fail') - print(pct.GetColorEntry(1)) - return 'fail' + assert pct.GetCount() == 256 + assert pct.GetColorEntry(1) == (176, 184, 176, 255) pct = ds.GetRasterBand(1).GetColorTable() - if pct.GetCount() != 256: - gdaltest.post_reason('fail') - return 'fail' + assert pct.GetCount() == 256 cs = ds.GetRasterBand(1).GetOverview(0).Checksum() - if cs != 35614: - gdaltest.post_reason('fail') - print(cs) - return 'fail' - - return 'success' + assert cs == 35614 ############################################################################### # Test opening a rl2 DB with various data types -def rl2_5(): +def test_rl2_5(): if gdaltest.rl2_drv is None: - return 'skip' + pytest.skip() ds = gdal.Open('data/multi_type.rl2') subds = ds.GetSubDatasets() expected_subds = [('RASTERLITE2:data/multi_type.rl2:uint8', 'Coverage uint8'), ('RASTERLITE2:data/multi_type.rl2:int8', 'Coverage int8'), ('RASTERLITE2:data/multi_type.rl2:uint16', 'Coverage uint16'), ('RASTERLITE2:data/multi_type.rl2:int16', 'Coverage int16'), ('RASTERLITE2:data/multi_type.rl2:uint32', 'Coverage uint32'), ('RASTERLITE2:data/multi_type.rl2:int32', 'Coverage int32'), ('RASTERLITE2:data/multi_type.rl2:float', 'Coverage float'), ('RASTERLITE2:data/multi_type.rl2:double', 'Coverage double'), ('RASTERLITE2:data/multi_type.rl2:1bit', 'Coverage 1bit'), ('RASTERLITE2:data/multi_type.rl2:2bit', 'Coverage 2bit'), ('RASTERLITE2:data/multi_type.rl2:4bit', 'Coverage 4bit')] - if subds != expected_subds: - gdaltest.post_reason('fail') - print(subds) - return 'fail' + assert subds == expected_subds tests = [('RASTERLITE2:data/multi_type.rl2:uint8', gdal.GDT_Byte, 4672), ('RASTERLITE2:data/multi_type.rl2:int8', gdal.GDT_Byte, 4575), @@ -261,31 +186,21 @@ def rl2_5(): ('RASTERLITE2:data/multi_type.rl2:1bit', gdal.GDT_Byte, 4873)] for (subds_name, dt, expected_cs) in tests: ds = gdal.Open(subds_name) - if ds.GetRasterBand(1).DataType != dt: - gdaltest.post_reason('fail') - print(subds_name) - return 'fail' + assert ds.GetRasterBand(1).DataType == dt, subds_name cs = ds.GetRasterBand(1).Checksum() - if cs != expected_cs: - gdaltest.post_reason('fail') - print(cs) - return 'fail' + assert cs == expected_cs if subds_name == 'RASTERLITE2:data/multi_type.rl2:int8': - if ds.GetRasterBand(1).GetMetadataItem('PIXELTYPE', 'IMAGE_STRUCTURE') != 'SIGNEDBYTE': - gdaltest.post_reason('fail') - print(ds.GetRasterBand(1).GetMetadataItem('PIXELTYPE', 'IMAGE_STRUCTURE')) - return 'fail' - - return 'success' + assert ds.GetRasterBand(1).GetMetadataItem('PIXELTYPE', 'IMAGE_STRUCTURE') == 'SIGNEDBYTE' + ############################################################################### # Test CreateCopy() on a grayscale uint8 -def rl2_6(): +def test_rl2_6(): if gdaltest.rl2_drv is None: - return 'skip' + pytest.skip() tst = gdaltest.GDALTest('SQLite', 'byte.tif', 1, 4672) return tst.testCreateCopy(vsimem=1, check_minmax=False) @@ -294,10 +209,10 @@ def rl2_6(): # Test CreateCopy() on a RGB -def rl2_7(): +def test_rl2_7(): if gdaltest.rl2_drv is None: - return 'skip' + pytest.skip() tst = gdaltest.GDALTest('SQLite', 'small_world.tif', 1, 30111, options=['COMPRESS=PNG']) return tst.testCreateCopy(vsimem=1) @@ -306,10 +221,10 @@ def rl2_7(): # Test CreateCopy() on a paletted dataset -def rl2_8(): +def test_rl2_8(): if gdaltest.rl2_drv is None: - return 'skip' + pytest.skip() tst = gdaltest.GDALTest('SQLite', 'small_world_pct.tif', 1, 14890, options=['COMPRESS=PNG']) return tst.testCreateCopy(vsimem=1, check_minmax=False) @@ -318,10 +233,10 @@ def rl2_8(): # Test CreateCopy() on a DATAGRID uint16 -def rl2_9(): +def test_rl2_9(): if gdaltest.rl2_drv is None: - return 'skip' + pytest.skip() tst = gdaltest.GDALTest('SQLite', '../../gcore/data/uint16.tif', 1, 4672) return tst.testCreateCopy(vsimem=1) @@ -330,10 +245,10 @@ def rl2_9(): # Test CreateCopy() on a DATAGRID int16 -def rl2_10(): +def test_rl2_10(): if gdaltest.rl2_drv is None: - return 'skip' + pytest.skip() tst = gdaltest.GDALTest('SQLite', '../../gcore/data/int16.tif', 1, 4672) return tst.testCreateCopy(vsimem=1) @@ -342,10 +257,10 @@ def rl2_10(): # Test CreateCopy() on a DATAGRID uint32 -def rl2_11(): +def test_rl2_11(): if gdaltest.rl2_drv is None: - return 'skip' + pytest.skip() tst = gdaltest.GDALTest('SQLite', '../../gcore/data/uint32.tif', 1, 4672) return tst.testCreateCopy(vsimem=1) @@ -354,10 +269,10 @@ def rl2_11(): # Test CreateCopy() on a DATAGRID int32 -def rl2_12(): +def test_rl2_12(): if gdaltest.rl2_drv is None: - return 'skip' + pytest.skip() tst = gdaltest.GDALTest('SQLite', '../../gcore/data/int32.tif', 1, 4672) return tst.testCreateCopy(vsimem=1) @@ -366,10 +281,10 @@ def rl2_12(): # Test CreateCopy() on a DATAGRID float -def rl2_13(): +def test_rl2_13(): if gdaltest.rl2_drv is None: - return 'skip' + pytest.skip() tst = gdaltest.GDALTest('SQLite', '../../gcore/data/float32.tif', 1, 4672) return tst.testCreateCopy(vsimem=1) @@ -378,10 +293,10 @@ def rl2_13(): # Test CreateCopy() on a DATAGRID double -def rl2_14(): +def test_rl2_14(): if gdaltest.rl2_drv is None: - return 'skip' + pytest.skip() tst = gdaltest.GDALTest('SQLite', '../../gcore/data/float64.tif', 1, 4672) return tst.testCreateCopy(vsimem=1) @@ -390,10 +305,10 @@ def rl2_14(): # Test CreateCopy() on a 1 bit paletted -def rl2_15(): +def test_rl2_15(): if gdaltest.rl2_drv is None: - return 'skip' + pytest.skip() tst = gdaltest.GDALTest('SQLite', '../../gcore/data/1bit.bmp', 1, 200) return tst.testCreateCopy(vsimem=1, check_minmax=False) @@ -402,10 +317,10 @@ def rl2_15(): # Test CreateCopy() on a forced 1 bit -def rl2_16(): +def test_rl2_16(): if gdaltest.rl2_drv is None: - return 'skip' + pytest.skip() tst = gdaltest.GDALTest('SQLite', 'byte.tif', 1, 4873, options=['NBITS=1', 'COMPRESS=CCITTFAX4']) return tst.testCreateCopy(vsimem=1, check_minmax=False) @@ -414,10 +329,10 @@ def rl2_16(): # Test CreateCopy() on a forced 2 bit -def rl2_17(): +def test_rl2_17(): if gdaltest.rl2_drv is None: - return 'skip' + pytest.skip() tst = gdaltest.GDALTest('SQLite', 'byte.tif', 1, 4873, options=['NBITS=2', 'COMPRESS=DEFLATE']) return tst.testCreateCopy(vsimem=1, check_minmax=False) @@ -426,10 +341,10 @@ def rl2_17(): # Test CreateCopy() on a forced 4 bit -def rl2_18(): +def test_rl2_18(): if gdaltest.rl2_drv is None: - return 'skip' + pytest.skip() tst = gdaltest.GDALTest('SQLite', 'byte.tif', 1, 2541, options=['NBITS=4']) return tst.testCreateCopy(vsimem=1, check_minmax=False) @@ -438,10 +353,10 @@ def rl2_18(): # Test CreateCopy() with forced monochrome -def rl2_19(): +def test_rl2_19(): if gdaltest.rl2_drv is None: - return 'skip' + pytest.skip() tst = gdaltest.GDALTest('SQLite', 'byte.tif', 1, 4873, options=['PIXEL_TYPE=MONOCHROME']) return tst.testCreateCopy(vsimem=1, check_minmax=False) @@ -451,10 +366,10 @@ def rl2_19(): # Se https://www.gaia-gis.it/fossil/librasterlite2/wiki?name=reference_table -def rl2_20(): +def test_rl2_20(): if gdaltest.rl2_drv is None: - return 'skip' + pytest.skip() tests = [('MONOCHROME', 2, gdal.GDT_Byte, 'NONE', None, None), ('MONOCHROME', 1, gdal.GDT_UInt16, 'NONE', None, None), @@ -489,22 +404,19 @@ def rl2_20(): options = ['PIXEL_TYPE=' + pixel_type, 'COMPRESS=' + compress] with gdaltest.error_handler(): out_ds = gdaltest.rl2_drv.CreateCopy('/vsimem/rl2_20.rl2', src_ds, options=options) - if out_ds is not None: - gdaltest.post_reason('Expected error for %s, band=%d, dt=%d, %s, nbits=%s' % (pixel_type, band_count, dt, compress, nbits)) - return 'fail' + assert out_ds is None, \ + ('Expected error for %s, band=%d, dt=%d, %s, nbits=%s' % (pixel_type, band_count, dt, compress, nbits)) gdal.Unlink('/vsimem/rl2_20.rl2') - return 'success' - ############################################################################### # Test compression methods -def rl2_21(): +def test_rl2_21(): if gdaltest.rl2_drv is None: - return 'skip' + pytest.skip() tests = [('DEFLATE', None), ('LZMA', None), @@ -531,25 +443,21 @@ def rl2_21(): if quality is not None: options += ['QUALITY=' + str(quality)] out_ds = gdaltest.rl2_drv.CreateCopy('/vsimem/rl2_21.rl2', src_ds, options=options) - if out_ds is None: - gdaltest.post_reason('Got error with %s, quality=%d' % (compress, quality)) - return 'fail' - if out_ds.GetMetadataItem('COMPRESSION', 'IMAGE_STRUCTURE').find(compress) < 0: - gdaltest.post_reason('Compression %s does not seem to have been applied' % compress) - return 'fail' + assert out_ds is not None, \ + ('Got error with %s, quality=%d' % (compress, quality)) + assert out_ds.GetMetadataItem('COMPRESSION', 'IMAGE_STRUCTURE').find(compress) >= 0, \ + ('Compression %s does not seem to have been applied' % compress) gdal.Unlink('/vsimem/rl2_21.rl2') - return 'success' - ############################################################################### # Test APPEND_SUBDATASET -def rl2_22(): +def test_rl2_22(): if gdaltest.rl2_drv is None: - return 'skip' + pytest.skip() src_ds = gdal.Open('data/byte.tif') @@ -557,146 +465,77 @@ def rl2_22(): ds.CreateLayer('foo', None, ogr.wkbPoint) ds = None ds = gdaltest.rl2_drv.CreateCopy('/vsimem/rl2_22.rl2', src_ds, options=['APPEND_SUBDATASET=YES', 'COVERAGE=byte']) - if ds.GetRasterBand(1).Checksum() != 4672: - gdaltest.post_reason('fail') - print(ds.GetRasterBand(1).Checksum()) - return 'fail' + assert ds.GetRasterBand(1).Checksum() == 4672 ds = None ds = gdal.OpenEx('/vsimem/rl2_22.rl2') - if ds.RasterXSize != 20: - gdaltest.post_reason('fail') - return 'fail' - if ds.GetLayerCount() != 1: - gdaltest.post_reason('fail') - return 'fail' + assert ds.RasterXSize == 20 + assert ds.GetLayerCount() == 1 left_ds = gdal.Translate('left', src_ds, srcWin=[0, 0, 10, 20], format='MEM') right_ds = gdal.Translate('', src_ds, srcWin=[10, 0, 10, 20], format='MEM') gdaltest.rl2_drv.CreateCopy('/vsimem/rl2_22.rl2', left_ds, options=['COVERAGE=left_right']) ds = gdaltest.rl2_drv.CreateCopy('/vsimem/rl2_22.rl2', right_ds, options=['APPEND_SUBDATASET=YES', 'COVERAGE=left_right', 'SECTION=right']) - if ds.GetRasterBand(1).Checksum() != 4672: - gdaltest.post_reason('fail') - print(ds.GetRasterBand(1).Checksum()) - return 'fail' + assert ds.GetRasterBand(1).Checksum() == 4672 src_ds = gdal.Open('data/rgbsmall.tif') ds = gdaltest.rl2_drv.CreateCopy('/vsimem/rl2_22.rl2', src_ds, options=['APPEND_SUBDATASET=YES', 'COVERAGE=rgbsmall']) - if ds.GetRasterBand(1).Checksum() != src_ds.GetRasterBand(1).Checksum(): - gdaltest.post_reason('fail') - print(ds.GetRasterBand(1).Checksum()) - return 'fail' + assert ds.GetRasterBand(1).Checksum() == src_ds.GetRasterBand(1).Checksum() ds = None gdal.Unlink('/vsimem/rl2_22.rl2') - return 'success' - ############################################################################### # Test BuildOverviews -def rl2_23(): +def test_rl2_23(): if gdaltest.rl2_drv is None: - return 'skip' + pytest.skip() src_ds = gdal.Open('data/byte.tif') src_ds = gdal.Translate('', src_ds, format='MEM', width=2048, height=2048) ds = gdaltest.rl2_drv.CreateCopy('/vsimem/rl2_23.rl2', src_ds) ret = ds.BuildOverviews('NEAR', [2]) - if ret != 0: - gdaltest.post_reason('fail') - return 'fail' - if ds.GetRasterBand(1).GetOverviewCount() != 5: - gdaltest.post_reason('fail') - print(ds.GetRasterBand(1).GetOverviewCount()) - return 'fail' + assert ret == 0 + assert ds.GetRasterBand(1).GetOverviewCount() == 5 cs = ds.GetRasterBand(1).GetOverview(0).Checksum() - if cs == 0: - gdaltest.post_reason('fail') - print(cs) - return 'fail' + assert cs != 0 ret = ds.BuildOverviews('NONE', []) - if ret != 0: - gdaltest.post_reason('fail') - return 'fail' + assert ret == 0 ds = gdal.Open('/vsimem/rl2_23.rl2') - if ds.GetRasterBand(1).GetOverviewCount() == 5: - gdaltest.post_reason('fail') - print(ds.GetRasterBand(1).GetOverviewCount()) - return 'fail' + assert ds.GetRasterBand(1).GetOverviewCount() != 5 ds = None gdal.Unlink('/vsimem/rl2_23.rl2') - return 'success' - ############################################################################### # Test opening a .rl2.sql file -def rl2_24(): +def test_rl2_24(): if gdaltest.rl2_drv is None: - return 'skip' + pytest.skip() if gdal.GetDriverByName('SQLite').GetMetadataItem("ENABLE_SQL_SQLITE_FORMAT") != 'YES': - return 'skip' + pytest.skip() ds = gdal.Open('data/byte.rl2.sql') - if ds.GetRasterBand(1).Checksum() != 4672: - gdaltest.post_reason('validation failed') - return 'fail' - return 'success' + assert ds.GetRasterBand(1).Checksum() == 4672, 'validation failed' ############################################################################### # Test Create() -def rl2_error_create(): +def test_rl2_error_create(): if gdaltest.rl2_drv is None: - return 'skip' + pytest.skip() with gdaltest.error_handler(): - if gdaltest.rl2_drv.Create('/vsimem/out.db', 1, 1) is not None: - return 'fail' - return 'success' - - -gdaltest_list = [ - rl2_1, - rl2_2, - rl2_3, - rl2_4, - rl2_5, - rl2_6, - rl2_7, - rl2_8, - rl2_9, - rl2_10, - rl2_11, - rl2_12, - rl2_13, - rl2_14, - rl2_15, - rl2_16, - rl2_17, - rl2_18, - rl2_19, - rl2_20, - rl2_21, - rl2_22, - rl2_23, - rl2_24, - rl2_error_create, -] - -if __name__ == '__main__': - - gdaltest.setup_run('rl2') - - gdaltest.run_tests(gdaltest_list) - - sys.exit(gdaltest.summarize()) + assert gdaltest.rl2_drv.Create('/vsimem/out.db', 1, 1) is None + + + diff --git a/autotest/gdrivers/rmf.py b/autotest/gdrivers/rmf.py index 5fc6bbda1edf..72bb839df417 100755 --- a/autotest/gdrivers/rmf.py +++ b/autotest/gdrivers/rmf.py @@ -29,92 +29,79 @@ ############################################################################### import os -import sys -sys.path.append('../pymod') import gdaltest from osgeo import gdal from osgeo import osr +import pytest ############################################################################### # Perform simple read tests. -def rmf_1(): +def test_rmf_1(): tst = gdaltest.GDALTest('rmf', 'byte.rsw', 1, 4672) return tst.testOpen(check_gt=(440720, 60, 0, 3751320, 0, -60)) -def rmf_2(): +def test_rmf_2(): tst = gdaltest.GDALTest('rmf', 'byte-lzw.rsw', 1, 40503) with gdaltest.error_handler(): return tst.testOpen() -def rmf_3(): +def test_rmf_3(): tst = gdaltest.GDALTest('rmf', 'float64.mtw', 1, 4672) with gdaltest.error_handler(): return tst.testOpen(check_gt=(440720, 60, 0, 3751320, 0, -60)) -def rmf_4(): +def test_rmf_4(): tst = gdaltest.GDALTest('rmf', 'rgbsmall.rsw', 1, 21212) - ret = tst.testOpen(check_gt=(-44.840320, 0.003432, 0, + tst.testOpen(check_gt=(-44.840320, 0.003432, 0, -22.932584, 0, -0.003432)) - if ret != 'success': - return 'fail' tst = gdaltest.GDALTest('rmf', 'rgbsmall.rsw', 2, 21053) - ret = tst.testOpen(check_gt=(-44.840320, 0.003432, 0, + tst.testOpen(check_gt=(-44.840320, 0.003432, 0, -22.932584, 0, -0.003432)) - if ret != 'success': - return 'fail' tst = gdaltest.GDALTest('rmf', 'rgbsmall.rsw', 3, 21349) - return tst.testOpen(check_gt=(-44.840320, 0.003432, 0, + tst.testOpen(check_gt=(-44.840320, 0.003432, 0, -22.932584, 0, -0.003432)) -def rmf_5(): +def test_rmf_5(): tst = gdaltest.GDALTest('rmf', 'rgbsmall-lzw.rsw', 1, 40503) with gdaltest.error_handler(): - ret = tst.testOpen() - - if ret != 'success': - return 'fail' + tst.testOpen() + tst = gdaltest.GDALTest('rmf', 'rgbsmall-lzw.rsw', 2, 41429) with gdaltest.error_handler(): - ret = tst.testOpen() - - if ret != 'success': - return 'fail' + tst.testOpen() + tst = gdaltest.GDALTest('rmf', 'rgbsmall-lzw.rsw', 3, 40238) with gdaltest.error_handler(): return tst.testOpen() -def rmf_6(): +def test_rmf_6(): tst = gdaltest.GDALTest('rmf', 'big-endian.rsw', 1, 7782) with gdaltest.error_handler(): - ret = tst.testOpen() - if ret != 'success': - return 'fail' - + tst.testOpen() + tst = gdaltest.GDALTest('rmf', 'big-endian.rsw', 2, 8480) with gdaltest.error_handler(): - ret = tst.testOpen() - if ret != 'success': - return 'fail' - + tst.testOpen() + tst = gdaltest.GDALTest('rmf', 'big-endian.rsw', 3, 4195) with gdaltest.error_handler(): return tst.testOpen() @@ -123,14 +110,14 @@ def rmf_6(): # Create simple copy and check. -def rmf_7(): +def test_rmf_7(): tst = gdaltest.GDALTest('rmf', 'byte.rsw', 1, 4672) return tst.testCreateCopy(check_srs=1, check_gt=1, vsimem=1) -def rmf_8(): +def test_rmf_8(): tst = gdaltest.GDALTest('rmf', 'rgbsmall.rsw', 2, 21053) @@ -140,7 +127,7 @@ def rmf_8(): # Create RMFHUGE=YES -def rmf_9(): +def test_rmf_9(): tst = gdaltest.GDALTest('rmf', 'byte.rsw', 1, 4672, options=['RMFHUGE=YES']) @@ -150,7 +137,7 @@ def rmf_9(): # Compressed DEM -def rmf_10(): +def test_rmf_10(): tst = gdaltest.GDALTest('rmf', 't100.mtw', 1, 6388) @@ -161,20 +148,16 @@ def rmf_10(): # Overviews -def rmf_11(): +def test_rmf_11(): test_fn = '/vsigzip/data/overviews.rsw.gz' src_ds = gdal.Open(test_fn) - 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.' band1 = src_ds.GetRasterBand(1) - if band1.GetOverviewCount() != 3: - gdaltest.post_reason('overviews is missing') - return 'fail' + assert band1.GetOverviewCount() == 3, 'overviews is missing' ovr_n = (0, 1, 2) ovr_size = (256, 64, 16) @@ -185,22 +168,19 @@ def rmf_11(): if ovr_band.XSize != ovr_size[i] or ovr_band.YSize != ovr_size[i]: msg = 'overview wrong size: overview %d, size = %d * %d,' % \ (i, ovr_band.XSize, ovr_band.YSize) - gdaltest.post_reason(msg) - return 'fail' + pytest.fail(msg) if ovr_band.Checksum() != ovr_checksum[i]: msg = 'overview wrong checksum: overview %d, checksum = %d,' % \ (i, ovr_band.Checksum()) - gdaltest.post_reason(msg) - return 'fail' - - return 'success' + pytest.fail(msg) + ############################################################################### # Check file open with cucled header offsets . -def rmf_12a(): +def test_rmf_12a(): tst = gdaltest.GDALTest('rmf', 'cucled-1.rsw', 1, 4672) with gdaltest.error_handler(): @@ -210,7 +190,7 @@ def rmf_12a(): # Check file open with cucled header offsets . -def rmf_12b(): +def test_rmf_12b(): tst = gdaltest.GDALTest('rmf', 'cucled-2.rsw', 1, 4672) with gdaltest.error_handler(): @@ -220,7 +200,7 @@ def rmf_12b(): # Check file open with invalid subheader marker. -def rmf_12c(): +def test_rmf_12c(): tst = gdaltest.GDALTest('rmf', 'invalid-subheader.rsw', 1, 4672) with gdaltest.error_handler(): @@ -230,7 +210,7 @@ def rmf_12c(): # Check file open with corrupted subheader. -def rmf_12d(): +def test_rmf_12d(): tst = gdaltest.GDALTest('rmf', 'corrupted-subheader.rsw', 1, 4672) return tst.testOpen(check_gt=(440720, 60, 0, 3751320, 0, -60)) @@ -242,36 +222,26 @@ def rmf_12d(): def rmf_build_ov(source, testid, options, ov_sizes, crs, reopen=False, pass_count=1): rmf_drv = gdal.GetDriverByName('RMF') - if rmf_drv is None: - gdaltest.post_reason('RMF driver not found.') - return 'fail' + assert rmf_drv is not None, 'RMF driver not found.' src_ds = gdal.Open('data/' + source, 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.' test_ds_name = 'tmp/ov-' + testid + '.tst' src_ds = rmf_drv.CreateCopy(test_ds_name, src_ds, options=options) - if src_ds is None: - gdaltest.post_reason('Failed to create test dataset copy.') - return 'fail' + assert src_ds is not None, 'Failed to create test dataset copy.' for _ in range(pass_count): if reopen: src_ds = None src_ds = gdal.Open(test_ds_name, 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.' reopen = True 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' src_ds = None src_ds = gdal.Open(test_ds_name, gdal.GA_ReadOnly) @@ -279,9 +249,7 @@ def rmf_build_ov(source, testid, options, ov_sizes, crs, reopen=False, pass_coun for iBand in range(src_ds.RasterCount): band = src_ds.GetRasterBand(iBand + 1) - if band.GetOverviewCount() != 2: - gdaltest.post_reason('overviews missing') - return 'fail' + assert band.GetOverviewCount() == 2, 'overviews missing' for iOverview in range(band.GetOverviewCount()): ovr_band = band.GetOverview(iOverview) @@ -289,25 +257,21 @@ def rmf_build_ov(source, testid, options, ov_sizes, crs, reopen=False, pass_coun ovr_band.YSize != ov_sizes[iOverview][1]: msg = 'overview wrong size: band %d, overview %d, size = %d * %d,' % \ (iBand, iOverview, ovr_band.XSize, ovr_band.YSize) - gdaltest.post_reason(msg) - return 'fail' + pytest.fail(msg) if ovr_band.Checksum() != crs[iOverview][iBand]: msg = 'overview wrong checksum: band %d, overview %d, checksum = %d,' % \ (iBand, iOverview, ovr_band.Checksum()) - gdaltest.post_reason(msg) - return 'fail' + pytest.fail(msg) src_ds = None os.remove(test_ds_name) - return 'success' - ############################################################################### # Build overviews on newly created RSW file -def rmf_13(): +def test_rmf_13(): return rmf_build_ov(source='byte.rsw', testid='13', options=['RMFHUGE=NO'], @@ -319,7 +283,7 @@ def rmf_13(): # Build overviews on newly created huge RSW file -def rmf_14(): +def test_rmf_14(): return rmf_build_ov(source='byte.rsw', testid='14', options=['RMFHUGE=YES'], @@ -331,7 +295,7 @@ def rmf_14(): # Build overviews on closed and reopened RSW file -def rmf_15(): +def test_rmf_15(): return rmf_build_ov(source='byte.rsw', testid='15', options=['RMFHUGE=NO'], @@ -343,7 +307,7 @@ def rmf_15(): # Build overviews on closed and reopened huge RSW file -def rmf_16(): +def test_rmf_16(): return rmf_build_ov(source='byte.rsw', testid='16', options=['RMFHUGE=YES'], @@ -355,7 +319,7 @@ def rmf_16(): # Build overviews on newly created MTW file -def rmf_17(): +def test_rmf_17(): return rmf_build_ov(source='float64.mtw', testid='17', options=['RMFHUGE=NO', 'MTW=YES'], @@ -367,7 +331,7 @@ def rmf_17(): # Build overviews on newly created MTW file -def rmf_18(): +def test_rmf_18(): return rmf_build_ov(source='float64.mtw', testid='18', options=['RMFHUGE=YES', 'MTW=YES'], @@ -379,7 +343,7 @@ def rmf_18(): # Build overviews on closed and reopened MTW file -def rmf_19(): +def test_rmf_19(): return rmf_build_ov(source='float64.mtw', testid='19', options=['RMFHUGE=NO', 'MTW=YES'], @@ -391,7 +355,7 @@ def rmf_19(): # Build overviews on closed and reopened huge MTW file -def rmf_20(): +def test_rmf_20(): return rmf_build_ov(source='float64.mtw', testid='20', options=['RMFHUGE=YES', 'MTW=YES'], @@ -403,7 +367,7 @@ def rmf_20(): # Recreate overviews on newly created MTW file -def rmf_21(): +def test_rmf_21(): return rmf_build_ov(source='float64.mtw', testid='21', options=['RMFHUGE=NO', 'MTW=YES'], @@ -416,7 +380,7 @@ def rmf_21(): # Recreate overviews on newly created huge MTW file -def rmf_22(): +def test_rmf_22(): return rmf_build_ov(source='float64.mtw', testid='22', options=['RMFHUGE=YES', 'MTW=YES'], @@ -429,7 +393,7 @@ def rmf_22(): ############################################################################### # Recreate overviews on closed and reopened MTW file -def rmf_23(): +def test_rmf_23(): return rmf_build_ov(source='float64.mtw', testid='23', options=['RMFHUGE=NO', 'MTW=YES'], @@ -442,7 +406,7 @@ def rmf_23(): # Recreate overviews on closed and reopened huge MTW file -def rmf_24(): +def test_rmf_24(): return rmf_build_ov(source='float64.mtw', testid='24', options=['RMFHUGE=YES', 'MTW=YES'], @@ -455,207 +419,146 @@ def rmf_24(): # Nodata write test -def rmf_25(): +def test_rmf_25(): rmf_drv = gdal.GetDriverByName('RMF') - if rmf_drv is None: - gdaltest.post_reason('RMF driver not found.') - return 'fail' + assert rmf_drv is not None, 'RMF driver not found.' src_ds = gdal.Open('data/byte.rsw', 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.' test_ds_name = 'tmp/nodata.rsw' test_ds = rmf_drv.CreateCopy(test_ds_name, src_ds) - if test_ds is None: - gdaltest.post_reason('Failed to create test dataset copy.') - return 'fail' + assert test_ds is not None, 'Failed to create test dataset copy.' test_ds.GetRasterBand(1).SetNoDataValue(33) nd = test_ds.GetRasterBand(1).GetNoDataValue() - if nd != 33: - gdaltest.post_reason('Invalid NoData value after CreateCopy.') - return 'fail' + assert nd == 33, 'Invalid NoData value after CreateCopy.' test_ds = None test_ds = gdal.Open(test_ds_name, gdal.GA_Update) - if test_ds is None: - gdaltest.post_reason('Failed to reopen test dataset.') - return 'fail' + assert test_ds is not None, 'Failed to reopen test dataset.' nd = test_ds.GetRasterBand(1).GetNoDataValue() - if nd != 33: - gdaltest.post_reason('Invalid NoData value after dataset reopen.') - return 'fail' + assert nd == 33, 'Invalid NoData value after dataset reopen.' test_ds.GetRasterBand(1).SetNoDataValue(55) test_ds = None test_ds = gdal.Open(test_ds_name, gdal.GA_ReadOnly) - if test_ds is None: - gdaltest.post_reason('Failed to reopen test dataset.') - return 'fail' + assert test_ds is not None, 'Failed to reopen test dataset.' nd = test_ds.GetRasterBand(1).GetNoDataValue() - if nd != 55: - gdaltest.post_reason('Invalid NoData value after dataset update.') - return 'fail' + assert nd == 55, 'Invalid NoData value after dataset update.' test_ds = None os.remove(test_ds_name) - - return 'success' ############################################################################### # Unit write test -def rmf_26(): +def test_rmf_26(): rmf_drv = gdal.GetDriverByName('RMF') - if rmf_drv is None: - gdaltest.post_reason('RMF driver not found.') - return 'fail' + assert rmf_drv is not None, 'RMF driver not found.' src_ds = gdal.Open('data/float64.mtw', 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.' test_ds_name = 'tmp/unit.mtw' test_ds = rmf_drv.CreateCopy(test_ds_name, src_ds, options=['MTW=YES']) - if test_ds is None: - gdaltest.post_reason('Failed to create test dataset copy.') - return 'fail' + assert test_ds is not None, 'Failed to create test dataset copy.' test_ds.GetRasterBand(1).SetUnitType('cm') unittype = test_ds.GetRasterBand(1).GetUnitType() - if unittype != 'cm': - gdaltest.post_reason('Invalid UnitType after CreateCopy.') - return 'fail' + assert unittype == 'cm', 'Invalid UnitType after CreateCopy.' test_ds = None test_ds = gdal.Open(test_ds_name, gdal.GA_Update) - if test_ds is None: - gdaltest.post_reason('Failed to reopen test dataset.') - return 'fail' + assert test_ds is not None, 'Failed to reopen test dataset.' unittype = test_ds.GetRasterBand(1).GetUnitType() - if unittype != 'cm': - gdaltest.post_reason('Invalid UnitType after dataset reopen.') - return 'fail' + assert unittype == 'cm', 'Invalid UnitType after dataset reopen.' test_ds.GetRasterBand(1).SetUnitType('mm') test_ds = None test_ds = gdal.Open(test_ds_name, gdal.GA_ReadOnly) - if test_ds is None: - gdaltest.post_reason('Failed to reopen test dataset.') - return 'fail' + assert test_ds is not None, 'Failed to reopen test dataset.' unittype = test_ds.GetRasterBand(1).GetUnitType() - if unittype != 'mm': - gdaltest.post_reason('Invalid UnitType after dataset update.') - return 'fail' + assert unittype == 'mm', 'Invalid UnitType after dataset update.' test_ds.GetRasterBand(1).SetUnitType('ft') unittype = test_ds.GetRasterBand(1).GetUnitType() - if unittype != 'mm': - gdaltest.post_reason('Invalid UnitType after dataset update.') - return 'fail' + assert unittype == 'mm', 'Invalid UnitType after dataset update.' test_ds = None os.remove(test_ds_name) - return 'success' - ############################################################################### # Test read JPEG compressed RMF dataset -def rmf_27(): +def test_rmf_27(): if gdal.GetDriverByName('JPEG') is None: - return 'skip' + pytest.skip() cs1 = [50553, 27604, 36652] # cs2 = [51009, 27640, 37765] # osx, clang ds = gdal.Open('data/jpeg-in-rmf.rsw', 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.' md = ds.GetMetadata('IMAGE_STRUCTURE') - if md['COMPRESSION'] != 'JPEG': - gdaltest.post_reason('"COMPRESSION" value is "%s" but expected "JPEG"' % + assert md['COMPRESSION'] == 'JPEG', \ + ('"COMPRESSION" value is "%s" but expected "JPEG"' % md['COMPRESSION']) - return 'fail' cs = [0, 0, 0] for iBand in range(ds.RasterCount): band = ds.GetRasterBand(iBand + 1) cs[iBand] = band.Checksum() - if cs != cs1 and cs != cs2: - gdaltest.post_reason('Invalid checksum %s expected %s or %s.' % + assert cs == cs1 or cs == cs2, ('Invalid checksum %s expected %s or %s.' % (str(cs), str(cs1), str(cs2))) - return 'fail' - - return 'success' ############################################################################### # Check compression metadata -def rmf_28a(): +def test_rmf_28a(): ds = gdal.Open('data/byte-lzw.rsw', 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.' md = ds.GetMetadata('IMAGE_STRUCTURE') - if md['COMPRESSION'] != 'LZW': - gdaltest.post_reason('"COMPRESSION" value is "%s" but expected "LZW"' % + assert md['COMPRESSION'] == 'LZW', \ + ('"COMPRESSION" value is "%s" but expected "LZW"' % md['COMPRESSION']) - return 'fail' - - return 'success' -def rmf_28b(): +def test_rmf_28b(): ds = gdal.Open('data/t100.mtw', 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.' md = ds.GetMetadata('IMAGE_STRUCTURE') - if md['COMPRESSION'] != 'RMF_DEM': - gdaltest.post_reason('"COMPRESSION" value is "%s" but expected "RMF_DEM"' % + assert md['COMPRESSION'] == 'RMF_DEM', \ + ('"COMPRESSION" value is "%s" but expected "RMF_DEM"' % md['COMPRESSION']) - return 'fail' - - return 'success' ############################################################################### # Check EPSG code -def rmf_29(): +def test_rmf_29(): rmf_drv = gdal.GetDriverByName('RMF') - if rmf_drv is None: - gdaltest.post_reason('RMF driver not found.') - return 'fail' + assert rmf_drv is not None, 'RMF driver not found.' ds = gdal.Open('data/byte.rsw', 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.' test_ds_name = 'tmp/epsg.rsw' test_ds = rmf_drv.CreateCopy(test_ds_name, ds) - if test_ds is None: - gdaltest.post_reason('Failed to create test dataset copy.') - return 'fail' + assert test_ds is not None, 'Failed to create test dataset copy.' sr = osr.SpatialReference() sr.SetFromUserInput('EPSG:3388') @@ -664,50 +567,39 @@ def rmf_29(): ds = None test_ds = gdal.Open(test_ds_name, gdal.GA_ReadOnly) - if test_ds is None: - gdaltest.post_reason('Failed to open test dataset.') - return 'fail' + assert test_ds is not None, 'Failed to open test dataset.' wkt = test_ds.GetProjectionRef() sr = osr.SpatialReference() sr.SetFromUserInput(wkt) - if str(sr.GetAuthorityCode(None)) != '3388': - gdaltest.post_reason('EPSG code is %s expected 3388.' % + assert str(sr.GetAuthorityCode(None)) == '3388', ('EPSG code is %s expected 3388.' % str(sr.GetAuthorityCode(None))) - return 'fail' - - return 'success' ############################################################################### # Check interleaved access -def rmf_30(): +def test_rmf_30(): ds_name = 'tmp/interleaved.tif' gdal.Translate(ds_name, 'data/rgbsmall-lzw.rsw', format='GTiff') ds = gdal.Open(ds_name) - if ds is None: - gdaltest.post_reason('Can\'t open ' + ds_name) - return 'fail' + assert ds is not None, ('Can\'t open ' + ds_name) expected_cs = [40503, 41429, 40238] cs = [ds.GetRasterBand(1).Checksum(), ds.GetRasterBand(2).Checksum(), ds.GetRasterBand(3).Checksum()] - if cs != expected_cs: - gdaltest.post_reason('Invalid checksum %s expected %s.' % + assert cs == expected_cs, ('Invalid checksum %s expected %s.' % (str(cs), str(expected_cs))) - return 'fail' - return 'success' ############################################################################### # Check compressed write -def rmf_31a(): +def test_rmf_31a(): tst = gdaltest.GDALTest('rmf', 'small_world.tif', 1, 30111, options=['COMPRESS=NONE']) @@ -715,7 +607,7 @@ def rmf_31a(): return tst.testCreateCopy(check_minmax=0, check_srs=1, check_gt=1) -def rmf_31b(): +def test_rmf_31b(): tst = gdaltest.GDALTest('rmf', 'small_world.tif', 1, 30111, options=['COMPRESS=LZW']) @@ -723,30 +615,26 @@ def rmf_31b(): return tst.testCreateCopy(check_minmax=0, check_srs=1, check_gt=1) -def rmf_31c(): +def test_rmf_31c(): ds_name = 'tmp/rmf_31c.rsw' gdal.Translate(ds_name, 'data/small_world.tif', format='RMF', options='-co COMPRESS=JPEG') ds = gdal.Open(ds_name) - if ds is None: - gdaltest.post_reason('Can\'t open ' + ds_name) - return 'fail' + assert ds is not None, ('Can\'t open ' + ds_name) expected_cs1 = [25789, 27405, 31974] expected_cs2 = [23764, 25264, 33585] # osx cs = [ds.GetRasterBand(1).Checksum(), ds.GetRasterBand(2).Checksum(), ds.GetRasterBand(3).Checksum()] - if cs != expected_cs1 and cs != expected_cs2: - gdaltest.post_reason('Invalid checksum %s expected %s or %s.' % + assert cs == expected_cs1 or cs == expected_cs2, \ + ('Invalid checksum %s expected %s or %s.' % (str(cs), str(expected_cs1), str(expected_cs2))) - return 'fail' - return 'success' -def rmf_31d(): +def test_rmf_31d(): tst = gdaltest.GDALTest('rmf', 't100.mtw', 1, 6388, options=['MTW=YES', 'COMPRESS=RMF_DEM']) @@ -754,24 +642,22 @@ def rmf_31d(): return tst.testCreateCopy(check_minmax=0, check_srs=1, check_gt=1) -def rmf_31e(): +def test_rmf_31e(): try: import numpy except ImportError: - return 'skip' + pytest.skip() drv = gdal.GetDriverByName('Gtiff') if drv is None: - return 'skip' + pytest.skip() # Create test data stripeSize = 32; sx = 256 sy = 8*stripeSize tst_name = 'tmp/rmf_31e.tif' tst_ds = drv.Create(tst_name, sx, sy, 1, gdal.GDT_Int32 ) - if tst_ds is None: - gdaltest.post_reason('Can\'t create ' + tst_name) - return 'fail' + assert tst_ds is not None, ('Can\'t create ' + tst_name) # No deltas buff = numpy.zeros((sx, stripeSize), dtype = numpy.int32) @@ -803,9 +689,7 @@ def rmf_31e(): tst_ds = None tst_ds = gdal.Open(tst_name) - if tst_ds is None: - gdaltest.post_reason('Can\'t open ' + tst_name) - return 'fail' + assert tst_ds is not None, ('Can\'t open ' + tst_name) cs = tst_ds.GetRasterBand(1).Checksum() tst_ds = None @@ -819,7 +703,7 @@ def rmf_31e(): ############################################################################### # Check parallel compression -def rmf_32a(): +def test_rmf_32a(): ds_name = 'tmp/rmf_32a.rsw' gdal.Translate(ds_name, 'data/small_world.tif', format='RMF', @@ -832,7 +716,7 @@ def rmf_32a(): return res -def rmf_32b(): +def test_rmf_32b(): ds_name = 'tmp/rmf_32b.rsw' gdal.Translate(ds_name, 'data/small_world.tif', format='RMF', @@ -849,7 +733,7 @@ def rmf_32b(): # Parallel build overviews on newly created RSW file -def rmf_32c(): +def test_rmf_32c(): ds_name = 'tmp/rmf_32c.rsw' gdal.Translate(ds_name, 'data/small_world.tif', format='RMF', options='-outsize 400% 400% -co COMPRESS=LZW -co NUM_THREADS=4') @@ -869,19 +753,19 @@ def rmf_32c(): # Read 1-bit & 4-bit files -def rmf_33a(): +def test_rmf_33a(): tst = gdaltest.GDALTest('rmf', '1bit.rsw', 1, 34325) return tst.testOpen() -def rmf_33b(): +def test_rmf_33b(): tst = gdaltest.GDALTest('rmf', '4bit.rsw', 1, 55221) return tst.testOpen() -def rmf_33c(): +def test_rmf_33c(): tst = gdaltest.GDALTest('rmf', '4bit-lzw.rsw', 1, 55221) return tst.testOpen() @@ -890,58 +774,4 @@ def rmf_33c(): ############################################################################### -gdaltest_list = [ - rmf_1, - rmf_2, - rmf_3, - rmf_4, - rmf_5, - rmf_6, - rmf_7, - rmf_8, - rmf_9, - rmf_10, - rmf_11, - rmf_12a, - rmf_12b, - rmf_12c, - rmf_12d, - rmf_13, - rmf_14, - rmf_15, - rmf_16, - rmf_17, - rmf_18, - rmf_19, - rmf_20, - rmf_21, - rmf_22, - rmf_23, - rmf_24, - rmf_25, - rmf_26, - rmf_27, - rmf_28a, - rmf_28b, - rmf_29, - rmf_30, - rmf_31a, - rmf_31b, - rmf_31c, - rmf_31d, - rmf_31e, - rmf_32a, - rmf_32b, - rmf_32c, - rmf_33a, - rmf_33b, - rmf_33c, -] - -if __name__ == '__main__': - - gdaltest.setup_run('rmf') - - gdaltest.run_tests(gdaltest_list) - - sys.exit(gdaltest.summarize()) + diff --git a/autotest/gdrivers/roipac.py b/autotest/gdrivers/roipac.py index 835aa0309308..e5e24087670f 100755 --- a/autotest/gdrivers/roipac.py +++ b/autotest/gdrivers/roipac.py @@ -29,10 +29,8 @@ # DEALINGS IN THE SOFTWARE. ############################################################################### -import sys from osgeo import gdal -sys.path.append('../pymod') import gdaltest @@ -40,7 +38,7 @@ # Perform simple read test. -def roipac_1(): +def test_roipac_1(): tst = gdaltest.GDALTest('roi_pac', 'srtm.dem', 1, 64074) @@ -64,20 +62,17 @@ def roipac_1(): # Test reading of metadata from the ROI_PAC metadata domain -def roipac_2(): +def test_roipac_2(): ds = gdal.Open('data/srtm.dem') val = ds.GetMetadataItem('YMAX', 'ROI_PAC') - if val != '9': - return 'fail' - - return 'success' + assert val == '9' ############################################################################### # Verify this can be exported losslessly. -def roipac_3(): +def test_roipac_3(): tst = gdaltest.GDALTest('roi_pac', 'srtm.dem', 1, 64074) return tst.testCreateCopy(check_gt=1, new_filename='strm.tst.dem') @@ -86,7 +81,7 @@ def roipac_3(): # Verify VSIF*L capacity -def roipac_4(): +def test_roipac_4(): tst = gdaltest.GDALTest('roi_pac', 'srtm.dem', 1, 64074) return tst.testCreateCopy(check_gt=1, new_filename='strm.tst.dem', vsimem=1) @@ -95,24 +90,20 @@ def roipac_4(): # Verify offset/scale metadata reading -def roipac_5(): +def test_roipac_5(): ds = gdal.Open('data/srtm.dem') band = ds.GetRasterBand(1) offset = band.GetOffset() - if offset != 1: - return 'fail' + assert offset == 1 scale = band.GetScale() - if scale != 2: - return 'fail' - - return 'success' + assert scale == 2 ############################################################################### # Test .flg -def roipac_6(): +def test_roipac_6(): tst = gdaltest.GDALTest('roi_pac', 'byte.tif', 1, 4672) with gdaltest.error_handler(): @@ -120,20 +111,5 @@ def roipac_6(): return ret -gdaltest_list = [ - roipac_1, - roipac_2, - roipac_3, - roipac_4, - roipac_5, - roipac_6, -] - - -if __name__ == '__main__': - - gdaltest.setup_run('roipac') - gdaltest.run_tests(gdaltest_list) - sys.exit(gdaltest.summarize()) diff --git a/autotest/gdrivers/rpftoc.py b/autotest/gdrivers/rpftoc.py index a6417d31fa65..8d7e4c3956ea 100755 --- a/autotest/gdrivers/rpftoc.py +++ b/autotest/gdrivers/rpftoc.py @@ -29,11 +29,9 @@ ############################################################################### import os -import sys import shutil from osgeo import gdal -sys.path.append('../pymod') import gdaltest @@ -42,7 +40,7 @@ # whose content is fully empty. -def rpftoc_1(): +def test_rpftoc_1(): tst = gdaltest.GDALTest('RPFTOC', 'NITF_TOC_ENTRY:CADRG_ONC_1,000,000_2_0:data/A.TOC', 1, 53599, filename_absolute=1) gt = (1.9999416000000001, 0.0017833876302083334, 0.0, 36.000117500000002, 0.0, -0.0013461816406249993) return tst.testOpen(check_gt=gt) @@ -51,7 +49,7 @@ def rpftoc_1(): # Same test as rpftoc_1, but the dataset is forced to be opened in RGBA mode -def rpftoc_2(): +def test_rpftoc_2(): gdal.SetConfigOption('RPFTOC_FORCE_RGBA', 'YES') tst = gdaltest.GDALTest('RPFTOC', 'NITF_TOC_ENTRY:CADRG_ONC_1,000,000_2_0:data/A.TOC', 1, 0, filename_absolute=1) res = tst.testOpen() @@ -62,26 +60,22 @@ def rpftoc_2(): # Test reading the metadata -def rpftoc_3(): +def test_rpftoc_3(): ds = gdal.Open('data/A.TOC') md = ds.GetMetadata('SUBDATASETS') - if 'SUBDATASET_1_NAME' not in md or md['SUBDATASET_1_NAME'] != 'NITF_TOC_ENTRY:CADRG_ONC_1,000,000_2_0:data/A.TOC': - gdaltest.post_reason('missing SUBDATASET_1_NAME metadata') - return 'fail' + assert 'SUBDATASET_1_NAME' in md and md['SUBDATASET_1_NAME'] == 'NITF_TOC_ENTRY:CADRG_ONC_1,000,000_2_0:data/A.TOC', \ + 'missing SUBDATASET_1_NAME metadata' ds = gdal.Open('NITF_TOC_ENTRY:CADRG_ONC_1,000,000_2_0:data/A.TOC') md = ds.GetMetadata() - if 'FILENAME_0' not in md or (md['FILENAME_0'] != 'data/RPFTOC01.ON2' and md['FILENAME_0'] != 'data\\RPFTOC01.ON2'): - gdaltest.post_reason('missing SUBDATASET_1_NAME metadata') - return 'fail' - - return 'success' + assert 'FILENAME_0' in md and not (md['FILENAME_0'] != 'data/RPFTOC01.ON2' and md['FILENAME_0'] != 'data\\RPFTOC01.ON2'), \ + 'missing SUBDATASET_1_NAME metadata' ############################################################################### # Add an overview -def rpftoc_4(): +def test_rpftoc_4(): gdal.SetConfigOption('RPFTOC_FORCE_RGBA', 'YES') shutil.copyfile('data/A.TOC', 'tmp/A.TOC') @@ -90,19 +84,15 @@ def rpftoc_4(): ds = gdal.Open('NITF_TOC_ENTRY:CADRG_ONC_1,000,000_2_0:tmp/A.TOC') 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' - if ds.GetRasterBand(1).GetOverviewCount() != 2: - gdaltest.post_reason('Overview missing on target file.') - return 'fail' + assert ds.GetRasterBand(1).GetOverviewCount() == 2, \ + 'Overview missing on target file.' ds = None ds = gdal.Open('NITF_TOC_ENTRY:CADRG_ONC_1,000,000_2_0:tmp/A.TOC') - if ds.GetRasterBand(1).GetOverviewCount() != 2: - gdaltest.post_reason('Overview missing on target file after re-open.') - return 'fail' + assert ds.GetRasterBand(1).GetOverviewCount() == 2, \ + 'Overview missing on target file after re-open.' ds = None @@ -112,19 +102,5 @@ def rpftoc_4(): os.unlink('tmp/A.TOC.1.ovr') os.unlink('tmp/RPFTOC01.ON2') - return 'success' - - -gdaltest_list = [ - rpftoc_1, - rpftoc_2, - rpftoc_3, - rpftoc_4] - -if __name__ == '__main__': - - gdaltest.setup_run('rpftoc') - gdaltest.run_tests(gdaltest_list) - sys.exit(gdaltest.summarize()) diff --git a/autotest/gdrivers/rraster.py b/autotest/gdrivers/rraster.py index f79091e0c50d..6357a528c92a 100755 --- a/autotest/gdrivers/rraster.py +++ b/autotest/gdrivers/rraster.py @@ -30,11 +30,9 @@ ############################################################################### import pprint -import sys from osgeo import gdal from osgeo import osr -sys.path.append('../pymod') import gdaltest @@ -42,47 +40,35 @@ # Perform simple read test. -def rraster_1(filename='data/byte_rraster.grd', check_prj=None): +def test_rraster_1(filename='data/byte_rraster.grd', check_prj=None): tst = gdaltest.GDALTest('RRASTER', filename, 1, 4672, filename_absolute=True) ref_ds = gdal.Open('data/byte.tif') if check_prj is None: check_prj = ref_ds.GetProjectionRef() - ret = tst.testOpen(check_prj=check_prj, + tst.testOpen(check_prj=check_prj, check_gt=ref_ds.GetGeoTransform(), check_min=74, check_max=255) - if ret != 'success': - return ret ds = gdal.Open(filename) md = ds.GetMetadata() - if md != {'CREATOR': "R package 'raster'", 'CREATED': '2016-06-25 17:32:47'}: - gdaltest.post_reason('fail') - print(md) - return 'fail' - if ds.GetRasterBand(1).GetDescription() != 'byte': - gdaltest.post_reason('fail') - return 'fail' - return 'success' + assert md == {'CREATOR': "R package 'raster'", 'CREATED': '2016-06-25 17:32:47'} + assert ds.GetRasterBand(1).GetDescription() == 'byte' ############################################################################### -def rraster_1_copy(): +def test_rraster_1_copy(): filename = '/vsimem/byte_rraster.grd' gdal.Translate(filename, 'data/byte_rraster.grd', format='RRASTER') - if gdal.VSIStatL(filename + '.aux.xml'): - gdaltest.post_reason('did not expect .aux.xml') - return 'fail' + assert not gdal.VSIStatL(filename + '.aux.xml'), 'did not expect .aux.xml' sr = osr.SpatialReference() sr.SetFromUserInput('+proj=utm +zone=11 +ellps=clrk66 +nadgrids=@conus,@alaska,@ntv2_0.gsb,@ntv1_can.dat +units=m +no_defs') - ret = rraster_1(filename, check_prj=sr.ExportToWkt()) + test_rraster_1(filename, check_prj=sr.ExportToWkt()) gdal.GetDriverByName('RRASTER').Delete(filename) - return ret - ############################################################################### @@ -122,7 +108,7 @@ def _is_dict_included_in_dict(got, expected, key_name='', to_print=None): ############################################################################### -def rraster_rgba(filename='data/rgba_rraster.grd'): +def test_rraster_rgba(filename='data/rgba_rraster.grd'): ds = gdal.Open(filename) info = gdal.Info(ds, computeChecksum=True, format='json') @@ -148,36 +134,28 @@ def rraster_rgba(filename='data/rgba_rraster.grd'): 'colorInterpretation': 'Alpha', 'description': 'alpha'}] } - if not _is_dict_included_in_dict(info, expected_info): - return 'fail' - - return 'success' + assert _is_dict_included_in_dict(info, expected_info) ############################################################################### -def rraster_rgba_copy(): +def test_rraster_rgba_copy(): filename = '/vsimem/rgba_rraster.grd' for creationOptions in [[], ['INTERLEAVE=BIP'], ['INTERLEAVE=BIL'], ['INTERLEAVE=BSQ']]: gdal.Translate(filename, 'data/rgba_rraster.grd', format='RRASTER', creationOptions=creationOptions) - if gdal.VSIStatL(filename + '.aux.xml'): - gdaltest.post_reason('did not expect .aux.xml') - return 'fail' - ret = rraster_rgba(filename) + assert not gdal.VSIStatL(filename + '.aux.xml'), 'did not expect .aux.xml' + print(creationOptions) + test_rraster_rgba(filename) gdal.GetDriverByName('RRASTER').Delete(filename) - if ret != 'success': - print(creationOptions) - return ret - - return 'success' + ############################################################################### -def rraster_ct_rgb(filename='data/byte_rraster_ct_rgb.grd'): +def test_rraster_ct_rgb(filename='data/byte_rraster_ct_rgb.grd'): ds = gdal.Open(filename) info = gdal.Info(ds, format='json') @@ -190,30 +168,23 @@ def rraster_ct_rgb(filename='data/byte_rraster_ct_rgb.grd'): 'palette': 'RGB'}, 'type': 'Byte'}] } - if not _is_dict_included_in_dict(info, expected_info): - return 'fail' - - return 'success' + assert _is_dict_included_in_dict(info, expected_info) ############################################################################### -def rraster_ct_rgb_copy(): +def test_rraster_ct_rgb_copy(): filename = '/vsimem/byte_rraster_ct_rgb.grd' gdal.Translate(filename, 'data/byte_rraster_ct_rgb.grd', format='RRASTER') - if gdal.VSIStatL(filename + '.aux.xml'): - gdaltest.post_reason('did not expect .aux.xml') - return 'fail' - ret = rraster_ct_rgb(filename) + assert not gdal.VSIStatL(filename + '.aux.xml'), 'did not expect .aux.xml' + test_rraster_ct_rgb(filename) gdal.GetDriverByName('RRASTER').Delete(filename) - return ret - ############################################################################### -def rraster_ct_rgba(filename='data/byte_rraster_ct_rgba.grd'): +def test_rraster_ct_rgba(filename='data/byte_rraster_ct_rgba.grd'): ds = gdal.Open(filename) info = gdal.Info(ds, format='json') @@ -226,30 +197,23 @@ def rraster_ct_rgba(filename='data/byte_rraster_ct_rgba.grd'): 'palette': 'RGB'}, 'type': 'Byte'}] } - if not _is_dict_included_in_dict(info, expected_info): - return 'fail' - - return 'success' + assert _is_dict_included_in_dict(info, expected_info) ############################################################################### -def rraster_ct_rgba_copy(): +def test_rraster_ct_rgba_copy(): filename = '/vsimem/byte_rraster_ct_rgba.grd' gdal.Translate(filename, 'data/byte_rraster_ct_rgba.grd', format='RRASTER') - if gdal.VSIStatL(filename + '.aux.xml'): - gdaltest.post_reason('did not expect .aux.xml') - return 'fail' - ret = rraster_ct_rgba(filename) + assert not gdal.VSIStatL(filename + '.aux.xml'), 'did not expect .aux.xml' + test_rraster_ct_rgba(filename) gdal.GetDriverByName('RRASTER').Delete(filename) - return ret - ############################################################################### -def rraster_rat(filename='data/byte_rraster_rat.grd'): +def test_rraster_rat(filename='data/byte_rraster_rat.grd'): ds = gdal.Open(filename) info = gdal.Info(ds, format='json') @@ -322,30 +286,23 @@ def rraster_rat(filename='data/byte_rraster_rat.grd'): 'baw'], 'index': 1}]} } - if not _is_dict_included_in_dict(info, expected_info): - return 'fail' - - return 'success' + assert _is_dict_included_in_dict(info, expected_info) ############################################################################### -def rraster_rat_copy(): +def test_rraster_rat_copy(): filename = '/vsimem/byte_rraster_rat.grd' gdal.Translate(filename, 'data/byte_rraster_rat.grd', format='RRASTER') - if gdal.VSIStatL(filename + '.aux.xml'): - gdaltest.post_reason('did not expect .aux.xml') - return 'fail' - ret = rraster_rat(filename) + assert not gdal.VSIStatL(filename + '.aux.xml'), 'did not expect .aux.xml' + test_rraster_rat(filename) gdal.GetDriverByName('RRASTER').Delete(filename) - return ret - ############################################################################### -def rraster_signedbyte(): +def test_rraster_signedbyte(): filename = '/vsimem/rraster_signedbyte.grd' filename2 = '/vsimem/rraster_signedbyte2.grd' @@ -354,23 +311,17 @@ def rraster_signedbyte(): gdal.Translate(filename2, filename, format='RRASTER') ds = gdal.Open(filename2) - if ds.GetRasterBand(1).GetMetadataItem('PIXELTYPE', 'IMAGE_STRUCTURE') != 'SIGNEDBYTE': - gdaltest.post_reason('fail') - return 'fail' - if ds.GetRasterBand(1).GetMinimum() != -124: - gdaltest.post_reason('fail') - return 'fail' + assert ds.GetRasterBand(1).GetMetadataItem('PIXELTYPE', 'IMAGE_STRUCTURE') == 'SIGNEDBYTE' + assert ds.GetRasterBand(1).GetMinimum() == -124 ds = None gdal.GetDriverByName('RRASTER').Delete(filename) gdal.GetDriverByName('RRASTER').Delete(filename2) - return 'success' - ############################################################################### -def rraster_datatypes(): +def test_rraster_datatypes(): filename = '/vsimem/temp.grd' @@ -383,23 +334,17 @@ def rraster_datatypes(): src_ds = gdal.Open(srcfilename) gdal.Translate(filename, src_ds, format='RRASTER') ds = gdal.Open(filename) - if ds.GetRasterBand(1).DataType != src_ds.GetRasterBand(1).DataType: - gdaltest.post_reason('fail') - print(srcfilename) - return 'fail' - if ds.GetRasterBand(1).Checksum() != src_ds.GetRasterBand(1).Checksum(): - gdaltest.post_reason('fail') - print(srcfilename) - return 'fail' + assert ds.GetRasterBand(1).DataType == src_ds.GetRasterBand(1).DataType, \ + srcfilename + assert ds.GetRasterBand(1).Checksum() == src_ds.GetRasterBand(1).Checksum(), \ + srcfilename gdal.GetDriverByName('RRASTER').Delete(filename) - return 'success' - ############################################################################### -def rraster_nodata_and_metadata(): +def test_rraster_nodata_and_metadata(): filename = '/vsimem/temp.grd' ds = gdal.GetDriverByName('RRASTER').Create(filename, 1, 1) @@ -410,46 +355,34 @@ def rraster_nodata_and_metadata(): ds.SetMetadataItem('CREATED', 'Today') ds = None ds = gdal.Open(filename) - if ds.GetMetadata() != {'CREATOR': 'GDAL', 'CREATED': 'Today'}: - gdaltest.post_reason('fail') - return 'fail' - if ds.GetRasterBand(1).GetNoDataValue() != 1: - gdaltest.post_reason('fail') - return 'fail' + assert ds.GetMetadata() == {'CREATOR': 'GDAL', 'CREATED': 'Today'} + assert ds.GetRasterBand(1).GetNoDataValue() == 1 ds = None gdal.GetDriverByName('RRASTER').Delete(filename) - return 'success' - ############################################################################### -def rraster_update(): +def test_rraster_update(): filename = '/vsimem/temp.grd' gdal.Translate(filename, 'data/byte_rraster.grd', format='RRASTER') gdal.Open(filename, gdal.GA_Update) ds = gdal.Open(filename, gdal.GA_Update) - if ds.GetRasterBand(1).Checksum() != 4672: - gdaltest.post_reason('fail') - return 'fail' + assert ds.GetRasterBand(1).Checksum() == 4672 ds.GetRasterBand(1).Fill(0) ds = None ds = gdal.Open(filename) - if ds.GetRasterBand(1).Checksum() != 0: - gdaltest.post_reason('fail') - return 'fail' + assert ds.GetRasterBand(1).Checksum() == 0 ds = None gdal.GetDriverByName('RRASTER').Delete(filename) - return 'success' - ############################################################################### -def rraster_colorinterpretation(): +def test_rraster_colorinterpretation(): filename = '/vsimem/temp.grd' ds = gdal.GetDriverByName('RRASTER').Create(filename, 1, 1, 4) @@ -459,48 +392,14 @@ def rraster_colorinterpretation(): ds.GetRasterBand(4).SetColorInterpretation(gdal.GCI_AlphaBand) ds = None ds = gdal.Open(filename) - 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_BlueBand: - gdaltest.post_reason('fail') - return 'fail' - if ds.GetRasterBand(4).GetColorInterpretation() != gdal.GCI_AlphaBand: - 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_BlueBand + assert ds.GetRasterBand(4).GetColorInterpretation() == gdal.GCI_AlphaBand ds = None gdal.GetDriverByName('RRASTER').Delete(filename) - return 'success' - - -gdaltest_list = [ - rraster_1, - rraster_1_copy, - rraster_rgba, - rraster_rgba_copy, - rraster_ct_rgb, - rraster_ct_rgb_copy, - rraster_ct_rgba, - rraster_ct_rgba_copy, - rraster_rat, - rraster_rat_copy, - rraster_signedbyte, - rraster_datatypes, - rraster_nodata_and_metadata, - rraster_update, - rraster_colorinterpretation, -] - - -if __name__ == '__main__': - gdaltest.setup_run('RRASTER') - gdaltest.run_tests(gdaltest_list) - sys.exit(gdaltest.summarize()) diff --git a/autotest/gdrivers/rs2.py b/autotest/gdrivers/rs2.py index d1c5bf40c9be..f90d3ce8df26 100755 --- a/autotest/gdrivers/rs2.py +++ b/autotest/gdrivers/rs2.py @@ -28,9 +28,7 @@ # DEALINGS IN THE SOFTWARE. ############################################################################### -import sys -sys.path.append('../pymod') from osgeo import gdal import gdaltest @@ -41,19 +39,19 @@ # evolves, this might break the test legitimately ! -def rs2_1(): +def test_rs2_1(): tst = gdaltest.GDALTest('RS2', 'product.xml', 1, 4672) return tst.testOpen() -def rs2_2(): +def test_rs2_2(): tst = gdaltest.GDALTest('RS2', 'RADARSAT_2_CALIB:BETA0:data/product.xml', 1, 4848, filename_absolute=1) return tst.testOpen() # Test reading our dummy RPC -def rs2_3(): +def test_rs2_3(): ds = gdal.Open('data/product.xml') got_rpc = ds.GetMetadata('RPC') expected_rpc = {'ERR_BIAS': 'biasError', @@ -72,22 +70,7 @@ def rs2_3(): 'SAMP_NUM_COEFF': 'pixelNumeratorCoefficients', 'SAMP_OFF': 'pixelOffset', 'SAMP_SCALE': 'pixelScale'} - if got_rpc != expected_rpc: - gdaltest.post_reason('fail') - print(got_rpc) - return 'fail' - return 'success' + assert got_rpc == expected_rpc -gdaltest_list = [ - rs2_1, - rs2_2, - rs2_3] -if __name__ == '__main__': - - gdaltest.setup_run('rs2') - - gdaltest.run_tests(gdaltest_list) - - sys.exit(gdaltest.summarize()) diff --git a/autotest/gdrivers/safe.py b/autotest/gdrivers/safe.py index 1102a8b8c53e..50b73b645bb6 100755 --- a/autotest/gdrivers/safe.py +++ b/autotest/gdrivers/safe.py @@ -28,9 +28,7 @@ # DEALINGS IN THE SOFTWARE. ############################################################################### -import sys -sys.path.append('../pymod') import gdaltest @@ -39,7 +37,7 @@ # reduced to 1% of their initial size and metadata stripped -def safe_1(): +def test_safe_1(): tst = gdaltest.GDALTest( 'SAFE', @@ -47,14 +45,14 @@ def safe_1(): return tst.testOpen() -def safe_2(): +def test_safe_2(): tst = gdaltest.GDALTest( 'SAFE', 'SAFE_FAKE/test.SAFE/manifest.safe', 2, 3732) return tst.testOpen() -def safe_3(): +def test_safe_3(): tst = gdaltest.GDALTest( 'SAFE', @@ -62,7 +60,7 @@ def safe_3(): return tst.testOpen() -def safe_4(): +def test_safe_4(): tst = gdaltest.GDALTest( 'SAFE', @@ -70,7 +68,7 @@ def safe_4(): return tst.testOpen() -def safe_5(): +def test_safe_5(): tst = gdaltest.GDALTest( 'SAFE', @@ -78,17 +76,4 @@ def safe_5(): return tst.testOpen() -gdaltest_list = [ - safe_1, - safe_2, - safe_3, - safe_4, - safe_5] -if __name__ == '__main__': - - gdaltest.setup_run('safe') - - gdaltest.run_tests(gdaltest_list) - - sys.exit(gdaltest.summarize()) diff --git a/autotest/gdrivers/saga.py b/autotest/gdrivers/saga.py index 271ae7042048..6a3c556c61d2 100755 --- a/autotest/gdrivers/saga.py +++ b/autotest/gdrivers/saga.py @@ -30,10 +30,8 @@ ############################################################################### import os -import sys from osgeo import gdal -sys.path.append('../pymod') import gdaltest @@ -41,7 +39,7 @@ # Test opening -def saga_1(): +def test_saga_1(): tst = gdaltest.GDALTest('SAGA', '4byteFloat.sdat', 1, 108) return tst.testOpen(check_prj="""PROJCS["NAD_1927_UTM_Zone_11N", @@ -62,7 +60,7 @@ def saga_1(): # Test copying a reference sample with CreateCopy() -def saga_2(): +def test_saga_2(): tst = gdaltest.GDALTest('SAGA', '4byteFloat.sdat', 1, 108) return tst.testCreateCopy(new_filename='tmp/createcopy.sdat', check_srs=True) @@ -71,7 +69,7 @@ def saga_2(): # Test copying a reference sample with Create() -def saga_3(): +def test_saga_3(): tst = gdaltest.GDALTest('SAGA', '4byteFloat.sdat', 1, 108) return tst.testCreate(new_filename='tmp/copy.sdat', out_bands=1) @@ -80,7 +78,7 @@ def saga_3(): # Test CreateCopy() for various data types -def saga_4(): +def test_saga_4(): src_files = ['byte.tif', 'int16.tif', @@ -96,17 +94,14 @@ def saga_4(): check_minmax = 0 else: check_minmax = 1 - ret = tst.testCreateCopy(new_filename='tmp/test4.sdat', check_minmax=check_minmax) - if ret != 'success': - return ret - - return 'success' + tst.testCreateCopy(new_filename='tmp/test4.sdat', check_minmax=check_minmax) + ############################################################################### # Test Create() for various data types -def saga_5(): +def test_saga_5(): src_files = ['byte.tif', 'int16.tif', @@ -122,17 +117,14 @@ def saga_5(): check_minmax = 0 else: check_minmax = 1 - ret = tst.testCreate(new_filename='tmp/test5.sdat', out_bands=1, check_minmax=check_minmax) - if ret != 'success': - return ret - - return 'success' + tst.testCreate(new_filename='tmp/test5.sdat', out_bands=1, check_minmax=check_minmax) + ############################################################################### # Test creating empty datasets and check that nodata values are properly written -def saga_6(): +def test_saga_6(): gdal_types = [gdal.GDT_Byte, gdal.GDT_Int16, @@ -156,16 +148,10 @@ def saga_6(): # Read raw data into tuple of float numbers import struct value = struct.unpack('d' * 1, data)[0] - if value != expected_nodata[i]: - print(value) - gdaltest.post_reason('did not get expected pixel value') - return 'fail' + assert value == expected_nodata[i], 'did not get expected pixel value' nodata = ds.GetRasterBand(1).GetNoDataValue() - if nodata != expected_nodata[i]: - print(nodata) - gdaltest.post_reason('did not get expected nodata value') - return 'fail' + assert nodata == expected_nodata[i], 'did not get expected nodata value' ds = None @@ -175,13 +161,12 @@ def saga_6(): except OSError: pass - return 'success' - + ############################################################################### # Test /vsimem -def saga_7(): +def test_saga_7(): tst = gdaltest.GDALTest('SAGA', '4byteFloat.sdat', 1, 108) return tst.testCreateCopy(new_filename='/vsimem/createcopy.sdat') @@ -190,7 +175,7 @@ def saga_7(): ############################################################################### # Test zipped saga grid (.sg-grd-z) -def saga_8(): +def test_saga_8(): tst = gdaltest.GDALTest('SAGA', '4byteFloat.sg-grd-z', 1, 108) return tst.testOpen(check_prj="""PROJCS["NAD_1927_UTM_Zone_11N", GEOGCS["GCS_North_American_1927", @@ -207,20 +192,4 @@ def saga_8(): UNIT["Meter",1]]""") -gdaltest_list = [ - saga_1, - saga_2, - saga_3, - saga_4, - saga_5, - saga_6, - saga_7, - saga_8] - -if __name__ == '__main__': - - gdaltest.setup_run('saga') - - gdaltest.run_tests(gdaltest_list) - sys.exit(gdaltest.summarize()) diff --git a/autotest/gdrivers/sar_ceos.py b/autotest/gdrivers/sar_ceos.py index 3c83fcaf1f2a..510a8f1b2648 100755 --- a/autotest/gdrivers/sar_ceos.py +++ b/autotest/gdrivers/sar_ceos.py @@ -28,16 +28,15 @@ # DEALINGS IN THE SOFTWARE. ############################################################################### -import sys -sys.path.append('../pymod') import gdaltest +import pytest ############################################################################### -def sar_ceos_online_1(): +def test_sar_ceos_online_1(): list_files = ['ottawa_patch.img', 'ottawa_patch.led', 'ottawa_patch.nul', @@ -46,19 +45,10 @@ def sar_ceos_online_1(): for filename in list_files: if not gdaltest.download_file('http://download.osgeo.org/gdal/data/ceos/' + filename, filename): - return 'skip' + pytest.skip() tst = gdaltest.GDALTest('SAR_CEOS', 'tmp/cache/ottawa_patch.img', 1, 23026, filename_absolute=1) return tst.testOpen() -gdaltest_list = [ - sar_ceos_online_1] -if __name__ == '__main__': - - gdaltest.setup_run('sar_ceos') - - gdaltest.run_tests(gdaltest_list) - - sys.exit(gdaltest.summarize()) diff --git a/autotest/gdrivers/sdts.py b/autotest/gdrivers/sdts.py index f80f92ffcfa9..1f8ef7b3bf99 100755 --- a/autotest/gdrivers/sdts.py +++ b/autotest/gdrivers/sdts.py @@ -28,11 +28,9 @@ # DEALINGS IN THE SOFTWARE. ############################################################################### -import sys from osgeo import gdal from osgeo import osr -sys.path.append('../pymod') import gdaltest @@ -41,32 +39,20 @@ # http://thor-f5.er.usgs.gov/sdts/datasets/raster/dem/dem_oct_2001/1107834.dem.sdts.tar.gz -def sdts_1(): +def test_sdts_1(): tst = gdaltest.GDALTest('SDTS', 'STDS_1107834_truncated/1107CATD.DDF', 1, 61672) srs = osr.SpatialReference() srs.SetWellKnownGeogCS('NAD27') srs.SetUTM(16) - if tst.testOpen(check_prj=srs.ExportToWkt(), + tst.testOpen(check_prj=srs.ExportToWkt(), check_gt=(666015, 30, 0, 5040735, 0, -30), - check_filelist=False) != 'success': - return 'fail' + check_filelist=False) ds = gdal.Open('data/STDS_1107834_truncated/1107CATD.DDF') md = ds.GetMetadata() - if md['TITLE'] != 'ALANSON, MI-24000': - return 'fail' + assert md['TITLE'] == 'ALANSON, MI-24000' - return 'success' -gdaltest_list = [sdts_1] - -if __name__ == '__main__': - - gdaltest.setup_run('sdts') - - gdaltest.run_tests(gdaltest_list) - - sys.exit(gdaltest.summarize()) diff --git a/autotest/gdrivers/sentinel2.py b/autotest/gdrivers/sentinel2.py index 6602278729b4..5bd74760a4f9 100755 --- a/autotest/gdrivers/sentinel2.py +++ b/autotest/gdrivers/sentinel2.py @@ -33,22 +33,20 @@ import sys from osgeo import gdal -sys.path.append('../pymod') import gdaltest +import pytest ############################################################################### # Test opening a L1C product -def sentinel2_l1c_1(): +def test_sentinel2_l1c_1(): filename_xml = 'data/fake_sentinel2_l1c/S2A_OPER_PRD_MSIL1C.SAFE/S2A_OPER_MTD_SAFL1C.xml' gdal.ErrorReset() ds = gdal.Open(filename_xml) - if ds is None or gdal.GetLastErrorMsg() != '': - gdaltest.post_reason('fail') - return 'fail' + assert ds is not None and gdal.GetLastErrorMsg() == '' expected_md = {'CLOUD_COVERAGE_ASSESSMENT': '0.0', 'DATATAKE_1_DATATAKE_SENSING_START': '2015-12-31T23:59:59.999Z', @@ -80,10 +78,9 @@ def sentinel2_l1c_1(): 'SPECIAL_VALUE_SATURATED': '0'} got_md = ds.GetMetadata() if got_md != expected_md: - gdaltest.post_reason('fail') import pprint pprint.pprint(got_md) - return 'fail' + pytest.fail() expected_md = {'SUBDATASET_1_DESC': 'Bands B2, B3, B4, B8 with 10m resolution, UTM 32N', 'SUBDATASET_1_NAME': 'SENTINEL2_L1C:data/fake_sentinel2_l1c/S2A_OPER_PRD_MSIL1C.SAFE/S2A_OPER_MTD_SAFL1C.xml:10m:EPSG_32632', @@ -95,29 +92,24 @@ def sentinel2_l1c_1(): 'SUBDATASET_4_NAME': 'SENTINEL2_L1C:data/fake_sentinel2_l1c/S2A_OPER_PRD_MSIL1C.SAFE/S2A_OPER_MTD_SAFL1C.xml:PREVIEW:EPSG_32632'} got_md = ds.GetMetadata('SUBDATASETS') if got_md != expected_md: - gdaltest.post_reason('fail') import pprint pprint.pprint(got_md) - return 'fail' + pytest.fail() # Try opening a zip file as distributed from https://scihub.esa.int/ if not sys.platform.startswith('win'): os.system('sh -c "cd data/fake_sentinel2_l1c && zip -r ../../tmp/S2A_OPER_PRD_MSIL1C.zip S2A_OPER_PRD_MSIL1C.SAFE >/dev/null" && cd ../..') if os.path.exists('tmp/S2A_OPER_PRD_MSIL1C.zip'): ds = gdal.Open('tmp/S2A_OPER_PRD_MSIL1C.zip') - if ds is None: - gdaltest.post_reason('fail') - return 'fail' + assert ds is not None os.unlink('tmp/S2A_OPER_PRD_MSIL1C.zip') # Try opening the 4 subdatasets for i in range(4): gdal.ErrorReset() ds = gdal.Open(got_md['SUBDATASET_%d_NAME' % (i + 1)]) - if ds is None or gdal.GetLastErrorMsg() != '': - gdaltest.post_reason('fail') - print(got_md['SUBDATASET_%d_NAME' % (i + 1)]) - return 'fail' + assert ds is not None and gdal.GetLastErrorMsg() == '', \ + got_md['SUBDATASET_%d_NAME' % (i + 1)] # Try various invalid subdataset names for name in ['SENTINEL2_L1C:', @@ -131,25 +123,19 @@ def sentinel2_l1c_1(): 'SENTINEL2_L1C:%s:10m:EPSG_32633' % filename_xml]: with gdaltest.error_handler(): ds = gdal.Open(name) - if ds is not None: - gdaltest.post_reason('fail') - print(name) - return 'fail' - - return 'success' + assert ds is None, name + ############################################################################### # Test opening a L1C subdataset on the 10m bands -def sentinel2_l1c_2(): +def test_sentinel2_l1c_2(): filename_xml = 'data/fake_sentinel2_l1c/S2A_OPER_PRD_MSIL1C.SAFE/S2A_OPER_MTD_SAFL1C.xml' gdal.ErrorReset() ds = gdal.Open('SENTINEL2_L1C:%s:10m:EPSG_32632' % filename_xml) - if ds is None or gdal.GetLastErrorMsg() != '': - gdaltest.post_reason('fail') - return 'fail' + assert ds is not None and gdal.GetLastErrorMsg() == '' expected_md = {'CLOUD_COVERAGE_ASSESSMENT': '0.0', 'DATATAKE_1_DATATAKE_SENSING_START': '2015-12-31T23:59:59.999Z', @@ -180,30 +166,18 @@ def sentinel2_l1c_2(): 'SPECIAL_VALUE_SATURATED': '0'} got_md = ds.GetMetadata() if got_md != expected_md: - gdaltest.post_reason('fail') import pprint pprint.pprint(got_md) - return 'fail' + pytest.fail() - if ds.RasterXSize != 20984 or ds.RasterYSize != 20980: - gdaltest.post_reason('fail') - print(ds.RasterXSize) - print(ds.RasterYSize) - return 'fail' + assert ds.RasterXSize == 20984 and ds.RasterYSize == 20980 - if ds.GetProjectionRef().find('32632') < 0: - gdaltest.post_reason('fail') - return 'fail' + assert ds.GetProjectionRef().find('32632') >= 0 got_gt = ds.GetGeoTransform() - if got_gt != (699960.0, 10.0, 0.0, 5100060.0, 0.0, -10.0): - gdaltest.post_reason('fail') - print(got_gt) - return 'fail' + assert got_gt == (699960.0, 10.0, 0.0, 5100060.0, 0.0, -10.0) - if ds.RasterCount != 4: - gdaltest.post_reason('fail') - return 'fail' + assert ds.RasterCount == 4 vrt = ds.GetMetadata('xml:VRT')[0] placement_vrt = """<SimpleSource> @@ -220,14 +194,9 @@ def sentinel2_l1c_2(): <SrcRect xOff="0" yOff="0" xSize="10980" ySize="10980" /> <DstRect xOff="10004" yOff="10000" xSize="10980" ySize="10980" /> </SimpleSource>""" - if vrt.find(placement_vrt) < 0: - gdaltest.post_reason('fail') - print(vrt) - return 'fail' + assert vrt.find(placement_vrt) >= 0 - if ds.GetMetadata('xml:SENTINEL2') is None: - gdaltest.post_reason('fail') - return 'fail' + assert ds.GetMetadata('xml:SENTINEL2') is not None band = ds.GetRasterBand(1) got_md = band.GetMetadata() @@ -239,28 +208,19 @@ def sentinel2_l1c_2(): 'WAVELENGTH': '665', 'WAVELENGTH_UNIT': 'nm'} if got_md != expected_md: - gdaltest.post_reason('fail') import pprint pprint.pprint(got_md) - return 'fail' + pytest.fail() - if band.GetColorInterpretation() != gdal.GCI_RedBand: - gdaltest.post_reason('fail') - return 'fail' + assert band.GetColorInterpretation() == gdal.GCI_RedBand - if band.DataType != gdal.GDT_UInt16: - gdaltest.post_reason('fail') - return 'fail' + assert band.DataType == gdal.GDT_UInt16 - if band.GetMetadataItem('NBITS', 'IMAGE_STRUCTURE') != '12': - gdaltest.post_reason('fail') - return 'fail' + assert band.GetMetadataItem('NBITS', 'IMAGE_STRUCTURE') == '12' band = ds.GetRasterBand(4) - if band.GetColorInterpretation() != gdal.GCI_Undefined: - gdaltest.post_reason('fail') - return 'fail' + assert band.GetColorInterpretation() == gdal.GCI_Undefined got_md = band.GetMetadata() expected_md = {'BANDNAME': 'B8', @@ -271,85 +231,62 @@ def sentinel2_l1c_2(): 'WAVELENGTH': '842', 'WAVELENGTH_UNIT': 'nm'} if got_md != expected_md: - gdaltest.post_reason('fail') import pprint pprint.pprint(got_md) - return 'fail' - - return 'success' + pytest.fail() + ############################################################################### # Test opening a L1C subdataset on the 60m bands and enabling alpha band -def sentinel2_l1c_3(): +def test_sentinel2_l1c_3(): filename_xml = 'data/fake_sentinel2_l1c/S2A_OPER_PRD_MSIL1C.SAFE/S2A_OPER_MTD_SAFL1C.xml' ds = gdal.OpenEx('SENTINEL2_L1C:%s:60m:EPSG_32632' % filename_xml, open_options=['ALPHA=YES']) - if ds is None: - gdaltest.post_reason('fail') - return 'fail' + assert ds is not None - if ds.RasterCount != 4: - gdaltest.post_reason('fail') - return 'fail' + assert ds.RasterCount == 4 band = ds.GetRasterBand(4) - if band.GetColorInterpretation() != gdal.GCI_AlphaBand: - gdaltest.post_reason('fail') - return 'fail' + assert band.GetColorInterpretation() == gdal.GCI_AlphaBand gdal.ErrorReset() cs = band.Checksum() - if cs != 0 or gdal.GetLastErrorMsg() != '': - gdaltest.post_reason('fail') - return 'fail' + assert cs == 0 and gdal.GetLastErrorMsg() == '' band.ReadRaster() - return 'success' - ############################################################################### # Test opening a L1C subdataset on the PREVIEW bands -def sentinel2_l1c_4(): +def test_sentinel2_l1c_4(): filename_xml = 'data/fake_sentinel2_l1c/S2A_OPER_PRD_MSIL1C.SAFE/S2A_OPER_MTD_SAFL1C.xml' ds = gdal.OpenEx('SENTINEL2_L1C:%s:PREVIEW:EPSG_32632' % filename_xml) - if ds is None: - gdaltest.post_reason('fail') - return 'fail' + assert ds is not None - if ds.RasterCount != 3: - gdaltest.post_reason('fail') - return 'fail' + assert ds.RasterCount == 3 fl = ds.GetFileList() # main XML + 2 granule XML + 2 jp2 if len(fl) != 1 + 2 + 2: - gdaltest.post_reason('fail') import pprint pprint.pprint(fl) - return 'fail' + pytest.fail() band = ds.GetRasterBand(1) - if band.GetColorInterpretation() != gdal.GCI_RedBand: - gdaltest.post_reason('fail') - return 'fail' - - if band.DataType != gdal.GDT_Byte: - gdaltest.post_reason('fail') - return 'fail' + assert band.GetColorInterpretation() == gdal.GCI_RedBand - return 'success' + assert band.DataType == gdal.GDT_Byte ############################################################################### # Test opening invalid XML files -def sentinel2_l1c_5(): +def test_sentinel2_l1c_5(): # Invalid XML gdal.FileFromMemBuffer('/vsimem/test.xml', @@ -358,15 +295,11 @@ def sentinel2_l1c_5(): with gdaltest.error_handler(): ds = gdal.Open('/vsimem/test.xml') - if ds is not None: - gdaltest.post_reason('fail') - return 'fail' + assert ds is None with gdaltest.error_handler(): ds = gdal.Open('SENTINEL2_L1C:/vsimem/test.xml:10m:EPSG_32632') - if ds is not None: - gdaltest.post_reason('fail') - return 'fail' + assert ds is None # File is OK, but granule MTD are missing gdal.FileFromMemBuffer('/vsimem/test.xml', @@ -439,16 +372,12 @@ def sentinel2_l1c_5(): gdal.ErrorReset() with gdaltest.error_handler(): gdal.Open('/vsimem/test.xml') - if gdal.GetLastErrorMsg() == '': - gdaltest.post_reason('fail') - return 'fail' + assert gdal.GetLastErrorMsg() != '' gdal.ErrorReset() with gdaltest.error_handler(): ds = gdal.Open('SENTINEL2_L1C:/vsimem/test.xml:10m:EPSG_32632') - if ds is not None: - gdaltest.post_reason('fail') - return 'fail' + assert ds is None # No Product_Info gdal.FileFromMemBuffer('/vsimem/test.xml', @@ -460,16 +389,12 @@ def sentinel2_l1c_5(): gdal.ErrorReset() with gdaltest.error_handler(): ds = gdal.Open('/vsimem/test.xml') - if ds is not None: - gdaltest.post_reason('fail') - return 'fail' + assert ds is None gdal.ErrorReset() with gdaltest.error_handler(): ds = gdal.Open('SENTINEL2_L1C:/vsimem/test.xml:10m:EPSG_32632') - if ds is not None: - gdaltest.post_reason('fail') - return 'fail' + assert ds is None # No Product_Organisation gdal.FileFromMemBuffer('/vsimem/test.xml', @@ -482,16 +407,12 @@ def sentinel2_l1c_5(): gdal.ErrorReset() with gdaltest.error_handler(): ds = gdal.Open('/vsimem/test.xml') - if ds is not None: - gdaltest.post_reason('fail') - return 'fail' + assert ds is None gdal.ErrorReset() with gdaltest.error_handler(): ds = gdal.Open('SENTINEL2_L1C:/vsimem/test.xml:10m:EPSG_32632') - if ds is not None: - gdaltest.post_reason('fail') - return 'fail' + assert ds is None # No Band_List gdal.FileFromMemBuffer('/vsimem/test.xml', @@ -507,9 +428,7 @@ def sentinel2_l1c_5(): gdal.ErrorReset() with gdaltest.error_handler(): ds = gdal.Open('/vsimem/test.xml') - if ds is not None: - gdaltest.post_reason('fail') - return 'fail' + assert ds is None # No valid bands gdal.FileFromMemBuffer('/vsimem/test.xml', @@ -530,46 +449,36 @@ def sentinel2_l1c_5(): gdal.ErrorReset() with gdaltest.error_handler(): ds = gdal.Open('/vsimem/test.xml') - if ds is not None: - gdaltest.post_reason('fail') - return 'fail' + assert ds is None gdal.Unlink('/vsimem/test.xml') - return 'success' - ############################################################################### # Windows specific test to test support for long filenames -def sentinel2_l1c_6(): +def test_sentinel2_l1c_6(): if sys.platform != 'win32': - return 'skip' + pytest.skip() filename_xml = 'data/fake_sentinel2_l1c/S2A_OPER_PRD_MSIL1C.SAFE/S2A_OPER_MTD_SAFL1C.xml' filename_xml = filename_xml.replace('/', '\\') filename_xml = '\\\\?\\' + os.getcwd() + '\\' + filename_xml gdal.ErrorReset() ds = gdal.Open(filename_xml) - if ds is None or gdal.GetLastErrorMsg() != '': - gdaltest.post_reason('fail') - return 'fail' + assert ds is not None and gdal.GetLastErrorMsg() == '' subds_name = ds.GetMetadataItem('SUBDATASET_1_NAME', 'SUBDATASETS') gdal.ErrorReset() ds = gdal.Open(subds_name) - if ds is None or gdal.GetLastErrorMsg() != '': - gdaltest.post_reason('fail') - return 'fail' - - return 'success' + assert ds is not None and gdal.GetLastErrorMsg() == '' ############################################################################### # Test with a real JP2 tile -def sentinel2_l1c_7(): +def test_sentinel2_l1c_7(): gdal.FileFromMemBuffer('/vsimem/test.xml', """<n1:Level-1C_User_Product xmlns:n1="https://psd-13.sentinel2.eo.esa.int/PSD/User_Product_Level-1C.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://pdgs.s2.esa.int/PSD/User_Product_Level-1C.xsd S2_User_Product_Level-1C_Metadata.xsd"> @@ -630,28 +539,21 @@ def sentinel2_l1c_7(): ds = gdal.Open('SENTINEL2_L1C:/vsimem/test.xml:60m:EPSG_32753') nbits = ds.GetRasterBand(1).GetMetadataItem('NBITS', 'IMAGE_STRUCTURE') - if nbits != '10': - gdaltest.post_reason('fail') - print(nbits) - return 'fail' + assert nbits == '10' gdal.Unlink('/vsimem/test.xml') gdal.Unlink('/vsimem/GRANULE/S2A_OPER_MSI_L1C_bla_N01.03/IMG_DATA/S2A_OPER_MSI_L1C_bla_B01.jp2') - return 'success' - ############################################################################### # Test opening a L1C tile -def sentinel2_l1c_tile_1(): +def test_sentinel2_l1c_tile_1(): filename_xml = 'data/fake_sentinel2_l1c/S2A_OPER_PRD_MSIL1C.SAFE/GRANULE/S2A_OPER_MSI_L1C_T32TQR_N01.03/S2A_OPER_MTD_L1C_T32TQR.xml' gdal.ErrorReset() ds = gdal.Open(filename_xml) - if ds is None or gdal.GetLastErrorMsg() != '': - gdaltest.post_reason('fail') - return 'fail' + assert ds is not None and gdal.GetLastErrorMsg() == '' expected_md = {'CLOUDY_PIXEL_PERCENTAGE': '0', 'DATASTRIP_ID': 'S2A_OPER_MSI_L1C_DS_MTI__20151231T235959_S20151231T235959_N01.03', @@ -686,10 +588,9 @@ def sentinel2_l1c_tile_1(): 'TILE_ID': 'S2A_OPER_MSI_L1C_TL_MTI__20151231T235959_A000123_T32TQR_N01.03'} got_md = ds.GetMetadata() if got_md != expected_md: - gdaltest.post_reason('fail') import pprint pprint.pprint(got_md) - return 'fail' + pytest.fail() expected_md = {'SUBDATASET_1_DESC': 'Bands B2, B3, B4, B8 with 10m resolution', 'SUBDATASET_1_NAME': 'SENTINEL2_L1C_TILE:data/fake_sentinel2_l1c/S2A_OPER_PRD_MSIL1C.SAFE/GRANULE/S2A_OPER_MSI_L1C_T32TQR_N01.03/S2A_OPER_MTD_L1C_T32TQR.xml:10m', @@ -701,19 +602,16 @@ def sentinel2_l1c_tile_1(): 'SUBDATASET_4_NAME': 'SENTINEL2_L1C_TILE:data/fake_sentinel2_l1c/S2A_OPER_PRD_MSIL1C.SAFE/GRANULE/S2A_OPER_MSI_L1C_T32TQR_N01.03/S2A_OPER_MTD_L1C_T32TQR.xml:PREVIEW'} got_md = ds.GetMetadata('SUBDATASETS') if got_md != expected_md: - gdaltest.post_reason('fail') import pprint pprint.pprint(got_md) - return 'fail' + pytest.fail() # Try opening the 4 subdatasets for i in range(4): gdal.ErrorReset() ds = gdal.Open(got_md['SUBDATASET_%d_NAME' % (i + 1)]) - if ds is None or gdal.GetLastErrorMsg() != '': - gdaltest.post_reason('fail') - print(got_md['SUBDATASET_%d_NAME' % (i + 1)]) - return 'fail' + assert ds is not None and gdal.GetLastErrorMsg() == '', \ + got_md['SUBDATASET_%d_NAME' % (i + 1)] # Try various invalid subdataset names for name in ['SENTINEL2_L1C_TILE:', @@ -722,27 +620,21 @@ def sentinel2_l1c_tile_1(): 'SENTINEL2_L1C_TILE:%s:' % filename_xml]: with gdaltest.error_handler(): ds = gdal.Open(name) - if ds is not None: - gdaltest.post_reason('fail') - print(name) - return 'fail' - - return 'success' + assert ds is None, name + ############################################################################### # Test opening a L1C tile without main MTD file -def sentinel2_l1c_tile_2(): +def test_sentinel2_l1c_tile_2(): filename_xml = 'data/fake_sentinel2_l1c/S2A_OPER_PRD_MSIL1C.SAFE/GRANULE/S2A_OPER_MSI_L1C_T32TQR_N01.03/S2A_OPER_MTD_L1C_T32TQR.xml' gdal.ErrorReset() gdal.SetConfigOption('SENTINEL2_USE_MAIN_MTD', 'NO') # Simulate absence of main MTD file ds = gdal.Open(filename_xml) gdal.SetConfigOption('SENTINEL2_USE_MAIN_MTD', None) - if ds is None or gdal.GetLastErrorMsg() != '': - gdaltest.post_reason('fail') - return 'fail' + assert ds is not None and gdal.GetLastErrorMsg() == '' expected_md = {'CLOUDY_PIXEL_PERCENTAGE': '0', 'DATASTRIP_ID': 'S2A_OPER_MSI_L1C_DS_MTI__20151231T235959_S20151231T235959_N01.03', @@ -752,10 +644,9 @@ def sentinel2_l1c_tile_2(): 'TILE_ID': 'S2A_OPER_MSI_L1C_TL_MTI__20151231T235959_A000123_T32TQR_N01.03'} got_md = ds.GetMetadata() if got_md != expected_md: - gdaltest.post_reason('fail') import pprint pprint.pprint(got_md) - return 'fail' + pytest.fail() expected_md = {'SUBDATASET_1_DESC': 'Bands B2, B3, B4, B8 with 10m resolution', 'SUBDATASET_1_NAME': 'SENTINEL2_L1C_TILE:data/fake_sentinel2_l1c/S2A_OPER_PRD_MSIL1C.SAFE/GRANULE/S2A_OPER_MSI_L1C_T32TQR_N01.03/S2A_OPER_MTD_L1C_T32TQR.xml:10m', @@ -767,25 +658,21 @@ def sentinel2_l1c_tile_2(): 'SUBDATASET_4_NAME': 'SENTINEL2_L1C_TILE:data/fake_sentinel2_l1c/S2A_OPER_PRD_MSIL1C.SAFE/GRANULE/S2A_OPER_MSI_L1C_T32TQR_N01.03/S2A_OPER_MTD_L1C_T32TQR.xml:PREVIEW'} got_md = ds.GetMetadata('SUBDATASETS') if got_md != expected_md: - gdaltest.post_reason('fail') import pprint pprint.pprint(got_md) - return 'fail' - - return 'success' + pytest.fail() + ############################################################################### # Test opening a L1C tile subdataset on the 10m bands -def sentinel2_l1c_tile_3(): +def test_sentinel2_l1c_tile_3(): filename_xml = 'data/fake_sentinel2_l1c/S2A_OPER_PRD_MSIL1C.SAFE/GRANULE/S2A_OPER_MSI_L1C_T32TQR_N01.03/S2A_OPER_MTD_L1C_T32TQR.xml' gdal.ErrorReset() ds = gdal.Open('SENTINEL2_L1C_TILE:%s:10m' % filename_xml) - if ds is None or gdal.GetLastErrorMsg() != '': - gdaltest.post_reason('fail') - return 'fail' + assert ds is not None and gdal.GetLastErrorMsg() == '' expected_md = {'CLOUDY_PIXEL_PERCENTAGE': '0', 'DATASTRIP_ID': 'S2A_OPER_MSI_L1C_DS_MTI__20151231T235959_S20151231T235959_N01.03', @@ -820,30 +707,18 @@ def sentinel2_l1c_tile_3(): 'TILE_ID': 'S2A_OPER_MSI_L1C_TL_MTI__20151231T235959_A000123_T32TQR_N01.03'} got_md = ds.GetMetadata() if got_md != expected_md: - gdaltest.post_reason('fail') import pprint pprint.pprint(got_md) - return 'fail' + pytest.fail() - if ds.RasterXSize != 10980 or ds.RasterYSize != 10980: - gdaltest.post_reason('fail') - print(ds.RasterXSize) - print(ds.RasterYSize) - return 'fail' + assert ds.RasterXSize == 10980 and ds.RasterYSize == 10980 - if ds.GetProjectionRef().find('32632') < 0: - gdaltest.post_reason('fail') - return 'fail' + assert ds.GetProjectionRef().find('32632') >= 0 got_gt = ds.GetGeoTransform() - if got_gt != (699960.0, 10.0, 0.0, 5100060.0, 0.0, -10.0): - gdaltest.post_reason('fail') - print(got_gt) - return 'fail' + assert got_gt == (699960.0, 10.0, 0.0, 5100060.0, 0.0, -10.0) - if ds.RasterCount != 4: - gdaltest.post_reason('fail') - return 'fail' + assert ds.RasterCount == 4 vrt = ds.GetMetadata('xml:VRT')[0] placement_vrt = """<SimpleSource> @@ -853,14 +728,9 @@ def sentinel2_l1c_tile_3(): <SrcRect xOff="0" yOff="0" xSize="10980" ySize="10980" /> <DstRect xOff="0" yOff="0" xSize="10980" ySize="10980" /> </SimpleSource>""" - if vrt.find(placement_vrt) < 0: - gdaltest.post_reason('fail') - print(vrt) - return 'fail' + assert vrt.find(placement_vrt) >= 0 - if ds.GetMetadata('xml:SENTINEL2') is None: - gdaltest.post_reason('fail') - return 'fail' + assert ds.GetMetadata('xml:SENTINEL2') is not None band = ds.GetRasterBand(1) got_md = band.GetMetadata() @@ -872,28 +742,19 @@ def sentinel2_l1c_tile_3(): 'WAVELENGTH': '665', 'WAVELENGTH_UNIT': 'nm'} if got_md != expected_md: - gdaltest.post_reason('fail') import pprint pprint.pprint(got_md) - return 'fail' + pytest.fail() - if band.GetColorInterpretation() != gdal.GCI_RedBand: - gdaltest.post_reason('fail') - return 'fail' + assert band.GetColorInterpretation() == gdal.GCI_RedBand - if band.DataType != gdal.GDT_UInt16: - gdaltest.post_reason('fail') - return 'fail' + assert band.DataType == gdal.GDT_UInt16 - if band.GetMetadataItem('NBITS', 'IMAGE_STRUCTURE') != '12': - gdaltest.post_reason('fail') - return 'fail' + assert band.GetMetadataItem('NBITS', 'IMAGE_STRUCTURE') == '12' band = ds.GetRasterBand(4) - if band.GetColorInterpretation() != gdal.GCI_Undefined: - gdaltest.post_reason('fail') - return 'fail' + assert band.GetColorInterpretation() == gdal.GCI_Undefined got_md = band.GetMetadata() expected_md = {'BANDNAME': 'B8', @@ -904,27 +765,23 @@ def sentinel2_l1c_tile_3(): 'WAVELENGTH': '842', 'WAVELENGTH_UNIT': 'nm'} if got_md != expected_md: - gdaltest.post_reason('fail') import pprint pprint.pprint(got_md) - return 'fail' - - return 'success' + pytest.fail() + ############################################################################### # Test opening a L1C tile subdataset on the 10m bands without main MTD file -def sentinel2_l1c_tile_4(): +def test_sentinel2_l1c_tile_4(): filename_xml = 'data/fake_sentinel2_l1c/S2A_OPER_PRD_MSIL1C.SAFE/GRANULE/S2A_OPER_MSI_L1C_T32TQR_N01.03/S2A_OPER_MTD_L1C_T32TQR.xml' gdal.ErrorReset() gdal.SetConfigOption('SENTINEL2_USE_MAIN_MTD', 'NO') # Simulate absence of main MTD file ds = gdal.OpenEx('SENTINEL2_L1C_TILE:%s:10m' % filename_xml, open_options=['ALPHA=YES']) gdal.SetConfigOption('SENTINEL2_USE_MAIN_MTD', None) - if ds is None or gdal.GetLastErrorMsg() != '': - gdaltest.post_reason('fail') - return 'fail' + assert ds is not None and gdal.GetLastErrorMsg() == '' expected_md = {'CLOUDY_PIXEL_PERCENTAGE': '0', 'DATASTRIP_ID': 'S2A_OPER_MSI_L1C_DS_MTI__20151231T235959_S20151231T235959_N01.03', @@ -934,30 +791,18 @@ def sentinel2_l1c_tile_4(): 'TILE_ID': 'S2A_OPER_MSI_L1C_TL_MTI__20151231T235959_A000123_T32TQR_N01.03'} got_md = ds.GetMetadata() if got_md != expected_md: - gdaltest.post_reason('fail') import pprint pprint.pprint(got_md) - return 'fail' + pytest.fail() - if ds.RasterXSize != 10980 or ds.RasterYSize != 10980: - gdaltest.post_reason('fail') - print(ds.RasterXSize) - print(ds.RasterYSize) - return 'fail' + assert ds.RasterXSize == 10980 and ds.RasterYSize == 10980 - if ds.GetProjectionRef().find('32632') < 0: - gdaltest.post_reason('fail') - return 'fail' + assert ds.GetProjectionRef().find('32632') >= 0 got_gt = ds.GetGeoTransform() - if got_gt != (699960.0, 10.0, 0.0, 5100060.0, 0.0, -10.0): - gdaltest.post_reason('fail') - print(got_gt) - return 'fail' + assert got_gt == (699960.0, 10.0, 0.0, 5100060.0, 0.0, -10.0) - if ds.RasterCount != 5: - gdaltest.post_reason('fail') - return 'fail' + assert ds.RasterCount == 5 vrt = ds.GetMetadata('xml:VRT')[0] placement_vrt = """<SimpleSource> @@ -967,14 +812,9 @@ def sentinel2_l1c_tile_4(): <SrcRect xOff="0" yOff="0" xSize="10980" ySize="10980" /> <DstRect xOff="0" yOff="0" xSize="10980" ySize="10980" /> </SimpleSource>""" - if vrt.find(placement_vrt) < 0: - gdaltest.post_reason('fail') - print(vrt) - return 'fail' + assert vrt.find(placement_vrt) >= 0 - if ds.GetMetadata('xml:SENTINEL2') is None: - gdaltest.post_reason('fail') - return 'fail' + assert ds.GetMetadata('xml:SENTINEL2') is not None band = ds.GetRasterBand(1) got_md = band.GetMetadata() @@ -984,63 +824,39 @@ def sentinel2_l1c_tile_4(): 'WAVELENGTH': '665', 'WAVELENGTH_UNIT': 'nm'} if got_md != expected_md: - gdaltest.post_reason('fail') import pprint pprint.pprint(got_md) - return 'fail' + pytest.fail() - if band.GetColorInterpretation() != gdal.GCI_RedBand: - gdaltest.post_reason('fail') - return 'fail' + assert band.GetColorInterpretation() == gdal.GCI_RedBand - if band.DataType != gdal.GDT_UInt16: - gdaltest.post_reason('fail') - return 'fail' + assert band.DataType == gdal.GDT_UInt16 - if band.GetMetadataItem('NBITS', 'IMAGE_STRUCTURE') != '12': - gdaltest.post_reason('fail') - return 'fail' + assert band.GetMetadataItem('NBITS', 'IMAGE_STRUCTURE') == '12' band = ds.GetRasterBand(5) - if band.GetColorInterpretation() != gdal.GCI_AlphaBand: - gdaltest.post_reason('fail') - return 'fail' - - return 'success' + assert band.GetColorInterpretation() == gdal.GCI_AlphaBand ############################################################################### # Test opening a L1C tile subdataset on the preview bands -def sentinel2_l1c_tile_5(): +def test_sentinel2_l1c_tile_5(): filename_xml = 'data/fake_sentinel2_l1c/S2A_OPER_PRD_MSIL1C.SAFE/GRANULE/S2A_OPER_MSI_L1C_T32TQR_N01.03/S2A_OPER_MTD_L1C_T32TQR.xml' gdal.ErrorReset() ds = gdal.Open('SENTINEL2_L1C_TILE:%s:PREVIEW' % filename_xml) - if ds is None or gdal.GetLastErrorMsg() != '': - gdaltest.post_reason('fail') - return 'fail' + assert ds is not None and gdal.GetLastErrorMsg() == '' - if ds.RasterXSize != 343 or ds.RasterYSize != 343: - gdaltest.post_reason('fail') - print(ds.RasterXSize) - print(ds.RasterYSize) - return 'fail' + assert ds.RasterXSize == 343 and ds.RasterYSize == 343 - if ds.GetProjectionRef().find('32632') < 0: - gdaltest.post_reason('fail') - return 'fail' + assert ds.GetProjectionRef().find('32632') >= 0 got_gt = ds.GetGeoTransform() - if got_gt != (699960.0, 320.0, 0.0, 5100060.0, 0.0, -320.0): - gdaltest.post_reason('fail') - print(got_gt) - return 'fail' + assert got_gt == (699960.0, 320.0, 0.0, 5100060.0, 0.0, -320.0) - if ds.RasterCount != 3: - gdaltest.post_reason('fail') - return 'fail' + assert ds.RasterCount == 3 vrt = ds.GetMetadata('xml:VRT')[0] placement_vrt = """<SimpleSource> @@ -1050,18 +866,13 @@ def sentinel2_l1c_tile_5(): <SrcRect xOff="0" yOff="0" xSize="343" ySize="343" /> <DstRect xOff="0" yOff="0" xSize="343" ySize="343" /> </SimpleSource>""" - if vrt.find(placement_vrt) < 0: - gdaltest.post_reason('fail') - print(vrt) - return 'fail' - - return 'success' + assert vrt.find(placement_vrt) >= 0 ############################################################################### # Test opening invalid XML files -def sentinel2_l1c_tile_6(): +def test_sentinel2_l1c_tile_6(): # Invalid XML gdal.FileFromMemBuffer('/vsimem/test.xml', @@ -1070,15 +881,11 @@ def sentinel2_l1c_tile_6(): with gdaltest.error_handler(): ds = gdal.Open('/vsimem/test.xml') - if ds is not None: - gdaltest.post_reason('fail') - return 'fail' + assert ds is None with gdaltest.error_handler(): ds = gdal.Open('SENTINEL2_L1C_TILE:/vsimem/test.xml:10m') - if ds is not None: - gdaltest.post_reason('fail') - return 'fail' + assert ds is None gdal.FileFromMemBuffer('/vsimem/GRANULE/S2A_OPER_MSI_L1C_bla_N01.03/S2A_OPER_MTD_L1C_bla.xml', """<?xml version="1.0" encoding="UTF-8" standalone="no"?> @@ -1110,27 +917,21 @@ def sentinel2_l1c_tile_6(): with gdaltest.error_handler(): ds = gdal.Open('SENTINEL2_L1C_TILE:/vsimem/GRANULE/S2A_OPER_MSI_L1C_bla_N01.03/S2A_OPER_MTD_L1C_bla.xml:10m') - if ds is not None: - gdaltest.post_reason('fail') - return 'fail' + assert ds is None gdal.Unlink('/vsimem/test.xml') gdal.Unlink('/vsimem/S2A_OPER_MSI_L1C_bla_N01.03/S2A_OPER_MTD_L1C_bla.xml') - return 'success' - ############################################################################### # Test opening a L1B product -def sentinel2_l1b_1(): +def test_sentinel2_l1b_1(): filename_xml = 'data/fake_sentinel2_l1b/S2B_OPER_PRD_MSIL1B.SAFE/S2B_OPER_MTD_SAFL1B.xml' gdal.ErrorReset() ds = gdal.Open(filename_xml) - if ds is None or gdal.GetLastErrorMsg() != '': - gdaltest.post_reason('fail') - return 'fail' + assert ds is not None and gdal.GetLastErrorMsg() == '' expected_md = {'CLOUD_COVERAGE_ASSESSMENT': '0.0', 'DATATAKE_1_DATATAKE_SENSING_START': '2015-12-31T23:59:59.999Z', @@ -1159,10 +960,9 @@ def sentinel2_l1b_1(): 'SPECIAL_VALUE_SATURATED': '0'} got_md = ds.GetMetadata() if got_md != expected_md: - gdaltest.post_reason('fail') import pprint pprint.pprint(got_md) - return 'fail' + pytest.fail() expected_md = {'SUBDATASET_1_DESC': 'Bands B2, B3, B4, B8 of granule S2B_OPER_MTD_L1B.xml with 10m resolution', 'SUBDATASET_1_NAME': 'SENTINEL2_L1B:data/fake_sentinel2_l1b/S2B_OPER_PRD_MSIL1B.SAFE/GRANULE/S2B_OPER_MSI_L1B_N01.03/S2B_OPER_MTD_L1B.xml:10m', @@ -1172,19 +972,16 @@ def sentinel2_l1b_1(): 'SUBDATASET_3_NAME': 'SENTINEL2_L1B:data/fake_sentinel2_l1b/S2B_OPER_PRD_MSIL1B.SAFE/GRANULE/S2B_OPER_MSI_L1B_N01.03/S2B_OPER_MTD_L1B.xml:60m'} got_md = ds.GetMetadata('SUBDATASETS') if got_md != expected_md: - gdaltest.post_reason('fail') import pprint pprint.pprint(got_md) - return 'fail' + pytest.fail() # Try opening the 3 subdatasets for i in range(3): gdal.ErrorReset() ds = gdal.Open(got_md['SUBDATASET_%d_NAME' % (i + 1)]) - if ds is None or gdal.GetLastErrorMsg() != '': - gdaltest.post_reason('fail') - print(got_md['SUBDATASET_%d_NAME' % (i + 1)]) - return 'fail' + assert ds is not None and gdal.GetLastErrorMsg() == '', \ + got_md['SUBDATASET_%d_NAME' % (i + 1)] # Try various invalid subdataset names for name in ['SENTINEL2_L1B:', @@ -1194,25 +991,19 @@ def sentinel2_l1b_1(): 'SENTINEL2_L1B:%s:30m' % filename_xml]: with gdaltest.error_handler(): ds = gdal.Open(name) - if ds is not None: - gdaltest.post_reason('fail') - print(name) - return 'fail' - - return 'success' + assert ds is None, name + ############################################################################### # Test opening a L1B granule -def sentinel2_l1b_2(): +def test_sentinel2_l1b_2(): filename_xml = 'data/fake_sentinel2_l1b/S2B_OPER_PRD_MSIL1B.SAFE/GRANULE/S2B_OPER_MSI_L1B_N01.03/S2B_OPER_MTD_L1B.xml' gdal.ErrorReset() ds = gdal.Open(filename_xml) - if ds is None or gdal.GetLastErrorMsg() != '': - gdaltest.post_reason('fail') - return 'fail' + assert ds is not None and gdal.GetLastErrorMsg() == '' expected_md = {'CLOUDY_PIXEL_PERCENTAGE': '0', 'DATASTRIP_ID': 'S2B_OPER_MSI_L1B_DS_MTI__20151231T235959_S20151231T235959_N01.03', @@ -1250,10 +1041,9 @@ def sentinel2_l1b_2(): 'SPECIAL_VALUE_SATURATED': '0'} got_md = ds.GetMetadata() if got_md != expected_md: - gdaltest.post_reason('fail') import pprint pprint.pprint(got_md) - return 'fail' + pytest.fail() subdatasets_md = {'SUBDATASET_1_DESC': 'Bands B2, B3, B4, B8 with 10m resolution', 'SUBDATASET_1_NAME': 'SENTINEL2_L1B:data/fake_sentinel2_l1b/S2B_OPER_PRD_MSIL1B.SAFE/GRANULE/S2B_OPER_MSI_L1B_N01.03/S2B_OPER_MTD_L1B.xml:10m', @@ -1263,10 +1053,9 @@ def sentinel2_l1b_2(): 'SUBDATASET_3_NAME': 'SENTINEL2_L1B:data/fake_sentinel2_l1b/S2B_OPER_PRD_MSIL1B.SAFE/GRANULE/S2B_OPER_MSI_L1B_N01.03/S2B_OPER_MTD_L1B.xml:60m'} got_md = ds.GetMetadata('SUBDATASETS') if got_md != subdatasets_md: - gdaltest.post_reason('fail') import pprint pprint.pprint(got_md) - return 'fail' + pytest.fail() cwd = os.getcwd() gdal.ErrorReset() @@ -1275,29 +1064,23 @@ def sentinel2_l1b_2(): ds = gdal.Open('S2B_OPER_MTD_L1B.xml') finally: os.chdir(cwd) - if ds is None or gdal.GetLastErrorMsg() != '': - gdaltest.post_reason('fail') - return 'fail' + assert ds is not None and gdal.GetLastErrorMsg() == '' got_md = ds.GetMetadata() if got_md != expected_md: - gdaltest.post_reason('fail') import pprint pprint.pprint(got_md) - return 'fail' - - return 'success' + pytest.fail() + ############################################################################### # Test opening a L1B subdataset -def sentinel2_l1b_3(): +def test_sentinel2_l1b_3(): gdal.ErrorReset() ds = gdal.Open('SENTINEL2_L1B:data/fake_sentinel2_l1b/S2B_OPER_PRD_MSIL1B.SAFE/GRANULE/S2B_OPER_MSI_L1B_N01.03/S2B_OPER_MTD_L1B.xml:60m') - if ds is None or gdal.GetLastErrorMsg() != '': - gdaltest.post_reason('fail') - return 'fail' + assert ds is not None and gdal.GetLastErrorMsg() == '' expected_md = {'CLOUDY_PIXEL_PERCENTAGE': '0', 'DATASTRIP_ID': 'S2B_OPER_MSI_L1B_DS_MTI__20151231T235959_S20151231T235959_N01.03', @@ -1335,75 +1118,48 @@ def sentinel2_l1b_3(): 'SPECIAL_VALUE_SATURATED': '0'} got_md = ds.GetMetadata() if got_md != expected_md: - gdaltest.post_reason('fail') import pprint pprint.pprint(got_md) - return 'fail' + pytest.fail() - if ds.RasterXSize != 1276 or ds.RasterYSize != 384: - gdaltest.post_reason('fail') - print(ds.RasterXSize) - print(ds.RasterYSize) - return 'fail' + assert ds.RasterXSize == 1276 and ds.RasterYSize == 384 - if ds.GetGCPProjection().find('4326') < 0: - gdaltest.post_reason('fail') - return 'fail' + assert ds.GetGCPProjection().find('4326') >= 0 gcps = ds.GetGCPs() - if len(gcps) != 5: - gdaltest.post_reason('fail') - print(len(gcps)) - return 'fail' - - if gcps[0].GCPPixel != 0 or \ - gcps[0].GCPLine != 0 or \ - gcps[0].GCPX != 11 or \ - gcps[0].GCPY != 46 or \ - gcps[0].GCPZ != 1: - gdaltest.post_reason('fail') - print(gcps[0]) - return 'fail' - - if gcps[1].GCPPixel != 0 or \ - gcps[1].GCPLine != 384 or \ - gcps[1].GCPX != 11 or \ - gcps[1].GCPY != 45 or \ - gcps[1].GCPZ != 2: - gdaltest.post_reason('fail') - print(gcps[1]) - return 'fail' - - if gcps[2].GCPPixel != 1276 or \ - gcps[2].GCPLine != 384 or \ - gcps[2].GCPX != 13 or \ - gcps[2].GCPY != 45 or \ - gcps[2].GCPZ != 3: - gdaltest.post_reason('fail') - print(gcps[2]) - return 'fail' - - if gcps[3].GCPPixel != 1276 or \ - gcps[3].GCPLine != 0 or \ - gcps[3].GCPX != 13 or \ - gcps[3].GCPY != 46 or \ - gcps[3].GCPZ != 4: - gdaltest.post_reason('fail') - print(gcps[3]) - return 'fail' - - if gcps[4].GCPPixel != 1276. / 2 or \ - gcps[4].GCPLine != 384. / 2 or \ - gcps[4].GCPX != 12 or \ - gcps[4].GCPY != 45.5 or \ - gcps[4].GCPZ != 2.5: - gdaltest.post_reason('fail') - print(gcps[4]) - return 'fail' - - if ds.RasterCount != 3: - gdaltest.post_reason('fail') - return 'fail' + assert len(gcps) == 5 + + assert (gcps[0].GCPPixel == 0 and \ + gcps[0].GCPLine == 0 and \ + gcps[0].GCPX == 11 and \ + gcps[0].GCPY == 46 and \ + gcps[0].GCPZ == 1) + + assert (gcps[1].GCPPixel == 0 and \ + gcps[1].GCPLine == 384 and \ + gcps[1].GCPX == 11 and \ + gcps[1].GCPY == 45 and \ + gcps[1].GCPZ == 2) + + assert (gcps[2].GCPPixel == 1276 and \ + gcps[2].GCPLine == 384 and \ + gcps[2].GCPX == 13 and \ + gcps[2].GCPY == 45 and \ + gcps[2].GCPZ == 3) + + assert (gcps[3].GCPPixel == 1276 and \ + gcps[3].GCPLine == 0 and \ + gcps[3].GCPX == 13 and \ + gcps[3].GCPY == 46 and \ + gcps[3].GCPZ == 4) + + assert (gcps[4].GCPPixel == 1276. / 2 and \ + gcps[4].GCPLine == 384. / 2 and \ + gcps[4].GCPX == 12 and \ + gcps[4].GCPY == 45.5 and \ + gcps[4].GCPZ == 2.5) + + assert ds.RasterCount == 3 vrt = ds.GetMetadata('xml:VRT')[0] placement_vrt = """<SimpleSource> @@ -1413,14 +1169,9 @@ def sentinel2_l1b_3(): <SrcRect xOff="0" yOff="0" xSize="1276" ySize="384" /> <DstRect xOff="0" yOff="0" xSize="1276" ySize="384" /> </SimpleSource>""" - if vrt.find(placement_vrt) < 0: - gdaltest.post_reason('fail') - print(vrt) - return 'fail' + assert vrt.find(placement_vrt) >= 0 - if ds.GetMetadata('xml:SENTINEL2') is None: - gdaltest.post_reason('fail') - return 'fail' + assert ds.GetMetadata('xml:SENTINEL2') is not None band = ds.GetRasterBand(1) got_md = band.GetMetadata() @@ -1430,26 +1181,19 @@ def sentinel2_l1b_3(): 'WAVELENGTH': '443', 'WAVELENGTH_UNIT': 'nm'} if got_md != expected_md: - gdaltest.post_reason('fail') import pprint pprint.pprint(got_md) - return 'fail' - - if band.DataType != gdal.GDT_UInt16: - gdaltest.post_reason('fail') - return 'fail' + pytest.fail() - if band.GetMetadataItem('NBITS', 'IMAGE_STRUCTURE') != '12': - gdaltest.post_reason('fail') - return 'fail' + assert band.DataType == gdal.GDT_UInt16 - return 'success' + assert band.GetMetadataItem('NBITS', 'IMAGE_STRUCTURE') == '12' ############################################################################### # Test opening a L1B granule (with missing tile, without any ../../main_mtd.xml) -def sentinel2_l1b_4(): +def test_sentinel2_l1b_4(): gdal.FileFromMemBuffer('/vsimem/foo/S2B_PROD_MTD_foo.xml', """<n1:Level-1B_User_Product xmlns:n1="https://psd-13.sentinel2.eo.esa.int/PSD/User_Product_Level-1B.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://pdgs.s2.esa.int/PSD/User_Product_Level-1B.xsd S2_User_Product_Level-1B_Metadata.xsd"> @@ -1510,9 +1254,7 @@ def sentinel2_l1b_4(): </n1:Level-1B_Granule_ID> """) ds = gdal.Open('SENTINEL2_L1B:/vsimem/foo/GRANULE/S2B_OPER_MTD_L1B_N01.03/S2B_OPER_MTD_L1B.xml:60m') - if ds.RasterXSize != 500: - gdaltest.post_reason('fail') - return 'fail' + assert ds.RasterXSize == 500 # With standard granule metadata (with Granule_Dimensions) gdal.FileFromMemBuffer('/vsimem/foo/GRANULE/S2B_OPER_MTD_L1B_N01.03/S2B_OPER_MTD_L1B.xml', @@ -1537,31 +1279,24 @@ def sentinel2_l1b_4(): 'SUBDATASET_1_NAME': 'SENTINEL2_L1B:/vsimem/foo/GRANULE/S2B_OPER_MTD_L1B_N01.03/S2B_OPER_MTD_L1B.xml:60m'} got_md = ds.GetMetadata('SUBDATASETS') if got_md != expected_md: - gdaltest.post_reason('fail') import pprint pprint.pprint(got_md) - return 'fail' + pytest.fail() ds = None ds = gdal.OpenEx('SENTINEL2_L1B:/vsimem/foo/GRANULE/S2B_OPER_MTD_L1B_N01.03/S2B_OPER_MTD_L1B.xml:60m', open_options=['ALPHA=YES']) - if ds is None: - gdaltest.post_reason('fail') - return 'fail' - if ds.RasterCount != 2: - gdaltest.post_reason('fail') - return 'fail' + assert ds is not None + assert ds.RasterCount == 2 ds = None gdal.Unlink('/vsimem/foo/GRANULE/S2B_OPER_MTD_L1B_N01.03/S2B_OPER_MTD_L1B.xml') gdal.Unlink('/vsimem/foo/GRANULE/S2B_OPER_MTD_L1B_N01.03/IMG_DATA/S2B_OPER_MSI_L1B_B01.jp2') - return 'success' - ############################################################################### # Test opening invalid XML files -def sentinel2_l1b_5(): +def test_sentinel2_l1b_5(): # Invalid XML gdal.FileFromMemBuffer('/vsimem/test.xml', @@ -1570,9 +1305,7 @@ def sentinel2_l1b_5(): with gdaltest.error_handler(): ds = gdal.Open('/vsimem/test.xml') - if ds is not None: - gdaltest.post_reason('fail') - return 'fail' + assert ds is None # No Product_Info gdal.FileFromMemBuffer('/vsimem/test.xml', @@ -1584,9 +1317,7 @@ def sentinel2_l1b_5(): gdal.ErrorReset() with gdaltest.error_handler(): ds = gdal.Open('/vsimem/test.xml') - if ds is not None: - gdaltest.post_reason('fail') - return 'fail' + assert ds is None # No Product_Organisation gdal.FileFromMemBuffer('/vsimem/test.xml', @@ -1599,16 +1330,12 @@ def sentinel2_l1b_5(): gdal.ErrorReset() with gdaltest.error_handler(): ds = gdal.Open('/vsimem/test.xml') - if ds is not None: - gdaltest.post_reason('fail') - return 'fail' + assert ds is None gdal.ErrorReset() with gdaltest.error_handler(): ds = gdal.Open('SENTINEL2_L1B:/vsimem/test.xml:10m') - if ds is not None: - gdaltest.post_reason('fail') - return 'fail' + assert ds is None # No Band_List gdal.FileFromMemBuffer('/vsimem/test.xml', @@ -1624,9 +1351,7 @@ def sentinel2_l1b_5(): gdal.ErrorReset() with gdaltest.error_handler(): ds = gdal.Open('/vsimem/test.xml') - if ds is not None: - gdaltest.post_reason('fail') - return 'fail' + assert ds is None # No valid bands gdal.FileFromMemBuffer('/vsimem/test.xml', @@ -1647,9 +1372,7 @@ def sentinel2_l1b_5(): gdal.ErrorReset() with gdaltest.error_handler(): ds = gdal.Open('/vsimem/test.xml') - if ds is not None: - gdaltest.post_reason('fail') - return 'fail' + assert ds is None # Invalid XML gdal.FileFromMemBuffer('/vsimem/test.xml', @@ -1658,16 +1381,12 @@ def sentinel2_l1b_5(): with gdaltest.error_handler(): ds = gdal.Open('/vsimem/test.xml') - if ds is not None: - gdaltest.post_reason('fail') - return 'fail' + assert ds is None gdal.ErrorReset() with gdaltest.error_handler(): ds = gdal.Open('SENTINEL2_L1B:/vsimem/test.xml:10m') - if ds is not None: - gdaltest.post_reason('fail') - return 'fail' + assert ds is None # No Granule_Dimensions gdal.FileFromMemBuffer('/vsimem/test.xml', @@ -1681,9 +1400,7 @@ def sentinel2_l1b_5(): gdal.ErrorReset() with gdaltest.error_handler(): ds = gdal.Open('SENTINEL2_L1B:/vsimem/test.xml:10m') - if ds is not None: - gdaltest.post_reason('fail') - return 'fail' + assert ds is None # No ROWS gdal.FileFromMemBuffer('/vsimem/test.xml', @@ -1703,9 +1420,7 @@ def sentinel2_l1b_5(): gdal.ErrorReset() with gdaltest.error_handler(): ds = gdal.Open('SENTINEL2_L1B:/vsimem/test.xml:10m') - if ds is not None: - gdaltest.post_reason('fail') - return 'fail' + assert ds is None # No NCOLS gdal.FileFromMemBuffer('/vsimem/test.xml', @@ -1725,9 +1440,7 @@ def sentinel2_l1b_5(): gdal.ErrorReset() with gdaltest.error_handler(): ds = gdal.Open('SENTINEL2_L1B:/vsimem/test.xml:10m') - if ds is not None: - gdaltest.post_reason('fail') - return 'fail' + assert ds is None # Not the desired resolution gdal.FileFromMemBuffer('/vsimem/test.xml', @@ -1743,27 +1456,21 @@ def sentinel2_l1b_5(): gdal.ErrorReset() with gdaltest.error_handler(): ds = gdal.Open('SENTINEL2_L1B:/vsimem/test.xml:10m') - if ds is not None: - gdaltest.post_reason('fail') - return 'fail' + assert ds is None gdal.Unlink('/vsimem/test.xml') gdal.Unlink('/vsimem/test.xml') - return 'success' - ############################################################################### # Test opening a L2A product -def sentinel2_l2a_1(): +def test_sentinel2_l2a_1(): filename_xml = 'data/fake_sentinel2_l2a/S2A_USER_PRD_MSIL2A.SAFE/S2A_USER_MTD_SAFL2A.xml' gdal.ErrorReset() ds = gdal.Open(filename_xml) - if ds is None or gdal.GetLastErrorMsg() != '': - gdaltest.post_reason('fail') - return 'fail' + assert ds is not None and gdal.GetLastErrorMsg() == '' expected_md = {'AOT_RETRIEVAL_ACCURACY': '0', 'BARE_SOILS_PERCENTAGE': '0', @@ -1817,10 +1524,9 @@ def sentinel2_l2a_1(): 'WATER_VAPOUR_RETRIEVAL_ACCURACY': '0'} got_md = ds.GetMetadata() if got_md != expected_md: - gdaltest.post_reason('fail') import pprint pprint.pprint(got_md) - return 'fail' + pytest.fail() expected_md = {'SUBDATASET_1_DESC': 'Bands B1, B2, B3, B4, B5, B6, B7, B9, B10, B11, B12, B8A, AOT, CLD, SCL, SNW, WVP with 60m resolution, UTM 32N', 'SUBDATASET_1_NAME': 'SENTINEL2_L2A:data/fake_sentinel2_l2a/S2A_USER_PRD_MSIL2A.SAFE/S2A_USER_MTD_SAFL2A.xml:60m:EPSG_32632', @@ -1828,19 +1534,16 @@ def sentinel2_l2a_1(): 'SUBDATASET_2_NAME': 'SENTINEL2_L2A:data/fake_sentinel2_l2a/S2A_USER_PRD_MSIL2A.SAFE/S2A_USER_MTD_SAFL2A.xml:PREVIEW:EPSG_32632'} got_md = ds.GetMetadata('SUBDATASETS') if got_md != expected_md: - gdaltest.post_reason('fail') import pprint pprint.pprint(got_md) - return 'fail' + pytest.fail() # Try opening the 4 subdatasets for i in range(2): gdal.ErrorReset() ds = gdal.Open(got_md['SUBDATASET_%d_NAME' % (i + 1)]) - if ds is None or gdal.GetLastErrorMsg() != '': - gdaltest.post_reason('fail') - print(got_md['SUBDATASET_%d_NAME' % (i + 1)]) - return 'fail' + assert ds is not None and gdal.GetLastErrorMsg() == '', \ + got_md['SUBDATASET_%d_NAME' % (i + 1)] # Try various invalid subdataset names for name in ['SENTINEL2_L2A:', @@ -1854,25 +1557,19 @@ def sentinel2_l2a_1(): 'SENTINEL2_L2A:%s:10m:EPSG_32633' % filename_xml]: with gdaltest.error_handler(): ds = gdal.Open(name) - if ds is not None: - gdaltest.post_reason('fail') - print(name) - return 'fail' - - return 'success' + assert ds is None, name + ############################################################################### # Test opening a L21 subdataset on the 60m bands -def sentinel2_l2a_2(): +def test_sentinel2_l2a_2(): filename_xml = 'data/fake_sentinel2_l2a/S2A_USER_PRD_MSIL2A.SAFE/S2A_USER_MTD_SAFL2A.xml' gdal.ErrorReset() ds = gdal.Open('SENTINEL2_L2A:%s:60m:EPSG_32632' % filename_xml) - if ds is None or gdal.GetLastErrorMsg() != '': - gdaltest.post_reason('fail') - return 'fail' + assert ds is not None and gdal.GetLastErrorMsg() == '' expected_md = {'AOT_RETRIEVAL_ACCURACY': '0', 'BARE_SOILS_PERCENTAGE': '0', @@ -1925,31 +1622,18 @@ def sentinel2_l2a_2(): 'WATER_VAPOUR_RETRIEVAL_ACCURACY': '0'} got_md = ds.GetMetadata() if got_md != expected_md: - gdaltest.post_reason('fail') import pprint pprint.pprint(got_md) - return 'fail' + pytest.fail() - if ds.RasterXSize != 1830 or ds.RasterYSize != 1830: - gdaltest.post_reason('fail') - print(ds.RasterXSize) - print(ds.RasterYSize) - return 'fail' + assert ds.RasterXSize == 1830 and ds.RasterYSize == 1830 - if ds.GetProjectionRef().find('32632') < 0: - gdaltest.post_reason('fail') - return 'fail' + assert ds.GetProjectionRef().find('32632') >= 0 got_gt = ds.GetGeoTransform() - if got_gt != (699960.0, 60.0, 0.0, 5100060.0, 0.0, -60.0): - gdaltest.post_reason('fail') - print(got_gt) - return 'fail' + assert got_gt == (699960.0, 60.0, 0.0, 5100060.0, 0.0, -60.0) - if ds.RasterCount != 17: - gdaltest.post_reason('fail') - print(ds.RasterCount) - return 'fail' + assert ds.RasterCount == 17 vrt = ds.GetMetadata('xml:VRT')[0] placement_vrt = """<SimpleSource> @@ -1959,14 +1643,9 @@ def sentinel2_l2a_2(): <SrcRect xOff="0" yOff="0" xSize="1830" ySize="1830" /> <DstRect xOff="0" yOff="0" xSize="1830" ySize="1830" /> </SimpleSource>""" - if vrt.find(placement_vrt) < 0: - gdaltest.post_reason('fail') - print(vrt) - return 'fail' + assert vrt.find(placement_vrt) >= 0 - if ds.GetMetadata('xml:SENTINEL2') is None: - gdaltest.post_reason('fail') - return 'fail' + assert ds.GetMetadata('xml:SENTINEL2') is not None band = ds.GetRasterBand(1) got_md = band.GetMetadata() @@ -1978,36 +1657,28 @@ def sentinel2_l2a_2(): 'WAVELENGTH': '443', 'WAVELENGTH_UNIT': 'nm'} if got_md != expected_md: - gdaltest.post_reason('fail') import pprint pprint.pprint(got_md) - return 'fail' + pytest.fail() - if band.DataType != gdal.GDT_UInt16: - gdaltest.post_reason('fail') - return 'fail' + assert band.DataType == gdal.GDT_UInt16 band = ds.GetRasterBand(13) - if band.GetColorInterpretation() != gdal.GCI_Undefined: - gdaltest.post_reason('fail') - return 'fail' + assert band.GetColorInterpretation() == gdal.GCI_Undefined got_md = band.GetMetadata() expected_md = {'BANDNAME': 'AOT'} if got_md != expected_md: - gdaltest.post_reason('fail') import pprint pprint.pprint(got_md) - return 'fail' + pytest.fail() scl_band = 0 for i in range(ds.RasterCount): if ds.GetRasterBand(i + 1).GetMetadataItem('BANDNAME') == 'SCL': scl_band = i + 1 - if scl_band == 0: - gdaltest.post_reason('fail') - return 'fail' + assert scl_band != 0 band = ds.GetRasterBand(scl_band) expected_categories = ['NODATA', 'SATURATED_DEFECTIVE', @@ -2023,18 +1694,16 @@ def sentinel2_l2a_2(): 'SNOW_ICE'] got_categories = band.GetCategoryNames() if got_categories != expected_categories: - gdaltest.post_reason('fail') import pprint pprint.pprint(got_categories) - return 'fail' - - return 'success' + pytest.fail() + ############################################################################### # Test opening invalid XML files -def sentinel2_l2a_3(): +def test_sentinel2_l2a_3(): # Invalid XML gdal.FileFromMemBuffer('/vsimem/test.xml', @@ -2043,15 +1712,11 @@ def sentinel2_l2a_3(): with gdaltest.error_handler(): ds = gdal.Open('/vsimem/test.xml') - if ds is not None: - gdaltest.post_reason('fail') - return 'fail' + assert ds is None with gdaltest.error_handler(): ds = gdal.Open('SENTINEL2_L2A:/vsimem/test.xml:10m:EPSG_32632') - if ds is not None: - gdaltest.post_reason('fail') - return 'fail' + assert ds is None # File is OK, but granule MTD are missing gdal.FileFromMemBuffer('/vsimem/test.xml', @@ -2095,33 +1760,25 @@ def sentinel2_l2a_3(): gdal.ErrorReset() with gdaltest.error_handler(): gdal.Open('/vsimem/test.xml') - if gdal.GetLastErrorMsg() == '': - gdaltest.post_reason('fail') - return 'fail' + assert gdal.GetLastErrorMsg() != '' gdal.ErrorReset() with gdaltest.error_handler(): ds = gdal.Open('SENTINEL2_L2A:/vsimem/test.xml:10m:EPSG_32632') - if ds is not None: - gdaltest.post_reason('fail') - return 'fail' + assert ds is None gdal.Unlink('/vsimem/test.xml') - return 'success' - ############################################################################### # Test opening a L2A MSIL2A product -def sentinel2_l2a_4(): +def test_sentinel2_l2a_4(): filename_xml = 'data/fake_sentinel2_l2a_MSIL2A/S2A_MSIL2A_20180818T094031_N0208_R036_T34VFJ_20180818T120345.SAFE/MTD_MSIL2A.xml' gdal.ErrorReset() ds = gdal.Open(filename_xml) - if ds is None or gdal.GetLastErrorMsg() != '': - gdaltest.post_reason('fail') - return 'fail' + assert ds is not None and gdal.GetLastErrorMsg() == '' expected_md = { 'AOT_QUANTIFICATION_VALUE': '1000.0', @@ -2174,10 +1831,9 @@ def sentinel2_l2a_4(): 'WVP_QUANTIFICATION_VALUE_UNIT': 'cm'} got_md = ds.GetMetadata() if got_md != expected_md: - gdaltest.post_reason('fail') import pprint pprint.pprint(got_md) - return 'fail' + pytest.fail() expected_md = { 'SUBDATASET_1_DESC': @@ -2198,19 +1854,16 @@ def sentinel2_l2a_4(): 'SENTINEL2_L2A:data/fake_sentinel2_l2a_MSIL2A/S2A_MSIL2A_20180818T094031_N0208_R036_T34VFJ_20180818T120345.SAFE/MTD_MSIL2A.xml:TCI:EPSG_32634'} got_md = ds.GetMetadata('SUBDATASETS') if got_md != expected_md: - gdaltest.post_reason('fail') import pprint pprint.pprint(got_md) - return 'fail' + pytest.fail() # Try opening the 4 subdatasets for i in range(2): gdal.ErrorReset() ds = gdal.Open(got_md['SUBDATASET_%d_NAME' % (i + 1)]) - if ds is None or gdal.GetLastErrorMsg() != '': - gdaltest.post_reason('fail') - print(got_md['SUBDATASET_%d_NAME' % (i + 1)]) - return 'fail' + assert ds is not None and gdal.GetLastErrorMsg() == '', \ + got_md['SUBDATASET_%d_NAME' % (i + 1)] # Try various invalid subdataset names for name in ['SENTINEL2_L2A:', @@ -2224,26 +1877,20 @@ def sentinel2_l2a_4(): 'SENTINEL2_L2A:%s:10m:EPSG_32633' % filename_xml]: with gdaltest.error_handler(): ds = gdal.Open(name) - if ds is not None: - gdaltest.post_reason('fail') - print(name) - return 'fail' - - return 'success' + assert ds is None, name + ############################################################################### # Test opening a L2A MSIL2A subdataset on the 60m bands -def sentinel2_l2a_5(): +def test_sentinel2_l2a_5(): filename_xml = 'data/fake_sentinel2_l2a_MSIL2A/S2A_MSIL2A_20180818T094031_N0208_R036_T34VFJ_20180818T120345.SAFE/MTD_MSIL2A.xml' gdal.ErrorReset() ds = gdal.Open('SENTINEL2_L2A:%s:60m:EPSG_32634' % filename_xml) - if ds is None or gdal.GetLastErrorMsg() != '': - gdaltest.post_reason('fail') - return 'fail' + assert ds is not None and gdal.GetLastErrorMsg() == '' expected_md = { 'AOT_QUANTIFICATION_VALUE': '1000.0', @@ -2295,31 +1942,18 @@ def sentinel2_l2a_5(): 'WVP_QUANTIFICATION_VALUE_UNIT': 'cm'} got_md = ds.GetMetadata() if got_md != expected_md: - gdaltest.post_reason('fail') import pprint pprint.pprint(got_md) - return 'fail' + pytest.fail() - if ds.RasterXSize != 1830 or ds.RasterYSize != 1830: - gdaltest.post_reason('fail') - print(ds.RasterXSize) - print(ds.RasterYSize) - return 'fail' + assert ds.RasterXSize == 1830 and ds.RasterYSize == 1830 - if ds.GetProjectionRef().find('32634') < 0: - gdaltest.post_reason('fail') - return 'fail' + assert ds.GetProjectionRef().find('32634') >= 0 got_gt = ds.GetGeoTransform() - if got_gt != (600000.0, 60.0, 0.0, 6400020.0, 0.0, -60.0): - gdaltest.post_reason('fail') - print(got_gt) - return 'fail' + assert got_gt == (600000.0, 60.0, 0.0, 6400020.0, 0.0, -60.0) - if ds.RasterCount != 2: - gdaltest.post_reason('fail') - print(ds.RasterCount) - return 'fail' + assert ds.RasterCount == 2 vrt = ds.GetMetadata('xml:VRT')[0] placement_vrt = """<SimpleSource> @@ -2329,14 +1963,9 @@ def sentinel2_l2a_5(): <SrcRect xOff="0" yOff="0" xSize="1830" ySize="1830" /> <DstRect xOff="0" yOff="0" xSize="1830" ySize="1830" /> </SimpleSource>""" - if vrt.find(placement_vrt) < 0: - gdaltest.post_reason('fail') - print(vrt) - return 'fail' + assert vrt.find(placement_vrt) >= 0 - if ds.GetMetadata('xml:SENTINEL2') is None: - gdaltest.post_reason('fail') - return 'fail' + assert ds.GetMetadata('xml:SENTINEL2') is not None band = ds.GetRasterBand(1) got_md = band.GetMetadata() @@ -2348,29 +1977,22 @@ def sentinel2_l2a_5(): 'WAVELENGTH': '443', 'WAVELENGTH_UNIT': 'nm'} if got_md != expected_md: - gdaltest.post_reason('fail') import pprint pprint.pprint(got_md) - return 'fail' + pytest.fail() - if band.DataType != gdal.GDT_UInt16: - gdaltest.post_reason('fail') - return 'fail' - - return 'success' + assert band.DataType == gdal.GDT_UInt16 ############################################################################### # Test opening a L2A MSIL2Ap product -def sentinel2_l2a_6(): +def test_sentinel2_l2a_6(): filename_xml = 'data/fake_sentinel2_l2a_MSIL2Ap/S2A_MSIL2A_20170823T094031_N0205_R036_T34VFJ_20170823T094252.SAFE/MTD_MSIL2A.xml' gdal.ErrorReset() ds = gdal.Open(filename_xml) - if ds is None or gdal.GetLastErrorMsg() != '': - gdaltest.post_reason('fail') - return 'fail' + assert ds is not None and gdal.GetLastErrorMsg() == '' expected_md = { 'AOT_RETRIEVAL_ACCURACY': '0.0', @@ -2428,10 +2050,9 @@ def sentinel2_l2a_6(): 'WATER_VAPOUR_RETRIEVAL_ACCURACY': '0.0'} got_md = ds.GetMetadata() if got_md != expected_md: - gdaltest.post_reason('fail') import pprint pprint.pprint(got_md) - return 'fail' + pytest.fail() expected_md = { 'SUBDATASET_1_DESC': @@ -2452,19 +2073,16 @@ def sentinel2_l2a_6(): 'SENTINEL2_L2A:data/fake_sentinel2_l2a_MSIL2Ap/S2A_MSIL2A_20170823T094031_N0205_R036_T34VFJ_20170823T094252.SAFE/MTD_MSIL2A.xml:TCI:EPSG_32634'} got_md = ds.GetMetadata('SUBDATASETS') if got_md != expected_md: - gdaltest.post_reason('fail') import pprint pprint.pprint(got_md) - return 'fail' + pytest.fail() # Try opening the 4 subdatasets for i in range(2): gdal.ErrorReset() ds = gdal.Open(got_md['SUBDATASET_%d_NAME' % (i + 1)]) - if ds is None or gdal.GetLastErrorMsg() != '': - gdaltest.post_reason('fail') - print(got_md['SUBDATASET_%d_NAME' % (i + 1)]) - return 'fail' + assert ds is not None and gdal.GetLastErrorMsg() == '', \ + got_md['SUBDATASET_%d_NAME' % (i + 1)] # Try various invalid subdataset names for name in ['SENTINEL2_L2A:', @@ -2478,26 +2096,20 @@ def sentinel2_l2a_6(): 'SENTINEL2_L2A:%s:10m:EPSG_32633' % filename_xml]: with gdaltest.error_handler(): ds = gdal.Open(name) - if ds is not None: - gdaltest.post_reason('fail') - print(name) - return 'fail' - - return 'success' + assert ds is None, name + ############################################################################### # Test opening a L2A MSIL2Ap subdataset on the 60m bands -def sentinel2_l2a_7(): +def test_sentinel2_l2a_7(): filename_xml = 'data/fake_sentinel2_l2a_MSIL2Ap/S2A_MSIL2A_20170823T094031_N0205_R036_T34VFJ_20170823T094252.SAFE/MTD_MSIL2A.xml' gdal.ErrorReset() ds = gdal.Open('SENTINEL2_L2A:%s:60m:EPSG_32634' % filename_xml) - if ds is None or gdal.GetLastErrorMsg() != '': - gdaltest.post_reason('fail') - return 'fail' + assert ds is not None and gdal.GetLastErrorMsg() == '' expected_md = { 'AOT_RETRIEVAL_ACCURACY': '0.0', @@ -2554,31 +2166,18 @@ def sentinel2_l2a_7(): 'WATER_VAPOUR_RETRIEVAL_ACCURACY': '0.0'} got_md = ds.GetMetadata() if got_md != expected_md: - gdaltest.post_reason('fail') import pprint pprint.pprint(got_md) - return 'fail' + pytest.fail() - if ds.RasterXSize != 1830 or ds.RasterYSize != 1830: - gdaltest.post_reason('fail') - print(ds.RasterXSize) - print(ds.RasterYSize) - return 'fail' + assert ds.RasterXSize == 1830 and ds.RasterYSize == 1830 - if ds.GetProjectionRef().find('32634') < 0: - gdaltest.post_reason('fail') - return 'fail' + assert ds.GetProjectionRef().find('32634') >= 0 got_gt = ds.GetGeoTransform() - if got_gt != (600000.0, 60.0, 0.0, 6400020.0, 0.0, -60.0): - gdaltest.post_reason('fail') - print(got_gt) - return 'fail' + assert got_gt == (600000.0, 60.0, 0.0, 6400020.0, 0.0, -60.0) - if ds.RasterCount != 2: - gdaltest.post_reason('fail') - print(ds.RasterCount) - return 'fail' + assert ds.RasterCount == 2 vrt = ds.GetMetadata('xml:VRT')[0] placement_vrt = """<SimpleSource> @@ -2588,14 +2187,9 @@ def sentinel2_l2a_7(): <SrcRect xOff="0" yOff="0" xSize="1830" ySize="1830" /> <DstRect xOff="0" yOff="0" xSize="1830" ySize="1830" /> </SimpleSource>""" - if vrt.find(placement_vrt) < 0: - gdaltest.post_reason('fail') - print(vrt) - return 'fail' + assert vrt.find(placement_vrt) >= 0 - if ds.GetMetadata('xml:SENTINEL2') is None: - gdaltest.post_reason('fail') - return 'fail' + assert ds.GetMetadata('xml:SENTINEL2') is not None band = ds.GetRasterBand(1) got_md = band.GetMetadata() @@ -2607,30 +2201,23 @@ def sentinel2_l2a_7(): 'WAVELENGTH': '443', 'WAVELENGTH_UNIT': 'nm'} if got_md != expected_md: - gdaltest.post_reason('fail') import pprint pprint.pprint(got_md) - return 'fail' + pytest.fail() - if band.DataType != gdal.GDT_UInt16: - gdaltest.post_reason('fail') - return 'fail' - - return 'success' + assert band.DataType == gdal.GDT_UInt16 ############################################################################### # Test opening a L1C Safe Compact product -def sentinel2_l1c_safe_compact_1(): +def test_sentinel2_l1c_safe_compact_1(): filename_xml = 'data/fake_sentinel2_l1c_safecompact/S2A_MSIL1C_test.SAFE/MTD_MSIL1C.xml' gdal.ErrorReset() ds = gdal.Open(filename_xml) - if ds is None or gdal.GetLastErrorMsg() != '': - gdaltest.post_reason('fail') - return 'fail' + assert ds is not None and gdal.GetLastErrorMsg() == '' expected_md = {'CLOUD_COVERAGE_ASSESSMENT': '0.0', 'DATATAKE_1_DATATAKE_SENSING_START': '2015-12-31T23:59:59.999Z', @@ -2662,10 +2249,9 @@ def sentinel2_l1c_safe_compact_1(): 'SPECIAL_VALUE_SATURATED': '0'} got_md = ds.GetMetadata() if got_md != expected_md: - gdaltest.post_reason('fail') import pprint pprint.pprint(got_md) - return 'fail' + pytest.fail() expected_md = {'SUBDATASET_1_DESC': 'Bands B2, B3, B4, B8 with 10m resolution, UTM 32N', 'SUBDATASET_1_NAME': 'SENTINEL2_L1C:data/fake_sentinel2_l1c_safecompact/S2A_MSIL1C_test.SAFE/MTD_MSIL1C.xml:10m:EPSG_32632', @@ -2677,19 +2263,16 @@ def sentinel2_l1c_safe_compact_1(): 'SUBDATASET_4_NAME': 'SENTINEL2_L1C:data/fake_sentinel2_l1c_safecompact/S2A_MSIL1C_test.SAFE/MTD_MSIL1C.xml:TCI:EPSG_32632'} got_md = ds.GetMetadata('SUBDATASETS') if got_md != expected_md: - gdaltest.post_reason('fail') import pprint pprint.pprint(got_md) - return 'fail' + pytest.fail() # Try opening the 4 subdatasets for i in range(4): gdal.ErrorReset() ds = gdal.Open(got_md['SUBDATASET_%d_NAME' % (i + 1)]) - if ds is None or gdal.GetLastErrorMsg() != '': - gdaltest.post_reason('fail') - print(got_md['SUBDATASET_%d_NAME' % (i + 1)]) - return 'fail' + assert ds is not None and gdal.GetLastErrorMsg() == '', \ + got_md['SUBDATASET_%d_NAME' % (i + 1)] # Try various invalid subdataset names for name in ['SENTINEL2_L1C:', @@ -2703,35 +2286,27 @@ def sentinel2_l1c_safe_compact_1(): 'SENTINEL2_L1C:%s:10m:EPSG_32633' % filename_xml]: with gdaltest.error_handler(): ds = gdal.Open(name) - if ds is not None: - gdaltest.post_reason('fail') - print(name) - return 'fail' + assert ds is None, name # Try opening a zip file as distributed from https://scihub.esa.int/ if not sys.platform.startswith('win'): os.system('sh -c "cd data/fake_sentinel2_l1c_safecompact && zip -r ../../tmp/S2A_MSIL1C_test.zip S2A_OPER_PRD_MSIL1C.SAFE >/dev/null" && cd ../..') if os.path.exists('tmp/S2A_MSIL1C_test.zip'): ds = gdal.Open('tmp/S2A_MSIL1C_test.zip') - if ds is None: - gdaltest.post_reason('fail') - return 'fail' + assert ds is not None os.unlink('tmp/S2A_MSIL1C_test.zip') - return 'success' - + ############################################################################### # Test opening a L1C Safe Compact subdataset on the 10m bands -def sentinel2_l1c_safe_compact_2(): +def test_sentinel2_l1c_safe_compact_2(): filename_xml = 'data/fake_sentinel2_l1c_safecompact/S2A_MSIL1C_test.SAFE/MTD_MSIL1C.xml' gdal.ErrorReset() ds = gdal.Open('SENTINEL2_L1C:%s:10m:EPSG_32632' % filename_xml) - if ds is None or gdal.GetLastErrorMsg() != '': - gdaltest.post_reason('fail') - return 'fail' + assert ds is not None and gdal.GetLastErrorMsg() == '' expected_md = {'CLOUD_COVERAGE_ASSESSMENT': '0.0', 'DATATAKE_1_DATATAKE_SENSING_START': '2015-12-31T23:59:59.999Z', @@ -2762,30 +2337,18 @@ def sentinel2_l1c_safe_compact_2(): 'SPECIAL_VALUE_SATURATED': '0'} got_md = ds.GetMetadata() if got_md != expected_md: - gdaltest.post_reason('fail') import pprint pprint.pprint(got_md) - return 'fail' + pytest.fail() - if ds.RasterXSize != 10980 or ds.RasterYSize != 10980: - gdaltest.post_reason('fail') - print(ds.RasterXSize) - print(ds.RasterYSize) - return 'fail' + assert ds.RasterXSize == 10980 and ds.RasterYSize == 10980 - if ds.GetProjectionRef().find('32632') < 0: - gdaltest.post_reason('fail') - return 'fail' + assert ds.GetProjectionRef().find('32632') >= 0 got_gt = ds.GetGeoTransform() - if got_gt != (699960.0, 10.0, 0.0, 5100060.0, 0.0, -10.0): - gdaltest.post_reason('fail') - print(got_gt) - return 'fail' + assert got_gt == (699960.0, 10.0, 0.0, 5100060.0, 0.0, -10.0) - if ds.RasterCount != 4: - gdaltest.post_reason('fail') - return 'fail' + assert ds.RasterCount == 4 vrt = ds.GetMetadata('xml:VRT')[0] placement_vrt = """<SimpleSource> @@ -2796,14 +2359,9 @@ def sentinel2_l1c_safe_compact_2(): <DstRect xOff="0" yOff="0" xSize="10980" ySize="10980" /> </SimpleSource> """ - if vrt.find(placement_vrt) < 0: - gdaltest.post_reason('fail') - print(vrt) - return 'fail' + assert vrt.find(placement_vrt) >= 0 - if ds.GetMetadata('xml:SENTINEL2') is None: - gdaltest.post_reason('fail') - return 'fail' + assert ds.GetMetadata('xml:SENTINEL2') is not None band = ds.GetRasterBand(1) got_md = band.GetMetadata() @@ -2815,28 +2373,19 @@ def sentinel2_l1c_safe_compact_2(): 'WAVELENGTH': '665', 'WAVELENGTH_UNIT': 'nm'} if got_md != expected_md: - gdaltest.post_reason('fail') import pprint pprint.pprint(got_md) - return 'fail' + pytest.fail() - if band.GetColorInterpretation() != gdal.GCI_RedBand: - gdaltest.post_reason('fail') - return 'fail' + assert band.GetColorInterpretation() == gdal.GCI_RedBand - if band.DataType != gdal.GDT_UInt16: - gdaltest.post_reason('fail') - return 'fail' + assert band.DataType == gdal.GDT_UInt16 - if band.GetMetadataItem('NBITS', 'IMAGE_STRUCTURE') != '12': - gdaltest.post_reason('fail') - return 'fail' + assert band.GetMetadataItem('NBITS', 'IMAGE_STRUCTURE') == '12' band = ds.GetRasterBand(4) - if band.GetColorInterpretation() != gdal.GCI_Undefined: - gdaltest.post_reason('fail') - return 'fail' + assert band.GetColorInterpretation() == gdal.GCI_Undefined got_md = band.GetMetadata() expected_md = {'BANDNAME': 'B8', @@ -2847,84 +2396,34 @@ def sentinel2_l1c_safe_compact_2(): 'WAVELENGTH': '842', 'WAVELENGTH_UNIT': 'nm'} if got_md != expected_md: - gdaltest.post_reason('fail') import pprint pprint.pprint(got_md) - return 'fail' - - return 'success' + pytest.fail() + ############################################################################### # Test opening a L1C subdataset on the TCI bands -def sentinel2_l1c_safe_compact_3(): +def test_sentinel2_l1c_safe_compact_3(): filename_xml = 'data/fake_sentinel2_l1c_safecompact/S2A_MSIL1C_test.SAFE/MTD_MSIL1C.xml' ds = gdal.OpenEx('SENTINEL2_L1C:%s:TCI:EPSG_32632' % filename_xml) - if ds is None: - gdaltest.post_reason('fail') - return 'fail' + assert ds is not None - if ds.RasterCount != 3: - gdaltest.post_reason('fail') - return 'fail' + assert ds.RasterCount == 3 fl = ds.GetFileList() # main XML + 1 granule XML + 1 jp2 if len(fl) != 1 + 1 + 1: - gdaltest.post_reason('fail') import pprint pprint.pprint(fl) - return 'fail' + pytest.fail() band = ds.GetRasterBand(1) - if band.GetColorInterpretation() != gdal.GCI_RedBand: - gdaltest.post_reason('fail') - return 'fail' - - if band.DataType != gdal.GDT_Byte: - gdaltest.post_reason('fail') - return 'fail' - - return 'success' - - -gdaltest_list = [ - sentinel2_l1c_1, - sentinel2_l1c_2, - sentinel2_l1c_3, - sentinel2_l1c_4, - sentinel2_l1c_5, - sentinel2_l1c_6, - sentinel2_l1c_7, - sentinel2_l1c_tile_1, - sentinel2_l1c_tile_2, - sentinel2_l1c_tile_3, - sentinel2_l1c_tile_4, - sentinel2_l1c_tile_5, - sentinel2_l1c_tile_6, - sentinel2_l1b_1, - sentinel2_l1b_2, - sentinel2_l1b_3, - sentinel2_l1b_4, - sentinel2_l1b_5, - sentinel2_l2a_1, - sentinel2_l2a_2, - sentinel2_l2a_3, - sentinel2_l2a_4, - sentinel2_l2a_5, - sentinel2_l2a_6, - sentinel2_l2a_7, - sentinel2_l1c_safe_compact_1, - sentinel2_l1c_safe_compact_2, - sentinel2_l1c_safe_compact_3 -] - -if __name__ == '__main__': - - gdaltest.setup_run('sentinel2') - - gdaltest.run_tests(gdaltest_list) - - sys.exit(gdaltest.summarize()) + assert band.GetColorInterpretation() == gdal.GCI_RedBand + + assert band.DataType == gdal.GDT_Byte + + + diff --git a/autotest/gdrivers/sgi.py b/autotest/gdrivers/sgi.py index 3871df5c6904..8a3496778b14 100755 --- a/autotest/gdrivers/sgi.py +++ b/autotest/gdrivers/sgi.py @@ -28,9 +28,7 @@ # DEALINGS IN THE SOFTWARE. ############################################################################### -import sys -sys.path.append('../pymod') import gdaltest @@ -38,7 +36,7 @@ # Read existing simple 1 band SGI file. -def sgi_1(): +def test_sgi_1(): tst = gdaltest.GDALTest('SGI', 'byte.sgi', 1, 4672) @@ -48,7 +46,7 @@ def sgi_1(): # Write Test grayscale -def sgi_2(): +def test_sgi_2(): tst = gdaltest.GDALTest('SGI', 'byte.tif', 1, 4672) @@ -58,24 +56,12 @@ def sgi_2(): # Write Test rgb -def sgi_3(): +def test_sgi_3(): tst = gdaltest.GDALTest('SGI', 'rgbsmall.tif', 2, 21053) return tst.testCreate() -gdaltest_list = [ - sgi_1, - sgi_2, - sgi_3, -] -if __name__ == '__main__': - - gdaltest.setup_run('SGI') - - gdaltest.run_tests(gdaltest_list) - - sys.exit(gdaltest.summarize()) diff --git a/autotest/gdrivers/sigdem.py b/autotest/gdrivers/sigdem.py index 1c695a2c000f..d636c9b21731 100755 --- a/autotest/gdrivers/sigdem.py +++ b/autotest/gdrivers/sigdem.py @@ -29,9 +29,7 @@ # DEALINGS IN THE SOFTWARE. ############################################################################### -import sys -sys.path.append('../pymod') import gdaltest @@ -39,7 +37,7 @@ # Create simple copy and check. -def sigdem_copy_check_prj(): +def test_sigdem_copy_check_prj(): tst = gdaltest.GDALTest('SIGDEM', 'byte.tif', 1, 4672) @@ -50,7 +48,7 @@ def sigdem_copy_check_prj(): ############################################################################### # Verify writing files with non-square pixels. -def sigdem_non_square(): +def test_sigdem_non_square(): tst = gdaltest.GDALTest('SIGDEM', 'nonsquare_nad27_utm11.vrt', 1, 12481) @@ -61,7 +59,7 @@ def sigdem_non_square(): ############################################################################### # Test creating an in memory copy. -def sigdem_in_memory(): +def test_sigdem_in_memory(): tst = gdaltest.GDALTest('SIGDEM', 'byte.tif', 1, 4672) @@ -71,16 +69,4 @@ def sigdem_in_memory(): ############################################################################### -gdaltest_list = [ - sigdem_copy_check_prj, - sigdem_non_square, - sigdem_in_memory -] -if __name__ == '__main__': - - gdaltest.setup_run('sigdem') - - gdaltest.run_tests(gdaltest_list) - - sys.exit(gdaltest.summarize()) diff --git a/autotest/gdrivers/snodas.py b/autotest/gdrivers/snodas.py index 58cb7ae41b43..7220259549ec 100755 --- a/autotest/gdrivers/snodas.py +++ b/autotest/gdrivers/snodas.py @@ -28,10 +28,8 @@ # DEALINGS IN THE SOFTWARE. ############################################################################### -import sys from osgeo import gdal -sys.path.append('../pymod') import gdaltest @@ -39,7 +37,7 @@ # Test a fake SNODAS dataset -def snodas_1(): +def test_snodas_1(): tst = gdaltest.GDALTest('SNODAS', 'fake_snodas.hdr', 1, 0) expected_gt = [-124.733749999995, 0.0083333333333330643, 0.0, 52.874583333331302, 0.0, -0.0083333333333330054] @@ -59,26 +57,11 @@ def snodas_1(): if ret == 'success': ds = gdal.Open('data/fake_snodas.hdr') ds.GetFileList() - if ds.GetRasterBand(1).GetNoDataValue() != -9999: - print(ds.GetRasterBand(1).GetNoDataValue()) - return 'fail' - if ds.GetRasterBand(1).GetMinimum() != 0: - print(ds.GetRasterBand(1).GetMinimum()) - return 'fail' - if ds.GetRasterBand(1).GetMaximum() != 429: - print(ds.GetRasterBand(1).GetMaximum()) - return 'fail' + assert ds.GetRasterBand(1).GetNoDataValue() == -9999 + assert ds.GetRasterBand(1).GetMinimum() == 0 + assert ds.GetRasterBand(1).GetMaximum() == 429 return ret -gdaltest_list = [ - snodas_1] -if __name__ == '__main__': - - gdaltest.setup_run('snodas') - - gdaltest.run_tests(gdaltest_list) - - sys.exit(gdaltest.summarize()) diff --git a/autotest/gdrivers/srp.py b/autotest/gdrivers/srp.py index 80c910fc5547..42fd5d497fea 100755 --- a/autotest/gdrivers/srp.py +++ b/autotest/gdrivers/srp.py @@ -30,11 +30,9 @@ ############################################################################### import os -import sys from osgeo import gdal from osgeo import osr -sys.path.append('../pymod') import gdaltest @@ -42,35 +40,23 @@ # Read USRP dataset with PCB=0 -def srp_1(filename='USRP_PCB0/FKUSRP01.IMG'): +def test_srp_1(filename='USRP_PCB0/FKUSRP01.IMG'): srs = osr.SpatialReference() srs.ImportFromEPSG(32600 + 17) tst = gdaltest.GDALTest('SRP', filename, 1, 24576) - ret = tst.testOpen(check_prj=srs.ExportToWkt(), check_gt=(500000.0, 5.0, 0.0, 5000000.0, 0.0, -5.0)) - if ret != 'success': - return ret + tst.testOpen(check_prj=srs.ExportToWkt(), check_gt=(500000.0, 5.0, 0.0, 5000000.0, 0.0, -5.0)) ds = gdal.Open('data/' + filename) - if ds.GetRasterBand(1).GetColorInterpretation() != gdal.GCI_PaletteIndex: - gdaltest.post_reason('fail') - return 'fail' + assert ds.GetRasterBand(1).GetColorInterpretation() == gdal.GCI_PaletteIndex ct = ds.GetRasterBand(1).GetColorTable() - if ct.GetCount() != 4: - gdaltest.post_reason('fail') - return 'fail' + assert ct.GetCount() == 4 - if ct.GetColorEntry(0) != (0, 0, 0, 255): - gdaltest.post_reason('fail') - print(ct.GetColorEntry(0)) - return 'fail' + assert ct.GetColorEntry(0) == (0, 0, 0, 255) - if ct.GetColorEntry(1) != (255, 0, 0, 255): - gdaltest.post_reason('fail') - print(ct.GetColorEntry(1)) - return 'fail' + assert ct.GetColorEntry(1) == (255, 0, 0, 255) expected_md = ['SRP_CLASSIFICATION=U', 'SRP_CREATIONDATE=20120505', @@ -84,32 +70,28 @@ def srp_1(filename='USRP_PCB0/FKUSRP01.IMG'): got_md = ds.GetMetadata() for md in expected_md: (key, value) = md.split('=') - if key not in got_md or got_md[key] != value: - gdaltest.post_reason('did not find %s' % md) - print(got_md) - return 'fail' - - return 'success' + assert key in got_md and got_md[key] == value, ('did not find %s' % md) + ############################################################################### # Read USRP dataset with PCB=4 -def srp_2(): - return srp_1('USRP_PCB4/FKUSRP01.IMG') +def test_srp_2(): + return test_srp_1('USRP_PCB4/FKUSRP01.IMG') ############################################################################### # Read USRP dataset with PCB=8 -def srp_3(): - return srp_1('USRP_PCB8/FKUSRP01.IMG') +def test_srp_3(): + return test_srp_1('USRP_PCB8/FKUSRP01.IMG') ############################################################################### # Read from TRANSH01.THF file. -def srp_4(): +def test_srp_4(): tst = gdaltest.GDALTest('SRP', 'USRP_PCB0/TRANSH01.THF', 1, 24576) ret = tst.testOpen() @@ -119,22 +101,16 @@ def srp_4(): # Read from TRANSH01.THF file (without "optimization" for single GEN in THF) -def srp_5(): +def test_srp_5(): gdal.SetConfigOption('SRP_SINGLE_GEN_IN_THF_AS_DATASET', 'FALSE') ds = gdal.Open('data/USRP_PCB0/TRANSH01.THF') gdal.SetConfigOption('SRP_SINGLE_GEN_IN_THF_AS_DATASET', None) subdatasets = ds.GetMetadata('SUBDATASETS') - if subdatasets['SUBDATASET_1_NAME'] != 'SRP:data/USRP_PCB0/FKUSRP01.GEN,data/USRP_PCB0/FKUSRP01.IMG' and \ - subdatasets['SUBDATASET_1_NAME'] != 'SRP:data/USRP_PCB0\\FKUSRP01.GEN,data/USRP_PCB0\\FKUSRP01.IMG': - gdaltest.post_reason('fail') - print(subdatasets) - return 'fail' - if subdatasets['SUBDATASET_1_DESC'] != 'SRP:data/USRP_PCB0/FKUSRP01.GEN,data/USRP_PCB0/FKUSRP01.IMG' and \ - subdatasets['SUBDATASET_1_DESC'] != 'SRP:data/USRP_PCB0\\FKUSRP01.GEN,data/USRP_PCB0\\FKUSRP01.IMG': - gdaltest.post_reason('fail') - print(subdatasets) - return 'fail' + assert (subdatasets['SUBDATASET_1_NAME'] == 'SRP:data/USRP_PCB0/FKUSRP01.GEN,data/USRP_PCB0/FKUSRP01.IMG' or \ + subdatasets['SUBDATASET_1_NAME'] == 'SRP:data/USRP_PCB0\\FKUSRP01.GEN,data/USRP_PCB0\\FKUSRP01.IMG') + assert (subdatasets['SUBDATASET_1_DESC'] == 'SRP:data/USRP_PCB0/FKUSRP01.GEN,data/USRP_PCB0/FKUSRP01.IMG' or \ + subdatasets['SUBDATASET_1_DESC'] == 'SRP:data/USRP_PCB0\\FKUSRP01.GEN,data/USRP_PCB0\\FKUSRP01.IMG') expected_md = ['SRP_CLASSIFICATION=U', 'SRP_CREATIONDATE=20120505', @@ -144,49 +120,25 @@ def srp_5(): got_md = ds.GetMetadata() for md in expected_md: (key, value) = md.split('=') - if key not in got_md or got_md[key] != value: - gdaltest.post_reason('did not find %s' % md) - print(got_md) - return 'fail' - - return 'success' + assert key in got_md and got_md[key] == value, ('did not find %s' % md) + ############################################################################### # Read with subdataset syntax -def srp_6(): +def test_srp_6(): tst = gdaltest.GDALTest('SRP', 'SRP:data/USRP_PCB4/FKUSRP01.GEN,data/USRP_PCB4/FKUSRP01.IMG', 1, 24576, filename_absolute=1) - return tst.testOpen() + tst.testOpen() ############################################################################### # Cleanup -def srp_cleanup(): +def test_srp_cleanup(): # FIXME ? os.unlink('data/USRP_PCB0/TRANSH01.THF.aux.xml') - return 'success' ############################################################################### - - -gdaltest_list = [ - srp_1, - srp_2, - srp_3, - srp_4, - srp_5, - srp_6, - srp_cleanup -] - -if __name__ == '__main__': - - gdaltest.setup_run('srp') - - gdaltest.run_tests(gdaltest_list) - - sys.exit(gdaltest.summarize()) diff --git a/autotest/gdrivers/srtmhgt.py b/autotest/gdrivers/srtmhgt.py index 0006f20b8a88..26ae584e08b9 100755 --- a/autotest/gdrivers/srtmhgt.py +++ b/autotest/gdrivers/srtmhgt.py @@ -30,18 +30,16 @@ ############################################################################### import os -import sys from osgeo import gdal -sys.path.append('../pymod') -import gdaltest +import pytest ############################################################################### # Test a SRTMHGT Level 1 (made from a DTED Level 0) -def srtmhgt_1(): +def test_srtmhgt_1(): ds = gdal.Open('data/n43.dt0') @@ -70,17 +68,13 @@ def srtmhgt_1(): band = dsDst.GetRasterBand(1) chksum = band.Checksum() - if chksum != 60918: - gdaltest.post_reason('Wrong checksum. Checksum found %d' % chksum) - return 'fail' - - return 'success' + assert chksum == 60918, ('Wrong checksum. Checksum found %d' % chksum) ############################################################################### # Test creating an in memory copy. -def srtmhgt_2(): +def test_srtmhgt_2(): ds = gdal.Open('tmp/n43w080.hgt') driver = gdal.GetDriverByName("SRTMHGT") @@ -89,9 +83,7 @@ def srtmhgt_2(): band = dsDst.GetRasterBand(1) chksum = band.Checksum() - if chksum != 60918: - gdaltest.post_reason('Wrong checksum. Checksum found %d' % chksum) - return 'fail' + assert chksum == 60918, ('Wrong checksum. Checksum found %d' % chksum) dsDst = None # Test update support @@ -100,18 +92,14 @@ def srtmhgt_2(): dsDst.ReadRaster()) dsDst.FlushCache() - if chksum != 60918: - gdaltest.post_reason('Wrong checksum. Checksum found %d' % chksum) - return 'fail' + assert chksum == 60918, ('Wrong checksum. Checksum found %d' % chksum) dsDst = None - return 'success' - ############################################################################### # Test reading from a .hgt.zip file -def srtmhgt_3(): +def test_srtmhgt_3(): ds = gdal.Open('tmp/n43w080.hgt') driver = gdal.GetDriverByName("SRTMHGT") @@ -122,43 +110,33 @@ def srtmhgt_3(): band = dsDst.GetRasterBand(1) chksum = band.Checksum() - if chksum != 60918: - gdaltest.post_reason('Wrong checksum. Checksum found %d' % chksum) - return 'fail' - - return 'success' + assert chksum == 60918, ('Wrong checksum. Checksum found %d' % chksum) ############################################################################### # Test reading from a .SRTMSWBD.raw.zip file (GRASS #3246) -def srtmhgt_4(): +def test_srtmhgt_4(): f = gdal.VSIFOpenL('/vsizip//vsimem/N43W080.SRTMSWBD.raw.zip/N43W080.raw', 'wb') if f is None: - return 'skip' + pytest.skip() gdal.VSIFWriteL(' ' * (3601 * 3601), 1, 3601 * 3601, f) gdal.VSIFCloseL(f) ds = gdal.Open('/vsimem/N43W080.SRTMSWBD.raw.zip') - if ds is None: - gdaltest.post_reason('fail') - return 'fail' + assert ds is not None cs = ds.GetRasterBand(1).Checksum() ds = None gdal.Unlink('/vsimem/N43W080.SRTMSWBD.raw.zip') - if cs != 3636: - gdaltest.post_reason('Wrong checksum. Checksum found %d' % cs) - return 'fail' - - return 'success' + assert cs == 3636, ('Wrong checksum. Checksum found %d' % cs) ############################################################################### # Cleanup. -def srtmhgt_cleanup(): +def test_srtmhgt_cleanup(): try: gdal.GetDriverByName("SRTMHGT").Delete('tmp/n43w080.hgt') gdal.GetDriverByName("SRTMHGT").Delete('/vsimem/n43w080.hgt') @@ -166,22 +144,7 @@ def srtmhgt_cleanup(): os.remove('tmp/n43.dt1.tif') except (RuntimeError, OSError): pass - return 'success' - - -gdaltest_list = [ - srtmhgt_1, - srtmhgt_2, - srtmhgt_3, - srtmhgt_4, - srtmhgt_cleanup -] - - -if __name__ == '__main__': + - gdaltest.setup_run('srtmhgt') - gdaltest.run_tests(gdaltest_list) - sys.exit(gdaltest.summarize()) diff --git a/autotest/gdrivers/terragen.py b/autotest/gdrivers/terragen.py index 90fdd74a72cb..d71699120007 100755 --- a/autotest/gdrivers/terragen.py +++ b/autotest/gdrivers/terragen.py @@ -27,9 +27,7 @@ # DEALINGS IN THE SOFTWARE. ############################################################################### -import sys -sys.path.append('../pymod') from osgeo import gdal import gdaltest @@ -37,7 +35,7 @@ ############################################################################### -def terragen_1(): +def test_terragen_1(): tst = gdaltest.GDALTest('terragen', 'float32.ter', 1, 1128) @@ -47,29 +45,16 @@ def terragen_1(): # Write -def terragen_2(): +def test_terragen_2(): gdal.Translate('/vsimem/out.ter', 'data/float32.tif', options='-of TERRAGEN -co MINUSERPIXELVALUE=74 -co MAXUSERPIXELVALUE=255') gdal.Translate('/vsimem/out.tif', '/vsimem/out.ter', options='-unscale') ds = gdal.Open('/vsimem/out.tif') - if ds.GetRasterBand(1).Checksum() != 4672: - return 'fail' + assert ds.GetRasterBand(1).Checksum() == 4672 ds = None gdal.GetDriverByName('TERRAGEN').Delete('/vsimem/out.ter') gdal.GetDriverByName('TERRAGEN').Delete('/vsimem/out.tif') - return 'success' -gdaltest_list = [ - terragen_1, - terragen_2 -] -if __name__ == '__main__': - - gdaltest.setup_run('TERRAGEN') - - gdaltest.run_tests(gdaltest_list) - - sys.exit(gdaltest.summarize()) diff --git a/autotest/gdrivers/test_validate_jp2.py b/autotest/gdrivers/test_validate_jp2.py index 94ce46b7de37..8a7db1c1b35b 100755 --- a/autotest/gdrivers/test_validate_jp2.py +++ b/autotest/gdrivers/test_validate_jp2.py @@ -32,8 +32,8 @@ import os import sys from osgeo import gdal +import pytest -sys.path.append('../pymod') sys.path.append('../../gdal/swig/python/samples') import gdaltest @@ -47,7 +47,7 @@ def test_validate_jp2_1(): gdaltest.has_validate_jp2_and_build_jp2 = False gdaltest.jp2openjpeg_drv = gdal.GetDriverByName('JP2OpenJPEG') if gdaltest.jp2openjpeg_drv is None: - return 'skip' + pytest.skip() try: import validate_jp2 @@ -55,13 +55,11 @@ def test_validate_jp2_1(): validate_jp2.validate build_jp2_from_xml.build_file except (ImportError, AttributeError): - return 'skip' + pytest.skip() gdaltest.has_validate_jp2_and_build_jp2 = True gdaltest.deregister_all_jpeg2000_drivers_but('JP2OpenJPEG') - return 'success' - ############################################################################### @@ -91,7 +89,7 @@ def validate(filename, inspire_tg=True, expected_gmljp2=True, oidoc=None): def test_validate_jp2_2(): if not gdaltest.has_validate_jp2_and_build_jp2: - return 'skip' + pytest.skip() import build_jp2_from_xml @@ -128,11 +126,10 @@ def test_validate_jp2_2(): 'ERROR[PROFILE_1, Conformance class A.8.14]: SPcod_xcb_minus_2 = 5, whereas max allowed for Profile 1 is 4'] if error_report.error_array != expected_errors: - gdaltest.post_reason('did not get expected errors') import pprint pp = pprint.PrettyPrinter() pp.pprint(error_report.error_array) - return 'fail' + pytest.fail('did not get expected errors') expected_warnings = [ 'WARNING[GENERAL]: Unknown value 1 for colr.PREC', @@ -144,14 +141,12 @@ def test_validate_jp2_2(): 'WARNING[INSPIRE_TG, Recommendation 39]: No user-defined precincts 0 defined' ] if error_report.warning_array != expected_warnings: - gdaltest.post_reason('did not get expected errors') import pprint pp = pprint.PrettyPrinter() pp.pprint(error_report.warning_array) - return 'fail' - - return 'success' + pytest.fail('did not get expected errors') + ############################################################################### # Another highly corrupted file @@ -159,7 +154,7 @@ def test_validate_jp2_2(): def test_validate_jp2_3(): if not gdaltest.has_validate_jp2_and_build_jp2: - return 'skip' + pytest.skip() import build_jp2_from_xml @@ -190,25 +185,22 @@ def test_validate_jp2_3(): 'ERROR[PROFILE_1, Conformance class A.8.14]: Not enough decomposition levels = 0 (max_dim=162, 128 * 2**SPcod_NumDecompositions=128)'] if error_report.error_array != expected_errors: - gdaltest.post_reason('did not get expected errors') import pprint pp = pprint.PrettyPrinter() pp.pprint(error_report.error_array) - return 'fail' + pytest.fail('did not get expected errors') expected_warnings = [ 'WARNING[INSPIRE_TG, Recommendation 38]: Bit depth of alpha channel should be 1 (BPCC 0), but its BPCC is 7', 'WARNING[INSPIRE_TG, Recommendation 38]: Bit depth of alpha channel should be 1 (BPCC 0), but its BPCC is 7' ] if error_report.warning_array != expected_warnings: - gdaltest.post_reason('did not get expected errors') import pprint pp = pprint.PrettyPrinter() pp.pprint(error_report.warning_array) - return 'fail' - - return 'success' + pytest.fail('did not get expected errors') + ############################################################################### # Another highly corrupted file @@ -216,7 +208,7 @@ def test_validate_jp2_3(): def test_validate_jp2_4(): if not gdaltest.has_validate_jp2_and_build_jp2: - return 'skip' + pytest.skip() import build_jp2_from_xml @@ -236,23 +228,20 @@ def test_validate_jp2_4(): 'ERROR[GENERAL]: No EOC marker found'] if error_report.error_array != expected_errors: - gdaltest.post_reason('did not get expected errors') import pprint pp = pprint.PrettyPrinter() pp.pprint(error_report.error_array) - return 'fail' + pytest.fail('did not get expected errors') expected_warnings = [ ] if error_report.warning_array != expected_warnings: - gdaltest.post_reason('did not get expected errors') import pprint pp = pprint.PrettyPrinter() pp.pprint(error_report.warning_array) - return 'fail' - - return 'success' + pytest.fail('did not get expected errors') + ############################################################################### # Slightly less corrupted file. Test mainly issues with JP2boxes and color table # Also a RGN marker @@ -261,7 +250,7 @@ def test_validate_jp2_4(): def test_validate_jp2_5(): if not gdaltest.has_validate_jp2_and_build_jp2: - return 'skip' + pytest.skip() import build_jp2_from_xml @@ -284,23 +273,20 @@ def test_validate_jp2_5(): 'ERROR[INSPIRE_TG, Requirement 26, Conformance class A.8.16]: RGN marker found, which is not allowed'] if error_report.error_array != expected_errors: - gdaltest.post_reason('did not get expected errors') import pprint pp = pprint.PrettyPrinter() pp.pprint(error_report.error_array) - return 'fail' + pytest.fail('did not get expected errors') expected_warnings = [ ] if error_report.warning_array != expected_warnings: - gdaltest.post_reason('did not get expected errors') import pprint pp = pprint.PrettyPrinter() pp.pprint(error_report.warning_array) - return 'fail' - - return 'success' + pytest.fail('did not get expected errors') + ############################################################################### # Nominal case with single band data @@ -308,29 +294,26 @@ def test_validate_jp2_5(): def test_validate_jp2_6(): if not gdaltest.has_validate_jp2_and_build_jp2: - return 'skip' + pytest.skip() error_report = validate('data/test_validate_jp2/byte.jp2', oidoc='data/test_validate_jp2/byte_oi.xml') gdal.Unlink('/vsimem/out.jp2') expected_errors = [] if error_report.error_array != expected_errors: - gdaltest.post_reason('did not get expected errors') import pprint pp = pprint.PrettyPrinter() pp.pprint(error_report.error_array) - return 'fail' + pytest.fail('did not get expected errors') expected_warnings = [] if error_report.warning_array != expected_warnings: - gdaltest.post_reason('did not get expected errors') import pprint pp = pprint.PrettyPrinter() pp.pprint(error_report.warning_array) - return 'fail' - - return 'success' + pytest.fail('did not get expected errors') + ############################################################################### # Nominal case with RGBA data @@ -338,29 +321,26 @@ def test_validate_jp2_6(): def test_validate_jp2_7(): if not gdaltest.has_validate_jp2_and_build_jp2: - return 'skip' + pytest.skip() error_report = validate('data/test_validate_jp2/stefan_full_rgba.jp2', oidoc='data/test_validate_jp2/stefan_full_rgba_oi.xml', expected_gmljp2=False) gdal.Unlink('/vsimem/out.jp2') expected_errors = [] if error_report.error_array != expected_errors: - gdaltest.post_reason('did not get expected errors') import pprint pp = pprint.PrettyPrinter() pp.pprint(error_report.error_array) - return 'fail' + pytest.fail('did not get expected errors') expected_warnings = [] if error_report.warning_array != expected_warnings: - gdaltest.post_reason('did not get expected errors') import pprint pp = pprint.PrettyPrinter() pp.pprint(error_report.warning_array) - return 'fail' - - return 'success' + pytest.fail('did not get expected errors') + ############################################################################### # Nominal case with color table data @@ -368,29 +348,26 @@ def test_validate_jp2_7(): def test_validate_jp2_8(): if not gdaltest.has_validate_jp2_and_build_jp2: - return 'skip' + pytest.skip() error_report = validate('data/test_validate_jp2/utmsmall_pct.jp2', oidoc='data/test_validate_jp2/utmsmall_pct_oi.xml') gdal.Unlink('/vsimem/out.jp2') expected_errors = [] if error_report.error_array != expected_errors: - gdaltest.post_reason('did not get expected errors') import pprint pp = pprint.PrettyPrinter() pp.pprint(error_report.error_array) - return 'fail' + pytest.fail('did not get expected errors') expected_warnings = [] if error_report.warning_array != expected_warnings: - gdaltest.post_reason('did not get expected errors') import pprint pp = pprint.PrettyPrinter() pp.pprint(error_report.warning_array) - return 'fail' - - return 'success' + pytest.fail('did not get expected errors') + ############################################################################### @@ -399,24 +376,6 @@ def test_validate_jp2_cleanup(): if gdaltest.has_validate_jp2_and_build_jp2: gdaltest.reregister_all_jpeg2000_drivers() - return 'success' - - -gdaltest_list = [ - test_validate_jp2_1, - test_validate_jp2_2, - test_validate_jp2_3, - test_validate_jp2_4, - test_validate_jp2_5, - test_validate_jp2_6, - test_validate_jp2_7, - test_validate_jp2_cleanup, -] - -if __name__ == '__main__': - - gdaltest.setup_run('test_validate_jp2') + - gdaltest.run_tests(gdaltest_list) - sys.exit(gdaltest.summarize()) diff --git a/autotest/gdrivers/tiff_profile.py b/autotest/gdrivers/tiff_profile.py index 9847f64daee4..aea4f4193305 100755 --- a/autotest/gdrivers/tiff_profile.py +++ b/autotest/gdrivers/tiff_profile.py @@ -34,21 +34,15 @@ import sys import base64 -sys.path.append('../pymod') -import gdaltest from osgeo import gdal - -############################################################################### -# When imported build a list of units based on the files available. - -gdaltest_list = [] +import pytest ############################################################################### # Test writing and reading of ICC profile in Create() options -def tiff_write_icc(): +def test_tiff_write_icc(): f = open('data/sRGB.icc', 'rb') data = f.read() @@ -65,58 +59,41 @@ def tiff_write_icc(): md = ds.GetMetadata("COLOR_PROFILE") ds = None - try: + with pytest.raises(OSError): os.stat('tmp/icc_test.tiff.aux.xml') - gdaltest.post_reason('fail') - return 'fail' - except OSError: - pass + - if md['SOURCE_ICC_PROFILE'] != icc: - gdaltest.post_reason('fail') - return 'fail' + assert md['SOURCE_ICC_PROFILE'] == icc # Check again with dataset from Open() ds = gdal.Open('tmp/icc_test.tiff') md = ds.GetMetadata("COLOR_PROFILE") ds = None - try: + with pytest.raises(OSError): os.stat('tmp/icc_test.tiff.aux.xml') - gdaltest.post_reason('fail') - return 'fail' - except OSError: - pass + - if md['SOURCE_ICC_PROFILE'] != icc: - gdaltest.post_reason('fail') - return 'fail' + assert md['SOURCE_ICC_PROFILE'] == icc # Check again with GetMetadataItem() ds = gdal.Open('tmp/icc_test.tiff') source_icc_profile = ds.GetMetadataItem("SOURCE_ICC_PROFILE", "COLOR_PROFILE") ds = None - try: + with pytest.raises(OSError): os.stat('tmp/icc_test.tiff.aux.xml') - gdaltest.post_reason('fail') - return 'fail' - except OSError: - pass + - if source_icc_profile != icc: - gdaltest.post_reason('fail') - return 'fail' + assert source_icc_profile == icc driver.Delete('tmp/icc_test.tiff') - return 'success' - ############################################################################### # Test writing and reading of ICC profile in CreateCopy() -def tiff_copy_icc(): +def test_tiff_copy_icc(): f = open('data/sRGB.icc', 'rb') data = f.read() @@ -135,9 +112,7 @@ def tiff_copy_icc(): ds = None ds2 = None - if md['SOURCE_ICC_PROFILE'] != icc: - gdaltest.post_reason('fail') - return 'fail' + assert md['SOURCE_ICC_PROFILE'] == icc # Check again with dataset from Open() ds2 = gdal.Open('tmp/icc_test2.tiff') @@ -145,20 +120,16 @@ def tiff_copy_icc(): ds = None ds2 = None - if md['SOURCE_ICC_PROFILE'] != icc: - gdaltest.post_reason('fail') - return 'fail' + assert md['SOURCE_ICC_PROFILE'] == icc driver.Delete('tmp/icc_test.tiff') driver.Delete('tmp/icc_test2.tiff') - return 'success' - ############################################################################### # Test writing and reading of ICC profile in CreateCopy() options -def tiff_copy_options_icc(): +def test_tiff_copy_options_icc(): f = open('data/sRGB.icc', 'rb') data = f.read() @@ -177,9 +148,7 @@ def tiff_copy_options_icc(): ds = None ds2 = None - if md['SOURCE_ICC_PROFILE'] != icc: - gdaltest.post_reason('fail') - return 'fail' + assert md['SOURCE_ICC_PROFILE'] == icc # Check again with dataset from Open() ds2 = gdal.Open('tmp/icc_test2.tiff') @@ -187,15 +156,11 @@ def tiff_copy_options_icc(): ds = None ds2 = None - if md['SOURCE_ICC_PROFILE'] != icc: - gdaltest.post_reason('fail') - return 'fail' + assert md['SOURCE_ICC_PROFILE'] == icc driver.Delete('tmp/icc_test.tiff') driver.Delete('tmp/icc_test2.tiff') - return 'success' - def cvtTuple2String(t): return str(t).lstrip('([').rstrip(')]') @@ -204,7 +169,7 @@ def cvtTuple2String(t): # Test writing and reading of ICC colorimetric data from options -def tiff_copy_options_colorimetric_data(): +def test_tiff_copy_options_colorimetric_data(): # sRGB values source_primaries = [(0.64, 0.33, 1.0), (0.3, 0.6, 1.0), (0.15, 0.06, 1.0)] source_whitepoint = (0.31271, 0.32902, 1.0) @@ -231,8 +196,7 @@ def tiff_copy_options_colorimetric_data(): source_whitepoint2 = eval('(' + md['SOURCE_WHITEPOINT'] + ')') for i in range(0, 3): - if abs(source_whitepoint2[i] - source_whitepoint[i]) > 0.0001: - return 'fail' + assert abs(source_whitepoint2[i] - source_whitepoint[i]) <= 0.0001 source_primaries2 = [ eval('(' + md['SOURCE_PRIMARIES_RED'] + ')'), @@ -241,18 +205,14 @@ def tiff_copy_options_colorimetric_data(): for j in range(0, 3): for i in range(0, 3): - if abs(source_primaries2[j][i] - source_primaries[j][i]) > 0.0001: - gdaltest.post_reason('fail') - return 'fail' + assert abs(source_primaries2[j][i] - source_primaries[j][i]) <= 0.0001 tifftag_transferfunction2 = ( eval('[' + md['TIFFTAG_TRANSFERFUNCTION_RED'] + ']'), eval('[' + md['TIFFTAG_TRANSFERFUNCTION_GREEN'] + ']'), eval('[' + md['TIFFTAG_TRANSFERFUNCTION_BLUE'] + ']')) - if tifftag_transferfunction2 != tifftag_transferfunction: - gdaltest.post_reason('fail') - return 'fail' + assert tifftag_transferfunction2 == tifftag_transferfunction # Check again with dataset from Open() ds2 = gdal.Open('tmp/icc_test2.tiff') @@ -263,9 +223,7 @@ def tiff_copy_options_colorimetric_data(): source_whitepoint2 = eval('(' + md['SOURCE_WHITEPOINT'] + ')') for i in range(0, 3): - if abs(source_whitepoint2[i] - source_whitepoint[i]) > 0.0001: - gdaltest.post_reason('fail') - return 'fail' + assert abs(source_whitepoint2[i] - source_whitepoint[i]) <= 0.0001 source_primaries2 = [ eval('(' + md['SOURCE_PRIMARIES_RED'] + ')'), @@ -274,29 +232,23 @@ def tiff_copy_options_colorimetric_data(): for j in range(0, 3): for i in range(0, 3): - if abs(source_primaries2[j][i] - source_primaries[j][i]) > 0.0001: - gdaltest.post_reason('fail') - return 'fail' + assert abs(source_primaries2[j][i] - source_primaries[j][i]) <= 0.0001 tifftag_transferfunction2 = ( eval('[' + md['TIFFTAG_TRANSFERFUNCTION_RED'] + ']'), eval('[' + md['TIFFTAG_TRANSFERFUNCTION_GREEN'] + ']'), eval('[' + md['TIFFTAG_TRANSFERFUNCTION_BLUE'] + ']')) - if tifftag_transferfunction2 != tifftag_transferfunction: - gdaltest.post_reason('fail') - return 'fail' + assert tifftag_transferfunction2 == tifftag_transferfunction driver.Delete('tmp/icc_test.tiff') driver.Delete('tmp/icc_test2.tiff') - return 'success' - ############################################################################### # Test writing and reading of ICC colorimetric data in the file -def tiff_copy_colorimetric_data(): +def test_tiff_copy_colorimetric_data(): # sRGB values source_primaries = [(0.64, 0.33, 1.0), (0.3, 0.6, 1.0), (0.15, 0.06, 1.0)] source_whitepoint = (0.31271, 0.32902, 1.0) @@ -325,9 +277,7 @@ def tiff_copy_colorimetric_data(): source_whitepoint2 = eval('(' + md['SOURCE_WHITEPOINT'] + ')') for i in range(0, 3): - if abs(source_whitepoint2[i] - source_whitepoint[i]) > 0.0001: - gdaltest.post_reason('fail') - return 'fail' + assert abs(source_whitepoint2[i] - source_whitepoint[i]) <= 0.0001 source_primaries2 = [ eval('(' + md['SOURCE_PRIMARIES_RED'] + ')'), @@ -336,18 +286,14 @@ def tiff_copy_colorimetric_data(): for j in range(0, 3): for i in range(0, 3): - if abs(source_primaries2[j][i] - source_primaries[j][i]) > 0.0001: - gdaltest.post_reason('fail') - return 'fail' + assert abs(source_primaries2[j][i] - source_primaries[j][i]) <= 0.0001 tifftag_transferfunction2 = ( eval('[' + md['TIFFTAG_TRANSFERFUNCTION_RED'] + ']'), eval('[' + md['TIFFTAG_TRANSFERFUNCTION_GREEN'] + ']'), eval('[' + md['TIFFTAG_TRANSFERFUNCTION_BLUE'] + ']')) - if tifftag_transferfunction2 != tifftag_transferfunction: - gdaltest.post_reason('fail') - return 'fail' + assert tifftag_transferfunction2 == tifftag_transferfunction # Check again with dataset from Open() ds2 = gdal.Open('tmp/icc_test2.tiff') @@ -358,9 +304,7 @@ def tiff_copy_colorimetric_data(): source_whitepoint2 = eval('(' + md['SOURCE_WHITEPOINT'] + ')') for i in range(0, 3): - if abs(source_whitepoint2[i] - source_whitepoint[i]) > 0.0001: - gdaltest.post_reason('fail') - return 'fail' + assert abs(source_whitepoint2[i] - source_whitepoint[i]) <= 0.0001 source_primaries2 = [ eval('(' + md['SOURCE_PRIMARIES_RED'] + ')'), @@ -369,29 +313,23 @@ def tiff_copy_colorimetric_data(): for j in range(0, 3): for i in range(0, 3): - if abs(source_primaries2[j][i] - source_primaries[j][i]) > 0.0001: - gdaltest.post_reason('fail') - return 'fail' + assert abs(source_primaries2[j][i] - source_primaries[j][i]) <= 0.0001 tifftag_transferfunction2 = ( eval('[' + md['TIFFTAG_TRANSFERFUNCTION_RED'] + ']'), eval('[' + md['TIFFTAG_TRANSFERFUNCTION_GREEN'] + ']'), eval('[' + md['TIFFTAG_TRANSFERFUNCTION_BLUE'] + ']')) - if tifftag_transferfunction2 != tifftag_transferfunction: - gdaltest.post_reason('fail') - return 'fail' + assert tifftag_transferfunction2 == tifftag_transferfunction driver.Delete('tmp/icc_test.tiff') driver.Delete('tmp/icc_test2.tiff') - return 'success' - ############################################################################### # Test updating ICC profile -def tiff_update_icc(): +def test_tiff_update_icc(): f = open('data/sRGB.icc', 'rb') data = f.read() @@ -411,28 +349,22 @@ def tiff_update_icc(): md = ds.GetMetadata("COLOR_PROFILE") ds = None - if md['SOURCE_ICC_PROFILE'] != icc: - gdaltest.post_reason('fail') - return 'fail' + assert md['SOURCE_ICC_PROFILE'] == icc # Reopen the file to verify it was written. ds = gdal.Open('tmp/icc_test.tiff') md = ds.GetMetadata("COLOR_PROFILE") ds = None - if md['SOURCE_ICC_PROFILE'] != icc: - gdaltest.post_reason('fail') - return 'fail' + assert md['SOURCE_ICC_PROFILE'] == icc driver.Delete('tmp/icc_test.tiff') - return 'success' - ############################################################################### # Test updating colorimetric options -def tiff_update_colorimetric(): +def test_tiff_update_colorimetric(): source_primaries = [(0.234, 0.555, 1.0), (0.2, 0, 1), (2, 3.5, 1)] source_whitepoint = (0.31271, 0.32902, 1.0) tifftag_transferfunction = (list(range(1, 256 * 4, 4)), list(range(2, 256 * 4 + 1, 4)), list(range(3, 256 * 4 + 2, 4))) @@ -457,9 +389,7 @@ def tiff_update_colorimetric(): source_whitepoint2 = eval('(' + md['SOURCE_WHITEPOINT'] + ')') for i in range(0, 3): - if abs(source_whitepoint2[i] - source_whitepoint[i]) > 0.0001: - gdaltest.post_reason('fail') - return 'fail' + assert abs(source_whitepoint2[i] - source_whitepoint[i]) <= 0.0001 source_primaries2 = [ eval('(' + md['SOURCE_PRIMARIES_RED'] + ')'), @@ -468,18 +398,14 @@ def tiff_update_colorimetric(): for j in range(0, 3): for i in range(0, 3): - if abs(source_primaries2[j][i] - source_primaries[j][i]) > 0.0001: - gdaltest.post_reason('fail') - return 'fail' + assert abs(source_primaries2[j][i] - source_primaries[j][i]) <= 0.0001 tifftag_transferfunction2 = ( eval('[' + md['TIFFTAG_TRANSFERFUNCTION_RED'] + ']'), eval('[' + md['TIFFTAG_TRANSFERFUNCTION_GREEN'] + ']'), eval('[' + md['TIFFTAG_TRANSFERFUNCTION_BLUE'] + ']')) - if tifftag_transferfunction2 != tifftag_transferfunction: - gdaltest.post_reason('fail') - return 'fail' + assert tifftag_transferfunction2 == tifftag_transferfunction # Reopen the file to verify it was written. ds = gdal.Open('tmp/icc_test.tiff') @@ -489,9 +415,7 @@ def tiff_update_colorimetric(): source_whitepoint2 = eval('(' + md['SOURCE_WHITEPOINT'] + ')') for i in range(0, 3): - if abs(source_whitepoint2[i] - source_whitepoint[i]) > 0.0001: - gdaltest.post_reason('fail') - return 'fail' + assert abs(source_whitepoint2[i] - source_whitepoint[i]) <= 0.0001 source_primaries2 = [ eval('(' + md['SOURCE_PRIMARIES_RED'] + ')'), @@ -500,38 +424,18 @@ def tiff_update_colorimetric(): for j in range(0, 3): for i in range(0, 3): - if abs(source_primaries2[j][i] - source_primaries[j][i]) > 0.0001: - gdaltest.post_reason('fail') - return 'fail' + assert abs(source_primaries2[j][i] - source_primaries[j][i]) <= 0.0001 tifftag_transferfunction2 = ( eval('[' + md['TIFFTAG_TRANSFERFUNCTION_RED'] + ']'), eval('[' + md['TIFFTAG_TRANSFERFUNCTION_GREEN'] + ']'), eval('[' + md['TIFFTAG_TRANSFERFUNCTION_BLUE'] + ']')) - if tifftag_transferfunction2 != tifftag_transferfunction: - gdaltest.post_reason('fail') - return 'fail' + assert tifftag_transferfunction2 == tifftag_transferfunction driver.Delete('tmp/icc_test.tiff') - return 'success' - ############################################################################ -gdaltest_list.append((tiff_write_icc)) -gdaltest_list.append((tiff_copy_icc)) -gdaltest_list.append((tiff_copy_options_icc)) -gdaltest_list.append((tiff_copy_options_colorimetric_data)) -gdaltest_list.append((tiff_copy_colorimetric_data)) -gdaltest_list.append((tiff_update_icc)) -gdaltest_list.append((tiff_update_colorimetric)) - -if __name__ == '__main__': - - gdaltest.setup_run('tiff_profile') - - gdaltest.run_tests(gdaltest_list) - sys.exit(gdaltest.summarize()) diff --git a/autotest/gdrivers/til.py b/autotest/gdrivers/til.py index 58f5fd0b70c1..807aec107dc3 100755 --- a/autotest/gdrivers/til.py +++ b/autotest/gdrivers/til.py @@ -29,18 +29,17 @@ ############################################################################### import os -import sys -sys.path.append('../pymod') import gdaltest from osgeo import gdal +import pytest ############################################################################### # Test a fake TIL dataset -def til_1(): +def test_til_1(): tst = gdaltest.GDALTest('TIL', 'testtil.til', 1, 4672) return tst.testOpen() @@ -49,7 +48,7 @@ def til_1(): # Check GetFileList() result (#4018) & IMD -def til_2(): +def test_til_2(): try: os.remove('data/testtil.til.aux.xml') @@ -59,37 +58,26 @@ def til_2(): ds = gdal.Open('data/testtil.til') 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.' 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' ds = None - try: + with pytest.raises(OSError, message='Expected not generation of data/testtil.til.aux.xml'): os.stat('data/testtil.til.aux.xml') - gdaltest.post_reason('Expected not generation of data/testtil.til.aux.xml') - return 'fail' - except OSError: - pass - - return 'success' + + ############################################################################### # Check GetFileList() & XML -def til_3(): +def test_til_3(): try: os.remove('data/testtil.til.aux.xml') @@ -99,42 +87,20 @@ def til_3(): ds = gdal.Open('data/testtil2.til') 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.' 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' ds = None - try: + with pytest.raises(OSError, message='Expected not generation of data/testtil.til.aux.xml'): os.stat('data/testtil.til.aux.xml') - gdaltest.post_reason('Expected not generation of data/testtil.til.aux.xml') - return 'fail' - except OSError: - pass - - return 'success' - - -gdaltest_list = [ - til_1, - til_2, - til_3] - -if __name__ == '__main__': + - gdaltest.setup_run('til') + - gdaltest.run_tests(gdaltest_list) - sys.exit(gdaltest.summarize()) diff --git a/autotest/gdrivers/usgsdem.py b/autotest/gdrivers/usgsdem.py index d0853c02e123..753767f6b03c 100755 --- a/autotest/gdrivers/usgsdem.py +++ b/autotest/gdrivers/usgsdem.py @@ -29,19 +29,18 @@ ############################################################################### import os -import sys from osgeo import gdal from osgeo import osr -sys.path.append('../pymod') import gdaltest +import pytest ############################################################################### # Test truncated version of http://download.osgeo.org/gdal/data/usgsdem/022gdeme -def usgsdem_1(): +def test_usgsdem_1(): tst = gdaltest.GDALTest('USGSDEM', '022gdeme_truncated', 1, 1583) srs = osr.SpatialReference() @@ -53,7 +52,7 @@ def usgsdem_1(): # Test truncated version of http://download.osgeo.org/gdal/data/usgsdem/114p01_0100_deme.dem -def usgsdem_2(): +def test_usgsdem_2(): tst = gdaltest.GDALTest('USGSDEM', '114p01_0100_deme_truncated.dem', 1, 53864) srs = osr.SpatialReference() @@ -65,7 +64,7 @@ def usgsdem_2(): # Test truncated version of file that triggered bug #2348 -def usgsdem_3(): +def test_usgsdem_3(): tst = gdaltest.GDALTest('USGSDEM', '39079G6_truncated.dem', 1, 61424) srs = osr.SpatialReference() @@ -78,7 +77,7 @@ def usgsdem_3(): # Test CreateCopy() -def usgsdem_4(): +def test_usgsdem_4(): tst = gdaltest.GDALTest('USGSDEM', '39079G6_truncated.dem', 1, 61424, options=['RESAMPLE=Nearest']) @@ -88,19 +87,18 @@ def usgsdem_4(): ############################################################################### # Test CreateCopy() without any creation options -def usgsdem_5(): +def test_usgsdem_5(): ds = gdal.Open('data/n43.dt0') ds2 = gdal.GetDriverByName('USGSDEM').CreateCopy('tmp/n43.dem', ds, options=['RESAMPLE=Nearest']) if ds.GetRasterBand(1).Checksum() != ds2.GetRasterBand(1).Checksum(): - gdaltest.post_reason('Bad checksum.') print(ds2.GetRasterBand(1).Checksum()) print(ds.GetRasterBand(1).Checksum()) ds2 = None print(open('tmp/n43.dem', 'rb').read()) - return 'fail' + pytest.fail('Bad checksum.') gt1 = ds.GetGeoTransform() gt2 = ds2.GetGeoTransform() @@ -109,25 +107,20 @@ def usgsdem_5(): print('') print('old = ', gt1) print('new = ', gt2) - gdaltest.post_reason('Geotransform differs.') - return 'fail' + pytest.fail('Geotransform differs.') srs = osr.SpatialReference() srs.SetWellKnownGeogCS('WGS84') - if ds2.GetProjectionRef() != srs.ExportToWkt(): - gdaltest.post_reason('Bad SRS.') - return 'fail' + assert ds2.GetProjectionRef() == srs.ExportToWkt(), 'Bad SRS.' ds2 = None - return 'success' - ############################################################################### # Test CreateCopy() without a few creation options. Then create a new copy with TEMPLATE # creation option and check that both files are binary identical. -def usgsdem_6(): +def test_usgsdem_6(): ds = gdal.Open('data/n43.dt0') ds2 = gdal.GetDriverByName('USGSDEM').CreateCopy('tmp/file_1.dem', ds, @@ -150,19 +143,16 @@ def usgsdem_6(): data1 = f1.read() data2 = f2.read() - if data1 != data2: - return 'fail' + assert data1 == data2 f1.close() f2.close() - return 'success' - ############################################################################### # Test CreateCopy() with CDED50K profile -def usgsdem_7(): +def test_usgsdem_7(): ds = gdal.Open('data/n43.dt0') @@ -172,11 +162,7 @@ def usgsdem_7(): options=['PRODUCT=CDED50K', 'TOPLEFT=80w,44n', 'RESAMPLE=Nearest', 'ZRESOLUTION=1.1', 'INTERNALNAME=GDAL']) gdal.PopErrorHandler() - if ds2.RasterXSize != 1201 or ds2.RasterYSize != 1201: - gdaltest.post_reason('Bad image dimensions.') - print(ds2.RasterXSize) - print(ds2.RasterYSize) - return 'fail' + assert ds2.RasterXSize == 1201 and ds2.RasterYSize == 1201, 'Bad image dimensions.' expected_gt = (-80.000104166666674, 0.000208333333333, 0, 44.000104166666667, 0, -0.000208333333333) got_gt = ds2.GetGeoTransform() @@ -185,25 +171,20 @@ def usgsdem_7(): print('') print('expected = ', expected_gt) print('got = ', got_gt) - gdaltest.post_reason('Geotransform differs.') - return 'fail' + pytest.fail('Geotransform differs.') srs = osr.SpatialReference() srs.SetWellKnownGeogCS('NAD83') - if ds2.GetProjectionRef() != srs.ExportToWkt(): - gdaltest.post_reason('Bad SRS.') - return 'fail' + assert ds2.GetProjectionRef() == srs.ExportToWkt(), 'Bad SRS.' ds2 = None - return 'success' - ############################################################################### # Test truncated version of http://download.osgeo.org/gdal/data/usgsdem/various.zip/39109h1.dem # Undocumented format -def usgsdem_8(): +def test_usgsdem_8(): tst = gdaltest.GDALTest('USGSDEM', '39109h1_truncated.dem', 1, 39443) srs = osr.SpatialReference() @@ -217,7 +198,7 @@ def usgsdem_8(): # Old format -def usgsdem_9(): +def test_usgsdem_9(): tst = gdaltest.GDALTest('USGSDEM', '4619old_truncated.dem', 1, 10659) srs = osr.SpatialReference() @@ -229,7 +210,7 @@ def usgsdem_9(): # https://github.com/OSGeo/gdal/issues/583 -def usgsdem_with_extra_values_at_end_of_profile(): +def test_usgsdem_with_extra_values_at_end_of_profile(): tst = gdaltest.GDALTest('USGSDEM', 'usgsdem_with_extra_values_at_end_of_profile.dem', 1, 56679) return tst.testOpen() @@ -238,7 +219,7 @@ def usgsdem_with_extra_values_at_end_of_profile(): # Like Novato.dem of https://trac.osgeo.org/gdal/ticket/4901 -def usgsdem_with_spaces_after_byte_864(): +def test_usgsdem_with_spaces_after_byte_864(): tst = gdaltest.GDALTest('USGSDEM', 'usgsdem_with_spaces_after_byte_864.dem', 1, 61078) return tst.testOpen() @@ -247,7 +228,7 @@ def usgsdem_with_spaces_after_byte_864(): # Cleanup -def usgsdem_cleanup(): +def test_usgsdem_cleanup(): try: os.remove('tmp/n43.dem') @@ -263,27 +244,6 @@ def usgsdem_cleanup(): except OSError: pass - return 'success' - - -gdaltest_list = [ - usgsdem_1, - usgsdem_2, - usgsdem_3, - usgsdem_4, - usgsdem_5, - usgsdem_6, - usgsdem_7, - usgsdem_8, - usgsdem_9, - usgsdem_with_extra_values_at_end_of_profile, - usgsdem_with_spaces_after_byte_864, - usgsdem_cleanup] - -if __name__ == '__main__': - - gdaltest.setup_run('usgsdem') + - gdaltest.run_tests(gdaltest_list) - sys.exit(gdaltest.summarize()) diff --git a/autotest/gdrivers/vicar.py b/autotest/gdrivers/vicar.py index 436e6af88a33..a505ae2a21a4 100755 --- a/autotest/gdrivers/vicar.py +++ b/autotest/gdrivers/vicar.py @@ -29,18 +29,17 @@ # DEALINGS IN THE SOFTWARE. ############################################################################### -import sys from osgeo import gdal -sys.path.append('../pymod') import gdaltest +import pytest ############################################################################### # Read truncated VICAR file -def vicar_1(): +def test_vicar_1(): tst = gdaltest.GDALTest('VICAR', 'test_vicar_truncated.bin', 1, 0) expected_prj = """PROJCS["SINUSOIDAL MARS", @@ -53,57 +52,26 @@ def vicar_1(): PARAMETER["longitude_of_center",137], PARAMETER["false_easting",0], PARAMETER["false_northing",0]]""" - if tst.testOpen(check_prj=expected_prj, skip_checksum=True) != 'success': - gdaltest.post_reason('fail') - return 'fail' + tst.testOpen(check_prj=expected_prj, skip_checksum=True) ds = gdal.Open('data/test_vicar_truncated.bin') expected_gt = (-53985.0, 25.0, 0.0, -200805.0, 0.0, -25.0) got_gt = ds.GetGeoTransform() for i in range(6): - if abs(got_gt[i] - expected_gt[i]) > 1e-8: - gdaltest.post_reason('failure') - print(got_gt) - print(expected_gt) - return 'fail' + assert abs(got_gt[i] - expected_gt[i]) <= 1e-8 - if ds.GetRasterBand(1).GetNoDataValue() != 0: - gdaltest.post_reason('fail') - return 'fail' - if abs(ds.GetRasterBand(1).GetScale() - 2.34) > 1e-5: - gdaltest.post_reason('fail') - print(ds.GetRasterBand(1).GetScale()) - return 'fail' - if abs(ds.GetRasterBand(1).GetOffset() - 4.56) > 1e-5: - gdaltest.post_reason('fail') - return 'fail' + assert ds.GetRasterBand(1).GetNoDataValue() == 0 + assert abs(ds.GetRasterBand(1).GetScale() - 2.34) <= 1e-5 + assert abs(ds.GetRasterBand(1).GetOffset() - 4.56) <= 1e-5 expected_md = {'DLRTO8.REFLECTANCE_OFFSET': '4.56', 'PRODUCT_TYPE': 'IMAGE', 'PIXEL-SHIFT-BUG': 'CORRECTED', 'M94_ORBIT.STOP_TIME': 'stop_time', 'FILE.EVENT_TYPE': 'EVENT_TYPE', 'M94_CAMERAS.MACROPIXEL_SIZE': '1', 'M94_INSTRUMENT.DETECTOR_ID': 'MEX_HRSC_NADIR', 'HRORTHO.SPICE_FILE_NAME': 'SPICE_FILE_NAME', 'DLRTO8.RADIANCE_SCALING_FACTOR': '1.23', 'CONVERSION_DETAILS': 'http://www.lpi.usra.edu/meetings/lpsc2014/pdf/1088.pdf', 'HRORTHO.GEOMETRIC_CALIB_FILE_NAME': 'calib_file_name', 'HRORTHO.EXTORI_FILE_NAME': "extori'_file_name", 'M94_INSTRUMENT.MISSION_PHASE_NAME': 'MISSION_PHASE_NAME', 'HRCONVER.MISSING_FRAMES': '0', 'DLRTO8.RADIANCE_OFFSET': '1.23', 'HRCONVER.OVERFLOW_FRAMES': '0', 'SPACECRAFT_NAME': 'MARS EXPRESS', 'HRFOOT.BEST_GROUND_SAMPLING_DISTANCE': '1.23', 'M94_ORBIT.START_TIME': 'start_time', 'HRORTHO.DTM_NAME': 'dtm_name', 'DLRTO8.REFLECTANCE_SCALING_FACTOR': '2.34', 'HRCONVER.ERROR_FRAMES': '1'} md = ds.GetMetadata() if len(md) != len(expected_md): - gdaltest.post_reason('fail') - print(md) - print(len(md)) - print(len(expected_md)) print(sorted(md.keys())) - print(sorted(expected_md.keys())) - return 'fail' + pytest.fail(sorted(expected_md.keys())) for key in expected_md: - if md[key] != expected_md[key]: - gdaltest.post_reason('fail') - print(md) - return 'fail' + assert md[key] == expected_md[key] - return 'success' + -gdaltest_list = [ - vicar_1] - -if __name__ == '__main__': - - gdaltest.setup_run('vicar') - - gdaltest.run_tests(gdaltest_list) - - sys.exit(gdaltest.summarize()) diff --git a/autotest/gdrivers/vrtderived.py b/autotest/gdrivers/vrtderived.py index d4c9d827be35..214fafc297d2 100755 --- a/autotest/gdrivers/vrtderived.py +++ b/autotest/gdrivers/vrtderived.py @@ -31,13 +31,12 @@ import os import shutil -import sys import threading from osgeo import gdal -sys.path.append('../pymod') import gdaltest +import pytest def _xmlsearch(root, nodetype, name): @@ -49,7 +48,7 @@ def _xmlsearch(root, nodetype, name): # Verify raster band subClass -def vrtderived_1(): +def test_vrtderived_1(): filename = 'tmp/derived.vrt' vrt_ds = gdal.GetDriverByName('VRT').Create(filename, 50, 50, 0) @@ -77,10 +76,7 @@ def vrtderived_1(): ' <SourceProperties RasterXSize="20" RasterYSize="20" DataType="Byte" ' 'BlockXSize="20" BlockYSize="20" />\n' '</SimpleSource>\n') - if md_read['source_0'] != expected_md_read: - gdaltest.post_reason('fail') - print(md_read['source_0']) - return 'fail' + assert md_read['source_0'] == expected_md_read xmlstring = open(filename).read() gdal.Unlink(filename) @@ -89,17 +85,13 @@ def vrtderived_1(): node = _xmlsearch(node, gdal.CXT_Element, 'VRTRasterBand') node = _xmlsearch(node, gdal.CXT_Attribute, 'subClass') node = _xmlsearch(node, gdal.CXT_Text, 'VRTDerivedRasterBand') - if node is None: - gdaltest.post_reason('invalid subclass') - return 'fail' - - return 'success' + assert node is not None, 'invalid subclass' ############################################################################### # Verify derived raster band pixel function type -def vrtderived_2(): +def test_vrtderived_2(): filename = 'tmp/derived.vrt' vrt_ds = gdal.GetDriverByName('VRT').Create(filename, 50, 50, 0) @@ -121,14 +113,10 @@ def vrtderived_2(): vrt_ds.GetRasterBand(1).SetMetadata(md, 'vrt_sources') with gdaltest.error_handler(): cs = vrt_ds.GetRasterBand(1).Checksum() - if cs != 0: - gdaltest.post_reason('fail') - return 'fail' + assert cs == 0 with gdaltest.error_handler(): ret = vrt_ds.GetRasterBand(1).WriteRaster(0, 0, 1, 1, ' ') - if ret == 0: - gdaltest.post_reason('fail') - return 'fail' + assert ret != 0 vrt_ds = None xmlstring = open(filename).read() @@ -138,22 +126,16 @@ def vrtderived_2(): node = _xmlsearch(node, gdal.CXT_Element, 'VRTRasterBand') pixelfunctiontype = _xmlsearch(node, gdal.CXT_Element, 'PixelFunctionType') pixelfunctiontype = _xmlsearch(pixelfunctiontype, gdal.CXT_Text, 'dummy') - if pixelfunctiontype is None: - gdaltest.post_reason('incorrect PixelFunctionType value') - return 'fail' + assert pixelfunctiontype is not None, 'incorrect PixelFunctionType value' pixelfunctionlanguage = _xmlsearch(node, gdal.CXT_Element, 'PixelFunctionLanguage') pixelfunctionlanguage = _xmlsearch(pixelfunctionlanguage, gdal.CXT_Text, 'Python') - if pixelfunctionlanguage is None: - gdaltest.post_reason('incorrect PixelFunctionLanguage value') - return 'fail' - - return 'success' + assert pixelfunctionlanguage is not None, 'incorrect PixelFunctionLanguage value' ############################################################################### # Verify derived raster band transfer type -def vrtderived_3(): +def test_vrtderived_3(): filename = 'tmp/derived.vrt' vrt_ds = gdal.GetDriverByName('VRT').Create(filename, 50, 50, 0) @@ -182,17 +164,13 @@ def vrtderived_3(): node = _xmlsearch(node, gdal.CXT_Element, 'VRTRasterBand') node = _xmlsearch(node, gdal.CXT_Element, 'SourceTransferType') node = _xmlsearch(node, gdal.CXT_Text, 'Byte') - if node is None: - gdaltest.post_reason('incorrect SourceTransferType value') - return 'fail' - - return 'success' + assert node is not None, 'incorrect SourceTransferType value' ############################################################################### # Check handling of invalid derived raster band transfer type -def vrtderived_4(): +def test_vrtderived_4(): filename = 'tmp/derived.vrt' vrt_ds = gdal.GetDriverByName('VRT').Create(filename, 50, 50, 0) @@ -204,67 +182,53 @@ def vrtderived_4(): gdal.PushErrorHandler('CPLQuietErrorHandler') ret = vrt_ds.AddBand(gdal.GDT_Byte, options) gdal.PopErrorHandler() - if ret == 0: - gdaltest.post_reason('invalid SourceTransferType value not detected') - return 'fail' - - return 'success' + assert ret != 0, 'invalid SourceTransferType value not detected' ############################################################################### # Check Python derived function with BufferRadius=1 -def vrtderived_5(): +def test_vrtderived_5(): try: import numpy numpy.ones except (ImportError, AttributeError): - return 'skip' + pytest.skip() gdal.SetConfigOption('GDAL_VRT_ENABLE_PYTHON', 'YES') ds = gdal.Open('data/n43_hillshade.vrt') cs = ds.GetRasterBand(1).Checksum() gdal.SetConfigOption('GDAL_VRT_ENABLE_PYTHON', None) - if cs != 50577: - gdaltest.post_reason('invalid checksum') - print(cs) - return 'fail' - - return 'success' + assert cs == 50577, 'invalid checksum' ############################################################################### # Check Python derived function with BufferRadius=0 and no source -def vrtderived_6(): +def test_vrtderived_6(): try: import numpy numpy.ones except (ImportError, AttributeError): - return 'skip' + pytest.skip() gdal.SetConfigOption('GDAL_VRT_ENABLE_PYTHON', 'YES') ds = gdal.Open('data/python_ones.vrt') cs = ds.GetRasterBand(1).Checksum() gdal.SetConfigOption('GDAL_VRT_ENABLE_PYTHON', None) - if cs != 10000: - gdaltest.post_reason('invalid checksum') - print(cs) - return 'fail' - - return 'success' + assert cs == 10000, 'invalid checksum' ############################################################################### # Check Python derived function with no started Python interpreter -def vrtderived_7(): +def test_vrtderived_7(): import test_cli_utilities if test_cli_utilities.get_gdalinfo_path() is None: - return 'skip' + pytest.skip() ret, err = gdaltest.runexternal_out_and_err(test_cli_utilities.get_gdalinfo_path() + ' -checksum data/n43_hillshade.vrt --config GDAL_VRT_ENABLE_PYTHON YES') if gdal.GetConfigOption('CPL_DEBUG') is not None: @@ -273,10 +237,8 @@ def vrtderived_7(): if ret.find('Checksum=0') >= 0: print('Did not manage to find a Python library') elif ret.find('Checksum=50577') < 0: - gdaltest.post_reason('fail') - print(ret) print(err) - return 'fail' + pytest.fail(ret) ret, err = gdaltest.runexternal_out_and_err(test_cli_utilities.get_gdalinfo_path() + ' -checksum data/n43_hillshade.vrt --config GDAL_VRT_ENABLE_PYTHON YES --config VRT_ENABLE_PYTHON_PATH NO') if gdal.GetConfigOption('CPL_DEBUG') is not None: @@ -285,10 +247,8 @@ def vrtderived_7(): if ret.find('Checksum=0') >= 0: print('Did not manage to find a Python library') elif ret.find('Checksum=50577') < 0: - gdaltest.post_reason('fail') - print(ret) print(err) - return 'fail' + pytest.fail(ret) ret, err = gdaltest.runexternal_out_and_err(test_cli_utilities.get_gdalinfo_path() + ' -checksum data/n43_hillshade.vrt --config GDAL_VRT_ENABLE_PYTHON YES --config VRT_ENABLE_PYTHON_SYMLINK NO') if gdal.GetConfigOption('CPL_DEBUG') is not None: @@ -297,20 +257,14 @@ def vrtderived_7(): if ret.find('Checksum=0') >= 0: print('Did not manage to find a Python library') elif ret.find('Checksum=50577') < 0: - gdaltest.post_reason('fail') - print(ret) print(err) - return 'fail' + pytest.fail(ret) # Invalid shared object name ret, err = gdaltest.runexternal_out_and_err(test_cli_utilities.get_gdalinfo_path() + ' -checksum data/n43_hillshade.vrt --config GDAL_VRT_ENABLE_PYTHON YES --config PYTHONSO foo') if gdal.GetConfigOption('CPL_DEBUG') is not None: print(err) - if ret.find('Checksum=0') < 0: - gdaltest.post_reason('fail') - print(ret) - print(err) - return 'fail' + assert ret.find('Checksum=0') >= 0, err # Valid shared object name, but without Python symbols libgdal_so = gdaltest.find_lib('gdal') @@ -318,57 +272,44 @@ def vrtderived_7(): ret, err = gdaltest.runexternal_out_and_err(test_cli_utilities.get_gdalinfo_path() + ' -checksum data/n43_hillshade.vrt --config GDAL_VRT_ENABLE_PYTHON YES --config PYTHONSO "%s"' % libgdal_so) if gdal.GetConfigOption('CPL_DEBUG') is not None: print(err) - if ret.find('Checksum=0') < 0: - gdaltest.post_reason('fail') - print(ret) - print(err) - return 'fail' - - return 'success' + assert ret.find('Checksum=0') >= 0, err + ############################################################################### # Check that GDAL_VRT_ENABLE_PYTHON=NO or undefined is honored -def vrtderived_8(): +def test_vrtderived_8(): try: import numpy numpy.ones except (ImportError, AttributeError): - return 'skip' + pytest.skip() gdal.SetConfigOption('GDAL_VRT_ENABLE_PYTHON', 'NO') ds = gdal.Open('data/n43_hillshade.vrt') with gdaltest.error_handler(): cs = ds.GetRasterBand(1).Checksum() gdal.SetConfigOption('GDAL_VRT_ENABLE_PYTHON', None) - if cs != 0: - gdaltest.post_reason('invalid checksum') - print(cs) - return 'fail' + assert cs == 0, 'invalid checksum' ds = gdal.Open('data/n43_hillshade.vrt') with gdaltest.error_handler(): cs = ds.GetRasterBand(1).Checksum() - if cs != 0: - gdaltest.post_reason('invalid checksum') - print(cs) - return 'fail' - - return 'success' + assert cs == 0, 'invalid checksum' ############################################################################### # Check various failure modes with Python functions -def vrtderived_9(): +def test_vrtderived_9(): try: import numpy numpy.ones except (ImportError, AttributeError): - return 'skip' + pytest.skip() # Missing PixelFunctionType with gdaltest.error_handler(): @@ -378,9 +319,7 @@ def vrtderived_9(): </VRTRasterBand> </VRTDataset> """) - if ds is not None: - gdaltest.post_reason('fail') - return 'fail' + assert ds is None # Unsupported PixelFunctionLanguage with gdaltest.error_handler(): @@ -391,9 +330,7 @@ def vrtderived_9(): </VRTRasterBand> </VRTDataset> """) - if ds is not None: - gdaltest.post_reason('fail') - return 'fail' + assert ds is None # PixelFunctionCode can only be used with Python with gdaltest.error_handler(): @@ -408,9 +345,7 @@ def identity(in_ar, out_ar, xoff, yoff, xsize, ysize, raster_xsize, raster_ysize </VRTRasterBand> </VRTDataset> """) - if ds is not None: - gdaltest.post_reason('fail') - return 'fail' + assert ds is None # PixelFunctionArguments can only be used with Python with gdaltest.error_handler(): @@ -421,9 +356,7 @@ def identity(in_ar, out_ar, xoff, yoff, xsize, ysize, raster_xsize, raster_ysize </VRTRasterBand> </VRTDataset> """) - if ds is not None: - gdaltest.post_reason('fail') - return 'fail' + assert ds is None # BufferRadius can only be used with Python with gdaltest.error_handler(): @@ -434,9 +367,7 @@ def identity(in_ar, out_ar, xoff, yoff, xsize, ysize, raster_xsize, raster_ysize </VRTRasterBand> </VRTDataset> """) - if ds is not None: - gdaltest.post_reason('fail') - return 'fail' + assert ds is None # Invalid BufferRadius with gdaltest.error_handler(): @@ -448,9 +379,7 @@ def identity(in_ar, out_ar, xoff, yoff, xsize, ysize, raster_xsize, raster_ysize </VRTRasterBand> </VRTDataset> """) - if ds is not None: - gdaltest.post_reason('fail') - return 'fail' + assert ds is None # Error at Python code compilation (indentation error) ds = gdal.Open("""<VRTDataset rasterXSize="10" rasterYSize="10"> @@ -470,10 +399,8 @@ def identity(in_ar, out_ar, xoff, yoff, xsize, ysize, raster_xsize, raster_ysize cs = ds.GetRasterBand(1).Checksum() gdal.SetConfigOption('GDAL_VRT_ENABLE_PYTHON', None) if cs != 0: - gdaltest.post_reason('invalid checksum') - print(cs) print(gdal.GetLastErrorMsg()) - return 'fail' + pytest.fail('invalid checksum') # Error at run time (in global code) ds = gdal.Open("""<VRTDataset rasterXSize="10" rasterYSize="10"> @@ -494,10 +421,8 @@ def identity(in_ar, out_ar, xoff, yoff, xsize, ysize, raster_xsize, raster_ysize cs = ds.GetRasterBand(1).Checksum() gdal.SetConfigOption('GDAL_VRT_ENABLE_PYTHON', None) if cs != 0: - gdaltest.post_reason('invalid checksum') - print(cs) print(gdal.GetLastErrorMsg()) - return 'fail' + pytest.fail('invalid checksum') # Error at run time (in pixel function) ds = gdal.Open("""<VRTDataset rasterXSize="10" rasterYSize="10"> @@ -517,10 +442,8 @@ def identity(in_ar, out_ar, xoff, yoff, xsize, ysize, raster_xsize, raster_ysize cs = ds.GetRasterBand(1).Checksum() gdal.SetConfigOption('GDAL_VRT_ENABLE_PYTHON', None) if cs != 0: - gdaltest.post_reason('invalid checksum') - print(cs) print(gdal.GetLastErrorMsg()) - return 'fail' + pytest.fail('invalid checksum') # User exception ds = gdal.Open("""<VRTDataset rasterXSize="10" rasterYSize="10"> @@ -540,10 +463,8 @@ def identity(in_ar, out_ar, xoff, yoff, xsize, ysize, raster_xsize, raster_ysize cs = ds.GetRasterBand(1).Checksum() gdal.SetConfigOption('GDAL_VRT_ENABLE_PYTHON', None) if cs != 0: - gdaltest.post_reason('invalid checksum') - print(cs) print(gdal.GetLastErrorMsg()) - return 'fail' + pytest.fail('invalid checksum') # unknown_function ds = gdal.Open("""<VRTDataset rasterXSize="10" rasterYSize="10"> @@ -563,10 +484,8 @@ def identity(in_ar, out_ar, xoff, yoff, xsize, ysize, raster_xsize, raster_ysize cs = ds.GetRasterBand(1).Checksum() gdal.SetConfigOption('GDAL_VRT_ENABLE_PYTHON', None) if cs != 0: - gdaltest.post_reason('invalid checksum') - print(cs) print(gdal.GetLastErrorMsg()) - return 'fail' + pytest.fail('invalid checksum') # uncallable object ds = gdal.Open("""<VRTDataset rasterXSize="10" rasterYSize="10"> @@ -585,10 +504,8 @@ def identity(in_ar, out_ar, xoff, yoff, xsize, ysize, raster_xsize, raster_ysize cs = ds.GetRasterBand(1).Checksum() gdal.SetConfigOption('GDAL_VRT_ENABLE_PYTHON', None) if cs != 0: - gdaltest.post_reason('invalid checksum') - print(cs) print(gdal.GetLastErrorMsg()) - return 'fail' + pytest.fail('invalid checksum') # unknown_module ds = gdal.Open("""<VRTDataset rasterXSize="10" rasterYSize="10"> @@ -603,13 +520,10 @@ def identity(in_ar, out_ar, xoff, yoff, xsize, ysize, raster_xsize, raster_ysize cs = ds.GetRasterBand(1).Checksum() gdal.SetConfigOption('GDAL_VRT_ENABLE_PYTHON', None) if cs != 0: - gdaltest.post_reason('invalid checksum') - print(cs) print(gdal.GetLastErrorMsg()) - return 'fail' - - return 'success' + pytest.fail('invalid checksum') + def vrtderived_code_that_only_makes_sense_with_GDAL_VRT_ENABLE_PYTHON_equal_IF_SAFE_but_that_is_now_disabled(): @@ -629,10 +543,8 @@ def my_func(in_ar, out_ar, xoff, yoff, xsize, ysize, raster_xsize, raster_ysize, with gdaltest.error_handler(): cs = ds.GetRasterBand(1).Checksum() if cs != 0: - gdaltest.post_reason('invalid checksum') - print(cs) print(gdal.GetLastErrorMsg()) - return 'fail' + pytest.fail('invalid checksum') # untrusted function ds = gdal.Open("""<VRTDataset rasterXSize="10" rasterYSize="10"> @@ -650,10 +562,8 @@ def my_func(in_ar, out_ar, xoff, yoff, xsize, ysize, raster_xsize, raster_ysize, with gdaltest.error_handler(): cs = ds.GetRasterBand(1).Checksum() if cs != 0: - gdaltest.post_reason('invalid checksum') - print(cs) print(gdal.GetLastErrorMsg()) - return 'fail' + pytest.fail('invalid checksum') # GDAL_VRT_ENABLE_PYTHON not set to YES ds = gdal.Open("""<VRTDataset rasterXSize="10" rasterYSize="10"> @@ -666,13 +576,10 @@ def my_func(in_ar, out_ar, xoff, yoff, xsize, ysize, raster_xsize, raster_ysize, with gdaltest.error_handler(): cs = ds.GetRasterBand(1).Checksum() if cs != 0: - gdaltest.post_reason('invalid checksum') - print(cs) print(gdal.GetLastErrorMsg()) - return 'fail' - - return 'success' + pytest.fail('invalid checksum') + ############################################################################### # Check Python function in another module @@ -682,13 +589,13 @@ def one_pix_func(in_ar, out_ar, xoff, yoff, xsize, ysize, raster_xsize, raster_y out_ar.fill(1) -def vrtderived_10(): +def test_vrtderived_10(): try: import numpy numpy.ones except (ImportError, AttributeError): - return 'skip' + pytest.skip() content = """<VRTDataset rasterXSize="10" rasterYSize="10"> <VRTRasterBand dataType="Byte" band="1" subClass="VRTDerivedRasterBand"> @@ -704,20 +611,16 @@ def vrtderived_10(): cs = ds.GetRasterBand(1).Checksum() gdal.SetConfigOption('GDAL_VRT_ENABLE_PYTHON', None) if cs != 100: - gdaltest.post_reason('invalid checksum') - print(cs) print(gdal.GetLastErrorMsg()) - return 'fail' + pytest.fail('invalid checksum') # GDAL_VRT_TRUSTED_MODULES not defined ds = gdal.Open(content) with gdaltest.error_handler(): cs = ds.GetRasterBand(1).Checksum() if cs != 0: - gdaltest.post_reason('invalid checksum') - print(cs) print(gdal.GetLastErrorMsg()) - return 'fail' + pytest.fail('invalid checksum') # GDAL_VRT_PYTHON_TRUSTED_MODULES *NOT* matching our module for val in ['vrtderive', @@ -731,10 +634,8 @@ def vrtderived_10(): cs = ds.GetRasterBand(1).Checksum() gdal.SetConfigOption('GDAL_VRT_PYTHON_TRUSTED_MODULES', None) if cs != 0: - gdaltest.post_reason('invalid checksum') - print(cs) print(gdal.GetLastErrorMsg()) - return 'fail' + pytest.fail('invalid checksum') # GDAL_VRT_PYTHON_TRUSTED_MODULES matching our module for val in ['foo,vrtderived,bar', @@ -747,24 +648,21 @@ def vrtderived_10(): cs = ds.GetRasterBand(1).Checksum() gdal.SetConfigOption('GDAL_VRT_PYTHON_TRUSTED_MODULES', None) if cs != 100: - gdaltest.post_reason('invalid checksum') - print(cs) print(gdal.GetLastErrorMsg()) - return 'fail' - - return 'success' + pytest.fail('invalid checksum') + ############################################################################### # Test serializing with python code -def vrtderived_11(): +def test_vrtderived_11(): try: import numpy numpy.ones except (ImportError, AttributeError): - return 'skip' + pytest.skip() shutil.copy('data/n43_hillshade.vrt', 'tmp/n43_hillshade.vrt') shutil.copy('data/n43.dt0', 'tmp/n43.dt0') @@ -780,24 +678,19 @@ def vrtderived_11(): os.unlink('tmp/n43_hillshade.vrt') os.unlink('tmp/n43.dt0') - if cs != 50577: - gdaltest.post_reason('invalid checksum') - print(cs) - return 'fail' - - return 'success' + assert cs == 50577, 'invalid checksum' ############################################################################### # Test all data types with python code -def vrtderived_12(): +def test_vrtderived_12(): try: import numpy numpy.ones except (ImportError, AttributeError): - return 'skip' + pytest.skip() for dt in ["Byte", "UInt16", "Int16", "UInt32", "Int32", "Float32", "Float64", @@ -820,11 +713,9 @@ def vrtderived_12(): else: expected_cs = 100 if cs != expected_cs: - gdaltest.post_reason('invalid checksum') print(dt) - print(cs) print(gdal.GetLastErrorMsg()) - return 'fail' + pytest.fail('invalid checksum') # Same for SourceTransferType for dt in ["CInt16", "CInt32"]: @@ -842,25 +733,22 @@ def vrtderived_12(): cs = ds.GetRasterBand(1).Checksum() gdal.SetConfigOption('GDAL_VRT_ENABLE_PYTHON', None) if cs != 0: - gdaltest.post_reason('invalid checksum') print(dt) - print(cs) print(gdal.GetLastErrorMsg()) - return 'fail' - - return 'success' + pytest.fail('invalid checksum') + ############################################################################### # Test translating a Python derived VRT -def vrtderived_13(): +def test_vrtderived_13(): try: import numpy numpy.ones except (ImportError, AttributeError): - return 'skip' + pytest.skip() gdal.SetConfigOption('GDAL_VRT_ENABLE_PYTHON', "YES") # Will test the VRTDerivedRasterBand::IGetDataCoverageStatus() interface @@ -870,24 +758,19 @@ def vrtderived_13(): ds = None gdal.Unlink('/vsimem/vrtderived_13.tif') - if cs != 10000: - gdaltest.post_reason('invalid checksum') - print(cs) - return 'fail' - - return 'success' + assert cs == 10000, 'invalid checksum' ############################################################################### # Test statistics functions -def vrtderived_14(): +def test_vrtderived_14(): try: import numpy numpy.ones except (ImportError, AttributeError): - return 'skip' + pytest.skip() gdal.SetConfigOption('GDAL_VRT_ENABLE_PYTHON', "YES") ds = gdal.GetDriverByName('VRT').CreateCopy('/vsimem/vrtderived_14.vrt', gdal.Open('data/python_ones.vrt')) @@ -896,26 +779,16 @@ def vrtderived_14(): hist = ds.GetRasterBand(1).GetHistogram() gdal.SetConfigOption('GDAL_VRT_ENABLE_PYTHON', None) - if (my_min, my_max) != (1.0, 1.0): - gdaltest.post_reason('invalid ComputeRasterMinMax') - print(my_min, my_max) - return 'fail' + assert (my_min, my_max) == (1.0, 1.0), 'invalid ComputeRasterMinMax' - if (my_min2, my_max2, mean, stddev) != (1.0, 1.0, 1.0, 0.0): - gdaltest.post_reason('invalid ComputeStatistics') - print(my_min2, my_max2, mean, stddev) - return 'fail' + assert (my_min2, my_max2, mean, stddev) == (1.0, 1.0, 1.0, 0.0), \ + 'invalid ComputeStatistics' - if hist[1] != 10000: - gdaltest.post_reason('invalid GetHistogram') - print(hist) - return 'fail' + assert hist[1] == 10000, 'invalid GetHistogram' ds = None gdal.GetDriverByName('VRT').Delete('/vsimem/vrtderived_14.vrt') - return 'success' - ############################################################################### # Test threading @@ -939,13 +812,13 @@ def vrtderived_15_worker(args_dict): ds.FlushCache() -def vrtderived_15(): +def test_vrtderived_15(): try: import numpy numpy.ones except (ImportError, AttributeError): - return 'skip' + pytest.skip() gdal.SetConfigOption('GDAL_VRT_ENABLE_PYTHON', "YES") @@ -972,37 +845,11 @@ def vrtderived_15(): ############################################################################### # Cleanup. -def vrtderived_cleanup(): +def test_vrtderived_cleanup(): try: os.remove('tmp/derived.vrt') except OSError: pass - return 'success' - - -gdaltest_list = [ - vrtderived_1, - vrtderived_2, - vrtderived_3, - vrtderived_4, - vrtderived_5, - vrtderived_6, - vrtderived_7, - vrtderived_8, - vrtderived_9, - vrtderived_10, - vrtderived_11, - vrtderived_12, - vrtderived_13, - vrtderived_14, - vrtderived_15, - vrtderived_cleanup, -] - -if __name__ == '__main__': - - gdaltest.setup_run('vrtderived') - - gdaltest.run_tests(gdaltest_list) - - sys.exit(gdaltest.summarize()) + + + diff --git a/autotest/gdrivers/vrtfilt.py b/autotest/gdrivers/vrtfilt.py index 1e17d5de7f0a..10acaaf180db 100755 --- a/autotest/gdrivers/vrtfilt.py +++ b/autotest/gdrivers/vrtfilt.py @@ -29,18 +29,17 @@ # DEALINGS IN THE SOFTWARE. ############################################################################### -import sys from osgeo import gdal -sys.path.append('../pymod') import gdaltest +import pytest ############################################################################### # Verify simple 3x3 averaging filter. -def vrtfilt_1(): +def test_vrtfilt_1(): tst = gdaltest.GDALTest('VRT', 'avfilt.vrt', 1, 21890) return tst.testOpen() @@ -49,7 +48,7 @@ def vrtfilt_1(): # Verify simple 3x3 averaging filter (normalized) on a dataset with nodata -def vrtfilt_2(): +def test_vrtfilt_2(): ds = gdal.Open('data/test_vrt_filter_nodata.tif') checksum = ds.GetRasterBand(1).Checksum() @@ -65,7 +64,7 @@ def vrtfilt_2(): # Same result expected as for vrtfilt_1 -def vrtfilt_3(): +def test_vrtfilt_3(): ds = gdal.OpenShared('data/rgbsmall.tif') vrt_ds = gdal.GetDriverByName('VRT').CreateCopy('', ds) @@ -85,19 +84,16 @@ def vrtfilt_3(): try: vrt_ds.GetRasterBand(1).SetMetadataItem except: - return 'skip' + pytest.skip() vrt_ds.GetRasterBand(1).SetMetadataItem('source_0', filterSourceXML, 'vrt_sources') - if vrt_ds.GetRasterBand(1).Checksum() != 21890: - return 'fail' - - return 'success' + assert vrt_ds.GetRasterBand(1).Checksum() == 21890 ############################################################################### # Variant for SetMetadataItem('source_0', xml, 'vrt_sources') -def vrtfilt_4(): +def test_vrtfilt_4(): vrt_ds = gdal.GetDriverByName('VRT').Create('', 50, 50, 1) @@ -115,19 +111,16 @@ def vrtfilt_4(): try: vrt_ds.GetRasterBand(1).SetMetadataItem except: - return 'skip' + pytest.skip() vrt_ds.GetRasterBand(1).SetMetadataItem('source_0', filterSourceXML, 'new_vrt_sources') - if vrt_ds.GetRasterBand(1).Checksum() != 21890: - return 'fail' - - return 'success' + assert vrt_ds.GetRasterBand(1).Checksum() == 21890 ############################################################################### # Variant for SetMetadata(md, 'vrt_sources') -def vrtfilt_5(): +def test_vrtfilt_5(): vrt_ds = gdal.GetDriverByName('VRT').Create('', 50, 50, 1) @@ -146,16 +139,13 @@ def vrtfilt_5(): md['source_0'] = filterSourceXML vrt_ds.GetRasterBand(1).SetMetadata(md, 'vrt_sources') - if vrt_ds.GetRasterBand(1).Checksum() != 21890: - return 'fail' - - return 'success' + assert vrt_ds.GetRasterBand(1).Checksum() == 21890 ############################################################################### # Verify separable Gaussian blur filter. -def vrtfilt_6(): +def test_vrtfilt_6(): tst = gdaltest.GDALTest('VRT', 'avfilt_1d.vrt', 1, 22377) return tst.testOpen() @@ -164,23 +154,7 @@ def vrtfilt_6(): # Cleanup. -def vrtfilt_cleanup(): - return 'success' - - -gdaltest_list = [ - vrtfilt_1, - vrtfilt_2, - vrtfilt_3, - vrtfilt_4, - vrtfilt_5, - vrtfilt_6, - vrtfilt_cleanup] - -if __name__ == '__main__': - - gdaltest.setup_run('vrtfilt') +def test_vrtfilt_cleanup(): + pass - gdaltest.run_tests(gdaltest_list) - sys.exit(gdaltest.summarize()) diff --git a/autotest/gdrivers/vrtlut.py b/autotest/gdrivers/vrtlut.py index 81d6e7681f0d..3bbe8f21eeb9 100755 --- a/autotest/gdrivers/vrtlut.py +++ b/autotest/gdrivers/vrtlut.py @@ -28,9 +28,7 @@ # DEALINGS IN THE SOFTWARE. ############################################################################### -import sys -sys.path.append('../pymod') import gdaltest @@ -38,7 +36,7 @@ # Simple test -def vrtlut_1(): +def test_vrtlut_1(): tst = gdaltest.GDALTest('VRT', 'byte_lut.vrt', 1, 4655) return tst.testOpen() @@ -47,18 +45,7 @@ def vrtlut_1(): ############################################################################### # Cleanup. -def vrtlut_cleanup(): - return 'success' +def test_vrtlut_cleanup(): + pass -gdaltest_list = [ - vrtlut_1, - vrtlut_cleanup] - -if __name__ == '__main__': - - gdaltest.setup_run('vrtlut') - - gdaltest.run_tests(gdaltest_list) - - sys.exit(gdaltest.summarize()) diff --git a/autotest/gdrivers/vrtmask.py b/autotest/gdrivers/vrtmask.py index 8c7c771ab208..06afc9ceb35e 100755 --- a/autotest/gdrivers/vrtmask.py +++ b/autotest/gdrivers/vrtmask.py @@ -30,18 +30,17 @@ ############################################################################### import os -import sys from osgeo import gdal -sys.path.append('../pymod') import gdaltest +import pytest ############################################################################### # Test with a global dataset mask band -def vrtmask_1(): +def test_vrtmask_1(): vrt_string = """<VRTDataset rasterXSize="20" rasterYSize="20"> <VRTRasterBand dataType="Byte" band="1"> @@ -68,26 +67,19 @@ def vrtmask_1(): </VRTDataset>""" ds = gdal.Open(vrt_string) - 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' cs = ds.GetRasterBand(1).GetMaskBand().Checksum() - if cs != 4672: - gdaltest.post_reason('did not get expected mask band checksum') - print(cs) - return 'fail' + assert cs == 4672, 'did not get expected mask band checksum' ds = None - return 'success' - ############################################################################### # Test with a per band mask band -def vrtmask_2(): +def test_vrtmask_2(): vrt_string = """<VRTDataset rasterXSize="20" rasterYSize="20"> <VRTRasterBand dataType="Byte" band="1"> @@ -114,31 +106,23 @@ def vrtmask_2(): </VRTDataset>""" ds = gdal.Open(vrt_string) - if ds.GetRasterBand(1).GetMaskFlags() != 0: - gdaltest.post_reason('did not get expected mask flags') - print(ds.GetRasterBand(1).GetMaskFlags()) - return 'fail' + assert ds.GetRasterBand(1).GetMaskFlags() == 0, 'did not get expected mask flags' cs = ds.GetRasterBand(1).GetMaskBand().Checksum() - if cs != 4873: - gdaltest.post_reason('did not get expected mask band checksum') - print(cs) - return 'fail' + assert cs == 4873, 'did not get expected mask band checksum' ds = None - return 'success' - ############################################################################### # Translate a RGB dataset with a mask into a VRT -def vrtmask_3(): +def test_vrtmask_3(): gtiff_drv = gdal.GetDriverByName('GTiff') md = gtiff_drv.GetMetadata() if md['DMD_CREATIONOPTIONLIST'].find('JPEG') == -1: - return 'skip' + pytest.skip() src_ds = gdal.Open('../gcore/data/ycbcr_with_mask.tif') ds = gdal.GetDriverByName('VRT').CreateCopy('tmp/vrtmask_3.vrt', src_ds) @@ -156,27 +140,21 @@ def vrtmask_3(): os.remove('tmp/vrtmask_3.vrt') - if msk_cs != expected_msk_cs: - gdaltest.post_reason('did not get expected mask band checksum') - print(msk_cs) - print(expected_msk_cs) - return 'fail' - - return 'success' + assert msk_cs == expected_msk_cs, 'did not get expected mask band checksum' ############################################################################### # Same with gdalbuildvrt -def vrtmask_4(): +def test_vrtmask_4(): import test_cli_utilities if test_cli_utilities.get_gdalbuildvrt_path() is None: - return 'skip' + pytest.skip() gtiff_drv = gdal.GetDriverByName('GTiff') md = gtiff_drv.GetMetadata() if md['DMD_CREATIONOPTIONLIST'].find('JPEG') == -1: - return 'skip' + pytest.skip() gdaltest.runexternal(test_cli_utilities.get_gdalbuildvrt_path() + ' tmp/vrtmask_4.vrt ../gcore/data/ycbcr_with_mask.tif') @@ -190,24 +168,18 @@ def vrtmask_4(): os.remove('tmp/vrtmask_4.vrt') - if msk_cs != expected_msk_cs: - gdaltest.post_reason('did not get expected mask band checksum') - print(msk_cs) - print(expected_msk_cs) - return 'fail' - - return 'success' + assert msk_cs == expected_msk_cs, 'did not get expected mask band checksum' ############################################################################### # Same with gdal_translate -def vrtmask_5(): +def test_vrtmask_5(): gtiff_drv = gdal.GetDriverByName('GTiff') md = gtiff_drv.GetMetadata() if md['DMD_CREATIONOPTIONLIST'].find('JPEG') == -1: - return 'skip' + pytest.skip() gdal.Translate('tmp/vrtmask_5.vrt', '../gcore/data/ycbcr_with_mask.tif', options='-of VRT -outsize 100% 100%') @@ -221,24 +193,18 @@ def vrtmask_5(): os.remove('tmp/vrtmask_5.vrt') - if msk_cs != expected_msk_cs: - gdaltest.post_reason('did not get expected mask band checksum') - print(msk_cs) - print(expected_msk_cs) - return 'fail' - - return 'success' + assert msk_cs == expected_msk_cs, 'did not get expected mask band checksum' ############################################################################### # Same with gdal_translate with explicit -b and -mask arguments -def vrtmask_6(): +def test_vrtmask_6(): gtiff_drv = gdal.GetDriverByName('GTiff') md = gtiff_drv.GetMetadata() if md['DMD_CREATIONOPTIONLIST'].find('JPEG') == -1: - return 'skip' + pytest.skip() gdal.Translate('tmp/vrtmask_6.vrt', '../gcore/data/ycbcr_with_mask.tif', options='-of VRT -b 1 -b 2 -b 3 -mask mask,1') @@ -253,24 +219,18 @@ def vrtmask_6(): os.remove('tmp/vrtmask_6.vrt') - if msk_cs != expected_msk_cs: - gdaltest.post_reason('did not get expected mask band checksum') - print(msk_cs) - print(expected_msk_cs) - return 'fail' - - return 'success' + assert msk_cs == expected_msk_cs, 'did not get expected mask band checksum' ############################################################################### # gdal_translate with RGBmask -> RGBA and then RGBA->RGBmask -def vrtmask_7(): +def test_vrtmask_7(): gtiff_drv = gdal.GetDriverByName('GTiff') md = gtiff_drv.GetMetadata() if md['DMD_CREATIONOPTIONLIST'].find('JPEG') == -1: - return 'skip' + pytest.skip() try: os.remove('tmp/vrtmask_7_rgba.tif.msk') except OSError: @@ -296,38 +256,25 @@ def vrtmask_7(): ds = None os.remove('tmp/vrtmask_7_rgba.tif') - try: + with pytest.raises(OSError, message='did not expect tmp/vrtmask_7_rgba.tif.msk'): os.remove('tmp/vrtmask_7_rgba.tif.msk') - gdaltest.post_reason('did not expect tmp/vrtmask_7_rgba.tif.msk') - return 'fail' - except OSError: - pass + os.remove('tmp/vrtmask_7_rgbmask.vrt') - if alpha_cs != expected_msk_cs: - gdaltest.post_reason('did not get expected alpha band checksum') - print(alpha_cs) - print(expected_msk_cs) - return 'fail' + assert alpha_cs == expected_msk_cs, 'did not get expected alpha band checksum' - if msk_cs != expected_msk_cs: - gdaltest.post_reason('did not get expected mask band checksum') - print(msk_cs) - print(expected_msk_cs) - return 'fail' - - return 'success' + assert msk_cs == expected_msk_cs, 'did not get expected mask band checksum' ############################################################################### # gdal_translate with RGBmask -> RGB -def vrtmask_8(): +def test_vrtmask_8(): gtiff_drv = gdal.GetDriverByName('GTiff') md = gtiff_drv.GetMetadata() if md['DMD_CREATIONOPTIONLIST'].find('JPEG') == -1: - return 'skip' + pytest.skip() gdal.Translate('tmp/vrtmask_8.vrt', '../gcore/data/ycbcr_with_mask.tif', options='-of VRT -mask none') @@ -338,20 +285,16 @@ def vrtmask_8(): os.remove('tmp/vrtmask_8.vrt') - if flags != gdal.GMF_ALL_VALID: - print(flags) - return 'fail' - - return 'success' + assert flags == gdal.GMF_ALL_VALID ############################################################################### # gdal_translate with RGBA -> RGB -def vrtmask_9(): +def test_vrtmask_9(): import test_cli_utilities if test_cli_utilities.get_gdal_translate_path() is None: - return 'skip' + pytest.skip() src_ds = gdal.GetDriverByName('GTiff').Create('tmp/vrtmask_9_src.tif', 10, 10, 4) del src_ds @@ -364,22 +307,15 @@ def vrtmask_9(): os.remove('tmp/vrtmask_9_src.tif') os.remove('tmp/vrtmask_9_dst.tif') - if err != '': - gdaltest.post_reason('unexpected output on standard err') - print(err) - return 'fail' - - if flags != gdal.GMF_ALL_VALID: - print(flags) - return 'fail' + assert err == '', 'unexpected output on standard err' - return 'success' + assert flags == gdal.GMF_ALL_VALID ############################################################################### # Test fix for #5120 (VRTSourcedRasterBand::AddMaskBandSource() ignores specified window) -def vrtmask_10(): +def test_vrtmask_10(): gdal.Translate('tmp/vrtmask_10_ref.tif', '../gcore/data/stefan_full_rgba.tif', options='-srcwin 40 40 100 100') gdal.Translate('tmp/vrtmask_10.vrt', '../gcore/data/stefan_full_rgba.tif', options='-of VRT -b 1 -b 2 -b 3 -mask 4 -srcwin 30 30 120 120') @@ -398,77 +334,43 @@ def vrtmask_10(): os.remove('tmp/vrtmask_10_2.vrt') os.remove('tmp/vrtmask_10_3.tif') - if cs_ref != cs_got: - return 'fail' - - return 'success' + assert cs_ref == cs_got ############################################################################### -def vrtmask_11(): +def test_vrtmask_11(): # Cannot create mask band at raster band level when a dataset mask band already exists ds = gdal.Translate('', 'data/byte.tif', format='VRT') ds.CreateMaskBand(gdal.GMF_PER_DATASET) with gdaltest.error_handler(): ret = ds.GetRasterBand(1).CreateMaskBand(0) - if ret == 0: - gdaltest.post_reason('expected an error, but got success') - return 'fail' + assert ret != 0, 'expected an error, but got success' # This VRT dataset has already a mask band ds = gdal.Translate('', 'data/byte.tif', format='VRT') ds.CreateMaskBand(gdal.GMF_PER_DATASET) with gdaltest.error_handler(): ret = ds.CreateMaskBand(gdal.GMF_PER_DATASET) - if ret == 0: - gdaltest.post_reason('expected an error, but got success') - return 'fail' + assert ret != 0, 'expected an error, but got success' # This VRT band has already a mask band ds = gdal.Translate('', 'data/byte.tif', format='VRT') ds.GetRasterBand(1).CreateMaskBand(0) with gdaltest.error_handler(): ret = ds.GetRasterBand(1).CreateMaskBand(0) - if ret == 0: - gdaltest.post_reason('expected an error, but got success') - return 'fail' + assert ret != 0, 'expected an error, but got success' ds = gdal.Translate('', 'data/byte.tif', format='VRT') ret = ds.GetRasterBand(1).CreateMaskBand(gdal.GMF_PER_DATASET) - if ret != 0: - gdaltest.post_reason('fail') - return 'fail' - - return 'success' + assert ret == 0 ############################################################################### # Cleanup. -def vrtmask_cleanup(): - return 'success' - - -gdaltest_list = [ - vrtmask_1, - vrtmask_2, - vrtmask_3, - vrtmask_4, - vrtmask_5, - vrtmask_6, - vrtmask_7, - vrtmask_8, - vrtmask_9, - vrtmask_10, - vrtmask_11, - vrtmask_cleanup] - -if __name__ == '__main__': - - gdaltest.setup_run('vrtmask') +def test_vrtmask_cleanup(): + pass - gdaltest.run_tests(gdaltest_list) - sys.exit(gdaltest.summarize()) diff --git a/autotest/gdrivers/vrtovr.py b/autotest/gdrivers/vrtovr.py index acaed92f7a26..b3d205d0bbd9 100755 --- a/autotest/gdrivers/vrtovr.py +++ b/autotest/gdrivers/vrtovr.py @@ -28,10 +28,8 @@ # DEALINGS IN THE SOFTWARE. ############################################################################### -import sys from osgeo import gdal -sys.path.append('../pymod') import gdaltest @@ -39,7 +37,7 @@ # Simple test -def vrtovr_1(): +def test_vrtovr_1(): vrt_string = """<VRTDataset rasterXSize="20" rasterYSize="20"> <VRTRasterBand dataType="Byte" band="1"> @@ -59,32 +57,22 @@ def vrtovr_1(): </VRTDataset>""" ds = gdal.Open(vrt_string) - if ds.GetRasterBand(1).GetOverviewCount() != 1: - gdaltest.post_reason('did not get expected overview count') - print(ds.GetRasterBand(1).GetOverviewCount()) - return 'fail' + assert ds.GetRasterBand(1).GetOverviewCount() == 1, \ + 'did not get expected overview count' cs = ds.GetRasterBand(1).GetOverview(0).Checksum() - if cs != 4672: - gdaltest.post_reason('did not get expected overview checksum') - print(cs) - return 'fail' + assert cs == 4672, 'did not get expected overview checksum' fl = ds.GetFileList() - if fl != ['data/byte.tif', 'data/int16.tif']: - gdaltest.post_reason('did not get expected file list') - print(fl) - return 'fail' + assert fl == ['data/byte.tif', 'data/int16.tif'], 'did not get expected file list' ds = None - return 'success' - ############################################################################### # Test serialization -def vrtovr_2(): +def test_vrtovr_2(): vrt_string = """<VRTDataset rasterXSize="20" rasterYSize="20"> <VRTRasterBand dataType="Byte" band="1"> @@ -112,28 +100,21 @@ def vrtovr_2(): ds = None ds = gdal.Open("/vsimem/vrtovr_2.vrt") - if ds.GetRasterBand(1).GetOverviewCount() != 1: - gdaltest.post_reason('did not get expected overview count') - print(ds.GetRasterBand(1).GetOverviewCount()) - return 'fail' + assert ds.GetRasterBand(1).GetOverviewCount() == 1, \ + 'did not get expected overview count' cs = ds.GetRasterBand(1).GetOverview(0).Checksum() - if cs != 4672: - gdaltest.post_reason('did not get expected overview checksum') - print(cs) - return 'fail' + assert cs == 4672, 'did not get expected overview checksum' ds = None gdal.Unlink("/vsimem/vrtovr_2.vrt") - return 'success' - ############################################################################### # -def vrtovr_none(): +def test_vrtovr_none(): vrt_string = """<VRTDataset rasterXSize="20" rasterYSize="20"> <VRTRasterBand dataType="Byte" band="1"> @@ -149,22 +130,16 @@ def vrtovr_none(): </VRTDataset>""" ds = gdal.Open(vrt_string) - if ds.GetRasterBand(1).GetOverviewCount() != 0: - gdaltest.post_reason('did not get expected overview count') - print(ds.GetRasterBand(1).GetOverviewCount()) - return 'fail' + assert ds.GetRasterBand(1).GetOverviewCount() == 0, \ + 'did not get expected overview count' - if ds.GetRasterBand(1).GetOverview(0): - gdaltest.post_reason('fail') - return 'fail' - - return 'success' + assert not ds.GetRasterBand(1).GetOverview(0) ############################################################################### # -def vrtovr_errors(): +def test_vrtovr_errors(): vrt_string = """<VRTDataset rasterXSize="20" rasterYSize="20"> <VRTRasterBand dataType="Byte" band="1"> @@ -184,45 +159,22 @@ def vrtovr_errors(): </VRTDataset>""" ds = gdal.Open(vrt_string) - if ds.GetRasterBand(1).GetOverviewCount() != 1: - gdaltest.post_reason('did not get expected overview count') - print(ds.GetRasterBand(1).GetOverviewCount()) - return 'fail' + assert ds.GetRasterBand(1).GetOverviewCount() == 1, \ + 'did not get expected overview count' - if ds.GetRasterBand(1).GetOverview(-1): - gdaltest.post_reason('fail') - return 'fail' + assert not ds.GetRasterBand(1).GetOverview(-1) - if ds.GetRasterBand(1).GetOverview(1): - gdaltest.post_reason('fail') - return 'fail' + assert not ds.GetRasterBand(1).GetOverview(1) with gdaltest.error_handler(): - if ds.GetRasterBand(1).GetOverview(0): - gdaltest.post_reason('fail') - return 'fail' - - return 'success' + assert not ds.GetRasterBand(1).GetOverview(0) + ############################################################################### # Cleanup. -def vrtovr_cleanup(): - return 'success' - - -gdaltest_list = [ - vrtovr_1, - vrtovr_2, - vrtovr_none, - vrtovr_errors, - vrtovr_cleanup] - -if __name__ == '__main__': - - gdaltest.setup_run('vrtovr') +def test_vrtovr_cleanup(): + pass - gdaltest.run_tests(gdaltest_list) - sys.exit(gdaltest.summarize()) diff --git a/autotest/gdrivers/vrtpansharpen.py b/autotest/gdrivers/vrtpansharpen.py index b7f7f6195e61..f3626e17edf4 100755 --- a/autotest/gdrivers/vrtpansharpen.py +++ b/autotest/gdrivers/vrtpansharpen.py @@ -28,19 +28,17 @@ # DEALINGS IN THE SOFTWARE. ############################################################################### -import sys import shutil from osgeo import gdal -sys.path.append('../pymod') -import gdaltest +import pytest ############################################################################### # Error cases -def vrtpansharpen_1(): +def test_vrtpansharpen_1(): src_ds = gdal.Open('data/small_world.tif') src_data = src_ds.GetRasterBand(1).ReadRaster() @@ -70,9 +68,7 @@ def vrtpansharpen_1(): </VRTRasterBand> </VRTDataset>""") gdal.PopErrorHandler() - if vrt_ds is not None: - gdaltest.post_reason('fail') - return 'fail' + assert vrt_ds is None # PanchroBand missing gdal.PushErrorHandler() @@ -109,9 +105,7 @@ def vrtpansharpen_1(): </PansharpeningOptions> </VRTDataset>""") gdal.PopErrorHandler() - if vrt_ds is not None: - gdaltest.post_reason('fail') - return 'fail' + assert vrt_ds is None # PanchroBand.SourceFilename missing gdal.PushErrorHandler() @@ -150,9 +144,7 @@ def vrtpansharpen_1(): </PansharpeningOptions> </VRTDataset>""") gdal.PopErrorHandler() - if vrt_ds is not None: - gdaltest.post_reason('fail') - return 'fail' + assert vrt_ds is None # Invalid dataset name gdal.PushErrorHandler() @@ -193,9 +185,7 @@ def vrtpansharpen_1(): </PansharpeningOptions> </VRTDataset>""") gdal.PopErrorHandler() - if vrt_ds is not None: - gdaltest.post_reason('fail') - return 'fail' + assert vrt_ds is None # Inconsistent declared VRT dimensions with panchro dataset. gdal.PushErrorHandler() @@ -236,9 +226,7 @@ def vrtpansharpen_1(): </PansharpeningOptions> </VRTDataset>""") gdal.PopErrorHandler() - if vrt_ds is not None: - gdaltest.post_reason('fail') - return 'fail' + assert vrt_ds is None # VRTRasterBand of unrecognized subclass 'blabla' gdal.PushErrorHandler() @@ -279,9 +267,7 @@ def vrtpansharpen_1(): </PansharpeningOptions> </VRTDataset>""") gdal.PopErrorHandler() - if vrt_ds is not None: - gdaltest.post_reason('fail') - return 'fail' + assert vrt_ds is None # Algorithm unsupported_alg unsupported gdal.PushErrorHandler() @@ -322,9 +308,7 @@ def vrtpansharpen_1(): </PansharpeningOptions> </VRTDataset>""") gdal.PopErrorHandler() - if vrt_ds is not None: - gdaltest.post_reason('fail') - return 'fail' + assert vrt_ds is None # 10 invalid band of tmp/small_world_pan.tif gdal.PushErrorHandler() @@ -365,9 +349,7 @@ def vrtpansharpen_1(): </PansharpeningOptions> </VRTDataset>""") gdal.PopErrorHandler() - if vrt_ds is not None: - gdaltest.post_reason('fail') - return 'fail' + assert vrt_ds is None # SpectralBand.dstBand = '-1' invalid gdal.PushErrorHandler() @@ -408,9 +390,7 @@ def vrtpansharpen_1(): </PansharpeningOptions> </VRTDataset>""") gdal.PopErrorHandler() - if vrt_ds is not None: - gdaltest.post_reason('fail') - return 'fail' + assert vrt_ds is None # SpectralBand.SourceFilename missing gdal.PushErrorHandler() @@ -450,9 +430,7 @@ def vrtpansharpen_1(): </PansharpeningOptions> </VRTDataset>""") gdal.PopErrorHandler() - if vrt_ds is not None: - gdaltest.post_reason('fail') - return 'fail' + assert vrt_ds is None # Invalid dataset name gdal.PushErrorHandler() @@ -493,9 +471,7 @@ def vrtpansharpen_1(): </PansharpeningOptions> </VRTDataset>""") gdal.PopErrorHandler() - if vrt_ds is not None: - gdaltest.post_reason('fail') - return 'fail' + assert vrt_ds is None # 10 invalid band of data/small_world.tif gdal.PushErrorHandler() @@ -536,9 +512,7 @@ def vrtpansharpen_1(): </PansharpeningOptions> </VRTDataset>""") gdal.PopErrorHandler() - if vrt_ds is not None: - gdaltest.post_reason('fail') - return 'fail' + assert vrt_ds is None # Another spectral band is already mapped to output band 1 gdal.PushErrorHandler() @@ -579,9 +553,7 @@ def vrtpansharpen_1(): </PansharpeningOptions> </VRTDataset>""") gdal.PopErrorHandler() - if vrt_ds is not None: - gdaltest.post_reason('fail') - return 'fail' + assert vrt_ds is None # No spectral band defined gdal.PushErrorHandler() @@ -610,9 +582,7 @@ def vrtpansharpen_1(): </PansharpeningOptions> </VRTDataset>""") gdal.PopErrorHandler() - if vrt_ds is not None: - gdaltest.post_reason('fail') - return 'fail' + assert vrt_ds is None # Hole in SpectralBand.dstBand numbering gdal.PushErrorHandler() @@ -644,9 +614,7 @@ def vrtpansharpen_1(): </PansharpeningOptions> </VRTDataset>""") gdal.PopErrorHandler() - if vrt_ds is not None: - gdaltest.post_reason('fail') - return 'fail' + assert vrt_ds is None # Band 4 of type VRTPansharpenedRasterBand, but no corresponding SpectralBand gdal.PushErrorHandler() @@ -689,9 +657,7 @@ def vrtpansharpen_1(): </PansharpeningOptions> </VRTDataset>""") gdal.PopErrorHandler() - if vrt_ds is not None: - gdaltest.post_reason('fail') - return 'fail' + assert vrt_ds is None # SpectralBand.dstBand = '3' invalid gdal.PushErrorHandler() @@ -729,9 +695,7 @@ def vrtpansharpen_1(): </PansharpeningOptions> </VRTDataset>""") gdal.PopErrorHandler() - if vrt_ds is not None: - gdaltest.post_reason('fail') - return 'fail' + assert vrt_ds is None # 2 weights defined, but 3 input spectral bands gdal.PushErrorHandler() @@ -772,9 +736,7 @@ def vrtpansharpen_1(): </PansharpeningOptions> </VRTDataset>""") gdal.PopErrorHandler() - if vrt_ds is not None: - gdaltest.post_reason('fail') - return 'fail' + assert vrt_ds is None # Dimensions of input spectral band 1 different from first spectral band gdal.PushErrorHandler() @@ -795,9 +757,7 @@ def vrtpansharpen_1(): </PansharpeningOptions> </VRTDataset>""") gdal.PopErrorHandler() - if vrt_ds is not None: - gdaltest.post_reason('fail') - return 'fail' + assert vrt_ds is None # Just warnings # Warning 1: Pan dataset and data/byte.tif do not seem to have same projection. Results might be incorrect @@ -819,12 +779,8 @@ def vrtpansharpen_1(): </PansharpeningOptions> </VRTDataset>""") gdal.PopErrorHandler() - if vrt_ds is None: - gdaltest.post_reason('fail') - return 'fail' - if gdal.GetLastErrorMsg() == '': - gdaltest.post_reason('fail') - return 'fail' + assert vrt_ds is not None + assert gdal.GetLastErrorMsg() != '' # Just warnings # No spectral band is mapped to an output band @@ -859,28 +815,20 @@ def vrtpansharpen_1(): </PansharpeningOptions> </VRTDataset>""") gdal.PopErrorHandler() - if vrt_ds is None: - gdaltest.post_reason('fail') - return 'fail' - if gdal.GetLastErrorMsg() == '': - gdaltest.post_reason('fail') - return 'fail' + assert vrt_ds is not None + assert gdal.GetLastErrorMsg() != '' # Unsupported gdal.PushErrorHandler() ret = vrt_ds.AddBand(gdal.GDT_Byte) gdal.PopErrorHandler() - if ret == 0: - gdaltest.post_reason('fail') - return 'fail' - - return 'success' + assert ret != 0 ############################################################################### # Nominal cases -def vrtpansharpen_2(): +def test_vrtpansharpen_2(): shutil.copy('data/small_world.tif', 'tmp/small_world.tif') @@ -923,47 +871,26 @@ def vrtpansharpen_2(): </SpectralBand> </PansharpeningOptions> </VRTDataset>""") - if vrt_ds is None: - gdaltest.post_reason('fail') - return 'fail' - if vrt_ds.GetFileList() != ['tmp/small_world_pan.tif', 'data/small_world.tif']: - gdaltest.post_reason('fail') - print(vrt_ds.GetFileList()) - return 'fail' - if vrt_ds.GetRasterBand(1).GetMetadataItem('NBITS', 'IMAGE_STRUCTURE') is not None: - gdaltest.post_reason('fail') - return 'fail' + assert vrt_ds is not None + assert vrt_ds.GetFileList() == ['tmp/small_world_pan.tif', 'data/small_world.tif'] + assert vrt_ds.GetRasterBand(1).GetMetadataItem('NBITS', 'IMAGE_STRUCTURE') is None cs = [vrt_ds.GetRasterBand(i + 1).Checksum() for i in range(vrt_ds.RasterCount)] - if cs not in ([4735, 10000, 9742], [4731, 9991, 9734]): - gdaltest.post_reason('fail') - print(cs) - return 'fail' - if vrt_ds.GetRasterBand(1).GetOverviewCount() != 0: - gdaltest.post_reason('fail') - return 'fail' - if vrt_ds.GetRasterBand(1).GetOverview(-1) is not None: - gdaltest.post_reason('fail') - return 'fail' - if vrt_ds.GetRasterBand(1).GetOverview(0) is not None: - gdaltest.post_reason('fail') - return 'fail' + assert cs in ([4735, 10000, 9742], [4731, 9991, 9734]) + assert vrt_ds.GetRasterBand(1).GetOverviewCount() == 0 + assert vrt_ds.GetRasterBand(1).GetOverview(-1) is None + assert vrt_ds.GetRasterBand(1).GetOverview(0) is None # Check VRTPansharpenedDataset::IRasterIO() in non-resampling case data = vrt_ds.ReadRaster() tmp_ds = gdal.GetDriverByName('MEM').Create('', 800, 400, 3) tmp_ds.WriteRaster(0, 0, 800, 400, data) cs = [tmp_ds.GetRasterBand(i + 1).Checksum() for i in range(tmp_ds.RasterCount)] - if cs not in ([4735, 10000, 9742], [4731, 9991, 9734]): - gdaltest.post_reason('fail') - print(cs) - return 'fail' + assert cs in ([4735, 10000, 9742], [4731, 9991, 9734]) # Check VRTPansharpenedDataset::IRasterIO() in resampling case data = vrt_ds.ReadRaster(0, 0, 800, 400, 400, 200) ref_data = tmp_ds.ReadRaster(0, 0, 800, 400, 400, 200) - if data != ref_data: - gdaltest.post_reason('fail') - return 'fail' + assert data == ref_data # Compact case vrt_ds = gdal.Open("""<VRTDataset subClass="VRTPansharpenedDataset"> @@ -986,14 +913,9 @@ def vrtpansharpen_2(): </SpectralBand> </PansharpeningOptions> </VRTDataset>""") - if vrt_ds is None: - gdaltest.post_reason('fail') - return 'fail' + assert vrt_ds is not None cs = [vrt_ds.GetRasterBand(i + 1).Checksum() for i in range(vrt_ds.RasterCount)] - if cs not in ([4735, 10000, 9742], [4731, 9991, 9734]): - gdaltest.post_reason('fail') - print(cs) - return 'fail' + assert cs in ([4735, 10000, 9742], [4731, 9991, 9734]) # Expose pan band too vrt_ds = gdal.Open("""<VRTDataset rasterXSize="800" rasterYSize="400" subClass="VRTPansharpenedDataset"> @@ -1040,15 +962,10 @@ def vrtpansharpen_2(): </SpectralBand> </PansharpeningOptions> </VRTDataset>""") - if vrt_ds is None: - gdaltest.post_reason('fail') - return 'fail' + assert vrt_ds is not None # gdal.GetDriverByName('GTiff').CreateCopy('out1.tif', vrt_ds) cs = [vrt_ds.GetRasterBand(i + 1).Checksum() for i in range(vrt_ds.RasterCount)] - if cs not in ([50261, 4735, 10000, 9742], [50261, 4731, 9991, 9734]): - gdaltest.post_reason('fail') - print(cs) - return 'fail' + assert cs in ([50261, 4735, 10000, 9742], [50261, 4731, 9991, 9734]) # Same, but everything scrambled, and with spectral bands not in # the same dataset @@ -1096,23 +1013,16 @@ def vrtpansharpen_2(): </SpectralBand> </PansharpeningOptions> </VRTDataset>""") - if vrt_ds is None: - gdaltest.post_reason('fail') - return 'fail' + assert vrt_ds is not None # gdal.GetDriverByName('GTiff').CreateCopy('out2.tif', vrt_ds) cs = [vrt_ds.GetRasterBand(i + 1).Checksum() for i in range(vrt_ds.RasterCount)] - if cs not in ([50261, 4735, 10000, 9742], [50261, 4727, 9998, 9732]): - gdaltest.post_reason('fail') - print(cs) - return 'fail' - - return 'success' + assert cs in ([50261, 4735, 10000, 9742], [50261, 4727, 9998, 9732]) ############################################################################### # Test with overviews -def vrtpansharpen_3(): +def test_vrtpansharpen_3(): ds = gdal.Open('tmp/small_world_pan.tif') ds.BuildOverviews('CUBIC', [2]) @@ -1141,17 +1051,10 @@ def vrtpansharpen_3(): # Test when only Pan band has overviews vrt_ds = gdal.Open(xml) - if vrt_ds.GetRasterBand(1).GetOverviewCount() != 1: - gdaltest.post_reason('fail') - return 'fail' - if vrt_ds.GetRasterBand(1).GetOverview(0) is None: - gdaltest.post_reason('fail') - return 'fail' + assert vrt_ds.GetRasterBand(1).GetOverviewCount() == 1 + assert vrt_ds.GetRasterBand(1).GetOverview(0) is not None cs = [vrt_ds.GetRasterBand(i + 1).GetOverview(0).Checksum() for i in range(vrt_ds.RasterCount)] - if cs not in ([7123, 7445, 5025], [7120, 7440, 5025]): - gdaltest.post_reason('fail') - print(cs) - return 'fail' + assert cs in ([7123, 7445, 5025], [7120, 7440, 5025]) # Check VRTPansharpenedDataset::IRasterIO() in resampling case with overviews data = vrt_ds.ReadRaster(0, 0, 800, 400, 400, 200) @@ -1160,17 +1063,12 @@ def vrtpansharpen_3(): data2 += vrt_ds.GetRasterBand(2).ReadRaster(0, 0, 800, 400, 400, 200) data2 += vrt_ds.GetRasterBand(3).ReadRaster(0, 0, 800, 400, 400, 200) - if data != data2: - gdaltest.post_reason('fail') - return 'fail' + assert data == data2 tmp_ds = gdal.GetDriverByName('MEM').Create('', 400, 200, 3) tmp_ds.WriteRaster(0, 0, 400, 200, data) cs = [tmp_ds.GetRasterBand(i + 1).Checksum() for i in range(tmp_ds.RasterCount)] - if cs not in ([7123, 7445, 5025], [7120, 7440, 5025]): - gdaltest.post_reason('fail') - print(cs) - return 'fail' + assert cs in ([7123, 7445, 5025], [7120, 7440, 5025]) vrt_ds = None @@ -1180,27 +1078,18 @@ def vrtpansharpen_3(): # Test when both Pan and spectral bands have overviews vrt_ds = gdal.Open(xml) - if vrt_ds.GetRasterBand(1).GetOverviewCount() != 1: - gdaltest.post_reason('fail') - return 'fail' - if vrt_ds.GetRasterBand(1).GetOverview(0) is None: - gdaltest.post_reason('fail') - return 'fail' + assert vrt_ds.GetRasterBand(1).GetOverviewCount() == 1 + assert vrt_ds.GetRasterBand(1).GetOverview(0) is not None cs = [vrt_ds.GetRasterBand(i + 1).GetOverview(0).Checksum() for i in range(vrt_ds.RasterCount)] - if cs not in ([18033, 18395, 16824], [18033, 18395, 16822]): - gdaltest.post_reason('fail') - print(cs) - return 'fail' + assert cs in ([18033, 18395, 16824], [18033, 18395, 16822]) vrt_ds = None - return 'success' - ############################################################################### # Test RasterIO() with various buffer datatypes -def vrtpansharpen_4(): +def test_vrtpansharpen_4(): xml = """<VRTDataset subClass="VRTPansharpenedDataset"> <PansharpeningOptions> @@ -1233,19 +1122,14 @@ def vrtpansharpen_4(): expected_cs = [4724, 4720] else: expected_cs = [4735, 4731] - if cs not in expected_cs: - gdaltest.post_reason('fail') - print(gdal.GetDataTypeName(dt)) - print(cs) - return 'fail' - - return 'success' + assert cs in expected_cs, gdal.GetDataTypeName(dt) + ############################################################################### # Test RasterIO() with various band datatypes -def vrtpansharpen_5(): +def test_vrtpansharpen_5(): for dt in [gdal.GDT_Int16, gdal.GDT_UInt16, gdal.GDT_Int32, gdal.GDT_UInt32, gdal.GDT_Float32, gdal.GDT_Float64, gdal.GDT_CFloat64]: @@ -1311,32 +1195,23 @@ def vrtpansharpen_5(): tmp_ds.WriteRaster(0, 0, 800, 400, data) cs = tmp_ds.GetRasterBand(1).Checksum() if dt == gdal.GDT_UInt16: - if cs not in (4553, 4549): - gdaltest.post_reason('fail') - print(gdal.GetDataTypeName(dt)) - print(cs) - return 'fail' + assert cs in (4553, 4549), gdal.GetDataTypeName(dt) else: - if cs != 4450: - gdaltest.post_reason('fail') - print(gdal.GetDataTypeName(dt)) - print(cs) - return 'fail' - - return 'success' + assert cs == 4450, gdal.GetDataTypeName(dt) + ############################################################################### # Test BitDepth limitations -def vrtpansharpen_6(): +def test_vrtpansharpen_6(): try: from osgeo import gdalnumeric gdalnumeric.zeros import numpy except (ImportError, AttributeError): - return 'skip' + pytest.skip() # i = 0: VRT has <BitDepth>7</BitDepth> # i = 1: bands have NBITS=7 and VRT <BitDepth>7</BitDepth> @@ -1389,9 +1264,7 @@ def vrtpansharpen_6(): </VRTDataset>""" vrt_ds = gdal.Open(xml) - if vrt_ds.GetRasterBand(1).GetMetadataItem('NBITS', 'IMAGE_STRUCTURE') != str(nbits): - gdaltest.post_reason('fail') - return 'fail' + assert vrt_ds.GetRasterBand(1).GetMetadataItem('NBITS', 'IMAGE_STRUCTURE') == str(nbits) ar = vrt_ds.GetRasterBand(1).ReadAsArray() if dt == gdal.GDT_Byte: @@ -1402,23 +1275,19 @@ def vrtpansharpen_6(): expected_ar = [97280, 113920, 131071, 131071, 131071, 131071, 113920, 97280] if list(ar[0]) != expected_ar: - gdaltest.post_reason('fail') print(gdal.GetDataTypeName(dt)) - print(i) - print(list(ar[0])) - return 'fail' + pytest.fail(i) vrt_ds = None gdal.Unlink('/vsimem/ms.tif') gdal.Unlink('/vsimem/pan.tif') - return 'success' - + ############################################################################### # Test bands with different extents -def vrtpansharpen_7(): +def test_vrtpansharpen_7(): ds = gdal.GetDriverByName('GTiff').Create('/vsimem/vrtpansharpen_7_pan.tif', 20, 40) ds.SetGeoTransform([120, 1, 0, 80, 0, -1]) @@ -1439,12 +1308,7 @@ def vrtpansharpen_7(): </PansharpeningOptions> </VRTDataset>""" ds = gdal.Open(xml) - if ds.GetGeoTransform() != (100.0, 1.0, 0.0, 100.0, 0.0, -1.0) or ds.RasterXSize != 40 or ds.RasterYSize != 60: - gdaltest.post_reason('fail') - print(ds.GetGeoTransform()) - print(ds.RasterXSize) - print(ds.RasterYSize) - return 'fail' + assert ds.GetGeoTransform() == (100.0, 1.0, 0.0, 100.0, 0.0, -1.0) and ds.RasterXSize == 40 and ds.RasterYSize == 60 ds = None xml = """<VRTDataset subClass="VRTPansharpenedDataset"> @@ -1459,12 +1323,7 @@ def vrtpansharpen_7(): </PansharpeningOptions> </VRTDataset>""" ds = gdal.Open(xml) - if ds.GetGeoTransform() != (100.0, 1.0, 0.0, 100.0, 0.0, -1.0) or ds.RasterXSize != 40 or ds.RasterYSize != 60: - gdaltest.post_reason('fail') - print(ds.GetGeoTransform()) - print(ds.RasterXSize) - print(ds.RasterYSize) - return 'fail' + assert ds.GetGeoTransform() == (100.0, 1.0, 0.0, 100.0, 0.0, -1.0) and ds.RasterXSize == 40 and ds.RasterYSize == 60 ds = None xml = """<VRTDataset subClass="VRTPansharpenedDataset"> @@ -1482,15 +1341,8 @@ def vrtpansharpen_7(): gdal.PushErrorHandler() ds = gdal.Open(xml) gdal.PopErrorHandler() - if ds.GetGeoTransform() != (100.0, 1.0, 0.0, 100.0, 0.0, -1.0) or ds.RasterXSize != 40 or ds.RasterYSize != 60: - gdaltest.post_reason('fail') - print(ds.GetGeoTransform()) - print(ds.RasterXSize) - print(ds.RasterYSize) - return 'fail' - if gdal.GetLastErrorMsg() != '': - gdaltest.post_reason('fail') - return 'fail' + assert ds.GetGeoTransform() == (100.0, 1.0, 0.0, 100.0, 0.0, -1.0) and ds.RasterXSize == 40 and ds.RasterYSize == 60 + assert gdal.GetLastErrorMsg() == '' ds = None xml = """<VRTDataset subClass="VRTPansharpenedDataset"> @@ -1505,12 +1357,7 @@ def vrtpansharpen_7(): </PansharpeningOptions> </VRTDataset>""" ds = gdal.Open(xml) - if ds.GetGeoTransform() != (120.0, 1.0, 0.0, 80.0, 0.0, -1.0) or ds.RasterXSize != 10 or ds.RasterYSize != 40: - gdaltest.post_reason('fail') - print(ds.GetGeoTransform()) - print(ds.RasterXSize) - print(ds.RasterYSize) - return 'fail' + assert ds.GetGeoTransform() == (120.0, 1.0, 0.0, 80.0, 0.0, -1.0) and ds.RasterXSize == 10 and ds.RasterYSize == 40 ds = None xml = """<VRTDataset subClass="VRTPansharpenedDataset"> @@ -1528,15 +1375,8 @@ def vrtpansharpen_7(): gdal.PushErrorHandler() ds = gdal.Open(xml) gdal.PopErrorHandler() - if ds.GetGeoTransform() != (120.0, 1.0, 0.0, 80.0, 0.0, -1.0) or ds.RasterXSize != 20 or ds.RasterYSize != 40: - gdaltest.post_reason('fail') - print(ds.GetGeoTransform()) - print(ds.RasterXSize) - print(ds.RasterYSize) - return 'fail' - if gdal.GetLastErrorMsg() == '': - gdaltest.post_reason('fail') - return 'fail' + assert ds.GetGeoTransform() == (120.0, 1.0, 0.0, 80.0, 0.0, -1.0) and ds.RasterXSize == 20 and ds.RasterYSize == 40 + assert gdal.GetLastErrorMsg() != '' ds = None xml = """<VRTDataset subClass="VRTPansharpenedDataset"> @@ -1552,15 +1392,8 @@ def vrtpansharpen_7(): </VRTDataset>""" gdal.ErrorReset() ds = gdal.Open(xml) - if ds.GetGeoTransform() != (120.0, 1.0, 0.0, 80.0, 0.0, -1.0) or ds.RasterXSize != 20 or ds.RasterYSize != 40: - gdaltest.post_reason('fail') - print(ds.GetGeoTransform()) - print(ds.RasterXSize) - print(ds.RasterYSize) - return 'fail' - if gdal.GetLastErrorMsg() != '': - gdaltest.post_reason('fail') - return 'fail' + assert ds.GetGeoTransform() == (120.0, 1.0, 0.0, 80.0, 0.0, -1.0) and ds.RasterXSize == 20 and ds.RasterYSize == 40 + assert gdal.GetLastErrorMsg() == '' ds = None # Empty intersection @@ -1582,21 +1415,17 @@ def vrtpansharpen_7(): gdal.PushErrorHandler() ds = gdal.Open(xml) gdal.PopErrorHandler() - if ds is not None: - gdaltest.post_reason('fail') - return 'fail' + assert ds is None ds = None gdal.GetDriverByName('GTiff').Delete('/vsimem/vrtpansharpen_7_pan.tif') gdal.GetDriverByName('GTiff').Delete('/vsimem/vrtpansharpen_7_ms.tif') - return 'success' - ############################################################################### # Test SerializeToXML() -def vrtpansharpen_8(): +def test_vrtpansharpen_8(): xml = """<VRTDataset subClass="VRTPansharpenedDataset"> <VRTRasterBand dataType="Byte" band="1" subClass="VRTPansharpenedRasterBand"> @@ -1637,23 +1466,13 @@ def vrtpansharpen_8(): gdal.Unlink('tmp/vrtpansharpen_8.vrt') - if cs1 != expected_cs1 or cs2 != expected_cs2 or cs3 != expected_cs3: - gdaltest.post_reason('fail') - print(cs1) - print(expected_cs1) - print(cs2) - print(expected_cs2) - print(cs3) - print(expected_cs3) - return 'fail' - - return 'success' + assert cs1 == expected_cs1 and cs2 == expected_cs2 and cs3 == expected_cs3 ############################################################################### # Test NoData support -def vrtpansharpen_9(): +def test_vrtpansharpen_9(): # Explicit nodata vrt_ds = gdal.Open("""<VRTDataset subClass="VRTPansharpenedDataset"> @@ -1677,14 +1496,9 @@ def vrtpansharpen_9(): </SpectralBand> </PansharpeningOptions> </VRTDataset>""") - if vrt_ds is None: - gdaltest.post_reason('fail') - return 'fail' + assert vrt_ds is not None cs = [vrt_ds.GetRasterBand(i + 1).Checksum() for i in range(vrt_ds.RasterCount)] - if cs not in ([6950, 11745, 8965],): - gdaltest.post_reason('fail') - print(cs) - return 'fail' + assert cs in ([6950, 11745, 8965],) # Implicit nodata ds = gdal.GetDriverByName('GTiff').Create('/vsimem/small_world_pan_nodata.tif', 800, 400) @@ -1719,25 +1533,18 @@ def vrtpansharpen_9(): </SpectralBand> </PansharpeningOptions> </VRTDataset>""") - if vrt_ds is None: - gdaltest.post_reason('fail') - return 'fail' + assert vrt_ds is not None cs = [vrt_ds.GetRasterBand(i + 1).Checksum() for i in range(vrt_ds.RasterCount)] - if cs not in ([6950, 11745, 8965],): - gdaltest.post_reason('fail') - print(cs) - return 'fail' + assert cs in ([6950, 11745, 8965],) gdal.Unlink('/vsimem/small_world_pan_nodata.tif') gdal.Unlink('/vsimem/small_world_nodata.tif') - return 'success' - ############################################################################### # Test UInt16 optimizations -def vrtpansharpen_10(): +def test_vrtpansharpen_10(): ds = gdal.GetDriverByName('GTiff').Create('/vsimem/pan.tif', 1023, 1023, 1, gdal.GDT_UInt16) ds.GetRasterBand(1).Fill(1000) @@ -1774,10 +1581,7 @@ def vrtpansharpen_10(): </PansharpeningOptions> </VRTDataset>""") cs = [vrt_ds.GetRasterBand(i + 1).Checksum() for i in range(vrt_ds.RasterCount)] - if cs != [62009, 62009, 62009, 62009]: - gdaltest.post_reason('fail') - print(cs) - return 'fail' + assert cs == [62009, 62009, 62009, 62009] # Actually go through the optimized impl data = vrt_ds.ReadRaster() @@ -1786,9 +1590,7 @@ def vrtpansharpen_10(): tmp_ds = gdal.GetDriverByName('MEM').Create('', vrt_ds.RasterXSize, vrt_ds.RasterYSize, vrt_ds.RasterCount, gdal.GDT_Int32) tmp_ds.WriteRaster(0, 0, vrt_ds.RasterXSize, vrt_ds.RasterYSize, data_int32) ref_data = tmp_ds.ReadRaster(buf_type=gdal.GDT_UInt16) - if data != ref_data: - gdaltest.post_reason('fail') - return 'fail' + assert data == ref_data # 4 bands -> 3 bands vrt_ds = gdal.Open("""<VRTDataset subClass="VRTPansharpenedDataset"> @@ -1817,10 +1619,7 @@ def vrtpansharpen_10(): </PansharpeningOptions> </VRTDataset>""") cs = [vrt_ds.GetRasterBand(i + 1).Checksum() for i in range(vrt_ds.RasterCount)] - if cs != [62009, 62009, 62009]: - gdaltest.post_reason('fail') - print(cs) - return 'fail' + assert cs == [62009, 62009, 62009] # Actually go through the optimized impl data = vrt_ds.ReadRaster() @@ -1829,9 +1628,7 @@ def vrtpansharpen_10(): tmp_ds = gdal.GetDriverByName('MEM').Create('', vrt_ds.RasterXSize, vrt_ds.RasterYSize, vrt_ds.RasterCount, gdal.GDT_Int32) tmp_ds.WriteRaster(0, 0, vrt_ds.RasterXSize, vrt_ds.RasterYSize, data_int32) ref_data = tmp_ds.ReadRaster(buf_type=gdal.GDT_UInt16) - if data != ref_data: - gdaltest.post_reason('fail') - return 'fail' + assert data == ref_data # 3 bands vrt_ds = gdal.Open("""<VRTDataset subClass="VRTPansharpenedDataset"> @@ -1856,10 +1653,7 @@ def vrtpansharpen_10(): </PansharpeningOptions> </VRTDataset>""") cs = [vrt_ds.GetRasterBand(i + 1).Checksum() for i in range(vrt_ds.RasterCount)] - if cs != [62009, 62009, 62009]: - gdaltest.post_reason('fail') - print(cs) - return 'fail' + assert cs == [62009, 62009, 62009] # Actually go through the optimized impl data = vrt_ds.ReadRaster() @@ -1868,17 +1662,13 @@ def vrtpansharpen_10(): tmp_ds = gdal.GetDriverByName('MEM').Create('', vrt_ds.RasterXSize, vrt_ds.RasterYSize, vrt_ds.RasterCount, gdal.GDT_Int32) tmp_ds.WriteRaster(0, 0, vrt_ds.RasterXSize, vrt_ds.RasterYSize, data_int32) ref_data = tmp_ds.ReadRaster(buf_type=gdal.GDT_UInt16) - if data != ref_data: - gdaltest.post_reason('fail') - return 'fail' - - return 'success' + assert data == ref_data ############################################################################### # Test gdal.CreatePansharpenedVRT() -def vrtpansharpen_11(): +def test_vrtpansharpen_11(): pan_ds = gdal.Open('tmp/small_world_pan.tif') ms_ds = gdal.Open('data/small_world.tif') @@ -1893,14 +1683,9 @@ def vrtpansharpen_11(): </SpectralBand> </PansharpeningOptions> </VRTDataset>""", pan_ds.GetRasterBand(1), [ms_ds.GetRasterBand(i + 1) for i in range(3)]) - if vrt_ds is None: - gdaltest.post_reason('fail') - return 'fail' + assert vrt_ds is not None cs = [vrt_ds.GetRasterBand(i + 1).Checksum() for i in range(vrt_ds.RasterCount)] - if cs not in([4735, 10000, 9742], [4731, 9991, 9734]): - gdaltest.post_reason('fail') - print(cs) - return 'fail' + assert cs in([4735, 10000, 9742], [4731, 9991, 9734]) # Also test with completely anonymous datasets pan_mem_ds = gdal.GetDriverByName('MEM').CreateCopy('', pan_ds) @@ -1918,14 +1703,9 @@ def vrtpansharpen_11(): </SpectralBand> </PansharpeningOptions> </VRTDataset>""", pan_mem_ds.GetRasterBand(1), [ms_mem_ds.GetRasterBand(i + 1) for i in range(3)]) - if vrt_ds is None: - gdaltest.post_reason('fail') - return 'fail' + assert vrt_ds is not None cs = [vrt_ds.GetRasterBand(i + 1).Checksum() for i in range(vrt_ds.RasterCount)] - if cs not in([4735, 10000, 9742], [4731, 9991, 9734]): - gdaltest.post_reason('fail') - print(cs) - return 'fail' + assert cs in([4735, 10000, 9742], [4731, 9991, 9734]) vrt_ds = None # Check that wrapping with VRT works (when gt are not compatible) @@ -1944,21 +1724,14 @@ def vrtpansharpen_11(): </SpectralBand> </PansharpeningOptions> </VRTDataset>""", pan_mem_ds.GetRasterBand(1), [ms_mem_ds.GetRasterBand(i + 1) for i in range(3)]) - if vrt_ds.GetGeoTransform() != (100.0, 1.0, 0.0, 100.0, 0.0, -1.0) or vrt_ds.RasterXSize != 40 or vrt_ds.RasterYSize != 60: - gdaltest.post_reason('fail') - print(vrt_ds.GetGeoTransform()) - print(vrt_ds.RasterXSize) - print(vrt_ds.RasterYSize) - return 'fail' + assert vrt_ds.GetGeoTransform() == (100.0, 1.0, 0.0, 100.0, 0.0, -1.0) and vrt_ds.RasterXSize == 40 and vrt_ds.RasterYSize == 60 vrt_ds = None # Test error cases as well gdal.PushErrorHandler() vrt_ds = gdal.CreatePansharpenedVRT("""<invalid_xml""", pan_mem_ds.GetRasterBand(1), [ms_mem_ds.GetRasterBand(i + 1) for i in range(3)]) gdal.PopErrorHandler() - if vrt_ds is not None: - gdaltest.post_reason('fail') - return 'fail' + assert vrt_ds is None # Not enough bands gdal.PushErrorHandler() @@ -1971,9 +1744,7 @@ def vrtpansharpen_11(): </PansharpeningOptions> </VRTDataset>""", pan_mem_ds.GetRasterBand(1), [ms_mem_ds.GetRasterBand(i + 1) for i in range(3)]) gdal.PopErrorHandler() - if vrt_ds is not None: - gdaltest.post_reason('fail') - return 'fail' + assert vrt_ds is None # Too many bands gdal.PushErrorHandler() @@ -1990,47 +1761,15 @@ def vrtpansharpen_11(): </PansharpeningOptions> </VRTDataset>""", pan_mem_ds.GetRasterBand(1), [ms_mem_ds.GetRasterBand(i + 1) for i in range(3)]) gdal.PopErrorHandler() - if vrt_ds is not None: - gdaltest.post_reason('fail') - return 'fail' - - return 'success' + assert vrt_ds is None ############################################################################### # Cleanup -def vrtpansharpen_cleanup(): +def test_vrtpansharpen_cleanup(): gdal.GetDriverByName('GTiff').Delete('tmp/small_world_pan.tif') gdal.GetDriverByName('GTiff').Delete('tmp/small_world.tif') gdal.GetDriverByName('GTiff').Delete('/vsimem/pan.tif') gdal.GetDriverByName('GTiff').Delete('/vsimem/ms.tif') - - return 'success' - - -gdaltest_list = [ - vrtpansharpen_1, - vrtpansharpen_2, - vrtpansharpen_3, - vrtpansharpen_4, - vrtpansharpen_5, - vrtpansharpen_6, - vrtpansharpen_7, - vrtpansharpen_8, - vrtpansharpen_9, - vrtpansharpen_10, - vrtpansharpen_11, - vrtpansharpen_cleanup, -] - -# gdaltest_list= [ vrtpansharpen_1, vrtpansharpen_8 ] - -if __name__ == '__main__': - - gdaltest.setup_run('vrtpansharpen') - - gdaltest.run_tests(gdaltest_list) - - sys.exit(gdaltest.summarize()) diff --git a/autotest/gdrivers/vrtrawlink.py b/autotest/gdrivers/vrtrawlink.py index 21d77b2e2645..a2c46c1ad41b 100755 --- a/autotest/gdrivers/vrtrawlink.py +++ b/autotest/gdrivers/vrtrawlink.py @@ -31,10 +31,8 @@ ############################################################################### import os -import sys from osgeo import gdal -sys.path.append('../pymod') import gdaltest @@ -48,7 +46,7 @@ def _xmlsearch(root, nodetype, name): # Verify reading from simple existing raw definition. -def vrtrawlink_1(): +def test_vrtrawlink_1(): tst = gdaltest.GDALTest('VRT', 'small.vrt', 2, 12816) return tst.testOpen() @@ -57,7 +55,7 @@ def vrtrawlink_1(): # Create a new VRT raw link via the AddBand() method. -def vrtrawlink_2(): +def test_vrtrawlink_2(): driver = gdal.GetDriverByName("VRT") ds = driver.Create('tmp/rawlink.vrt', 31, 35, 0) @@ -68,49 +66,36 @@ def vrtrawlink_2(): ] result = ds.AddBand(gdal.GDT_Byte, options) - if result != gdal.CE_None: - gdaltest.post_reason('AddBand() returned error code') - return 'fail' + assert result == gdal.CE_None, 'AddBand() returned error code' band = ds.GetRasterBand(1) chksum = band.Checksum() - if chksum != 12481: - gdaltest.post_reason('Wrong checksum') - return 'fail' + assert chksum == 12481, 'Wrong checksum' # Force it to be written to disk. ds = None - return 'success' - ############################################################################### # Confirm that the newly written file is was saved properly -def vrtrawlink_3(): +def test_vrtrawlink_3(): gdaltest.rawlink_ds = gdal.Open('tmp/rawlink.vrt', gdal.GA_Update) filelist = gdaltest.rawlink_ds.GetFileList() band = gdaltest.rawlink_ds.GetRasterBand(1) chksum = band.Checksum() - if chksum != 12481: - gdaltest.post_reason('Wrong checksum') - return 'fail' - - if len(filelist) != 2: - gdaltest.post_reason('Wrong filelist') - print(filelist) - return 'fail' + assert chksum == 12481, 'Wrong checksum' - return 'success' + assert len(filelist) == 2, 'Wrong filelist' ############################################################################### # Add a new band, and we will test if we can write to it. -def vrtrawlink_4(): +def test_vrtrawlink_4(): # force creation of the file. open('tmp/rawlink.dat', 'w').write(chr(0)) @@ -127,9 +112,7 @@ def vrtrawlink_4(): ] result = gdaltest.rawlink_ds.AddBand(gdal.GDT_UInt16, options) - if result != gdal.CE_None: - gdaltest.post_reason('AddBand() returned error code') - return 'fail' + assert result == gdal.CE_None, 'AddBand() returned error code' # write out some simple data. band_1 = gdaltest.rawlink_ds.GetRasterBand(1) @@ -143,9 +126,7 @@ def vrtrawlink_4(): # Verify it seems to be right. chksum = band.Checksum() - if chksum != 12481: - gdaltest.post_reason('Wrong checksum') - return 'fail' + assert chksum == 12481, 'Wrong checksum' band_1 = None band = None @@ -157,23 +138,17 @@ def vrtrawlink_4(): band = gdaltest.rawlink_ds.GetRasterBand(2) chksum = band.Checksum() - if chksum != 12481: - gdaltest.post_reason('Wrong checksum') - return 'fail' + assert chksum == 12481, 'Wrong checksum' # verify file length. statinfo = os.stat('tmp/rawlink.dat') - if statinfo.st_size != 3354: - gdaltest.post_reason('data file is wrong size') - return 'fail' - - return 'success' + assert statinfo.st_size == 3354, 'data file is wrong size' ############################################################################### # Add a new band, and check the relativeToVRT property. -def vrtrawlink_5(): +def test_vrtrawlink_5(): driver = gdal.GetDriverByName("VRT") ds = driver.Create('tmp/rawlink.vrt', 31, 35, 0) @@ -190,9 +165,7 @@ def vrtrawlink_5(): ] result = ds.AddBand(gdal.GDT_UInt16, options) - if result != gdal.CE_None: - gdaltest.post_reason('AddBand() returned error code') - return 'fail' + assert result == gdal.CE_None, 'AddBand() returned error code' gdaltest.rawlink_ds.FlushCache() @@ -205,24 +178,17 @@ def vrtrawlink_5(): node = _xmlsearch(node, gdal.CXT_Element, 'SourceFilename') node = _xmlsearch(node, gdal.CXT_Attribute, 'relativeToVRT') - if node is None or node[2][1] != "1": - gdaltest.post_reason('incorrect relativeToVRT value') - return 'fail' - - if xmlstring.find('<ImageOffset>100</ImageOffset>') < 0 or \ - xmlstring.find('<PixelOffset>3</PixelOffset>') < 0 or \ - xmlstring.find('<LineOffset>93</LineOffset>') < 0: - gdaltest.post_reason('fail') - print(xmlstring) - return 'fail' + assert node is not None and node[2][1] == "1", 'incorrect relativeToVRT value' - return 'success' + assert (xmlstring.find('<ImageOffset>100</ImageOffset>') >= 0 and \ + xmlstring.find('<PixelOffset>3</PixelOffset>') >= 0 and \ + xmlstring.find('<LineOffset>93</LineOffset>') >= 0) ############################################################################### # Add a new band with relativeToVRT=1, and re-open the dataset. -def vrtrawlink_6(): +def test_vrtrawlink_6(): driver = gdal.GetDriverByName("VRT") ds = driver.Create('tmp/rawlink.vrt', 31, 35, 0) @@ -239,9 +205,7 @@ def vrtrawlink_6(): ] result = ds.AddBand(gdal.GDT_UInt16, options) - if result != gdal.CE_None: - gdaltest.post_reason('AddBand() returned error code') - return 'fail' + assert result == gdal.CE_None, 'AddBand() returned error code' ds.FlushCache() @@ -249,27 +213,19 @@ def vrtrawlink_6(): ds = None ds = gdal.Open('tmp/rawlink.vrt') - if ds is None: - gdaltest.post_reason('unable to open the dataset: "tmp/rawlink.vrt"') - return 'fail' + assert ds is not None, 'unable to open the dataset: "tmp/rawlink.vrt"' b = ds.GetRasterBand(1) - if b is None: - gdaltest.post_reason('unable to open the raster band #1') - return 'fail' + assert b is not None, 'unable to open the raster band #1' - if not os.path.exists('tmp/rawlink6.dat'): - gdaltest.post_reason( - 'tha raw file is not in the expected location ("tmp/rawlink6.dat")') - return 'fail' - - return 'success' + assert os.path.exists('tmp/rawlink6.dat'), \ + 'tha raw file is not in the expected location ("tmp/rawlink6.dat")' ############################################################################### # Add a new band with relativeToVRT=1, change directory and re-open the dataset. -def vrtrawlink_7(): +def test_vrtrawlink_7(): driver = gdal.GetDriverByName("VRT") ds = driver.Create('tmp/rawlink.vrt', 31, 35, 0) @@ -286,9 +242,7 @@ def vrtrawlink_7(): ] result = ds.AddBand(gdal.GDT_UInt16, options) - if result != gdal.CE_None: - gdaltest.post_reason('AddBand() returned error code') - return 'fail' + assert result == gdal.CE_None, 'AddBand() returned error code' ds.FlushCache() @@ -298,24 +252,19 @@ def vrtrawlink_7(): os.chdir('tmp') try: ds = gdal.Open('rawlink.vrt') - if ds is None: - gdaltest.post_reason('unable to open the dataset: "rawlink.vrt"') - return 'fail' + assert ds is not None, 'unable to open the dataset: "rawlink.vrt"' b = ds.GetRasterBand(1) - if b is None: - gdaltest.post_reason('unable to open the raster band #1') - return 'fail' + assert b is not None, 'unable to open the raster band #1' finally: os.chdir('..') - return 'success' - + ############################################################################### # Test error case (too much memory allocation) -def vrtrawlink_8(): +def test_vrtrawlink_8(): for _ in range(2): with gdaltest.error_handler(): @@ -328,17 +277,14 @@ def vrtrawlink_8(): <ByteOrder>LSB</ByteOrder> </VRTRasterBand> </VRTDataset>""") - if ds or gdal.GetLastErrorMsg().find('Image file is too small') < 0: - print(gdal.GetLastErrorMsg()) - return 'fail' - - return 'success' + assert not (ds or gdal.GetLastErrorMsg().find('Image file is too small') < 0) + ############################################################################### # Test error case (inexisting file) -def vrtrawlink_9(): +def test_vrtrawlink_9(): with gdaltest.error_handler(): ds = gdal.Open("""<VRTDataset rasterXSize="1" rasterYSize="1"> @@ -346,17 +292,13 @@ def vrtrawlink_9(): <SourceFilename relativetoVRT="0">i/do/not/exist</SourceFilename> </VRTRasterBand> </VRTDataset>""") - if ds or gdal.GetLastErrorMsg().find('Unable to open') < 0: - print(gdal.GetLastErrorMsg()) - return 'fail' - - return 'success' + assert not (ds or gdal.GetLastErrorMsg().find('Unable to open') < 0) ############################################################################### # Test error case (invalid byte order) -def vrtrawlink_10(): +def test_vrtrawlink_10(): with gdaltest.error_handler(): ds = gdal.Open("""<VRTDataset rasterXSize="1" rasterYSize="1"> @@ -365,17 +307,13 @@ def vrtrawlink_10(): <ByteOrder>invalid</ByteOrder> </VRTRasterBand> </VRTDataset>""") - if ds or gdal.GetLastErrorMsg().find('ByteOrder') < 0: - print(gdal.GetLastErrorMsg()) - return 'fail' - - return 'success' + assert not (ds or gdal.GetLastErrorMsg().find('ByteOrder') < 0) ############################################################################### # Cleanup. -def vrtrawlink_cleanup(): +def test_vrtrawlink_cleanup(): gdaltest.rawlink_ds = None try: @@ -386,26 +324,6 @@ def vrtrawlink_cleanup(): os.remove('tmp/rawlink7.dat') except OSError: pass - return 'success' - - -gdaltest_list = [ - vrtrawlink_1, - vrtrawlink_2, - vrtrawlink_3, - vrtrawlink_4, - vrtrawlink_5, - vrtrawlink_6, - vrtrawlink_7, - vrtrawlink_8, - vrtrawlink_9, - vrtrawlink_10, - vrtrawlink_cleanup] - -if __name__ == '__main__': - - gdaltest.setup_run('vrtrawlink') + - gdaltest.run_tests(gdaltest_list) - sys.exit(gdaltest.summarize()) diff --git a/autotest/gdrivers/vrtwarp.py b/autotest/gdrivers/vrtwarp.py index 120ba806dfa1..05a0cd523966 100755 --- a/autotest/gdrivers/vrtwarp.py +++ b/autotest/gdrivers/vrtwarp.py @@ -30,18 +30,17 @@ import os import shutil -import sys from osgeo import gdal -sys.path.append('../pymod') import gdaltest +import pytest ############################################################################### # Verify reading from simple existing warp definition. -def vrtwarp_1(): +def test_vrtwarp_1(): tst = gdaltest.GDALTest('VRT', 'rgb_warp.vrt', 2, 21504) return tst.testOpen(check_filelist=False) @@ -50,7 +49,7 @@ def vrtwarp_1(): # Create a new VRT warp in the temp directory. -def vrtwarp_2(): +def test_vrtwarp_2(): try: os.remove('tmp/warp.vrt') @@ -65,19 +64,15 @@ def vrtwarp_2(): checksum = gdaltest.vrtwarp_ds.GetRasterBand(2).Checksum() expected = 21504 - if checksum != expected: - gdaltest.post_reason('Got checksum of %d instead of expected %d.' + assert checksum == expected, ('Got checksum of %d instead of expected %d.' % (checksum, expected)) - return 'fail' - - return 'success' ############################################################################### # Force the VRT warp file to be written to disk and close it. Reopen, and # verify checksum. -def vrtwarp_3(): +def test_vrtwarp_3(): gdaltest.vrtwarp_ds.SetDescription('tmp/warp.vrt') gdaltest.vrtwarp_ds = None @@ -90,18 +85,14 @@ def vrtwarp_3(): gdaltest.vrtwarp_ds = None gdal.GetDriverByName('VRT').Delete('tmp/warp.vrt') - if checksum != expected: - gdaltest.post_reason('Got checksum of %d instead of expected %d.' + assert checksum == expected, ('Got checksum of %d instead of expected %d.' % (checksum, expected)) - return 'fail' - - return 'success' ############################################################################### # Test implicit overviews with default source overview level strategy (AUTO) -def vrtwarp_4(): +def test_vrtwarp_4(): src_ds = gdal.Open('../gcore/data/byte.tif') tmp_ds = gdal.GetDriverByName('GTiff').CreateCopy('tmp/vrtwarp_4.tif', src_ds) @@ -116,19 +107,10 @@ def vrtwarp_4(): tmp_ds = None for i in range(3): - if vrtwarp_ds.GetRasterBand(1).GetOverviewCount() != 2: - gdaltest.post_reason('fail') - return 'fail' - if vrtwarp_ds.GetRasterBand(1).Checksum() != cs_main: - print(i) - gdaltest.post_reason('fail') - return 'fail' - if vrtwarp_ds.GetRasterBand(1).GetOverview(0).Checksum() != cs_ov0: - gdaltest.post_reason('fail') - return 'fail' - if vrtwarp_ds.GetRasterBand(1).GetOverview(1).Checksum() != cs_ov1: - gdaltest.post_reason('fail') - return 'fail' + assert vrtwarp_ds.GetRasterBand(1).GetOverviewCount() == 2 + assert vrtwarp_ds.GetRasterBand(1).Checksum() == cs_main, i + assert vrtwarp_ds.GetRasterBand(1).GetOverview(0).Checksum() == cs_ov0 + assert vrtwarp_ds.GetRasterBand(1).GetOverview(1).Checksum() == cs_ov1 if i == 0: vrtwarp_ds.SetDescription('tmp/vrtwarp_4.vrt') vrtwarp_ds = None @@ -151,33 +133,21 @@ def vrtwarp_4(): ds = None vrtwarp_ds = gdal.Open('tmp/vrtwarp_4.vrt') - if vrtwarp_ds.GetRasterBand(1).GetOverviewCount() != 3: - gdaltest.post_reason('fail') - return 'fail' - if vrtwarp_ds.GetRasterBand(1).Checksum() != cs_main: - gdaltest.post_reason('fail') - return 'fail' - if vrtwarp_ds.GetRasterBand(1).GetOverview(0).Checksum() != cs_ov0: - gdaltest.post_reason('fail') - return 'fail' - if vrtwarp_ds.GetRasterBand(1).GetOverview(1).Checksum() != cs_ov1: - gdaltest.post_reason('fail') - return 'fail' - if vrtwarp_ds.GetRasterBand(1).GetOverview(2).Checksum() != expected_cs_ov2: - gdaltest.post_reason('fail') - return 'fail' + assert vrtwarp_ds.GetRasterBand(1).GetOverviewCount() == 3 + assert vrtwarp_ds.GetRasterBand(1).Checksum() == cs_main + assert vrtwarp_ds.GetRasterBand(1).GetOverview(0).Checksum() == cs_ov0 + assert vrtwarp_ds.GetRasterBand(1).GetOverview(1).Checksum() == cs_ov1 + assert vrtwarp_ds.GetRasterBand(1).GetOverview(2).Checksum() == expected_cs_ov2 vrtwarp_ds = None gdal.Unlink('tmp/vrtwarp_4.vrt') gdal.Unlink('tmp/vrtwarp_4.tif') - return 'success' - ############################################################################### # Test implicit overviews with selection of the upper source overview level -def vrtwarp_5(): +def test_vrtwarp_5(): src_ds = gdal.Open('../gcore/data/byte.tif') tmp_ds = gdal.GetDriverByName('GTiff').CreateCopy('tmp/vrtwarp_5.tif', src_ds) @@ -202,29 +172,19 @@ def vrtwarp_5(): vrtwarp_ds = gdal.AutoCreateWarpedVRT(tmp_ds) vrtwarp_ds.SetMetadataItem('SrcOvrLevel', 'AUTO-1') tmp_ds = None - if vrtwarp_ds.GetRasterBand(1).GetOverviewCount() != 2: - gdaltest.post_reason('fail') - return 'fail' - if vrtwarp_ds.GetRasterBand(1).Checksum() != cs_main: - gdaltest.post_reason('fail') - return 'fail' - if vrtwarp_ds.GetRasterBand(1).GetOverview(0).Checksum() != expected_cs_ov0: - gdaltest.post_reason('fail') - return 'fail' - if vrtwarp_ds.GetRasterBand(1).GetOverview(1).Checksum() != expected_cs_ov1: - gdaltest.post_reason('fail') - return 'fail' + assert vrtwarp_ds.GetRasterBand(1).GetOverviewCount() == 2 + assert vrtwarp_ds.GetRasterBand(1).Checksum() == cs_main + assert vrtwarp_ds.GetRasterBand(1).GetOverview(0).Checksum() == expected_cs_ov0 + assert vrtwarp_ds.GetRasterBand(1).GetOverview(1).Checksum() == expected_cs_ov1 vrtwarp_ds = None gdal.Unlink('tmp/vrtwarp_5.tif') - return 'success' - ############################################################################### # Test implicit overviews with GCP -def vrtwarp_6(): +def test_vrtwarp_6(): src_ds = gdal.Open('../gcore/data/byte.tif') tmp_ds = gdal.GetDriverByName('GTiff').CreateCopy('tmp/vrtwarp_6.tif', src_ds) @@ -258,29 +218,19 @@ def vrtwarp_6(): vrtwarp_ds = gdal.Open('tmp/vrtwarp_6.vrt') - if vrtwarp_ds.GetRasterBand(1).GetOverviewCount() != 2: - gdaltest.post_reason('fail') - return 'fail' - if vrtwarp_ds.GetRasterBand(1).Checksum() != cs_main: - gdaltest.post_reason('fail') - return 'fail' - if vrtwarp_ds.GetRasterBand(1).GetOverview(0).Checksum() != cs_ov0: - gdaltest.post_reason('fail') - return 'fail' - if vrtwarp_ds.GetRasterBand(1).GetOverview(1).Checksum() != cs_ov1: - gdaltest.post_reason('fail') - return 'fail' + assert vrtwarp_ds.GetRasterBand(1).GetOverviewCount() == 2 + assert vrtwarp_ds.GetRasterBand(1).Checksum() == cs_main + assert vrtwarp_ds.GetRasterBand(1).GetOverview(0).Checksum() == cs_ov0 + assert vrtwarp_ds.GetRasterBand(1).GetOverview(1).Checksum() == cs_ov1 gdal.Unlink('tmp/vrtwarp_6.vrt') gdal.Unlink('tmp/vrtwarp_6.tif') - return 'success' - ############################################################################### # Test implicit overviews with GCP (TPS) -def vrtwarp_7(): +def test_vrtwarp_7(): src_ds = gdal.Open('../gcore/data/byte.tif') tmp_ds = gdal.GetDriverByName('GTiff').CreateCopy('tmp/vrtwarp_7.tif', src_ds) @@ -309,30 +259,20 @@ def vrtwarp_7(): tmp_ds = None vrtwarp_ds = gdal.Warp('tmp/vrtwarp_7.vrt', 'tmp/vrtwarp_7.tif', options='-overwrite -of VRT -tps') - if vrtwarp_ds.GetRasterBand(1).GetOverviewCount() != 2: - gdaltest.post_reason('fail') - return 'fail' - if vrtwarp_ds.GetRasterBand(1).Checksum() != cs_main: - print(cs_main) - return 'fail' - if vrtwarp_ds.GetRasterBand(1).GetOverview(0).Checksum() != cs_ov0: - gdaltest.post_reason('fail') - return 'fail' - if vrtwarp_ds.GetRasterBand(1).GetOverview(1).Checksum() != cs_ov1: - gdaltest.post_reason('fail') - return 'fail' + assert vrtwarp_ds.GetRasterBand(1).GetOverviewCount() == 2 + assert vrtwarp_ds.GetRasterBand(1).Checksum() == cs_main + assert vrtwarp_ds.GetRasterBand(1).GetOverview(0).Checksum() == cs_ov0 + assert vrtwarp_ds.GetRasterBand(1).GetOverview(1).Checksum() == cs_ov1 vrtwarp_ds = None gdal.Unlink('tmp/vrtwarp_7.vrt') gdal.Unlink('tmp/vrtwarp_7.tif') - return 'success' - ############################################################################### # Test implicit overviews with RPC -def vrtwarp_8(): +def test_vrtwarp_8(): shutil.copy('../gcore/data/byte.tif', 'tmp/vrtwarp_8.tif') shutil.copy('../gcore/data/test_rpc.txt', 'tmp/vrtwarp_8_rpc.txt') @@ -345,31 +285,22 @@ def vrtwarp_8(): ds = None vrtwarp_ds = gdal.Warp('tmp/vrtwarp_8.vrt', 'tmp/vrtwarp_8.tif', options='-overwrite -of VRT -rpc') - if vrtwarp_ds.GetRasterBand(1).GetOverviewCount() != 1: - gdaltest.post_reason('fail') - return 'fail' - if vrtwarp_ds.GetRasterBand(1).Checksum() != expected_cs_main: - gdaltest.post_reason('fail') - return 'fail' + assert vrtwarp_ds.GetRasterBand(1).GetOverviewCount() == 1 + assert vrtwarp_ds.GetRasterBand(1).Checksum() == expected_cs_main if vrtwarp_ds.GetRasterBand(1).GetOverview(0).Checksum() != 1214: - gdaltest.post_reason('fail') print(vrtwarp_ds.GetRasterBand(1).GetOverview(0).XSize) - print(vrtwarp_ds.GetRasterBand(1).GetOverview(0).YSize) - print(vrtwarp_ds.GetRasterBand(1).GetOverview(0).Checksum()) - return 'fail' + pytest.fail(vrtwarp_ds.GetRasterBand(1).GetOverview(0).YSize) vrtwarp_ds = None gdal.Unlink('tmp/vrtwarp_8.vrt') gdal.Unlink('tmp/vrtwarp_8.tif') gdal.Unlink('tmp/vrtwarp_8_rpc.txt') - return 'success' - ############################################################################### # Test implicit overviews with GEOLOCATION -def vrtwarp_9(): +def test_vrtwarp_9(): shutil.copy('../gcore/data/sstgeo.tif', 'tmp/sstgeo.tif') @@ -408,18 +339,11 @@ def vrtwarp_9(): ds = None vrtwarp_ds = gdal.Warp('tmp/vrtwarp_9.vrt', 'tmp/sstgeo.vrt', options='-overwrite -of VRT -geoloc') - if vrtwarp_ds.GetRasterBand(1).GetOverviewCount() != 1: - gdaltest.post_reason('fail') - return 'fail' - if vrtwarp_ds.GetRasterBand(1).Checksum() != expected_cs_main: - gdaltest.post_reason('fail') - return 'fail' + assert vrtwarp_ds.GetRasterBand(1).GetOverviewCount() == 1 + assert vrtwarp_ds.GetRasterBand(1).Checksum() == expected_cs_main if vrtwarp_ds.GetRasterBand(1).GetOverview(0).Checksum() != 63859: - gdaltest.post_reason('fail') print(vrtwarp_ds.GetRasterBand(1).GetOverview(0).XSize) - print(vrtwarp_ds.GetRasterBand(1).GetOverview(0).YSize) - print(vrtwarp_ds.GetRasterBand(1).GetOverview(0).Checksum()) - return 'fail' + pytest.fail(vrtwarp_ds.GetRasterBand(1).GetOverview(0).YSize) vrtwarp_ds = None gdal.Unlink('tmp/vrtwarp_9.vrt') @@ -427,13 +351,11 @@ def vrtwarp_9(): gdal.Unlink('tmp/sstgeo.vrt.ovr') gdal.Unlink('tmp/sstgeo.tif') - return 'success' - ############################################################################### # Test implicit overviews with selection of the full resolution level -def vrtwarp_10(): +def test_vrtwarp_10(): src_ds = gdal.Open('../gcore/data/byte.tif') tmp_ds = gdal.GetDriverByName('GTiff').CreateCopy('tmp/vrtwarp_10.tif', src_ds) @@ -457,29 +379,19 @@ def vrtwarp_10(): vrtwarp_ds = gdal.AutoCreateWarpedVRT(tmp_ds) vrtwarp_ds.SetMetadataItem('SrcOvrLevel', 'NONE') tmp_ds = None - if vrtwarp_ds.GetRasterBand(1).GetOverviewCount() != 2: - gdaltest.post_reason('fail') - return 'fail' - if vrtwarp_ds.GetRasterBand(1).Checksum() != cs_main: - gdaltest.post_reason('fail') - return 'fail' - if vrtwarp_ds.GetRasterBand(1).GetOverview(0).Checksum() != expected_cs_ov0: - gdaltest.post_reason('fail') - return 'fail' - if vrtwarp_ds.GetRasterBand(1).GetOverview(1).Checksum() != expected_cs_ov1: - gdaltest.post_reason('fail') - return 'fail' + assert vrtwarp_ds.GetRasterBand(1).GetOverviewCount() == 2 + assert vrtwarp_ds.GetRasterBand(1).Checksum() == cs_main + assert vrtwarp_ds.GetRasterBand(1).GetOverview(0).Checksum() == expected_cs_ov0 + assert vrtwarp_ds.GetRasterBand(1).GetOverview(1).Checksum() == expected_cs_ov1 vrtwarp_ds = None gdal.Unlink('tmp/vrtwarp_10.tif') - return 'success' - ############################################################################### # Test implicit overviews with dest alpha band (#6081) -def vrtwarp_11(): +def test_vrtwarp_11(): ds = gdal.Open('data/bug6581.vrt') cs1 = ds.GetRasterBand(1).Checksum() @@ -487,53 +399,21 @@ def vrtwarp_11(): cs3 = ds.GetRasterBand(3).Checksum() ds = None - if cs1 != 22122 or cs2 != 56685 or cs3 != 22122: - gdaltest.post_reason('fail') - print(cs1) - print(cs2) - print(cs3) - return 'fail' - - return 'success' + assert cs1 == 22122 and cs2 == 56685 and cs3 == 22122 ############################################################################### # Test reading a regular VRT whose source is a warped VRT inlined -def vrtwarp_read_vrt_of_warped_vrt(): +def test_vrtwarp_read_vrt_of_warped_vrt(): ds = gdal.Open('data/vrt_of_warped_vrt.vrt') cs = ds.GetRasterBand(1).Checksum() - if cs != 4672: - print(cs) - return 'fail' - - return 'success' + assert cs == 4672 ############################################################################### # Test different nodata values on bands and partial blocks (#6581) -gdaltest_list = [ - vrtwarp_1, - vrtwarp_2, - vrtwarp_3, - vrtwarp_4, - vrtwarp_5, - vrtwarp_6, - vrtwarp_7, - vrtwarp_8, - vrtwarp_9, - vrtwarp_10, - vrtwarp_11, - vrtwarp_read_vrt_of_warped_vrt -] - - -if __name__ == '__main__': - - gdaltest.setup_run('vrtwarp') - gdaltest.run_tests(gdaltest_list) - sys.exit(gdaltest.summarize()) diff --git a/autotest/gdrivers/wcs.py b/autotest/gdrivers/wcs.py index 7fcd40cb1f16..8962a435f833 100755 --- a/autotest/gdrivers/wcs.py +++ b/autotest/gdrivers/wcs.py @@ -31,20 +31,22 @@ ############################################################################### import os -import sys import numbers import re import shutil -import urlparse + +try: + import urllib.parse as urlparse +except ImportError: + import urlparse try: from BaseHTTPServer import BaseHTTPRequestHandler except ImportError: from http.server import BaseHTTPRequestHandler -from osgeo import gdal - -sys.path.append('../pymod') +import pytest +from osgeo import gdal import webserver import gdaltest @@ -52,7 +54,7 @@ # Verify we have the driver. -def wcs_1(): +def test_wcs_1(): # Disable wcs tests till we have a more reliable test server. gdaltest.wcs_drv = gdal.GetDriverByName('WCS') @@ -66,9 +68,8 @@ def wcs_1(): gdaltest.wcs_ds = None if gdaltest.wcs_drv is None: - return 'skip' - return 'success' - + pytest.skip() + ############################################################################### # Open the GeoServer WCS service. @@ -76,7 +77,7 @@ def wcs_1(): def wcs_2(): if gdaltest.wcs_drv is None: - return 'skip' + pytest.skip() # first, copy to tmp directory. open('tmp/geoserver.wcs', 'w').write(open('data/geoserver.wcs').read()) @@ -85,66 +86,45 @@ def wcs_2(): gdaltest.wcs_ds = gdal.Open('tmp/geoserver.wcs') if gdaltest.wcs_ds is not None: - return 'success' - gdaltest.post_reason('open failed.') - return 'fail' + return + pytest.fail('open failed.') ############################################################################### # Check various things about the configuration. -def wcs_3(): +def test_wcs_3(): if gdaltest.wcs_drv is None or gdaltest.wcs_ds is None: - return 'skip' + pytest.skip() - if gdaltest.wcs_ds.RasterXSize != 983 \ - or gdaltest.wcs_ds.RasterYSize != 598 \ - or gdaltest.wcs_ds.RasterCount != 3: - gdaltest.post_reason('wrong size or bands') - print(gdaltest.wcs_ds.RasterXSize) - print(gdaltest.wcs_ds.RasterYSize) - print(gdaltest.wcs_ds.RasterCount) - return 'fail' + assert gdaltest.wcs_ds.RasterXSize == 983 and gdaltest.wcs_ds.RasterYSize == 598 and gdaltest.wcs_ds.RasterCount == 3, \ + 'wrong size or bands' wkt = gdaltest.wcs_ds.GetProjectionRef() - if wkt[:14] != 'GEOGCS["WGS 84': - gdaltest.post_reason('Got wrong SRS: ' + wkt) - return 'fail' + assert wkt[:14] == 'GEOGCS["WGS 84', ('Got wrong SRS: ' + wkt) gt = gdaltest.wcs_ds.GetGeoTransform() expected_gt = (-130.85167999999999, 0.070036907426246159, 0.0, 54.114100000000001, 0.0, -0.055867725752508368) for i in range(6): - if abs(gt[i] - expected_gt[i]) > 0.00001: - gdaltest.post_reason('wrong geotransform') - print(gt) - return 'fail' + assert abs(gt[i] - expected_gt[i]) <= 0.00001, 'wrong geotransform' - if gdaltest.wcs_ds.GetRasterBand(1).GetOverviewCount() < 1: - gdaltest.post_reason('no overviews!') - return 'fail' + assert gdaltest.wcs_ds.GetRasterBand(1).GetOverviewCount() >= 1, 'no overviews!' - if gdaltest.wcs_ds.GetRasterBand(1).DataType != gdal.GDT_Byte: - gdaltest.post_reason('wrong band data type') - return 'fail' - - return 'success' + assert gdaltest.wcs_ds.GetRasterBand(1).DataType == gdal.GDT_Byte, \ + 'wrong band data type' ############################################################################### # Check checksum -def wcs_4(): +def test_wcs_4(): if gdaltest.wcs_drv is None or gdaltest.wcs_ds is None: - return 'skip' + pytest.skip() cs = gdaltest.wcs_ds.GetRasterBand(1).Checksum() - if cs != 58765: - gdaltest.post_reason('Wrong checksum: ' + str(cs)) - return 'fail' - - return 'success' + assert cs == 58765, ('Wrong checksum: ' + str(cs)) ############################################################################### # Open the service using XML as filename. @@ -153,7 +133,7 @@ def wcs_4(): def wcs_5(): if gdaltest.wcs_drv is None: - return 'skip' + pytest.skip() fn = """<WCS_GDAL> <ServiceURL>http://demo.opengeo.org/geoserver/wcs?</ServiceURL> @@ -163,22 +143,12 @@ def wcs_5(): ds = gdal.Open(fn) - if ds is None: - gdaltest.post_reason('open failed.') - return 'fail' + assert ds is not None, 'open failed.' - if ds.RasterXSize != 983 \ - or ds.RasterYSize != 598 \ - or ds.RasterCount != 3: - gdaltest.post_reason('wrong size or bands') - print(ds.RasterXSize) - print(ds.RasterYSize) - print(ds.RasterCount) - return 'fail' + assert ds.RasterXSize == 983 and ds.RasterYSize == 598 and ds.RasterCount == 3, \ + 'wrong size or bands' ds = None - - return 'success' ############################################################################### # Open the srtm plus service. @@ -186,7 +156,7 @@ def wcs_5(): def old_wcs_2(): if gdaltest.wcs_drv is None: - return 'skip' + pytest.skip() # first, copy to tmp directory. open('tmp/srtmplus.wcs', 'w').write(open('data/srtmplus.wcs').read()) @@ -195,9 +165,8 @@ def old_wcs_2(): gdaltest.wcs_ds = gdal.Open('tmp/srtmplus.wcs') if gdaltest.wcs_ds is not None: - return 'success' - gdaltest.post_reason('open failed.') - return 'fail' + return + pytest.fail('open failed.') ############################################################################### # Check various things about the configuration. @@ -206,39 +175,22 @@ def old_wcs_2(): def old_wcs_3(): if gdaltest.wcs_drv is None or gdaltest.wcs_ds is None: - return 'skip' + pytest.skip() - if gdaltest.wcs_ds.RasterXSize != 43200 \ - or gdaltest.wcs_ds.RasterYSize != 21600 \ - or gdaltest.wcs_ds.RasterCount != 1: - gdaltest.post_reason('wrong size or bands') - return 'fail' + assert gdaltest.wcs_ds.RasterXSize == 43200 and gdaltest.wcs_ds.RasterYSize == 21600 and gdaltest.wcs_ds.RasterCount == 1, \ + 'wrong size or bands' wkt = gdaltest.wcs_ds.GetProjectionRef() - if wkt[:12] != 'GEOGCS["NAD8': - gdaltest.post_reason('Got wrong SRS: ' + wkt) - return 'fail' + assert wkt[:12] == 'GEOGCS["NAD8', ('Got wrong SRS: ' + wkt) gt = gdaltest.wcs_ds.GetGeoTransform() - if abs(gt[0] - -180.0041667) > 0.00001 \ - or abs(gt[3] - 90.004167) > 0.00001 \ - or abs(gt[1] - 0.00833333) > 0.00001 \ - or abs(gt[2] - 0) > 0.00001 \ - or abs(gt[5] - -0.00833333) > 0.00001 \ - or abs(gt[4] - 0) > 0.00001: - gdaltest.post_reason('wrong geotransform') - print(gt) - return 'fail' - - if gdaltest.wcs_ds.GetRasterBand(1).GetOverviewCount() < 1: - gdaltest.post_reason('no overviews!') - return 'fail' - - if gdaltest.wcs_ds.GetRasterBand(1).DataType < gdal.GDT_Int16: - gdaltest.post_reason('wrong band data type') - return 'fail' - - return 'success' + assert abs(gt[0] - -180.0041667) <= 0.00001 and abs(gt[3] - 90.004167) <= 0.00001 and abs(gt[1] - 0.00833333) <= 0.00001 and abs(gt[2] - 0) <= 0.00001 and abs(gt[5] - -0.00833333) <= 0.00001 and abs(gt[4] - 0) <= 0.00001, \ + 'wrong geotransform' + + assert gdaltest.wcs_ds.GetRasterBand(1).GetOverviewCount() >= 1, 'no overviews!' + + assert gdaltest.wcs_ds.GetRasterBand(1).DataType >= gdal.GDT_Int16, \ + 'wrong band data type' ############################################################################### # Check checksum for a small region. @@ -247,14 +199,10 @@ def old_wcs_3(): def old_wcs_4(): if gdaltest.wcs_drv is None or gdaltest.wcs_ds is None: - return 'skip' + pytest.skip() cs = gdaltest.wcs_ds.GetRasterBand(1).Checksum(0, 0, 100, 100) - if cs != 10469: - gdaltest.post_reason('Wrong checksum: ' + str(cs)) - return 'fail' - - return 'success' + assert cs == 10469, ('Wrong checksum: ' + str(cs)) ############################################################################### # Open the srtm plus service using XML as filename. @@ -263,26 +211,19 @@ def old_wcs_4(): def old_wcs_5(): if gdaltest.wcs_drv is None: - return 'skip' + pytest.skip() fn = '<WCS_GDAL><ServiceURL>http://geodata.telascience.org/cgi-bin/mapserv_dem?</ServiceURL><CoverageName>srtmplus_raw</CoverageName><Timeout>75</Timeout></WCS_GDAL>' ds = gdal.Open(fn) - if ds is None: - gdaltest.post_reason('open failed.') - return 'fail' + assert ds is not None, 'open failed.' - if ds.RasterXSize != 43200 \ - or ds.RasterYSize != 21600 \ - or ds.RasterCount != 1: - gdaltest.post_reason('wrong size or bands') - return 'fail' + assert ds.RasterXSize == 43200 and ds.RasterYSize == 21600 and ds.RasterCount == 1, \ + 'wrong size or bands' ds = None - return 'success' - ############################################################################### # utilities @@ -292,9 +233,9 @@ def read_urls(): retval = {} fname = 'data/wcs/urls' f = open(fname, 'rb') - content = f.read() + text = f.read().decode('utf-8') f.close() - for line in content.splitlines(): + for line in text.splitlines(): items = line.split() if items[1].endswith('2'): items[1] = items[1][:-1] @@ -479,10 +420,10 @@ def setupFct(): ############################################################################### -def wcs_6(): +def test_wcs_6(): driver = gdal.GetDriverByName('WCS') if driver is None: - return 'skip' + pytest.skip() # Generating various URLs from the driver and comparing them to ones # that have worked. first_call = True @@ -566,7 +507,7 @@ def wcs_6(): print(server + ' ' + version + ' non_scaled skipped (no response file)') webserver.server_stop(process, port) - return 'success' if wcs_6_ok else 'fail' + assert wcs_6_ok ############################################################################### @@ -578,7 +519,7 @@ def wcs_6(): ############################################################################### -def wcs_cleanup(): +def test_wcs_cleanup(): gdaltest.wcs_drv = None gdaltest.wcs_ds = None @@ -593,23 +534,7 @@ def wcs_cleanup(): except OSError: pass - return 'success' - - -gdaltest_list = [ - wcs_1, - # wcs_2, #FIXME: re-enable after adapting test - wcs_3, - wcs_4, - # wcs_5, #FIXME: re-enable after adapting test - wcs_6, - wcs_cleanup] - - -if __name__ == '__main__': + - gdaltest.setup_run('wcs') - gdaltest.run_tests(gdaltest_list) - sys.exit(gdaltest.summarize()) diff --git a/autotest/gdrivers/webp.py b/autotest/gdrivers/webp.py index e1d7c9179f75..135c901128f5 100755 --- a/autotest/gdrivers/webp.py +++ b/autotest/gdrivers/webp.py @@ -29,51 +29,45 @@ # DEALINGS IN THE SOFTWARE. ############################################################################### -import sys from osgeo import gdal -sys.path.append('../pymod') import gdaltest +import pytest ############################################################################### # Test if WEBP driver is present -def webp_1(): +def test_webp_1(): gdaltest.webp_drv = gdal.GetDriverByName('WEBP') if gdaltest.webp_drv is None: - return 'skip' - - return 'success' + pytest.skip() + ############################################################################### # Open() test -def webp_2(): +def test_webp_2(): if gdaltest.webp_drv is None: - return 'skip' + pytest.skip() ds = gdal.Open('data/rgbsmall.webp') cs = ds.GetRasterBand(1).Checksum() - if cs != 21464 and cs != 21450 and cs != 21459: - gdaltest.post_reason('did not get expected checksum on band 1') - print(cs) - return 'fail' - - return 'success' + assert cs == 21464 or cs == 21450 or cs == 21459, \ + 'did not get expected checksum on band 1' ############################################################################### # CreateCopy() test -def webp_3(): +def test_webp_3(): if gdaltest.webp_drv is None: - return 'skip' + pytest.skip() src_ds = gdal.Open('data/rgbsmall.tif') out_ds = gdaltest.webp_drv.CreateCopy('/vsimem/webp_3.webp', src_ds, options=['QUALITY=80']) @@ -84,25 +78,21 @@ def webp_3(): gdal.Unlink('/vsimem/webp_3.webp.aux.xml') # 21502 is for libwebp 0.3.0 - if cs1 != 21464 and cs1 != 21502 and cs1 != 21695 and cs1 != 21700: - gdaltest.post_reason('did not get expected checksum on band 1') - print(cs1) - return 'fail' - - return 'success' + assert cs1 == 21464 or cs1 == 21502 or cs1 == 21695 or cs1 == 21700, \ + 'did not get expected checksum on band 1' ############################################################################### # CreateCopy() on RGBA -def webp_4(): +def test_webp_4(): if gdaltest.webp_drv is None: - return 'skip' + pytest.skip() md = gdaltest.webp_drv.GetMetadata() if md['DMD_CREATIONOPTIONLIST'].find('LOSSLESS') == -1: - return 'skip' + pytest.skip() src_ds = gdal.Open('../gcore/data/stefan_full_rgba.tif') out_ds = gdaltest.webp_drv.CreateCopy('/vsimem/webp_4.webp', src_ds) @@ -113,30 +103,23 @@ def webp_4(): gdal.Unlink('/vsimem/webp_4.webp') # 22849 is for libwebp 0.3.0 - if cs1 not in (22001, 22849, 34422, 36652, 36658, 45319): - gdaltest.post_reason('did not get expected checksum on band 1') - print(cs1) - return 'fail' - - if cs4 != 10807: # lossless alpha - gdaltest.post_reason('did not get expected checksum on band 4') - print(cs4) - return 'fail' + assert cs1 in (22001, 22849, 34422, 36652, 36658, 45319), \ + 'did not get expected checksum on band 1' - return 'success' + assert cs4 == 10807, 'did not get expected checksum on band 4' ############################################################################### # CreateCopy() on RGBA with lossless compression -def webp_5(): +def test_webp_5(): if gdaltest.webp_drv is None: - return 'skip' + pytest.skip() md = gdaltest.webp_drv.GetMetadata() if md['DMD_CREATIONOPTIONLIST'].find('LOSSLESS') == -1: - return 'skip' + pytest.skip() src_ds = gdal.Open('../gcore/data/stefan_full_rgba.tif') out_ds = gdaltest.webp_drv.CreateCopy('/vsimem/webp_5.webp', src_ds, options=['LOSSLESS=YES']) @@ -146,30 +129,10 @@ def webp_5(): out_ds = None gdal.Unlink('/vsimem/webp_5.webp') - if cs1 != 12603 and cs1 != 18536 and cs1 != 14800: - gdaltest.post_reason('did not get expected checksum on band 1') - print(cs1) - return 'fail' - - if cs4 != 10807: - gdaltest.post_reason('did not get expected checksum on band 4') - print(cs4) - return 'fail' - - return 'success' - - -gdaltest_list = [ - webp_1, - webp_2, - webp_3, - webp_4, - webp_5] + assert cs1 == 12603 or cs1 == 18536 or cs1 == 14800, \ + 'did not get expected checksum on band 1' -if __name__ == '__main__': + assert cs4 == 10807, 'did not get expected checksum on band 4' - gdaltest.setup_run('webp') - gdaltest.run_tests(gdaltest_list) - sys.exit(gdaltest.summarize()) diff --git a/autotest/gdrivers/wms.py b/autotest/gdrivers/wms.py index 0eac2ae7c629..3e635ed4ec6b 100755 --- a/autotest/gdrivers/wms.py +++ b/autotest/gdrivers/wms.py @@ -31,27 +31,25 @@ ############################################################################### import os -import sys import shutil from time import sleep import hashlib from osgeo import gdal -sys.path.append('../pymod') import gdaltest +import pytest ############################################################################### # Verify we have the driver. -def wms_1(): +def test_wms_1(): gdaltest.wms_drv = gdal.GetDriverByName('WMS') if gdaltest.wms_drv is None: - return 'skip' - return 'success' - + pytest.skip() + ############################################################################### # Open the WMS dataset @@ -59,7 +57,7 @@ def wms_1(): def wms_2(): if gdaltest.wms_drv is None: - return 'skip' + pytest.skip() # NOTE - mloskot: # This is a dirty hack checking if remote WMS service is online. @@ -70,14 +68,13 @@ def wms_2(): gdaltest.wms_ds = None if not gdaltest.wms_srv1_ok: - return 'skip' + pytest.skip() gdaltest.wms_ds = gdal.Open('data/pop_wms.xml') if gdaltest.wms_ds is not None: - return 'success' - gdaltest.post_reason('open failed.') - return 'fail' + return + pytest.fail('open failed.') ############################################################################### # Check various things about the configuration. @@ -86,42 +83,25 @@ def wms_2(): def wms_3(): if gdaltest.wms_drv is None or gdaltest.wms_ds is None: - return 'skip' + pytest.skip() if not gdaltest.wms_srv1_ok: - return 'skip' + pytest.skip() - if gdaltest.wms_ds.RasterXSize != 36000 \ - or gdaltest.wms_ds.RasterYSize != 14500 \ - or gdaltest.wms_ds.RasterCount != 3: - gdaltest.post_reason('wrong size or bands') - return 'fail' + assert gdaltest.wms_ds.RasterXSize == 36000 and gdaltest.wms_ds.RasterYSize == 14500 and gdaltest.wms_ds.RasterCount == 3, \ + 'wrong size or bands' wkt = gdaltest.wms_ds.GetProjectionRef() - if wkt[:14] != 'GEOGCS["WGS 84': - gdaltest.post_reason('Got wrong SRS: ' + wkt) - return 'fail' + assert wkt[:14] == 'GEOGCS["WGS 84', ('Got wrong SRS: ' + wkt) gt = gdaltest.wms_ds.GetGeoTransform() - if abs(gt[0] - -180) > 0.00001 \ - or abs(gt[3] - 85) > 0.00001 \ - or abs(gt[1] - 0.01) > 0.00001 \ - or abs(gt[2] - 0) > 0.00001 \ - or abs(gt[5] - -0.01) > 0.00001 \ - or abs(gt[4] - 0) > 0.00001: - gdaltest.post_reason('wrong geotransform') - print(gt) - return 'fail' - - if gdaltest.wms_ds.GetRasterBand(1).GetOverviewCount() < 1: - gdaltest.post_reason('no overviews!') - return 'fail' - - if gdaltest.wms_ds.GetRasterBand(1).DataType < gdal.GDT_Byte: - gdaltest.post_reason('wrong band data type') - return 'fail' - - return 'success' + assert abs(gt[0] - -180) <= 0.00001 and abs(gt[3] - 85) <= 0.00001 and abs(gt[1] - 0.01) <= 0.00001 and abs(gt[2] - 0) <= 0.00001 and abs(gt[5] - -0.01) <= 0.00001 and abs(gt[4] - 0) <= 0.00001, \ + 'wrong geotransform' + + assert gdaltest.wms_ds.GetRasterBand(1).GetOverviewCount() >= 1, 'no overviews!' + + assert gdaltest.wms_ds.GetRasterBand(1).DataType >= gdal.GDT_Byte, \ + 'wrong band data type' ############################################################################### # Check checksum for a small region. @@ -130,10 +110,10 @@ def wms_3(): def wms_4(): if gdaltest.wms_drv is None or gdaltest.wms_ds is None: - return 'skip' + pytest.skip() if not gdaltest.wms_srv1_ok: - return 'skip' + pytest.skip() gdal.SetConfigOption('CPL_ACCUM_ERROR_MSG', 'ON') gdal.PushErrorHandler('CPLQuietErrorHandler') @@ -146,23 +126,18 @@ def wms_4(): gdal.ErrorReset() if msg is not None and msg.find('Service denied due to system overload') != -1: - print(msg) - return 'skip' + pytest.skip(msg) - if cs != 57182: - gdaltest.post_reason('Wrong checksum: ' + str(cs)) - return 'fail' - - return 'success' + assert cs == 57182, ('Wrong checksum: ' + str(cs)) ############################################################################### # Open the WMS service using XML as filename. -def wms_5(): +def test_wms_5(): if gdaltest.wms_drv is None: - return 'skip' + pytest.skip() # We don't need to check if the remote service is online as we # don't need a connection for this test @@ -171,28 +146,21 @@ def wms_5(): ds = gdal.Open(fn) - if ds is None: - gdaltest.post_reason('open failed.') - return 'fail' + assert ds is not None, 'open failed.' - if ds.RasterXSize != 2666666 \ - or ds.RasterYSize != 1333333 \ - or ds.RasterCount != 3: - gdaltest.post_reason('wrong size or bands') - return 'fail' + assert ds.RasterXSize == 2666666 and ds.RasterYSize == 1333333 and ds.RasterCount == 3, \ + 'wrong size or bands' ds = None - return 'success' - ############################################################################### # Test TileService -def wms_6(): +def test_wms_6(): if gdaltest.wms_drv is None: - return 'skip' + pytest.skip() # We don't need to check if the remote service is online as we # don't need a connection for this test @@ -201,33 +169,26 @@ def wms_6(): ds = gdal.Open(fn) - if ds is None: - gdaltest.post_reason('open failed.') - return 'fail' + assert ds is not None, 'open failed.' - if ds.RasterXSize != 268435456 \ - or ds.RasterYSize != 134217728 \ - or ds.RasterCount != 3: - gdaltest.post_reason('wrong size or bands') - return 'fail' + assert ds.RasterXSize == 268435456 and ds.RasterYSize == 134217728 and ds.RasterCount == 3, \ + 'wrong size or bands' ds = None - return 'success' - ############################################################################### # Test TMS -def wms_7(): +def test_wms_7(): if gdaltest.wms_drv is None: - return 'skip' + pytest.skip() srv = 'http://tilecache.osgeo.org/wms-c/Basic.py' gdaltest.metacarta_tms = False if gdaltest.gdalurlopen(srv) is None: - return 'skip' + pytest.skip() gdaltest.metacarta_tms = True tms = """<GDAL_WMS> @@ -253,38 +214,25 @@ def wms_7(): ds = gdal.Open(tms) - if ds is None: - gdaltest.post_reason('open failed.') - return 'fail' - - if ds.RasterXSize != 268435456 \ - or ds.RasterYSize != 134217728 \ - or ds.RasterCount != 3: - gdaltest.post_reason('wrong size or bands') - print(ds.RasterXSize) - print(ds.RasterYSize) - return 'fail' - - if ds.GetRasterBand(1).GetOverview(18).XSize != 512 \ - or ds.GetRasterBand(1).GetOverview(18).YSize != 256: - print(ds.GetRasterBand(1).GetOverview(18).XSize) - print(ds.GetRasterBand(1).GetOverview(18).YSize) - return 'fail' + assert ds is not None, 'open failed.' + + assert ds.RasterXSize == 268435456 and ds.RasterYSize == 134217728 and ds.RasterCount == 3, \ + 'wrong size or bands' + + assert ds.GetRasterBand(1).GetOverview(18).XSize == 512 and ds.GetRasterBand(1).GetOverview(18).YSize == 256 ds.GetRasterBand(1).GetOverview(18).ReadRaster(0, 0, 512, 256) ds = None - return 'success' - ############################################################################### # Test TMS with cache -def wms_8(): +def test_wms_8(): if gdaltest.wms_drv is None: - return 'skip' + pytest.skip() # server_url = 'http://tilecache.osgeo.org/wms-c/Basic.py' # wmstms_version = '/1.0.0/basic' @@ -383,7 +331,7 @@ def wms_8(): </GDAL_WMS>""" % server_url_mask if gdaltest.gdalurlopen(server_url) is None: - return 'skip' + pytest.skip() try: shutil.rmtree('tmp/gdalwmscache') @@ -392,15 +340,11 @@ def wms_8(): ds = gdal.Open(tms) - if ds is None: - gdaltest.post_reason('open failed.') - return 'fail' + assert ds is not None, 'open failed.' # Check cache metadata item cache_path = ds.GetMetadataItem("CACHE_PATH") - if not cache_path: - gdaltest.post_reason('did not get expected cache path metadata item') - return 'fail' + assert cache_path, 'did not get expected cache path metadata item' cache_subfolder = hashlib.md5(server_url_mask.encode('utf-8')).hexdigest() @@ -408,7 +352,7 @@ def wms_8(): data = ds.GetRasterBand(1).GetOverview(ovr_upper_level).ReadRaster(0, 0, 512, 512) if gdal.GetLastErrorMsg() != '': if gdaltest.gdalurlopen(server_url + zero_tile) is None: - return 'skip' + pytest.skip() ds = None @@ -425,17 +369,14 @@ def wms_8(): try: os.stat(expected_file) except OSError: - gdaltest.post_reason('%s should exist' % expected_file) - return 'fail' + pytest.fail('%s should exist' % expected_file) # Now, we should read from the cache ds = gdal.Open(tms) cached_data = ds.GetRasterBand(1).GetOverview(ovr_upper_level).ReadRaster(0, 0, 512, 512) ds = None - if data != cached_data: - gdaltest.post_reason('data != cached_data') - return 'fail' + assert data == cached_data, 'data != cached_data' # Replace the cache with fake data for expected_file in expected_files: @@ -451,9 +392,7 @@ def wms_8(): ds = gdal.Open(tms) cs = ds.GetRasterBand(1).GetOverview(ovr_upper_level).Checksum() ds = None - if cs != 0: - gdaltest.post_reason('cs != 0') - return 'fail' + assert cs == 0, 'cs != 0' # Test with GDAL_DEFAULT_WMS_CACHE_PATH # Now, we should read from the cache @@ -462,9 +401,7 @@ def wms_8(): cs = ds.GetRasterBand(1).GetOverview(ovr_upper_level).Checksum() ds = None gdal.SetConfigOption("GDAL_DEFAULT_WMS_CACHE_PATH", None) - if cs != 0: - gdaltest.post_reason('cs != 0') - return 'fail' + assert cs == 0, 'cs != 0' # Check maxsize and expired tags tms_expires = """<GDAL_WMS> @@ -500,11 +437,9 @@ def wms_8(): # tiles should be overwritten by new ones for expected_file in expected_files: - if os.path.getmtime(expected_file) <= mod_time: - return 'fail' - - return 'success' + assert os.path.getmtime(expected_file) > mod_time + ############################################################################### # Test OnEarth Tiled WMS minidriver @@ -512,7 +447,7 @@ def wms_8(): def wms_9(): if gdaltest.wms_drv is None: - return 'skip' + pytest.skip() tms = """<GDAL_WMS> <Service name="TiledWMS"> @@ -527,22 +462,16 @@ def wms_9(): if ds is None: srv = 'http://onearth.jpl.nasa.gov/wms.cgi?' if gdaltest.gdalurlopen(srv) is None: - return 'skip' - gdaltest.post_reason('open failed.') - return 'fail' + pytest.skip() + pytest.fail('open failed.') expected_cs = 5478 cs = ds.GetRasterBand(1).GetOverview(9).Checksum() - if cs != expected_cs: - gdaltest.post_reason('Did not get expected SRTM checksum.') - print(cs) - return 'fail' + assert cs == expected_cs, 'Did not get expected SRTM checksum.' ds = None - return 'success' - ############################################################################### # Test getting subdatasets from GetCapabilities @@ -550,100 +479,78 @@ def wms_9(): def wms_10(): if gdaltest.wms_drv is None: - return 'skip' + pytest.skip() if not gdaltest.wms_srv1_ok: - return 'skip' + pytest.skip() name = "WMS:http://sedac.ciesin.columbia.edu/mapserver/map/GPWv3?" ds = gdal.Open(name) - if ds is None: - gdaltest.post_reason('open of %s failed.' % name) - return 'fail' + assert ds is not None, ('open of %s failed.' % name) subdatasets = ds.GetMetadata("SUBDATASETS") - if not subdatasets: - gdaltest.post_reason('did not get expected subdataset count') - print(subdatasets) - return 'fail' + assert subdatasets, 'did not get expected subdataset count' ds = None name = subdatasets['SUBDATASET_1_NAME'] ds = gdal.Open(name) - if ds is None: - gdaltest.post_reason('open of %s failed.' % name) - return 'fail' + assert ds is not None, ('open of %s failed.' % name) ds = None - return 'success' - ############################################################################### # Test getting subdatasets from GetTileService -def wms_11(): +def test_wms_11(): if gdaltest.wms_drv is None: - return 'skip' + pytest.skip() if gdaltest.skip_on_travis(): - return 'skip' + pytest.skip() srv = 'http://onearth.jpl.nasa.gov/wms.cgi' if gdaltest.gdalurlopen(srv) is None: - return 'skip' + pytest.skip() name = "WMS:http://onearth.jpl.nasa.gov/wms.cgi?request=GetTileService" ds = gdal.Open(name) - if ds is None: - gdaltest.post_reason('open of %s failed.' % name) - return 'fail' + assert ds is not None, ('open of %s failed.' % name) subdatasets = ds.GetMetadata("SUBDATASETS") - if not subdatasets: - gdaltest.post_reason('did not get expected subdataset count') - print(subdatasets) - return 'fail' + assert subdatasets, 'did not get expected subdataset count' ds = None name = subdatasets['SUBDATASET_1_NAME'] ds = gdal.Open(name) - if ds is None: - gdaltest.post_reason('open of %s failed.' % name) - return 'fail' + assert ds is not None, ('open of %s failed.' % name) ds = None - return 'success' - ############################################################################### # Test getting subdatasets from a TMS server -def wms_12(): +def test_wms_12(): if gdaltest.wms_drv is None: - return 'skip' + pytest.skip() if gdaltest.metacarta_tms is not True: - return 'skip' + pytest.skip() name = "http://tilecache.osgeo.org/wms-c/Basic.py/1.0.0/" ds = gdal.Open(name) if ds is None: if gdaltest.gdalurlopen('http://tilecache.osgeo.org/wms-c/Basic.py/1.0.0/basic/0/0/0.png') is None: - return 'skip' - gdaltest.post_reason('open of %s failed.' % name) - return 'fail' + pytest.skip() + pytest.fail('open of %s failed.' % name) subdatasets = ds.GetMetadata("SUBDATASETS") - if not subdatasets: - gdaltest.post_reason('did not get expected subdataset count') - print(subdatasets) - return 'fail' + assert subdatasets, 'did not get expected subdataset count' ds = None @@ -654,40 +561,36 @@ def wms_12(): ds = gdal.Open(name) if ds is None: if gdaltest.gdalurlopen('http://tilecache.osgeo.org/wms-c/Basic.py/1.0.0/basic/0/0/0.png') is None: - return 'skip' - gdaltest.post_reason('open of %s failed.' % name) - return 'fail' + pytest.skip() + pytest.fail('open of %s failed.' % name) ds = None - return 'success' - + ############################################################################### # Test reading WMS through VRT (test effect of r21866) -def wms_13(): +def test_wms_13(): if gdaltest.wms_drv is None: - return 'skip' + pytest.skip() ds = gdal.Open("data/DNEC_250K.vrt") if ds.ReadRaster(0, 0, 1024, 682) is None: srv = 'http://wms.geobase.ca/wms-bin/cubeserv.cgi?SERVICE=WMS&VERSION=1.1.1&REQUEST=GeCapabilities' if gdaltest.gdalurlopen(srv) is None: - return 'skip' - return 'fail' + pytest.skip() + pytest.fail() ds = None - return 'success' - ############################################################################### # Test reading Virtual Earth layer -def wms_14(): +def test_wms_14(): if gdaltest.wms_drv is None: - return 'skip' + pytest.skip() ds = gdal.Open("""<GDAL_WMS> <Service name="VirtualEarth"> <ServerUrl>http://a${server_num}.ortho.tiles.virtualearth.net/tiles/a${quadkey}.jpeg?g=90</ServerUrl> @@ -696,122 +599,84 @@ def wms_14(): if ds is None: return' fail' - if ds.RasterXSize != 134217728 \ - or ds.RasterYSize != 134217728 \ - or ds.RasterCount != 3: - gdaltest.post_reason('wrong size or bands') - return 'fail' + assert ds.RasterXSize == 134217728 and ds.RasterYSize == 134217728 and ds.RasterCount == 3, \ + 'wrong size or bands' wkt = ds.GetProjectionRef() - if wkt.find('PROJCS["Google Maps Global Mercator"') != 0: - gdaltest.post_reason('Got wrong SRS: ' + wkt) - return 'fail' + assert wkt.find('PROJCS["Google Maps Global Mercator"') == 0, \ + ('Got wrong SRS: ' + wkt) gt = ds.GetGeoTransform() - if abs(gt[0] - -20037508.34278924,) > 0.00001 \ - or abs(gt[3] - 20037508.34278924,) > 0.00001 \ - or abs(gt[1] - 0.2985821417389697) > 0.00001 \ - or abs(gt[2] - 0) > 0.00001 \ - or abs(gt[5] - -0.2985821417389697,) > 0.00001 \ - or abs(gt[4] - 0) > 0.00001: - gdaltest.post_reason('wrong geotransform') - print(gt) - return 'fail' - - if ds.GetRasterBand(1).GetOverviewCount() != 18: - gdaltest.post_reason('bad overview count') - print(ds.GetRasterBand(1).GetOverviewCount()) - return 'fail' + assert abs(gt[0] - -20037508.34278924,) <= 0.00001 and abs(gt[3] - 20037508.34278924,) <= 0.00001 and abs(gt[1] - 0.2985821417389697) <= 0.00001 and abs(gt[2] - 0) <= 0.00001 and abs(gt[5] - -0.2985821417389697,) <= 0.00001 and abs(gt[4] - 0) <= 0.00001, \ + 'wrong geotransform' + + assert ds.GetRasterBand(1).GetOverviewCount() == 18, 'bad overview count' (block_xsize, block_ysize) = ds.GetRasterBand(1).GetBlockSize() if block_xsize != 256 or block_ysize != 256: - gdaltest.post_reason('bad block size') print("(%d, %d)" % (block_xsize, block_ysize)) - return 'fail' - - return 'success' + pytest.fail('bad block size') + ############################################################################### # Test reading ArcGIS MapServer JSon definition and CreateCopy() -def wms_15(): +def test_wms_15(): if gdaltest.wms_drv is None: - return 'skip' + pytest.skip() src_ds = gdal.Open("http://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer?f=json&pretty=true") if src_ds is None: srv = 'http://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer?f=json&pretty=true' if gdaltest.gdalurlopen(srv) is None: - return 'skip' - return 'fail' + pytest.skip() + pytest.fail() ds = gdal.GetDriverByName("WMS").CreateCopy("/vsimem/wms.xml", src_ds) src_ds = None if ds is None: return' fail' - if ds.RasterXSize != 1073741824 \ - or ds.RasterYSize != 1073741824 \ - or ds.RasterCount != 3: - gdaltest.post_reason('wrong size or bands') - return 'fail' + assert ds.RasterXSize == 1073741824 and ds.RasterYSize == 1073741824 and ds.RasterCount == 3, \ + 'wrong size or bands' wkt = ds.GetProjectionRef() - if wkt.find('PROJCS["WGS 84 / Pseudo-Mercator"') != 0: - gdaltest.post_reason('Got wrong SRS: ' + wkt) - return 'fail' + assert wkt.find('PROJCS["WGS 84 / Pseudo-Mercator"') == 0, ('Got wrong SRS: ' + wkt) gt = ds.GetGeoTransform() - if abs(gt[0] - -20037508.342787001) > 0.00001 \ - or abs(gt[3] - 20037508.342787001) > 0.00001 \ - or abs(gt[1] - 0.037322767717361482) > 0.00001 \ - or abs(gt[2] - 0) > 0.00001 \ - or abs(gt[5] - -0.037322767717361482) > 0.00001 \ - or abs(gt[4] - 0) > 0.00001: - gdaltest.post_reason('wrong geotransform') - print(gt) - return 'fail' - - if ds.GetRasterBand(1).GetOverviewCount() != 22: - gdaltest.post_reason('bad overview count') - print(ds.GetRasterBand(1).GetOverviewCount()) - return 'fail' + assert abs(gt[0] - -20037508.342787001) <= 0.00001 and abs(gt[3] - 20037508.342787001) <= 0.00001 and abs(gt[1] - 0.037322767717361482) <= 0.00001 and abs(gt[2] - 0) <= 0.00001 and abs(gt[5] - -0.037322767717361482) <= 0.00001 and abs(gt[4] - 0) <= 0.00001, \ + 'wrong geotransform' + + assert ds.GetRasterBand(1).GetOverviewCount() == 22, 'bad overview count' (block_xsize, block_ysize) = ds.GetRasterBand(1).GetBlockSize() if block_xsize != 256 or block_ysize != 256: - gdaltest.post_reason('bad block size') print("(%d, %d)" % (block_xsize, block_ysize)) - return 'fail' + pytest.fail('bad block size') ds = None gdal.Unlink("/vsimem/wms.xml") - return 'success' - ############################################################################### # Test getting subdatasets from WMS-C Capabilities -def wms_16(): +def test_wms_16(): if gdaltest.wms_drv is None: - return 'skip' + pytest.skip() name = "WMS:http://demo.opengeo.org/geoserver/gwc/service/wms?tiled=TRUE" ds = gdal.Open(name) if ds is None: srv = 'http://demo.opengeo.org/geoserver/gwc/service/wms?' if gdaltest.gdalurlopen(srv) is None: - return 'skip' - gdaltest.post_reason('open of %s failed.' % name) - return 'fail' + pytest.skip() + pytest.fail('open of %s failed.' % name) subdatasets = ds.GetMetadata("SUBDATASETS") - if not subdatasets: - gdaltest.post_reason('did not get expected subdataset count') - print(subdatasets) - return 'fail' + assert subdatasets, 'did not get expected subdataset count' ds = None @@ -820,14 +685,11 @@ def wms_16(): if key[-5:] == '_NAME' and subdatasets[key].find('bugsites') != -1: name = subdatasets[key] break - if name is None: - return 'fail' + assert name is not None name = 'http://demo.opengeo.org/geoserver/wms?SERVICE=WMS&request=GetMap&version=1.1.1&layers=og:bugsites&styles=&srs=EPSG:26713&bbox=599351.50000000,4914096.00000000,608471.00000000,4920512.00000000' ds = gdal.Open(name) - if ds is None: - gdaltest.post_reason('open of %s failed.' % name) - return 'fail' + assert ds is not None, ('open of %s failed.' % name) # Matches feature of "WFS:http://demo.opengeo.org/geoserver/wfs?SRSNAME=EPSG:900913" og:bugsites # OGRFeature(og:bugsites):68846 @@ -841,51 +703,38 @@ def wms_16(): # Some bug in GeoServer ? if val is not None and val.find('java.lang.NoSuchMethodError: org.geoserver.wms.WMS.pixelToWorld') >= 0: - print(val) - return 'skip' + pytest.skip(val) if val is not None and (val.find('Gateway Time-out') >= 0 or val.find('HTTP error code : 5') >= 0): - return 'skip' + pytest.skip() if val is None or val.find('<og:cat>86</og:cat>') == -1: if val.find('java.lang.NullPointerException') >= 0 or val.find('504 Gateway Time-out') >= 0 or val.find('java.lang.OutOfMemoryError') >= 0: - print(val) - return 'skip' + pytest.skip(val) - gdaltest.post_reason('expected a value') print(val) - return 'fail' + pytest.fail('expected a value') # Ask again. Should be cached val_again = ds.GetRasterBand(1).GetMetadataItem(pixel, "LocationInfo") - if val_again != val: - gdaltest.post_reason('expected a value') - print(val_again) - return 'fail' + assert val_again == val, 'expected a value' # Ask another band. Should be cached val2 = ds.GetRasterBand(2).GetMetadataItem(pixel, "LocationInfo") - if val2 != val: - gdaltest.post_reason('expected a value') - print(val2) - return 'fail' + assert val2 == val, 'expected a value' # Ask an overview band val2 = ds.GetRasterBand(1).GetOverview(0).GetMetadataItem(pixel, "LocationInfo") if val2 != val: if val2.find('java.lang.NullPointerException') >= 0 or val2.find('504 Gateway Time-out') >= 0 or val2.find('java.lang.OutOfMemoryError') >= 0: - print(val2) - return 'skip' + pytest.skip(val2) - gdaltest.post_reason('expected a value') print(val2) - return 'fail' + pytest.fail('expected a value') ds = None - return 'success' - ############################################################################### # Test a TiledWMS dataset with a color table (#4613) @@ -893,34 +742,29 @@ def wms_16(): def wms_17(): if gdaltest.wms_drv is None: - return 'skip' + pytest.skip() srv = 'http://onmoon.lmmp.nasa.gov/sites/wms.cgi?' if gdaltest.gdalurlopen(srv) is None: - return 'skip' + pytest.skip() name = '<GDAL_WMS><Service name="TiledWMS"><ServerUrl>http://onmoon.lmmp.nasa.gov/sites/wms.cgi?</ServerUrl><TiledGroupName>King Crater DEM Color Confidence, LMMP</TiledGroupName></Service></GDAL_WMS>' ds = gdal.Open(name) - if ds is None: - gdaltest.post_reason('open of %s failed.' % name) - return 'fail' + assert ds is not None, ('open of %s failed.' % name) band = ds.GetRasterBand(1) - if band.GetColorTable() is None: - return 'fail' + assert band.GetColorTable() is not None ds = None - return 'success' - ############################################################################### # Test a ArcGIS Server -def wms_18(): +def test_wms_18(): if gdaltest.wms_drv is None: - return 'skip' + pytest.skip() # We don't need to check if the remote service is online as we # don't need a connection for this test. @@ -929,70 +773,51 @@ def wms_18(): ds = gdal.Open(fn) - if ds is None: - gdaltest.post_reason('open failed.') - return 'fail' + assert ds is not None, 'open failed.' - if ds.RasterXSize != 512 \ - or ds.RasterYSize != 512 \ - or ds.RasterCount != 3: - gdaltest.post_reason('wrong size or bands') - return 'fail' + assert ds.RasterXSize == 512 and ds.RasterYSize == 512 and ds.RasterCount == 3, \ + 'wrong size or bands' # todo: add locationinfo test # add getting image test if gdaltest.gdalurlopen('http://sampleserver1.arcgisonline.com/ArcGIS/rest/services/Specialty/ESRI_StateCityHighway_USA/MapServer') is None: - return 'skip' + pytest.skip() expected_cs = 12824 cs = ds.GetRasterBand(1).Checksum() - if cs != expected_cs: - gdaltest.post_reason('Did not get expected SRTM checksum.') - print(cs) - return 'fail' + assert cs == expected_cs, 'Did not get expected SRTM checksum.' ds = None - return 'success' - ############################################################################### # Test a IIP server -def wms_19(): +def test_wms_19(): if gdaltest.wms_drv is None: - return 'skip' + pytest.skip() ds = gdal.Open('IIP:http://merovingio.c2rmf.cnrs.fr/fcgi-bin/iipsrv.fcgi?FIF=globe.256x256.tif') if ds is None: if gdaltest.gdalurlopen('http://merovingio.c2rmf.cnrs.fr/fcgi-bin/iipsrv.fcgi?FIF=globe.256x256.tif&obj=Basic-Info') is None: - return 'skip' - gdaltest.post_reason('open failed.') - return 'fail' + pytest.skip() + pytest.fail('open failed.') - if ds.RasterXSize != 86400 \ - or ds.RasterYSize != 43200 \ - or ds.RasterCount != 3: - gdaltest.post_reason('wrong size or bands') - return 'fail' + assert ds.RasterXSize == 86400 and ds.RasterYSize == 43200 and ds.RasterCount == 3, \ + 'wrong size or bands' # Expected checksum seems to change over time. Hum... cs = ds.GetRasterBand(1).GetOverview(ds.GetRasterBand(1).GetOverviewCount() - 1).Checksum() - if cs == 0: - gdaltest.post_reason('Did not get expected checksum.') - print(cs) - return 'fail' + assert cs != 0, 'Did not get expected checksum.' ds = None - - return 'success' ############################################################################### -def wms_cleanup(): +def test_wms_cleanup(): gdaltest.wms_ds = None gdaltest.clean_tmp() @@ -1002,36 +827,7 @@ def wms_cleanup(): except OSError: pass - return 'success' - - -gdaltest_list = [ - wms_1, - # wms_2, - # wms_3, - # wms_4, - wms_5, - wms_6, - wms_7, - wms_8, - # wms_9, - # wms_10, - wms_11, - wms_12, - wms_13, - wms_14, - wms_15, - wms_16, - # wms_17, - wms_18, - wms_19, - wms_cleanup] - - -if __name__ == '__main__': + - gdaltest.setup_run('wms') - gdaltest.run_tests(gdaltest_list) - sys.exit(gdaltest.summarize()) diff --git a/autotest/gdrivers/wmts.py b/autotest/gdrivers/wmts.py index c874230600e3..c541796da89a 100755 --- a/autotest/gdrivers/wmts.py +++ b/autotest/gdrivers/wmts.py @@ -29,20 +29,19 @@ # DEALINGS IN THE SOFTWARE. ############################################################################### -import sys import shutil -sys.path.append('../pymod') from osgeo import gdal import gdaltest +import pytest ############################################################################### # Find WMTS driver -def wmts_1(): +def test_wmts_1(): gdaltest.wmts_drv = gdal.GetDriverByName('WMTS') @@ -55,152 +54,122 @@ def wmts_1(): gdal.SetConfigOption('CPL_CURL_ENABLE_VSIMEM', 'YES') gdal.SetConfigOption('GDAL_DEFAULT_WMS_CACHE_PATH', '/vsimem/cache') - return 'success' - return 'skip' + return + pytest.skip() ############################################################################### # Error: no URL and invalid GDAL_WMTS service file documents -def wmts_2(): +def test_wmts_2(): if gdaltest.wmts_drv is None: - return 'skip' + pytest.skip() gdal.PushErrorHandler() ds = gdal.Open('WMTS:') gdal.PopErrorHandler() - if ds is not None: - gdaltest.post_reason('fail') - return 'fail' + assert ds is None gdal.PushErrorHandler() ds = gdal.Open('<GDAL_WMTS>') gdal.PopErrorHandler() - if ds is not None: - gdaltest.post_reason('fail') - return 'fail' + assert ds is None gdal.PushErrorHandler() ds = gdal.Open('<GDAL_WMTSxxx/>') gdal.PopErrorHandler() - if ds is not None: - gdaltest.post_reason('fail') - return 'fail' + assert ds is None gdal.PushErrorHandler() ds = gdal.Open('<GDAL_WMTS></GDAL_WMTS>') gdal.PopErrorHandler() - if ds is not None: - gdaltest.post_reason('fail') - return 'fail' - - return 'success' + assert ds is None ############################################################################### # Error: invalid URL -def wmts_3(): +def test_wmts_3(): if gdaltest.wmts_drv is None: - return 'skip' + pytest.skip() gdal.PushErrorHandler() ds = gdal.Open('WMTS:https://non_existing') gdal.PopErrorHandler() - if ds is not None: - gdaltest.post_reason('fail') - return 'fail' - - return 'success' + assert ds is None ############################################################################### # Error: invalid URL -def wmts_4(): +def test_wmts_4(): if gdaltest.wmts_drv is None: - return 'skip' + pytest.skip() gdal.PushErrorHandler() ds = gdal.Open('WMTS:/vsimem/non_existing') gdal.PopErrorHandler() - if ds is not None: - gdaltest.post_reason('fail') - return 'fail' - - return 'success' + assert ds is None ############################################################################### # Error: invalid XML in GetCapabilities response -def wmts_5(): +def test_wmts_5(): if gdaltest.wmts_drv is None: - return 'skip' + pytest.skip() gdal.FileFromMemBuffer('/vsimem/invalid_getcapabilities.xml', '<invalid_xml') gdal.PushErrorHandler() ds = gdal.Open('WMTS:/vsimem/invalid_getcapabilities.xml') gdal.PopErrorHandler() - if ds is not None: - gdaltest.post_reason('fail') - return 'fail' - - return 'success' + assert ds is None ############################################################################### # Error: invalid content in GetCapabilities response -def wmts_6(): +def test_wmts_6(): if gdaltest.wmts_drv is None: - return 'skip' + pytest.skip() gdal.FileFromMemBuffer('/vsimem/invalid_getcapabilities.xml', '<Capabilities/>') gdal.PushErrorHandler() ds = gdal.Open('WMTS:/vsimem/invalid_getcapabilities.xml') gdal.PopErrorHandler() - if ds is not None: - gdaltest.post_reason('fail') - return 'fail' - - return 'success' + assert ds is None ############################################################################### # Error: no layers -def wmts_7(): +def test_wmts_7(): if gdaltest.wmts_drv is None: - return 'skip' + pytest.skip() gdal.FileFromMemBuffer('/vsimem/empty_getcapabilities.xml', '<Capabilities><Contents/></Capabilities>') gdal.PushErrorHandler() ds = gdal.Open('WMTS:/vsimem/empty_getcapabilities.xml') gdal.PopErrorHandler() - if ds is not None: - gdaltest.post_reason('fail') - return 'fail' - - return 'success' + assert ds is None ############################################################################### # Error: missing TileMatrixSetLink and Style -def wmts_8(): +def test_wmts_8(): if gdaltest.wmts_drv is None: - return 'skip' + pytest.skip() gdal.FileFromMemBuffer('/vsimem/missing.xml', """<Capabilities> <Contents> @@ -213,20 +182,16 @@ def wmts_8(): gdal.PushErrorHandler() ds = gdal.Open('WMTS:/vsimem/missing.xml') gdal.PopErrorHandler() - if ds is not None: - gdaltest.post_reason('fail') - return 'fail' - - return 'success' + assert ds is None ############################################################################### # Error: missing TileMatrixSet -def wmts_9(): +def test_wmts_9(): if gdaltest.wmts_drv is None: - return 'skip' + pytest.skip() gdal.FileFromMemBuffer('/vsimem/missing_tms.xml', """<Capabilities> <Contents> @@ -246,20 +211,16 @@ def wmts_9(): gdal.PushErrorHandler() ds = gdal.Open('WMTS:/vsimem/missing_tms.xml') gdal.PopErrorHandler() - if ds is not None: - gdaltest.post_reason('fail') - return 'fail' - - return 'success' + assert ds is None ############################################################################### # Error: Missing SupportedCRS -def wmts_10(): +def test_wmts_10(): if gdaltest.wmts_drv is None: - return 'skip' + pytest.skip() gdal.FileFromMemBuffer('/vsimem/missing_SupportedCRS.xml', """<Capabilities> <Contents> @@ -282,20 +243,16 @@ def wmts_10(): gdal.PushErrorHandler() ds = gdal.Open('WMTS:/vsimem/missing_SupportedCRS.xml') gdal.PopErrorHandler() - if ds is not None: - gdaltest.post_reason('fail') - return 'fail' - - return 'success' + assert ds is None ############################################################################### # Error: Cannot find TileMatrix in TileMatrixSet -def wmts_11(): +def test_wmts_11(): if gdaltest.wmts_drv is None: - return 'skip' + pytest.skip() gdal.FileFromMemBuffer('/vsimem/no_tilematrix.xml', """<Capabilities> <Contents> @@ -319,20 +276,16 @@ def wmts_11(): gdal.PushErrorHandler() ds = gdal.Open('WMTS:/vsimem/no_tilematrix.xml') gdal.PopErrorHandler() - if ds is not None: - gdaltest.post_reason('fail') - return 'fail' - - return 'success' + assert ds is None ############################################################################### # Error: Missing required element in TileMatrix element -def wmts_12(): +def test_wmts_12(): if gdaltest.wmts_drv is None: - return 'skip' + pytest.skip() gdal.FileFromMemBuffer('/vsimem/missing_required_element_in_tilematrix.xml', """<Capabilities> <Contents> @@ -357,20 +310,16 @@ def wmts_12(): gdal.PushErrorHandler() ds = gdal.Open('WMTS:/vsimem/missing_required_element_in_tilematrix.xml') gdal.PopErrorHandler() - if ds is not None: - gdaltest.post_reason('fail') - return 'fail' - - return 'success' + assert ds is None ############################################################################### # Error: Missing ResourceURL -def wmts_12bis(): +def test_wmts_12bis(): if gdaltest.wmts_drv is None: - return 'skip' + pytest.skip() gdal.FileFromMemBuffer('/vsimem/wmts_12bis.xml', """<Capabilities> <Contents> @@ -402,20 +351,16 @@ def wmts_12bis(): gdal.PushErrorHandler() ds = gdal.Open('WMTS:/vsimem/wmts_12bis.xml') gdal.PopErrorHandler() - if ds is not None: - gdaltest.post_reason('fail') - return 'fail' - - return 'success' + assert ds is None ############################################################################### # Minimal -def wmts_13(): +def test_wmts_13(): if gdaltest.wmts_drv is None: - return 'skip' + pytest.skip() gdal.FileFromMemBuffer('/vsimem/minimal.xml', """<Capabilities> <Contents> @@ -446,54 +391,26 @@ def wmts_13(): </Capabilities>""") ds = gdal.Open('WMTS:/vsimem/minimal.xml') - if ds is None: - gdaltest.post_reason('fail') - return 'fail' - if ds.RasterXSize != 256: - gdaltest.post_reason('fail') - return 'fail' - if ds.RasterYSize != 256: - gdaltest.post_reason('fail') - return 'fail' + assert ds is not None + assert ds.RasterXSize == 256 + assert ds.RasterYSize == 256 got_gt = ds.GetGeoTransform() expected_gt = (-20037508.342799999, 156543.03392811998, 0.0, 20037508.342799999, 0.0, -156543.03392811998) for i in range(6): - if abs(got_gt[i] - expected_gt[i]) > 1e-8: - gdaltest.post_reason('fail') - print(got_gt) - return 'fail' - if ds.GetProjectionRef().find('3857') < 0: - gdaltest.post_reason('fail') - return 'fail' - if ds.RasterCount != 4: - gdaltest.post_reason('fail') - return 'fail' + assert abs(got_gt[i] - expected_gt[i]) <= 1e-8 + assert ds.GetProjectionRef().find('3857') >= 0 + assert ds.RasterCount == 4 for i in range(4): - if ds.GetRasterBand(i + 1).GetColorInterpretation() != gdal.GCI_RedBand + i: - gdaltest.post_reason('fail') - return 'fail' - if ds.GetRasterBand(1).GetOverviewCount() != 0: - gdaltest.post_reason('fail') - return 'fail' - if ds.GetRasterBand(1).GetOverview(0) is not None: - gdaltest.post_reason('fail') - return 'fail' + assert ds.GetRasterBand(i + 1).GetColorInterpretation() == gdal.GCI_RedBand + i + assert ds.GetRasterBand(1).GetOverviewCount() == 0 + assert ds.GetRasterBand(1).GetOverview(0) is None gdal.PushErrorHandler() cs = ds.GetRasterBand(1).Checksum() gdal.PopErrorHandler() - if cs != 0: - gdaltest.post_reason('fail') - return 'fail' - if ds.GetSubDatasets() != []: - gdaltest.post_reason('fail') - print(ds.GetSubDatasets()) - return 'fail' - if ds.GetRasterBand(1).GetMetadataItem('Pixel_0_0', 'LocationInfo') is not None: - gdaltest.post_reason('fail') - return 'fail' - if ds.GetRasterBand(1).GetMetadataItem('foo') is not None: - gdaltest.post_reason('fail') - return 'fail' + assert cs == 0 + assert ds.GetSubDatasets() == [] + assert ds.GetRasterBand(1).GetMetadataItem('Pixel_0_0', 'LocationInfo') is None + assert ds.GetRasterBand(1).GetMetadataItem('foo') is None for connection_str in ['WMTS:/vsimem/minimal.xml,layer=', 'WMTS:/vsimem/minimal.xml,style=', @@ -502,10 +419,7 @@ def wmts_13(): 'WMTS:/vsimem/minimal.xml,zoom_level=', 'WMTS:/vsimem/minimal.xml,layer=,style=,tilematrixset=']: ds = gdal.Open(connection_str) - if ds is None: - gdaltest.post_reason('fail') - print(connection_str) - return 'fail' + assert ds is not None, connection_str ds = None for connection_str in ['WMTS:/vsimem/minimal.xml,layer=foo', @@ -516,10 +430,7 @@ def wmts_13(): gdal.PushErrorHandler() ds = gdal.Open(connection_str) gdal.PopErrorHandler() - if ds is not None: - gdaltest.post_reason('fail') - print(connection_str) - return 'fail' + assert ds is None, connection_str ds = None ds = gdal.Open('WMTS:/vsimem/minimal.xml') @@ -529,35 +440,27 @@ def wmts_13(): tmp_ds = gdal.GetDriverByName('PNG').CreateCopy('/vsimem/0/0/0.png', tmp_ds) for i in range(4): cs = ds.GetRasterBand(i + 1).Checksum() - if cs != tmp_ds.GetRasterBand(i + 1).Checksum(): - gdaltest.post_reason('fail') - return 'fail' + assert cs == tmp_ds.GetRasterBand(i + 1).Checksum() ref_data = tmp_ds.ReadRaster(0, 0, 256, 256) got_data = ds.ReadRaster(0, 0, ds.RasterXSize, ds.RasterYSize, 256, 256) - if ref_data != got_data: - gdaltest.post_reason('fail') - return 'fail' + assert ref_data == got_data ref_data = tmp_ds.GetRasterBand(1).ReadRaster(0, 0, 256, 256) got_data = ds.GetRasterBand(1).ReadRaster(0, 0, ds.RasterXSize, ds.RasterYSize, 256, 256) - if ref_data != got_data: - gdaltest.post_reason('fail') - return 'fail' + assert ref_data == got_data ds = None wmts_CleanCache() - return 'success' - ############################################################################### # Nominal RESTful -def wmts_14(): +def test_wmts_14(): if gdaltest.wmts_drv is None: - return 'skip' + pytest.skip() gdal.FileFromMemBuffer('/vsimem/nominal.xml', """<Capabilities> <Contents> @@ -645,34 +548,21 @@ def wmts_14(): </Capabilities>""") ds = gdal.Open('WMTS:/vsimem/nominal.xml') - if ds is None: - gdaltest.post_reason('fail') - return 'fail' - if ds.GetSubDatasets() != [('WMTS:/vsimem/nominal.xml,layer=lyr1,tilematrixset=tms,style="style=auto"', + assert ds is not None + assert (ds.GetSubDatasets() == [('WMTS:/vsimem/nominal.xml,layer=lyr1,tilematrixset=tms,style="style=auto"', 'Layer My layer1, tile matrix set tms, style "Default style"'), ('WMTS:/vsimem/nominal.xml,layer=lyr1,tilematrixset=tms,style=another_style', 'Layer My layer1, tile matrix set tms, style "Another style"'), ('WMTS:/vsimem/nominal.xml,layer=lyr1,tilematrixset=another_tms,style="style=auto"', 'Layer My layer1, tile matrix set another_tms, style "Default style"'), ('WMTS:/vsimem/nominal.xml,layer=lyr1,tilematrixset=another_tms,style=another_style', - 'Layer My layer1, tile matrix set another_tms, style "Another style"')]: - gdaltest.post_reason('fail') - print(ds.GetSubDatasets()) - return 'fail' - if ds.RasterXSize != 67108864: - gdaltest.post_reason('fail') - return 'fail' + 'Layer My layer1, tile matrix set another_tms, style "Another style"')]) + assert ds.RasterXSize == 67108864 gdal.PushErrorHandler() res = ds.GetRasterBand(1).GetMetadataItem('Pixel_1_2', 'LocationInfo') gdal.PopErrorHandler() - if res != '': - gdaltest.post_reason('fail') - print(res) - return 'fail' - if ds.GetMetadata() != {'ABSTRACT': 'My abstract', 'TITLE': 'My layer1'}: - gdaltest.post_reason('fail') - print(ds.GetMetadata()) - return 'fail' + assert res == '' + assert ds.GetMetadata() == {'ABSTRACT': 'My abstract', 'TITLE': 'My layer1'} gdal.PushErrorHandler() gdaltest.wmts_drv.CreateCopy('/vsimem/gdal_nominal.xml', gdal.GetDriverByName('MEM').Create('', 1, 1)) @@ -684,7 +574,7 @@ def wmts_14(): f = gdal.VSIFOpenL('/vsimem/gdal_nominal.xml', 'rb') data = gdal.VSIFReadL(1, 10000, f).decode('ascii') gdal.VSIFCloseL(f) - if data != """<GDAL_WMTS> + assert data == """<GDAL_WMTS> <GetCapabilitiesUrl>/vsimem/nominal.xml</GetCapabilitiesUrl> <Layer>lyr1</Layer> <Style>style=auto</Style> @@ -701,40 +591,25 @@ def wmts_14(): <ZeroBlockHttpCodes>204,404</ZeroBlockHttpCodes> <ZeroBlockOnServerException>true</ZeroBlockOnServerException> </GDAL_WMTS> -""": - gdaltest.post_reason('fail') - print(data) - return 'fail' +""" ds = gdal.Open('/vsimem/gdal_nominal.xml') gdal.FileFromMemBuffer('/vsimem/2011-10-04/style=auto/tms/tm_18/0/0/2/1.txt', 'foo') res = ds.GetRasterBand(1).GetMetadataItem('Pixel_1_2', 'LocationInfo') - if res != '<LocationInfo>foo</LocationInfo>': - gdaltest.post_reason('fail') - print(res) - return 'fail' + assert res == '<LocationInfo>foo</LocationInfo>' res = ds.GetRasterBand(1).GetMetadataItem('Pixel_1_2', 'LocationInfo') - if res != '<LocationInfo>foo</LocationInfo>': - gdaltest.post_reason('fail') - print(res) - return 'fail' + assert res == '<LocationInfo>foo</LocationInfo>' ds = gdal.Open('<GDAL_WMTS><GetCapabilitiesUrl>/vsimem/nominal.xml</GetCapabilitiesUrl></GDAL_WMTS>') - if ds is None: - gdaltest.post_reason('fail') - return 'fail' + assert ds is not None ds = gdal.Open('WMTS:/vsimem/gdal_nominal.xml') - if ds is None: - gdaltest.post_reason('fail') - return 'fail' + assert ds is not None for open_options in [['URL=/vsimem/nominal.xml'], ['URL=/vsimem/nominal.xml', 'STYLE=style=auto', 'TILEMATRIXSET=tms']]: ds = gdal.OpenEx('WMTS:', open_options=open_options) - if ds is None: - gdaltest.post_reason('fail') - return 'fail' + assert ds is not None for open_options in [['URL=/vsimem/nominal.xml', 'STYLE=x', 'TILEMATRIXSET=y'], ['URL=/vsimem/nominal.xml', 'STYLE=style=auto', 'TILEMATRIX=30'], @@ -742,54 +617,29 @@ def wmts_14(): gdal.PushErrorHandler() ds = gdal.OpenEx('WMTS:', open_options=open_options) gdal.PopErrorHandler() - if ds is not None: - gdaltest.post_reason('fail') - return 'fail' + assert ds is None ds = gdal.Open('WMTS:/vsimem/nominal.xml') gdal.FileFromMemBuffer('/vsimem/2011-10-04/style=auto/tms/tm_18/0/0/2/1.txt', '<?xml version="1.0" encoding="UTF-8"?><xml_content/>') res = ds.GetRasterBand(1).GetMetadataItem('Pixel_1_2', 'LocationInfo') - if res != """<LocationInfo><xml_content /> -</LocationInfo>""": - gdaltest.post_reason('fail') - print(res) - return 'fail' + assert res == """<LocationInfo><xml_content /> +</LocationInfo>""" ds = gdal.Open('WMTS:/vsimem/gdal_nominal.xml,tilematrix=tm_0') - if ds is None: - gdaltest.post_reason('fail') - return 'fail' - if ds.RasterXSize != 256: - gdaltest.post_reason('fail') - print(ds.RasterXSize) - return 'fail' + assert ds is not None + assert ds.RasterXSize == 256 ds = gdal.OpenEx('WMTS:/vsimem/gdal_nominal.xml', open_options=['tilematrix=tm_0']) - if ds is None: - gdaltest.post_reason('fail') - return 'fail' - if ds.RasterXSize != 256: - gdaltest.post_reason('fail') - print(ds.RasterXSize) - return 'fail' + assert ds is not None + assert ds.RasterXSize == 256 ds = gdal.Open('WMTS:/vsimem/gdal_nominal.xml,zoom_level=0') - if ds is None: - gdaltest.post_reason('fail') - return 'fail' - if ds.RasterXSize != 256: - gdaltest.post_reason('fail') - print(ds.RasterXSize) - return 'fail' + assert ds is not None + assert ds.RasterXSize == 256 ds = gdal.OpenEx('WMTS:/vsimem/gdal_nominal.xml', open_options=['zoom_level=0']) - if ds is None: - gdaltest.post_reason('fail') - return 'fail' - if ds.RasterXSize != 256: - gdaltest.post_reason('fail') - print(ds.RasterXSize) - return 'fail' + assert ds is not None + assert ds.RasterXSize == 256 gdal.FileFromMemBuffer('/vsimem/gdal_nominal.xml', """<GDAL_WMTS> <GetCapabilitiesUrl>/vsimem/nominal.xml</GetCapabilitiesUrl> @@ -810,13 +660,8 @@ def wmts_14(): <ZeroBlockOnServerException>true</ZeroBlockOnServerException> </GDAL_WMTS>""") ds = gdal.Open('WMTS:/vsimem/gdal_nominal.xml') - if ds is None: - gdaltest.post_reason('fail') - return 'fail' - if ds.RasterXSize != 256: - gdaltest.post_reason('fail') - print(ds.RasterXSize) - return 'fail' + assert ds is not None + assert ds.RasterXSize == 256 gdal.FileFromMemBuffer('/vsimem/gdal_nominal.xml', """<GDAL_WMTS> <GetCapabilitiesUrl>/vsimem/nominal.xml</GetCapabilitiesUrl> @@ -837,24 +682,17 @@ def wmts_14(): <ZeroBlockOnServerException>true</ZeroBlockOnServerException> </GDAL_WMTS>""") ds = gdal.Open('WMTS:/vsimem/gdal_nominal.xml') - if ds is None: - gdaltest.post_reason('fail') - return 'fail' - if ds.RasterXSize != 256: - gdaltest.post_reason('fail') - print(ds.RasterXSize) - return 'fail' - - return 'success' + assert ds is not None + assert ds.RasterXSize == 256 ############################################################################### # Nominal KVP -def wmts_15(): +def test_wmts_15(): if gdaltest.wmts_drv is None: - return 'skip' + pytest.skip() gdal.FileFromMemBuffer('/vsimem/nominal_kvp.xml?service=WMTS&request=GetCapabilities', """<Capabilities xmlns="http://www.opengis.net/wmts/1.0"> <ows:OperationsMetadata> @@ -953,19 +791,12 @@ def wmts_15(): </Capabilities>""") ds = gdal.Open('/vsimem/nominal_kvp.xml?service=WMTS&request=GetCapabilities') - if ds is None: - gdaltest.post_reason('fail') - return 'fail' - if ds.RasterXSize != 67108864: - gdaltest.post_reason('fail') - return 'fail' + assert ds is not None + assert ds.RasterXSize == 67108864 gdal.PushErrorHandler() res = ds.GetRasterBand(1).GetMetadataItem('Pixel_1_2', 'LocationInfo') gdal.PopErrorHandler() - if res != '': - gdaltest.post_reason('fail') - print(res) - return 'fail' + assert res == '' gdaltest.wmts_drv.CreateCopy('/vsimem/gdal_nominal_kvp.xml', ds) ds = None @@ -973,50 +804,37 @@ def wmts_15(): ds = gdal.Open('/vsimem/gdal_nominal_kvp.xml') gdal.FileFromMemBuffer('/vsimem/nominal_kvp.xml?service=WMTS&request=GetFeatureInfo&version=1.0.0&layer=lyr1&style=default_style&InfoFormat=text/plain&TileMatrixSet=tms&TileMatrix=18&TileRow=0&TileCol=0&J=2&I=1&time=2011-10-04', 'bar') res = ds.GetRasterBand(1).GetMetadataItem('Pixel_1_2', 'LocationInfo') - if res != '<LocationInfo>bar</LocationInfo>': - gdaltest.post_reason('fail') - print(res) - return 'fail' + assert res == '<LocationInfo>bar</LocationInfo>' ds = gdal.Open('WMTS:/vsimem/gdal_nominal_kvp.xml') - if ds is None: - gdaltest.post_reason('fail') - return 'fail' + assert ds is not None tmp_ds = gdal.GetDriverByName('MEM').Create('', 256, 256, 4) for i in range(4): tmp_ds.GetRasterBand(i + 1).Fill((i + 1) * 255 / 4) tmp_ds = gdal.GetDriverByName('PNG').CreateCopy('/vsimem/nominal_kvp.xml?service=WMTS&request=GetTile&version=1.0.0&layer=lyr1&style=default_style&format=image/png&TileMatrixSet=tms&TileMatrix=0&TileRow=0&TileCol=0&time=2011-10-04', tmp_ds) for i in range(4): cs = ds.GetRasterBand(i + 1).GetOverview(0).Checksum() - if cs != tmp_ds.GetRasterBand(i + 1).Checksum(): - gdaltest.post_reason('fail') - return 'fail' + assert cs == tmp_ds.GetRasterBand(i + 1).Checksum() ref_data = tmp_ds.ReadRaster(0, 0, 256, 256) got_data = ds.ReadRaster(0, 0, ds.RasterXSize, ds.RasterYSize, 256, 256) - if ref_data != got_data: - gdaltest.post_reason('fail') - return 'fail' + assert ref_data == got_data ref_data = tmp_ds.GetRasterBand(1).ReadRaster(0, 0, 256, 256) got_data = ds.GetRasterBand(1).ReadRaster(0, 0, ds.RasterXSize, ds.RasterYSize, 256, 256) - if ref_data != got_data: - gdaltest.post_reason('fail') - return 'fail' + assert ref_data == got_data ds = None wmts_CleanCache() - return 'success' - ############################################################################### # AOI from layer WGS84BoundingBox -def wmts_16(): +def test_wmts_16(): if gdaltest.wmts_drv is None: - return 'skip' + pytest.skip() gdal.FileFromMemBuffer('/vsimem/wmts_16.xml', """<Capabilities> <Contents> @@ -1074,39 +892,23 @@ def wmts_16(): </Capabilities>""") ds = gdal.Open('WMTS:/vsimem/wmts_16.xml') - if ds is None: - gdaltest.post_reason('fail') - return 'fail' - if ds.RasterXSize != 512: - gdaltest.post_reason('fail') - print(ds.RasterXSize) - return 'fail' - if ds.RasterYSize != 256: - gdaltest.post_reason('fail') - print(ds.RasterYSize) - return 'fail' + assert ds is not None + assert ds.RasterXSize == 512 + assert ds.RasterYSize == 256 got_gt = ds.GetGeoTransform() expected_gt = (-90, 0.3515625, 0.0, 90.0, 0.0, -0.3515625) for i in range(6): - if abs(got_gt[i] - expected_gt[i]) > 1e-8: - gdaltest.post_reason('fail') - print(got_gt) - return 'fail' - if ds.GetProjectionRef().find('4326') < 0 or ds.GetProjectionRef().find('AXIS') >= 0: - gdaltest.post_reason('fail') - print(ds.GetProjectionRef()) - return 'fail' - - return 'success' + assert abs(got_gt[i] - expected_gt[i]) <= 1e-8 + assert ds.GetProjectionRef().find('4326') >= 0 and ds.GetProjectionRef().find('AXIS') < 0 ############################################################################### # AOI from layer BoundingBox -def wmts_17(): +def test_wmts_17(): if gdaltest.wmts_drv is None: - return 'skip' + pytest.skip() gdal.FileFromMemBuffer('/vsimem/wmts_17.xml', """<Capabilities> <Contents> @@ -1164,39 +966,23 @@ def wmts_17(): </Capabilities>""") ds = gdal.Open('WMTS:/vsimem/wmts_17.xml') - if ds is None: - gdaltest.post_reason('fail') - return 'fail' - if ds.RasterXSize != 512: - gdaltest.post_reason('fail') - print(ds.RasterXSize) - return 'fail' - if ds.RasterYSize != 256: - gdaltest.post_reason('fail') - print(ds.RasterYSize) - return 'fail' + assert ds is not None + assert ds.RasterXSize == 512 + assert ds.RasterYSize == 256 got_gt = ds.GetGeoTransform() expected_gt = (-90, 0.3515625, 0.0, 90.0, 0.0, -0.3515625) for i in range(6): - if abs(got_gt[i] - expected_gt[i]) > 1e-8: - gdaltest.post_reason('fail') - print(got_gt) - return 'fail' - if ds.GetProjectionRef().find('4326') < 0 or ds.GetProjectionRef().find('AXIS') >= 0: - gdaltest.post_reason('fail') - print(ds.GetProjectionRef()) - return 'fail' - - return 'success' + assert abs(got_gt[i] - expected_gt[i]) <= 1e-8 + assert ds.GetProjectionRef().find('4326') >= 0 and ds.GetProjectionRef().find('AXIS') < 0 ############################################################################### # AOI from TileMatrixSet BoundingBox -def wmts_18(): +def test_wmts_18(): if gdaltest.wmts_drv is None: - return 'skip' + pytest.skip() gdal.FileFromMemBuffer('/vsimem/wmts_18.xml', """<Capabilities> <Contents> @@ -1254,39 +1040,23 @@ def wmts_18(): </Capabilities>""") ds = gdal.Open('WMTS:/vsimem/wmts_18.xml') - if ds is None: - gdaltest.post_reason('fail') - return 'fail' - if ds.RasterXSize != 512: - gdaltest.post_reason('fail') - print(ds.RasterXSize) - return 'fail' - if ds.RasterYSize != 256: - gdaltest.post_reason('fail') - print(ds.RasterYSize) - return 'fail' + assert ds is not None + assert ds.RasterXSize == 512 + assert ds.RasterYSize == 256 got_gt = ds.GetGeoTransform() expected_gt = (-90, 0.3515625, 0.0, 90.0, 0.0, -0.3515625) for i in range(6): - if abs(got_gt[i] - expected_gt[i]) > 1e-8: - gdaltest.post_reason('fail') - print(got_gt) - return 'fail' - if ds.GetProjectionRef().find('4326') < 0 or ds.GetProjectionRef().find('AXIS') >= 0: - gdaltest.post_reason('fail') - print(ds.GetProjectionRef()) - return 'fail' - - return 'success' + assert abs(got_gt[i] - expected_gt[i]) <= 1e-8 + assert ds.GetProjectionRef().find('4326') >= 0 and ds.GetProjectionRef().find('AXIS') < 0 ############################################################################### # AOI from TileMatrixSetLimits -def wmts_19(): +def test_wmts_19(): if gdaltest.wmts_drv is None: - return 'skip' + pytest.skip() gdal.FileFromMemBuffer('/vsimem/wmts_19.xml', """<Capabilities> <Contents> @@ -1349,39 +1119,23 @@ def wmts_19(): </Capabilities>""") ds = gdal.Open('WMTS:/vsimem/wmts_19.xml') - if ds is None: - gdaltest.post_reason('fail') - return 'fail' - if ds.RasterXSize != 512: - gdaltest.post_reason('fail') - print(ds.RasterXSize) - return 'fail' - if ds.RasterYSize != 256: - gdaltest.post_reason('fail') - print(ds.RasterYSize) - return 'fail' + assert ds is not None + assert ds.RasterXSize == 512 + assert ds.RasterYSize == 256 got_gt = ds.GetGeoTransform() expected_gt = (-90, 0.3515625, 0.0, 90.0, 0.0, -0.3515625) for i in range(6): - if abs(got_gt[i] - expected_gt[i]) > 1e-8: - gdaltest.post_reason('fail') - print(got_gt) - return 'fail' - if ds.GetProjectionRef().find('4326') < 0 or ds.GetProjectionRef().find('AXIS') >= 0: - gdaltest.post_reason('fail') - print(ds.GetProjectionRef()) - return 'fail' - - return 'success' + assert abs(got_gt[i] - expected_gt[i]) <= 1e-8 + assert ds.GetProjectionRef().find('4326') >= 0 and ds.GetProjectionRef().find('AXIS') < 0 ############################################################################### # AOI from layer BoundingBox but restricted with TileMatrixSetLimits -def wmts_20(): +def test_wmts_20(): if gdaltest.wmts_drv is None: - return 'skip' + pytest.skip() gdal.FileFromMemBuffer('/vsimem/wmts_20.xml', """<Capabilities> <Contents> @@ -1448,39 +1202,23 @@ def wmts_20(): </Capabilities>""") ds = gdal.Open('WMTS:/vsimem/wmts_20.xml') - if ds is None: - gdaltest.post_reason('fail') - return 'fail' - if ds.RasterXSize != 512: - gdaltest.post_reason('fail') - print(ds.RasterXSize) - return 'fail' - if ds.RasterYSize != 256: - gdaltest.post_reason('fail') - print(ds.RasterYSize) - return 'fail' + assert ds is not None + assert ds.RasterXSize == 512 + assert ds.RasterYSize == 256 got_gt = ds.GetGeoTransform() expected_gt = (-90, 0.3515625, 0.0, 90.0, 0.0, -0.3515625) for i in range(6): - if abs(got_gt[i] - expected_gt[i]) > 1e-8: - gdaltest.post_reason('fail') - print(got_gt) - return 'fail' - if ds.GetProjectionRef().find('4326') < 0 or ds.GetProjectionRef().find('AXIS') >= 0: - gdaltest.post_reason('fail') - print(ds.GetProjectionRef()) - return 'fail' - - return 'success' + assert abs(got_gt[i] - expected_gt[i]) <= 1e-8 + assert ds.GetProjectionRef().find('4326') >= 0 and ds.GetProjectionRef().find('AXIS') < 0 ############################################################################### # Test ExtendBeyondDateLine -def wmts_21(): +def test_wmts_21(): if gdaltest.wmts_drv is None: - return 'skip' + pytest.skip() gdal.FileFromMemBuffer('/vsimem/wmts_21.xml', """<Capabilities> <Contents> @@ -1543,28 +1281,14 @@ def wmts_21(): </Capabilities>""") ds = gdal.Open('WMTS:/vsimem/wmts_21.xml,extendbeyonddateline=yes') - if ds is None: - gdaltest.post_reason('fail') - return 'fail' - if ds.RasterXSize != 512: - gdaltest.post_reason('fail') - print(ds.RasterXSize) - return 'fail' - if ds.RasterYSize != 256: - gdaltest.post_reason('fail') - print(ds.RasterYSize) - return 'fail' + assert ds is not None + assert ds.RasterXSize == 512 + assert ds.RasterYSize == 256 got_gt = ds.GetGeoTransform() expected_gt = (90, 0.3515625, 0.0, 0.0, 0.0, -0.3515625) for i in range(6): - if abs(got_gt[i] - expected_gt[i]) > 1e-8: - gdaltest.post_reason('fail') - print(got_gt) - return 'fail' - if ds.GetProjectionRef().find('4326') < 0 or ds.GetProjectionRef().find('AXIS') >= 0: - gdaltest.post_reason('fail') - print(ds.GetProjectionRef()) - return 'fail' + assert abs(got_gt[i] - expected_gt[i]) <= 1e-8 + assert ds.GetProjectionRef().find('4326') >= 0 and ds.GetProjectionRef().find('AXIS') < 0 tmp_ds = gdal.GetDriverByName('MEM').Create('', 256, 256, 4) for i in range(4): @@ -1576,24 +1300,18 @@ def wmts_21(): tmp_ds.GetRasterBand(i + 1).Fill(128) tmp0_ds = gdal.GetDriverByName('PNG').CreateCopy('/vsimem/wmts_21/default_style/tms/GoogleCRS84Quad:2/1/0.png', tmp_ds) - if ds.GetRasterBand(1).ReadRaster(0, 0, 256, 256) != tmp3_ds.GetRasterBand(1).ReadRaster(0, 0, 256, 256): - gdaltest.post_reason('fail') - return 'fail' - - if ds.GetRasterBand(1).ReadRaster(256, 0, 256, 256) != tmp0_ds.GetRasterBand(1).ReadRaster(0, 0, 256, 256): - gdaltest.post_reason('fail') - return 'fail' + assert ds.GetRasterBand(1).ReadRaster(0, 0, 256, 256) == tmp3_ds.GetRasterBand(1).ReadRaster(0, 0, 256, 256) - return 'success' + assert ds.GetRasterBand(1).ReadRaster(256, 0, 256, 256) == tmp0_ds.GetRasterBand(1).ReadRaster(0, 0, 256, 256) ############################################################################### # Test when WGS84BoundingBox is a densified reprojection of the tile matrix bbox -def wmts_22(): +def test_wmts_22(): if gdaltest.wmts_drv is None: - return 'skip' + pytest.skip() gdal.FileFromMemBuffer('/vsimem/wmts_22.xml', """<Capabilities> <Contents> @@ -1633,30 +1351,14 @@ def wmts_22(): </Capabilities>""") ds = gdal.Open('WMTS:/vsimem/wmts_22.xml') - if ds is None: - gdaltest.post_reason('fail') - return 'fail' - if ds.RasterXSize != 2097152: - gdaltest.post_reason('fail') - print(ds.RasterXSize) - return 'fail' - if ds.RasterYSize != 2097152: - gdaltest.post_reason('fail') - print(ds.RasterYSize) - return 'fail' + assert ds is not None + assert ds.RasterXSize == 2097152 + assert ds.RasterYSize == 2097152 got_gt = ds.GetGeoTransform() expected_gt = (-548576.0, 1.0000000000004, 0.0, 8388608.0, 0.0, -1.0000000000004) for i in range(6): - if abs(got_gt[i] - expected_gt[i]) > 1e-8: - gdaltest.post_reason('fail') - print(got_gt) - return 'fail' - if ds.GetProjectionRef().find('3067') < 0: - gdaltest.post_reason('fail') - print(ds.GetProjectionRef()) - return 'fail' - - return 'success' + assert abs(got_gt[i] - expected_gt[i]) <= 1e-8 + assert ds.GetProjectionRef().find('3067') >= 0 ############################################################################### # @@ -1664,7 +1366,7 @@ def wmts_22(): def wmts_23(imagetype, expected_cs): if gdaltest.wmts_drv is None: - return 'skip' + pytest.skip() inputXml = '/vsimem/' + imagetype + '.xml' serviceUrl = '/vsimem/wmts_23/' + imagetype @@ -1697,63 +1399,47 @@ def wmts_23(imagetype, expected_cs): </Capabilities>""") tmp_ds = gdal.Open('data/wms/' + imagetype + '.png') - if tmp_ds is None: - gdaltest.post_reason('fail - cannot open tmp_ds') - return 'fail' + assert tmp_ds is not None, 'fail - cannot open tmp_ds' tile0_ds = gdal.GetDriverByName('PNG').CreateCopy(serviceUrl + '/0/0/0.png', tmp_ds) - if tile0_ds is None: - gdaltest.post_reason('fail - cannot create tile0') - return 'fail' + assert tile0_ds is not None, 'fail - cannot create tile0' ds = gdal.Open('WMTS:' + inputXml) - if ds is None: - gdaltest.post_reason('fail') - return 'fail' - - if ds.RasterXSize != 128: - gdaltest.post_reason('fail') - print(ds.RasterXSize) - return 'fail' - if ds.RasterYSize != 128: - gdaltest.post_reason('fail') - print(ds.RasterYSize) - return 'fail' + assert ds is not None + + assert ds.RasterXSize == 128 + assert ds.RasterYSize == 128 for i in range(4): cs = ds.GetRasterBand(i + 1).Checksum() - if cs != expected_cs[i]: - gdaltest.post_reason('fail') - print(cs) - return 'fail' - - return 'success' + assert cs == expected_cs[i] + -def wmts_23_gray(): +def test_wmts_23_gray(): return wmts_23('gray', [60137, 60137, 60137, 4428]) -def wmts_23_grayalpha(): +def test_wmts_23_grayalpha(): return wmts_23('gray+alpha', [39910, 39910, 39910, 63180]) -def wmts_23_pal(): +def test_wmts_23_pal(): return wmts_23('pal', [62950, 59100, 63864, 453]) -def wmts_23_rgb(): +def test_wmts_23_rgb(): return wmts_23('rgb', [1020, 3665, 6180, 4428]) -def wmts_23_rgba(): +def test_wmts_23_rgba(): return wmts_23('rgba', [65530, 51449, 1361, 59291]) -def wmts_invalid_global_to_tm_reprojection(): +def test_wmts_invalid_global_to_tm_reprojection(): if gdaltest.wmts_drv is None: - return 'skip' + pytest.skip() inputXml = '/vsimem/wmts_invalid_global_to_tm_reprojection.xml' gdal.FileFromMemBuffer(inputXml, """<?xml version="1.0"?> @@ -1799,22 +1485,19 @@ def wmts_invalid_global_to_tm_reprojection(): </Capabilities>""") ds = gdal.Open('WMTS:' + inputXml) - if ds.RasterXSize != 512 or ds.RasterYSize != 1024: - return 'fail' + assert ds.RasterXSize == 512 and ds.RasterYSize == 1024 ds = None gdal.Unlink(inputXml) - return 'success' - ############################################################################### # -def wmts_check_no_overflow_zoom_level(): +def test_wmts_check_no_overflow_zoom_level(): if gdaltest.wmts_drv is None: - return 'skip' + pytest.skip() inputXml = '/vsimem/wmts_check_no_overflow_zoom_level.xml' gdal.FileFromMemBuffer(inputXml, """<?xml version="1.0"?> @@ -2067,21 +1750,13 @@ def wmts_check_no_overflow_zoom_level(): </Capabilities>""") ds = gdal.Open(inputXml) - if ds.RasterXSize != 1073741766 or ds.RasterYSize != 1070224430: - gdaltest.post_reason('fail') - print(ds.RasterXSize, ds.RasterYSize) - return 'fail' + assert ds.RasterXSize == 1073741766 and ds.RasterYSize == 1070224430 count_levels = 1 + ds.GetRasterBand(1).GetOverviewCount() - if count_levels != 23: # there are 24 in total, but we discard the one labelled 23 - gdaltest.post_reason('fail') - print(count_levels) - return 'fail' + assert count_levels == 23 ds = None gdal.Unlink(inputXml) - return 'success' - ############################################################################### @@ -2101,10 +1776,10 @@ def wmts_CleanCache(): # -def wmts_cleanup(): +def test_wmts_cleanup(): if gdaltest.wmts_drv is None: - return 'skip' + pytest.skip() gdal.SetConfigOption('CPL_CURL_ENABLE_VSIMEM', None) gdal.SetConfigOption('GDAL_DEFAULT_WMS_CACHE_PATH', None) @@ -2121,46 +1796,6 @@ def wmts_cleanup(): except OSError: pass - return 'success' - - -gdaltest_list = [ - wmts_1, - wmts_2, - wmts_3, - wmts_4, - wmts_5, - wmts_6, - wmts_7, - wmts_8, - wmts_9, - wmts_10, - wmts_11, - wmts_12, - wmts_12bis, - wmts_13, - wmts_14, - wmts_15, - wmts_16, - wmts_17, - wmts_18, - wmts_19, - wmts_20, - wmts_21, - wmts_22, - wmts_23_gray, - wmts_23_grayalpha, - wmts_23_pal, - wmts_23_rgb, - wmts_23_rgba, - wmts_invalid_global_to_tm_reprojection, - wmts_check_no_overflow_zoom_level, - wmts_cleanup] - -if __name__ == '__main__': - - gdaltest.setup_run('wmts') - - gdaltest.run_tests(gdaltest_list) - - sys.exit(gdaltest.summarize()) + + + diff --git a/autotest/gdrivers/xmp.py b/autotest/gdrivers/xmp.py index c1c559bf7daf..8e956bc2c3a3 100755 --- a/autotest/gdrivers/xmp.py +++ b/autotest/gdrivers/xmp.py @@ -29,11 +29,10 @@ # DEALINGS IN THE SOFTWARE. ############################################################################### -import sys +import pytest from osgeo import gdal -sys.path.append('../pymod') import gdaltest @@ -41,94 +40,72 @@ # -class TestXMPRead(object): - def __init__(self, drivername, filename, expect_xmp): - self.drivername = drivername - self.filename = filename - self.expect_xmp = expect_xmp - - def test(self): - drv = gdal.GetDriverByName(self.drivername) - if drv is None: - return 'skip' - - if self.drivername == 'PDF': - md = drv.GetMetadata() - if 'HAVE_POPPLER' not in md and 'HAVE_PODOFO' not in md: - return 'skip' - - # 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 self.filename.find('.jp2') >= 0: - gdaltest.deregister_all_jpeg2000_drivers_but(self.drivername) - - ret = 'success' - ds = gdal.Open(self.filename) - if ds is None: - # Old libwebp don't support VP8X containers - if self.filename == 'data/rgbsmall_with_xmp.webp': - ret = 'skip' - else: - gdaltest.post_reason('open failed') - ret = 'failure' +lst = [ + ["GTiff", "data/byte_with_xmp.tif", True], + ["GTiff", "data/byte.tif", False], + ["GIF", "data/byte_with_xmp.gif", True], + ["BIGGIF", "data/fakebig.gif", False], + ["JPEG", "data/byte_with_xmp.jpg", True], + ["JPEG", "data/rgbsmall_rgb.jpg", False], + ["PNG", "data/byte_with_xmp.png", True], + ["PNG", "data/test.png", False], + ["JP2ECW", "data/byte_with_xmp.jp2", True], + ["JP2ECW", "data/byte.jp2", False], + ["JP2MrSID", "data/byte_with_xmp.jp2", True], + ["JP2MrSID", "data/byte.jp2", False], + ["JPEG2000", "data/byte_with_xmp.jp2", True], + ["JPEG2000", "data/byte.jp2", False], + ["JP2OpenJPEG", "data/byte_with_xmp.jp2", True], + ["JP2OpenJPEG", "data/byte.jp2", False], + ["JP2KAK", "data/byte_with_xmp.jp2", True], + ["JP2KAK", "data/byte.jp2", False], + ["PDF", "data/adobe_style_geospatial_with_xmp.pdf", True], + ["PDF", "data/adobe_style_geospatial.pdf", False], + ["WEBP", "data/rgbsmall_with_xmp.webp", True], + ["WEBP", "data/rgbsmall.webp", False], +] + + +@pytest.mark.parametrize( + 'drivername,filename,expect_xmp', + lst, + ids=[ + "xmp_read_%s_%s" % (drivername, str(expect_xmp)) + for (drivername, filename, expect_xmp) in lst + ] +) +def test_xmp(drivername, filename, expect_xmp): + drv = gdal.GetDriverByName(drivername) + if drv is None: + pytest.skip() + + if drivername == 'PDF': + md = drv.GetMetadata() + if 'HAVE_POPPLER' not in md and 'HAVE_PODOFO' not in md: + pytest.skip() + + # 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 filename.find('.jp2') >= 0: + gdaltest.deregister_all_jpeg2000_drivers_but(drivername) + + try: + ds = gdal.Open(filename) + if filename == 'data/rgbsmall_with_xmp.webp': + if ds is None: + pytest.skip("Old libwebp don't support VP8X containers") else: - xmp_md = ds.GetMetadata('xml:XMP') - if ds.GetDriver().ShortName != self.drivername: - gdaltest.post_reason('opened with wrong driver') - print(ds.GetDriver().ShortName) - ret = 'failure' - elif self.expect_xmp and not xmp_md: - gdaltest.post_reason('did not find xml:XMP metadata') - ret = 'failure' - elif self.expect_xmp and 'xml:XMP' not in ds.GetMetadataDomainList(): - gdaltest.post_reason('did not find xml:XMP metadata domain') - ret = 'failure' - elif (not self.expect_xmp) and xmp_md: - gdaltest.post_reason('found unexpected xml:XMP metadata') - ret = 'failure' - ds = None + assert ds is not None, 'open failed' - if self.filename.find('.jp2') >= 0: - gdaltest.reregister_all_jpeg2000_drivers() + xmp_md = ds.GetMetadata('xml:XMP') + + assert ds.GetDriver().ShortName == drivername, 'opened with wrong driver' + assert not (expect_xmp and not xmp_md), 'did not find xml:XMP metadata' + assert not (expect_xmp and 'xml:XMP' not in ds.GetMetadataDomainList()), 'did not find xml:XMP metadata domain' + assert expect_xmp or not xmp_md, 'found unexpected xml:XMP metadata' - return ret - - -gdaltest_list = [] - -lst = [["GTiff", "data/byte_with_xmp.tif", True], - ["GTiff", "data/byte.tif", False], - ["GIF", "data/byte_with_xmp.gif", True], - ["BIGGIF", "data/fakebig.gif", False], - ["JPEG", "data/byte_with_xmp.jpg", True], - ["JPEG", "data/rgbsmall_rgb.jpg", False], - ["PNG", "data/byte_with_xmp.png", True], - ["PNG", "data/test.png", False], - ["JP2ECW", "data/byte_with_xmp.jp2", True], - ["JP2ECW", "data/byte.jp2", False], - ["JP2MrSID", "data/byte_with_xmp.jp2", True], - ["JP2MrSID", "data/byte.jp2", False], - ["JPEG2000", "data/byte_with_xmp.jp2", True], - ["JPEG2000", "data/byte.jp2", False], - ["JP2OpenJPEG", "data/byte_with_xmp.jp2", True], - ["JP2OpenJPEG", "data/byte.jp2", False], - ["JP2KAK", "data/byte_with_xmp.jp2", True], - ["JP2KAK", "data/byte.jp2", False], - ["PDF", "data/adobe_style_geospatial_with_xmp.pdf", True], - ["PDF", "data/adobe_style_geospatial.pdf", False], - ["WEBP", "data/rgbsmall_with_xmp.webp", True], - ["WEBP", "data/rgbsmall.webp", False], - ] - -for drivername, filename, expect_xmp in lst: - ut = TestXMPRead(drivername, filename, expect_xmp) - gdaltest_list.append((ut.test, "xmp_read_%s_%s" % (drivername, "true" if expect_xmp is True else "false"))) - -if __name__ == '__main__': - - gdaltest.setup_run('xmp') - - gdaltest.run_tests(gdaltest_list) - - sys.exit(gdaltest.summarize()) + ds = None + finally: + if filename.find('.jp2') >= 0: + gdaltest.reregister_all_jpeg2000_drivers() diff --git a/autotest/gdrivers/xpm.py b/autotest/gdrivers/xpm.py index 929e763942a2..7564daa68eb6 100755 --- a/autotest/gdrivers/xpm.py +++ b/autotest/gdrivers/xpm.py @@ -28,57 +28,35 @@ # DEALINGS IN THE SOFTWARE. ############################################################################### -import sys -from osgeo import gdal -sys.path.append('../pymod') +import pytest -import gdaltest +from osgeo import gdal +import gdaltest -############################################################################### -# -class TestXPM(object): - def __init__(self, downloadURL, fileName, checksum, download_size): - self.downloadURL = downloadURL - self.fileName = fileName - self.checksum = checksum - self.download_size = download_size - def test(self): - if not gdaltest.download_file(self.downloadURL + '/' + self.fileName, self.fileName, self.download_size): - return 'skip' +xpm_list = [('http://download.osgeo.org/gdal/data/xpm', 'utm.xpm', 44206, -1)] - ds = gdal.Open('tmp/cache/' + self.fileName) - if ds.GetRasterBand(1).Checksum() != self.checksum: - gdaltest.post_reason('Bad checksum. Expected %d, got %d' % (self.checksum, ds.GetRasterBand(1).Checksum())) - return 'fail' +@pytest.mark.parametrize( + 'downloadURL,fileName,checksum,download_size', + xpm_list, + ids=[item[1] for item in xpm_list], +) +def test_xpm(downloadURL, fileName, checksum, download_size): + if not gdaltest.download_file(downloadURL + '/' + fileName, fileName, download_size): + pytest.skip() - return 'success' + ds = gdal.Open('tmp/cache/' + fileName) + assert ds.GetRasterBand(1).Checksum() == checksum, 'Bad checksum. Expected %d, got %d' % (checksum, ds.GetRasterBand(1).Checksum()) -def xpm_1(): +def test_xpm_1(): tst = gdaltest.GDALTest('XPM', 'byte.tif', 1, 4583) return tst.testCreateCopy(vsimem=1, check_minmax=False) -gdaltest_list = [] - -xpm_list = [('http://download.osgeo.org/gdal/data/xpm', 'utm.xpm', 44206, -1), - ] - -for item in xpm_list: - ut = TestXPM(item[0], item[1], item[2], item[3]) - gdaltest_list.append((ut.test, item[1])) - -gdaltest_list.append(xpm_1) - -if __name__ == '__main__': - - gdaltest.setup_run('xpm') - gdaltest.run_tests(gdaltest_list) - sys.exit(gdaltest.summarize()) diff --git a/autotest/gdrivers/xyz.py b/autotest/gdrivers/xyz.py index e6ffad6874a4..8609c423da64 100755 --- a/autotest/gdrivers/xyz.py +++ b/autotest/gdrivers/xyz.py @@ -29,11 +29,9 @@ # DEALINGS IN THE SOFTWARE. ############################################################################### -import sys import struct from osgeo import gdal -sys.path.append('../pymod') import gdaltest @@ -41,7 +39,7 @@ # Test CreateCopy() of byte.tif -def xyz_1(): +def test_xyz_1(): tst = gdaltest.GDALTest('XYZ', 'byte.tif', 1, 4672) return tst.testCreateCopy(vsimem=1, check_gt=(-67.00041667, 0.00083333, 0.0, 50.000416667, 0.0, -0.00083333)) @@ -50,7 +48,7 @@ def xyz_1(): # Test CreateCopy() of float.img -def xyz_2(): +def test_xyz_2(): src_ds = gdal.Open('data/float.img') ds = gdal.GetDriverByName('XYZ').CreateCopy('tmp/float.xyz', src_ds, options=['COLUMN_SEPARATOR=,', 'ADD_HEADER_LINE=YES']) @@ -58,16 +56,13 @@ def xyz_2(): expected_cs = src_ds.GetRasterBand(1).Checksum() ds = None gdal.GetDriverByName('XYZ').Delete('tmp/float.xyz') - if got_cs != expected_cs and got_cs != 24387: - print(got_cs) - return 'fail' - return 'success' + assert got_cs == expected_cs or got_cs == 24387 ############################################################################### # Test random access to lines of imagery -def xyz_3(): +def test_xyz_3(): content = """Y X Z 0 0 65 @@ -86,24 +81,15 @@ def xyz_3(): gdal.FileFromMemBuffer('/vsimem/grid.xyz', content) ds = gdal.Open('/vsimem/grid.xyz') buf = ds.ReadRaster(0, 2, 2, 1) - if struct.unpack('B' * 2, buf) != (69, 70): - print(buf) - return 'fail' + assert struct.unpack('B' * 2, buf) == (69, 70) buf = ds.ReadRaster(0, 1, 2, 1) - if struct.unpack('B' * 2, buf) != (67, 68): - print(buf) - return 'fail' + assert struct.unpack('B' * 2, buf) == (67, 68) buf = ds.ReadRaster(0, 0, 2, 1) - if struct.unpack('B' * 2, buf) != (65, 66): - print(buf) - return 'fail' + assert struct.unpack('B' * 2, buf) == (65, 66) buf = ds.ReadRaster(0, 2, 2, 1) - if struct.unpack('B' * 2, buf) != (69, 70): - print(buf) - return 'fail' + assert struct.unpack('B' * 2, buf) == (69, 70) ds = None gdal.Unlink('/vsimem/grid.xyz') - return 'success' ############################################################################### @@ -115,7 +101,7 @@ def xyz_4_checkline(ds, i, expected_bytes): return struct.unpack('B' * ds.RasterXSize, buf) == expected_bytes -def xyz_4(): +def test_xyz_4(): content = """ 440750.001 3751290 1 @@ -134,34 +120,21 @@ def xyz_4(): got_gt = ds.GetGeoTransform() expected_gt = (440660.0, 60.0, 0.0, 3751350.0, 0.0, -120.0) for i in range(6): - if abs(got_gt[i] - expected_gt[i]) > 1e-5: - gdaltest.post_reason('fail') - print(got_gt) - print(expected_gt) - return 'fail' - - if ds.GetRasterBand(1).GetMinimum() != 1: - gdaltest.post_reason('fail') - return 'fail' - if ds.GetRasterBand(1).GetMaximum() != 7: - gdaltest.post_reason('fail') - return 'fail' - if ds.GetRasterBand(1).GetNoDataValue() != 0: - gdaltest.post_reason('fail') - return 'fail' + assert abs(got_gt[i] - expected_gt[i]) <= 1e-5 + + assert ds.GetRasterBand(1).GetMinimum() == 1 + assert ds.GetRasterBand(1).GetMaximum() == 7 + assert ds.GetRasterBand(1).GetNoDataValue() == 0 for i in [0, 1, 2, 1, 0, 2, 0, 2, 0, 1, 2]: - if not xyz_4_checkline(ds, i, expected[i]): - gdaltest.post_reason('fail') - return 'fail' + assert xyz_4_checkline(ds, i, expected[i]) ds = None gdal.Unlink('/vsimem/grid.xyz') - return 'success' ############################################################################### # Test XYZ with only integral values and comma field separator -def xyz_5(): +def test_xyz_5(): content = """0,1,100 0.5,1,100 @@ -173,28 +146,21 @@ def xyz_5(): gdal.FileFromMemBuffer('/vsimem/grid.xyz', content) ds = gdal.Open('/vsimem/grid.xyz') - if ds.RasterXSize != 3 or ds.RasterYSize != 2: - gdaltest.post_reason('fail') - return 'fail' + assert ds.RasterXSize == 3 and ds.RasterYSize == 2 got_gt = ds.GetGeoTransform() expected_gt = (-0.25, 0.5, 0.0, 0.5, 0.0, 1.0) ds = None gdal.Unlink('/vsimem/grid.xyz') for i in range(6): - if abs(got_gt[i] - expected_gt[i]) > 1e-5: - gdaltest.post_reason('fail') - print(got_gt) - print(expected_gt) - return 'fail' - - return 'success' + assert abs(got_gt[i] - expected_gt[i]) <= 1e-5 + ############################################################################### # Test XYZ with comma decimal separator and semi-colon field separator -def xyz_6(): +def test_xyz_6(): content = """0;1;100 0,5;1;100 @@ -206,28 +172,21 @@ def xyz_6(): gdal.FileFromMemBuffer('/vsimem/grid.xyz', content) ds = gdal.Open('/vsimem/grid.xyz') - if ds.RasterXSize != 3 or ds.RasterYSize != 2: - gdaltest.post_reason('fail') - return 'fail' + assert ds.RasterXSize == 3 and ds.RasterYSize == 2 got_gt = ds.GetGeoTransform() expected_gt = (-0.25, 0.5, 0.0, 0.5, 0.0, 1.0) ds = None gdal.Unlink('/vsimem/grid.xyz') for i in range(6): - if abs(got_gt[i] - expected_gt[i]) > 1e-5: - gdaltest.post_reason('fail') - print(got_gt) - print(expected_gt) - return 'fail' - - return 'success' + assert abs(got_gt[i] - expected_gt[i]) <= 1e-5 + ############################################################################### # Test XYZ with not completely equal stepX and stepY -def xyz_7(): +def test_xyz_7(): content = """y x z 51.500000 354.483333 54.721 @@ -249,9 +208,7 @@ def xyz_7(): gdal.FileFromMemBuffer('/vsimem/grid.xyz', content) ds = gdal.Open('/vsimem/grid.xyz') - if ds.RasterXSize != 3 or ds.RasterYSize != 5: - gdaltest.post_reason('fail') - return 'fail' + assert ds.RasterXSize == 3 and ds.RasterYSize == 5 got_gt = ds.GetGeoTransform() expected_gt = (354.46666625, 0.0333335, 0.0, 51.5125, 0.0, -0.025) cs = ds.GetRasterBand(1).Checksum() @@ -259,24 +216,15 @@ def xyz_7(): gdal.Unlink('/vsimem/grid.xyz') for i in range(6): - if abs(got_gt[i] - expected_gt[i]) > 1e-8: - gdaltest.post_reason('fail') - print(got_gt) - print(expected_gt) - return 'fail' + assert abs(got_gt[i] - expected_gt[i]) <= 1e-8 - if cs != 146: - gdaltest.post_reason('fail') - print(cs) - return 'fail' - - return 'success' + assert cs == 146 ############################################################################### # Test particular case of XYZ file with missed samples (#6934) -def xyz_8(): +def test_xyz_8(): content = """0 500 50 750 500 100 @@ -287,44 +235,19 @@ def xyz_8(): gdal.FileFromMemBuffer('/vsimem/grid.xyz', content) ds = gdal.Open('/vsimem/grid.xyz') - if ds.RasterXSize != 4 or ds.RasterYSize != 2: - gdaltest.post_reason('fail') - return 'fail' + assert ds.RasterXSize == 4 and ds.RasterYSize == 2 cs = ds.GetRasterBand(1).Checksum() ds = None gdal.Unlink('/vsimem/grid.xyz') - if cs != 35: - gdaltest.post_reason('fail') - print(cs) - return 'fail' - - return 'success' + assert cs == 35 ############################################################################### # Cleanup -def xyz_cleanup(): - - return 'success' - - -gdaltest_list = [ - xyz_1, - xyz_2, - xyz_3, - xyz_4, - xyz_5, - xyz_6, - xyz_7, - xyz_8, - xyz_cleanup] - -if __name__ == '__main__': +def test_xyz_cleanup(): - gdaltest.setup_run('xyz') + pass - gdaltest.run_tests(gdaltest_list) - sys.exit(gdaltest.summarize()) diff --git a/autotest/gdrivers/zmap.py b/autotest/gdrivers/zmap.py index 9fdeba5eeb4e..e39bcc745a06 100755 --- a/autotest/gdrivers/zmap.py +++ b/autotest/gdrivers/zmap.py @@ -28,9 +28,7 @@ # DEALINGS IN THE SOFTWARE. ############################################################################### -import sys -sys.path.append('../pymod') import gdaltest @@ -38,20 +36,10 @@ # Test CreateCopy() of byte.tif -def zmap_1(): +def test_zmap_1(): tst = gdaltest.GDALTest('ZMap', 'byte.tif', 1, 4672) return tst.testCreateCopy(vsimem=1, check_gt=(-67.00041667, 0.00083333, 0.0, 50.000416667, 0.0, -0.00083333)) -gdaltest_list = [ - zmap_1 -] -if __name__ == '__main__': - - gdaltest.setup_run('zmap') - - gdaltest.run_tests(gdaltest_list) - - sys.exit(gdaltest.summarize()) diff --git a/autotest/gnm/__init__.py b/autotest/gnm/__init__.py new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/autotest/gnm/gnm_test.py b/autotest/gnm/gnm_test.py index 09b18c007c70..4224f711b0e6 100755 --- a/autotest/gnm/gnm_test.py +++ b/autotest/gnm/gnm_test.py @@ -32,21 +32,19 @@ ############################################################################### import os -import sys import shutil -sys.path.append('../pymod') -import gdaltest from osgeo import gdal from osgeo import gnm +import pytest ############################################################################### # Create file base network -def gnm_filenetwork_create(): +def test_gnm_filenetwork_create(): try: shutil.rmtree('tmp/test_gnm') @@ -59,64 +57,48 @@ def gnm_filenetwork_create(): ogrtest.drv = gdal.GetDriverByName('GNMFile') if ogrtest.drv is None: - return 'skip' + pytest.skip() ds = ogrtest.drv.Create('tmp/', 0, 0, 0, gdal.GDT_Unknown, options=['net_name=test_gnm', 'net_description=Test file based GNM', 'net_srs=EPSG:4326']) # cast to GNM dn = gnm.CastToNetwork(ds) - if dn is None: - gdaltest.post_reason('fail') - return 'fail' - if dn.GetVersion() != 100: - gdaltest.post_reason('GNM: Check GNM version failed') - return 'fail' - if dn.GetName() != 'test_gnm': - gdaltest.post_reason('GNM: Check GNM name failed') - return 'fail' - if dn.GetDescription() != 'Test file based GNM': - gdaltest.post_reason('GNM: Check GNM description failed') - return 'fail' + assert dn is not None + assert dn.GetVersion() == 100, 'GNM: Check GNM version failed' + assert dn.GetName() == 'test_gnm', 'GNM: Check GNM name failed' + assert dn.GetDescription() == 'Test file based GNM', \ + 'GNM: Check GNM description failed' dn = None ogrtest.have_gnm = 1 - return 'success' ############################################################################### # Open file base network -def gnm_filenetwork_open(): +def test_gnm_filenetwork_open(): if not ogrtest.have_gnm: - return 'skip' + pytest.skip() ds = gdal.OpenEx('tmp/test_gnm') # cast to GNM dn = gnm.CastToNetwork(ds) - if dn is None: - gdaltest.post_reason('fail') - return 'fail' - if dn.GetVersion() != 100: - gdaltest.post_reason('GNM: Check GNM version failed') - return 'fail' - if dn.GetName() != 'test_gnm': - gdaltest.post_reason('GNM: Check GNM name failed') - return 'fail' - if dn.GetDescription() != 'Test file based GNM': - gdaltest.post_reason('GNM: Check GNM description failed') - return 'fail' + assert dn is not None + assert dn.GetVersion() == 100, 'GNM: Check GNM version failed' + assert dn.GetName() == 'test_gnm', 'GNM: Check GNM name failed' + assert dn.GetDescription() == 'Test file based GNM', \ + 'GNM: Check GNM description failed' dn = None - return 'success' ############################################################################### # Import layers into file base network -def gnm_import(): +def test_gnm_import(): if not ogrtest.have_gnm: - return 'skip' + pytest.skip() ds = gdal.OpenEx('tmp/test_gnm') @@ -124,9 +106,7 @@ def gnm_import(): dspipes = gdal.OpenEx('data/pipes.shp', gdal.OF_VECTOR) lyrpipes = dspipes.GetLayerByIndex(0) new_lyr = ds.CopyLayer(lyrpipes, 'pipes') - if new_lyr is None: - gdaltest.post_reason('failed to import pipes') - return 'fail' + assert new_lyr is not None, 'failed to import pipes' dspipes = None new_lyr = None @@ -134,70 +114,54 @@ def gnm_import(): dswells = gdal.OpenEx('data/wells.shp', gdal.OF_VECTOR) lyrwells = dswells.GetLayerByIndex(0) new_lyr = ds.CopyLayer(lyrwells, 'wells') - if new_lyr is None: - gdaltest.post_reason('failed to import wells') - return 'fail' + assert new_lyr is not None, 'failed to import wells' dswells = None new_lyr = None - if ds.GetLayerCount() != 2: - gdaltest.post_reason('expected 2 layers') - return 'fail' + assert ds.GetLayerCount() == 2, 'expected 2 layers' ds = None - return 'success' ############################################################################### # autoconnect -def gnm_autoconnect(): +def test_gnm_autoconnect(): if not ogrtest.have_gnm: - return 'skip' + pytest.skip() ds = gdal.OpenEx('tmp/test_gnm') dgn = gnm.CastToGenericNetwork(ds) - if dgn is None: - gdaltest.post_reason('cast to GNMGenericNetwork failed') - return 'fail' + assert dgn is not None, 'cast to GNMGenericNetwork failed' ret = dgn.ConnectPointsByLines(['pipes', 'wells'], 0.000001, 1, 1, gnm.GNM_EDGE_DIR_BOTH) - if ret != 0: - gdaltest.post_reason('failed to connect') - return 'fail' + assert ret == 0, 'failed to connect' dgn = None - return 'success' ############################################################################### # Dijkstra shortest path -def gnm_graph_dijkstra(): +def test_gnm_graph_dijkstra(): if not ogrtest.have_gnm: - return 'skip' + pytest.skip() ds = gdal.OpenEx('tmp/test_gnm') dn = gnm.CastToNetwork(ds) - if dn is None: - gdaltest.post_reason('cast to GNMNetwork failed') - return 'fail' + assert dn is not None, 'cast to GNMNetwork failed' lyr = dn.GetPath(61, 50, gnm.GATDijkstraShortestPath) - if lyr is None: - gdaltest.post_reason('failed to get path') - return 'fail' + assert lyr is not None, 'failed to get path' if lyr.GetFeatureCount() == 0: dn.ReleaseResultSet(lyr) - gdaltest.post_reason('failed to get path') - return 'fail' + pytest.fail('failed to get path') dn.ReleaseResultSet(lyr) dn = None - return 'success' import ogrtest @@ -205,96 +169,63 @@ def gnm_graph_dijkstra(): # KShortest Paths -def gnm_graph_kshortest(): +def test_gnm_graph_kshortest(): if not ogrtest.have_gnm: - return 'skip' + pytest.skip() ds = gdal.OpenEx('tmp/test_gnm') dn = gnm.CastToNetwork(ds) - if dn is None: - gdaltest.post_reason('cast to GNMNetwork failed') - return 'fail' + assert dn is not None, 'cast to GNMNetwork failed' lyr = dn.GetPath(61, 50, gnm.GATKShortestPath, options=['num_paths=3']) - if lyr is None: - gdaltest.post_reason('failed to get path') - return 'fail' + assert lyr is not None, 'failed to get path' if lyr.GetFeatureCount() < 20: dn.ReleaseResultSet(lyr) - gdaltest.post_reason('failed to get path') - return 'fail' + pytest.fail('failed to get path') dn.ReleaseResultSet(lyr) dn = None - return 'success' ############################################################################### # ConnectedComponents -def gnm_graph_connectedcomponents(): +def test_gnm_graph_connectedcomponents(): if not ogrtest.have_gnm: - return 'skip' + pytest.skip() ds = gdal.OpenEx('tmp/test_gnm') dn = gnm.CastToNetwork(ds) - if dn is None: - gdaltest.post_reason('cast to GNMNetwork failed') - return 'fail' + assert dn is not None, 'cast to GNMNetwork failed' lyr = dn.GetPath(61, 50, gnm.GATConnectedComponents) - if lyr is None: - gdaltest.post_reason('failed to get path') - return 'fail' + assert lyr is not None, 'failed to get path' if lyr.GetFeatureCount() == 0: dn.ReleaseResultSet(lyr) - gdaltest.post_reason('failed to get path') - return 'fail' + pytest.fail('failed to get path') dn.ReleaseResultSet(lyr) dn = None - return 'success' ############################################################################### # Network deleting -def gnm_delete(): +def test_gnm_delete(): if not ogrtest.have_gnm: - return 'skip' + pytest.skip() gdal.GetDriverByName('GNMFile').Delete('tmp/test_gnm') - try: + with pytest.raises(OSError, message='Expected delete tmp/test_gnm'): os.stat('tmp/test_gnm') - gdaltest.post_reason('Expected delete tmp/test_gnm') - return 'fail' - except OSError: - pass - - return 'success' - - -gdaltest_list = [ - gnm_filenetwork_create, - gnm_filenetwork_open, - gnm_import, - gnm_autoconnect, - gnm_graph_dijkstra, - gnm_graph_kshortest, - gnm_graph_connectedcomponents, - gnm_delete -] - -if __name__ == '__main__': + - gdaltest.setup_run('gnm_test') + - gdaltest.run_tests(gdaltest_list) - sys.exit(gdaltest.summarize()) diff --git a/autotest/kml_generate_test_files.py b/autotest/kml_generate_test_files.py index 8fc14f0dda42..57d2b9b151e1 100644 --- a/autotest/kml_generate_test_files.py +++ b/autotest/kml_generate_test_files.py @@ -355,11 +355,4 @@ def generate_kmlsuperoverlay(filename): src_ds = None -gdaltest_list = [] -if __name__ == '__main__': - - generate_libkml('test_ogrlibkml.kml') - generate_libkml('test_ogrlibkml.kmz') - generate_libkml_update('test_ogrlibkml_update.kml') - generate_kmlsuperoverlay('test_superoverlay.kmz') diff --git a/autotest/ogr/__init__.py b/autotest/ogr/__init__.py new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/autotest/ogr/ogr_arcgen.py b/autotest/ogr/ogr_arcgen.py index 638634b7b8ce..8ee14b5c00ba 100755 --- a/autotest/ogr/ogr_arcgen.py +++ b/autotest/ogr/ogr_arcgen.py @@ -28,234 +28,160 @@ # DEALINGS IN THE SOFTWARE. ############################################################################### -import sys -sys.path.append('../pymod') -import gdaltest import ogrtest from osgeo import ogr +import pytest ############################################################################### # Read points -def ogr_arcgen_points(): +def test_ogr_arcgen_points(): ds = ogr.Open('data/points.gen') - if ds is None: - gdaltest.post_reason('cannot open dataset') - return 'fail' + assert ds is not None, 'cannot open dataset' - if ds.GetLayerCount() != 1: - gdaltest.post_reason('bad layer count') - return 'fail' + assert ds.GetLayerCount() == 1, 'bad layer count' lyr = ds.GetLayer(0) - if lyr is None: - gdaltest.post_reason('cannot find layer') - return 'fail' + assert lyr is not None, 'cannot find layer' - if lyr.GetGeomType() != ogr.wkbPoint: - gdaltest.post_reason('bad layer geometry type') - return 'fail' + assert lyr.GetGeomType() == ogr.wkbPoint, 'bad layer geometry type' feat = lyr.GetNextFeature() if feat.GetField(0) != 1: - gdaltest.post_reason('did not get expected ID') feat.DumpReadable() - return 'fail' + pytest.fail('did not get expected ID') if ogrtest.check_feature_geometry(feat, 'POINT (2 49)', max_error=0.0000001) != 0: - gdaltest.post_reason('did not get expected first geom') feat.DumpReadable() - return 'fail' - - return 'success' + pytest.fail('did not get expected first geom') + ############################################################################### # Read points25d -def ogr_arcgen_points25d(): +def test_ogr_arcgen_points25d(): ds = ogr.Open('data/points25d.gen') - if ds is None: - gdaltest.post_reason('cannot open dataset') - return 'fail' + assert ds is not None, 'cannot open dataset' - if ds.GetLayerCount() != 1: - gdaltest.post_reason('bad layer count') - return 'fail' + assert ds.GetLayerCount() == 1, 'bad layer count' lyr = ds.GetLayer(0) - if lyr is None: - gdaltest.post_reason('cannot find layer') - return 'fail' + assert lyr is not None, 'cannot find layer' - if lyr.GetGeomType() != ogr.wkbPoint25D: - gdaltest.post_reason('bad layer geometry type') - return 'fail' + assert lyr.GetGeomType() == ogr.wkbPoint25D, 'bad layer geometry type' feat = lyr.GetNextFeature() if feat.GetField(0) != 1: - gdaltest.post_reason('did not get expected ID') feat.DumpReadable() - return 'fail' + pytest.fail('did not get expected ID') if ogrtest.check_feature_geometry(feat, 'POINT (2 49 10)', max_error=0.0000001) != 0: - gdaltest.post_reason('did not get expected first geom') feat.DumpReadable() - return 'fail' - - return 'success' + pytest.fail('did not get expected first geom') + ############################################################################### # Read lines -def ogr_arcgen_lines(): +def test_ogr_arcgen_lines(): ds = ogr.Open('data/lines.gen') - if ds is None: - gdaltest.post_reason('cannot open dataset') - return 'fail' + assert ds is not None, 'cannot open dataset' lyr = ds.GetLayer(0) - if lyr is None: - gdaltest.post_reason('cannot find layer') - return 'fail' + assert lyr is not None, 'cannot find layer' - if lyr.GetGeomType() != ogr.wkbLineString: - gdaltest.post_reason('bad layer geometry type') - return 'fail' + assert lyr.GetGeomType() == ogr.wkbLineString, 'bad layer geometry type' feat = lyr.GetNextFeature() if feat.GetField(0) != 1: - gdaltest.post_reason('did not get expected ID') feat.DumpReadable() - return 'fail' + pytest.fail('did not get expected ID') if ogrtest.check_feature_geometry(feat, 'LINESTRING (2 49,3 50)', max_error=0.0000001) != 0: - gdaltest.post_reason('did not get expected first geom') feat.DumpReadable() - return 'fail' - - return 'success' + pytest.fail('did not get expected first geom') + ############################################################################### # Read lines25d -def ogr_arcgen_lines25d(): +def test_ogr_arcgen_lines25d(): ds = ogr.Open('data/lines25d.gen') - if ds is None: - gdaltest.post_reason('cannot open dataset') - return 'fail' + assert ds is not None, 'cannot open dataset' lyr = ds.GetLayer(0) - if lyr is None: - gdaltest.post_reason('cannot find layer') - return 'fail' + assert lyr is not None, 'cannot find layer' - if lyr.GetGeomType() != ogr.wkbLineString25D: - gdaltest.post_reason('bad layer geometry type') - return 'fail' + assert lyr.GetGeomType() == ogr.wkbLineString25D, 'bad layer geometry type' feat = lyr.GetNextFeature() if feat.GetField(0) != 1: - gdaltest.post_reason('did not get expected ID') feat.DumpReadable() - return 'fail' + pytest.fail('did not get expected ID') if ogrtest.check_feature_geometry(feat, 'LINESTRING (2 49 10,3 50 10)', max_error=0.0000001) != 0: - gdaltest.post_reason('did not get expected first geom') feat.DumpReadable() - return 'fail' - - return 'success' + pytest.fail('did not get expected first geom') + ############################################################################### # Read polygons -def ogr_arcgen_polygons(): +def test_ogr_arcgen_polygons(): ds = ogr.Open('data/polygons.gen') - if ds is None: - gdaltest.post_reason('cannot open dataset') - return 'fail' + assert ds is not None, 'cannot open dataset' lyr = ds.GetLayer(0) - if lyr is None: - gdaltest.post_reason('cannot find layer') - return 'fail' + assert lyr is not None, 'cannot find layer' - if lyr.GetGeomType() != ogr.wkbPolygon: - gdaltest.post_reason('bad layer geometry type') - return 'fail' + assert lyr.GetGeomType() == ogr.wkbPolygon, 'bad layer geometry type' feat = lyr.GetNextFeature() if feat.GetField(0) != 1: - print('did not get expected ID') feat.DumpReadable() - return 'fail' + pytest.fail('did not get expected ID') if ogrtest.check_feature_geometry(feat, 'POLYGON ((2 49,2 50,3 50,3 49,2 49))', max_error=0.0000001) != 0: - gdaltest.post_reason('did not get expected first geom') feat.DumpReadable() - return 'fail' - - return 'success' + pytest.fail('did not get expected first geom') + ############################################################################### # Read polygons25d -def ogr_arcgen_polygons25d(): +def test_ogr_arcgen_polygons25d(): ds = ogr.Open('data/polygons25d.gen') - if ds is None: - gdaltest.post_reason('cannot open dataset') - return 'fail' + assert ds is not None, 'cannot open dataset' lyr = ds.GetLayer(0) - if lyr is None: - gdaltest.post_reason('cannot find layer') - return 'fail' + assert lyr is not None, 'cannot find layer' - if lyr.GetGeomType() != ogr.wkbPolygon25D: - gdaltest.post_reason('bad layer geometry type') - return 'fail' + assert lyr.GetGeomType() == ogr.wkbPolygon25D, 'bad layer geometry type' feat = lyr.GetNextFeature() if feat.GetField(0) != 1: - gdaltest.post_reason('did not get expected ID') feat.DumpReadable() - return 'fail' + pytest.fail('did not get expected ID') if ogrtest.check_feature_geometry(feat, 'POLYGON ((2 49 10,2 50 10,3 50 10,3 49 10,2 49 10))', max_error=0.0000001) != 0: - gdaltest.post_reason('did not get expected first geom') feat.DumpReadable() - return 'fail' - - return 'success' - - -gdaltest_list = [ - ogr_arcgen_points, - ogr_arcgen_points25d, - ogr_arcgen_lines, - ogr_arcgen_lines25d, - ogr_arcgen_polygons, - ogr_arcgen_polygons25d] - + pytest.fail('did not get expected first geom') -if __name__ == '__main__': + - gdaltest.setup_run('ogr_arcgen') - gdaltest.run_tests(gdaltest_list) - sys.exit(gdaltest.summarize()) diff --git a/autotest/ogr/ogr_as_sqlite_extension.py b/autotest/ogr/ogr_as_sqlite_extension.py index 0d38949d3c2d..ac49ee9333ea 100755 --- a/autotest/ogr/ogr_as_sqlite_extension.py +++ b/autotest/ogr/ogr_as_sqlite_extension.py @@ -110,8 +110,6 @@ def do(sqlite3name, gdalname): sys.exit(1) -gdaltest_list = [] - if __name__ == '__main__': if len(sys.argv) != 3: print('python ogr_as_sqlite_extension name_of_libsqlite3 name_of_libgdal') diff --git a/autotest/ogr/ogr_avc.py b/autotest/ogr/ogr_avc.py index c51d622e95f3..3f810e8c0d3d 100755 --- a/autotest/ogr/ogr_avc.py +++ b/autotest/ogr/ogr_avc.py @@ -28,14 +28,12 @@ # DEALINGS IN THE SOFTWARE. ############################################################################### -import sys -sys.path.append('../pymod') -import gdaltest import ogrtest from osgeo import ogr from osgeo import gdal +import pytest ############################################################################### # @@ -47,75 +45,61 @@ def check_content(ds): expect = ['1', '2', '3', '4', '5', '6', '7'] tr = ogrtest.check_features_against_list(lyr, 'UserID', expect) - if not tr: - return 'fail' + assert tr lyr.ResetReading() feat = lyr.GetNextFeature() - if ogrtest.check_feature_geometry(feat, 'LINESTRING (340099.875 4100200.0,340400.0625 4100399.5,340900.125 4100200.0,340700.03125 4100199.5)', - max_error=0.01) != 0: - return 'fail' - - return 'success' + assert (ogrtest.check_feature_geometry(feat, 'LINESTRING (340099.875 4100200.0,340400.0625 4100399.5,340900.125 4100200.0,340700.03125 4100199.5)', + max_error=0.01) == 0) ############################################################################### # Open AVCE00 datasource. -def ogr_avc_1(): +def test_ogr_avc_1(): # Example given at Annex A of http://avce00.maptools.org/docs/v7_e00_cover.html avc_ds = ogr.Open('data/test.e00') - if avc_ds.GetLayer(0).GetSpatialRef() is None: - gdaltest.post_reason('expected SRS') - return 'fail' + assert avc_ds.GetLayer(0).GetSpatialRef() is not None, 'expected SRS' if avc_ds is not None: return check_content(avc_ds) - return 'fail' + pytest.fail() ############################################################################### # Open AVCBin datasource. -def ogr_avc_2(): +def test_ogr_avc_2(): avc_ds = ogr.Open('data/testavc/testavc') - if avc_ds.GetLayer(0).GetSpatialRef() is None: - gdaltest.post_reason('expected SRS') - return 'fail' + assert avc_ds.GetLayer(0).GetSpatialRef() is not None, 'expected SRS' if avc_ds is not None: return check_content(avc_ds) - return 'fail' + pytest.fail() ############################################################################### # Try opening a compressed E00 (which is not supported) -def ogr_avc_3(): +def test_ogr_avc_3(): gdal.PushErrorHandler('CPLQuietErrorHandler') avc_ds = ogr.Open('data/compressed.e00') gdal.PopErrorHandler() last_error_msg = gdal.GetLastErrorMsg() - if avc_ds is not None: - gdaltest.post_reason('expected failure') - return 'fail' - - if last_error_msg == '': - gdaltest.post_reason('expected error message') - return 'fail' + assert avc_ds is None, 'expected failure' - return 'success' + assert last_error_msg != '', 'expected error message' ############################################################################### # Open larger AVCBin datasource. -def ogr_avc_4(): +def test_ogr_avc_4(): for filename in ['data/testpointavc/testpointavc', 'data/testpoint.e00']: avc_ds = ogr.Open(filename) @@ -125,39 +109,26 @@ def ogr_avc_4(): for f in lyr: count += 1 last_feature = f - if count != 80: - gdaltest.post_reason('fail') - print(filename) - print(count) - return 'fail' + assert count == 80, filename count = lyr.GetFeatureCount() - if count != 80: - gdaltest.post_reason('fail') - print(filename) - print(count) - return 'fail' + assert count == 80, filename if last_feature.GetFieldCount() != 7: - gdaltest.post_reason('fail') - print(filename) f.DumpReadable() - return 'fail' + pytest.fail(filename) if filename == 'data/testpointavc/testpointavc': fld_name = 'TESTPOINTAVC-ID' else: fld_name = 'WELLS-ID' if last_feature.GetField('ValueId') != 80 or last_feature.GetField(fld_name) != 80: - gdaltest.post_reason('fail') - print(filename) f.DumpReadable() - return 'fail' - - return 'success' + pytest.fail(filename) + ############################################################################### # Open AVCBin datasource with polygon -def ogr_avc_5(): +def test_ogr_avc_5(): for filename in ['data/testpolyavc/testpolyavc', 'data/testpoly.e00']: avc_ds = ogr.Open(filename) @@ -167,53 +138,24 @@ def ogr_avc_5(): for f in lyr: count += 1 last_feature = f - if count != 3: - gdaltest.post_reason('fail') - print(filename) - print(count) - return 'fail' + assert count == 3, filename count = lyr.GetFeatureCount() - if count != 3: - gdaltest.post_reason('fail') - print(filename) - print(count) - return 'fail' + assert count == 3, filename if last_feature.GetFieldCount() != 5: - gdaltest.post_reason('fail') - print(filename) f.DumpReadable() - return 'fail' + pytest.fail(filename) if last_feature.GetField('ArcIds') != [-4, -5] or abs(last_feature.GetField('AREA') - 9939.059) > 1e-3: - gdaltest.post_reason('fail') - print(filename) f.DumpReadable() - return 'fail' + pytest.fail(filename) if filename == 'data/testpolyavc/testpolyavc': expected_wkt = 'POLYGON ((340700.03125 4100199.5,340500.0 4100199.75,340599.96875 4100100.25,340700.03125 4100199.5))' else: # Likely a bug in AVCE00 driver expected_wkt = 'POLYGON ((340299.94 4100199.8,340099.88 4100200.0,340299.94 4100199.8))' if last_feature.GetGeometryRef().ExportToWkt() != expected_wkt: - gdaltest.post_reason('fail') - print(filename) f.DumpReadable() - return 'fail' - - return 'success' - - -gdaltest_list = [ - ogr_avc_1, - ogr_avc_2, - ogr_avc_3, - ogr_avc_4, - ogr_avc_5 -] - -if __name__ == '__main__': + pytest.fail(filename) - gdaltest.setup_run('ogr_avc') + - gdaltest.run_tests(gdaltest_list) - sys.exit(gdaltest.summarize()) diff --git a/autotest/ogr/ogr_basic_test.py b/autotest/ogr/ogr_basic_test.py index f3603d9ea5c1..94ea8d329d99 100755 --- a/autotest/ogr/ogr_basic_test.py +++ b/autotest/ogr/ogr_basic_test.py @@ -30,48 +30,39 @@ import os import sys -sys.path.append('../pymod') import gdaltest import ogrtest from osgeo import gdal from osgeo import ogr +import pytest ############################################################################### -def ogr_basic_1(): +def test_ogr_basic_1(): gdaltest.ds = ogr.Open('data/poly.shp') - if gdaltest.ds is None: - gdaltest.post_reason('fail') - return 'fail' - - return 'success' + assert gdaltest.ds is not None ############################################################################### # Test Feature counting. -def ogr_basic_2(): +def test_ogr_basic_2(): gdaltest.lyr = gdaltest.ds.GetLayerByName('poly') - if gdaltest.lyr.GetName() != 'poly': - return 'fail' - if gdaltest.lyr.GetGeomType() != ogr.wkbPolygon: - return 'fail' + assert gdaltest.lyr.GetName() == 'poly' + assert gdaltest.lyr.GetGeomType() == ogr.wkbPolygon - if gdaltest.lyr.GetLayerDefn().GetName() != 'poly': - return 'fail' - if gdaltest.lyr.GetLayerDefn().GetGeomType() != ogr.wkbPolygon: - return 'fail' + assert gdaltest.lyr.GetLayerDefn().GetName() == 'poly' + assert gdaltest.lyr.GetLayerDefn().GetGeomType() == ogr.wkbPolygon count = gdaltest.lyr.GetFeatureCount() - if count != 10: - gdaltest.post_reason('Got wrong count with GetFeatureCount() - %d, expecting 10' % count) - return 'fail' + assert count == 10, \ + ('Got wrong count with GetFeatureCount() - %d, expecting 10' % count) # Now actually iterate through counting the features and ensure they agree. gdaltest.lyr.ResetReading() @@ -82,17 +73,14 @@ def ogr_basic_2(): count2 = count2 + 1 feat = gdaltest.lyr.GetNextFeature() - if count2 != 10: - gdaltest.post_reason('Got wrong count with GetNextFeature() - %d, expecting 10' % count2) - return 'fail' - - return 'success' + assert count2 == 10, \ + ('Got wrong count with GetNextFeature() - %d, expecting 10' % count2) ############################################################################### # Test Spatial Query. -def ogr_basic_3(): +def test_ogr_basic_3(): minx = 479405 miny = 4762826 @@ -117,46 +105,36 @@ def ogr_basic_3(): gdaltest.lyr.ResetReading() count = gdaltest.lyr.GetFeatureCount() - if count != 1: - gdaltest.post_reason('Got wrong feature count with spatial filter, expected 1, got %d' % count) - return 'fail' + assert count == 1, \ + ('Got wrong feature count with spatial filter, expected 1, got %d' % count) feat1 = gdaltest.lyr.GetNextFeature() feat2 = gdaltest.lyr.GetNextFeature() - if feat1 is None or feat2 is not None: - gdaltest.post_reason('Got too few or too many features with spatial filter.') - return 'fail' + assert feat1 is not None and feat2 is None, \ + 'Got too few or too many features with spatial filter.' gdaltest.lyr.SetSpatialFilter(None) count = gdaltest.lyr.GetFeatureCount() - if count != 10: - gdaltest.post_reason('Clearing spatial query may not have worked properly, getting\n%d features instead of expected 10 features.' % count) - return 'fail' - - return 'success' + assert count == 10, \ + ('Clearing spatial query may not have worked properly, getting\n%d features instead of expected 10 features.' % count) ############################################################################### # Test GetDriver(). -def ogr_basic_4(): +def test_ogr_basic_4(): driver = gdaltest.ds.GetDriver() - if driver is None: - gdaltest.post_reason('GetDriver() returns None') - return 'fail' - - if driver.GetName() != 'ESRI Shapefile': - gdaltest.post_reason('Got wrong driver name: ' + driver.GetName()) - return 'fail' + assert driver is not None, 'GetDriver() returns None' - return 'success' + assert driver.GetName() == 'ESRI Shapefile', \ + ('Got wrong driver name: ' + driver.GetName()) ############################################################################### # Test attribute query on special field fid - per bug 1468. -def ogr_basic_5(): +def test_ogr_basic_5(): gdaltest.lyr.SetAttributeFilter('FID = 3') gdaltest.lyr.ResetReading() @@ -166,49 +144,37 @@ def ogr_basic_5(): gdaltest.lyr.SetAttributeFilter(None) - if feat1 is None or feat2 is not None: - gdaltest.post_reason('unexpected result count.') - return 'fail' + assert feat1 is not None and feat2 is None, 'unexpected result count.' - if feat1.GetFID() != 3: - gdaltest.post_reason('got wrong feature.') - return 'fail' - - return 'success' + assert feat1.GetFID() == 3, 'got wrong feature.' ############################################################################### # Test opening a dataset with an empty string and a non existing dataset -def ogr_basic_6(): +def test_ogr_basic_6(): # Put inside try/except for OG python bindings - if ogr.Open('') is not None: - return 'fail' - - if ogr.Open('non_existing') is not None: - return 'fail' + assert ogr.Open('') is None - return 'success' + assert ogr.Open('non_existing') is None ############################################################################### # Test ogr.Feature.Equal() -def ogr_basic_7(): +def test_ogr_basic_7(): feat_defn = ogr.FeatureDefn() feat = ogr.Feature(feat_defn) - if not feat.Equal(feat): - return 'fail' + assert feat.Equal(feat) try: feat.SetFieldIntegerList except AttributeError: - return 'skip' + pytest.skip() feat_clone = feat.Clone() - if not feat.Equal(feat_clone): - return 'fail' + assert feat.Equal(feat_clone) # We MUST delete now as we are changing the feature defn afterwards! # Crash guaranteed otherwise @@ -255,7 +221,7 @@ def ogr_basic_7(): feat_clone = feat.Clone() if not feat.Equal(feat_clone): feat.DumpReadable() - return 'fail' + pytest.fail() feat_almost_clone = feat.Clone() geom = ogr.CreateGeometryFromWkt('POINT(0 1)') @@ -263,7 +229,7 @@ def ogr_basic_7(): if feat.Equal(feat_almost_clone): feat.DumpReadable() feat_almost_clone.DumpReadable() - return 'fail' + pytest.fail() feat_almost_clone = feat.Clone() geom = ogr.CreateGeometryFromWkt('POINT(0 1)') @@ -271,83 +237,83 @@ def ogr_basic_7(): if feat.Equal(feat_almost_clone): feat.DumpReadable() feat_almost_clone.DumpReadable() - return 'fail' + pytest.fail() feat_clone = feat.Clone() if not feat.Equal(feat_clone): feat.DumpReadable() feat_clone.DumpReadable() - return 'fail' + pytest.fail() feat_almost_clone = feat.Clone() feat_almost_clone.SetFID(99) if feat.Equal(feat_almost_clone): feat.DumpReadable() feat_almost_clone.DumpReadable() - return 'fail' + pytest.fail() feat_almost_clone = feat.Clone() feat_almost_clone.SetField(0, 2) if feat.Equal(feat_almost_clone): feat.DumpReadable() feat_almost_clone.DumpReadable() - return 'fail' + pytest.fail() feat_almost_clone = feat.Clone() feat_almost_clone.SetField(1, 2.2) if feat.Equal(feat_almost_clone): feat.DumpReadable() feat_almost_clone.DumpReadable() - return 'fail' + pytest.fail() feat_almost_clone = feat.Clone() feat_almost_clone.SetField(2, "B") if feat.Equal(feat_almost_clone): feat.DumpReadable() feat_almost_clone.DumpReadable() - return 'fail' + pytest.fail() feat_almost_clone = feat.Clone() feat_almost_clone.SetFieldIntegerList(3, [1, 2, 3]) if feat.Equal(feat_almost_clone): feat.DumpReadable() feat_almost_clone.DumpReadable() - return 'fail' + pytest.fail() feat_almost_clone = feat.Clone() feat_almost_clone.SetFieldIntegerList(3, [1, 3]) if feat.Equal(feat_almost_clone): feat.DumpReadable() feat_almost_clone.DumpReadable() - return 'fail' + pytest.fail() feat_almost_clone = feat.Clone() feat_almost_clone.SetFieldDoubleList(4, [1.2, 3.4, 5.6]) if feat.Equal(feat_almost_clone): feat.DumpReadable() feat_almost_clone.DumpReadable() - return 'fail' + pytest.fail() feat_almost_clone = feat.Clone() feat_almost_clone.SetFieldDoubleList(4, [1.2, 3.5]) if feat.Equal(feat_almost_clone): feat.DumpReadable() feat_almost_clone.DumpReadable() - return 'fail' + pytest.fail() feat_almost_clone = feat.Clone() feat_almost_clone.SetFieldStringList(5, ["A", "B", "C"]) if feat.Equal(feat_almost_clone): feat.DumpReadable() feat_almost_clone.DumpReadable() - return 'fail' + pytest.fail() feat_almost_clone = feat.Clone() feat_almost_clone.SetFieldStringList(5, ["A", "D"]) if feat.Equal(feat_almost_clone): feat.DumpReadable() feat_almost_clone.DumpReadable() - return 'fail' + pytest.fail() for num_field in [6, 7, 8]: for i in range(7): @@ -358,48 +324,45 @@ def ogr_basic_7(): if feat.Equal(feat_almost_clone): feat.DumpReadable() feat_almost_clone.DumpReadable() - return 'fail' + pytest.fail() feat_almost_clone = feat.Clone() feat_almost_clone.SetFieldBinaryFromHexString(9, '00') if feat.Equal(feat_almost_clone): feat.DumpReadable() feat_almost_clone.DumpReadable() - return 'fail' + pytest.fail() feat_almost_clone = feat.Clone() feat_almost_clone.SetField(10, 2) if feat.Equal(feat_almost_clone): feat.DumpReadable() feat_almost_clone.DumpReadable() - return 'fail' + pytest.fail() feat_almost_clone = feat.Clone() feat_almost_clone.SetField(10, 2) if feat.Equal(feat_almost_clone): feat.DumpReadable() feat_almost_clone.DumpReadable() - return 'fail' - - return 'success' + pytest.fail() + ############################################################################### # Issue several RegisterAll() to check that OGR drivers are good citizens -def ogr_basic_8(): +def test_ogr_basic_8(): ogr.RegisterAll() ogr.RegisterAll() ogr.RegisterAll() - return 'success' - ############################################################################### # Test ogr.GeometryTypeToName (#4871) -def ogr_basic_9(): +def test_ogr_basic_9(): geom_type_tuples = [[ogr.wkbUnknown, "Unknown (any)"], [ogr.wkbPoint, "Point"], @@ -422,39 +385,31 @@ def ogr_basic_9(): ] for geom_type_tuple in geom_type_tuples: - if ogr.GeometryTypeToName(geom_type_tuple[0]) != geom_type_tuple[1]: - gdaltest.post_reason('fail') - print('Got %s, expected %s' % (ogr.GeometryTypeToName(geom_type_tuple[0]), geom_type_tuple[1])) - return 'fail' - - return 'success' + assert ogr.GeometryTypeToName(geom_type_tuple[0]) == geom_type_tuple[1] + ############################################################################### # Run test_ogrsf -all_drivers -def ogr_basic_10(): +def test_ogr_basic_10(): import test_cli_utilities if test_cli_utilities.get_test_ogrsf_path() is None: - return 'skip' + pytest.skip() ret = gdaltest.runexternal(test_cli_utilities.get_test_ogrsf_path() + ' -all_drivers') - if ret.find('INFO') == -1 or ret.find('ERROR') != -1: - print(ret) - return 'fail' - - return 'success' + assert ret.find('INFO') != -1 and ret.find('ERROR') == -1 ############################################################################### # Test double call to UseExceptions() (#5704) -def ogr_basic_11(): +def test_ogr_basic_11(): if not ogrtest.have_geos(): - return 'skip' + pytest.skip() used_exceptions_before = ogr.GetUseExceptions() for _ in range(2): @@ -465,24 +420,19 @@ def ogr_basic_11(): if used_exceptions_before == 0: ogr.DontUseExceptions() - return 'success' - + ############################################################################### # Test OFSTBoolean, OFSTInt16 and OFSTFloat32 -def ogr_basic_12(): +def test_ogr_basic_12(): # boolean integer feat_def = ogr.FeatureDefn() - if ogr.GetFieldSubTypeName(ogr.OFSTBoolean) != 'Boolean': - gdaltest.post_reason('fail') - return 'fail' + assert ogr.GetFieldSubTypeName(ogr.OFSTBoolean) == 'Boolean' field_def = ogr.FieldDefn('fld', ogr.OFTInteger) field_def.SetSubType(ogr.OFSTBoolean) - if field_def.GetSubType() != ogr.OFSTBoolean: - gdaltest.post_reason('fail') - return 'fail' + assert field_def.GetSubType() == ogr.OFSTBoolean feat_def.AddFieldDefn(field_def) f = ogr.Feature(feat_def) @@ -492,12 +442,8 @@ def ogr_basic_12(): gdal.PushErrorHandler('CPLQuietErrorHandler') f.SetField('fld', 2) gdal.PopErrorHandler() - if gdal.GetLastErrorMsg() == '': - gdaltest.post_reason('fail') - return 'fail' - if f.GetField('fld') != 1: - gdaltest.post_reason('fail') - return 'fail' + assert gdal.GetLastErrorMsg() != '' + assert f.GetField('fld') == 1 f.SetField('fld', '0') f.SetField('fld', '1') @@ -505,32 +451,22 @@ def ogr_basic_12(): gdal.PushErrorHandler('CPLQuietErrorHandler') f.SetField('fld', '2') gdal.PopErrorHandler() - if gdal.GetLastErrorMsg() == '': - gdaltest.post_reason('fail') - return 'fail' - if f.GetField('fld') != 1: - gdaltest.post_reason('fail') - return 'fail' + assert gdal.GetLastErrorMsg() != '' + assert f.GetField('fld') == 1 gdal.ErrorReset() gdal.PushErrorHandler('CPLQuietErrorHandler') field_def = ogr.FieldDefn('fld', ogr.OFTString) field_def.SetSubType(ogr.OFSTBoolean) gdal.PopErrorHandler() - if gdal.GetLastErrorMsg() == '': - gdaltest.post_reason('fail') - return 'fail' - if field_def.GetSubType() != ogr.OFSTNone: - gdaltest.post_reason('fail') - return 'fail' + assert gdal.GetLastErrorMsg() != '' + assert field_def.GetSubType() == ogr.OFSTNone # boolean list feat_def = ogr.FeatureDefn() field_def = ogr.FieldDefn('fld', ogr.OFTIntegerList) field_def.SetSubType(ogr.OFSTBoolean) - if field_def.GetSubType() != ogr.OFSTBoolean: - gdaltest.post_reason('fail') - return 'fail' + assert field_def.GetSubType() == ogr.OFSTBoolean feat_def.AddFieldDefn(field_def) f = ogr.Feature(feat_def) @@ -539,24 +475,15 @@ def ogr_basic_12(): gdal.PushErrorHandler('CPLQuietErrorHandler') f.SetFieldIntegerList(0, [0, 1, 2, 1]) gdal.PopErrorHandler() - if gdal.GetLastErrorMsg() == '': - gdaltest.post_reason('fail') - return 'fail' - if f.GetField('fld') != [0, 1, 1, 1]: - print(f.GetField('fld')) - gdaltest.post_reason('fail') - return 'fail' + assert gdal.GetLastErrorMsg() != '' + assert f.GetField('fld') == [0, 1, 1, 1] # int16 integer feat_def = ogr.FeatureDefn() - if ogr.GetFieldSubTypeName(ogr.OFSTInt16) != 'Int16': - gdaltest.post_reason('fail') - return 'fail' + assert ogr.GetFieldSubTypeName(ogr.OFSTInt16) == 'Int16' field_def = ogr.FieldDefn('fld', ogr.OFTInteger) field_def.SetSubType(ogr.OFSTInt16) - if field_def.GetSubType() != ogr.OFSTInt16: - gdaltest.post_reason('fail') - return 'fail' + assert field_def.GetSubType() == ogr.OFSTInt16 feat_def.AddFieldDefn(field_def) f = ogr.Feature(feat_def) @@ -566,85 +493,58 @@ def ogr_basic_12(): gdal.PushErrorHandler('CPLQuietErrorHandler') f.SetField('fld', -32769) gdal.PopErrorHandler() - if gdal.GetLastErrorMsg() == '': - gdaltest.post_reason('fail') - return 'fail' - if f.GetField('fld') != -32768: - gdaltest.post_reason('fail') - return 'fail' + assert gdal.GetLastErrorMsg() != '' + assert f.GetField('fld') == -32768 gdal.ErrorReset() gdal.PushErrorHandler('CPLQuietErrorHandler') f.SetField('fld', 32768) gdal.PopErrorHandler() - if gdal.GetLastErrorMsg() == '': - gdaltest.post_reason('fail') - return 'fail' - if f.GetField('fld') != 32767: - gdaltest.post_reason('fail') - return 'fail' + assert gdal.GetLastErrorMsg() != '' + assert f.GetField('fld') == 32767 gdal.ErrorReset() gdal.PushErrorHandler('CPLQuietErrorHandler') field_def = ogr.FieldDefn('fld', ogr.OFTString) field_def.SetSubType(ogr.OFSTInt16) gdal.PopErrorHandler() - if gdal.GetLastErrorMsg() == '': - gdaltest.post_reason('fail') - return 'fail' - if field_def.GetSubType() != ogr.OFSTNone: - gdaltest.post_reason('fail') - return 'fail' + assert gdal.GetLastErrorMsg() != '' + assert field_def.GetSubType() == ogr.OFSTNone # float32 feat_def = ogr.FeatureDefn() - if ogr.GetFieldSubTypeName(ogr.OFSTFloat32) != 'Float32': - gdaltest.post_reason('fail') - return 'fail' + assert ogr.GetFieldSubTypeName(ogr.OFSTFloat32) == 'Float32' field_def = ogr.FieldDefn('fld', ogr.OFTReal) field_def.SetSubType(ogr.OFSTFloat32) - if field_def.GetSubType() != ogr.OFSTFloat32: - gdaltest.post_reason('fail') - return 'fail' + assert field_def.GetSubType() == ogr.OFSTFloat32 feat_def.AddFieldDefn(field_def) if False: # pylint: disable=using-constant-test f = ogr.Feature(feat_def) gdal.ErrorReset() f.SetField('fld', '1.23') - if gdal.GetLastErrorMsg() != '': - gdaltest.post_reason('fail') - return 'fail' + assert gdal.GetLastErrorMsg() == '' gdal.ErrorReset() gdal.PushErrorHandler('CPLQuietErrorHandler') f.SetField('fld', 1.230000000001) gdal.PopErrorHandler() - if gdal.GetLastErrorMsg() == '': - gdaltest.post_reason('fail') - return 'fail' + assert gdal.GetLastErrorMsg() != '' if abs(f.GetField('fld') - 1.23) < 1e-8: - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' + pytest.fail() gdal.ErrorReset() gdal.PushErrorHandler('CPLQuietErrorHandler') field_def = ogr.FieldDefn('fld', ogr.OFSTFloat32) field_def.SetSubType(ogr.OFSTInt16) gdal.PopErrorHandler() - if gdal.GetLastErrorMsg() == '': - gdaltest.post_reason('fail') - return 'fail' - if field_def.GetSubType() != ogr.OFSTNone: - gdaltest.post_reason('fail') - return 'fail' - - return 'success' + assert gdal.GetLastErrorMsg() != '' + assert field_def.GetSubType() == ogr.OFSTNone ############################################################################### # Test OGRParseDate (#6452) -def ogr_basic_13(): +def test_ogr_basic_13(): feat_defn = ogr.FeatureDefn('test') field_defn = ogr.FieldDefn('date', ogr.OFTDateTime) feat_defn.AddFieldDefn(field_defn) @@ -675,37 +575,29 @@ def ogr_basic_13(): for (val, expected_ret) in tests: f = ogr.Feature(feat_defn) f.SetField('date', val) - if f.GetField('date') != expected_ret: - gdaltest.post_reason('fail') - print(val) - print(f.GetField('date')) - return 'fail' - - return 'success' + assert f.GetField('date') == expected_ret, val + ############################################################################### # Test ogr.Open(.) in an empty directory -def ogr_basic_14(): +def test_ogr_basic_14(): os.mkdir('tmp/ogr_basic_14') os.chdir('tmp/ogr_basic_14') ds = ogr.Open('.') os.chdir('../..') - if ds is not None: - return 'fail' + assert ds is None os.rmdir('tmp/ogr_basic_14') - return 'success' - ############################################################################### # Test exceptions with OGRErr return code -def ogr_basic_15(): +def test_ogr_basic_15(): ds = ogr.Open('data/poly.shp') lyr = ds.GetLayer(0) @@ -716,16 +608,13 @@ def ogr_basic_15(): lyr.CreateFeature(ogr.Feature(lyr.GetLayerDefn())) except RuntimeError as e: ok = str(e).find('CreateFeature : unsupported operation on a read-only datasource') >= 0 - if not ok: - print('Got: %s' + str(e)) - return 'fail' - return 'success' + assert ok, ('Got: %s' + str(e)) + return finally: if used_exceptions_before == 0: ogr.DontUseExceptions() - print('Expected exception') - return 'fail' + pytest.fail('Expected exception') ############################################################################### @@ -743,15 +632,12 @@ def ogr_basic_16_gen_list(N): yield i -def ogr_basic_16(): +def test_ogr_basic_16(): - if list(ogr_basic_16_gen_list(2)) != [0, 1]: - return 'fail' + assert list(ogr_basic_16_gen_list(2)) == [0, 1] - return 'success' - -def ogr_basic_invalid_unicode(): +def test_ogr_basic_invalid_unicode(): if sys.version_info >= (3, 0, 0): val = '\udcfc' @@ -772,10 +658,9 @@ def ogr_basic_invalid_unicode(): except: pass - return 'success' - + -def ogr_basic_dataset_slice(): +def test_ogr_basic_dataset_slice(): ds = ogr.GetDriverByName('Memory').CreateDataSource('') ds.CreateLayer('lyr1') @@ -783,64 +668,19 @@ def ogr_basic_dataset_slice(): ds.CreateLayer('lyr3') lyrs = [lyr.GetName() for lyr in ds[1:3]] - if lyrs != ['lyr2', 'lyr3']: - gdaltest.post_reason('fail') - print(lyrs) - return 'fail' + assert lyrs == ['lyr2', 'lyr3'] lyrs = [lyr.GetName() for lyr in ds[0:4]] - if lyrs != ['lyr1', 'lyr2', 'lyr3']: - gdaltest.post_reason('fail') - print(lyrs) - return 'fail' + assert lyrs == ['lyr1', 'lyr2', 'lyr3'] lyrs = [lyr.GetName() for lyr in ds[0:3:2]] - if lyrs != ['lyr1', 'lyr3']: - gdaltest.post_reason('fail') - print(lyrs) - return 'fail' - - return 'success' + assert lyrs == ['lyr1', 'lyr3'] ############################################################################### # cleanup -def ogr_basic_cleanup(): +def test_ogr_basic_cleanup(): gdaltest.lyr = None gdaltest.ds = None - - return 'success' - - -gdaltest_list = [ - ogr_basic_1, - ogr_basic_2, - ogr_basic_3, - ogr_basic_4, - ogr_basic_5, - ogr_basic_6, - ogr_basic_7, - ogr_basic_8, - ogr_basic_9, - ogr_basic_10, - ogr_basic_11, - ogr_basic_12, - ogr_basic_13, - ogr_basic_14, - ogr_basic_15, - ogr_basic_16, - ogr_basic_invalid_unicode, - ogr_basic_dataset_slice, - ogr_basic_cleanup] - -# gdaltest_list = [ ogr_basic_13 ] - -if __name__ == '__main__': - - gdaltest.setup_run('ogr_basic_test') - - gdaltest.run_tests(gdaltest_list) - - sys.exit(gdaltest.summarize()) diff --git a/autotest/ogr/ogr_bna.py b/autotest/ogr/ogr_bna.py index 8afa02c8117c..11f0ca0d9033 100755 --- a/autotest/ogr/ogr_bna.py +++ b/autotest/ogr/ogr_bna.py @@ -30,9 +30,7 @@ ############################################################################### import os -import sys -sys.path.append('../pymod') import gdaltest import ogrtest @@ -42,7 +40,7 @@ # Test points bna layer. -def ogr_bna_1(): +def test_ogr_bna_1(): gdaltest.bna_ds = ogr.Open('data/test.bna') @@ -51,27 +49,22 @@ def ogr_bna_1(): expect = ['PID5', 'PID4'] tr = ogrtest.check_features_against_list(lyr, 'Primary ID', expect) - if not tr: - return 'fail' + assert tr lyr.ResetReading() feat = lyr.GetNextFeature() - if ogrtest.check_feature_geometry(feat, 'POINT (573.736 476.563)', - max_error=0.0001) != 0: - return 'fail' + assert (ogrtest.check_feature_geometry(feat, 'POINT (573.736 476.563)', + max_error=0.0001) == 0) feat = lyr.GetNextFeature() - if ogrtest.check_feature_geometry(feat, 'POINT (532.991 429.121)', - max_error=0.0001) != 0: - return 'fail' - - return 'success' + assert (ogrtest.check_feature_geometry(feat, 'POINT (532.991 429.121)', + max_error=0.0001) == 0) ############################################################################### # Test lines bna layer. -def ogr_bna_2(): +def test_ogr_bna_2(): gdaltest.bna_ds = ogr.Open('data/test.bna') @@ -80,21 +73,17 @@ def ogr_bna_2(): expect = ['PID3'] tr = ogrtest.check_features_against_list(lyr, 'Primary ID', expect) - if not tr: - return 'fail' + assert tr lyr.ResetReading() feat = lyr.GetNextFeature() - if ogrtest.check_feature_geometry(feat, 'LINESTRING (224.598 307.425,333.043 341.461,396.629 304.952)', max_error=0.0001) != 0: - return 'fail' - - return 'success' + assert ogrtest.check_feature_geometry(feat, 'LINESTRING (224.598 307.425,333.043 341.461,396.629 304.952)', max_error=0.0001) == 0 ############################################################################### # Test polygons bna layer. -def ogr_bna_3(): +def test_ogr_bna_3(): gdaltest.bna_ds = ogr.Open('data/test.bna') @@ -103,34 +92,26 @@ def ogr_bna_3(): expect = ['PID2', 'PID1', 'PID7', 'PID8', 'PID9', 'PID10'] tr = ogrtest.check_features_against_list(lyr, 'Primary ID', expect) - if not tr: - return 'fail' + assert tr lyr.ResetReading() feat = lyr.GetNextFeature() feat = lyr.GetNextFeature() feat = lyr.GetNextFeature() - if ogrtest.check_feature_geometry(feat, 'MULTIPOLYGON (((0 0,1 0,1 1,0 1,0 0)))', max_error=0.0001) != 0: - return 'fail' + assert ogrtest.check_feature_geometry(feat, 'MULTIPOLYGON (((0 0,1 0,1 1,0 1,0 0)))', max_error=0.0001) == 0 feat = lyr.GetFeature(2) - if ogrtest.check_feature_geometry(feat, 'MULTIPOLYGON (((0 0,1 0,1 1,0 1,0 0)))', max_error=0.0001) != 0: - return 'fail' + assert ogrtest.check_feature_geometry(feat, 'MULTIPOLYGON (((0 0,1 0,1 1,0 1,0 0)))', max_error=0.0001) == 0 feat = lyr.GetFeature(3) - if ogrtest.check_feature_geometry(feat, 'POLYGON ((0 0,0 10,10 10,10 0,0 0),(2 2,2 8,8 8,8 2,2 2))', max_error=0.0001) != 0: - return 'fail' + assert ogrtest.check_feature_geometry(feat, 'POLYGON ((0 0,0 10,10 10,10 0,0 0),(2 2,2 8,8 8,8 2,2 2))', max_error=0.0001) == 0 feat = lyr.GetFeature(4) - if ogrtest.check_feature_geometry(feat, 'MULTIPOLYGON (((0 0,0 10,10 10,10 0,0 0)))', max_error=0.0001) != 0: - return 'fail' + assert ogrtest.check_feature_geometry(feat, 'MULTIPOLYGON (((0 0,0 10,10 10,10 0,0 0)))', max_error=0.0001) == 0 feat = lyr.GetFeature(5) - if ogrtest.check_feature_geometry(feat, 'MULTIPOLYGON (((0 0,0 10,10 10,10 0,0 0)))', max_error=0.0001) != 0: - return 'fail' - - return 'success' + assert ogrtest.check_feature_geometry(feat, 'MULTIPOLYGON (((0 0,0 10,10 10,10 0,0 0)))', max_error=0.0001) == 0 ############################################################################### # Test ellipses bna layer. -def ogr_bna_4(): +def test_ogr_bna_4(): gdaltest.bna_ds = ogr.Open('data/test.bna') @@ -139,39 +120,32 @@ def ogr_bna_4(): expect = ['PID6'] tr = ogrtest.check_features_against_list(lyr, 'Primary ID', expect) - if not tr: - return 'fail' + assert tr lyr.ResetReading() lyr.GetNextFeature() - return 'success' - ############################################################################### # Test write support def ogr_bna_check_content(lyr1, lyr2): - if lyr1.GetFeatureCount() != lyr2.GetFeatureCount(): - return 'fail' + assert lyr1.GetFeatureCount() == lyr2.GetFeatureCount() feat1 = lyr1.GetNextFeature() feat2 = lyr2.GetNextFeature() while feat1 is not None: for i in range(lyr1.GetLayerDefn().GetFieldCount()): - if feat1.GetField(i) != feat2.GetField(i): - return 'fail' + assert feat1.GetField(i) == feat2.GetField(i) - if ogrtest.check_feature_geometry(feat1, feat2.GetGeometryRef(), - max_error=0.000000001) != 0: - return 'fail' + assert (ogrtest.check_feature_geometry(feat1, feat2.GetGeometryRef(), + max_error=0.000000001) == 0) feat1 = lyr1.GetNextFeature() feat2 = lyr2.GetNextFeature() - return 'success' - + def ogr_bna_write(creation_options): @@ -193,9 +167,7 @@ def ogr_bna_write(creation_options): while feat is not None: dst_feat.SetFrom(feat) - if dst_lyr.CreateFeature(dst_feat) != 0: - gdaltest.post_reason('CreateFeature failed.') - return 'fail' + assert dst_lyr.CreateFeature(dst_feat) == 0, 'CreateFeature failed.' feat = src_lyr.GetNextFeature() @@ -206,51 +178,39 @@ def ogr_bna_write(creation_options): for layer_name in ['points', 'lines', 'polygons', 'ellipses']: src_lyr = gdaltest.bna_ds.GetLayerByName('test_' + layer_name) dst_lyr = output_ds.GetLayerByName('out_' + layer_name) - if ogr_bna_check_content(src_lyr, dst_lyr) != 'success': - return 'fail' - - return 'success' + ogr_bna_check_content(src_lyr, dst_lyr) + -def ogr_bna_5(): +def test_ogr_bna_5(): return ogr_bna_write(['ELLIPSES_AS_ELLIPSES=YES']) -def ogr_bna_6(): +def test_ogr_bna_6(): try: os.remove('tmp/out.bna') except OSError: pass - ret = ogr_bna_write(['LINEFORMAT=LF', 'MULTILINE=NO', 'COORDINATE_PRECISION=3']) - if ret != 'success': - return ret + ogr_bna_write(['LINEFORMAT=LF', 'MULTILINE=NO', 'COORDINATE_PRECISION=3']) size = os.stat('tmp/out.bna').st_size - if size != 1601: - gdaltest.post_reason('Got size %d. Expected %d' % (size, 1601)) - return 'fail' + assert size == 1601, ('Got size %d. Expected %d' % (size, 1601)) os.remove('tmp/out.bna') - ret = ogr_bna_write(['LINEFORMAT=CRLF', 'MULTILINE=NO', 'COORDINATE_PRECISION=3']) - if ret != 'success': - return ret + ogr_bna_write(['LINEFORMAT=CRLF', 'MULTILINE=NO', 'COORDINATE_PRECISION=3']) size = os.stat('tmp/out.bna').st_size - if size != 1611: - gdaltest.post_reason('Got size %d. Expected %d' % (size, 1611)) - return 'fail' - - return 'success' + assert size == 1611, ('Got size %d. Expected %d' % (size, 1611)) ############################################################################### # -def ogr_bna_cleanup(): +def test_ogr_bna_cleanup(): gdaltest.bna_ds = None @@ -259,22 +219,6 @@ def ogr_bna_cleanup(): except OSError: pass - return 'success' - - -gdaltest_list = [ - ogr_bna_1, - ogr_bna_2, - ogr_bna_3, - ogr_bna_4, - ogr_bna_5, - ogr_bna_6, - ogr_bna_cleanup] - -if __name__ == '__main__': - - gdaltest.setup_run('ogr_bna') + - gdaltest.run_tests(gdaltest_list) - sys.exit(gdaltest.summarize()) diff --git a/autotest/ogr/ogr_cad.py b/autotest/ogr/ogr_cad.py index 8a1800971161..279ebc5b9402 100755 --- a/autotest/ogr/ogr_cad.py +++ b/autotest/ogr/ogr_cad.py @@ -30,353 +30,281 @@ # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. ################################################################################ -import sys -sys.path.append('../pymod') import gdaltest import ogrtest from osgeo import gdal from osgeo import ogr +import pytest ############################################################################### # Check driver existence. -def ogr_cad_1(): +def test_ogr_cad_1(): gdaltest.cad_ds = None gdaltest.cad_dr = None gdaltest.cad_dr = ogr.GetDriverByName('CAD') if gdaltest.cad_dr is None: - return 'skip' - - return 'success' + pytest.skip() + ############################################################################### # Check driver properly opens simple file, reads correct feature (ellipse). -def ogr_cad_2(): +def test_ogr_cad_2(): if gdaltest.cad_dr is None: - return 'skip' + pytest.skip() gdaltest.cad_ds = gdal.OpenEx('data/cad/ellipse_r2000.dwg', allowed_drivers=['CAD']) - if gdaltest.cad_ds is None: - return 'fail' + assert gdaltest.cad_ds is not None - if gdaltest.cad_ds.GetLayerCount() != 1: - gdaltest.post_reason('expected exactly one layer.') - return 'fail' + assert gdaltest.cad_ds.GetLayerCount() == 1, 'expected exactly one layer.' gdaltest.cad_layer = gdaltest.cad_ds.GetLayer(0) - if gdaltest.cad_layer.GetName() != '0': - gdaltest.post_reason('layer name is expected to be default = 0.') - return 'fail' + assert gdaltest.cad_layer.GetName() == '0', \ + 'layer name is expected to be default = 0.' defn = gdaltest.cad_layer.GetLayerDefn() - if defn.GetFieldCount() != 5: - gdaltest.post_reason('did not get expected number of fields in defn. got %d' + assert defn.GetFieldCount() == 5, \ + ('did not get expected number of fields in defn. got %d' % defn.GetFieldCount()) - return 'fail' fc = gdaltest.cad_layer.GetFeatureCount() - if fc != 1: - gdaltest.post_reason('did not get expected feature count, got %d' % fc) - return 'fail' + assert fc == 1, ('did not get expected feature count, got %d' % fc) gdaltest.cad_layer.ResetReading() feat = gdaltest.cad_layer.GetNextFeature() - if feat is None: - gdaltest.post_reason('cad feature 0 get failed.') - return 'fail' + assert feat is not None, 'cad feature 0 get failed.' - if feat.cadgeom_type != 'CADEllipse': - gdaltest.post_reason('cad geometry type is wrong. Expected CADEllipse, got: %s' + assert feat.cadgeom_type == 'CADEllipse', \ + ('cad geometry type is wrong. Expected CADEllipse, got: %s' % feat.cadgeom_type) - return 'fail' - if feat.GetFID() != 0: - gdaltest.post_reason('did not get expected FID for feature 0.') - return 'fail' + assert feat.GetFID() == 0, 'did not get expected FID for feature 0.' - if feat.thickness != 0: - gdaltest.post_reason('did not get expected thickness. expected 0, got: %f' + assert feat.thickness == 0, ('did not get expected thickness. expected 0, got: %f' % feat.thickness) - return 'fail' - if feat.extentity_data is not None: - gdaltest.post_reason('expected feature ExtendedEntityData to be null.') - return 'fail' + assert feat.extentity_data is None, \ + 'expected feature ExtendedEntityData to be null.' expected_style = 'PEN(c:#FFFFFFFF,w:5px)' - if feat.GetStyleString() != expected_style: - gdaltest.post_reason('got unexpected style string on feature 0:\n%s\ninstead of:\n%s.' + assert feat.GetStyleString() == expected_style, \ + ('got unexpected style string on feature 0:\n%s\ninstead of:\n%s.' % (feat.GetStyleString(), expected_style)) - return 'fail' geom = feat.GetGeometryRef() - if geom is None: - gdaltest.post_reason('cad geometry is None.') - return 'fail' + assert geom is not None, 'cad geometry is None.' - if geom.GetGeometryType() != ogr.wkbLineString25D: - gdaltest.post_reason('did not get expected geometry type.') - return 'fail' + assert geom.GetGeometryType() == ogr.wkbLineString25D, \ + 'did not get expected geometry type.' gdaltest.cad_ds = None - return 'success' ############################################################################### # Check proper read of 3 layers (one circle on each) with different parameters. -def ogr_cad_3(): +def test_ogr_cad_3(): if gdaltest.cad_dr is None: - return 'skip' + pytest.skip() gdaltest.cad_ds = gdal.OpenEx('data/cad/triple_circles_r2000.dwg', allowed_drivers=['CAD']) - if gdaltest.cad_ds is None: - return 'fail' + assert gdaltest.cad_ds is not None - if gdaltest.cad_ds.GetLayerCount() != 3: - gdaltest.post_reason('expected 3 layers.') - return 'fail' + assert gdaltest.cad_ds.GetLayerCount() == 3, 'expected 3 layers.' # test first layer and circle gdaltest.cad_layer = gdaltest.cad_ds.GetLayer(0) - if gdaltest.cad_layer.GetName() != '0': - gdaltest.post_reason('layer name is expected to be default = 0.') - return 'fail' + assert gdaltest.cad_layer.GetName() == '0', \ + 'layer name is expected to be default = 0.' defn = gdaltest.cad_layer.GetLayerDefn() - if defn.GetFieldCount() != 5: - gdaltest.post_reason('did not get expected number of fields in defn. got %d' + assert defn.GetFieldCount() == 5, \ + ('did not get expected number of fields in defn. got %d' % defn.GetFieldCount()) - return 'fail' fc = gdaltest.cad_layer.GetFeatureCount() - if fc != 1: - gdaltest.post_reason('did not get expected feature count, got %d' % fc) - return 'fail' + assert fc == 1, ('did not get expected feature count, got %d' % fc) gdaltest.cad_layer.ResetReading() feat = gdaltest.cad_layer.GetNextFeature() - if feat.cadgeom_type != 'CADCircle': - gdaltest.post_reason('cad geometry type is wrong. Expected CADCircle, got: %s' + assert feat.cadgeom_type == 'CADCircle', \ + ('cad geometry type is wrong. Expected CADCircle, got: %s' % feat.cadgeom_type) - return 'fail' - if feat.thickness != 1.2: - gdaltest.post_reason('did not get expected thickness. expected 1.2, got: %f' + assert feat.thickness == 1.2, \ + ('did not get expected thickness. expected 1.2, got: %f' % feat.thickness) - return 'fail' - if feat.extentity_data is not None: - gdaltest.post_reason('expected feature ExtendedEntityData to be null.') - return 'fail' + assert feat.extentity_data is None, \ + 'expected feature ExtendedEntityData to be null.' expected_style = 'PEN(c:#FFFFFFFF,w:5px)' - if feat.GetStyleString() != expected_style: - gdaltest.post_reason('Got unexpected style string on feature 0:\n%s\ninstead of:\n%s.' + assert feat.GetStyleString() == expected_style, \ + ('Got unexpected style string on feature 0:\n%s\ninstead of:\n%s.' % (feat.GetStyleString(), expected_style)) - return 'fail' geom = feat.GetGeometryRef() - if geom.GetGeometryType() != ogr.wkbCircularStringZ: - gdaltest.post_reason('did not get expected geometry type.') - return 'fail' + assert geom.GetGeometryType() == ogr.wkbCircularStringZ, \ + 'did not get expected geometry type.' # test second layer and circle gdaltest.cad_layer = gdaltest.cad_ds.GetLayer(1) - if gdaltest.cad_layer.GetName() != '1': - gdaltest.post_reason('layer name is expected to be 1.') - return 'fail' + assert gdaltest.cad_layer.GetName() == '1', 'layer name is expected to be 1.' defn = gdaltest.cad_layer.GetLayerDefn() - if defn.GetFieldCount() != 5: - gdaltest.post_reason('did not get expected number of fields in defn. got %d' + assert defn.GetFieldCount() == 5, \ + ('did not get expected number of fields in defn. got %d' % defn.GetFieldCount()) - return 'fail' fc = gdaltest.cad_layer.GetFeatureCount() - if fc != 1: - gdaltest.post_reason('did not get expected feature count, got %d' % fc) - return 'fail' + assert fc == 1, ('did not get expected feature count, got %d' % fc) gdaltest.cad_layer.ResetReading() feat = gdaltest.cad_layer.GetNextFeature() - if feat.cadgeom_type != 'CADCircle': - gdaltest.post_reason('cad geometry type is wrong. Expected CADCircle, got: %s' + assert feat.cadgeom_type == 'CADCircle', \ + ('cad geometry type is wrong. Expected CADCircle, got: %s' % feat.cadgeom_type) - return 'fail' - if feat.thickness != 0.8: - gdaltest.post_reason('did not get expected thickness. expected 0.8, got: %f' + assert feat.thickness == 0.8, \ + ('did not get expected thickness. expected 0.8, got: %f' % feat.thickness) - return 'fail' - if feat.extentity_data is not None: - gdaltest.post_reason('expected feature ExtendedEntityData to be null.') - return 'fail' + assert feat.extentity_data is None, \ + 'expected feature ExtendedEntityData to be null.' expected_style = 'PEN(c:#FFFFFFFF,w:5px)' - if feat.GetStyleString() != expected_style: - gdaltest.post_reason('Got unexpected style string on feature 0:\n%s\ninstead of:\n%s.' + assert feat.GetStyleString() == expected_style, \ + ('Got unexpected style string on feature 0:\n%s\ninstead of:\n%s.' % (feat.GetStyleString(), expected_style)) - return 'fail' geom = feat.GetGeometryRef() - if geom.GetGeometryType() != ogr.wkbCircularStringZ: - gdaltest.post_reason('did not get expected geometry type.') - return 'fail' + assert geom.GetGeometryType() == ogr.wkbCircularStringZ, \ + 'did not get expected geometry type.' # test third layer and circle gdaltest.cad_layer = gdaltest.cad_ds.GetLayer(2) - if gdaltest.cad_layer.GetName() != '2': - gdaltest.post_reason('layer name is expected to be 2.') - return 'fail' + assert gdaltest.cad_layer.GetName() == '2', 'layer name is expected to be 2.' defn = gdaltest.cad_layer.GetLayerDefn() - if defn.GetFieldCount() != 5: - gdaltest.post_reason('did not get expected number of fields in defn. got %d' + assert defn.GetFieldCount() == 5, \ + ('did not get expected number of fields in defn. got %d' % defn.GetFieldCount()) - return 'fail' fc = gdaltest.cad_layer.GetFeatureCount() - if fc != 1: - gdaltest.post_reason('did not get expected feature count, got %d' % fc) - return 'fail' + assert fc == 1, ('did not get expected feature count, got %d' % fc) gdaltest.cad_layer.ResetReading() feat = gdaltest.cad_layer.GetNextFeature() - if feat.cadgeom_type != 'CADCircle': - gdaltest.post_reason('cad geometry type is wrong. Expected CADCircle, got: %s' + assert feat.cadgeom_type == 'CADCircle', \ + ('cad geometry type is wrong. Expected CADCircle, got: %s' % feat.cadgeom_type) - return 'fail' - if feat.thickness != 1.8: - gdaltest.post_reason('did not get expected thickness. expected 1.8, got: %f' + assert feat.thickness == 1.8, \ + ('did not get expected thickness. expected 1.8, got: %f' % feat.thickness) - return 'fail' - if feat.extentity_data is not None: - gdaltest.post_reason('expected feature ExtendedEntityData to be null.') - return 'fail' + assert feat.extentity_data is None, \ + 'expected feature ExtendedEntityData to be null.' expected_style = 'PEN(c:#FFFFFFFF,w:5px)' - if feat.GetStyleString() != expected_style: - gdaltest.post_reason('Got unexpected style string on feature 0:\n%s\ninstead of:\n%s.' + assert feat.GetStyleString() == expected_style, \ + ('Got unexpected style string on feature 0:\n%s\ninstead of:\n%s.' % (feat.GetStyleString(), expected_style)) - return 'fail' geom = feat.GetGeometryRef() - if geom.GetGeometryType() != ogr.wkbCircularStringZ: - gdaltest.post_reason('did not get expected geometry type.') - return 'fail' + assert geom.GetGeometryType() == ogr.wkbCircularStringZ, \ + 'did not get expected geometry type.' gdaltest.cad_ds = None - return 'success' ############################################################################### # Check reading of a single point. -def ogr_cad_4(): +def test_ogr_cad_4(): if gdaltest.cad_dr is None: - return 'skip' + pytest.skip() gdaltest.cad_ds = gdal.OpenEx('data/cad/point2d_r2000.dwg', allowed_drivers=['CAD']) - if gdaltest.cad_ds.GetLayerCount() != 1: - gdaltest.post_reason('expected exactly one layer.') - return 'fail' + assert gdaltest.cad_ds.GetLayerCount() == 1, 'expected exactly one layer.' gdaltest.cad_layer = gdaltest.cad_ds.GetLayer(0) - if gdaltest.cad_layer.GetFeatureCount() != 1: - gdaltest.post_reason('expected exactly one feature.') - return 'fail' + assert gdaltest.cad_layer.GetFeatureCount() == 1, 'expected exactly one feature.' feat = gdaltest.cad_layer.GetNextFeature() - if ogrtest.check_feature_geometry(feat, 'POINT (50 50 0)'): - gdaltest.post_reason('got feature which does not fit expectations.') - return 'fail' + assert not ogrtest.check_feature_geometry(feat, 'POINT (50 50 0)'), \ + 'got feature which does not fit expectations.' gdaltest.cad_ds = None - return 'success' ############################################################################### # Check reading of a simple line. -def ogr_cad_5(): +def test_ogr_cad_5(): if gdaltest.cad_dr is None: - return 'skip' + pytest.skip() gdaltest.cad_ds = gdal.OpenEx('data/cad/line_r2000.dwg', allowed_drivers=['CAD']) - if gdaltest.cad_ds.GetLayerCount() != 1: - gdaltest.post_reason('expected exactly one layer.') - return 'fail' + assert gdaltest.cad_ds.GetLayerCount() == 1, 'expected exactly one layer.' gdaltest.cad_layer = gdaltest.cad_ds.GetLayer(0) - if gdaltest.cad_layer.GetFeatureCount() != 1: - gdaltest.post_reason('expected exactly one feature.') - return 'fail' + assert gdaltest.cad_layer.GetFeatureCount() == 1, 'expected exactly one feature.' feat = gdaltest.cad_layer.GetNextFeature() - if ogrtest.check_feature_geometry(feat, 'LINESTRING (50 50 0,100 100 0)'): - gdaltest.post_reason('got feature which does not fit expectations.') - return 'fail' + assert not ogrtest.check_feature_geometry(feat, 'LINESTRING (50 50 0,100 100 0)'), \ + 'got feature which does not fit expectations.' gdaltest.cad_ds = None - return 'success' ############################################################################### # Check reading of a text (point with attached 'text' attribute, and set up # OGR feature style string to LABEL. -def ogr_cad_6(): +def test_ogr_cad_6(): if gdaltest.cad_dr is None: - return 'skip' + pytest.skip() gdaltest.cad_ds = gdal.OpenEx('data/cad/text_mtext_attdef_r2000.dwg', allowed_drivers=['CAD']) - if gdaltest.cad_ds.GetLayerCount() != 1: - gdaltest.post_reason('expected exactly one layer.') - return 'fail' + assert gdaltest.cad_ds.GetLayerCount() == 1, 'expected exactly one layer.' gdaltest.cad_layer = gdaltest.cad_ds.GetLayer(0) - if gdaltest.cad_layer.GetFeatureCount() != 3: - gdaltest.post_reason('expected 3 features, got: %d' + assert gdaltest.cad_layer.GetFeatureCount() == 3, ('expected 3 features, got: %d' % gdaltest.cad_layer.GetFeatureCount()) - return 'fail' feat = gdaltest.cad_layer.GetNextFeature() - if ogrtest.check_feature_geometry(feat, 'POINT(0.7413 1.7794 0)'): - return 'fail' + assert not ogrtest.check_feature_geometry(feat, 'POINT(0.7413 1.7794 0)') expected_style = 'LABEL(f:"Arial",t:"Русские буквы",c:#FFFFFFFF)' if feat.GetStyleString() != expected_style: @@ -384,97 +312,62 @@ def ogr_cad_6(): % (feat.GetStyleString(), expected_style)) return 'expected_fail' # cannot sure iconv is buildin - return 'success' - + ############################################################################### # Check MTEXT as TEXT geometry. -def ogr_cad_7(): +def test_ogr_cad_7(): if gdaltest.cad_dr is None: - return 'skip' + pytest.skip() feat = gdaltest.cad_layer.GetNextFeature() - if ogrtest.check_feature_geometry(feat, 'POINT(2.8139 5.7963 0)'): - return 'fail' + assert not ogrtest.check_feature_geometry(feat, 'POINT(2.8139 5.7963 0)') expected_style = 'LABEL(f:"Arial",t:"English letters",c:#FFFFFFFF)' - if feat.GetStyleString() != expected_style: - gdaltest.post_reason('Got unexpected style string:\n%s\ninstead of:\n%s.' + assert feat.GetStyleString() == expected_style, \ + ('Got unexpected style string:\n%s\ninstead of:\n%s.' % (feat.GetStyleString(), expected_style)) - return 'fail' - - return 'success' ############################################################################### # Check ATTDEF as TEXT geometry. -def ogr_cad_8(): +def test_ogr_cad_8(): if gdaltest.cad_dr is None: - return 'skip' + pytest.skip() feat = gdaltest.cad_layer.GetNextFeature() - if ogrtest.check_feature_geometry(feat, 'POINT(4.98953601938918 2.62670161690571 0)'): - return 'fail' + assert not ogrtest.check_feature_geometry(feat, 'POINT(4.98953601938918 2.62670161690571 0)') expected_style = 'LABEL(f:"Arial",t:"TESTTAG",c:#FFFFFFFF)' - if feat.GetStyleString() != expected_style: - gdaltest.post_reason('Got unexpected style string:\n%s\ninstead of:\n%s.' + assert feat.GetStyleString() == expected_style, \ + ('Got unexpected style string:\n%s\ninstead of:\n%s.' % (feat.GetStyleString(), expected_style)) - return 'fail' - - return 'success' ############################################################################### # Open a not handled DWG version -def ogr_cad_9(): +def test_ogr_cad_9(): if gdaltest.cad_dr is None: - return 'skip' + pytest.skip() with gdaltest.error_handler(): ds = gdal.OpenEx('data/AC1018_signature.dwg', allowed_drivers=['CAD']) - if ds is not None: - gdaltest.post_reason('fail') - return 'fail' + assert ds is None msg = gdal.GetLastErrorMsg() - if msg.find('does not support this version') < 0: - gdaltest.post_reason('fail') - return 'fail' - - return 'success' + assert msg.find('does not support this version') >= 0 ############################################################################### # Cleanup -def ogr_cad_cleanup(): +def test_ogr_cad_cleanup(): gdaltest.cad_layer = None gdaltest.cad_ds = None - return 'success' - - -gdaltest_list = [ - ogr_cad_1, - ogr_cad_2, - ogr_cad_3, - ogr_cad_4, - ogr_cad_5, - ogr_cad_6, - ogr_cad_7, - ogr_cad_8, - ogr_cad_9, - ogr_cad_cleanup] - -if __name__ == '__main__': - - gdaltest.setup_run('ogr_cad') - gdaltest.run_tests(gdaltest_list) - sys.exit(gdaltest.summarize()) diff --git a/autotest/ogr/ogr_carto.py b/autotest/ogr/ogr_carto.py index 18517b4c3b25..c78fc1a20c94 100755 --- a/autotest/ogr/ogr_carto.py +++ b/autotest/ogr/ogr_carto.py @@ -29,38 +29,36 @@ # DEALINGS IN THE SOFTWARE. ############################################################################### -import sys import uuid -sys.path.append('../pymod') import gdaltest import ogrtest from osgeo import gdal from osgeo import ogr from osgeo import osr +import pytest ############################################################################### # Test if driver is available -def ogr_carto_init(): +def test_ogr_carto_init(): ogrtest.carto_drv = None ogrtest.carto_drv = ogr.GetDriverByName('Carto') if ogrtest.carto_drv is None: - return 'skip' - - return 'success' + pytest.skip() + ############################################################################### # -def ogr_carto_vsimem(): +def test_ogr_carto_vsimem(): if ogrtest.carto_drv is None: - return 'skip' + pytest.skip() ogrtest.carto_api_key_ori = gdal.GetConfigOption('CARTO_API_KEY') gdal.SetConfigOption('CARTO_API_URL', '/vsimem/carto') @@ -72,9 +70,7 @@ def ogr_carto_vsimem(): gdal.PushErrorHandler() ds = ogr.Open('CARTO:foo') gdal.PopErrorHandler() - if ds is not None: - gdaltest.post_reason('fail') - return 'fail' + assert ds is None gdal.FileFromMemBuffer('/vsimem/carto&POSTFIELDS=q=SELECT current_schema() LIMIT 500 OFFSET 0', """Content-Type: text/html\r @@ -83,154 +79,101 @@ def ogr_carto_vsimem(): gdal.PushErrorHandler() ds = ogr.Open('CARTO:foo') gdal.PopErrorHandler() - if ds is not None or gdal.GetLastErrorMsg().find('HTML error page') < 0: - gdaltest.post_reason('fail') - print(gdal.GetLastErrorMsg()) - return 'fail' + assert ds is None and gdal.GetLastErrorMsg().find('HTML error page') >= 0 gdal.FileFromMemBuffer('/vsimem/carto&POSTFIELDS=q=SELECT current_schema() LIMIT 500 OFFSET 0', """""") ds = ogr.Open('CARTO:foo') - if ds is not None: - gdaltest.post_reason('fail') - print(gdal.GetLastErrorMsg()) - return 'fail' + assert ds is None, gdal.GetLastErrorMsg() gdal.FileFromMemBuffer('/vsimem/carto&POSTFIELDS=q=SELECT current_schema() LIMIT 500 OFFSET 0', """{""") gdal.PushErrorHandler() ds = ogr.Open('CARTO:foo') gdal.PopErrorHandler() - if ds is not None or gdal.GetLastErrorMsg().find('JSON parsing error') < 0: - gdaltest.post_reason('fail') - print(gdal.GetLastErrorMsg()) - return 'fail' + assert ds is None and gdal.GetLastErrorMsg().find('JSON parsing error') >= 0 gdal.FileFromMemBuffer('/vsimem/carto&POSTFIELDS=q=SELECT current_schema() LIMIT 500 OFFSET 0', """ "not_expected_json" """) ds = ogr.Open('CARTO:foo') - if ds is not None: - gdaltest.post_reason('fail') - print(gdal.GetLastErrorMsg()) - return 'fail' + assert ds is None, gdal.GetLastErrorMsg() gdal.FileFromMemBuffer('/vsimem/carto&POSTFIELDS=q=SELECT current_schema() LIMIT 500 OFFSET 0', """{ "error" : [ "bla"] }""") gdal.PushErrorHandler() ds = ogr.Open('CARTO:foo') gdal.PopErrorHandler() - if ds is not None or gdal.GetLastErrorMsg().find('Error returned by server : bla') < 0: - gdaltest.post_reason('fail') - print(gdal.GetLastErrorMsg()) - return 'fail' + assert ds is None and gdal.GetLastErrorMsg().find('Error returned by server : bla') >= 0 gdal.FileFromMemBuffer('/vsimem/carto&POSTFIELDS=q=SELECT current_schema() LIMIT 500 OFFSET 0', """{ "fields" : null } """) ds = ogr.Open('CARTO:foo') - if ds is not None: - gdaltest.post_reason('fail') - print(gdal.GetLastErrorMsg()) - return 'fail' + assert ds is None, gdal.GetLastErrorMsg() gdal.FileFromMemBuffer('/vsimem/carto&POSTFIELDS=q=SELECT current_schema() LIMIT 500 OFFSET 0', """{ "fields" : "invalid" } """) ds = ogr.Open('CARTO:foo') - if ds is not None: - gdaltest.post_reason('fail') - print(gdal.GetLastErrorMsg()) - return 'fail' + assert ds is None, gdal.GetLastErrorMsg() gdal.FileFromMemBuffer('/vsimem/carto&POSTFIELDS=q=SELECT current_schema() LIMIT 500 OFFSET 0', """{ "fields" : {} } """) ds = ogr.Open('CARTO:foo') - if ds is not None: - gdaltest.post_reason('fail') - print(gdal.GetLastErrorMsg()) - return 'fail' + assert ds is None, gdal.GetLastErrorMsg() gdal.FileFromMemBuffer('/vsimem/carto&POSTFIELDS=q=SELECT current_schema() LIMIT 500 OFFSET 0', """{ "fields" : { "foo": "invalid" } } """) ds = ogr.Open('CARTO:foo') - if ds is not None: - gdaltest.post_reason('fail') - print(gdal.GetLastErrorMsg()) - return 'fail' + assert ds is None, gdal.GetLastErrorMsg() gdal.FileFromMemBuffer('/vsimem/carto&POSTFIELDS=q=SELECT current_schema() LIMIT 500 OFFSET 0', """{ "fields" : { "foo": {} } } """) ds = ogr.Open('CARTO:foo') - if ds is not None: - gdaltest.post_reason('fail') - print(gdal.GetLastErrorMsg()) - return 'fail' + assert ds is None, gdal.GetLastErrorMsg() gdal.FileFromMemBuffer('/vsimem/carto&POSTFIELDS=q=SELECT current_schema() LIMIT 500 OFFSET 0', """{ "fields" : { "foo": { "type" : null } } } """) ds = ogr.Open('CARTO:foo') - if ds is not None: - gdaltest.post_reason('fail') - print(gdal.GetLastErrorMsg()) - return 'fail' + assert ds is None, gdal.GetLastErrorMsg() gdal.FileFromMemBuffer('/vsimem/carto&POSTFIELDS=q=SELECT current_schema() LIMIT 500 OFFSET 0', """{ "fields" : { "foo": { "type" : {} } } } """) ds = ogr.Open('CARTO:foo') - if ds is not None: - gdaltest.post_reason('fail') - print(gdal.GetLastErrorMsg()) - return 'fail' + assert ds is None, gdal.GetLastErrorMsg() gdal.FileFromMemBuffer('/vsimem/carto&POSTFIELDS=q=SELECT current_schema() LIMIT 500 OFFSET 0', """{ "fields" : { "foo": { "type" : "string" } } } """) ds = ogr.Open('CARTO:foo') - if ds is not None: - gdaltest.post_reason('fail') - print(gdal.GetLastErrorMsg()) - return 'fail' + assert ds is None, gdal.GetLastErrorMsg() gdal.FileFromMemBuffer('/vsimem/carto&POSTFIELDS=q=SELECT current_schema() LIMIT 500 OFFSET 0', """{"rows":[ {"field1": "foo", "field2": "bar"} ],"fields":{"field1":{"type":"string"}, "field2":{"type":"string"}}}""") ds = ogr.Open('CARTO:foo') - if ds is not None: - gdaltest.post_reason('fail') - print(gdal.GetLastErrorMsg()) - return 'fail' + assert ds is None, gdal.GetLastErrorMsg() gdal.FileFromMemBuffer('/vsimem/carto&POSTFIELDS=q=SELECT current_schema() LIMIT 500 OFFSET 0', """{"rows":[],"fields":{"current_schema":{"type":"string"}}}""") gdal.PushErrorHandler() ds = ogr.Open('CARTO:foo') gdal.PopErrorHandler() - if ds is not None: - gdaltest.post_reason('fail') - print(gdal.GetLastErrorMsg()) - return 'fail' + assert ds is None, gdal.GetLastErrorMsg() gdal.FileFromMemBuffer('/vsimem/carto&POSTFIELDS=q=SELECT current_schema() LIMIT 500 OFFSET 0', """{"rows":[{"current_schema":"public"}],"fields":{"current_schema":{"type":"unknown(19)"}}}""") gdal.PushErrorHandler() ds = ogr.Open('CARTO:foo') gdal.PopErrorHandler() - if ds is not None: - gdaltest.post_reason('fail') - print(gdal.GetLastErrorMsg()) - return 'fail' + assert ds is None, gdal.GetLastErrorMsg() gdal.FileFromMemBuffer('/vsimem/carto&POSTFIELDS=q=SELECT CDB_UserTables() LIMIT 500 OFFSET 0', """{"rows":[{"cdb_usertables":"table1"}],"fields":{"cdb_usertables":{"type":"string"}}}""") ds = ogr.Open('CARTO:foo') - if ds is None or ds.GetLayerCount() != 1: - gdaltest.post_reason('fail') - print(gdal.GetLastErrorMsg()) - return 'fail' + assert ds is not None and ds.GetLayerCount() == 1, gdal.GetLastErrorMsg() gdal.PushErrorHandler() lyr_defn = ds.GetLayer(0).GetLayerDefn() gdal.PopErrorHandler() - if lyr_defn.GetFieldCount() != 0: - gdaltest.post_reason('fail') - return 'fail' + assert lyr_defn.GetFieldCount() == 0 # Empty layer gdal.FileFromMemBuffer('/vsimem/carto&POSTFIELDS=q=SELECT * FROM "table1" LIMIT 0', @@ -238,17 +181,14 @@ def ogr_carto_vsimem(): ds = ogr.Open('CARTO:foo') lyr = ds.GetLayer(0) lyr_defn = lyr.GetLayerDefn() - if lyr_defn.GetFieldCount() != 0: - gdaltest.post_reason('fail') - return 'fail' + assert lyr_defn.GetFieldCount() == 0 gdal.FileFromMemBuffer('/vsimem/carto&POSTFIELDS=q=SELECT * FROM "table1" LIMIT 500 OFFSET 0', """{"rows":[{}],"fields":{}}}""") f = lyr.GetNextFeature() if f.GetFID() != 0: - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' + pytest.fail() # Layer without geometry or primary key gdal.FileFromMemBuffer('/vsimem/carto&POSTFIELDS=q=SELECT * FROM "table1" LIMIT 0', @@ -256,35 +196,24 @@ def ogr_carto_vsimem(): ds = ogr.Open('CARTO:foo') lyr = ds.GetLayer(0) lyr_defn = lyr.GetLayerDefn() - if lyr_defn.GetFieldCount() != 4: - gdaltest.post_reason('fail') - return 'fail' - if lyr_defn.GetFieldDefn(0).GetName() != 'strfield' or \ - lyr_defn.GetFieldDefn(0).GetType() != ogr.OFTString: - gdaltest.post_reason('fail') - return 'fail' - if lyr_defn.GetFieldDefn(1).GetName() != 'realfield' or \ - lyr_defn.GetFieldDefn(1).GetType() != ogr.OFTReal: - gdaltest.post_reason('fail') - return 'fail' - if lyr_defn.GetFieldDefn(2).GetName() != 'boolfield' or \ - lyr_defn.GetFieldDefn(2).GetType() != ogr.OFTInteger or \ - lyr_defn.GetFieldDefn(2).GetSubType() != ogr.OFSTBoolean: - gdaltest.post_reason('fail') - return 'fail' - if lyr_defn.GetFieldDefn(3).GetName() != 'datefield' or \ - lyr_defn.GetFieldDefn(3).GetType() != ogr.OFTDateTime: - gdaltest.post_reason('fail') - return 'fail' + assert lyr_defn.GetFieldCount() == 4 + assert (lyr_defn.GetFieldDefn(0).GetName() == 'strfield' and \ + lyr_defn.GetFieldDefn(0).GetType() == ogr.OFTString) + assert (lyr_defn.GetFieldDefn(1).GetName() == 'realfield' and \ + lyr_defn.GetFieldDefn(1).GetType() == ogr.OFTReal) + assert (lyr_defn.GetFieldDefn(2).GetName() == 'boolfield' and \ + lyr_defn.GetFieldDefn(2).GetType() == ogr.OFTInteger and \ + lyr_defn.GetFieldDefn(2).GetSubType() == ogr.OFSTBoolean) + assert (lyr_defn.GetFieldDefn(3).GetName() == 'datefield' and \ + lyr_defn.GetFieldDefn(3).GetType() == ogr.OFTDateTime) gdal.FileFromMemBuffer('/vsimem/carto&POSTFIELDS=q=SELECT "strfield", "realfield", "boolfield", "datefield" FROM "table1" LIMIT 500 OFFSET 0', """{"rows":[{ "strfield": "foo", "realfield": 1.23, "boolfield": true, "datefield": "2015-04-24T12:34:56.123Z" }],"fields":{"strfield":{"type":"string"}, "realfield":{"type":"number"}, "boolfield":{"type":"boolean"}, "datefield":{"type":"date"}}}""") f = lyr.GetNextFeature() if f['strfield'] != 'foo' or f['realfield'] != 1.23 or f['boolfield'] != 1 or \ f['datefield'] != '2015/04/24 12:34:56.123+00': - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' + pytest.fail() gdal.SetConfigOption('CARTO_API_KEY', 'foo') gdal.FileFromMemBuffer('/vsimem/carto&POSTFIELDS=q=SELECT current_schema() LIMIT 500 OFFSET 0&api_key=foo', @@ -295,9 +224,7 @@ def ogr_carto_vsimem(): gdal.PushErrorHandler() lyr_defn = ds.GetLayer(0).GetLayerDefn() gdal.PopErrorHandler() - if lyr_defn.GetFieldCount() != 0: - gdaltest.post_reason('fail') - return 'fail' + assert lyr_defn.GetFieldCount() == 0 get_full_details_fields_url = """/vsimem/carto&POSTFIELDS=q=SELECT a.attname, t.typname, a.attlen, format_type(a.atttypid,a.atttypmod), a.attnum, a.attnotnull, i.indisprimary, pg_get_expr(def.adbin, c.oid) AS defaultexpr, postgis_typmod_dims(a.atttypmod) dim, postgis_typmod_srid(a.atttypmod) srid, postgis_typmod_type(a.atttypmod)::text geomtyp, srtext FROM pg_class c JOIN pg_attribute a ON a.attnum > 0 AND a.attrelid = c.oid AND c.relname = 'table1' JOIN pg_type t ON a.atttypid = t.oid JOIN pg_namespace n ON c.relnamespace=n.oid AND n.nspname= 'public' LEFT JOIN pg_index i ON c.oid = i.indrelid AND i.indisprimary = 't' AND a.attnum = ANY(i.indkey) LEFT JOIN pg_attrdef def ON def.adrelid = c.oid AND def.adnum = a.attnum LEFT JOIN spatial_ref_sys srs ON srs.srid = postgis_typmod_srid(a.atttypmod) ORDER BY a.attnum LIMIT 500 OFFSET 0&api_key=foo""" gdal.FileFromMemBuffer(get_full_details_fields_url, '') @@ -305,9 +232,7 @@ def ogr_carto_vsimem(): gdal.PushErrorHandler() lyr_defn = ds.GetLayer(0).GetLayerDefn() gdal.PopErrorHandler() - if lyr_defn.GetFieldCount() != 0: - gdaltest.post_reason('fail') - return 'fail' + assert lyr_defn.GetFieldCount() == 0 gdal.FileFromMemBuffer(get_full_details_fields_url, """{"rows":[{"attname":"foo"}], "fields":{"attname":{"type":"string"}}}""") @@ -316,16 +241,12 @@ def ogr_carto_vsimem(): gdal.PushErrorHandler() lyr_defn = lyr.GetLayerDefn() gdal.PopErrorHandler() - if lyr_defn.GetFieldCount() != 1: - gdaltest.post_reason('fail') - return 'fail' + assert lyr_defn.GetFieldCount() == 1 gdal.PushErrorHandler() f = lyr.GetFeature(0) gdal.PopErrorHandler() - if f is not None: - gdaltest.post_reason('fail') - return 'fail' + assert f is None gdal.FileFromMemBuffer(get_full_details_fields_url, """{"rows":[{"attname":"strfield", "typname":"varchar", "attnotnull": true, "defaultexpr": "def_value"}, @@ -355,43 +276,27 @@ def ogr_carto_vsimem(): ds = ogr.Open('CARTO:foo') lyr = ds.GetLayer(0) lyr_defn = lyr.GetLayerDefn() - if lyr_defn.GetFieldCount() != 5: - gdaltest.post_reason('fail') - return 'fail' - if lyr_defn.GetFieldDefn(0).GetName() != 'strfield' or \ - lyr_defn.GetFieldDefn(0).GetType() != ogr.OFTString or \ - lyr_defn.GetFieldDefn(0).IsNullable() or \ - lyr_defn.GetFieldDefn(0).GetDefault() != 'def_value': - gdaltest.post_reason('fail') - return 'fail' - if lyr_defn.GetGeomFieldCount() != 1: - gdaltest.post_reason('fail') - return 'fail' - if lyr_defn.GetGeomFieldDefn(0).GetName() != 'my_geom': - gdaltest.post_reason('fail') - return 'fail' - if lyr_defn.GetGeomFieldDefn(0).GetType() != ogr.wkbPoint25D: - gdaltest.post_reason('fail') - return 'fail' - if lyr_defn.GetGeomFieldDefn(0).GetSpatialRef().ExportToWkt().find('4326') < 0: - gdaltest.post_reason('fail') - return 'fail' + assert lyr_defn.GetFieldCount() == 5 + assert (lyr_defn.GetFieldDefn(0).GetName() == 'strfield' and \ + lyr_defn.GetFieldDefn(0).GetType() == ogr.OFTString and not \ + lyr_defn.GetFieldDefn(0).IsNullable() and \ + lyr_defn.GetFieldDefn(0).GetDefault() == 'def_value') + assert lyr_defn.GetGeomFieldCount() == 1 + assert lyr_defn.GetGeomFieldDefn(0).GetName() == 'my_geom' + assert lyr_defn.GetGeomFieldDefn(0).GetType() == ogr.wkbPoint25D + assert lyr_defn.GetGeomFieldDefn(0).GetSpatialRef().ExportToWkt().find('4326') >= 0 gdal.PushErrorHandler() fc = lyr.GetFeatureCount() gdal.PopErrorHandler() - if fc != 0: - gdaltest.post_reason('fail') - return 'fail' + assert fc == 0 gdal.FileFromMemBuffer("""/vsimem/carto&POSTFIELDS=q=SELECT COUNT(*) FROM "table1"&api_key=foo""", """{}""") gdal.PushErrorHandler() fc = lyr.GetFeatureCount() gdal.PopErrorHandler() - if fc != 0: - gdaltest.post_reason('fail') - return 'fail' + assert fc == 0 gdal.FileFromMemBuffer("""/vsimem/carto&POSTFIELDS=q=SELECT COUNT(*) FROM "table1"&api_key=foo""", """{"rows":[{"foo":1}], @@ -399,23 +304,17 @@ def ogr_carto_vsimem(): gdal.PushErrorHandler() fc = lyr.GetFeatureCount() gdal.PopErrorHandler() - if fc != 0: - gdaltest.post_reason('fail') - return 'fail' + assert fc == 0 gdal.FileFromMemBuffer("""/vsimem/carto&POSTFIELDS=q=SELECT COUNT(*) FROM "table1"&api_key=foo""", """{"rows":[{"count":9876543210}], "fields":{"count":{"type":"number"}}}""") - if lyr.GetFeatureCount() != 9876543210: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.GetFeatureCount() == 9876543210 gdal.PushErrorHandler() extent = lyr.GetExtent() gdal.PopErrorHandler() - if extent != (0, 0, 0, 0): - gdaltest.post_reason('fail') - return 'fail' + assert extent == (0, 0, 0, 0) gdal.FileFromMemBuffer("""/vsimem/carto&POSTFIELDS=q=SELECT ST_Extent("my_geom") FROM "table1"&api_key=foo""", """{"rows":[{"foo":1}], @@ -424,9 +323,7 @@ def ogr_carto_vsimem(): gdal.PushErrorHandler() extent = lyr.GetExtent() gdal.PopErrorHandler() - if extent != (0, 0, 0, 0): - gdaltest.post_reason('fail') - return 'fail' + assert extent == (0, 0, 0, 0) gdal.FileFromMemBuffer("""/vsimem/carto&POSTFIELDS=q=SELECT ST_Extent("my_geom") FROM "table1"&api_key=foo""", """{"rows":[{"st_extent":""}], @@ -435,9 +332,7 @@ def ogr_carto_vsimem(): gdal.PushErrorHandler() lyr.GetExtent() gdal.PopErrorHandler() - if gdal.GetLastErrorMsg() == '': - gdaltest.post_reason('fail') - return 'fail' + assert gdal.GetLastErrorMsg() != '' gdal.FileFromMemBuffer("""/vsimem/carto&POSTFIELDS=q=SELECT ST_Extent("my_geom") FROM "table1"&api_key=foo""", """{"rows":[{"st_extent":"("}], @@ -446,9 +341,7 @@ def ogr_carto_vsimem(): gdal.PushErrorHandler() lyr.GetExtent() gdal.PopErrorHandler() - if gdal.GetLastErrorMsg() == '': - gdaltest.post_reason('fail') - return 'fail' + assert gdal.GetLastErrorMsg() != '' gdal.FileFromMemBuffer("""/vsimem/carto&POSTFIELDS=q=SELECT ST_Extent("my_geom") FROM "table1"&api_key=foo""", """{"rows":[{"st_extent":"BOX()"}], @@ -457,24 +350,17 @@ def ogr_carto_vsimem(): gdal.PushErrorHandler() lyr.GetExtent() gdal.PopErrorHandler() - if gdal.GetLastErrorMsg() == '': - gdaltest.post_reason('fail') - return 'fail' + assert gdal.GetLastErrorMsg() != '' gdal.FileFromMemBuffer("""/vsimem/carto&POSTFIELDS=q=SELECT ST_Extent("my_geom") FROM "table1"&api_key=foo""", """{"rows":[{"st_extent":"BOX(0,1,2,3)"}], "fields":{"st_extent":{"type":"string"}}}""") - if lyr.GetExtent() != (0.0, 2.0, 1.0, 3.0): - gdaltest.post_reason('fail') - print(lyr.GetExtent()) - return 'fail' + assert lyr.GetExtent() == (0.0, 2.0, 1.0, 3.0) gdal.PushErrorHandler() f = lyr.GetFeature(0) gdal.PopErrorHandler() - if f is not None: - gdaltest.post_reason('fail') - return 'fail' + assert f is None gdal.FileFromMemBuffer("""/vsimem/carto&POSTFIELDS=q=SELECT "cartodb_id", "my_geom", "strfield", "intfield", "doublefield", "boolfield", "datetimefield" FROM "table1" WHERE "cartodb_id" = 0&api_key=foo""", """""") @@ -482,50 +368,38 @@ def ogr_carto_vsimem(): gdal.PushErrorHandler() f = lyr.GetFeature(0) gdal.PopErrorHandler() - if f is not None: - gdaltest.post_reason('fail') - return 'fail' + assert f is None gdal.FileFromMemBuffer("""/vsimem/carto&POSTFIELDS=q=SELECT "cartodb_id", "my_geom", "strfield", "intfield", "doublefield", "boolfield", "datetimefield" FROM "table1" WHERE "cartodb_id" = 0&api_key=foo""", """{"rows":[{"st_extent":"BOX(0,1,2,3)"}], "fields":{"st_extent":{"type":"string"}}}""") f = lyr.GetFeature(0) - if f.GetFID() != -1 or not f.IsFieldNull(0): - gdaltest.post_reason('fail') - return 'fail' + assert f.GetFID() == -1 and f.IsFieldNull(0) gdal.FileFromMemBuffer("""/vsimem/carto&POSTFIELDS=q=SELECT "cartodb_id", "my_geom", "strfield", "intfield", "doublefield", "boolfield", "datetimefield" FROM "table1" WHERE "cartodb_id" = 0&api_key=foo""", """{"rows":[{"cartodb_id":0}], "fields":{"cartodb_id":{"type":"numeric"}}}""") f = lyr.GetFeature(0) - if f.GetFID() != 0: - gdaltest.post_reason('fail') - return 'fail' + assert f.GetFID() == 0 lyr.ResetReading() gdal.PushErrorHandler() f = lyr.GetNextFeature() gdal.PopErrorHandler() - if f is not None: - gdaltest.post_reason('fail') - return 'fail' + assert f is None gdal.FileFromMemBuffer("""/vsimem/carto&POSTFIELDS=q=SELECT "cartodb_id", "my_geom", "strfield", "intfield", "doublefield", "boolfield", "datetimefield" FROM "table1" WHERE "cartodb_id" >= 0 ORDER BY "cartodb_id" ASC LIMIT 500&api_key=foo""", """{"rows":[{"cartodb_id":0}], "fields":{"cartodb_id":{"type":"numeric"}}}""") lyr.ResetReading() f = lyr.GetNextFeature() - if f.GetFID() != 0: - gdaltest.post_reason('fail') - return 'fail' + assert f.GetFID() == 0 gdal.PushErrorHandler() f = lyr.GetNextFeature() gdal.PopErrorHandler() - if f is not None: - gdaltest.post_reason('fail') - return 'fail' + assert f is None gdal.SetConfigOption('CARTO_PAGE_SIZE', '2') gdal.FileFromMemBuffer("""/vsimem/carto&POSTFIELDS=q=SELECT "cartodb_id", "my_geom", "strfield", "intfield", "doublefield", "boolfield", "datetimefield" FROM "table1" WHERE "cartodb_id" >= 0 ORDER BY "cartodb_id" ASC LIMIT 2&api_key=foo""", @@ -533,68 +407,50 @@ def ogr_carto_vsimem(): "fields":{"cartodb_id":{"type":"numeric"}}}""") lyr.ResetReading() f = lyr.GetNextFeature() - if f.GetFID() != 0: - gdaltest.post_reason('fail') - return 'fail' + assert f.GetFID() == 0 f = lyr.GetNextFeature() - if f.GetFID() != 10: - gdaltest.post_reason('fail') - return 'fail' + assert f.GetFID() == 10 gdal.FileFromMemBuffer("""/vsimem/carto&POSTFIELDS=q=SELECT "cartodb_id", "my_geom", "strfield", "intfield", "doublefield", "boolfield", "datetimefield" FROM "table1" WHERE "cartodb_id" >= 11 ORDER BY "cartodb_id" ASC LIMIT 2&api_key=foo""", """{"rows":[{"cartodb_id":12}], "fields":{"cartodb_id":{"type":"numeric"}}}""") f = lyr.GetNextFeature() - if f.GetFID() != 12: - gdaltest.post_reason('fail') - return 'fail' + assert f.GetFID() == 12 gdal.ErrorReset() f = lyr.GetNextFeature() - if f is not None or gdal.GetLastErrorMsg() != '': - gdaltest.post_reason('fail') - return 'fail' + assert f is None and gdal.GetLastErrorMsg() == '' lyr.SetAttributeFilter('strfield is NULL') gdal.PushErrorHandler() fc = lyr.GetFeatureCount() gdal.PopErrorHandler() - if fc != 0: - gdaltest.post_reason('fail') - return 'fail' + assert fc == 0 gdal.FileFromMemBuffer("""/vsimem/carto&POSTFIELDS=q=SELECT "cartodb_id", "my_geom", "strfield", "intfield", "doublefield", "boolfield", "datetimefield" FROM "table1" WHERE (strfield is NULL) AND "cartodb_id" >= 0 ORDER BY "cartodb_id" ASC LIMIT 2&api_key=foo""", """{"rows":[{"cartodb_id":0}], "fields":{"cartodb_id":{"type":"numeric"}}}""") lyr.ResetReading() f = lyr.GetNextFeature() - if f is None: - gdaltest.post_reason('fail') - return 'fail' + assert f is not None gdal.FileFromMemBuffer("""/vsimem/carto&POSTFIELDS=q=SELECT "cartodb_id", "my_geom", "strfield", "intfield", "doublefield", "boolfield", "datetimefield" FROM "table1" WHERE (strfield is NULL) AND "cartodb_id" >= 1 ORDER BY "cartodb_id" ASC LIMIT 2&api_key=foo""", """{"rows":[], "fields":{"cartodb_id":{"type":"numeric"}}}""") gdal.ErrorReset() f = lyr.GetNextFeature() - if f is not None or gdal.GetLastErrorMsg() != '': - gdaltest.post_reason('fail') - return 'fail' + assert f is None and gdal.GetLastErrorMsg() == '' gdal.FileFromMemBuffer("""/vsimem/carto&POSTFIELDS=q=SELECT COUNT(*) FROM "table1" WHERE (strfield is NULL)&api_key=foo""", """{"rows":[{"count":9876543210}], "fields":{"count":{"type":"number"}}}""") - if lyr.GetFeatureCount() != 9876543210: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.GetFeatureCount() == 9876543210 lyr.SetSpatialFilterRect(-180, -90, 180, 90) gdal.PushErrorHandler() fc = lyr.GetFeatureCount() gdal.PopErrorHandler() - if fc != 0: - gdaltest.post_reason('fail') - return 'fail' + assert fc == 0 gdal.FileFromMemBuffer("""/vsimem/carto&POSTFIELDS=q=SELECT "cartodb_id", "my_geom", "strfield", "intfield", "doublefield", "boolfield", "datetimefield" FROM "table1" WHERE ("my_geom" %26%26 'BOX3D(-180 -90, 180 90)'::box3d) AND (strfield is NULL) AND "cartodb_id" >= 0 ORDER BY "cartodb_id" ASC LIMIT 2&api_key=foo""", """{"rows":[{"cartodb_id":20, "my_geom": "010100000000000000000000400000000000804840" }], @@ -602,23 +458,17 @@ def ogr_carto_vsimem(): lyr.ResetReading() f = lyr.GetNextFeature() - if f is None or f.GetGeometryRef().ExportToWkt() != 'POINT (2 49)': - gdaltest.post_reason('fail') - return 'fail' + assert f is not None and f.GetGeometryRef().ExportToWkt() == 'POINT (2 49)' gdal.PushErrorHandler() fc = lyr.GetFeatureCount() gdal.PopErrorHandler() - if fc != 1: - gdaltest.post_reason('fail') - return 'fail' + assert fc == 1 gdal.FileFromMemBuffer("""/vsimem/carto&POSTFIELDS=q=SELECT COUNT(*) FROM "table1" WHERE ("my_geom" %26%26 'BOX3D(-180 -90, 180 90)'::box3d) AND (strfield is NULL)&api_key=foo""", """{"rows":[{"count":9876543210}], "fields":{"count":{"type":"number"}}}""") - if lyr.GetFeatureCount() != 9876543210: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.GetFeatureCount() == 9876543210 # Not permitted in read-only mode f = ogr.Feature(lyr.GetLayerDefn()) @@ -644,9 +494,7 @@ def ogr_carto_vsimem(): gdal.PushErrorHandler() lyr.GetNextFeature() gdal.PopErrorHandler() - if gdal.GetLastErrorMsg() == '': - gdaltest.post_reason('fail') - return 'fail' + assert gdal.GetLastErrorMsg() != '' gdal.FileFromMemBuffer("""/vsimem/carto&POSTFIELDS=q=SELECT cdb_cartodbfytable('my_layer')&api_key=foo""", """{"rows":[], @@ -673,25 +521,19 @@ def ogr_carto_vsimem(): gdal.PushErrorHandler() ret = lyr.CreateFeature(f) gdal.PopErrorHandler() - if ret == 0: - gdaltest.post_reason('fail') - return 'fail' + assert ret != 0 f = None fld_defn = ogr.FieldDefn('INTFIELD', ogr.OFTInteger) # No server answer with gdaltest.error_handler(): ret = lyr.CreateField(fld_defn) - if ret == 0: - gdaltest.post_reason('fail') - return 'fail' + assert ret != 0 gdal.FileFromMemBuffer("""/vsimem/carto&POSTFIELDS=q=ALTER TABLE "my_layer" ADD COLUMN "intfield" INTEGER&api_key=foo""", """{"rows":[], "fields":{}}""") - if lyr.CreateField(fld_defn) != 0: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.CreateField(fld_defn) == 0 fld_defn = ogr.FieldDefn('boolfield', ogr.OFTInteger) fld_defn.SetSubType(ogr.OFSTBoolean) @@ -699,44 +541,32 @@ def ogr_carto_vsimem(): gdal.FileFromMemBuffer("""/vsimem/carto&POSTFIELDS=q=ALTER TABLE "my_layer" ADD COLUMN "boolfield" BOOLEAN&api_key=foo""", """{"rows":[], "fields":{}}""") - if lyr.CreateField(fld_defn) != 0: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.CreateField(fld_defn) == 0 # Invalid field with gdaltest.error_handler(): - if lyr.DeleteField(-1) == 0: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.DeleteField(-1) != 0 # No server answer with gdaltest.error_handler(): - if lyr.DeleteField(0) == 0: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.DeleteField(0) != 0 gdal.FileFromMemBuffer("""/vsimem/carto&POSTFIELDS=q=ALTER TABLE "my_layer" DROP COLUMN "boolfield"&api_key=foo""", """{"rows":[], "fields":{}}""") fld_pos = lyr.GetLayerDefn().GetFieldIndex(fld_defn.GetName()) - if lyr.DeleteField(fld_pos) != 0: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.DeleteField(fld_pos) == 0 gdal.FileFromMemBuffer("""/vsimem/carto&POSTFIELDS=q=ALTER TABLE "my_layer" ADD COLUMN "boolfield" BOOLEAN&api_key=foo""", """{"rows":[], "fields":{}}""") - if lyr.CreateField(fld_defn) != 0: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.CreateField(fld_defn) == 0 f = ogr.Feature(lyr.GetLayerDefn()) gdal.PushErrorHandler() ret = lyr.CreateFeature(f) gdal.PopErrorHandler() - if ret == 0: - gdaltest.post_reason('fail') - return 'fail' + assert ret != 0 f = ogr.Feature(lyr.GetLayerDefn()) f.SetField('strfield', 'foo') @@ -747,76 +577,56 @@ def ogr_carto_vsimem(): """{"rows":[ {"cartodb_id": 1} ], "fields":{"cartodb_id":{"type":"integer"}}}""") ret = lyr.CreateFeature(f) - if ret != 0 or f.GetFID() != 1: - gdaltest.post_reason('fail') - return 'fail' + assert ret == 0 and f.GetFID() == 1 f.SetFID(-1) gdal.PushErrorHandler() ret = lyr.SetFeature(f) gdal.PopErrorHandler() - if ret == 0: - gdaltest.post_reason('fail') - return 'fail' + assert ret != 0 f.SetFID(3) gdal.PushErrorHandler() ret = lyr.SetFeature(f) gdal.PopErrorHandler() - if ret == 0: - gdaltest.post_reason('fail') - return 'fail' + assert ret != 0 gdal.FileFromMemBuffer("""/vsimem/carto&POSTFIELDS=q=UPDATE "my_layer" SET "strfield" = 'foo', "intfield" = 1, "boolfield" = 't', "the_geom" = '0101000020E610000000000000000000400000000000804840' WHERE "cartodb_id" = 3&api_key=foo""", """{"total_rows": 0}""") ret = lyr.SetFeature(f) - if ret != ogr.OGRERR_NON_EXISTING_FEATURE: - gdaltest.post_reason('fail') - return 'fail' + assert ret == ogr.OGRERR_NON_EXISTING_FEATURE gdal.FileFromMemBuffer("""/vsimem/carto&POSTFIELDS=q=UPDATE "my_layer" SET "strfield" = 'foo', "intfield" = 1, "boolfield" = 't', "the_geom" = '0101000020E610000000000000000000400000000000804840' WHERE "cartodb_id" = 3&api_key=foo""", """{"total_rows": 1}""") ret = lyr.SetFeature(f) - if ret != 0: - gdaltest.post_reason('fail') - return 'fail' + assert ret == 0 f = ogr.Feature(lyr.GetLayerDefn()) gdal.PushErrorHandler() ret = lyr.CreateFeature(f) gdal.PopErrorHandler() - if ret == 0: - gdaltest.post_reason('fail') - return 'fail' + assert ret != 0 gdal.FileFromMemBuffer("""/vsimem/carto&POSTFIELDS=q=INSERT INTO "my_layer" DEFAULT VALUES RETURNING "cartodb_id"&api_key=foo""", """{"rows":[ {"cartodb_id": 4} ], "fields":{"cartodb_id":{"type":"integer"}}}""") ret = lyr.CreateFeature(f) - if ret != 0 or f.GetFID() != 4: - gdaltest.post_reason('fail') - return 'fail' + assert ret == 0 and f.GetFID() == 4 gdal.PushErrorHandler() ret = lyr.DeleteFeature(0) gdal.PopErrorHandler() - if ret == 0: - gdaltest.post_reason('fail') - return 'fail' + assert ret != 0 gdal.FileFromMemBuffer("""/vsimem/carto&POSTFIELDS=q=DELETE FROM "my_layer" WHERE "cartodb_id" = 0&api_key=foo""", """{"total_rows": 0}""") ret = lyr.DeleteFeature(0) - if ret != ogr.OGRERR_NON_EXISTING_FEATURE: - gdaltest.post_reason('fail') - return 'fail' + assert ret == ogr.OGRERR_NON_EXISTING_FEATURE gdal.FileFromMemBuffer("""/vsimem/carto&POSTFIELDS=q=DELETE FROM "my_layer" WHERE "cartodb_id" = 0&api_key=foo""", """{"total_rows": 1}""") ret = lyr.DeleteFeature(0) - if ret != 0: - gdaltest.post_reason('fail') - return 'fail' + assert ret == 0 gdal.FileFromMemBuffer("""/vsimem/carto&POSTFIELDS=q=SELECT cdb_cartodbfytable('my_layer')&api_key=foo""", """{"rows":[], @@ -836,9 +646,7 @@ def ogr_carto_vsimem(): f = ogr.Feature(lyr.GetLayerDefn()) f.SetField('strfield', 'foo') ret = lyr.CreateFeature(f) - if ret != 0 or f.GetFID() != 11: - gdaltest.post_reason('fail') - return 'fail' + assert ret == 0 and f.GetFID() == 11 f = ogr.Feature(lyr.GetLayerDefn()) @@ -848,9 +656,8 @@ def ogr_carto_vsimem(): ret = lyr.CreateFeature(f) ds = None if ret != 0 or f.GetFID() != 12: - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' + pytest.fail() ds = gdal.OpenEx('CARTO:foo', gdal.OF_VECTOR | gdal.OF_UPDATE, open_options=['COPY_MODE=NO']) lyr = ds.GetLayer(0) @@ -863,9 +670,8 @@ def ogr_carto_vsimem(): ds = None if ret != 0 or f.GetFID() != 11: - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' + pytest.fail() # Now remove default value to strfield gdal.FileFromMemBuffer(get_full_details_fields_url, @@ -901,40 +707,30 @@ def ogr_carto_vsimem(): with gdaltest.tempfile("""/vsimem/carto&POSTFIELDS=q=SELECT nextval('table1_cartodb_id_seq') AS nextid&api_key=foo""", """{"rows":[{"nextid":11}],"fields":{"nextid":{"type":"number"}}}"""): ret = lyr.CreateFeature(f) - if ret != 0 or f.GetFID() != 11: - gdaltest.post_reason('fail') - return 'fail' + assert ret == 0 and f.GetFID() == 11 f = ogr.Feature(lyr.GetLayerDefn()) f.SetField('strfield', 'bar') ret = lyr.CreateFeature(f) - if ret != 0 or f.GetFID() != 12: - gdaltest.post_reason('fail') - return 'fail' + assert ret == 0 and f.GetFID() == 12 f = ogr.Feature(lyr.GetLayerDefn()) f.SetField('strfield', 'baz') ret = lyr.CreateFeature(f) - if ret != 0 or f.GetFID() != 13: - gdaltest.post_reason('fail') - return 'fail' + assert ret == 0 and f.GetFID() == 13 gdal.ErrorReset() with gdaltest.tempfile("""/vsimem/carto&POSTFIELDS=q=BEGIN;INSERT INTO "table1" ("strfield", "cartodb_id") VALUES ('foo', 11);INSERT INTO "table1" ("strfield", "intfield", "doublefield", "boolfield", "datetimefield", "my_geom") VALUES ('bar', NULL, NULL, NULL, NULL, NULL), ('baz', NULL, NULL, NULL, NULL, NULL);COMMIT;&api_key=foo""", """{"rows":[], "fields":{}}"""): ds = None - if gdal.GetLastErrorMsg() != '': - gdaltest.post_reason('fail') - return 'fail' + assert gdal.GetLastErrorMsg() == '' ds = gdal.OpenEx('CARTO:foo', gdal.OF_VECTOR | gdal.OF_UPDATE, open_options=['COPY_MODE=NO']) gdal.PushErrorHandler() lyr = ds.CreateLayer('table1') gdal.PopErrorHandler() - if lyr is not None: - gdaltest.post_reason('fail') - return 'fail' + assert lyr is None with gdaltest.tempfile("""/vsimem/carto&POSTFIELDS=q=DROP TABLE "table1"&api_key=foo""", """{"rows":[], "fields":{}}"""): @@ -944,18 +740,14 @@ def ogr_carto_vsimem(): f.SetGeometry(ogr.CreateGeometryFromWkt('POLYGON((0 0,0 1,1 0,0 0))')) with gdaltest.tempfile("""/vsimem/carto&POSTFIELDS=q=CREATE TABLE "table1" ( cartodb_id SERIAL,the_geom Geometry(MULTIPOLYGON,0),PRIMARY KEY (cartodb_id) );DROP SEQUENCE IF EXISTS "table1_cartodb_id_seq" CASCADE;CREATE SEQUENCE "table1_cartodb_id_seq" START 1;ALTER SEQUENCE "table1_cartodb_id_seq" OWNED BY "table1".cartodb_id;ALTER TABLE "table1" ALTER COLUMN cartodb_id SET DEFAULT nextval('"table1_cartodb_id_seq"')&api_key=foo""", """{"rows":[], "fields":{}}"""): - if lyr.CreateFeature(f) != 0: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.CreateFeature(f) == 0 gdal.ErrorReset() with gdaltest.tempfile("""/vsimem/carto&POSTFIELDS=q=BEGIN;INSERT INTO "table1" ("the_geom") VALUES ('0106000020E61000000100000001030000000100000004000000000000000000000000000000000000000000000000000000000000000000F03F000000000000F03F000000000000000000000000000000000000000000000000');COMMIT;&api_key=foo""", """{"rows":[], "fields":{}}"""): ds = None - if gdal.GetLastErrorMsg() != '': - gdaltest.post_reason('fail') - return 'fail' + assert gdal.GetLastErrorMsg() == '' ds = gdal.OpenEx('CARTO:foo', gdal.OF_VECTOR | gdal.OF_UPDATE, open_options=['COPY_MODE=NO']) @@ -970,12 +762,8 @@ def ogr_carto_vsimem(): """{"rows":[], "fields":{}}"""): with gdaltest.tempfile("""/vsimem/carto&POSTFIELDS=q=BEGIN;INSERT INTO "table1" ("cartodb_id") VALUES (100);COMMIT;&api_key=foo""", """{"rows":[], "fields":{}}"""): - if lyr.CreateFeature(f) != 0: - gdaltest.post_reason('fail') - return 'fail' - if f.GetFID() != 100: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.CreateFeature(f) == 0 + assert f.GetFID() == 100 ds = None ds = ogr.Open('CARTO:foo', update=1) @@ -983,19 +771,13 @@ def ogr_carto_vsimem(): gdal.PushErrorHandler() ret = ds.DeleteLayer(0) gdal.PopErrorHandler() - if ret == 0: - gdaltest.post_reason('fail') - return 'fail' + assert ret != 0 gdal.ErrorReset() ds = gdal.OpenEx('CARTO:foo', gdal.OF_VECTOR | gdal.OF_UPDATE, open_options=['COPY_MODE=YES']) - if ds is None: - gdaltest.post_reason('fail') - return 'fail' + assert ds is not None lyr = ds.GetLayerByName('table1') - if lyr is None: - gdaltest.post_reason('fail') - return 'fail' + assert lyr is not None with gdaltest.tempfile("""/vsimem/carto/copyfrom?q=COPY%20"table1"%20("strfield","my_geom","cartodb_id")%20FROM%20STDIN%20WITH%20(FORMAT%20text,%20ENCODING%20UTF8)&api_key=foo&POSTFIELDS=copytest\t0101000020E610000000000000000059400000000000005940\t11\n\\.\n""","""{}"""): @@ -1004,16 +786,12 @@ def ogr_carto_vsimem(): f = ogr.Feature(lyr.GetLayerDefn()) f.SetField('strfield', 'copytest') f.SetGeometry(ogr.CreateGeometryFromWkt('POINT(100 100)')) - if lyr.CreateFeature(f) != 0: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.CreateFeature(f) == 0 f = ogr.Feature(lyr.GetLayerDefn()) f.SetField('intfield', 12) f.SetGeometry(ogr.CreateGeometryFromWkt('POINT(100 100)')) - if lyr.CreateFeature(f) != 0: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.CreateFeature(f) == 0 ds = None # force flush @@ -1023,9 +801,7 @@ def ogr_carto_vsimem(): with gdaltest.tempfile("""/vsimem/carto&POSTFIELDS=q=DROP TABLE "table1"&api_key=foo""", """{"rows":[], "fields":{}}"""): ds.ExecuteSQL('DELLAYER:table1') - if gdal.GetLastErrorMsg() != '' or ds.GetLayerByName('table1') is not None: - gdaltest.post_reason('fail') - return 'fail' + assert gdal.GetLastErrorMsg() == '' and ds.GetLayerByName('table1') is None with gdaltest.tempfile('/vsimem/carto&POSTFIELDS=q=SELECT current_schema() LIMIT 500 OFFSET 0&api_key=foo', """{"rows":[{"current_schema":"my_schema"}],"fields":{"current_schema":{"type":"unknown(19)"}}}"""): @@ -1034,22 +810,15 @@ def ogr_carto_vsimem(): with gdaltest.tempfile("""/vsimem/carto&POSTFIELDS=q=SELECT c.relname FROM pg_class c, pg_namespace n WHERE c.relkind in ('r', 'v') AND c.relname !~ '^pg_' AND c.relnamespace=n.oid AND n.nspname = 'my_schema' LIMIT 500 OFFSET 0&api_key=foo""", """{"rows":[{"relname": "a_layer"}],"fields":{"relname":{"type":"string"}}}"""): ds = ogr.Open('CARTO:foo') - if ds.GetLayerByName('a_layer') is None: - gdaltest.post_reason('fail') - return 'fail' - - - - - return 'success' + assert ds.GetLayerByName('a_layer') is not None ############################################################################### # -def ogr_carto_vsimem_cleanup(): +def test_ogr_carto_vsimem_cleanup(): if ogrtest.carto_drv is None: - return 'skip' + pytest.skip() gdal.SetConfigOption('CARTO_API_URL', None) gdal.SetConfigOption('CPL_CURL_ENABLE_VSIMEM', None) @@ -1060,37 +829,31 @@ def ogr_carto_vsimem_cleanup(): for f in gdal.ReadDir('/vsimem/'): gdal.Unlink('/vsimem/' + f) - return 'success' - + ############################################################################### # Run test_ogrsf -def ogr_carto_test_ogrsf(): +def test_ogr_carto_test_ogrsf(): if ogrtest.carto_drv is None or gdal.GetConfigOption('SKIP_SLOW') is not None: - return 'skip' + pytest.skip() if gdaltest.skip_on_travis(): - return 'skip' + pytest.skip() ogrtest.carto_test_server = 'https://gdalautotest2.carto.com' if gdaltest.gdalurlopen(ogrtest.carto_test_server) is None: - print('cannot open %s' % ogrtest.carto_test_server) ogrtest.carto_drv = None - return 'skip' + pytest.skip('cannot open %s' % ogrtest.carto_test_server) import test_cli_utilities if test_cli_utilities.get_test_ogrsf_path() is None: - return 'skip' + pytest.skip() ret = gdaltest.runexternal(test_cli_utilities.get_test_ogrsf_path() + ' --config CARTO_HTTPS NO --config CARTO_PAGE_SIZE 300 -ro "CARTO:gdalautotest2 tables=tm_world_borders_simpl_0_3"') - if ret.find('INFO') == -1 or ret.find('ERROR') != -1: - print(ret) - return 'fail' - - return 'success' + assert ret.find('INFO') != -1 and ret.find('ERROR') == -1 ############################################################################### # Test if driver is available @@ -1102,18 +865,15 @@ def ogr_carto_rw_init(): ogrtest.carto_connection = gdal.GetConfigOption('CARTO_CONNECTION') if ogrtest.carto_connection is None: - print('CARTO_CONNECTION missing') - return 'skip' + pytest.skip('CARTO_CONNECTION missing') if gdal.GetConfigOption('CARTO_API_KEY') is None: - print('CARTO_API_KEY missing') - return 'skip' + pytest.skip('CARTO_API_KEY missing') ogrtest.carto_drv = ogr.GetDriverByName('Carto') if ogrtest.carto_drv is None: - return 'skip' - - return 'success' + pytest.skip() + ############################################################################### # Read/write/update test @@ -1121,11 +881,10 @@ def ogr_carto_rw_init(): def ogr_carto_rw_1(): if ogrtest.carto_drv is None: - return 'skip' + pytest.skip() ds = ogr.Open(ogrtest.carto_connection, update=1) - if ds is None: - return 'fail' + assert ds is not None a_uuid = str(uuid.uuid1()).replace('-', '_') lyr_name = "LAYER_" + a_uuid @@ -1150,9 +909,7 @@ def ogr_carto_rw_1(): f = ogr.Feature(lyr.GetLayerDefn()) ret = lyr.CreateFeature(f) - if ret != 0: - gdaltest.post_reason('fail') - return 'fail' + assert ret == 0 f.SetFID(-1) f.SetField('STRFIELD', "fo'o") @@ -1163,17 +920,13 @@ def ogr_carto_rw_1(): f.SetField('bool', 0) f.SetGeometry(ogr.CreateGeometryFromWkt('POINT (1 2)')) ret = lyr.CreateFeature(f) - if ret != 0: - gdaltest.post_reason('fail') - return 'fail' + assert ret == 0 f.SetField('intfield', 456) f.SetField('bool', 1) f.SetGeometry(ogr.CreateGeometryFromWkt('POINT (3 4)')) ret = lyr.SetFeature(f) - if ret != 0: - gdaltest.post_reason('fail') - return 'fail' + assert ret == 0 fid = f.GetFID() ds = None @@ -1184,17 +937,13 @@ def ogr_carto_rw_1(): for lyr in ds: if lyr.GetName() == lyr_name: found = True - if not found: - gdaltest.post_reason('fail') - return 'fail' + assert found lyr = ds.GetLayerByName(lyr_name) found = False for i in range(lyr.GetLayerDefn().GetFieldCount()): if lyr.GetLayerDefn().GetFieldDefn(i).GetName() == 'strfield': found = True - if not found: - gdaltest.post_reason('fail') - return 'fail' + assert found f = lyr.GetFeature(fid) if f.GetField('strfield') != "fo'o" or \ f.GetField('intfield') != 456 or \ @@ -1203,17 +952,15 @@ def ogr_carto_rw_1(): f.GetField('dt') != '2014/12/04 12:34:56+00' or \ f.GetField('bool') != 1 or \ f.GetGeometryRef().ExportToWkt() != 'POINT (3 4)': - gdaltest.post_reason('fail') f.DumpReadable() ds.ExecuteSQL("DELLAYER:" + lyr_name) - return 'fail' + pytest.fail() lyr.DeleteFeature(fid) f = lyr.GetFeature(fid) if f is not None: - gdaltest.post_reason('fail') ds.ExecuteSQL("DELLAYER:" + lyr_name) - return 'fail' + pytest.fail() # Non-differed field creation lyr.CreateField(ogr.FieldDefn("otherstrfield", ogr.OFTString)) @@ -1239,10 +986,9 @@ def ogr_carto_rw_1(): sql_lyr = ds.ExecuteSQL('SELECT ST_AsText(the_geom_webmercator) AS foo FROM ' + lyr_name) f = sql_lyr.GetNextFeature() if not f.GetField(0).startswith('POINT'): - gdaltest.post_reason('fail') ds.ExecuteSQL("DELLAYER:" + lyr_name) ds.ReleaseResultSet(sql_lyr) - return 'fail' + pytest.fail() ds.ReleaseResultSet(sql_lyr) ds.ExecuteSQL("DELLAYER:" + lyr_name) @@ -1275,50 +1021,26 @@ def ogr_carto_rw_1(): lyr = ds.GetLayerByName(lyr_name) if lyr.GetLayerDefn().GetFieldDefn(lyr.GetLayerDefn().GetFieldIndex('nullable')).IsNullable() != 1: ds.ExecuteSQL("DELLAYER:" + lyr_name) - gdaltest.post_reason('fail') - return 'fail' + pytest.fail() if lyr.GetLayerDefn().GetFieldDefn(lyr.GetLayerDefn().GetFieldIndex('not_nullable')).IsNullable() != 0: ds.ExecuteSQL("DELLAYER:" + lyr_name) - gdaltest.post_reason('fail') - return 'fail' + pytest.fail() if lyr.GetLayerDefn().GetFieldDefn(lyr.GetLayerDefn().GetFieldIndex('field_string')).GetDefault() != "'a''b'": ds.ExecuteSQL("DELLAYER:" + lyr_name) - gdaltest.post_reason('fail') - return 'fail' + pytest.fail() if lyr.GetLayerDefn().GetFieldDefn(lyr.GetLayerDefn().GetFieldIndex('field_datetime_with_default')).GetDefault() != 'CURRENT_TIMESTAMP': ds.ExecuteSQL("DELLAYER:" + lyr_name) - gdaltest.post_reason('fail') - return 'fail' + pytest.fail() f = lyr.GetNextFeature() if f is None or f.GetField('field_string') != 'a\'b' or not f.IsFieldSet('field_datetime_with_default'): - gdaltest.post_reason('fail') ds.ExecuteSQL("DELLAYER:" + lyr_name) - return 'fail' + pytest.fail() ds.ExecuteSQL("DELLAYER:" + lyr_name) - return 'success' -gdaltest_list = [ - ogr_carto_init, - ogr_carto_vsimem, - ogr_carto_vsimem_cleanup, - ogr_carto_test_ogrsf -] - gdaltest_rw_list = [ ogr_carto_rw_init, ogr_carto_rw_1, ] - -if __name__ == '__main__': - - gdaltest.setup_run('ogr_carto') - - if gdal.GetConfigOption('CARTO_CONNECTION') is None: - gdaltest.run_tests(gdaltest_list) - else: - gdaltest.run_tests(gdaltest_rw_list) - - sys.exit(gdaltest.summarize()) diff --git a/autotest/ogr/ogr_cloudant.py b/autotest/ogr/ogr_cloudant.py index 9cd88cdcd5a2..47125e15dbd3 100755 --- a/autotest/ogr/ogr_cloudant.py +++ b/autotest/ogr/ogr_cloudant.py @@ -31,19 +31,18 @@ ############################################################################### import os -import sys -sys.path.append('../pymod') import gdaltest import ogrtest from osgeo import ogr +import pytest ############################################################################### # Test if driver is available -def ogr_cloudant_init(): +def test_ogr_cloudant_init(): ogrtest.cloudant_drv = None @@ -53,7 +52,7 @@ def ogr_cloudant_init(): pass if ogrtest.cloudant_drv is None: - return 'skip' + pytest.skip() if 'CLOUDANT_TEST_SERVER' in os.environ: ogrtest.cloudant_test_server = os.environ['CLOUDANT_TEST_SERVER'] @@ -65,163 +64,113 @@ def ogr_cloudant_init(): ogrtest.cloudant_test_layer = 'gdaltest' if gdaltest.gdalurlopen(ogrtest.cloudant_test_url) is None: - print('cannot open %s' % ogrtest.cloudant_test_url) ogrtest.cloudant_drv = None - return 'skip' - - return 'success' + pytest.skip('cannot open %s' % ogrtest.cloudant_test_url) + ############################################################################### # Test GetFeatureCount() -def ogr_cloudant_GetFeatureCount(): +def test_ogr_cloudant_GetFeatureCount(): if ogrtest.cloudant_drv is None: - return 'skip' + pytest.skip() ds = ogr.Open('cloudant:%s/%s' % (ogrtest.cloudant_test_server, ogrtest.cloudant_test_layer)) - if ds is None: - return 'fail' + assert ds is not None lyr = ds.GetLayer(0) - if lyr is None: - return 'fail' + assert lyr is not None count = lyr.GetFeatureCount() - if count != 52: - gdaltest.post_reason('did not get expected feature count') - print(count) - return 'fail' - - return 'success' + assert count == 52, 'did not get expected feature count' ############################################################################### # Test GetNextFeature() -def ogr_cloudant_GetNextFeature(): +def test_ogr_cloudant_GetNextFeature(): if ogrtest.cloudant_drv is None: - return 'skip' + pytest.skip() ds = ogr.Open('cloudant:%s/%s' % (ogrtest.cloudant_test_server, ogrtest.cloudant_test_layer)) - if ds is None: - return 'fail' + assert ds is not None lyr = ds.GetLayer(0) - if lyr is None: - return 'fail' + assert lyr is not None feat = lyr.GetNextFeature() - if feat is None: - gdaltest.post_reason('did not get expected feature') - return 'fail' + assert feat is not None, 'did not get expected feature' if feat.GetField('_id') != '0400000US01': - gdaltest.post_reason('did not get expected feature') feat.DumpReadable() - return 'fail' - - return 'success' + pytest.fail('did not get expected feature') + ############################################################################### # Test GetSpatialRef() -def ogr_cloudant_GetSpatialRef(): +def test_ogr_cloudant_GetSpatialRef(): if ogrtest.cloudant_drv is None: - return 'skip' + pytest.skip() ds = ogr.Open('cloudant:%s/%s' % (ogrtest.cloudant_test_server, ogrtest.cloudant_test_layer)) - if ds is None: - return 'fail' + assert ds is not None lyr = ds.GetLayer(0) - if lyr is None: - return 'fail' + assert lyr is not None sr = lyr.GetSpatialRef() if sr is None: - return 'success' - - return 'success' + return + ############################################################################### # Test GetExtent() -def ogr_cloudant_GetExtent(): +def test_ogr_cloudant_GetExtent(): if ogrtest.cloudant_drv is None: - return 'skip' + pytest.skip() ds = ogr.Open('cloudant:%s/%s' % (ogrtest.cloudant_test_server, ogrtest.cloudant_test_layer)) - if ds is None: - return 'fail' + assert ds is not None lyr = ds.GetLayer(0) - if lyr is None: - return 'fail' + assert lyr is not None extent = lyr.GetExtent() - if extent is None: - gdaltest.post_reason('did not get expected extent') - return 'fail' - - if extent != (-179.14734, 179.77847, 17.884813, 71.352561): - gdaltest.post_reason('did not get expected extent') - print(extent) - return 'fail' + assert extent is not None, 'did not get expected extent' - return 'success' + assert extent == (-179.14734, 179.77847, 17.884813, 71.352561), \ + 'did not get expected extent' ############################################################################### # Test SetSpatialFilter() -def ogr_cloudant_SetSpatialFilter(): +def test_ogr_cloudant_SetSpatialFilter(): if ogrtest.cloudant_drv is None: - return 'skip' + pytest.skip() if not ogrtest.have_geos(): - return 'skip' + pytest.skip() ds = ogr.Open('cloudant:%s/%s' % (ogrtest.cloudant_test_server, ogrtest.cloudant_test_layer)) - if ds is None: - return 'fail' + assert ds is not None lyr = ds.GetLayer(0) - if lyr is None: - return 'fail' + assert lyr is not None lyr.SetSpatialFilterRect(-104.9847, 39.7392, -104.9847, 39.7392) feat = lyr.GetNextFeature() - if feat is None: - gdaltest.post_reason('did not get expected feature') - return 'fail' + assert feat is not None, 'did not get expected feature' if feat.GetField('NAME') != 'Colorado': - gdaltest.post_reason('did not get expected feature') feat.DumpReadable() - return 'fail' - - return 'success' - - -if gdaltest.skip_on_travis(): - gdaltest_list = [] -else: - gdaltest_list = [ - ogr_cloudant_init, - ogr_cloudant_GetFeatureCount, - ogr_cloudant_GetNextFeature, - ogr_cloudant_GetSpatialRef, - ogr_cloudant_GetExtent, - ogr_cloudant_SetSpatialFilter - ] - -if __name__ == '__main__': + pytest.fail('did not get expected feature') - gdaltest.setup_run('ogr_cloudant') + - gdaltest.run_tests(gdaltest_list) - sys.exit(gdaltest.summarize()) diff --git a/autotest/ogr/ogr_couchdb.py b/autotest/ogr/ogr_couchdb.py index f5c9158da5aa..a43f27f870f1 100755 --- a/autotest/ogr/ogr_couchdb.py +++ b/autotest/ogr/ogr_couchdb.py @@ -30,27 +30,26 @@ ############################################################################### import os -import sys import uuid -sys.path.append('../pymod') import gdaltest import ogrtest from osgeo import gdal from osgeo import ogr +import pytest ############################################################################### # Test if driver is available -def ogr_couchdb_init(): +def test_ogr_couchdb_init(): ogrtest.couchdb_drv = None ogrtest.couchdb_drv = ogr.GetDriverByName('CouchDB') if ogrtest.couchdb_drv is None: - return 'skip' + pytest.skip() if 'COUCHDB_TEST_SERVER' in os.environ: ogrtest.couchdb_test_server = os.environ['COUCHDB_TEST_SERVER'] @@ -59,48 +58,41 @@ def ogr_couchdb_init(): ogrtest.couchdb_temp_layer_name = 'layer_' + str(uuid.uuid1()).replace('-', '_') if gdaltest.gdalurlopen(ogrtest.couchdb_test_server) is None: - print('cannot open %s' % ogrtest.couchdb_test_server) ogrtest.couchdb_drv = None - return 'skip' - - return 'success' + pytest.skip('cannot open %s' % ogrtest.couchdb_test_server) + ############################################################################### # Basic test -def ogr_couchdb_1(): +def test_ogr_couchdb_1(): if ogrtest.couchdb_drv is None: - return 'skip' + pytest.skip() gdal.VectorTranslate('CouchDB:' + ogrtest.couchdb_test_server, 'data/poly.shp', format='CouchDB', layerName=ogrtest.couchdb_temp_layer_name, layerCreationOptions=['UPDATE_PERMISSIONS=ALL']) ds = ogr.Open('couchdb:%s' % ogrtest.couchdb_test_server, update=1) - if ds is None: - return 'fail' + assert ds is not None lyr = ds.GetLayerByName(ogrtest.couchdb_temp_layer_name) f = lyr.GetNextFeature() if f['AREA'] != 215229.266 or f['EAS_ID'] != '168' or f.GetGeometryRef() is None: - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' + pytest.fail() ds.ExecuteSQL('DELLAYER:' + ogrtest.couchdb_temp_layer_name) - return 'success' - ############################################################################### # Test null / unset -def ogr_couchdb_2(): +def test_ogr_couchdb_2(): if ogrtest.couchdb_drv is None: - return 'skip' + pytest.skip() ds = ogr.Open('couchdb:%s' % ogrtest.couchdb_test_server, update=1) - if ds is None: - return 'fail' + assert ds is not None lyr = ds.CreateLayer(ogrtest.couchdb_temp_layer_name, geom_type=ogr.wkbNone, options=['UPDATE_PERMISSIONS=ALL']) lyr.CreateField(ogr.FieldDefn('str_field', ogr.OFTString)) @@ -117,51 +109,31 @@ def ogr_couchdb_2(): f = lyr.GetNextFeature() if f['str_field'] != 'foo': - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' + pytest.fail() f = lyr.GetNextFeature() if f['str_field'] is not None: - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' + pytest.fail() f = lyr.GetNextFeature() if f.IsFieldSet('str_field'): - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' - - return 'success' + pytest.fail() + ############################################################################### # Cleanup -def ogr_couchdb_cleanup(): +def test_ogr_couchdb_cleanup(): if ogrtest.couchdb_drv is None: - return 'skip' + pytest.skip() ds = ogr.Open('couchdb:%s' % ogrtest.couchdb_test_server, update=1) - if ds is None: - return 'fail' + assert ds is not None ds.ExecuteSQL('DELLAYER:' + ogrtest.couchdb_temp_layer_name) - return 'success' - - -gdaltest_list = [ - ogr_couchdb_init, - ogr_couchdb_1, - ogr_couchdb_2, - ogr_couchdb_cleanup -] - -if __name__ == '__main__': - - gdaltest.setup_run('ogr_couchdb') - gdaltest.run_tests(gdaltest_list) - sys.exit(gdaltest.summarize()) diff --git a/autotest/ogr/ogr_csv.py b/autotest/ogr/ogr_csv.py index d6d34a317957..c8f1375e816e 100755 --- a/autotest/ogr/ogr_csv.py +++ b/autotest/ogr/ogr_csv.py @@ -30,26 +30,26 @@ import os import sys -sys.path.append('../pymod') import gdaltest import ogrtest from osgeo import ogr from osgeo import osr from osgeo import gdal +import pytest ############################################################################### # Open CSV datasource. -def ogr_csv_1(): +def test_ogr_csv_1(): gdaltest.csv_ds = None gdaltest.csv_ds = ogr.Open('data/prime_meridian.csv') if gdaltest.csv_ds is not None: - return 'success' - return 'fail' + return + pytest.fail() ############################################################################### @@ -63,8 +63,7 @@ def ogr_csv_check_layer(lyr, expect_code_as_numeric): expect = ['8901', '8902', '8903', '8904'] tr = ogrtest.check_features_against_list(lyr, 'PRIME_MERIDIAN_CODE', expect) - if not tr: - return 'fail' + assert tr lyr.ResetReading() @@ -73,40 +72,29 @@ def ogr_csv_check_layer(lyr, expect_code_as_numeric): 'Instituto Geografico "Augustin Cadazzi" (IGAC); Bogota'] tr = ogrtest.check_features_against_list(lyr, 'INFORMATION_SOURCE', expect) - if not tr: - return 'fail' + assert tr lyr.ResetReading() - return 'success' - ############################################################################### # Verify the some attributes read properly. # -def ogr_csv_2(): +def test_ogr_csv_2(): if gdaltest.csv_ds is None: - return 'skip' + pytest.skip() with gdaltest.error_handler(): - if gdaltest.csv_ds.CreateLayer('foo') is not None: - gdaltest.post_reason('fail') - return 'fail' - if gdaltest.csv_ds.DeleteLayer(0) == 0: - gdaltest.post_reason('fail') - return 'fail' + assert gdaltest.csv_ds.CreateLayer('foo') is None + assert gdaltest.csv_ds.DeleteLayer(0) != 0 lyr = gdaltest.csv_ds.GetLayerByName('prime_meridian') f = ogr.Feature(lyr.GetLayerDefn()) with gdaltest.error_handler(): - if lyr.CreateField(ogr.FieldDefn('foo')) == 0: - gdaltest.post_reason('fail') - return 'fail' - if lyr.CreateFeature(f) == 0: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.CreateField(ogr.FieldDefn('foo')) != 0 + assert lyr.CreateFeature(f) != 0 return ogr_csv_check_layer(lyr, False) @@ -152,9 +140,9 @@ def ogr_csv_copy_layer(layer_name, options): # Copy prime_meridian.csv to a new subtree under the tmp directory. -def ogr_csv_3(): +def test_ogr_csv_3(): if gdaltest.csv_ds is None: - return 'skip' + pytest.skip() ####################################################### # Ensure any old copy of our working datasource is cleaned up @@ -177,19 +165,14 @@ def ogr_csv_3(): # No longer valid since we have editing capabilities if False: # pylint: disable=using-constant-test # Check that we cannot add a new field now - if gdaltest.csv_lyr1.TestCapability(ogr.OLCCreateField) != 0: - gdaltest.post_reason('fail') - return 'fail' + assert gdaltest.csv_lyr1.TestCapability(ogr.OLCCreateField) == 0 field_defn = ogr.FieldDefn('dummy', ogr.OFTString) gdal.PushErrorHandler('CPLQuietErrorHandler') ret = gdaltest.csv_lyr1.CreateField(field_defn) gdal.PopErrorHandler() - if ret == 0: - gdaltest.post_reason('fail') - return 'fail' - - return 'success' + assert ret != 0 + ############################################################################### # Verify the some attributes read properly. @@ -197,9 +180,9 @@ def ogr_csv_3(): # NOTE: one weird thing is that in this pass the prime_meridian_code field # is typed as integer instead of string since it is created literally. -def ogr_csv_4(): +def test_ogr_csv_4(): if gdaltest.csv_ds is None: - return 'skip' + pytest.skip() return ogr_csv_check_layer(gdaltest.csv_lyr1, True) @@ -207,24 +190,22 @@ def ogr_csv_4(): # Copy prime_meridian.csv again, in CRLF mode. -def ogr_csv_5(): +def test_ogr_csv_5(): if gdaltest.csv_ds is None: - return 'skip' + pytest.skip() ####################################################### # Create layer (.csv file) gdaltest.csv_lyr2 = ogr_csv_copy_layer('pm2', ['LINEFORMAT=CRLF', ]) - return 'success' - ############################################################################### # Verify the some attributes read properly. # -def ogr_csv_6(): +def test_ogr_csv_6(): if gdaltest.csv_ds is None: - return 'skip' + pytest.skip() return ogr_csv_check_layer(gdaltest.csv_lyr2, True) @@ -233,47 +214,35 @@ def ogr_csv_6(): # -def ogr_csv_7(): +def test_ogr_csv_7(): if gdaltest.csv_ds is None: - return 'skip' + pytest.skip() lyr = gdaltest.csv_tmpds.GetLayer(0) - if lyr.GetName() != 'pm1': - gdaltest.post_reason('unexpected name for first layer') - return 'fail' + assert lyr.GetName() == 'pm1', 'unexpected name for first layer' gdaltest.csv_lyr1 = None err = gdaltest.csv_tmpds.DeleteLayer(0) - if err != 0: - gdaltest.post_reason('got error code from DeleteLayer') - return 'fail' + assert err == 0, 'got error code from DeleteLayer' - if gdaltest.csv_tmpds.GetLayerCount() != 1 \ - or gdaltest.csv_tmpds.GetLayer(0).GetName() != 'pm2': - gdaltest.post_reason('Layer not destroyed properly?') - return 'fail' + assert gdaltest.csv_tmpds.GetLayerCount() == 1 and gdaltest.csv_tmpds.GetLayer(0).GetName() == 'pm2', \ + 'Layer not destroyed properly?' with gdaltest.error_handler(): - if gdaltest.csv_tmpds.DeleteLayer(-1) == 0: - gdaltest.post_reason('fail') - return 'fail' - if gdaltest.csv_tmpds.DeleteLayer(gdaltest.csv_tmpds.GetLayerCount()) == 0: - gdaltest.post_reason('fail') - return 'fail' + assert gdaltest.csv_tmpds.DeleteLayer(-1) != 0 + assert gdaltest.csv_tmpds.DeleteLayer(gdaltest.csv_tmpds.GetLayerCount()) != 0 gdaltest.csv_tmpds = None - return 'success' - ############################################################################### # Reopen and append a record then close. # -def ogr_csv_8(): +def test_ogr_csv_8(): if gdaltest.csv_ds is None: - return 'skip' + pytest.skip() gdaltest.csv_tmpds = ogr.Open('tmp/csvwrk', update=1) @@ -288,16 +257,14 @@ def ogr_csv_8(): gdaltest.csv_tmpds = None - return 'success' - ############################################################################### # Verify the some attributes read properly. # -def ogr_csv_9(): +def test_ogr_csv_9(): if gdaltest.csv_ds is None: - return 'skip' + pytest.skip() gdaltest.csv_tmpds = ogr.Open('tmp/csvwrk', update=1) @@ -306,8 +273,7 @@ def ogr_csv_9(): expect = ['8901', '8902', '8903', '8904', '7000'] tr = ogrtest.check_features_against_list(lyr, 'PRIME_MERIDIAN_CODE', expect) - if not tr: - return 'fail' + assert tr lyr.ResetReading() @@ -317,72 +283,55 @@ def ogr_csv_9(): 'This is a newline test\n'] tr = ogrtest.check_features_against_list(lyr, 'INFORMATION_SOURCE', expect) - if not tr: - return 'fail' + assert tr lyr.ResetReading() - return 'success' - ############################################################################### # Verify some capabilities and related stuff. # -def ogr_csv_10(): +def test_ogr_csv_10(): if gdaltest.csv_ds is None: - return 'skip' + pytest.skip() lyr = gdaltest.csv_ds.GetLayerByName('prime_meridian') - if lyr.TestCapability('SequentialWrite'): - gdaltest.post_reason('should not have write access to readonly layer') - return 'fail' + assert not lyr.TestCapability('SequentialWrite'), \ + 'should not have write access to readonly layer' - if lyr.TestCapability('RandomRead'): - gdaltest.post_reason('CSV files do not efficiently support ' + assert not lyr.TestCapability('RandomRead'), \ + ('CSV files do not efficiently support ' 'random reading.') - return 'fail' - if lyr.TestCapability('FastGetExtent'): - gdaltest.post_reason('CSV files do not support getextent') - return 'fail' + assert not lyr.TestCapability('FastGetExtent'), 'CSV files do not support getextent' - if lyr.TestCapability('FastFeatureCount'): - gdaltest.post_reason('CSV files do not support fast feature count') - return 'fail' + assert not lyr.TestCapability('FastFeatureCount'), \ + 'CSV files do not support fast feature count' - if not ogr.GetDriverByName('CSV').TestCapability('DeleteDataSource'): - gdaltest.post_reason('CSV files do support DeleteDataSource') - return 'fail' + assert ogr.GetDriverByName('CSV').TestCapability('DeleteDataSource'), \ + 'CSV files do support DeleteDataSource' - if not ogr.GetDriverByName('CSV').TestCapability('CreateDataSource'): - gdaltest.post_reason('CSV files do support CreateDataSource') - return 'fail' + assert ogr.GetDriverByName('CSV').TestCapability('CreateDataSource'), \ + 'CSV files do support CreateDataSource' - if gdaltest.csv_ds.TestCapability('CreateLayer'): - gdaltest.post_reason('readonly datasource should not CreateLayer') - return 'fail' + assert not gdaltest.csv_ds.TestCapability('CreateLayer'), \ + 'readonly datasource should not CreateLayer' - if gdaltest.csv_ds.TestCapability('DeleteLayer'): - gdaltest.post_reason('should not have deletelayer on readonly ds.') - return 'fail' + assert not gdaltest.csv_ds.TestCapability('DeleteLayer'), \ + 'should not have deletelayer on readonly ds.' lyr = gdaltest.csv_tmpds.GetLayer(0) - if not lyr.TestCapability('SequentialWrite'): - gdaltest.post_reason('should have write access to updatable layer') - return 'fail' + assert lyr.TestCapability('SequentialWrite'), \ + 'should have write access to updatable layer' - if not gdaltest.csv_tmpds.TestCapability('CreateLayer'): - gdaltest.post_reason('should have createlayer on updatable ds.') - return 'fail' + assert gdaltest.csv_tmpds.TestCapability('CreateLayer'), \ + 'should have createlayer on updatable ds.' - if not gdaltest.csv_tmpds.TestCapability('DeleteLayer'): - gdaltest.post_reason('should have deletelayer on updatable ds.') - return 'fail' - - return 'success' + assert gdaltest.csv_tmpds.TestCapability('DeleteLayer'), \ + 'should have deletelayer on updatable ds.' ############################################################################### @@ -393,103 +342,78 @@ def ogr_csv_check_testcsvt(lyr): expect = [12, None] tr = ogrtest.check_features_against_list(lyr, 'INTCOL', expect) - if not tr: - return 'fail' + assert tr lyr.ResetReading() expect = [5.7, None] tr = ogrtest.check_features_against_list(lyr, 'REALCOL', expect) - if not tr: - return 'fail' + assert tr lyr.ResetReading() expect = ['foo', ''] tr = ogrtest.check_features_against_list(lyr, 'STRINGCOL', expect) - if not tr: - return 'fail' + assert tr lyr.ResetReading() feat = lyr.GetNextFeature() - if feat.GetFieldAsString('DATETIME') != '2008/12/25 11:22:33': - print(feat.GetFieldAsString('DATETIME')) - return 'fail' + assert feat.GetFieldAsString('DATETIME') == '2008/12/25 11:22:33' feat = lyr.GetNextFeature() - if feat.GetFieldAsString('DATETIME') != '': - print(feat.GetFieldAsString('DATETIME')) - return 'fail' + assert feat.GetFieldAsString('DATETIME') == '' lyr.ResetReading() feat = lyr.GetNextFeature() - if feat.GetFieldAsString('DATE') != '2008/12/25': - print(feat.GetFieldAsString('DATE')) - return 'fail' + assert feat.GetFieldAsString('DATE') == '2008/12/25' feat = lyr.GetNextFeature() - if feat.GetFieldAsString('DATE') != '': - print(feat.GetFieldAsString('DATE')) - return 'fail' + assert feat.GetFieldAsString('DATE') == '' lyr.ResetReading() feat = lyr.GetNextFeature() - if feat.GetFieldAsString('TIME') != '11:22:33': - print(feat.GetFieldAsString('TIME')) - return 'fail' + assert feat.GetFieldAsString('TIME') == '11:22:33' feat = lyr.GetNextFeature() - if feat.GetFieldAsString('TIME') != '': - print(feat.GetFieldAsString('TIME')) - return 'fail' + assert feat.GetFieldAsString('TIME') == '' - if lyr.GetLayerDefn().GetFieldDefn(0).GetWidth() != 5: - gdaltest.post_reason('Field 0 : expecting width = 5') - return 'fail' + assert lyr.GetLayerDefn().GetFieldDefn(0).GetWidth() == 5, \ + 'Field 0 : expecting width = 5' - if lyr.GetLayerDefn().GetFieldDefn(1).GetWidth() != 10: - gdaltest.post_reason('Field 1 : expecting width = 10') - return 'fail' + assert lyr.GetLayerDefn().GetFieldDefn(1).GetWidth() == 10, \ + 'Field 1 : expecting width = 10' - if lyr.GetLayerDefn().GetFieldDefn(1).GetPrecision() != 7: - gdaltest.post_reason('Field 1 : expecting precision = 7') - return 'fail' + assert lyr.GetLayerDefn().GetFieldDefn(1).GetPrecision() == 7, \ + 'Field 1 : expecting precision = 7' - if lyr.GetLayerDefn().GetFieldDefn(2).GetWidth() != 15: - gdaltest.post_reason('Field 2 : expecting width = 15') - return 'fail' + assert lyr.GetLayerDefn().GetFieldDefn(2).GetWidth() == 15, \ + 'Field 2 : expecting width = 15' - if lyr.GetLayerDefn().GetFieldDefn(6).GetType() != ogr.OFTDateTime: - gdaltest.post_reason('Field DATETIME : wrong type') - return 'fail' + assert lyr.GetLayerDefn().GetFieldDefn(6).GetType() == ogr.OFTDateTime, \ + 'Field DATETIME : wrong type' - if lyr.GetLayerDefn().GetFieldDefn(7).GetType() != ogr.OFTDate: - gdaltest.post_reason('Field DATETIME : wrong type') - return 'fail' + assert lyr.GetLayerDefn().GetFieldDefn(7).GetType() == ogr.OFTDate, \ + 'Field DATETIME : wrong type' - if lyr.GetLayerDefn().GetFieldDefn(8).GetType() != ogr.OFTTime: - gdaltest.post_reason('Field DATETIME : wrong type') - return 'fail' + assert lyr.GetLayerDefn().GetFieldDefn(8).GetType() == ogr.OFTTime, \ + 'Field DATETIME : wrong type' lyr.ResetReading() - return 'success' - ############################################################################### # Verify handling of csvt with width and precision specified # Test NULL handling of non string columns too (#2756) -def ogr_csv_11(): +def test_ogr_csv_11(): if gdaltest.csv_ds is None: - return 'skip' + pytest.skip() gdaltest.csv_ds = None gdaltest.csv_ds = ogr.Open('data/testcsvt.csv') - if gdaltest.csv_ds is None: - return 'fail' + assert gdaltest.csv_ds is not None lyr = gdaltest.csv_ds.GetLayerByName('testcsvt') @@ -499,10 +423,10 @@ def ogr_csv_11(): # Verify CREATE_CSVT=YES option -def ogr_csv_12(): +def test_ogr_csv_12(): if gdaltest.csv_ds is None: - return 'skip' + pytest.skip() srclyr = gdaltest.csv_ds.GetLayerByName('testcsvt') @@ -536,9 +460,7 @@ def ogr_csv_12(): feat = srclyr.GetNextFeature() with gdaltest.error_handler(): - if gdaltest.csv_tmpds.CreateLayer('testcsvt_copy') is not None: - gdaltest.post_reason('fail') - return 'fail' + assert gdaltest.csv_tmpds.CreateLayer('testcsvt_copy') is None ####################################################### # Closes everything and reopen @@ -549,8 +471,7 @@ def ogr_csv_12(): ####################################################### # Checks copy - if gdaltest.csv_ds is None: - return 'fail' + assert gdaltest.csv_ds is not None lyr = gdaltest.csv_ds.GetLayerByName('testcsvt_copy') @@ -560,10 +481,10 @@ def ogr_csv_12(): # Verify GEOMETRY=AS_WKT,AS_XY,AS_XYZ,AS_YX options -def ogr_csv_13(): +def test_ogr_csv_13(): if gdaltest.csv_ds is None: - return 'skip' + pytest.skip() gdaltest.csv_tmpds = ogr.Open('tmp/csvwrk', update=1) @@ -575,8 +496,7 @@ def ogr_csv_13(): lyr.CreateField(field_defn) # Some applications expect the WKT column not to be exposed. Check it - if lyr.GetLayerDefn().GetFieldCount() != 1: - return 'fail' + assert lyr.GetLayerDefn().GetFieldCount() == 1 dst_feat = ogr.Feature(feature_def=lyr.GetLayerDefn()) dst_feat.SetGeometry(ogr.CreateGeometryFromWkt('POINT(1 2)')) @@ -644,95 +564,79 @@ def ogr_csv_13(): expect = ['POINT (1 2)'] tr = ogrtest.check_features_against_list(lyr, 'WKT', expect) - if not tr: - return 'fail' + assert tr lyr.ResetReading() expect = ['avalue'] tr = ogrtest.check_features_against_list(lyr, 'ADATA', expect) - if not tr: - return 'fail' + assert tr # Test as_wkt_no_field lyr = gdaltest.csv_tmpds.GetLayerByName('as_wkt_no_field') expect = ['POINT (1 2)'] tr = ogrtest.check_features_against_list(lyr, 'WKT', expect) - if not tr: - return 'fail' + assert tr # Test AS_XY lyr = gdaltest.csv_tmpds.GetLayerByName('as_xy') - if lyr.GetLayerDefn().GetFieldDefn(0).GetName() != 'X': - return 'fail' + assert lyr.GetLayerDefn().GetFieldDefn(0).GetName() == 'X' expect = [1, None] tr = ogrtest.check_features_against_list(lyr, 'X', expect) - if not tr: - return 'fail' + assert tr lyr.ResetReading() expect = [2, None] tr = ogrtest.check_features_against_list(lyr, 'Y', expect) - if not tr: - return 'fail' + assert tr lyr.ResetReading() expect = ['avalue', 'avalue'] tr = ogrtest.check_features_against_list(lyr, 'ADATA', expect) - if not tr: - return 'fail' + assert tr # Test AS_YX lyr = gdaltest.csv_tmpds.GetLayerByName('as_yx') - if lyr.GetLayerDefn().GetFieldDefn(0).GetName() != 'Y': - return 'fail' + assert lyr.GetLayerDefn().GetFieldDefn(0).GetName() == 'Y' expect = [1] tr = ogrtest.check_features_against_list(lyr, 'X', expect) - if not tr: - return 'fail' + assert tr lyr.ResetReading() expect = [2] tr = ogrtest.check_features_against_list(lyr, 'Y', expect) - if not tr: - return 'fail' + assert tr # Test AS_XYZ lyr = gdaltest.csv_tmpds.GetLayerByName('as_xyz') - if lyr.GetLayerDefn().GetFieldDefn(0).GetName() != 'X': - return 'fail' + assert lyr.GetLayerDefn().GetFieldDefn(0).GetName() == 'X' expect = [1] tr = ogrtest.check_features_against_list(lyr, 'X', expect) - if not tr: - return 'fail' + assert tr lyr.ResetReading() expect = [2] tr = ogrtest.check_features_against_list(lyr, 'Y', expect) - if not tr: - return 'fail' + assert tr lyr.ResetReading() expect = [3] tr = ogrtest.check_features_against_list(lyr, 'Z', expect) - if not tr: - return 'fail' - - return 'success' + assert tr ############################################################################### # Copy prime_meridian.csv again, with SEMICOLON as separator -def ogr_csv_14(): +def test_ogr_csv_14(): if gdaltest.csv_ds is None: - return 'skip' + pytest.skip() gdaltest.csv_tmpds = ogr.Open('tmp/csvwrk', update=1) gdaltest.csv_ds = None @@ -742,16 +646,14 @@ def ogr_csv_14(): # Create layer (.csv file) gdaltest.csv_lyr1 = ogr_csv_copy_layer('pm3', ['SEPARATOR=SEMICOLON', ]) - return 'success' - ############################################################################### # Verify the some attributes read properly. # -def ogr_csv_15(): +def test_ogr_csv_15(): if gdaltest.csv_ds is None: - return 'skip' + pytest.skip() return ogr_csv_check_layer(gdaltest.csv_lyr1, True) @@ -760,9 +662,9 @@ def ogr_csv_15(): # -def ogr_csv_16(): +def test_ogr_csv_16(): if gdaltest.csv_ds is None: - return 'skip' + pytest.skip() gdaltest.csv_tmpds = None gdaltest.csv_tmpds = ogr.Open('tmp/csvwrk') @@ -775,38 +677,32 @@ def ogr_csv_16(): # -def ogr_csv_17(): +def test_ogr_csv_17(): if gdaltest.csv_ds is None: - return 'skip' + pytest.skip() csv_ds = ogr.Open('data/wkt.csv') csv_lyr = csv_ds.GetLayer(0) - if csv_lyr.GetLayerDefn().GetGeomType() != ogr.wkbUnknown: - gdaltest.post_reason('did not get wktUnknown for geometry type.') - return 'fail' + assert csv_lyr.GetLayerDefn().GetGeomType() == ogr.wkbUnknown, \ + 'did not get wktUnknown for geometry type.' feat = csv_lyr.GetNextFeature() - if feat.GetField('WKT') != 'POLYGON((6.25 1.25,7.25 1.25,7.25 2.25,6.25 2.25,6.25 1.25))': - gdaltest.post_reason('feature 1: expected wkt value') - return 'fail' + assert feat.GetField('WKT') == 'POLYGON((6.25 1.25,7.25 1.25,7.25 2.25,6.25 2.25,6.25 1.25))', \ + 'feature 1: expected wkt value' - if ogrtest.check_feature_geometry(feat, 'POLYGON((6.25 1.25,7.25 1.25,7.25 2.25,6.25 2.25,6.25 1.25))'): - return 'fail' + assert not ogrtest.check_feature_geometry(feat, 'POLYGON((6.25 1.25,7.25 1.25,7.25 2.25,6.25 2.25,6.25 1.25))') feat = csv_lyr.GetNextFeature() feat = csv_lyr.GetNextFeature() - if ogrtest.check_feature_geometry(feat, 'POLYGON((1.001 1.001,3.999 3.999,3.2 1.6,1.001 1.001))'): - return 'fail' - - return 'success' + assert not ogrtest.check_feature_geometry(feat, 'POLYGON((1.001 1.001,3.999 3.999,3.2 1.6,1.001 1.001))') ############################################################################### # Write to /vsistdout/ -def ogr_csv_18(): +def test_ogr_csv_18(): ds = ogr.GetDriverByName('CSV').CreateDataSource('/vsistdout/') lyr = ds.CreateLayer('foo', options=['GEOMETRY=AS_WKT']) @@ -819,163 +715,131 @@ def ogr_csv_18(): feat.SetGeometry(geom) lyr.CreateFeature(feat) - return 'success' - ############################################################################### # Verify handling of non-numeric values in numeric columns -def ogr_csv_19(): +def test_ogr_csv_19(): if gdaltest.csv_ds is None: - return 'skip' + pytest.skip() gdaltest.csv_ds = None gdaltest.csv_ds = ogr.Open('data/testnull.csv') - if gdaltest.csv_ds is None: - return 'fail' + assert gdaltest.csv_ds is not None lyr = gdaltest.csv_ds.GetLayerByName('testnull') lyr.ResetReading() with gdaltest.error_handler(): - if not ogrtest.check_features_against_list(lyr, 'INTCOL', [12]): - return 'fail' + assert ogrtest.check_features_against_list(lyr, 'INTCOL', [12]) lyr.ResetReading() - if not ogrtest.check_features_against_list(lyr, 'REALCOL', [5.7]): - return 'fail' + assert ogrtest.check_features_against_list(lyr, 'REALCOL', [5.7]) lyr.ResetReading() - if not ogrtest.check_features_against_list(lyr, 'INTCOL2', [None]): - return 'fail' + assert ogrtest.check_features_against_list(lyr, 'INTCOL2', [None]) lyr.ResetReading() - if not ogrtest.check_features_against_list(lyr, 'REALCOL2', [None]): - return 'fail' + assert ogrtest.check_features_against_list(lyr, 'REALCOL2', [None]) lyr.ResetReading() - if not ogrtest.check_features_against_list(lyr, 'STRINGCOL', ['foo']): - return 'fail' - - return 'success' + assert ogrtest.check_features_against_list(lyr, 'STRINGCOL', ['foo']) ############################################################################### # Verify handling of column names with numbers -def ogr_csv_20(): +def test_ogr_csv_20(): if gdaltest.csv_ds is None: - return 'skip' + pytest.skip() gdaltest.csv_ds = None gdaltest.csv_ds = ogr.Open('data/testnumheader1.csv') - if gdaltest.csv_ds is None: - return 'fail' + assert gdaltest.csv_ds is not None lyr = gdaltest.csv_ds.GetLayerByName('testnumheader1') - if lyr is None: - return 'fail' + assert lyr is not None lyr.ResetReading() expect = ['1 - 2', '2-3'] got = [lyr.GetLayerDefn().GetFieldDefn(0).GetNameRef(), lyr.GetLayerDefn().GetFieldDefn(1).GetNameRef()] - if got[0] != expect[0]: - print('column 0 got name %s expected %s' % (str(got[0]), str(expect[0]))) - return 'fail' - if got[1] != expect[1]: - print('column 1 got name %s expected %s' % (str(got[1]), str(expect[1]))) - return 'fail' + assert got[0] == expect[0], \ + ('column 0 got name %s expected %s' % (str(got[0]), str(expect[0]))) + assert got[1] == expect[1], \ + ('column 1 got name %s expected %s' % (str(got[1]), str(expect[1]))) gdaltest.csv_ds = None gdaltest.csv_ds = ogr.Open('data/testnumheader2.csv') - if gdaltest.csv_ds is None: - return 'fail' + assert gdaltest.csv_ds is not None lyr = gdaltest.csv_ds.GetLayerByName('testnumheader2') - if lyr is None: - return 'fail' + assert lyr is not None lyr.ResetReading() expect = ['field_1', 'field_2'] got = [lyr.GetLayerDefn().GetFieldDefn(0).GetNameRef(), lyr.GetLayerDefn().GetFieldDefn(1).GetNameRef()] - if got[0] != expect[0]: - print('column 0 got name %s expected %s' % (str(got[0]), str(expect[0]))) - return 'fail' - if got[1] != expect[1]: - print('column 1 got name %s expected %s' % (str(got[1]), str(expect[1]))) - return 'fail' - - return 'success' + assert got[0] == expect[0], \ + ('column 0 got name %s expected %s' % (str(got[0]), str(expect[0]))) + assert got[1] == expect[1], \ + ('column 1 got name %s expected %s' % (str(got[1]), str(expect[1]))) ############################################################################### # Verify handling of numeric column names with quotes (bug #4361) -def ogr_csv_21(): +def test_ogr_csv_21(): if gdaltest.csv_ds is None: - return 'skip' + pytest.skip() gdaltest.csv_ds = None gdaltest.csv_ds = ogr.Open('data/testquoteheader1.csv') - if gdaltest.csv_ds is None: - return 'fail' + assert gdaltest.csv_ds is not None lyr = gdaltest.csv_ds.GetLayerByName('testquoteheader1') - if lyr is None: - return 'fail' + assert lyr is not None lyr.ResetReading() expect = ['test', '2000', '2000.12'] for i in range(0, 3): got = lyr.GetLayerDefn().GetFieldDefn(i).GetNameRef() - if got != expect[i]: - print('column %d got name %s expected %s' % (i, str(got), str(expect[i]))) - return 'fail' + assert got == expect[i], \ + ('column %d got name %s expected %s' % (i, str(got), str(expect[i]))) gdaltest.csv_ds = None gdaltest.csv_ds = ogr.Open('data/testquoteheader2.csv') - if gdaltest.csv_ds is None: - return 'fail' + assert gdaltest.csv_ds is not None lyr = gdaltest.csv_ds.GetLayerByName('testquoteheader2') - if lyr is None: - return 'fail' + assert lyr is not None lyr.ResetReading() expect = ['field_1', 'field_2', 'field_3'] for i in range(0, 3): got = lyr.GetLayerDefn().GetFieldDefn(i).GetNameRef() - if got != expect[i]: - print('column %d got name %s expected %s' % (i, str(got), str(expect[i]))) - return 'fail' - - return 'success' + assert got == expect[i], \ + ('column %d got name %s expected %s' % (i, str(got), str(expect[i]))) + ############################################################################### # Test handling of UTF8 BOM (bug #4623) -def ogr_csv_22(): +def test_ogr_csv_22(): ds = ogr.Open('data/csv_with_utf8_bom.csv') lyr = ds.GetLayer(0) fld0_name = lyr.GetLayerDefn().GetFieldDefn(0).GetNameRef() - if fld0_name != 'id': - gdaltest.post_reason('bad field name') - print(fld0_name) - return 'fail' + assert fld0_name == 'id', 'bad field name' - return 'success' - -def ogr_csv_23(): +def test_ogr_csv_23(): # create a CSV file with UTF8 BOM ds = ogr.Open('tmp/csvwrk', update=1) lyr = ds.CreateLayer('utf8', options=['WRITE_BOM=YES', 'GEOMETRY=AS_WKT']) @@ -998,9 +862,7 @@ def ogr_csv_23(): exec("ogrtest.ret = (data[:6] == b'\\xef\\xbb\\xbfWKT')") else: ogrtest.ret = (data[:6] == '\xef\xbb\xbfWKT') - if not ogrtest.ret: - gdaltest.post_reason("No UTF8 BOM header on output") - return 'fail' + assert ogrtest.ret, "No UTF8 BOM header on output" # create a CSV file without UTF8 BOM ds = ogr.Open('tmp/csvwrk', update=1) @@ -1019,17 +881,13 @@ def ogr_csv_23(): ds = None data = open('tmp/csvwrk/utf8no.csv', 'rb').read() - if data[:3] == '\xef\xbb\xbfWKT': - gdaltest.post_reason("Found UTF8 BOM header on output!") - return 'fail' - - return 'success' + assert data[:3] != '\xef\xbb\xbfWKT', "Found UTF8 BOM header on output!" ############################################################################### # Test single column CSV files -def ogr_csv_24(): +def test_ogr_csv_24(): # Create an invalid CSV file f = gdal.VSIFOpenL('/vsimem/invalid.csv', 'wb') @@ -1050,29 +908,21 @@ def ogr_csv_24(): ds = ogr.Open('/vsimem/single.csv') lyr = ds.GetLayer(0) - if lyr.GetLayerDefn().GetFieldCount() != 1: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.GetLayerDefn().GetFieldCount() == 1 feat = lyr.GetNextFeature() - if feat.GetField(0) != '': - gdaltest.post_reason('fail') - return 'fail' + assert feat.GetField(0) == '' feat = lyr.GetNextFeature() - if feat.GetField(0) != 'bar': - gdaltest.post_reason('fail') - return 'fail' + assert feat.GetField(0) == 'bar' ds = None gdal.Unlink('/vsimem/single.csv') gdal.Unlink('/vsimem/invalid.csv') - return 'success' - ############################################################################### # Test newline handling (#4452) -def ogr_csv_25(): +def test_ogr_csv_25(): ds = ogr.Open('tmp/csvwrk', update=1) lyr = ds.CreateLayer('newlines', options=['LINEFORMAT=LF']) # just in case tests are run on windows... lyr.CreateField(ogr.FieldDefn('foo', ogr.OFTString)) @@ -1087,17 +937,14 @@ def ogr_csv_25(): EXPECTED = 'foo,\n"windows newline:\r\nlinux newline:\nend of string:"\n' data = open('tmp/csvwrk/newlines.csv', 'rb').read().decode('ascii') - if data != EXPECTED: - gdaltest.post_reason("Newlines changed:\n\texpected=%s\n\tgot= %s" % (repr(EXPECTED), repr(data))) - return 'fail' - - return 'success' + assert data == EXPECTED, \ + ("Newlines changed:\n\texpected=%s\n\tgot= %s" % (repr(EXPECTED), repr(data))) ############################################################################### # Test number padding behaviour (#4469) -def ogr_csv_26(): +def test_ogr_csv_26(): ds = ogr.Open('tmp/csvwrk', update=1) lyr = ds.CreateLayer('num_padding', options=['LINEFORMAT=LF']) # just in case tests are run on windows... @@ -1120,24 +967,18 @@ def ogr_csv_26(): EXPECTED = 'foo,\n10.5000000000000000000000000\n' data = open('tmp/csvwrk/num_padding.csv', 'rb').read().decode('ascii') - if data != EXPECTED: - gdaltest.post_reason("expected=%s got= %s" % (repr(EXPECTED), repr(data))) - return 'fail' - - return 'success' + assert data == EXPECTED, ("expected=%s got= %s" % (repr(EXPECTED), repr(data))) ############################################################################### # Test Eurostat .TSV files -def ogr_csv_27(): +def test_ogr_csv_27(): ds = ogr.Open('data/test_eurostat.tsv') lyr = ds.GetLayer(0) layer_defn = lyr.GetLayerDefn() - if layer_defn.GetFieldCount() != 8: - gdaltest.post_reason('fail') - return 'fail' + assert layer_defn.GetFieldCount() == 8 expected_fields = [('unit', ogr.OFTString), ('geo', ogr.OFTString), @@ -1150,16 +991,8 @@ def ogr_csv_27(): i = 0 for expected_field in expected_fields: fld = layer_defn.GetFieldDefn(i) - if fld.GetName() != expected_field[0]: - print(fld.GetName()) - print(expected_field[0]) - gdaltest.post_reason('fail') - return 'fail' - if fld.GetType() != expected_field[1]: - print(fld.GetType()) - print(expected_field[1]) - gdaltest.post_reason('fail') - return 'fail' + assert fld.GetName() == expected_field[0] + assert fld.GetType() == expected_field[1] i = i + 1 feat = lyr.GetNextFeature() @@ -1172,16 +1005,14 @@ def ogr_csv_27(): feat.GetField('time_2012') != 2.34 or \ feat.IsFieldSet('time_2012_flag'): feat.DumpReadable() - gdaltest.post_reason('fail') - return 'fail' - - return 'success' + pytest.fail() + ############################################################################### # Check that we don't rewrite erroneously a file that has no header (#5161). -def ogr_csv_28(): +def test_ogr_csv_28(): f = open('tmp/ogr_csv_28.csv', 'wb') f.write('1,2\n'.encode('ascii')) @@ -1196,34 +1027,21 @@ def ogr_csv_28(): os.unlink('tmp/ogr_csv_28.csv') - if data != '1,2\n': - gdaltest.post_reason('fail') - print(data) - return 'fail' - - return 'success' + assert data == '1,2\n' ############################################################################### # Check multi geometry field support -def ogr_csv_29(): +def test_ogr_csv_29(): ds = ogr.GetDriverByName('CSV').CreateDataSource('tmp/ogr_csv_29', options=['GEOMETRY=AS_WKT']) - if ds.TestCapability(ogr.ODsCCurveGeometries) != 1: - gdaltest.post_reason('fail') - return 'fail' + assert ds.TestCapability(ogr.ODsCCurveGeometries) == 1 lyr = ds.CreateLayer('test', geom_type=ogr.wkbNone) - if lyr.CreateGeomField(ogr.GeomFieldDefn("geom__WKT_lyr1_EPSG_4326", ogr.wkbPoint)) != 0: - gdaltest.post_reason('fail') - return 'fail' - if lyr.CreateGeomField(ogr.GeomFieldDefn("geom__WKT_lyr2_EPSG_32632", ogr.wkbPolygon)) != 0: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.CreateGeomField(ogr.GeomFieldDefn("geom__WKT_lyr1_EPSG_4326", ogr.wkbPoint)) == 0 + assert lyr.CreateGeomField(ogr.GeomFieldDefn("geom__WKT_lyr2_EPSG_32632", ogr.wkbPolygon)) == 0 with gdaltest.error_handler(): - if lyr.CreateGeomField(ogr.GeomFieldDefn("geom__WKT_lyr2_EPSG_32632", ogr.wkbPolygon)) == 0: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.CreateGeomField(ogr.GeomFieldDefn("geom__WKT_lyr2_EPSG_32632", ogr.wkbPolygon)) != 0 ds = None ds = ogr.Open('tmp/ogr_csv_29', update=1) @@ -1236,84 +1054,63 @@ def ogr_csv_29(): ds = ogr.Open('tmp/ogr_csv_29') lyr = ds.GetLayerByName('test') - if lyr.GetLayerDefn().GetGeomFieldCount() != 2: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.GetLayerDefn().GetGeomFieldCount() == 2 srs = lyr.GetLayerDefn().GetGeomFieldDefn(0).GetSpatialRef() - if srs.GetAuthorityCode(None) != '4326': - gdaltest.post_reason('fail') - return 'fail' + assert srs.GetAuthorityCode(None) == '4326' srs = lyr.GetLayerDefn().GetGeomFieldDefn(1).GetSpatialRef() - if srs.GetAuthorityCode(None) != '32632': - gdaltest.post_reason('fail') - return 'fail' + assert srs.GetAuthorityCode(None) == '32632' feat = lyr.GetNextFeature() geom = feat.GetGeomFieldRef('geom__WKT_lyr1_EPSG_4326') if geom.ExportToWkt() != 'POINT (1 2)': feat.DumpReadable() - gdaltest.post_reason('fail') - return 'fail' + pytest.fail() geom = feat.GetGeomFieldRef('geom__WKT_lyr2_EPSG_32632') if geom.ExportToWkt() != 'POLYGON ((0 0,0 1,1 1,1 0,0 0))': feat.DumpReadable() - gdaltest.post_reason('fail') - return 'fail' + pytest.fail() ds = None - return 'success' - ############################################################################### # Run test_ogrsf -def ogr_csv_30(): +def test_ogr_csv_30(): import test_cli_utilities if test_cli_utilities.get_test_ogrsf_path() is None: - return 'skip' + pytest.skip() ret = gdaltest.runexternal(test_cli_utilities.get_test_ogrsf_path() + ' tmp/ogr_csv_29') - if ret.find('INFO') == -1 or ret.find('ERROR') != -1: - print(ret) - return 'fail' - - return 'success' + assert ret.find('INFO') != -1 and ret.find('ERROR') == -1 ############################################################################### # Read geonames.org allCountries.txt -def ogr_csv_31(): +def test_ogr_csv_31(): ds = ogr.Open('data/allCountries.txt') lyr = ds.GetLayer(0) f = lyr.GetNextFeature() if f.GetField('GEONAMEID') != '3038814' or f.GetField('LATITUDE') != 42.5 or \ f.GetGeometryRef().ExportToWkt() != 'POINT (1.48333 42.5)': - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' + pytest.fail() lyr.ResetReading() f = lyr.GetNextFeature() if f.GetField('GEONAMEID') != '3038814': - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' + pytest.fail() - if lyr.GetFeatureCount() != 10: - gdaltest.post_reason('fail') - print(lyr.GetFeatureCount()) - return 'fail' - - return 'success' + assert lyr.GetFeatureCount() == 10 ############################################################################### # Test AUTODETECT_TYPE=YES -def ogr_csv_32(): +def test_ogr_csv_32(): # Without limit, everything will be detected as string ds = gdal.OpenEx('data/testtypeautodetect.csv', gdal.OF_VECTOR, @@ -1323,18 +1120,11 @@ def ogr_csv_32(): col_values = ['', '1.5', '1', '1.5', '2', '', '2014-09-27 19:01:00', '2014-09-27', '2014-09-27 20:00:00', '2014-09-27', '12:34:56', 'a', 'a', '1', '1', '1.5', '2014-09-27 19:01:00', '2014-09-27', '19:01:00', '2014-09-27T00:00:00Z'] for i in range(lyr.GetLayerDefn().GetFieldCount()): - if lyr.GetLayerDefn().GetFieldDefn(i).GetType() != ogr.OFTString or \ - lyr.GetLayerDefn().GetFieldDefn(i).GetWidth() != 0: - gdaltest.post_reason('fail') - print(i) - print(lyr.GetLayerDefn().GetFieldDefn(i).GetType()) - print(lyr.GetLayerDefn().GetFieldDefn(i).GetWidth()) - return 'fail' + assert (lyr.GetLayerDefn().GetFieldDefn(i).GetType() == ogr.OFTString and \ + lyr.GetLayerDefn().GetFieldDefn(i).GetWidth() == 0) if f.GetField(i) != col_values[i]: - gdaltest.post_reason('fail') - print(i) f.DumpReadable() - return 'fail' + pytest.fail(i) # Without limit, everything will be detected as string ds = gdal.OpenEx('data/testtypeautodetect.csv', gdal.OF_VECTOR, @@ -1342,18 +1132,11 @@ def ogr_csv_32(): lyr = ds.GetLayer(0) f = lyr.GetNextFeature() for i in range(lyr.GetLayerDefn().GetFieldCount()): - if lyr.GetLayerDefn().GetFieldDefn(i).GetType() != ogr.OFTString or \ - lyr.GetLayerDefn().GetFieldDefn(i).GetWidth() != 0: - gdaltest.post_reason('fail') - print(i) - print(lyr.GetLayerDefn().GetFieldDefn(i).GetType()) - print(lyr.GetLayerDefn().GetFieldDefn(i).GetWidth()) - return 'fail' + assert (lyr.GetLayerDefn().GetFieldDefn(i).GetType() == ogr.OFTString and \ + lyr.GetLayerDefn().GetFieldDefn(i).GetWidth() == 0) if f.GetField(i) != col_values[i]: - gdaltest.post_reason('fail') - print(i) f.DumpReadable() - return 'fail' + pytest.fail(i) # We limit to the first "1.5" line ds = gdal.OpenEx('data/testtypeautodetect.csv', gdal.OF_VECTOR, @@ -1366,26 +1149,17 @@ def ogr_csv_32(): col_values = ['', 1.5, 1, 1.5, 2, '', '2014/09/27 19:01:00', '2014/09/27', '2014/09/27 20:00:00', '2014/09/27', '12:34:56', 'a', 'a', '1', 1, 1.5, '2014/09/27 19:01:00', '2014/09/27', '19:01:00', '2014/09/27 00:00:00+00'] for i in range(lyr.GetLayerDefn().GetFieldCount()): - if lyr.GetLayerDefn().GetFieldDefn(i).GetType() != col_type[i] or \ - lyr.GetLayerDefn().GetFieldDefn(i).GetWidth() != 0: - gdaltest.post_reason('fail') - print(i) - print(lyr.GetLayerDefn().GetFieldDefn(i).GetType()) - print(lyr.GetLayerDefn().GetFieldDefn(i).GetWidth()) - return 'fail' + assert (lyr.GetLayerDefn().GetFieldDefn(i).GetType() == col_type[i] and \ + lyr.GetLayerDefn().GetFieldDefn(i).GetWidth() == 0) if f.GetField(i) != col_values[i]: - gdaltest.post_reason('fail') - print(i) f.DumpReadable() - return 'fail' + pytest.fail(i) # Without QUOTED_FIELDS_AS_STRING=YES, str3 will be detected as integer ds = gdal.OpenEx('data/testtypeautodetect.csv', gdal.OF_VECTOR, open_options=['AUTODETECT_TYPE=YES', 'AUTODETECT_SIZE_LIMIT=300']) lyr = ds.GetLayer(0) - if lyr.GetLayerDefn().GetFieldDefn(lyr.GetLayerDefn().GetFieldIndex('str3')).GetType() != ogr.OFTInteger: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.GetLayerDefn().GetFieldDefn(lyr.GetLayerDefn().GetFieldIndex('str3')).GetType() == ogr.OFTInteger # We limit to the first 2 lines ds = gdal.OpenEx('data/testtypeautodetect.csv', gdal.OF_VECTOR, @@ -1398,18 +1172,11 @@ def ogr_csv_32(): col_values = ['', 1.5, 1, 1.5, 2, None, '2014/09/27 19:01:00', '2014/09/27 00:00:00', '2014/09/27 20:00:00', '2014/09/27', '12:34:56', 'a', 'a', '1', '1', '1.5', '2014-09-27 19:01:00', '2014-09-27', '19:01:00', '2014/09/27 00:00:00+00'] for i in range(lyr.GetLayerDefn().GetFieldCount()): - if lyr.GetLayerDefn().GetFieldDefn(i).GetType() != col_type[i] or \ - lyr.GetLayerDefn().GetFieldDefn(i).GetWidth() != 0: - gdaltest.post_reason('fail') - print(i) - print(lyr.GetLayerDefn().GetFieldDefn(i).GetType()) - print(lyr.GetLayerDefn().GetFieldDefn(i).GetWidth()) - return 'fail' + assert (lyr.GetLayerDefn().GetFieldDefn(i).GetType() == col_type[i] and \ + lyr.GetLayerDefn().GetFieldDefn(i).GetWidth() == 0) if f.GetField(i) != col_values[i]: - gdaltest.post_reason('fail') - print(i) f.DumpReadable() - return 'fail' + pytest.fail(i) # Test AUTODETECT_WIDTH=YES ds = gdal.OpenEx('data/testtypeautodetect.csv', gdal.OF_VECTOR, @@ -1420,20 +1187,12 @@ def ogr_csv_32(): col_precision = [0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] for i in range(lyr.GetLayerDefn().GetFieldCount()): - if lyr.GetLayerDefn().GetFieldDefn(i).GetType() != col_type[i] or \ - lyr.GetLayerDefn().GetFieldDefn(i).GetWidth() != col_width[i] or \ - lyr.GetLayerDefn().GetFieldDefn(i).GetPrecision() != col_precision[i]: - gdaltest.post_reason('fail') - print(i) - print(lyr.GetLayerDefn().GetFieldDefn(i).GetType()) - print(lyr.GetLayerDefn().GetFieldDefn(i).GetWidth()) - print(lyr.GetLayerDefn().GetFieldDefn(i).GetPrecision()) - return 'fail' + assert (lyr.GetLayerDefn().GetFieldDefn(i).GetType() == col_type[i] and \ + lyr.GetLayerDefn().GetFieldDefn(i).GetWidth() == col_width[i] and \ + lyr.GetLayerDefn().GetFieldDefn(i).GetPrecision() == col_precision[i]) if f.GetField(i) != col_values[i]: - gdaltest.post_reason('fail') - print(i) f.DumpReadable() - return 'fail' + pytest.fail(i) # Test AUTODETECT_WIDTH=STRING_ONLY ds = gdal.OpenEx('data/testtypeautodetect.csv', gdal.OF_VECTOR, @@ -1444,20 +1203,12 @@ def ogr_csv_32(): col_precision = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] for i in range(lyr.GetLayerDefn().GetFieldCount()): - if lyr.GetLayerDefn().GetFieldDefn(i).GetType() != col_type[i] or \ - lyr.GetLayerDefn().GetFieldDefn(i).GetWidth() != col_width[i] or \ - lyr.GetLayerDefn().GetFieldDefn(i).GetPrecision() != col_precision[i]: - gdaltest.post_reason('fail') - print(i) - print(lyr.GetLayerDefn().GetFieldDefn(i).GetType()) - print(lyr.GetLayerDefn().GetFieldDefn(i).GetWidth()) - print(lyr.GetLayerDefn().GetFieldDefn(i).GetPrecision()) - return 'fail' + assert (lyr.GetLayerDefn().GetFieldDefn(i).GetType() == col_type[i] and \ + lyr.GetLayerDefn().GetFieldDefn(i).GetWidth() == col_width[i] and \ + lyr.GetLayerDefn().GetFieldDefn(i).GetPrecision() == col_precision[i]) if f.GetField(i) != col_values[i]: - gdaltest.post_reason('fail') - print(i) f.DumpReadable() - return 'fail' + pytest.fail(i) # Test KEEP_SOURCE_COLUMNS=YES ds = gdal.OpenEx('data/testtypeautodetect.csv', gdal.OF_VECTOR, @@ -1470,18 +1221,11 @@ def ogr_csv_32(): '2014/09/27 00:00:00+00', '2014-09-27T00:00:00Z'] for i in range(lyr.GetLayerDefn().GetFieldCount()): - if lyr.GetLayerDefn().GetFieldDefn(i).GetType() != ogr.OFTString and \ - lyr.GetLayerDefn().GetFieldDefn(i + 1).GetNameRef() != lyr.GetLayerDefn().GetFieldDefn(i).GetNameRef() + '_original': - gdaltest.post_reason('fail') - print(i) - print(lyr.GetLayerDefn().GetFieldDefn(i).GetNameRef()) - print(lyr.GetLayerDefn().GetFieldDefn(i + 1).GetNameRef()) - return 'fail' + assert (lyr.GetLayerDefn().GetFieldDefn(i).GetType() == ogr.OFTString or \ + lyr.GetLayerDefn().GetFieldDefn(i + 1).GetNameRef() == lyr.GetLayerDefn().GetFieldDefn(i).GetNameRef() + '_original') if f.GetField(i) != col_values[i]: - gdaltest.post_reason('fail') - print(i) f.DumpReadable() - return 'fail' + pytest.fail(i) # Test warnings for fid in [3, # string in real field @@ -1500,10 +1244,8 @@ def ogr_csv_32(): lyr.GetFeature(fid) gdal.PopErrorHandler() if gdal.GetLastErrorType() != gdal.CE_Warning: - gdaltest.post_reason('fail') - print(fid) f.DumpReadable() - return 'fail' + pytest.fail(fid) # Test Real -> Integer64 (https://github.com/OSGeo/gdal/issues/343) gdal.FileFromMemBuffer('/vsimem/testtypeautodetect.csv', @@ -1516,17 +1258,15 @@ def ogr_csv_32(): lyr = ds.GetLayer(0) f = lyr.GetNextFeature() if f.GetField(0) != 1.2: - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' - - return 'success' + pytest.fail() + ############################################################################### # Test Boolean, Int16 and Float32 support -def ogr_csv_33(): +def test_ogr_csv_33(): ds = gdal.OpenEx('data/testtypeautodetectboolean.csv', gdal.OF_VECTOR, open_options=['AUTODETECT_TYPE=YES']) @@ -1534,17 +1274,11 @@ def ogr_csv_33(): f = lyr.GetNextFeature() col_values = [1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 1, 'y'] for i in range(lyr.GetLayerDefn().GetFieldCount()): - if (i < 10 and lyr.GetLayerDefn().GetFieldDefn(i).GetSubType() != ogr.OFSTBoolean) or \ - (i >= 10 and lyr.GetLayerDefn().GetFieldDefn(i).GetSubType() == ogr.OFSTBoolean): - gdaltest.post_reason('fail') - print(i) - print(lyr.GetLayerDefn().GetFieldDefn(i).GetSubType()) - return 'fail' + assert (not (i < 10 and lyr.GetLayerDefn().GetFieldDefn(i).GetSubType() != ogr.OFSTBoolean) or \ + (i >= 10 and lyr.GetLayerDefn().GetFieldDefn(i).GetSubType() == ogr.OFSTBoolean)) if f.GetField(i) != col_values[i]: - gdaltest.post_reason('fail') - print(i) f.DumpReadable() - return 'fail' + pytest.fail(i) ds = None ds = ogr.GetDriverByName('CSV').CreateDataSource('/vsimem/subtypes.csv') @@ -1568,35 +1302,26 @@ def ogr_csv_33(): ds = ogr.Open('/vsimem/subtypes.csv') lyr = ds.GetLayer(0) - if lyr.GetLayerDefn().GetFieldDefn(0).GetType() != ogr.OFTInteger or \ - lyr.GetLayerDefn().GetFieldDefn(0).GetSubType() != ogr.OFSTBoolean: - gdaltest.post_reason('fail') - return 'fail' - if lyr.GetLayerDefn().GetFieldDefn(1).GetType() != ogr.OFTInteger or \ - lyr.GetLayerDefn().GetFieldDefn(1).GetSubType() != ogr.OFSTInt16: - gdaltest.post_reason('fail') - return 'fail' - if lyr.GetLayerDefn().GetFieldDefn(2).GetType() != ogr.OFTReal or \ - lyr.GetLayerDefn().GetFieldDefn(2).GetSubType() != ogr.OFSTFloat32: - gdaltest.post_reason('fail') - return 'fail' + assert (lyr.GetLayerDefn().GetFieldDefn(0).GetType() == ogr.OFTInteger and \ + lyr.GetLayerDefn().GetFieldDefn(0).GetSubType() == ogr.OFSTBoolean) + assert (lyr.GetLayerDefn().GetFieldDefn(1).GetType() == ogr.OFTInteger and \ + lyr.GetLayerDefn().GetFieldDefn(1).GetSubType() == ogr.OFSTInt16) + assert (lyr.GetLayerDefn().GetFieldDefn(2).GetType() == ogr.OFTReal and \ + lyr.GetLayerDefn().GetFieldDefn(2).GetSubType() == ogr.OFSTFloat32) f = lyr.GetNextFeature() if f.GetField(0) != 1 or f.GetField(1) != -32768 or f.GetField(2) != 1.23: - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' + pytest.fail() ds = None gdal.Unlink('/vsimem/subtypes.csv') gdal.Unlink('/vsimem/subtypes.csvt') - return 'success' - ############################################################################### # Test Integer64 support -def ogr_csv_34(): +def test_ogr_csv_34(): ds = gdal.OpenEx('data/testtypeautodetectinteger64.csv', gdal.OF_VECTOR, open_options=['AUTODETECT_TYPE=YES']) @@ -1605,18 +1330,14 @@ def ogr_csv_34(): col_values = [1, 10000000000, 10000000000, 10000000000.0] for i in range(lyr.GetLayerDefn().GetFieldCount()): if f.GetField(i) != col_values[i]: - gdaltest.post_reason('fail') - print(i) f.DumpReadable() - return 'fail' + pytest.fail(i) f = lyr.GetNextFeature() col_values = [10000000000, 1, 10000000000, 1.0] for i in range(lyr.GetLayerDefn().GetFieldCount()): if f.GetField(i) != col_values[i]: - gdaltest.post_reason('fail') - print(i) f.DumpReadable() - return 'fail' + pytest.fail(i) ds = None ds = ogr.GetDriverByName('CSV').CreateDataSource('/vsimem/int64.csv') @@ -1633,21 +1354,18 @@ def ogr_csv_34(): lyr = ds.GetLayer(0) f = lyr.GetNextFeature() if f.GetField(0) != 10000000000: - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' + pytest.fail() ds = None gdal.Unlink('/vsimem/int64.csv') gdal.Unlink('/vsimem/int64.csvt') - return 'success' - ############################################################################### # Test comma separator -def ogr_csv_35(): +def test_ogr_csv_35(): gdal.FileFromMemBuffer('/vsimem/ogr_csv_35.csv', """FIELD_1 "FIELD 2" FIELD_3 @@ -1659,9 +1377,8 @@ def ogr_csv_35(): lyr = ds.GetLayer(0) f = lyr.GetNextFeature() if f['FIELD_1'] != 'VAL1' or f['FIELD 2'] != 'VAL 2' or f['FIELD_3'] != 'VAL 3': - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' + pytest.fail() ds = None gdal.Unlink('/vsimem/ogr_csv_35.csv') @@ -1680,20 +1397,15 @@ def ogr_csv_35(): data = gdal.VSIFReadL(1, 10000, f).decode('ascii') gdal.VSIFCloseL(f) - if data.find('FIELD_1 "FIELD 2"') < 0 or data.find('VAL1 "VAL 2"') < 0: - gdaltest.post_reason('fail') - print(data) - return 'fail' + assert data.find('FIELD_1 "FIELD 2"') >= 0 and data.find('VAL1 "VAL 2"') >= 0 gdal.Unlink('/vsimem/ogr_csv_35.csv') - return 'success' - ############################################################################### # Test GEOM_POSSIBLE_NAMES open option -def ogr_csv_36(): +def test_ogr_csv_36(): gdal.FileFromMemBuffer('/vsimem/ogr_csv_36.csv', """id,mygeometry,format @@ -1709,29 +1421,24 @@ def ogr_csv_36(): lyr = ds.GetLayer(0) f = lyr.GetNextFeature() if f.GetGeometryRef().ExportToWkt() != 'POINT (1 2)' or f['id'] != '1' or f['mygeometry'] != 'POINT(1 2)' or f['format'] != 'wkt': - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' + pytest.fail() f = lyr.GetNextFeature() if f.GetGeometryRef().ExportToWkt() != 'POINT (2 49)': - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' + pytest.fail() f = lyr.GetNextFeature() if f.GetGeometryRef().ExportToWkt() != 'POINT (3 50)': - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' + pytest.fail() f = lyr.GetNextFeature() if f.GetGeometryRef().ExportToWkt() != 'POINT (3 50)': - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' + pytest.fail() f = lyr.GetNextFeature() if f.GetGeometryRef() is not None: - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' + pytest.fail() ds = None # Test prefix* pattern @@ -1740,9 +1447,8 @@ def ogr_csv_36(): lyr = ds.GetLayer(0) f = lyr.GetNextFeature() if f.GetGeometryRef().ExportToWkt() != 'POINT (1 2)': - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' + pytest.fail() ds = None # Test *suffix pattern @@ -1751,9 +1457,8 @@ def ogr_csv_36(): lyr = ds.GetLayer(0) f = lyr.GetNextFeature() if f.GetGeometryRef().ExportToWkt() != 'POINT (1 2)': - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' + pytest.fail() ds = None # Test *middle* pattern @@ -1762,43 +1467,35 @@ def ogr_csv_36(): lyr = ds.GetLayer(0) f = lyr.GetNextFeature() if f.GetGeometryRef().ExportToWkt() != 'POINT (1 2)': - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' + pytest.fail() ds = None # Test non matching pattern ds = gdal.OpenEx('/vsimem/ogr_csv_36.csv', gdal.OF_VECTOR, open_options=['GEOM_POSSIBLE_NAMES=bla']) lyr = ds.GetLayer(0) - if lyr.GetLayerDefn().GetGeomFieldCount() != 0: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.GetLayerDefn().GetGeomFieldCount() == 0 ds = None # Check KEEP_GEOM_COLUMNS=NO ds = gdal.OpenEx('/vsimem/ogr_csv_36.csv', gdal.OF_VECTOR, open_options=['GEOM_POSSIBLE_NAMES=mygeometry', 'KEEP_GEOM_COLUMNS=NO']) lyr = ds.GetLayer(0) - if lyr.GetLayerDefn().GetFieldCount() != 2: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.GetLayerDefn().GetFieldCount() == 2 f = lyr.GetNextFeature() if f.GetGeometryRef().ExportToWkt() != 'POINT (1 2)' or f['id'] != '1' or f['format'] != 'wkt': - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' + pytest.fail() ds = None gdal.Unlink('/vsimem/ogr_csv_36.csv') - return 'success' - ############################################################################### # Test X_POSSIBLE_NAMES, Y_POSSIBLE_NAMES and Z_POSSIBLE_NAMES open options -def ogr_csv_37(): +def test_ogr_csv_37(): gdal.FileFromMemBuffer('/vsimem/ogr_csv_37.csv', """id,y,other,x,z @@ -1812,19 +1509,16 @@ def ogr_csv_37(): lyr = ds.GetLayer(0) f = lyr.GetNextFeature() if f.GetGeometryRef().ExportToWkt() != 'POINT (2 49)' or f['id'] != '1' or f['x'] != 2 or f['y'] != 49 or f['other'] != 'a' or f['z'] != '100': - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' + pytest.fail() f = lyr.GetNextFeature() if f.GetGeometryRef().ExportToWkt() != 'POINT (3 50)': - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' + pytest.fail() f = lyr.GetNextFeature() if f.GetGeometryRef() is not None: - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' + pytest.fail() ds = None # Check Z_POSSIBLE_NAMES @@ -1833,44 +1527,36 @@ def ogr_csv_37(): lyr = ds.GetLayer(0) f = lyr.GetNextFeature() if f.GetGeometryRef().ExportToWkt() != 'POINT (2 49 100)' or f['id'] != '1' or f['x'] != 2 or f['y'] != 49 or f['other'] != 'a' or f['z'] != 100: - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' + pytest.fail() f = lyr.GetNextFeature() if f.GetGeometryRef().ExportToWkt() != 'POINT (3 50)': - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' + pytest.fail() f = lyr.GetNextFeature() if f.GetGeometryRef() is not None: - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' + pytest.fail() ds = None # Check KEEP_GEOM_COLUMNS=NO ds = gdal.OpenEx('/vsimem/ogr_csv_37.csv', gdal.OF_VECTOR, open_options=['X_POSSIBLE_NAMES=long,x', 'Y_POSSIBLE_NAMES=lat,y', 'KEEP_GEOM_COLUMNS=NO']) lyr = ds.GetLayer(0) - if lyr.GetLayerDefn().GetFieldCount() != 3: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.GetLayerDefn().GetFieldCount() == 3 f = lyr.GetNextFeature() if f.GetGeometryRef().ExportToWkt() != 'POINT (2 49)' or f['id'] != '1' or f['other'] != 'a': - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' + pytest.fail() ds = None gdal.Unlink('/vsimem/ogr_csv_37.csv') - return 'success' - ############################################################################### # Test GeoCSV WKT type -def ogr_csv_38(): +def test_ogr_csv_38(): ds = ogr.GetDriverByName('CSV').CreateDataSource('/vsimem/ogr_csv_38.csv') srs = osr.SpatialReference() @@ -1885,30 +1571,23 @@ def ogr_csv_38(): ds = ogr.Open('/vsimem/ogr_csv_38.csv') lyr = ds.GetLayer(0) - if lyr.GetLayerDefn().GetGeomFieldDefn(0).GetName() != 'mygeom': - gdaltest.post_reason('fail') - return 'fail' - if lyr.GetLayerDefn().GetGeomFieldDefn(0).GetSpatialRef().ExportToWkt().find('4326') < 0: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.GetLayerDefn().GetGeomFieldDefn(0).GetName() == 'mygeom' + assert lyr.GetLayerDefn().GetGeomFieldDefn(0).GetSpatialRef().ExportToWkt().find('4326') >= 0 f = lyr.GetNextFeature() if f.GetGeometryRef().ExportToWkt() != 'POINT (2 49)': - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' + pytest.fail() ds = None gdal.Unlink('/vsimem/ogr_csv_38.csv') gdal.Unlink('/vsimem/ogr_csv_38.csvt') gdal.Unlink('/vsimem/ogr_csv_38.prj') - return 'success' - ############################################################################### # Test GeoCSV CoordX and CoordY types -def ogr_csv_39(): +def test_ogr_csv_39(): ds = ogr.GetDriverByName('CSV').CreateDataSource('/vsimem/ogr_csv_39.csv') lyr = ds.CreateLayer('ogr_csv_38', options=['GEOMETRY=AS_XY', 'CREATE_CSVT=YES']) @@ -1923,21 +1602,18 @@ def ogr_csv_39(): lyr = ds.GetLayer(0) f = lyr.GetNextFeature() if f.GetGeometryRef().ExportToWkt() != 'POINT (2 49)': - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' + pytest.fail() ds = None gdal.Unlink('/vsimem/ogr_csv_39.csv') gdal.Unlink('/vsimem/ogr_csv_39.csvt') - return 'success' - ############################################################################### # Test X_POSSIBLE_NAMES, Y_POSSIBLE_NAMES, GEOM_POSSIBLE_NAMES and KEEP_GEOM_COLUMNS=NO together (#6137) -def ogr_csv_40(): +def test_ogr_csv_40(): gdal.FileFromMemBuffer('/vsimem/ogr_csv_40.csv', """latitude,longitude,the_geom,id @@ -1949,9 +1625,8 @@ def ogr_csv_40(): lyr = ds.GetLayer(0) f = lyr.GetNextFeature() if f.GetGeometryRef().ExportToWkt() != 'POINT (2 49)' or f['id'] != '1' or f['the_geom'] != '0101000020E61000004486E281C5C257C068B89DDA998F4640': - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' + pytest.fail() f = lyr.GetNextFeature() ds = None @@ -1967,21 +1642,18 @@ def ogr_csv_40(): lyr = ds.GetLayer(0) f = lyr.GetNextFeature() if f.GetGeometryRef().ExportToWkt().find('POINT (-95.04') < 0 or f['id'] != '1' or f['longitude'] != '2' or f['latitude'] != '49': - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' + pytest.fail() f = lyr.GetNextFeature() ds = None gdal.Unlink('/vsimem/ogr_csv_40.csv') - return 'success' - ############################################################################### # Test GEOM_POSSIBLE_NAMES and KEEP_GEOM_COLUMNS=NO together with empty content in geom column (#6152) -def ogr_csv_41(): +def test_ogr_csv_41(): gdal.FileFromMemBuffer('/vsimem/ogr_csv_41.csv', """id,the_geom,foo @@ -1993,20 +1665,17 @@ def ogr_csv_41(): lyr = ds.GetLayer(0) f = lyr.GetNextFeature() if f.GetGeometryRef() is not None or f['id'] != '1' or f['foo'] != 'bar': - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' + pytest.fail() ds = None gdal.Unlink('/vsimem/ogr_csv_41.csv') - return 'success' - ############################################################################### # Test writing field with empty content -def ogr_csv_42(): +def test_ogr_csv_42(): ds = ogr.GetDriverByName('CSV').CreateDataSource('/vsimem/ogr_csv_42.csv') lyr = ds.CreateLayer('ogr_csv_42') @@ -2014,19 +1683,16 @@ def ogr_csv_42(): lyr.CreateField(ogr.FieldDefn('foo', ogr.OFTInteger)) f = ogr.Feature(lyr.GetLayerDefn()) f.SetField('id', 1) - if lyr.CreateFeature(f) != 0: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.CreateFeature(f) == 0 ds = None gdal.Unlink('/vsimem/ogr_csv_42.csv') - return 'success' ############################################################################### # Test editing capabilities -def ogr_csv_43(): +def test_ogr_csv_43(): ds = ogr.GetDriverByName('CSV').CreateDataSource('/vsimem/ogr_csv_43.csv') lyr = ds.CreateLayer('ogr_csv_43', options=['GEOMETRY=AS_WKT', 'CREATE_CSVT=YES']) @@ -2034,83 +1700,55 @@ def ogr_csv_43(): f = ogr.Feature(lyr.GetLayerDefn()) f.SetField('id', 1) f.SetGeometry(ogr.CreateGeometryFromWkt('POINT(2 49)')) - if lyr.CreateFeature(f) != 0: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.CreateFeature(f) == 0 f = None lyr.SetNextByIndex(0) f = lyr.GetNextFeature() if f['id'] != 1: - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' + pytest.fail() f = None - if lyr.TestCapability(ogr.OLCCreateField) != 1: - gdaltest.post_reason('fail') - return 'fail' - if lyr.CreateField(ogr.FieldDefn('foo', ogr.OFTString)) != 0: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.TestCapability(ogr.OLCCreateField) == 1 + assert lyr.CreateField(ogr.FieldDefn('foo', ogr.OFTString)) == 0 with gdaltest.error_handler(): - if lyr.CreateField(ogr.FieldDefn('foo', ogr.OFTString)) == 0: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.CreateField(ogr.FieldDefn('foo', ogr.OFTString)) != 0 f = lyr.GetFeature(1) f.SetField('foo', 'bar') - if lyr.TestCapability(ogr.OLCRandomWrite) != 1: - gdaltest.post_reason('fail') - return 'fail' - if lyr.SetFeature(f) != 0: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.TestCapability(ogr.OLCRandomWrite) == 1 + assert lyr.SetFeature(f) == 0 f = lyr.GetFeature(1) if f['id'] != 1 or f['foo'] != 'bar' or f.GetGeometryRef().ExportToWkt() != 'POINT (2 49)': - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' + pytest.fail() lyr.ResetReading() f = lyr.GetNextFeature() if f['id'] != 1 or f['foo'] != 'bar' or f.GetGeometryRef().ExportToWkt() != 'POINT (2 49)': - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' + pytest.fail() f = lyr.GetNextFeature() - if f is not None: - gdaltest.post_reason('fail') - return 'fail' - if lyr.GetFeatureCount() != 1: - gdaltest.post_reason('fail') - return 'fail' + assert f is None + assert lyr.GetFeatureCount() == 1 f = ogr.Feature(lyr.GetLayerDefn()) f.SetField('id', 2) f.SetGeometry(ogr.CreateGeometryFromWkt('POINT(3 50)')) f.SetField('foo', 'baz') - if lyr.CreateFeature(f) != 0: - gdaltest.post_reason('fail') - return 'fail' - if f.GetFID() != 2: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.CreateFeature(f) == 0 + assert f.GetFID() == 2 f = lyr.GetFeature(2) if f['id'] != 2 or f['foo'] != 'baz' or f.GetGeometryRef().ExportToWkt() != 'POINT (3 50)': - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' - if lyr.GetFeatureCount() != 2: - gdaltest.post_reason('fail') - return 'fail' + pytest.fail() + assert lyr.GetFeatureCount() == 2 lyr.SetNextByIndex(1) f = lyr.GetNextFeature() if f['id'] != 2: - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' + pytest.fail() f = lyr.GetNextFeature() if f is not None: - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' + pytest.fail() f = None ds = None @@ -2119,67 +1757,34 @@ def ogr_csv_43(): lyr = ds.GetLayer(0) f = lyr.GetFeature(2) if f['id'] != 2 or f['foo'] != 'baz' or f.GetGeometryRef().ExportToWkt() != 'POINT (3 50)': - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' + pytest.fail() f = None - if lyr.TestCapability(ogr.OLCDeleteField) != 1: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.TestCapability(ogr.OLCDeleteField) == 1 with gdaltest.error_handler(): - if lyr.DeleteField(-1) == 0: - gdaltest.post_reason('fail') - return 'fail' - if lyr.DeleteField(lyr.GetLayerDefn().GetFieldIndex('foo')) != 0: - gdaltest.post_reason('fail') - return 'fail' - if lyr.TestCapability(ogr.OLCDeleteFeature) != 1: - gdaltest.post_reason('fail') - return 'fail' - if lyr.DeleteFeature(2) != 0: - gdaltest.post_reason('fail') - return 'fail' - if lyr.DeleteFeature(2) != ogr.OGRERR_NON_EXISTING_FEATURE: - gdaltest.post_reason('fail') - return 'fail' - if lyr.DeleteFeature(3) != ogr.OGRERR_NON_EXISTING_FEATURE: - gdaltest.post_reason('fail') - return 'fail' - if lyr.GetFeature(2) is not None: - gdaltest.post_reason('fail') - return 'fail' - if lyr.GetFeature(3) is not None: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.DeleteField(-1) != 0 + assert lyr.DeleteField(lyr.GetLayerDefn().GetFieldIndex('foo')) == 0 + assert lyr.TestCapability(ogr.OLCDeleteFeature) == 1 + assert lyr.DeleteFeature(2) == 0 + assert lyr.DeleteFeature(2) == ogr.OGRERR_NON_EXISTING_FEATURE + assert lyr.DeleteFeature(3) == ogr.OGRERR_NON_EXISTING_FEATURE + assert lyr.GetFeature(2) is None + assert lyr.GetFeature(3) is None lyr.ResetReading() f = lyr.GetNextFeature() - if f is None: - gdaltest.post_reason('fail') - return 'fail' + assert f is not None f = lyr.GetNextFeature() - if f is not None: - gdaltest.post_reason('fail') - return 'fail' + assert f is None f = ogr.Feature(lyr.GetLayerDefn()) f['id'] = 3 - if lyr.CreateFeature(f) != 0: - gdaltest.post_reason('fail') - return 'fail' - if f.GetFID() != 3: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.CreateFeature(f) == 0 + assert f.GetFID() == 3 f = None - if lyr.CreateField(ogr.FieldDefn('foo', ogr.OFTString)) != 0: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.CreateField(ogr.FieldDefn('foo', ogr.OFTString)) == 0 f = lyr.GetFeature(1) - if f['foo'] == 'bar': - gdaltest.post_reason('fail') - return 'fail' + assert f['foo'] != 'bar' f = lyr.GetFeature(3) - if f.GetFID() != 3: - gdaltest.post_reason('fail') - return 'fail' + assert f.GetFID() == 3 f = None ds = None @@ -2187,31 +1792,19 @@ def ogr_csv_43(): lyr = ds.GetLayer(0) f = lyr.GetFeature(2) if f['id'] != 3: - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' + pytest.fail() f = None - if lyr.DeleteField(lyr.GetLayerDefn().GetFieldIndex('foo')) != 0: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.DeleteField(lyr.GetLayerDefn().GetFieldIndex('foo')) == 0 f = ogr.Feature(lyr.GetLayerDefn()) f.SetGeometry(ogr.CreateGeometryFromWkt('POINT(4 51)')) - if lyr.CreateFeature(f) != 0: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.CreateFeature(f) == 0 if f.GetFID() != 3: - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' - if lyr.GetExtent() != (2.0, 4.0, 49.0, 51.0): - gdaltest.post_reason('fail') - return 'fail' - if lyr.DeleteFeature(f.GetFID()) != 0: - gdaltest.post_reason('fail') - return 'fail' - if lyr.GetFeatureCount() != 2: - gdaltest.post_reason('fail') - return 'fail' + pytest.fail() + assert lyr.GetExtent() == (2.0, 4.0, 49.0, 51.0) + assert lyr.DeleteFeature(f.GetFID()) == 0 + assert lyr.GetFeatureCount() == 2 with gdaltest.error_handler(): lyr.SetSpatialFilter(-1, None) @@ -2221,76 +1814,42 @@ def ogr_csv_43(): lyr.SetSpatialFilterRect(0, 0, 0, 100, 100) lyr.SetSpatialFilter(0, lyr.GetSpatialFilter()) lyr.SetSpatialFilter(lyr.GetSpatialFilter()) - if lyr.GetFeatureCount() != 1: - gdaltest.post_reason('fail') - return 'fail' - if lyr.GetExtent() != (2.0, 2.0, 49.0, 49.0): - gdaltest.post_reason('fail') - return 'fail' - if lyr.GetExtent(geom_field=0) != (2.0, 2.0, 49.0, 49.0): - gdaltest.post_reason('fail') - return 'fail' + assert lyr.GetFeatureCount() == 1 + assert lyr.GetExtent() == (2.0, 2.0, 49.0, 49.0) + assert lyr.GetExtent(geom_field=0) == (2.0, 2.0, 49.0, 49.0) with gdaltest.error_handler(): lyr.GetExtent(geom_field=-1) lyr.SetAttributeFilter(None) - if lyr.TestCapability(ogr.OLCCurveGeometries) != 1: - gdaltest.post_reason('fail') - return 'fail' - if lyr.TestCapability(ogr.OLCTransactions) != 0: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.TestCapability(ogr.OLCCurveGeometries) == 1 + assert lyr.TestCapability(ogr.OLCTransactions) == 0 lyr.StartTransaction() lyr.RollbackTransaction() lyr.CommitTransaction() - if lyr.GetGeometryColumn() != '': - gdaltest.post_reason('fail') - return 'fail' - if lyr.GetFIDColumn() != '': - gdaltest.post_reason('fail') - return 'fail' - - if lyr.TestCapability(ogr.OLCReorderFields) != 1: - gdaltest.post_reason('fail') - return 'fail' - if lyr.ReorderFields([0, 1]) != 0: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.GetGeometryColumn() == '' + assert lyr.GetFIDColumn() == '' + + assert lyr.TestCapability(ogr.OLCReorderFields) == 1 + assert lyr.ReorderFields([0, 1]) == 0 with gdaltest.error_handler(): - if lyr.ReorderFields([0, -1]) == 0: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.ReorderFields([0, -1]) != 0 - if lyr.TestCapability(ogr.OLCAlterFieldDefn) != 1: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.TestCapability(ogr.OLCAlterFieldDefn) == 1 fld_defn = lyr.GetLayerDefn().GetFieldDefn(0) - if lyr.AlterFieldDefn(0, fld_defn, 0) != 0: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.AlterFieldDefn(0, fld_defn, 0) == 0 with gdaltest.error_handler(): - if lyr.AlterFieldDefn(-1, fld_defn, 0) == 0: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.AlterFieldDefn(-1, fld_defn, 0) != 0 f = lyr.GetFeature(2) f.SetGeomField(0, ogr.CreateGeometryFromWkt('POINT (1 2)')) - if lyr.SetFeature(f) != 0: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.SetFeature(f) == 0 f = None - if lyr.TestCapability(ogr.OLCCreateGeomField) != 1: - gdaltest.post_reason('fail') - return 'fail' - if lyr.CreateGeomField(ogr.GeomFieldDefn('geom__WKT_2')) != 0: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.TestCapability(ogr.OLCCreateGeomField) == 1 + assert lyr.CreateGeomField(ogr.GeomFieldDefn('geom__WKT_2')) == 0 f = lyr.GetFeature(2) f.SetGeomField(1, ogr.CreateGeometryFromWkt('POINT (3 4)')) - if lyr.SetFeature(f) != 0: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.SetFeature(f) == 0 f = None ds = None @@ -2299,33 +1858,23 @@ def ogr_csv_43(): lyr = ds.GetLayer(0) f = lyr.GetFeature(2) if f['WKT'] != 'POINT (1 2)' or f['_WKT_2'] != 'POINT (3 4)': - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' - if lyr.SetFeature(f) != 0: - gdaltest.post_reason('fail') - return 'fail' + pytest.fail() + assert lyr.SetFeature(f) == 0 f = None - if lyr.DeleteFeature(2) != 0: - gdaltest.post_reason('fail') - return 'fail' - if lyr.GetFeature(2) is not None: - gdaltest.post_reason('fail') - return 'fail' - if lyr.DeleteFeature(2) != ogr.OGRERR_NON_EXISTING_FEATURE: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.DeleteFeature(2) == 0 + assert lyr.GetFeature(2) is None + assert lyr.DeleteFeature(2) == ogr.OGRERR_NON_EXISTING_FEATURE ds = None gdal.Unlink('/vsimem/ogr_csv_43.csv') gdal.Unlink('/vsimem/ogr_csv_43.csvt') - return 'success' ############################################################################### # Test seeking back while creating -def ogr_csv_44(): +def test_ogr_csv_44(): ds = ogr.GetDriverByName('CSV').CreateDataSource('/vsimem/ogr_csv_44.csv') lyr = ds.CreateLayer('ogr_csv_44', options=['GEOMETRY=AS_WKT']) @@ -2333,36 +1882,29 @@ def ogr_csv_44(): f = ogr.Feature(lyr.GetLayerDefn()) f.SetField('id', 1) f.SetGeometry(ogr.CreateGeometryFromWkt('POINT(2 49)')) - if lyr.CreateFeature(f) != 0: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.CreateFeature(f) == 0 f = None f = lyr.GetFeature(1) if f['id'] != 1 or f.GetGeometryRef().ExportToWkt() != 'POINT (2 49)': - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' + pytest.fail() f = ogr.Feature(lyr.GetLayerDefn()) f.SetField('id', 2) - if lyr.CreateFeature(f) != 0: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.CreateFeature(f) == 0 f = lyr.GetFeature(2) if f['id'] != 2 or f.GetGeometryRef() is not None: - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' + pytest.fail() ds = None gdal.Unlink('/vsimem/ogr_csv_44.csv') - return 'success' ############################################################################### # Test QGIS use case that consists in reopening a file just after calling # CreateField() on the main dataset and assuming that file is already serialized. -def ogr_csv_45(): +def test_ogr_csv_45(): ds = ogr.GetDriverByName('CSV').CreateDataSource('/vsimem/ogr_csv_45.csv') lyr = ds.CreateLayer('ogr_csv_45', options=['GEOMETRY=AS_WKT']) @@ -2375,20 +1917,18 @@ def ogr_csv_45(): ds2 = ogr.Open('/vsimem/ogr_csv_45.csv') lyr2 = ds2.GetLayer(0) - if lyr2.GetLayerDefn().GetFieldCount() != 3: - return 'fail' + assert lyr2.GetLayerDefn().GetFieldCount() == 3 ds2 = None ds = None gdal.Unlink('/vsimem/ogr_csv_45.csv') - return 'success' ############################################################################### # Test edition of CSV files with X_POSSIBLE_NAMES, Y_POSSIBLE_NAMES open options -def ogr_csv_46(): +def test_ogr_csv_46(): ds = ogr.GetDriverByName('CSV').CreateDataSource('/vsimem/ogr_csv_46.csv') lyr = ds.CreateLayer('ogr_csv_46') @@ -2415,14 +1955,11 @@ def ogr_csv_46(): ds = ogr.Open('/vsimem/ogr_csv_46.csv') lyr = ds.GetLayer(0) - if lyr.GetLayerDefn().GetFieldCount() != 4: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.GetLayerDefn().GetFieldCount() == 4 f = lyr.GetNextFeature() if f['id'] != '1' or f['X'] != '10' or f['Y'] != '20' or f['Z'] != '3': - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' + pytest.fail() ds = None ds = gdal.OpenEx('/vsimem/ogr_csv_46.csv', gdal.OF_VECTOR | gdal.OF_UPDATE, open_options=['KEEP_GEOM_COLUMNS=NO', 'X_POSSIBLE_NAMES=X', 'Y_POSSIBLE_NAMES=Y']) @@ -2435,14 +1972,11 @@ def ogr_csv_46(): ds = ogr.Open('/vsimem/ogr_csv_46.csv') lyr = ds.GetLayer(0) - if lyr.GetLayerDefn().GetFieldCount() != 4: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.GetLayerDefn().GetFieldCount() == 4 f = lyr.GetNextFeature() if f['id'] != '1' or f['X'] != '-10' or f['Y'] != '-20' or f['Z'] != '3': - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' + pytest.fail() ds = None ds = gdal.OpenEx('/vsimem/ogr_csv_46.csv', gdal.OF_VECTOR | gdal.OF_UPDATE, open_options=['KEEP_GEOM_COLUMNS=NO', 'X_POSSIBLE_NAMES=X', 'Y_POSSIBLE_NAMES=Y', 'Z_POSSIBLE_NAMES=Z']) @@ -2455,34 +1989,25 @@ def ogr_csv_46(): ds = ogr.Open('/vsimem/ogr_csv_46.csv') lyr = ds.GetLayer(0) - if lyr.GetLayerDefn().GetFieldCount() != 4: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.GetLayerDefn().GetFieldCount() == 4 f = lyr.GetNextFeature() if f['id'] != '1' or f['X'] != '-1' or f['Y'] != '-2' or f['Z'] != '-3': - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' + pytest.fail() ds = None gdal.Unlink('/vsimem/ogr_csv_46.csv') - return 'success' - ############################################################################### # Test writing XYZM -def ogr_csv_47(): +def test_ogr_csv_47(): ds = ogr.GetDriverByName('CSV').CreateDataSource('/vsimem/ogr_csv_47.csv') - if ds.TestCapability(ogr.ODsCMeasuredGeometries) != 1: - gdaltest.post_reason('fail') - return 'fail' + assert ds.TestCapability(ogr.ODsCMeasuredGeometries) == 1 lyr = ds.CreateLayer('ogr_csv_47', options=['GEOMETRY=AS_WKT']) - if lyr.TestCapability(ogr.OLCMeasuredGeometries) != 1: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.TestCapability(ogr.OLCMeasuredGeometries) == 1 lyr.CreateField(ogr.FieldDefn('id', ogr.OFTInteger)) f = ogr.Feature(lyr.GetLayerDefn()) f['id'] = 1 @@ -2495,20 +2020,17 @@ def ogr_csv_47(): lyr = ds.GetLayer(0) f = lyr.GetNextFeature() if f.GetGeometryRef().ExportToIsoWkt() != 'POINT ZM (1 2 3 4)': - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' + pytest.fail() ds = None gdal.Unlink('/vsimem/ogr_csv_47.csv') - return 'success' - ############################################################################### # Test reading/writing StringList, etc.. -def ogr_csv_48(): +def test_ogr_csv_48(): gdal.FileFromMemBuffer('/vsimem/ogr_csv_48.csvt', 'JsonStringList,JsonIntegerList,JsonInteger64List,JsonRealList\n') gdal.FileFromMemBuffer('/vsimem/ogr_csv_48.csv', @@ -2522,32 +2044,24 @@ def ogr_csv_48(): data = gdal.VSIFReadL(1, 10000, f).decode('ascii') gdal.VSIFCloseL(f) - if data.find('stringlist,intlist,int64list,reallist\n"[ ""a"", """" ]",[ 1 ],[ 1234567890123 ],[ 0.125') != 0: - gdaltest.post_reason('fail') - print(data) - return 'fail' + assert data.find('stringlist,intlist,int64list,reallist\n"[ ""a"", """" ]",[ 1 ],[ 1234567890123 ],[ 0.125') == 0 f = gdal.VSIFOpenL('/vsimem/ogr_csv_48_out.csvt', 'rb') data = gdal.VSIFReadL(1, 10000, f).decode('ascii') gdal.VSIFCloseL(f) - if data.find('JSonStringList,JSonIntegerList,JSonInteger64List,JSonRealList') != 0: - gdaltest.post_reason('fail') - print(data) - return 'fail' + assert data.find('JSonStringList,JSonIntegerList,JSonInteger64List,JSonRealList') == 0 gdal.Unlink('/vsimem/ogr_csv_48.csv') gdal.Unlink('/vsimem/ogr_csv_48.csvt') gdal.Unlink('/vsimem/ogr_csv_48_out.csv') gdal.Unlink('/vsimem/ogr_csv_48_out.csvt') - return 'success' - ############################################################################### # Test EMPTY_STRING_AS_NULL=ES -def ogr_csv_49(): +def test_ogr_csv_49(): gdal.FileFromMemBuffer('/vsimem/ogr_csv_49.csv', """id,str 1, @@ -2557,31 +2071,26 @@ def ogr_csv_49(): lyr = ds.GetLayer(0) f = lyr.GetNextFeature() if not f.IsFieldNull('str'): - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' + pytest.fail() ds = None gdal.Unlink('/vsimem/ogr_csv_49.csv') - return 'success' - ############################################################################### -def ogr_csv_more_than_100_geom_fields(): +def test_ogr_csv_more_than_100_geom_fields(): with gdaltest.error_handler(): ds = ogr.Open('data/more_than_100_geom_fields.csv') lyr = ds.GetLayer(0) lyr.GetNextFeature() - return 'success' - ############################################################################### -def ogr_csv_string_quoting_always(): +def test_ogr_csv_string_quoting_always(): gdal.VectorTranslate('/vsimem/ogr_csv_string_quoting_always.csv', 'data/poly.shp', format='CSV', @@ -2592,10 +2101,7 @@ def ogr_csv_string_quoting_always(): data = gdal.VSIFReadL(1, 10000, f).decode('ascii') gdal.VSIFCloseL(f) - if data.find('"AREA","EAS_ID","PRFEDEA"\n215229.266,"168","35043411"') != 0: - gdaltest.post_reason('fail') - print(data) - return 'fail' + assert data.find('"AREA","EAS_ID","PRFEDEA"\n215229.266,"168","35043411"') == 0 ds = gdal.OpenEx('/vsimem/ogr_csv_string_quoting_always.csv', gdal.OF_UPDATE | gdal.OF_VECTOR) gdal.VectorTranslate(ds, 'data/poly.shp', @@ -2607,21 +2113,16 @@ def ogr_csv_string_quoting_always(): data = gdal.VSIFReadL(1, 10000, f).decode('ascii') gdal.VSIFCloseL(f) - if data.find('"AREA","EAS_ID","PRFEDEA"\n215229.266,"168","35043411"\n247328.172,"179","35043423"') != 0: - gdaltest.post_reason('fail') - print(data) - return 'fail' + assert data.find('"AREA","EAS_ID","PRFEDEA"\n215229.266,"168","35043411"\n247328.172,"179","35043423"') == 0 gdal.Unlink('/vsimem/ogr_csv_string_quoting_always.csv') gdal.Unlink('/vsimem/ogr_csv_string_quoting_always.csvt') gdal.Unlink('/vsimem/ogr_csv_string_quoting_always.prj') - return 'success' - ############################################################################### -def ogr_csv_string_quoting_if_ambiguous(): +def test_ogr_csv_string_quoting_if_ambiguous(): src_ds = gdal.GetDriverByName('Memory').Create('', 0, 0, 0, gdal.GDT_Unknown) lyr = src_ds.CreateLayer('layer') @@ -2641,19 +2142,14 @@ def ogr_csv_string_quoting_if_ambiguous(): data = gdal.VSIFReadL(1, 10000, f).decode('ascii') gdal.VSIFCloseL(f) - if data.find('"00123",x,"1.25"') < 0: - gdaltest.post_reason('fail') - print(data) - return 'fail' + assert data.find('"00123",x,"1.25"') >= 0 gdal.Unlink('/vsimem/ogr_csv_string_quoting_if_ambiguous.csv') - return 'success' - ############################################################################### -def ogr_csv_string_quoting_if_needed(): +def test_ogr_csv_string_quoting_if_needed(): src_ds = gdal.GetDriverByName('Memory').Create('', 0, 0, 0, gdal.GDT_Unknown) lyr = src_ds.CreateLayer('layer') @@ -2674,19 +2170,14 @@ def ogr_csv_string_quoting_if_needed(): data = gdal.VSIFReadL(1, 10000, f).decode('ascii') gdal.VSIFCloseL(f) - if data.find('00123,x,1.25') < 0: - gdaltest.post_reason('fail') - print(data) - return 'fail' + assert data.find('00123,x,1.25') >= 0 gdal.Unlink('/vsimem/ogr_csv_string_quoting_if_needed.csv') - return 'success' - ############################################################################### -def ogr_csv_iter_and_set_feature(): +def test_ogr_csv_iter_and_set_feature(): gdal.FileFromMemBuffer('/vsimem/ogr_csv_iter_and_set_feature.csv', """id,str 1, @@ -2704,20 +2195,16 @@ def ogr_csv_iter_and_set_feature(): gdal.Unlink('/vsimem/ogr_csv_iter_and_set_feature.csv') - if count != 2: - print(count) - return 'fail' - - return 'success' + assert count == 2 ############################################################################### # -def ogr_csv_cleanup(): +def test_ogr_csv_cleanup(): if gdaltest.csv_ds is None: - return 'skip' + pytest.skip() gdaltest.csv_ds = None @@ -2739,71 +2226,6 @@ def ogr_csv_cleanup(): except: pass - return 'success' - - -gdaltest_list = [ - ogr_csv_1, - ogr_csv_2, - ogr_csv_3, - ogr_csv_4, - ogr_csv_5, - ogr_csv_6, - ogr_csv_6, - ogr_csv_7, - ogr_csv_8, - ogr_csv_9, - ogr_csv_10, - ogr_csv_11, - ogr_csv_12, - ogr_csv_13, - ogr_csv_14, - ogr_csv_15, - ogr_csv_16, - ogr_csv_17, - ogr_csv_18, - ogr_csv_19, - ogr_csv_20, - ogr_csv_21, - ogr_csv_22, - ogr_csv_23, - ogr_csv_24, - ogr_csv_25, - ogr_csv_26, - ogr_csv_27, - ogr_csv_28, - ogr_csv_29, - ogr_csv_30, - ogr_csv_31, - ogr_csv_32, - ogr_csv_33, - ogr_csv_34, - ogr_csv_35, - ogr_csv_36, - ogr_csv_37, - ogr_csv_38, - ogr_csv_39, - ogr_csv_40, - ogr_csv_41, - ogr_csv_42, - ogr_csv_43, - ogr_csv_44, - ogr_csv_45, - ogr_csv_46, - ogr_csv_47, - ogr_csv_48, - ogr_csv_49, - ogr_csv_more_than_100_geom_fields, - ogr_csv_string_quoting_always, - ogr_csv_string_quoting_if_ambiguous, - ogr_csv_string_quoting_if_needed, - ogr_csv_iter_and_set_feature, - ogr_csv_cleanup] - -if __name__ == '__main__': - - gdaltest.setup_run('ogr_csv') - - gdaltest.run_tests(gdaltest_list) - - sys.exit(gdaltest.summarize()) + + + diff --git a/autotest/ogr/ogr_csw.py b/autotest/ogr/ogr_csw.py index 1f39a06cd277..0905575b2e6e 100755 --- a/autotest/ogr/ogr_csw.py +++ b/autotest/ogr/ogr_csw.py @@ -29,9 +29,8 @@ # DEALINGS IN THE SOFTWARE. ############################################################################### -import sys -sys.path.append('../pymod') +import pytest import gdaltest from osgeo import ogr @@ -41,93 +40,59 @@ # Test underlying OGR drivers # +pytestmark = pytest.mark.require_driver('CSW') -def ogr_csw_init(): - - gdaltest.csw_drv = None - try: - gdaltest.csw_drv = ogr.GetDriverByName('CSW') - except: - pass - - if gdaltest.csw_drv is None: - return 'skip' +@pytest.fixture(autouse=True, scope='module') +def ogr_csw_init(): + gdaltest.csw_drv = ogr.GetDriverByName('CSW') gml_ds = ogr.Open('data/ionic_wfs.gml') if gml_ds is None: gdaltest.csw_drv = None if gdal.GetLastErrorMsg().find('Xerces') != -1: - return 'skip' - gdaltest.post_reason('failed to open test file.') - return 'skip' - - return 'success' + pytest.skip() + pytest.skip('failed to open test file.') + ############################################################################### # Test reading a pyCSW server -def ogr_csw_pycsw(): - if gdaltest.csw_drv is None: - return 'skip' - +@pytest.mark.skip() +def test_ogr_csw_pycsw(): ds = ogr.Open('CSW:http://catalog.data.gov/csw') if ds is None: if gdaltest.gdalurlopen('http://catalog.data.gov/csw') is None: - print('cannot open URL') - return 'skip' - gdaltest.post_reason('did not managed to open CSW datastore') - return 'skip' + pytest.skip('cannot open URL') + pytest.skip('did not managed to open CSW datastore') lyr = ds.GetLayer(0) f = lyr.GetNextFeature() - if f is None: - gdaltest.post_reason('did not get expected layer name') - return 'fail' - - return 'success' + assert f is not None, 'did not get expected layer name' ############################################################################### -def ogr_csw_vsimem_fail_because_not_enabled(): - - if gdaltest.csw_drv is None: - return 'skip' - +def test_ogr_csw_vsimem_fail_because_not_enabled(): gdal.PushErrorHandler() ds = ogr.Open('CSW:/vsimem/csw_endpoint') gdal.PopErrorHandler() - if ds is not None: - return 'fail' - - return 'success' + assert ds is None ############################################################################### -def ogr_csw_vsimem_fail_because_no_get_capabilities(): - - if gdaltest.csw_drv is None: - return 'skip' - +def test_ogr_csw_vsimem_fail_because_no_get_capabilities(): gdal.SetConfigOption('CPL_CURL_ENABLE_VSIMEM', 'YES') gdal.PushErrorHandler() ds = ogr.Open('CSW:/vsimem/csw_endpoint') gdal.PopErrorHandler() - if ds is not None: - return 'fail' - - return 'success' + assert ds is None ############################################################################### -def ogr_csw_vsimem_fail_because_empty_response(): - - if gdaltest.csw_drv is None: - return 'skip' - +def test_ogr_csw_vsimem_fail_because_empty_response(): gdal.SetConfigOption('CPL_CURL_ENABLE_VSIMEM', 'YES') gdal.FileFromMemBuffer('/vsimem/csw_endpoint?SERVICE=CSW&REQUEST=GetCapabilities', @@ -135,24 +100,13 @@ def ogr_csw_vsimem_fail_because_empty_response(): gdal.PushErrorHandler() ds = ogr.Open('CSW:/vsimem/csw_endpoint') gdal.PopErrorHandler() - if ds is not None: - gdaltest.post_reason('fail') - return 'fail' - if gdal.GetLastErrorMsg().find('Empty content returned by server') < 0: - gdaltest.post_reason('fail') - print(gdal.GetLastErrorMsg()) - return 'fail' - - return 'success' + assert ds is None + assert gdal.GetLastErrorMsg().find('Empty content returned by server') >= 0 ############################################################################### -def ogr_csw_vsimem_fail_because_no_CSW_Capabilities(): - - if gdaltest.csw_drv is None: - return 'skip' - +def test_ogr_csw_vsimem_fail_because_no_CSW_Capabilities(): gdal.SetConfigOption('CPL_CURL_ENABLE_VSIMEM', 'YES') gdal.FileFromMemBuffer('/vsimem/csw_endpoint?SERVICE=CSW&REQUEST=GetCapabilities', @@ -160,24 +114,13 @@ def ogr_csw_vsimem_fail_because_no_CSW_Capabilities(): gdal.PushErrorHandler() ds = ogr.Open('CSW:/vsimem/csw_endpoint') gdal.PopErrorHandler() - if ds is not None: - gdaltest.post_reason('fail') - return 'fail' - if gdal.GetLastErrorMsg().find('Cannot find Capabilities.version') < 0: - gdaltest.post_reason('fail') - print(gdal.GetLastErrorMsg()) - return 'fail' - - return 'success' + assert ds is None + assert gdal.GetLastErrorMsg().find('Cannot find Capabilities.version') >= 0 ############################################################################### -def ogr_csw_vsimem_fail_because_exception(): - - if gdaltest.csw_drv is None: - return 'skip' - +def test_ogr_csw_vsimem_fail_because_exception(): gdal.SetConfigOption('CPL_CURL_ENABLE_VSIMEM', 'YES') gdal.FileFromMemBuffer('/vsimem/csw_endpoint?SERVICE=CSW&REQUEST=GetCapabilities', @@ -185,24 +128,13 @@ def ogr_csw_vsimem_fail_because_exception(): gdal.PushErrorHandler() ds = ogr.Open('CSW:/vsimem/csw_endpoint') gdal.PopErrorHandler() - if ds is not None: - gdaltest.post_reason('fail') - return 'fail' - if gdal.GetLastErrorMsg().find('Error returned by server : <ServiceExceptionReport/>') < 0: - gdaltest.post_reason('fail') - print(gdal.GetLastErrorMsg()) - return 'fail' - - return 'success' + assert ds is None + assert gdal.GetLastErrorMsg().find('Error returned by server : <ServiceExceptionReport/>') >= 0 ############################################################################### -def ogr_csw_vsimem_fail_because_invalid_xml_capabilities(): - - if gdaltest.csw_drv is None: - return 'skip' - +def test_ogr_csw_vsimem_fail_because_invalid_xml_capabilities(): gdal.SetConfigOption('CPL_CURL_ENABLE_VSIMEM', 'YES') gdal.FileFromMemBuffer('/vsimem/csw_endpoint?SERVICE=CSW&REQUEST=GetCapabilities', @@ -210,24 +142,13 @@ def ogr_csw_vsimem_fail_because_invalid_xml_capabilities(): gdal.PushErrorHandler() ds = ogr.Open('CSW:/vsimem/csw_endpoint') gdal.PopErrorHandler() - if ds is not None: - gdaltest.post_reason('fail') - return 'fail' - if gdal.GetLastErrorMsg().find('Invalid XML content : <invalid_xml') < 0: - gdaltest.post_reason('fail') - print(gdal.GetLastErrorMsg()) - return 'fail' - - return 'success' + assert ds is None + assert gdal.GetLastErrorMsg().find('Invalid XML content : <invalid_xml') >= 0 ############################################################################### -def ogr_csw_vsimem_fail_because_missing_version(): - - if gdaltest.csw_drv is None: - return 'skip' - +def test_ogr_csw_vsimem_fail_because_missing_version(): gdal.SetConfigOption('CPL_CURL_ENABLE_VSIMEM', 'YES') gdal.FileFromMemBuffer('/vsimem/csw_endpoint?SERVICE=CSW&REQUEST=GetCapabilities', @@ -237,24 +158,13 @@ def ogr_csw_vsimem_fail_because_missing_version(): gdal.PushErrorHandler() ds = ogr.Open('CSW:/vsimem/csw_endpoint') gdal.PopErrorHandler() - if ds is not None: - gdaltest.post_reason('fail') - return 'fail' - if gdal.GetLastErrorMsg().find('Cannot find Capabilities.version') < 0: - gdaltest.post_reason('fail') - print(gdal.GetLastErrorMsg()) - return 'fail' - - return 'success' + assert ds is None + assert gdal.GetLastErrorMsg().find('Cannot find Capabilities.version') >= 0 ############################################################################### -def ogr_csw_vsimem_csw_minimal_instance(): - - if gdaltest.csw_drv is None: - return 'skip' - +def test_ogr_csw_vsimem_csw_minimal_instance(): gdal.SetConfigOption('CPL_CURL_ENABLE_VSIMEM', 'YES') # Invalid response, but enough for use @@ -263,32 +173,22 @@ def ogr_csw_vsimem_csw_minimal_instance(): <Capabilities version="2.0.2"/> """) ds = ogr.Open('CSW:/vsimem/csw_endpoint') - if ds is None: - gdaltest.post_reason('fail') - return 'fail' + assert ds is not None ds.TestCapability('foo') - if ds.GetLayerCount() != 1: - gdaltest.post_reason('fail') - return 'fail' - if ds.GetLayer(-1) is not None or ds.GetLayer(1) is not None: - gdaltest.post_reason('fail') - return 'fail' + assert ds.GetLayerCount() == 1 + assert ds.GetLayer(-1) is None and ds.GetLayer(1) is None lyr = ds.GetLayer(0) lyr.TestCapability('foo') gdal.PushErrorHandler() f = lyr.GetNextFeature() gdal.PopErrorHandler() - if f is not None: - gdaltest.post_reason('fail') - return 'fail' + assert f is None gdal.PushErrorHandler() fc = lyr.GetFeatureCount() gdal.PopErrorHandler() - if fc != 0: - gdaltest.post_reason('fail') - return 'fail' + assert fc == 0 gdal.FileFromMemBuffer("""/vsimem/csw_endpoint&POSTFIELDS=<?xml version="1.0" encoding="UTF-8"?><csw:GetRecords resultType="results" service="CSW" version="2.0.2" startPosition="1" maxRecords="500" xmlns:csw="http://www.opengis.net/cat/csw/2.0.2" xmlns:gml="http://www.opengis.net/gml" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:dct="http://purl.org/dc/terms/" xmlns:ogc="http://www.opengis.net/ogc" xmlns:ows="http://www.opengis.net/ows" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.opengis.net/cat/csw/2.0.2 http://schemas.opengis.net/csw/2.0.2/CSW-discovery.xsd"><csw:Query typeNames="csw:Record"><csw:ElementSetName>full</csw:ElementSetName></csw:Query></csw:GetRecords>""", """""") @@ -296,10 +196,7 @@ def ogr_csw_vsimem_csw_minimal_instance(): gdal.PushErrorHandler() f = lyr.GetNextFeature() gdal.PopErrorHandler() - if f is not None or gdal.GetLastErrorMsg().find('Empty content returned by server') < 0: - gdaltest.post_reason('fail') - print(gdal.GetLastErrorMsg()) - return 'fail' + assert f is None and gdal.GetLastErrorMsg().find('Empty content returned by server') >= 0 gdal.FileFromMemBuffer("""/vsimem/csw_endpoint&POSTFIELDS=<?xml version="1.0" encoding="UTF-8"?><csw:GetRecords resultType="results" service="CSW" version="2.0.2" startPosition="1" maxRecords="500" xmlns:csw="http://www.opengis.net/cat/csw/2.0.2" xmlns:gml="http://www.opengis.net/gml" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:dct="http://purl.org/dc/terms/" xmlns:ogc="http://www.opengis.net/ogc" xmlns:ows="http://www.opengis.net/ows" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.opengis.net/cat/csw/2.0.2 http://schemas.opengis.net/csw/2.0.2/CSW-discovery.xsd"><csw:Query typeNames="csw:Record"><csw:ElementSetName>full</csw:ElementSetName></csw:Query></csw:GetRecords>""", """<invalid_xml""") @@ -307,10 +204,7 @@ def ogr_csw_vsimem_csw_minimal_instance(): gdal.PushErrorHandler() f = lyr.GetNextFeature() gdal.PopErrorHandler() - if f is not None or gdal.GetLastErrorMsg().find('Error: cannot parse') < 0: - gdaltest.post_reason('fail') - print(gdal.GetLastErrorMsg()) - return 'fail' + assert f is None and gdal.GetLastErrorMsg().find('Error: cannot parse') >= 0 gdal.FileFromMemBuffer("""/vsimem/csw_endpoint&POSTFIELDS=<?xml version="1.0" encoding="UTF-8"?><csw:GetRecords resultType="results" service="CSW" version="2.0.2" startPosition="1" maxRecords="500" xmlns:csw="http://www.opengis.net/cat/csw/2.0.2" xmlns:gml="http://www.opengis.net/gml" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:dct="http://purl.org/dc/terms/" xmlns:ogc="http://www.opengis.net/ogc" xmlns:ows="http://www.opengis.net/ows" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.opengis.net/cat/csw/2.0.2 http://schemas.opengis.net/csw/2.0.2/CSW-discovery.xsd"><csw:Query typeNames="csw:Record"><csw:ElementSetName>full</csw:ElementSetName></csw:Query></csw:GetRecords>""", """<dummy_xml/>""") @@ -318,10 +212,7 @@ def ogr_csw_vsimem_csw_minimal_instance(): gdal.PushErrorHandler() f = lyr.GetNextFeature() gdal.PopErrorHandler() - if f is not None or gdal.GetLastErrorMsg().find('Error: cannot parse') < 0: - gdaltest.post_reason('fail') - print(gdal.GetLastErrorMsg()) - return 'fail' + assert f is None and gdal.GetLastErrorMsg().find('Error: cannot parse') >= 0 gdal.FileFromMemBuffer("""/vsimem/csw_endpoint&POSTFIELDS=<?xml version="1.0" encoding="UTF-8"?><csw:GetRecords resultType="results" service="CSW" version="2.0.2" startPosition="1" maxRecords="500" xmlns:csw="http://www.opengis.net/cat/csw/2.0.2" xmlns:gml="http://www.opengis.net/gml" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:dct="http://purl.org/dc/terms/" xmlns:ogc="http://www.opengis.net/ogc" xmlns:ows="http://www.opengis.net/ows" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.opengis.net/cat/csw/2.0.2 http://schemas.opengis.net/csw/2.0.2/CSW-discovery.xsd"><csw:Query typeNames="csw:Record"><csw:ElementSetName>full</csw:ElementSetName></csw:Query></csw:GetRecords>""", """<ServiceExceptionReport/>""") @@ -329,10 +220,7 @@ def ogr_csw_vsimem_csw_minimal_instance(): gdal.PushErrorHandler() f = lyr.GetNextFeature() gdal.PopErrorHandler() - if f is not None or gdal.GetLastErrorMsg().find('Error returned by server') < 0: - gdaltest.post_reason('fail') - print(gdal.GetLastErrorMsg()) - return 'fail' + assert f is None and gdal.GetLastErrorMsg().find('Error returned by server') >= 0 gdal.FileFromMemBuffer("""/vsimem/csw_endpoint&POSTFIELDS=<?xml version="1.0" encoding="UTF-8"?><csw:GetRecords resultType="results" service="CSW" version="2.0.2" startPosition="1" maxRecords="500" xmlns:csw="http://www.opengis.net/cat/csw/2.0.2" xmlns:gml="http://www.opengis.net/gml" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:dct="http://purl.org/dc/terms/" xmlns:ogc="http://www.opengis.net/ogc" xmlns:ows="http://www.opengis.net/ows" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.opengis.net/cat/csw/2.0.2 http://schemas.opengis.net/csw/2.0.2/CSW-discovery.xsd"><csw:Query typeNames="csw:Record"><csw:ElementSetName>full</csw:ElementSetName></csw:Query></csw:GetRecords>""", """<?xml version="1.0" encoding="UTF-8" standalone="no"?> @@ -373,40 +261,29 @@ def ogr_csw_vsimem_csw_minimal_instance(): """) lyr.ResetReading() f = lyr.GetNextFeature() - if f is None: - gdaltest.post_reason('fail') - return 'fail' + assert f is not None if f['identifier'] != 'an_identifier' or f['other_identifiers'] != ['another_identifier'] or \ f['subject'] != 'a_subject' or f['other_subjects'] != ['another_subject'] or \ f['references'] != 'http://foo/' or f['other_references'] != ['http://bar/'] or \ f['format'] != 'a_format' or f['other_formats'] != ['another_format'] or \ f['boundingbox'].ExportToWkt() != 'POLYGON ((-180 -90,-180 90,180 90,180 -90,-180 -90))': - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' + pytest.fail() f = lyr.GetNextFeature() - if f is None: - gdaltest.post_reason('fail') - return 'fail' + assert f is not None gdal.PushErrorHandler() f = lyr.GetNextFeature() gdal.PopErrorHandler() - if f is not None: - gdaltest.post_reason('fail') - return 'fail' + assert f is None gdal.PushErrorHandler() fc = lyr.GetFeatureCount() gdal.PopErrorHandler() - if fc != 2: - gdaltest.post_reason('fail') - return 'fail' + assert fc == 2 lyr.ResetReading() f = lyr.GetNextFeature() - if f is None: - gdaltest.post_reason('fail') - return 'fail' + assert f is not None gdal.FileFromMemBuffer("""/vsimem/csw_endpoint&POSTFIELDS=<?xml version="1.0" encoding="UTF-8"?><csw:GetRecords resultType="results" service="CSW" version="2.0.2" startPosition="3" maxRecords="500" xmlns:csw="http://www.opengis.net/cat/csw/2.0.2" xmlns:gml="http://www.opengis.net/gml" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:dct="http://purl.org/dc/terms/" xmlns:ogc="http://www.opengis.net/ogc" xmlns:ows="http://www.opengis.net/ows" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.opengis.net/cat/csw/2.0.2 http://schemas.opengis.net/csw/2.0.2/CSW-discovery.xsd"><csw:Query typeNames="csw:Record"><csw:ElementSetName>full</csw:ElementSetName></csw:Query></csw:GetRecords>""", """<?xml version="1.0" encoding="UTF-8" standalone="no"?> <csw:GetRecordsResponse @@ -425,13 +302,9 @@ def ogr_csw_vsimem_csw_minimal_instance(): </csw:GetRecordsResponse> """) f = lyr.GetNextFeature() - if f is None: - gdaltest.post_reason('fail') - return 'fail' + assert f is not None f = lyr.GetNextFeature() - if f is None: - gdaltest.post_reason('fail') - return 'fail' + assert f is not None gdal.FileFromMemBuffer("""/vsimem/csw_endpoint&POSTFIELDS=<?xml version="1.0" encoding="UTF-8"?><csw:GetRecords resultType="results" service="CSW" version="2.0.2" startPosition="4" maxRecords="500" xmlns:csw="http://www.opengis.net/cat/csw/2.0.2" xmlns:gml="http://www.opengis.net/gml" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:dct="http://purl.org/dc/terms/" xmlns:ogc="http://www.opengis.net/ogc" xmlns:ows="http://www.opengis.net/ows" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.opengis.net/cat/csw/2.0.2 http://schemas.opengis.net/csw/2.0.2/CSW-discovery.xsd"><csw:Query typeNames="csw:Record"><csw:ElementSetName>full</csw:ElementSetName></csw:Query></csw:GetRecords>""", """<?xml version="1.0" encoding="UTF-8" standalone="no"?> @@ -449,49 +322,35 @@ def ogr_csw_vsimem_csw_minimal_instance(): </csw:GetRecordsResponse> """) f = lyr.GetNextFeature() - if f is not None: - gdaltest.post_reason('fail') - return 'fail' + assert f is None gdal.FileFromMemBuffer("""/vsimem/csw_endpoint&POSTFIELDS=<?xml version="1.0" encoding="UTF-8"?><csw:GetRecords resultType="hits" service="CSW" version="2.0.2" xmlns:csw="http://www.opengis.net/cat/csw/2.0.2" xmlns:gml="http://www.opengis.net/gml" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:dct="http://purl.org/dc/terms/" xmlns:ogc="http://www.opengis.net/ogc" xmlns:ows="http://www.opengis.net/ows" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.opengis.net/cat/csw/2.0.2 http://schemas.opengis.net/csw/2.0.2/CSW-discovery.xsd"><csw:Query typeNames="csw:Record"><csw:ElementSetName>full</csw:ElementSetName></csw:Query></csw:GetRecords>""", """""") gdal.PushErrorHandler() fc = lyr.GetFeatureCount() gdal.PopErrorHandler() - if fc != 3: - gdaltest.post_reason('fail') - print(gdal.GetLastErrorMsg()) - return 'fail' + assert fc == 3, gdal.GetLastErrorMsg() gdal.FileFromMemBuffer("""/vsimem/csw_endpoint&POSTFIELDS=<?xml version="1.0" encoding="UTF-8"?><csw:GetRecords resultType="hits" service="CSW" version="2.0.2" xmlns:csw="http://www.opengis.net/cat/csw/2.0.2" xmlns:gml="http://www.opengis.net/gml" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:dct="http://purl.org/dc/terms/" xmlns:ogc="http://www.opengis.net/ogc" xmlns:ows="http://www.opengis.net/ows" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.opengis.net/cat/csw/2.0.2 http://schemas.opengis.net/csw/2.0.2/CSW-discovery.xsd"><csw:Query typeNames="csw:Record"><csw:ElementSetName>full</csw:ElementSetName></csw:Query></csw:GetRecords>""", """<dummy_xml/>""") gdal.PushErrorHandler() fc = lyr.GetFeatureCount() gdal.PopErrorHandler() - if fc != 3: - gdaltest.post_reason('fail') - print(gdal.GetLastErrorMsg()) - return 'fail' + assert fc == 3, gdal.GetLastErrorMsg() gdal.FileFromMemBuffer("""/vsimem/csw_endpoint&POSTFIELDS=<?xml version="1.0" encoding="UTF-8"?><csw:GetRecords resultType="hits" service="CSW" version="2.0.2" xmlns:csw="http://www.opengis.net/cat/csw/2.0.2" xmlns:gml="http://www.opengis.net/gml" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:dct="http://purl.org/dc/terms/" xmlns:ogc="http://www.opengis.net/ogc" xmlns:ows="http://www.opengis.net/ows" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.opengis.net/cat/csw/2.0.2 http://schemas.opengis.net/csw/2.0.2/CSW-discovery.xsd"><csw:Query typeNames="csw:Record"><csw:ElementSetName>full</csw:ElementSetName></csw:Query></csw:GetRecords>""", """<invalid_xml>""") gdal.PushErrorHandler() fc = lyr.GetFeatureCount() gdal.PopErrorHandler() - if fc != 3: - gdaltest.post_reason('fail') - print(gdal.GetLastErrorMsg()) - return 'fail' + assert fc == 3, gdal.GetLastErrorMsg() gdal.FileFromMemBuffer("""/vsimem/csw_endpoint&POSTFIELDS=<?xml version="1.0" encoding="UTF-8"?><csw:GetRecords resultType="hits" service="CSW" version="2.0.2" xmlns:csw="http://www.opengis.net/cat/csw/2.0.2" xmlns:gml="http://www.opengis.net/gml" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:dct="http://purl.org/dc/terms/" xmlns:ogc="http://www.opengis.net/ogc" xmlns:ows="http://www.opengis.net/ows" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.opengis.net/cat/csw/2.0.2 http://schemas.opengis.net/csw/2.0.2/CSW-discovery.xsd"><csw:Query typeNames="csw:Record"><csw:ElementSetName>full</csw:ElementSetName></csw:Query></csw:GetRecords>""", """<ServiceExceptionReport/>""") gdal.PushErrorHandler() fc = lyr.GetFeatureCount() gdal.PopErrorHandler() - if fc != 3: - gdaltest.post_reason('fail') - print(gdal.GetLastErrorMsg()) - return 'fail' + assert fc == 3, gdal.GetLastErrorMsg() gdal.FileFromMemBuffer("""/vsimem/csw_endpoint&POSTFIELDS=<?xml version="1.0" encoding="UTF-8"?><csw:GetRecords resultType="hits" service="CSW" version="2.0.2" xmlns:csw="http://www.opengis.net/cat/csw/2.0.2" xmlns:gml="http://www.opengis.net/gml" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:dct="http://purl.org/dc/terms/" xmlns:ogc="http://www.opengis.net/ogc" xmlns:ows="http://www.opengis.net/ows" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.opengis.net/cat/csw/2.0.2 http://schemas.opengis.net/csw/2.0.2/CSW-discovery.xsd"><csw:Query typeNames="csw:Record"><csw:ElementSetName>full</csw:ElementSetName></csw:Query></csw:GetRecords>""", """<?xml version="1.0" encoding="UTF-8" standalone="no"?> @@ -509,9 +368,7 @@ def ogr_csw_vsimem_csw_minimal_instance(): </csw:GetRecordsResponse> """) fc = lyr.GetFeatureCount() - if fc != 200: - gdaltest.post_reason('fail') - return 'fail' + assert fc == 200 lyr.SetAttributeFilter("identifier = 'an_identifier'") lyr.SetSpatialFilterRect(-180, -90, 180, 90) @@ -533,9 +390,7 @@ def ogr_csw_vsimem_csw_minimal_instance(): </csw:GetRecordsResponse> """) f = lyr.GetNextFeature() - if f is None: - gdaltest.post_reason('fail') - return 'fail' + assert f is not None gdal.FileFromMemBuffer("""/vsimem/csw_endpoint&POSTFIELDS=<?xml version="1.0" encoding="UTF-8"?><csw:GetRecords resultType="hits" service="CSW" version="2.0.2" xmlns:csw="http://www.opengis.net/cat/csw/2.0.2" xmlns:gml="http://www.opengis.net/gml" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:dct="http://purl.org/dc/terms/" xmlns:ogc="http://www.opengis.net/ogc" xmlns:ows="http://www.opengis.net/ows" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.opengis.net/cat/csw/2.0.2 http://schemas.opengis.net/csw/2.0.2/CSW-discovery.xsd"><csw:Query typeNames="csw:Record"><csw:ElementSetName>full</csw:ElementSetName><csw:Constraint version="1.1.0"><ogc:Filter><ogc:And><ogc:BBOX><ogc:PropertyName>ows:BoundingBox</ogc:PropertyName><gml:Envelope srsName="urn:ogc:def:crs:EPSG::4326"><gml:lowerCorner>-90 -180</gml:lowerCorner><gml:upperCorner>90 180</gml:upperCorner></gml:Envelope></ogc:BBOX><ogc:PropertyIsEqualTo><ogc:PropertyName>dc:identifier</ogc:PropertyName><ogc:Literal>an_identifier</ogc:Literal></ogc:PropertyIsEqualTo></ogc:And></ogc:Filter></csw:Constraint></csw:Query></csw:GetRecords>""", """<?xml version="1.0" encoding="UTF-8" standalone="no"?> @@ -553,9 +408,7 @@ def ogr_csw_vsimem_csw_minimal_instance(): </csw:GetRecordsResponse> """) fc = lyr.GetFeatureCount() - if fc != 300: - gdaltest.post_reason('fail') - return 'fail' + assert fc == 300 lyr.SetAttributeFilter("identifier = 'an_identifier' AND " + "references = 'http://foo/' AND " + @@ -568,16 +421,10 @@ def ogr_csw_vsimem_csw_minimal_instance(): lyr.SetAttributeFilter(None) lyr.SetSpatialFilter(None) - return 'success' - ############################################################################### -def ogr_csw_vsimem_csw_output_schema_csw(): - - if gdaltest.csw_drv is None: - return 'skip' - +def test_ogr_csw_vsimem_csw_output_schema_csw(): ds = gdal.OpenEx('CSW:/vsimem/csw_endpoint', open_options=['OUTPUT_SCHEMA=CSW']) lyr = ds.GetLayer(0) @@ -588,9 +435,7 @@ def ogr_csw_vsimem_csw_output_schema_csw(): gdal.PushErrorHandler() f = lyr.GetNextFeature() gdal.PopErrorHandler() - if f is not None: - gdaltest.post_reason('fail') - return 'fail' + assert f is None gdal.FileFromMemBuffer("""/vsimem/csw_endpoint&POSTFIELDS=<?xml version="1.0" encoding="UTF-8"?><csw:GetRecords resultType="results" service="CSW" version="2.0.2" outputSchema="http://www.opengis.net/cat/csw/2.0.2" startPosition="1" maxRecords="500" xmlns:csw="http://www.opengis.net/cat/csw/2.0.2" xmlns:gml="http://www.opengis.net/gml" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:dct="http://purl.org/dc/terms/" xmlns:ogc="http://www.opengis.net/ogc" xmlns:ows="http://www.opengis.net/ows" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.opengis.net/cat/csw/2.0.2 http://schemas.opengis.net/csw/2.0.2/CSW-discovery.xsd"><csw:Query typeNames="csw:Record"><csw:ElementSetName>full</csw:ElementSetName></csw:Query></csw:GetRecords>""", """<csw:GetRecordsResponse/>""") @@ -598,9 +443,7 @@ def ogr_csw_vsimem_csw_output_schema_csw(): gdal.PushErrorHandler() f = lyr.GetNextFeature() gdal.PopErrorHandler() - if f is not None: - gdaltest.post_reason('fail') - return 'fail' + assert f is None gdal.FileFromMemBuffer("""/vsimem/csw_endpoint&POSTFIELDS=<?xml version="1.0" encoding="UTF-8"?><csw:GetRecords resultType="results" service="CSW" version="2.0.2" outputSchema="http://www.opengis.net/cat/csw/2.0.2" startPosition="1" maxRecords="500" xmlns:csw="http://www.opengis.net/cat/csw/2.0.2" xmlns:gml="http://www.opengis.net/gml" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:dct="http://purl.org/dc/terms/" xmlns:ogc="http://www.opengis.net/ogc" xmlns:ows="http://www.opengis.net/ows" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.opengis.net/cat/csw/2.0.2 http://schemas.opengis.net/csw/2.0.2/CSW-discovery.xsd"><csw:Query typeNames="csw:Record"><csw:ElementSetName>full</csw:ElementSetName></csw:Query></csw:GetRecords>""", """<?xml version="1.0" encoding="UTF-8" standalone="no"?> @@ -629,20 +472,14 @@ def ogr_csw_vsimem_csw_output_schema_csw(): f = lyr.GetNextFeature() if f['raw_xml'].find('<csw:Record') != 0 or \ f['boundingbox'].ExportToWkt() != 'POLYGON ((-180 -90,-180 90,180 90,180 -90,-180 -90))': - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' - - return 'success' + pytest.fail() + ############################################################################### -def ogr_csw_vsimem_csw_output_schema_gmd(): - - if gdaltest.csw_drv is None: - return 'skip' - +def test_ogr_csw_vsimem_csw_output_schema_gmd(): ds = gdal.OpenEx('CSW:/vsimem/csw_endpoint', open_options=['OUTPUT_SCHEMA=GMD']) lyr = ds.GetLayer(0) @@ -675,20 +512,14 @@ def ogr_csw_vsimem_csw_output_schema_gmd(): f = lyr.GetNextFeature() if f['raw_xml'].find('<gmd:MD_Metadata') != 0 or \ f['boundingbox'].ExportToWkt() != 'POLYGON ((-180 -90,-180 90,180 90,180 -90,-180 -90))': - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' - - return 'success' + pytest.fail() + ############################################################################### -def ogr_csw_vsimem_csw_output_schema_fgdc(): - - if gdaltest.csw_drv is None: - return 'skip' - +def test_ogr_csw_vsimem_csw_output_schema_fgdc(): ds = gdal.OpenEx('CSW:/vsimem/csw_endpoint', open_options=['OUTPUT_SCHEMA=http://www.opengis.net/cat/csw/csdgm']) lyr = ds.GetLayer(0) @@ -723,55 +554,19 @@ def ogr_csw_vsimem_csw_output_schema_fgdc(): f = lyr.GetNextFeature() if f['raw_xml'].find('<metadata') != 0 or \ f['boundingbox'].ExportToWkt() != 'POLYGON ((-180 -90,-180 90,180 90,180 -90,-180 -90))': - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' - - return 'success' + pytest.fail() + ############################################################################### -def ogr_csw_vsimem_cleanup(): - - if gdaltest.csw_drv is None: - return 'skip' - +def test_ogr_csw_vsimem_cleanup(): gdal.SetConfigOption('CPL_CURL_ENABLE_VSIMEM', None) for f in gdal.ReadDir('/vsimem/'): gdal.Unlink('/vsimem/' + f) - return 'success' - - -gdaltest_live_list = [ - ogr_csw_pycsw -] - -gdaltest_vsimem_list = [ - ogr_csw_vsimem_fail_because_not_enabled, - ogr_csw_vsimem_fail_because_no_get_capabilities, - ogr_csw_vsimem_fail_because_empty_response, - ogr_csw_vsimem_fail_because_no_CSW_Capabilities, - ogr_csw_vsimem_fail_because_exception, - ogr_csw_vsimem_fail_because_invalid_xml_capabilities, - ogr_csw_vsimem_fail_because_missing_version, - ogr_csw_vsimem_csw_minimal_instance, - ogr_csw_vsimem_csw_output_schema_csw, - ogr_csw_vsimem_csw_output_schema_gmd, - ogr_csw_vsimem_csw_output_schema_fgdc, - ogr_csw_vsimem_cleanup, -] - -gdaltest_list = [ogr_csw_init] -gdaltest_list += gdaltest_vsimem_list -# gdaltest_list += gdaltest_live_list - -if __name__ == '__main__': - - gdaltest.setup_run('ogr_csw') + - gdaltest.run_tests(gdaltest_list) - sys.exit(gdaltest.summarize()) diff --git a/autotest/ogr/ogr_db2.py b/autotest/ogr/ogr_db2.py index ed22919a79cd..e9dd071ae0c3 100755 --- a/autotest/ogr/ogr_db2.py +++ b/autotest/ogr/ogr_db2.py @@ -39,205 +39,163 @@ # These tests currently only run on Windows import os -import sys -sys.path.append('../pymod') -import gdaltest import ogrtest from osgeo import ogr +import pytest ############################################################################### # Test if driver is available -def ogr_db2_check_driver(): +def test_ogr_db2_check_driver(): ogrtest.db2_drv = None ogrtest.db2_drv = ogr.GetDriverByName('DB2ODBC') if ogrtest.db2_drv is None: - return 'skip' - - return 'success' + pytest.skip() + ############################################################################### # Test if environment variable for DB2 connection is set and we can connect -def ogr_db2_init(): +def test_ogr_db2_init(): if ogrtest.db2_drv is None: - return 'skip' + pytest.skip() if 'DB2_TEST_SERVER' in os.environ: ogrtest.db2_test_server = "DB2ODBC:" + os.environ['DB2_TEST_SERVER'] else: - gdaltest.post_reason('Environment variable DB2_TEST_SERVER not found') ogrtest.db2_drv = None - return 'skip' + pytest.skip('Environment variable DB2_TEST_SERVER not found') - return 'success' -############################################################################### + ############################################################################### # Test GetFeatureCount() -def ogr_db2_GetFeatureCount(): +def test_ogr_db2_GetFeatureCount(): if ogrtest.db2_drv is None: - return 'skip' + pytest.skip() ds = ogr.Open(ogrtest.db2_test_server) - if ds is None: - return 'fail' + assert ds is not None lyr = ds.GetLayer(0) - if lyr is None: - return 'fail' + assert lyr is not None count = lyr.GetFeatureCount() - if count != 5: - gdaltest.post_reason('did not get expected feature count') - return 'fail' - - return 'success' + assert count == 5, 'did not get expected feature count' ############################################################################### # Test GetSpatialRef() -def ogr_db2_GetSpatialRef(): +def test_ogr_db2_GetSpatialRef(): if ogrtest.db2_drv is None: - return 'skip' + pytest.skip() ds = ogr.Open(ogrtest.db2_test_server) - if ds is None: - return 'fail' + assert ds is not None lyr = ds.GetLayer(0) - if lyr is None: - return 'fail' + assert lyr is not None sr = lyr.GetSpatialRef() - if sr is None: - gdaltest.post_reason('did not get expected srs') - return 'fail' + assert sr is not None, 'did not get expected srs' txt = sr.ExportToWkt() - if txt.find('GEOGCS[\"GCS_WGS_1984') == -1: - gdaltest.post_reason('did not get expected srs') - print(txt) - return 'fail' - - return 'success' + assert txt.find('GEOGCS[\"GCS_WGS_1984') != -1, 'did not get expected srs' ############################################################################### # Test GetExtent() -def ogr_db2_GetExtent(): +def test_ogr_db2_GetExtent(): if ogrtest.db2_drv is None: - return 'skip' + pytest.skip() ds = ogr.Open(ogrtest.db2_test_server) - if ds is None: - return 'fail' + assert ds is not None lyr = ds.GetLayer(0) - if lyr is None: - return 'fail' + assert lyr is not None extent = lyr.GetExtent() - if extent is None: - gdaltest.post_reason('did not get extent') - return 'fail' - - if extent != (-122.030745, -121.95672, 37.278665, 37.440885): - gdaltest.post_reason('did not get expected extent') - print(extent) - return 'fail' + assert extent is not None, 'did not get extent' - return 'success' + assert extent == (-122.030745, -121.95672, 37.278665, 37.440885), \ + 'did not get expected extent' ############################################################################### # Test GetFeature() -def ogr_db2_GetFeature(): +def test_ogr_db2_GetFeature(): if ogrtest.db2_drv is None: - return 'skip' + pytest.skip() ds = ogr.Open(ogrtest.db2_test_server) - if ds is None: - return 'fail' + assert ds is not None lyr = ds.GetLayer(0) - if lyr is None: - return 'fail' + assert lyr is not None feat = lyr.GetFeature(5) - if feat is None: - gdaltest.post_reason('did not get a feature') - return 'fail' + assert feat is not None, 'did not get a feature' if feat.GetField('ZIP') != '95008': - gdaltest.post_reason('did not get expected feature') feat.DumpReadable() - return 'fail' - - return 'success' + pytest.fail('did not get expected feature') + ############################################################################### # Test SetSpatialFilter() -def ogr_db2_SetSpatialFilter(): +def test_ogr_db2_SetSpatialFilter(): if ogrtest.db2_drv is None: - return 'skip' + pytest.skip() ds = ogr.Open(ogrtest.db2_test_server) - if ds is None: - return 'fail' + assert ds is not None lyr = ds.GetLayer(0) - if lyr is None: - return 'fail' + assert lyr is not None # set a query envelope so we only get one feature lyr.SetSpatialFilterRect(-122.02, 37.42, -122.01, 37.43) count = lyr.GetFeatureCount() - if count != 1: - gdaltest.post_reason('did not get expected feature count (1)') - print(count) - return 'fail' + assert count == 1, 'did not get expected feature count (1)' feat = lyr.GetNextFeature() - if feat is None: - gdaltest.post_reason('did not get a feature') - return 'fail' + assert feat is not None, 'did not get a feature' if feat.GetField('ZIP') != '94089': - gdaltest.post_reason('did not get expected feature') feat.DumpReadable() - return 'fail' + pytest.fail('did not get expected feature') # start over with a larger envelope to get 3 out of 5 of the points lyr.ResetReading() @@ -245,10 +203,7 @@ def ogr_db2_SetSpatialFilter(): count = lyr.GetFeatureCount() - if count != 3: - gdaltest.post_reason('did not get expected feature count (3)') - print(count) - return 'fail' + assert count == 3, 'did not get expected feature count (3)' # iterate through the features to make sure we get the same count count = 0 @@ -257,27 +212,21 @@ def ogr_db2_SetSpatialFilter(): count = count + 1 feat = lyr.GetNextFeature() - if count != 3: - gdaltest.post_reason('did not get expected feature count (3)') - print(count) - return 'fail' - - return 'success' + assert count == 3, 'did not get expected feature count (3)' # # test what capabilities the DB2 driver provides # -def ogr_db2_capabilities(): +def test_ogr_db2_capabilities(): if ogrtest.db2_drv is None: - return 'skip' + pytest.skip() ds = ogr.Open(ogrtest.db2_test_server) - if ds is None: - return 'fail' + assert ds is not None layer = ds.GetLayer() capabilities = [ @@ -301,8 +250,7 @@ def ogr_db2_capabilities(): print("Layer Capabilities:") for cap in capabilities: print(" %s = %s" % (cap, layer.TestCapability(cap))) - return 'success' - + def ogr_db2_listdrivers(): cnt = ogr.GetDriverCount() @@ -320,26 +268,6 @@ def ogr_db2_listdrivers(): for i in formatsList: print(i) - return 'success' - + -gdaltest_list = [ - ogr_db2_check_driver, - ogr_db2_init, - # ogr_db2_listdrivers, - ogr_db2_GetSpatialRef, - ogr_db2_GetExtent, - ogr_db2_GetFeature, - ogr_db2_SetSpatialFilter, - ogr_db2_capabilities, - ogr_db2_GetFeatureCount -] -if __name__ == '__main__': - - gdaltest.setup_run('ogr_db2') - if os.name == 'nt': - gdaltest.run_tests(gdaltest_list) - else: - print("These tests only run on Windows") - sys.exit(gdaltest.summarize()) diff --git a/autotest/ogr/ogr_db2_hack.py b/autotest/ogr/ogr_db2_hack.py index 28ac0024f055..6557e157a510 100755 --- a/autotest/ogr/ogr_db2_hack.py +++ b/autotest/ogr/ogr_db2_hack.py @@ -27,80 +27,65 @@ # Boston, MA 02111-1307, USA. ############################################################################### -import sys -sys.path.append('../pymod') -import gdaltest from osgeo import ogr +import pytest ############################################################################### # Create a point in DB2 format, and verify the byte order flag. -def ogr_db2_hack_1(): +def test_ogr_db2_hack_1(): if ogr.SetGenerate_DB2_V72_BYTE_ORDER(1) != 0: - return 'skip' + pytest.skip() # XDR Case. geom = ogr.CreateGeometryFromWkt('POINT(10 20)') wkb = geom.ExportToWkb(byte_order=ogr.wkbXDR).decode('latin1') geom.Destroy() - if wkb[0] != '0': - gdaltest.post_reason('WKB wkbXDR point geometry has wrong byte order') - return 'fail' + assert wkb[0] == '0', 'WKB wkbXDR point geometry has wrong byte order' # NDR Case. geom = ogr.CreateGeometryFromWkt('POINT(10 20)') wkb = geom.ExportToWkb(byte_order=ogr.wkbNDR).decode('latin1') geom.Destroy() - if wkb[0] != '1': - gdaltest.post_reason('WKB wkbNDR point geometry has wrong byte order') - return 'fail' - - return 'success' + assert wkb[0] == '1', 'WKB wkbNDR point geometry has wrong byte order' ############################################################################### # Verify that we can turn DB2 V7.2 mode back off! -def ogr_db2_hack_2(): +def test_ogr_db2_hack_2(): - if ogr.SetGenerate_DB2_V72_BYTE_ORDER(0) != 0: - gdaltest.post_reason('SetGenerate to turn off hack failed!') - return 'fail' + assert ogr.SetGenerate_DB2_V72_BYTE_ORDER(0) == 0, \ + 'SetGenerate to turn off hack failed!' # XDR Case. geom = ogr.CreateGeometryFromWkt('POINT(10 20)') wkb = geom.ExportToWkb(byte_order=ogr.wkbXDR).decode('latin1') geom.Destroy() - if wkb[0] != chr(0): - gdaltest.post_reason('WKB wkbXDR point geometry has wrong byte order') - return 'fail' + assert wkb[0] == chr(0), 'WKB wkbXDR point geometry has wrong byte order' # NDR Case. geom = ogr.CreateGeometryFromWkt('POINT(10 20)') wkb = geom.ExportToWkb(byte_order=ogr.wkbNDR).decode('latin1') geom.Destroy() - if wkb[0] != chr(1): - gdaltest.post_reason('WKB wkbNDR point geometry has wrong byte order') - return 'fail' - - return 'success' + assert wkb[0] == chr(1), 'WKB wkbNDR point geometry has wrong byte order' ############################################################################### # Try a more complex geometry, and verify we can read it back. -def ogr_db2_hack_3(): +def test_ogr_db2_hack_3(): if ogr.SetGenerate_DB2_V72_BYTE_ORDER(1) != 0: - return 'skip' + pytest.skip() wkt = 'MULTIPOLYGON (((10.00121344 2.99853145,10.00121344 1.99853145,11.00121343 1.99853148,11.00121343 2.99853148)),((10.00121344 2.99853145,10.00121344 3.99853145,9.00121345 3.99853143,9.00121345 2.99853143)))' @@ -109,38 +94,20 @@ def ogr_db2_hack_3(): geom.Destroy() # Check primary byte order value. - if wkb.decode('latin1')[0] != '0' and wkb.decode('latin1')[0] != '1': - gdaltest.post_reason('corrupt primary geometry byte order') - return 'fail' + assert wkb.decode('latin1')[0] == '0' or wkb.decode('latin1')[0] == '1', \ + 'corrupt primary geometry byte order' # Check component geometry byte order - if wkb.decode('latin1')[9] != '0' and wkb.decode('latin1')[9] != '1': - gdaltest.post_reason('corrupt sub-geometry byte order') - return 'fail' + assert wkb.decode('latin1')[9] == '0' or wkb.decode('latin1')[9] == '1', \ + 'corrupt sub-geometry byte order' geom = ogr.CreateGeometryFromWkb(wkb) - if geom.ExportToWkt() != wkt: - gdaltest.post_reason('Conversion to/from DB2 format seems to have ' + assert geom.ExportToWkt() == wkt, ('Conversion to/from DB2 format seems to have ' 'corrupted geometry.') - return 'fail' geom.Destroy() ogr.SetGenerate_DB2_V72_BYTE_ORDER(0) - return 'success' - - -gdaltest_list = [ - ogr_db2_hack_1, - ogr_db2_hack_2, - ogr_db2_hack_3 -] - -if __name__ == '__main__': - - gdaltest.setup_run('ogr_db2_hack') - gdaltest.run_tests(gdaltest_list) - sys.exit(gdaltest.summarize()) diff --git a/autotest/ogr/ogr_dgn.py b/autotest/ogr/ogr_dgn.py index 10be1f93f05d..3ede5e77cd6e 100755 --- a/autotest/ogr/ogr_dgn.py +++ b/autotest/ogr/ogr_dgn.py @@ -25,141 +25,112 @@ # Boston, MA 02111-1307, USA. ############################################################################### -import sys -sys.path.append('../pymod') import gdaltest import ogrtest from osgeo import ogr +import pytest ############################################################################### # Verify we can open the test file. -def ogr_dgn_1(): +def test_ogr_dgn_1(): gdaltest.dgn_ds = ogr.Open('data/smalltest.dgn') - if gdaltest.dgn_ds is None: - gdaltest.post_reason('failed to open test file.') - return 'fail' + assert gdaltest.dgn_ds is not None, 'failed to open test file.' gdaltest.dgn_lyr = gdaltest.dgn_ds.GetLayer(0) - return 'success' - ############################################################################### # Check first feature, a text element. -def ogr_dgn_2(): +def test_ogr_dgn_2(): if gdaltest.dgn_ds is None: - return 'skip' + pytest.skip() feat = gdaltest.dgn_lyr.GetNextFeature() - if feat.GetField('Type') != 17 or feat.GetField('Level') != 1: - gdaltest.post_reason('feature 1: expected attributes') - return 'fail' - - if feat.GetField('Text') != 'Demo Text': - gdaltest.post_reason('feature 1: expected text') - return 'fail' + assert feat.GetField('Type') == 17 and feat.GetField('Level') == 1, \ + 'feature 1: expected attributes' - if ogrtest.check_feature_geometry(feat, 'POINT (0.73650000 4.21980000)'): - return 'fail' + assert feat.GetField('Text') == 'Demo Text', 'feature 1: expected text' - if feat.GetStyleString() != 'LABEL(t:"Demo Text",c:#ffffff,s:1.000g,f:ENGINEERING)': - gdaltest.post_reason('Style string different than expected.') - return 'fail' + assert not ogrtest.check_feature_geometry(feat, 'POINT (0.73650000 4.21980000)') - return 'success' + assert feat.GetStyleString() == 'LABEL(t:"Demo Text",c:#ffffff,s:1.000g,f:ENGINEERING)', \ + 'Style string different than expected.' ############################################################################### # Check second feature, a circle. -def ogr_dgn_3(): +def test_ogr_dgn_3(): if gdaltest.dgn_ds is None: - return 'skip' + pytest.skip() feat = gdaltest.dgn_lyr.GetNextFeature() - if feat.GetField('Type') != 15 or feat.GetField('Level') != 2: - gdaltest.post_reason('feature 2: expected attributes') - return 'fail' + assert feat.GetField('Type') == 15 and feat.GetField('Level') == 2, \ + 'feature 2: expected attributes' geom = feat.GetGeometryRef() - if geom.GetCoordinateDimension() != 2: - gdaltest.post_reason('expected 2d circle.') - return 'fail' + assert geom.GetCoordinateDimension() == 2, 'expected 2d circle.' - if geom.GetGeometryName() != 'LINESTRING': - gdaltest.post_reason('Expected circle to be translated as LINESTRING.') - return 'fail' + assert geom.GetGeometryName() == 'LINESTRING', \ + 'Expected circle to be translated as LINESTRING.' - if geom.GetPointCount() < 15: - gdaltest.post_reason('Unexpected small number of circle interpolation points.') - return 'fail' + assert geom.GetPointCount() >= 15, \ + 'Unexpected small number of circle interpolation points.' genvelope = geom.GetEnvelope() - if genvelope[0] < 0.328593 or genvelope[0] > 0.328594 \ - or genvelope[1] < 9.68780 or genvelope[1] > 9.68781 \ - or genvelope[2] < -0.09611 or genvelope[2] > -0.09610 \ - or genvelope[3] < 9.26310 or genvelope[3] > 9.26311: - gdaltest.post_reason('geometry extents seem odd') - return 'fail' - - return 'success' + assert genvelope[0] >= 0.328593 and genvelope[0] <= 0.328594 and genvelope[1] >= 9.68780 and genvelope[1] <= 9.68781 and genvelope[2] >= -0.09611 and genvelope[2] <= -0.09610 and genvelope[3] >= 9.26310 and genvelope[3] <= 9.26311, \ + 'geometry extents seem odd' ############################################################################### # Check third feature, a polygon with fill styling. -def ogr_dgn_4(): +def test_ogr_dgn_4(): if gdaltest.dgn_ds is None: - return 'skip' + pytest.skip() feat = gdaltest.dgn_lyr.GetNextFeature() - if feat.GetField('Type') != 6 or feat.GetField('Level') != 2 \ - or feat.GetField('ColorIndex') != 83: - gdaltest.post_reason('feature 3: expected attributes') - return 'fail' + assert feat.GetField('Type') == 6 and feat.GetField('Level') == 2 and feat.GetField('ColorIndex') == 83, \ + 'feature 3: expected attributes' wkt = 'POLYGON ((4.53550000 3.31700000,4.38320000 2.65170000,4.94410000 2.52350000,4.83200000 3.33310000,4.53550000 3.31700000))' - if ogrtest.check_feature_geometry(feat, wkt): - return 'fail' + assert not ogrtest.check_feature_geometry(feat, wkt) - if feat.GetStyleString() != 'BRUSH(fc:#b40000,id:"ogr-brush-0")': - gdaltest.post_reason('Style string different than expected.') - return 'fail' + assert feat.GetStyleString() == 'BRUSH(fc:#b40000,id:"ogr-brush-0")', \ + 'Style string different than expected.' gdaltest.dgn_lyr.ResetReading() - return 'success' - ############################################################################### # Use attribute query to pick just the type 15 level 2 object. -def ogr_dgn_5(): +def test_ogr_dgn_5(): if gdaltest.dgn_ds is None: - return 'skip' + pytest.skip() gdaltest.dgn_lyr.SetAttributeFilter('Type = 15 and Level = 2') tr = ogrtest.check_features_against_list(gdaltest.dgn_lyr, 'Type', [15]) gdaltest.dgn_lyr.SetAttributeFilter(None) - return 'success' if tr else 'fail' + assert tr ############################################################################### # Use spatial filter to just pick the big circle. -def ogr_dgn_6(): +def test_ogr_dgn_6(): if gdaltest.dgn_ds is None: - return 'skip' + pytest.skip() geom = ogr.CreateGeometryFromWkt('LINESTRING(1.0 8.55, 2.5 6.86)') gdaltest.dgn_lyr.SetSpatialFilter(geom) @@ -168,16 +139,16 @@ def ogr_dgn_6(): tr = ogrtest.check_features_against_list(gdaltest.dgn_lyr, 'Type', [15]) gdaltest.dgn_lyr.SetSpatialFilter(None) - return 'success' if tr else 'fail' + assert tr ############################################################################### # Copy our small dgn file to a new dgn file. -def ogr_dgn_7(): +def test_ogr_dgn_7(): if gdaltest.dgn_ds is None: - return 'skip' + pytest.skip() co_opts = ['UOR_PER_SUB_UNIT=100', 'SUB_UNITS_PER_MASTER_UNIT=100', 'ORIGIN=-50,-50,0'] @@ -194,17 +165,13 @@ def ogr_dgn_7(): feat = gdaltest.dgn_lyr.GetNextFeature() while feat is not None: dst_feat.SetFrom(feat) - if dgn2_lyr.CreateFeature(dst_feat) != 0: - gdaltest.post_reason('CreateFeature failed.') - return 'fail' + assert dgn2_lyr.CreateFeature(dst_feat) == 0, 'CreateFeature failed.' feat = gdaltest.dgn_lyr.GetNextFeature() dgn2_lyr = None dgn2_ds = None - return 'success' - ############################################################################### # Verify that our copy is pretty similar. # @@ -213,10 +180,10 @@ def ogr_dgn_7(): # -def ogr_dgn_8(): +def test_ogr_dgn_8(): if gdaltest.dgn_ds is None: - return 'skip' + pytest.skip() dgn2_ds = ogr.Open('tmp/dgn7.dgn') @@ -224,119 +191,76 @@ def ogr_dgn_8(): # Test first first, a text element. feat = dgn2_lyr.GetNextFeature() - if feat.GetField('Type') != 17 or feat.GetField('Level') != 1: - gdaltest.post_reason('feature 1: expected attributes') - return 'fail' + assert feat.GetField('Type') == 17 and feat.GetField('Level') == 1, \ + 'feature 1: expected attributes' - if feat.GetField('Text') != 'Demo Text': - gdaltest.post_reason('feature 1: expected text') - return 'fail' + assert feat.GetField('Text') == 'Demo Text', 'feature 1: expected text' - if ogrtest.check_feature_geometry(feat, 'POINT (0.73650000 4.21980000)'): - return 'fail' + assert not ogrtest.check_feature_geometry(feat, 'POINT (0.73650000 4.21980000)') - if feat.GetStyleString() != 'LABEL(t:"Demo Text",c:#ffffff,s:1.000g,f:ENGINEERING)': - gdaltest.post_reason('feature 1: Style string different than expected.') - return 'fail' + assert feat.GetStyleString() == 'LABEL(t:"Demo Text",c:#ffffff,s:1.000g,f:ENGINEERING)', \ + 'feature 1: Style string different than expected.' # Check second element, a circle. feat = dgn2_lyr.GetNextFeature() - if feat.GetField('Type') != 12 or feat.GetField('Level') != 2: - gdaltest.post_reason('feature 2: expected attributes') - return 'fail' + assert feat.GetField('Type') == 12 and feat.GetField('Level') == 2, \ + 'feature 2: expected attributes' geom = feat.GetGeometryRef() - if geom.GetCoordinateDimension() != 2: - gdaltest.post_reason('feature 2: expected 2d circle.') - return 'fail' + assert geom.GetCoordinateDimension() == 2, 'feature 2: expected 2d circle.' - if geom.GetGeometryName() != 'MULTILINESTRING': - gdaltest.post_reason('feature 2: Expected MULTILINESTRING.') - return 'fail' + assert geom.GetGeometryName() == 'MULTILINESTRING', \ + 'feature 2: Expected MULTILINESTRING.' genvelope = geom.GetEnvelope() - if genvelope[0] < 0.3285 or genvelope[0] > 0.3287 \ - or genvelope[1] < 9.6878 or genvelope[1] > 9.6879 \ - or genvelope[2] < -0.0962 or genvelope[2] > -0.0960 \ - or genvelope[3] < 9.26310 or genvelope[3] > 9.2632: - gdaltest.post_reason('feature 2: geometry extents seem odd') - print(genvelope) - return 'fail' + assert genvelope[0] >= 0.3285 and genvelope[0] <= 0.3287 and genvelope[1] >= 9.6878 and genvelope[1] <= 9.6879 and genvelope[2] >= -0.0962 and genvelope[2] <= -0.0960 and genvelope[3] >= 9.26310 and genvelope[3] <= 9.2632, \ + 'feature 2: geometry extents seem odd' # Check 3rd feature, a polygon feat = dgn2_lyr.GetNextFeature() - if feat.GetField('Type') != 6 or feat.GetField('Level') != 2 \ - or feat.GetField('ColorIndex') != 83: - gdaltest.post_reason('feature 3: expected attributes') - return 'fail' + assert feat.GetField('Type') == 6 and feat.GetField('Level') == 2 and feat.GetField('ColorIndex') == 83, \ + 'feature 3: expected attributes' wkt = 'POLYGON ((4.53550000 3.31700000,4.38320000 2.65170000,4.94410000 2.52350000,4.83200000 3.33310000,4.53550000 3.31700000))' - if ogrtest.check_feature_geometry(feat, wkt): - return 'fail' + assert not ogrtest.check_feature_geometry(feat, wkt) # should be: 'BRUSH(fc:#b40000,id:"ogr-brush-0")' - if feat.GetStyleString() != 'PEN(id:"ogr-pen-0",c:#b40000)': - gdaltest.post_reason('feature 3: Style string different than expected: ' + feat.GetStyleString()) - return 'fail' + assert feat.GetStyleString() == 'PEN(id:"ogr-pen-0",c:#b40000)', \ + ('feature 3: Style string different than expected: ' + feat.GetStyleString()) dgn2_ds = None - return 'success' - ############################################################################### # Test delta encoding (#6806) -def ogr_dgn_online_1(): +def test_ogr_dgn_online_1(): if not gdaltest.download_file('http://download.osgeo.org/gdal/data/dgn/DGNSample_v7.dgn', 'DGNSample_v7.dgn'): - return 'skip' + pytest.skip() ds = ogr.Open('tmp/cache/DGNSample_v7.dgn') - if ds is None: - return 'fail' + assert ds is not None lyr = ds.GetLayer(0) feat = lyr.GetFeature(35) wkt = 'LINESTRING (82.9999500717185 23.2084166997284,83.0007450788903 23.2084495986816,83.00081490524 23.2068095339824,82.9999503769036 23.2067737968078)' - if ogrtest.check_feature_geometry(feat, wkt): - return 'fail' - - return 'success' + assert not ogrtest.check_feature_geometry(feat, wkt) ############################################################################### # Cleanup -def ogr_dgn_cleanup(): +def test_ogr_dgn_cleanup(): if gdaltest.dgn_ds is not None: gdaltest.dgn_lyr = None gdaltest.dgn_ds = None gdaltest.clean_tmp() - return 'success' - - -gdaltest_list = [ - ogr_dgn_1, - ogr_dgn_2, - ogr_dgn_3, - ogr_dgn_4, - ogr_dgn_5, - ogr_dgn_6, - ogr_dgn_7, - ogr_dgn_8, - ogr_dgn_online_1, - ogr_dgn_cleanup] - -if __name__ == '__main__': - gdaltest.setup_run('ogr_dgn') - gdaltest.run_tests(gdaltest_list) - sys.exit(gdaltest.summarize()) diff --git a/autotest/ogr/ogr_dgnv8.py b/autotest/ogr/ogr_dgnv8.py index 2243e96a582b..529b2ac6cea4 100755 --- a/autotest/ogr/ogr_dgnv8.py +++ b/autotest/ogr/ogr_dgnv8.py @@ -30,39 +30,34 @@ import os import shutil -import sys -sys.path.append('../pymod') import gdaltest import ogrtest from osgeo import gdal, ogr +import pytest ############################################################################### # Verify we can open the test file. -def ogr_dgnv8_1(): +def test_ogr_dgnv8_1(): gdaltest.dgnv8_drv = ogr.GetDriverByName('DGNv8') if gdaltest.dgnv8_drv is None: - return 'skip' + pytest.skip() ds = ogr.Open('data/test_dgnv8.dgn') - if ds is None: - gdaltest.post_reason('failed to open test file.') - return 'fail' - - return 'success' + assert ds is not None, 'failed to open test file.' ############################################################################### # Compare with a reference CSV dump -def ogr_dgnv8_2(): +def test_ogr_dgnv8_2(): if gdaltest.dgnv8_drv is None: - return 'skip' + pytest.skip() gdal.VectorTranslate('/vsimem/ogr_dgnv8_2.csv', 'data/test_dgnv8.dgn', options='-f CSV -dsco geometry=as_wkt -sql "select *, ogr_style from my_model"') @@ -81,41 +76,33 @@ def ogr_dgnv8_2(): # Run test_ogrsf -def ogr_dgnv8_3(): +def test_ogr_dgnv8_3(): if gdaltest.dgnv8_drv is None: - return 'skip' + pytest.skip() import test_cli_utilities if test_cli_utilities.get_test_ogrsf_path() is None: - return 'skip' + pytest.skip() ret = gdaltest.runexternal(test_cli_utilities.get_test_ogrsf_path() + ' -ro data/test_dgnv8.dgn') - if ret.find('INFO') == -1 or ret.find('ERROR') != -1: - gdaltest.post_reason('fail') - print(ret) - return 'fail' + assert ret.find('INFO') != -1 and ret.find('ERROR') == -1 shutil.copy('data/test_dgnv8.dgn', 'tmp/test_dgnv8.dgn') ret = gdaltest.runexternal(test_cli_utilities.get_test_ogrsf_path() + ' tmp/test_dgnv8.dgn') os.unlink('tmp/test_dgnv8.dgn') - if ret.find('INFO') == -1 or ret.find('ERROR') != -1: - gdaltest.post_reason('fail') - print(ret) - return 'fail' - - return 'success' + assert ret.find('INFO') != -1 and ret.find('ERROR') == -1 ############################################################################### # Test creation code -def ogr_dgnv8_4(): +def test_ogr_dgnv8_4(): if gdaltest.dgnv8_drv is None: - return 'skip' + pytest.skip() tmp_dgn = 'tmp/ogr_dgnv8_4.dgn' gdal.VectorTranslate(tmp_dgn, 'data/test_dgnv8.dgn', format='DGNv8') @@ -139,10 +126,10 @@ def ogr_dgnv8_4(): # Test creation options -def ogr_dgnv8_5(): +def test_ogr_dgnv8_5(): if gdaltest.dgnv8_drv is None: - return 'skip' + pytest.skip() tmp_dgn = 'tmp/ogr_dgnv8_5.dgn' options = ['APPLICATION=application', @@ -165,28 +152,17 @@ def ogr_dgnv8_5(): ds = None ds = ogr.Open(tmp_dgn) got_md = ds.GetMetadata_List('DGN') - if got_md != options: - gdaltest.post_reason('fail') - print(got_md) - return 'fail' + assert got_md == options ds = None tmp2_dgn = 'tmp/ogr_dgnv8_5_2.dgn' gdaltest.dgnv8_drv.CreateDataSource(tmp2_dgn, options=['SEED=' + tmp_dgn, 'TITLE=another_title']) ds = ogr.Open(tmp2_dgn) - if ds.GetMetadataItem('TITLE', 'DGN') != 'another_title' or ds.GetMetadataItem('APPLICATION', 'DGN') != 'application': - gdaltest.post_reason('fail') - print(ds.GetMetadata('DGN')) - return 'fail' + assert ds.GetMetadataItem('TITLE', 'DGN') == 'another_title' and ds.GetMetadataItem('APPLICATION', 'DGN') == 'application', \ + ds.GetMetadata('DGN') lyr = ds.GetLayer(0) - if lyr.GetName() != 'my_layer': - gdaltest.post_reason('fail') - print(lyr.GetName()) - return 'fail' - if lyr.GetFeatureCount() != 0: - gdaltest.post_reason('fail') - print(lyr.GetFeatureCount()) - return 'fail' + assert lyr.GetName() == 'my_layer' + assert lyr.GetFeatureCount() == 0 ds = None ds = gdaltest.dgnv8_drv.CreateDataSource(tmp2_dgn, options=['SEED=' + tmp_dgn]) @@ -197,47 +173,23 @@ def ogr_dgnv8_5(): ds = None ds = ogr.Open(tmp2_dgn, update=1) lyr = ds.GetLayer(0) - if lyr.GetName() != 'a_layer': - gdaltest.post_reason('fail') - print(lyr.GetName()) - return 'fail' - if lyr.GetFeatureCount() != 1: - gdaltest.post_reason('fail') - print(lyr.GetFeatureCount()) - return 'fail' + assert lyr.GetName() == 'a_layer' + assert lyr.GetFeatureCount() == 1 f = lyr.GetNextFeature() if f.GetGeometryRef().ExportToWkt() != 'POINT (2 3)': - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' + pytest.fail() ds = None gdal.Unlink(tmp_dgn) gdal.Unlink(tmp2_dgn) - return 'success' - ############################################################################### # Cleanup -def ogr_dgnv8_cleanup(): - - return 'success' - - -gdaltest_list = [ - ogr_dgnv8_1, - ogr_dgnv8_2, - ogr_dgnv8_3, - ogr_dgnv8_4, - ogr_dgnv8_5, - ogr_dgnv8_cleanup] - -if __name__ == '__main__': +def test_ogr_dgnv8_cleanup(): - gdaltest.setup_run('ogr_dgnv8') + pass - gdaltest.run_tests(gdaltest_list) - sys.exit(gdaltest.summarize()) diff --git a/autotest/ogr/ogr_dods.py b/autotest/ogr/ogr_dods.py index c4a3bd83dfa2..ee24da6ddf67 100755 --- a/autotest/ogr/ogr_dods.py +++ b/autotest/ogr/ogr_dods.py @@ -26,37 +26,36 @@ # Boston, MA 02111-1307, USA. ############################################################################### -import sys -sys.path.append('../pymod') import gdaltest import ogrtest from osgeo import ogr from osgeo import gdal +import pytest ############################################################################### # Open DODS datasource. -def ogr_dods_1(): +@pytest.mark.skip() +def test_ogr_dods_1(): gdaltest.dods_ds = None ogrtest.dods_drv = ogr.GetDriverByName('DODS') if ogrtest.dods_drv is None: - return 'skip' + pytest.skip() gdal.SetConfigOption('DODS_AIS_FILE', 'data/ais.xml') srv = 'http://www.epic.noaa.gov:10100/dods/wod2001/natl_prof_bot.cdp?&_id=1' if gdaltest.gdalurlopen(srv) is None: gdaltest.dods_ds = None - return 'skip' + pytest.skip() gdaltest.dods_ds = ogr.Open('DODS:' + srv) - if gdaltest.dods_ds is None: - return 'fail' + assert gdaltest.dods_ds is not None try: gdaltest.dods_profiles = gdaltest.dods_ds.GetLayerByName('profiles') @@ -68,61 +67,52 @@ def ogr_dods_1(): if gdaltest.dods_profiles is None: gdaltest.dods_ds = None - gdaltest.post_reason('profiles layer missing, likely AIS stuff not working.') - return 'fail' - return 'success' - + pytest.fail('profiles layer missing, likely AIS stuff not working.') + ############################################################################### # Read a single feature from the profiles layer and verify a few things. # -def ogr_dods_2(): +@pytest.mark.skip() +def test_ogr_dods_2(): if gdaltest.dods_ds is None: - return 'skip' + pytest.skip() gdaltest.dods_profiles.ResetReading() feat = gdaltest.dods_profiles.GetNextFeature() - if feat.GetField('time') != -1936483200000: - gdaltest.post_reason('time wrong') - return 'fail' + assert feat.GetField('time') == -1936483200000, 'time wrong' - if feat.GetField('profile.depth') != [0, 10, 20, 30, 39]: - gdaltest.post_reason('depth wrong') - return 'fail' + assert feat.GetField('profile.depth') == [0, 10, 20, 30, 39], 'depth wrong' - if ogrtest.check_feature_geometry(feat, 'POINT (4.30000019 5.36999989)')\ - != 0: - return 'fail' + assert ogrtest.check_feature_geometry(feat, 'POINT (4.30000019 5.36999989)') == 0 feat.Destroy() feat = gdaltest.dods_profiles.GetNextFeature() if feat is not None: feat.Destroy() - gdaltest.post_reason('got more than expected number of features.') - return 'fail' - - return 'success' + pytest.fail('got more than expected number of features.') + ############################################################################### # Read the normalized form of the same profile, and verify some values. # -def ogr_dods_3(): +@pytest.mark.skip() +def test_ogr_dods_3(): if gdaltest.dods_ds is None: - return 'skip' + pytest.skip() gdaltest.dods_normalized.ResetReading() expect = [0, 10, 20, 30, 39] tr = ogrtest.check_features_against_list(gdaltest.dods_normalized, 'depth', expect) - if tr == 0: - return 'fail' + assert tr != 0 expected = [14.8100004196167, 14.8100004196167, 14.8100004196167, 14.60999965667725, 14.60999965667725] @@ -130,17 +120,11 @@ def ogr_dods_3(): for i in range(5): feat = gdaltest.dods_normalized.GetNextFeature() - if feat.GetField('time') != -1936483200000: - gdaltest.post_reason('time wrong') - return 'fail' + assert feat.GetField('time') == -1936483200000, 'time wrong' - if abs(feat.GetField('T_20') - expected[i]) > 0.001: - gdaltest.post_reason('T_20 wrong') - return 'fail' + assert abs(feat.GetField('T_20') - expected[i]) <= 0.001, 'T_20 wrong' - if ogrtest.check_feature_geometry(feat, 'POINT (4.30000019 5.36999989)')\ - != 0: - return 'fail' + assert ogrtest.check_feature_geometry(feat, 'POINT (4.30000019 5.36999989)') == 0 feat.Destroy() feat = None @@ -148,107 +132,76 @@ def ogr_dods_3(): feat = gdaltest.dods_normalized.GetNextFeature() if feat is not None: feat.Destroy() - gdaltest.post_reason('got more than expected number of features.') - return 'fail' - - return 'success' + pytest.fail('got more than expected number of features.') + ############################################################################### # Read the "lines" from from the same server and verify some values. # -def ogr_dods_4(): +@pytest.mark.skip() +def test_ogr_dods_4(): if gdaltest.dods_ds is None: - return 'skip' + pytest.skip() gdaltest.dods_lines.ResetReading() feat = gdaltest.dods_lines.GetNextFeature() - if feat.GetField('time') != -1936483200000: - gdaltest.post_reason('time wrong') - return 'fail' + assert feat.GetField('time') == -1936483200000, 'time wrong' - if feat.GetField('profile.depth') != [0, 10, 20, 30, 39]: - gdaltest.post_reason('depth wrong') - return 'fail' + assert feat.GetField('profile.depth') == [0, 10, 20, 30, 39], 'depth wrong' wkt_geom = 'LINESTRING (0.00000000 14.81000042,10.00000000 14.81000042,20.00000000 14.81000042,30.00000000 14.60999966,39.00000000 14.60999966)' - if ogrtest.check_feature_geometry(feat, wkt_geom) != 0: - print(feat.GetGeometryRef().ExportToWkt()) - return 'fail' + assert ogrtest.check_feature_geometry(feat, wkt_geom) == 0, \ + feat.GetGeometryRef().ExportToWkt() feat.Destroy() feat = gdaltest.dods_lines.GetNextFeature() if feat is not None: feat.Destroy() - gdaltest.post_reason('got more than expected number of features.') - return 'fail' - - return 'success' + pytest.fail('got more than expected number of features.') + ############################################################################### # Simple 1D Grid. # -def ogr_dods_5(): +@pytest.mark.skip() +def test_ogr_dods_5(): if ogrtest.dods_drv is None: - return 'skip' + pytest.skip() srv = 'http://uhslc1.soest.hawaii.edu/cgi-bin/nph-nc/fast/m004.nc.dds' if gdaltest.gdalurlopen(srv) is None: - return 'skip' + pytest.skip() grid_ds = ogr.Open('DODS:' + srv) - if grid_ds is None: - return 'fail' + assert grid_ds is not None lat_lyr = grid_ds.GetLayerByName('latitude') expect = [-0.53166663646698] tr = ogrtest.check_features_against_list(lat_lyr, 'latitude', expect) - if tr == 0: - return 'fail' - - return 'success' + assert tr != 0 ############################################################################### # -def ogr_dods_cleanup(): +@pytest.mark.skip() +def test_ogr_dods_cleanup(): if gdaltest.dods_ds is None: - return 'skip' + pytest.skip() gdaltest.dods_profiles = None gdaltest.dods_lines = None gdaltest.dods_normalized = None gdaltest.dods_ds.Destroy() gdaltest.dods_ds = None - - return 'success' - - -gdaltest_list = [] - -manual_gdaltest_list = [ - ogr_dods_1, - ogr_dods_2, - ogr_dods_3, - ogr_dods_4, - ogr_dods_5, - ogr_dods_cleanup] - -if __name__ == '__main__': - - gdaltest.setup_run('ogr_dods') - - gdaltest.run_tests(manual_gdaltest_list) - - sys.exit(gdaltest.summarize()) diff --git a/autotest/ogr/ogr_dxf.py b/autotest/ogr/ogr_dxf.py index b25a89dcc1d6..58823a6c827e 100644 --- a/autotest/ogr/ogr_dxf.py +++ b/autotest/ogr/ogr_dxf.py @@ -31,46 +31,37 @@ ############################################################################### import os -import sys from sys import version_info -sys.path.append('../pymod') import ogrtest import gdaltest from osgeo import gdal from osgeo import ogr +import pytest ############################################################################### # Check some general things to see if they meet expectations. -def ogr_dxf_1(): +def test_ogr_dxf_1(): gdaltest.dxf_ds = ogr.Open('data/assorted.dxf') - if gdaltest.dxf_ds is None: - return 'fail' + assert gdaltest.dxf_ds is not None - if gdaltest.dxf_ds.GetLayerCount() != 1: - gdaltest.post_reason('expected exactly one layer!') - return 'fail' + assert gdaltest.dxf_ds.GetLayerCount() == 1, 'expected exactly one layer!' gdaltest.dxf_layer = gdaltest.dxf_ds.GetLayer(0) - if gdaltest.dxf_layer.GetName() != 'entities': - gdaltest.post_reason('did not get expected layer name.') - return 'fail' + assert gdaltest.dxf_layer.GetName() == 'entities', \ + 'did not get expected layer name.' defn = gdaltest.dxf_layer.GetLayerDefn() - if defn.GetFieldCount() != 6: - gdaltest.post_reason('did not get expected number of fields.') - return 'fail' + assert defn.GetFieldCount() == 6, 'did not get expected number of fields.' fc = gdaltest.dxf_layer.GetFeatureCount() - if fc != 22: - gdaltest.post_reason('did not get expected feature count, got %d' % fc) - return 'fail' + assert fc == 22, ('did not get expected feature count, got %d' % fc) # Setup the utf-8 string. if version_info >= (3, 0, 0): @@ -86,72 +77,54 @@ def ogr_dxf_1(): gdaltest.sample_text += '"abc"' gdaltest.sample_text = gdaltest.sample_text.encode('utf-8') - return 'success' - + ############################################################################### # Read the first feature, an ellipse and see if it generally meets expectations. -def ogr_dxf_2(): +def test_ogr_dxf_2(): gdaltest.dxf_layer.ResetReading() feat = gdaltest.dxf_layer.GetNextFeature() - if feat.Layer != '0': - gdaltest.post_reason('did not get expected layer for feature 0') - return 'fail' + assert feat.Layer == '0', 'did not get expected layer for feature 0' - if feat.PaperSpace != None: - gdaltest.post_reason( 'did not get expected PaperSpace for feature 0' ) - return 'fail' + assert feat.PaperSpace == None, 'did not get expected PaperSpace for feature 0' - if feat.GetFID() != 0: - gdaltest.post_reason('did not get expected fid for feature 0') - return 'fail' + assert feat.GetFID() == 0, 'did not get expected fid for feature 0' - if feat.SubClasses != 'AcDbEntity:AcDbEllipse': - gdaltest.post_reason('did not get expected SubClasses on feature 0.') - return 'fail' + assert feat.SubClasses == 'AcDbEntity:AcDbEllipse', \ + 'did not get expected SubClasses on feature 0.' - if feat.LineType != 'ByLayer': - gdaltest.post_reason('Did not get expected LineType') - return 'fail' + assert feat.LineType == 'ByLayer', 'Did not get expected LineType' - if feat.EntityHandle != '43': - gdaltest.post_reason('did not get expected EntityHandle') - return 'fail' + assert feat.EntityHandle == '43', 'did not get expected EntityHandle' if feat.GetStyleString() != 'PEN(c:#000000)': print('%s' % feat.GetStyleString()) - gdaltest.post_reason('did not get expected style string on feat 0.') - return 'fail' + pytest.fail('did not get expected style string on feat 0.') geom = feat.GetGeometryRef() - if geom.GetGeometryType() != ogr.wkbLineString25D: - gdaltest.post_reason('did not get expected geometry type.') - return 'fail' + assert geom.GetGeometryType() == ogr.wkbLineString25D, \ + 'did not get expected geometry type.' envelope = geom.GetEnvelope() area = (envelope[1] - envelope[0]) * (envelope[3] - envelope[2]) exp_area = 1596.12 - if area < exp_area - 0.5 or area > exp_area + 0.5: - gdaltest.post_reason('envelope area not as expected, got %g.' % area) - return 'fail' + assert area >= exp_area - 0.5 and area <= exp_area + 0.5, \ + ('envelope area not as expected, got %g.' % area) - if abs(geom.GetX(0) - 73.25) > 0.001 or abs(geom.GetY(0) - 139.75) > 0.001: - gdaltest.post_reason('first point (%g,%g) not expected location.' + assert abs(geom.GetX(0) - 73.25) <= 0.001 and abs(geom.GetY(0) - 139.75) <= 0.001, \ + ('first point (%g,%g) not expected location.' % (geom.GetX(0), geom.GetY(0))) - return 'fail' - - return 'success' ############################################################################### # Second feature should be a partial ellipse. -def ogr_dxf_3(): +def test_ogr_dxf_3(): feat = gdaltest.dxf_layer.GetNextFeature() @@ -161,74 +134,57 @@ def ogr_dxf_3(): area = (envelope[1] - envelope[0]) * (envelope[3] - envelope[2]) exp_area = 311.864 - if area < exp_area - 0.5 or area > exp_area + 0.5: - gdaltest.post_reason('envelope area not as expected, got %g.' % area) - return 'fail' + assert area >= exp_area - 0.5 and area <= exp_area + 0.5, \ + ('envelope area not as expected, got %g.' % area) - if abs(geom.GetX(0) - 61.133) > 0.01 or abs(geom.GetY(0) - 103.592) > 0.01: - gdaltest.post_reason('first point (%g,%g) not expected location.' + assert abs(geom.GetX(0) - 61.133) <= 0.01 and abs(geom.GetY(0) - 103.592) <= 0.01, \ + ('first point (%g,%g) not expected location.' % (geom.GetX(0), geom.GetY(0))) - return 'fail' - - return 'success' ############################################################################### # Third feature: point. -def ogr_dxf_4(): +def test_ogr_dxf_4(): feat = gdaltest.dxf_layer.GetNextFeature() - if ogrtest.check_feature_geometry(feat, 'POINT (83.5 160.0 0)'): - return 'fail' - - return 'success' + assert not ogrtest.check_feature_geometry(feat, 'POINT (83.5 160.0 0)') ############################################################################### # Fourth feature: LINE -def ogr_dxf_5(): +def test_ogr_dxf_5(): feat = gdaltest.dxf_layer.GetNextFeature() - if ogrtest.check_feature_geometry(feat, 'LINESTRING (97.0 159.5 0,108.5 132.25 0)'): - return 'fail' + assert not ogrtest.check_feature_geometry(feat, 'LINESTRING (97.0 159.5 0,108.5 132.25 0)') - if feat.GetGeometryRef().GetGeometryType() == ogr.wkbLineString: - gdaltest.post_reason('not keeping 3D linestring as 3D') - return 'fail' - - return 'success' + assert feat.GetGeometryRef().GetGeometryType() != ogr.wkbLineString, \ + 'not keeping 3D linestring as 3D' ############################################################################### # Fourth feature: MTEXT -def ogr_dxf_6(): +def test_ogr_dxf_6(): feat = gdaltest.dxf_layer.GetNextFeature() - if ogrtest.check_feature_geometry(feat, 'POINT (84 126)'): - return 'fail' - - if feat.GetGeometryRef().GetGeometryType() == ogr.wkbPoint25D: - gdaltest.post_reason('not keeping 2D text as 2D') - return 'fail' + assert not ogrtest.check_feature_geometry(feat, 'POINT (84 126)') - if feat.GetStyleString() != 'LABEL(f:"Arial",t:"Test",a:30,s:5g,p:7,c:#000000)': - print(feat.GetStyleString()) - gdaltest.post_reason('got wrong style string') - return 'fail' + assert feat.GetGeometryRef().GetGeometryType() != ogr.wkbPoint25D, \ + 'not keeping 2D text as 2D' - return 'success' + assert feat.GetStyleString() == 'LABEL(f:"Arial",t:"Test",a:30,s:5g,p:7,c:#000000)', \ + 'got wrong style string' ############################################################################### # Partial CIRCLE -def ogr_dxf_7(): +def test_ogr_dxf_7(): feat = gdaltest.dxf_layer.GetNextFeature() @@ -240,80 +196,64 @@ def ogr_dxf_7(): if area < exp_area - 0.5 or area > exp_area + 0.5: print(envelope) - gdaltest.post_reason('envelope area not as expected, got %g.' % area) - return 'fail' + pytest.fail('envelope area not as expected, got %g.' % area) - if abs(geom.GetX(0) - 115.258) > 0.01 or abs(geom.GetY(0) - 107.791) > 0.01: - gdaltest.post_reason('first point (%g,%g) not expected location.' + assert abs(geom.GetX(0) - 115.258) <= 0.01 and abs(geom.GetY(0) - 107.791) <= 0.01, \ + ('first point (%g,%g) not expected location.' % (geom.GetX(0), geom.GetY(0))) - return 'fail' - - return 'success' ############################################################################### # PaperSpace and dimension -def ogr_dxf_8(): +def test_ogr_dxf_8(): # Check that this line is in PaperSpace feat = gdaltest.dxf_layer.GetNextFeature() - if feat.GetField('PaperSpace') != 1: - gdaltest.post_reason( 'did not get expected PaperSpace' ) - return 'fail' + assert feat.GetField('PaperSpace') == 1, 'did not get expected PaperSpace' # Dimension lines feat = gdaltest.dxf_layer.GetNextFeature() geom = feat.GetGeometryRef() - if geom.GetGeometryType() != ogr.wkbMultiLineString: - gdaltest.post_reason('did not get expected geometry type.') - return 'fail' + assert geom.GetGeometryType() == ogr.wkbMultiLineString, \ + 'did not get expected geometry type.' - if ogrtest.check_feature_geometry(feat, 'MULTILINESTRING ((63.8628719444825 149.209935992088,24.3419606685507 111.934531038653),(72.3255686642474 140.237438265109,63.0051995752285 150.119275371538),(32.8046573883157 102.962033311673,23.4842882992968 112.843870418103))'): - return 'fail' + assert not ogrtest.check_feature_geometry(feat, 'MULTILINESTRING ((63.8628719444825 149.209935992088,24.3419606685507 111.934531038653),(72.3255686642474 140.237438265109,63.0051995752285 150.119275371538),(32.8046573883157 102.962033311673,23.4842882992968 112.843870418103))') # Dimension arrowheads feat = gdaltest.dxf_layer.GetNextFeature() geom = feat.GetGeometryRef() - if geom.GetGeometryType() != ogr.wkbPolygon25D: - gdaltest.post_reason('did not get expected geometry type.') - return 'fail' + assert geom.GetGeometryType() == ogr.wkbPolygon25D, \ + 'did not get expected geometry type.' - if ogrtest.check_feature_geometry(feat, 'POLYGON Z ((61.7583023958313 147.797704380064 0,63.8628719444825 149.209935992088 0,62.3300839753339 147.191478127097 0,61.7583023958313 147.797704380064 0))'): - return 'fail' + assert not ogrtest.check_feature_geometry(feat, 'POLYGON Z ((61.7583023958313 147.797704380064 0,63.8628719444825 149.209935992088 0,62.3300839753339 147.191478127097 0,61.7583023958313 147.797704380064 0))') feat = gdaltest.dxf_layer.GetNextFeature() geom = feat.GetGeometryRef() - if geom.GetGeometryType() != ogr.wkbPolygon25D: - gdaltest.post_reason('did not get expected geometry type.') - return 'fail' + assert geom.GetGeometryType() == ogr.wkbPolygon25D, \ + 'did not get expected geometry type.' - if ogrtest.check_feature_geometry(feat, 'POLYGON Z ((26.4465302172018 113.346762650677 0,24.3419606685507 111.934531038653 0,25.8747486376992 113.952988903644 0,26.4465302172018 113.346762650677 0))'): - return 'fail' + assert not ogrtest.check_feature_geometry(feat, 'POLYGON Z ((26.4465302172018 113.346762650677 0,24.3419606685507 111.934531038653 0,25.8747486376992 113.952988903644 0,26.4465302172018 113.346762650677 0))') # Dimension text feat = gdaltest.dxf_layer.GetNextFeature() geom = feat.GetGeometryRef() - if ogrtest.check_feature_geometry(feat, 'POINT (42.815907752635709 131.936242584545397)'): - return 'fail' + assert not ogrtest.check_feature_geometry(feat, 'POINT (42.815907752635709 131.936242584545397)') expected_style = 'LABEL(f:"Arial",t:"54.33",p:5,a:43.3,s:2.5g,c:#000000)' - if feat.GetStyleString() != expected_style: - gdaltest.post_reason('Got unexpected style string:\n%s\ninstead of:\n%s' % (feat.GetStyleString(), expected_style)) - return 'fail' - - return 'success' + assert feat.GetStyleString() == expected_style, \ + ('Got unexpected style string:\n%s\ninstead of:\n%s' % (feat.GetStyleString(), expected_style)) ############################################################################### # BLOCK (inlined) -def ogr_dxf_9(): +def test_ogr_dxf_9(): # Skip two dimensions each with a line, two arrowheads and text. for _ in range(8): @@ -323,47 +263,36 @@ def ogr_dxf_9(): feat = gdaltest.dxf_layer.GetNextFeature() geom = feat.GetGeometryRef() - if geom.GetGeometryType() != ogr.wkbMultiLineString25D: - gdaltest.post_reason('did not get expected geometry type.') - return 'fail' + assert geom.GetGeometryType() == ogr.wkbMultiLineString25D, \ + 'did not get expected geometry type.' - if ogrtest.check_feature_geometry(feat, 'MULTILINESTRING ((79.069506278985116 121.003652476272777 0,79.716898725419625 118.892590150942851 0),(79.716898725419625 118.892590150942851 0,78.140638855839953 120.440702522851453 0),(78.140638855839953 120.440702522851453 0,80.139111190485622 120.328112532167196 0),(80.139111190485622 120.328112532167196 0,78.619146316248077 118.920737648613908 0),(78.619146316248077 118.920737648613908 0,79.041358781314059 120.975504978601705 0))'): - return 'fail' + assert not ogrtest.check_feature_geometry(feat, 'MULTILINESTRING ((79.069506278985116 121.003652476272777 0,79.716898725419625 118.892590150942851 0),(79.716898725419625 118.892590150942851 0,78.140638855839953 120.440702522851453 0),(78.140638855839953 120.440702522851453 0,80.139111190485622 120.328112532167196 0),(80.139111190485622 120.328112532167196 0,78.619146316248077 118.920737648613908 0),(78.619146316248077 118.920737648613908 0,79.041358781314059 120.975504978601705 0))') # First of two MTEXTs feat = gdaltest.dxf_layer.GetNextFeature() - if feat.GetField('Text') != gdaltest.sample_text: - gdaltest.post_reason('Did not get expected first mtext.') - return 'fail' + assert feat.GetField('Text') == gdaltest.sample_text, \ + 'Did not get expected first mtext.' expected_style = 'LABEL(f:"Arial",t:"' + gdaltest.sample_style + '",a:45,s:0.5g,p:5,c:#000000)' - if feat.GetStyleString() != expected_style: - gdaltest.post_reason('Got unexpected style string:\n%s\ninstead of:\n%s.' % (feat.GetStyleString(), expected_style)) - return 'fail' + assert feat.GetStyleString() == expected_style, \ + ('Got unexpected style string:\n%s\ninstead of:\n%s.' % (feat.GetStyleString(), expected_style)) - if ogrtest.check_feature_geometry(feat, 'POINT (77.602201427662891 120.775897075866169 0)'): - return 'fail' + assert not ogrtest.check_feature_geometry(feat, 'POINT (77.602201427662891 120.775897075866169 0)') # Second of two MTEXTs feat = gdaltest.dxf_layer.GetNextFeature() - if feat.GetField('Text') != 'Second': - gdaltest.post_reason('Did not get expected second mtext.') - return 'fail' + assert feat.GetField('Text') == 'Second', 'Did not get expected second mtext.' - if feat.GetField('SubClasses') != 'AcDbEntity:AcDbMText': - gdaltest.post_reason('Did not get expected subclasses.') - return 'fail' + assert feat.GetField('SubClasses') == 'AcDbEntity:AcDbMText', \ + 'Did not get expected subclasses.' - if ogrtest.check_feature_geometry(feat, 'POINT (79.977331629005178 119.698291706738644 0)'): - return 'fail' - - return 'success' + assert not ogrtest.check_feature_geometry(feat, 'POINT (79.977331629005178 119.698291706738644 0)') ############################################################################### # LWPOLYLINE in an Object Coordinate System. -def ogr_dxf_10(): +def test_ogr_dxf_10(): ocs_ds = ogr.Open('data/LWPOLYLINE-OCS.dxf') ocs_lyr = ocs_ds.GetLayer(0) @@ -375,31 +304,25 @@ def ogr_dxf_10(): feat = ocs_lyr.GetNextFeature() geom = feat.GetGeometryRef() - if geom.GetGeometryType() != ogr.wkbLineString25D: - print(geom.GetGeometryType()) - gdaltest.post_reason('did not get expected geometry type.') - return 'fail' + assert geom.GetGeometryType() == ogr.wkbLineString25D, \ + 'did not get expected geometry type.' - if ogrtest.check_feature_geometry(feat, 'LINESTRING (600325.567999998573214 3153021.253000000491738 562.760000000052969,600255.215999998385087 3151973.98600000096485 536.950000000069849,597873.927999997511506 3152247.628000000491738 602.705000000089058)'): - return 'fail' + assert not ogrtest.check_feature_geometry(feat, 'LINESTRING (600325.567999998573214 3153021.253000000491738 562.760000000052969,600255.215999998385087 3151973.98600000096485 536.950000000069849,597873.927999997511506 3152247.628000000491738 602.705000000089058)') # LWPOLYLINE in OCS with bulge feat = ocs_lyr.GetFeature(12) - if ogrtest.check_feature_geometry(feat, 'LINESTRING Z (611415.459819656 3139300.00002682 1807.37309215522,611245.079665823 3139720.59876424 1807.37309215522,611245.079665823 3139720.59876424 1807.37309215522,611244.054791235 3139723.12875936 1807.27984293229,611243.034695086 3139725.64695847 1807.00053001486,611242.024133533 3139728.14162057 1806.53645568869,611241.027818282 3139730.6011144 1805.88978368251,611240.050394615 3139733.01397265 1805.06352907972,611239.096419732 3139735.36894547 1804.06154426071,611238.170341503 3139737.65505289 1802.88850094122,611237.276477734 3139739.86163602 1801.54986839073,611236.418996029 3139741.97840675 1800.0518879321,611235.601894365 3139743.99549572 1798.40154384175,611234.828982446 3139745.90349832 1796.60653078564,611234.103863944 3139747.69351857 1794.67521794327,611233.429919697 3139749.35721058 1792.61660998662,611232.810291944 3139750.88681743 1790.44030509629,611232.247869676 3139752.27520739 1788.15645021029,611231.745275164 3139753.51590716 1785.77569371438,611231.304851737 3139754.60313201 1783.30913579435,611230.928652852 3139755.5318128 1780.76827668182,611230.618432521 3139756.29761959 1778.16496303489,611230.375637135 3139756.89698184 1775.51133270351,611230.201398719 3139757.32710505 1772.81975813727,611230.096529651 3139757.58598378 1770.10278869926,611230.06151888 3139757.67241101 1767.37309215522,611230.06151892 3139757.67241089 1661.18408370228,611230.06151892 3139757.67241089 1661.18408370228,611230.026508154 3139757.75883812 1658.45438717061,611229.921639091 3139758.01771683 1655.73741774404,611229.74740068 3139758.44784002 1653.04584318824,611229.5046053 3139759.04720226 1650.39221286628,611229.194384975 3139759.81300904 1647.78889922769,611228.818186096 3139760.74168982 1645.24804012238,611228.377762675 3139761.82891465 1642.78148220841,611227.87516817 3139763.0696144 1640.40072571739,611227.312745909 3139764.45800435 1638.11687083509,611226.693118163 3139765.98761118 1635.94056594722,611226.019173923 3139767.65130317 1633.88195799181,611225.294055428 3139769.4413234 1631.95064514943,611224.521143516 3139771.34932599 1630.15563209209,611223.704041858 3139773.36641494 1628.50528799927,611222.84656016 3139775.48318565 1627.00730753696,611221.952696397 3139777.68976876 1625.66867498157,611221.026618175 3139779.97587617 1624.49563165602,611220.072643298 3139782.33084897 1623.49364682979,611219.095219637 3139784.74370721 1622.66739221866,611218.098904392 3139787.20320102 1622.02072020306,611217.088342845 3139789.69786311 1621.55664586644,' + - '611216.0682467 3139792.21606221 1621.27733293758,611215.043372117 3139794.74605732 1621.18408370228,610905.973331759 3140557.71325641 1621.18408370228,610905.973331759 3140557.71325641 1621.18408370228,610904.948457176 3140560.24325151 1621.2773329396,610903.928361033 3140562.76145061 1621.55664587034,610902.917799487 3140565.2561127 1622.02072020868,610901.921484243 3140567.71560651 1622.66739222582,610900.944060583 3140570.12846474 1623.49364683831,610899.990085707 3140572.48343755 1624.49563166573,610899.064007486 3140574.76954495 1625.66867499227,610898.170143725 3140576.97612806 1627.00730754846,610897.312662028 3140579.09289877 1628.50528801138,610896.495560372 3140581.10998771 1630.1556321046,610895.722648461 3140583.0179903 1631.95064516215,610894.997529967 3140584.80801053 1633.88195800453,610894.323585729 3140586.47170251 1635.94056595974,610893.703957984 3140588.00130935 1638.1168708472,610893.141535724 3140589.38969929 1640.4007257289,610892.63894122 3140590.63039904 1642.78148221912,610892.198517801 3140591.71762387 1645.2480401321,610891.822318923 3140592.64630464 1647.78889923622,610891.5120986 3140593.41211142 1650.39221287345,610891.269303221 3140594.01147366 1653.04584319386,610891.095064811 3140594.44159685 1655.73741774794,610890.99019575 3140594.70047556 1658.45438717264,610890.955184986 3140594.78690278 1661.18408370228,610890.955185021 3140594.78690272 1752.31638281001,610890.955185021 3140594.78690271 1752.31638281001,610890.920174252 3140594.87332995 1755.04607934987,610890.815305187 3140595.13220867 1757.76304878401,610890.641066773 3140595.56233187 1760.45462334672,610890.398271389 3140596.16169412 1763.10825367492,610890.088051061 3140596.92750091 1765.71156731903,610889.711852178 3140597.85618169 1768.25242642912,610889.271428753 3140598.94340654 1770.71898434711,610888.768834244 3140600.1841063 1773.09974084137,610888.206411978 3140601.57249626 1775.38359572612,610887.586784228 3140603.1021031 1777.55990061562,610886.912839984 3140604.7657951 1779.61850857185,610886.187721485 3140606.55581535 1781.54982141423,610885.414809569 3140608.46381795 1783.34483447076,610884.597707907 3140610.48090691 1784.99517856195,610883.740226205 3140612.59767763 1786.49315902182,610882.846362438 3140614.80426075 1787.83179157397,610881.920284211 3140617.09036817 1789.0048348955,610880.96630933 3140619.44534098 1790.00681971696,610879.988885665 3140621.85819923 1790.83307432256,610878.992570417 3140624.31769305 1791.47974633192,610877.982008866 3140626.81235515 1791.94382066162,610876.961912718 3140629.33055426 1792.22313358291,610875.937038132 3140631.86054938 1792.31638281001,610699.99993399 3141066.17711854 1792.31638281001)'): - return 'fail' + assert (not ogrtest.check_feature_geometry(feat, 'LINESTRING Z (611415.459819656 3139300.00002682 1807.37309215522,611245.079665823 3139720.59876424 1807.37309215522,611245.079665823 3139720.59876424 1807.37309215522,611244.054791235 3139723.12875936 1807.27984293229,611243.034695086 3139725.64695847 1807.00053001486,611242.024133533 3139728.14162057 1806.53645568869,611241.027818282 3139730.6011144 1805.88978368251,611240.050394615 3139733.01397265 1805.06352907972,611239.096419732 3139735.36894547 1804.06154426071,611238.170341503 3139737.65505289 1802.88850094122,611237.276477734 3139739.86163602 1801.54986839073,611236.418996029 3139741.97840675 1800.0518879321,611235.601894365 3139743.99549572 1798.40154384175,611234.828982446 3139745.90349832 1796.60653078564,611234.103863944 3139747.69351857 1794.67521794327,611233.429919697 3139749.35721058 1792.61660998662,611232.810291944 3139750.88681743 1790.44030509629,611232.247869676 3139752.27520739 1788.15645021029,611231.745275164 3139753.51590716 1785.77569371438,611231.304851737 3139754.60313201 1783.30913579435,611230.928652852 3139755.5318128 1780.76827668182,611230.618432521 3139756.29761959 1778.16496303489,611230.375637135 3139756.89698184 1775.51133270351,611230.201398719 3139757.32710505 1772.81975813727,611230.096529651 3139757.58598378 1770.10278869926,611230.06151888 3139757.67241101 1767.37309215522,611230.06151892 3139757.67241089 1661.18408370228,611230.06151892 3139757.67241089 1661.18408370228,611230.026508154 3139757.75883812 1658.45438717061,611229.921639091 3139758.01771683 1655.73741774404,611229.74740068 3139758.44784002 1653.04584318824,611229.5046053 3139759.04720226 1650.39221286628,611229.194384975 3139759.81300904 1647.78889922769,611228.818186096 3139760.74168982 1645.24804012238,611228.377762675 3139761.82891465 1642.78148220841,611227.87516817 3139763.0696144 1640.40072571739,611227.312745909 3139764.45800435 1638.11687083509,611226.693118163 3139765.98761118 1635.94056594722,611226.019173923 3139767.65130317 1633.88195799181,611225.294055428 3139769.4413234 1631.95064514943,611224.521143516 3139771.34932599 1630.15563209209,611223.704041858 3139773.36641494 1628.50528799927,611222.84656016 3139775.48318565 1627.00730753696,611221.952696397 3139777.68976876 1625.66867498157,611221.026618175 3139779.97587617 1624.49563165602,611220.072643298 3139782.33084897 1623.49364682979,611219.095219637 3139784.74370721 1622.66739221866,611218.098904392 3139787.20320102 1622.02072020306,611217.088342845 3139789.69786311 1621.55664586644,' + + '611216.0682467 3139792.21606221 1621.27733293758,611215.043372117 3139794.74605732 1621.18408370228,610905.973331759 3140557.71325641 1621.18408370228,610905.973331759 3140557.71325641 1621.18408370228,610904.948457176 3140560.24325151 1621.2773329396,610903.928361033 3140562.76145061 1621.55664587034,610902.917799487 3140565.2561127 1622.02072020868,610901.921484243 3140567.71560651 1622.66739222582,610900.944060583 3140570.12846474 1623.49364683831,610899.990085707 3140572.48343755 1624.49563166573,610899.064007486 3140574.76954495 1625.66867499227,610898.170143725 3140576.97612806 1627.00730754846,610897.312662028 3140579.09289877 1628.50528801138,610896.495560372 3140581.10998771 1630.1556321046,610895.722648461 3140583.0179903 1631.95064516215,610894.997529967 3140584.80801053 1633.88195800453,610894.323585729 3140586.47170251 1635.94056595974,610893.703957984 3140588.00130935 1638.1168708472,610893.141535724 3140589.38969929 1640.4007257289,610892.63894122 3140590.63039904 1642.78148221912,610892.198517801 3140591.71762387 1645.2480401321,610891.822318923 3140592.64630464 1647.78889923622,610891.5120986 3140593.41211142 1650.39221287345,610891.269303221 3140594.01147366 1653.04584319386,610891.095064811 3140594.44159685 1655.73741774794,610890.99019575 3140594.70047556 1658.45438717264,610890.955184986 3140594.78690278 1661.18408370228,610890.955185021 3140594.78690272 1752.31638281001,610890.955185021 3140594.78690271 1752.31638281001,610890.920174252 3140594.87332995 1755.04607934987,610890.815305187 3140595.13220867 1757.76304878401,610890.641066773 3140595.56233187 1760.45462334672,610890.398271389 3140596.16169412 1763.10825367492,610890.088051061 3140596.92750091 1765.71156731903,610889.711852178 3140597.85618169 1768.25242642912,610889.271428753 3140598.94340654 1770.71898434711,610888.768834244 3140600.1841063 1773.09974084137,610888.206411978 3140601.57249626 1775.38359572612,610887.586784228 3140603.1021031 1777.55990061562,610886.912839984 3140604.7657951 1779.61850857185,610886.187721485 3140606.55581535 1781.54982141423,610885.414809569 3140608.46381795 1783.34483447076,610884.597707907 3140610.48090691 1784.99517856195,610883.740226205 3140612.59767763 1786.49315902182,610882.846362438 3140614.80426075 1787.83179157397,610881.920284211 3140617.09036817 1789.0048348955,610880.96630933 3140619.44534098 1790.00681971696,610879.988885665 3140621.85819923 1790.83307432256,610878.992570417 3140624.31769305 1791.47974633192,610877.982008866 3140626.81235515 1791.94382066162,610876.961912718 3140629.33055426 1792.22313358291,610875.937038132 3140631.86054938 1792.31638281001,610699.99993399 3141066.17711854 1792.31638281001)')) ocs_lyr = None ocs_ds = None - return 'success' - ############################################################################### # Test reading from an entities-only dxf file (#3412) -def ogr_dxf_11(): +def test_ogr_dxf_11(): eo_ds = ogr.Open('data/entities_only.dxf') eo_lyr = eo_ds.GetLayer(0) @@ -407,27 +330,23 @@ def ogr_dxf_11(): # Check first point. feat = eo_lyr.GetNextFeature() - if ogrtest.check_feature_geometry(feat, - 'POINT (672500.0 242000.0 539.986)'): - return 'fail' + assert (not ogrtest.check_feature_geometry(feat, + 'POINT (672500.0 242000.0 539.986)')) # Check second point. feat = eo_lyr.GetNextFeature() - if ogrtest.check_feature_geometry(feat, - 'POINT (672750.0 242000.0 558.974)'): - return 'fail' + assert (not ogrtest.check_feature_geometry(feat, + 'POINT (672750.0 242000.0 558.974)')) eo_lyr = None eo_ds = None - return 'success' - ############################################################################### # Write a simple file with a polygon and a line, and read back. -def ogr_dxf_12(): +def test_ogr_dxf_12(): ds = ogr.GetDriverByName('DXF').CreateDataSource('tmp/dxf_11.dxf') @@ -465,45 +384,39 @@ def ogr_dxf_12(): # Check first feature feat = lyr.GetNextFeature() - if ogrtest.check_feature_geometry(feat, - 'LINESTRING(10 12, 60 65)'): - print(feat.GetGeometryRef().ExportToWkt()) - return 'fail' + assert (not ogrtest.check_feature_geometry(feat, + 'LINESTRING(10 12, 60 65)')), \ + feat.GetGeometryRef().ExportToWkt() - if feat.GetGeometryRef().GetGeometryType() != ogr.wkbLineString: - gdaltest.post_reason('not linestring 2D') - return 'fail' + assert feat.GetGeometryRef().GetGeometryType() == ogr.wkbLineString, \ + 'not linestring 2D' feat = None # Check second feature feat = lyr.GetNextFeature() - if ogrtest.check_feature_geometry(feat, - 'POLYGON((0 0,100 0,100 100,0 0))'): - print(feat.GetGeometryRef().ExportToWkt()) - return 'fail' + assert (not ogrtest.check_feature_geometry(feat, + 'POLYGON((0 0,100 0,100 100,0 0))')), \ + feat.GetGeometryRef().ExportToWkt() - if feat.GetGeometryRef().GetGeometryType() != ogr.wkbPolygon: - gdaltest.post_reason('not keeping polygon 2D') - return 'fail' + assert feat.GetGeometryRef().GetGeometryType() == ogr.wkbPolygon, \ + 'not keeping polygon 2D' feat = None # Check third feature feat = lyr.GetNextFeature() - if ogrtest.check_feature_geometry(feat, - 'LINESTRING(1 2 10,3 4 10)'): - print(feat.GetGeometryRef().ExportToWkt()) - return 'fail' + assert (not ogrtest.check_feature_geometry(feat, + 'LINESTRING(1 2 10,3 4 10)')), \ + feat.GetGeometryRef().ExportToWkt() feat = None # Check fourth feature feat = lyr.GetNextFeature() - if ogrtest.check_feature_geometry(feat, - 'LINESTRING(1 2 -10,3 4 10)'): - print(feat.GetGeometryRef().ExportToWkt()) - return 'fail' + assert (not ogrtest.check_feature_geometry(feat, + 'LINESTRING(1 2 -10,3 4 10)')), \ + feat.GetGeometryRef().ExportToWkt() feat = None lyr = None @@ -512,13 +425,11 @@ def ogr_dxf_12(): os.unlink('tmp/dxf_11.dxf') - return 'success' - ############################################################################### # Check smoothed polyline. -def ogr_dxf_13(): +def test_ogr_dxf_13(): ds = ogr.Open('data/polyline_smooth.dxf') @@ -526,22 +437,18 @@ def ogr_dxf_13(): feat = layer.GetNextFeature() - if feat.Layer != '1': - gdaltest.post_reason('did not get expected layer for feature 0') - return 'fail' + assert feat.Layer == '1', 'did not get expected layer for feature 0' geom = feat.GetGeometryRef() - if geom.GetGeometryType() != ogr.wkbLineString25D: - gdaltest.post_reason('did not get expected geometry type.') - return 'fail' + assert geom.GetGeometryType() == ogr.wkbLineString25D, \ + 'did not get expected geometry type.' envelope = geom.GetEnvelope() area = (envelope[1] - envelope[0]) * (envelope[3] - envelope[2]) exp_area = 1350.43 - if area < exp_area - 0.5 or area > exp_area + 0.5: - gdaltest.post_reason('envelope area not as expected, got %g.' % area) - return 'fail' + assert area >= exp_area - 0.5 and area <= exp_area + 0.5, \ + ('envelope area not as expected, got %g.' % area) # Check for specific number of points from tessellated arc(s). # Note that this number depends on the tessellation algorithm and @@ -552,15 +459,12 @@ def ogr_dxf_13(): # only that more points are returned than in the original polyline, and # that the points lie along (or reasonably close to) said path. - if geom.GetPointCount() != 146: - gdaltest.post_reason('did not get expected number of points, got %d' % geom.GetPointCount()) - return 'fail' + assert geom.GetPointCount() == 146, \ + ('did not get expected number of points, got %d' % geom.GetPointCount()) - if abs(geom.GetX(0) - 251297.8179) > 0.001 \ - or abs(geom.GetY(0) - 412226.8286) > 0.001: - gdaltest.post_reason('first point (%g,%g) not expected location.' + assert abs(geom.GetX(0) - 251297.8179) <= 0.001 and abs(geom.GetY(0) - 412226.8286) <= 0.001, \ + ('first point (%g,%g) not expected location.' % (geom.GetX(0), geom.GetY(0))) - return 'fail' # Other possible tests: # Polylines with no explicit Z coordinates (e.g., no attribute 38 for @@ -572,13 +476,11 @@ def ogr_dxf_13(): ds = None - return 'success' - ############################################################################### # Check smooth LWPOLYLINE entity. -def ogr_dxf_14(): +def test_ogr_dxf_14(): # This test is identical to the previous one except the # newer lwpolyline entity is used. See the comments in the @@ -590,44 +492,35 @@ def ogr_dxf_14(): feat = layer.GetNextFeature() - if feat.Layer != '1': - gdaltest.post_reason('did not get expected layer for feature 0') - return 'fail' + assert feat.Layer == '1', 'did not get expected layer for feature 0' geom = feat.GetGeometryRef() - if geom.GetGeometryType() != ogr.wkbLineString: - gdaltest.post_reason('did not get expected geometry type.') - return 'fail' + assert geom.GetGeometryType() == ogr.wkbLineString, \ + 'did not get expected geometry type.' envelope = geom.GetEnvelope() area = (envelope[1] - envelope[0]) * (envelope[3] - envelope[2]) exp_area = 1350.43 - if area < exp_area - 0.5 or area > exp_area + 0.5: - gdaltest.post_reason('envelope area not as expected, got %g.' % area) - return 'fail' + assert area >= exp_area - 0.5 and area <= exp_area + 0.5, \ + ('envelope area not as expected, got %g.' % area) - if geom.GetPointCount() != 146: - gdaltest.post_reason('did not get expected number of points, got %d' % geom.GetPointCount()) - return 'fail' + assert geom.GetPointCount() == 146, \ + ('did not get expected number of points, got %d' % geom.GetPointCount()) - if abs(geom.GetX(0) - 251297.8179) > 0.001 \ - or abs(geom.GetY(0) - 412226.8286) > 0.001: - gdaltest.post_reason('first point (%g,%g) not expected location.' + assert abs(geom.GetX(0) - 251297.8179) <= 0.001 and abs(geom.GetY(0) - 412226.8286) <= 0.001, \ + ('first point (%g,%g) not expected location.' % (geom.GetX(0), geom.GetY(0))) - return 'fail' ds = None - return 'success' - ############################################################################### # Write a file with dynamic layer creation and confirm that the # dynamically created layer 'abc' matches the definition of the default # layer '0'. -def ogr_dxf_15(): +def test_ogr_dxf_15(): ds = ogr.GetDriverByName('DXF').CreateDataSource('tmp/dxf_14.dxf', ['FIRST_ENTITY=80']) @@ -653,35 +546,26 @@ def ogr_dxf_15(): # Check first feature feat = lyr.GetNextFeature() - if ogrtest.check_feature_geometry(feat, - 'LINESTRING(10 12, 60 65)'): - print(feat.GetGeometryRef().ExportToWkt()) - return 'fail' + assert (not ogrtest.check_feature_geometry(feat, + 'LINESTRING(10 12, 60 65)')), \ + feat.GetGeometryRef().ExportToWkt() - if feat.GetGeometryRef().GetGeometryType() == ogr.wkbLineString25D: - gdaltest.post_reason('not linestring 2D') - return 'fail' + assert feat.GetGeometryRef().GetGeometryType() != ogr.wkbLineString25D, \ + 'not linestring 2D' - if feat.GetField('Layer') != 'abc': - gdaltest.post_reason('Did not get expected layer, abc.') - return 'fail' + assert feat.GetField('Layer') == 'abc', 'Did not get expected layer, abc.' # Check second point. feat = lyr.GetNextFeature() - if ogrtest.check_feature_geometry(feat, - 'POLYGON((0 0,100 0,100 100,0 0))'): - print(feat.GetGeometryRef().ExportToWkt()) - return 'fail' + assert (not ogrtest.check_feature_geometry(feat, + 'POLYGON((0 0,100 0,100 100,0 0))')), \ + feat.GetGeometryRef().ExportToWkt() - if feat.GetGeometryRef().GetGeometryType() == ogr.wkbPolygon25D: - gdaltest.post_reason('not keeping polygon 2D') - return 'fail' + assert feat.GetGeometryRef().GetGeometryType() != ogr.wkbPolygon25D, \ + 'not keeping polygon 2D' - if feat.GetField('Layer') != '0': - print(feat.GetField('Layer')) - gdaltest.post_reason('Did not get expected layer, 0.') - return 'fail' + assert feat.GetField('Layer') == '0', 'Did not get expected layer, 0.' lyr = None ds = None @@ -700,45 +584,33 @@ def ogr_dxf_15(): abc_off = txt_2.find('abc\n') - if txt_2[16:abc_off] + '0' + txt_2[abc_off + 3:] != txt_1[16:]: - print(txt_2[abc_off] + '0' + txt_2[abc_off + 3:]) - print(txt_1) - gdaltest.post_reason('Layer abc does not seem to match layer 0.') - return 'fail' + assert txt_2[16:abc_off] + '0' + txt_2[abc_off + 3:] == txt_1[16:], \ + 'Layer abc does not seem to match layer 0.' # Check that $HANDSEED was set as expected. start_seed = outdxf.find('$HANDSEED') handseed = outdxf[start_seed + 10 + 4:start_seed + 10 + 4 + 8] - if handseed != '00000053': - gdaltest.post_reason('Did not get expected HANDSEED, got %s.' % handseed) - return 'fail' + assert handseed == '00000053', ('Did not get expected HANDSEED, got %s.' % handseed) os.unlink('tmp/dxf_14.dxf') - return 'success' - ############################################################################### # Test reading without DXF blocks inlined. -def ogr_dxf_16(): +def test_ogr_dxf_16(): gdal.SetConfigOption('DXF_INLINE_BLOCKS', 'FALSE') dxf_ds = ogr.Open('data/assorted.dxf') - if dxf_ds is None: - return 'fail' + assert dxf_ds is not None - if dxf_ds.GetLayerCount() != 2: - gdaltest.post_reason('expected exactly two layers!') - return 'fail' + assert dxf_ds.GetLayerCount() == 2, 'expected exactly two layers!' dxf_layer = dxf_ds.GetLayer(1) - if dxf_layer.GetName() != 'entities': - gdaltest.post_reason('did not get expected layer name.') - return 'fail' + assert dxf_layer.GetName() == 'entities', 'did not get expected layer name.' # read through till we encounter the block reference. feat = dxf_layer.GetNextFeature() @@ -746,21 +618,14 @@ def ogr_dxf_16(): feat = dxf_layer.GetNextFeature() # check contents. - if feat.GetField('BlockName') != 'STAR': - gdaltest.post_reason('Did not get blockname!') - return 'fail' + assert feat.GetField('BlockName') == 'STAR', 'Did not get blockname!' - if feat.GetField('BlockAngle') != 0.0: - gdaltest.post_reason('Did not get expected angle.') - return 'fail' + assert feat.GetField('BlockAngle') == 0.0, 'Did not get expected angle.' - if feat.GetField('BlockScale') != [1.0, 1.0, 1.0]: - print(feat.GetField('BlockScale')) - gdaltest.post_reason('Did not get expected BlockScale') - return 'fail' + assert feat.GetField('BlockScale') == [1.0, 1.0, 1.0], \ + 'Did not get expected BlockScale' - if ogrtest.check_feature_geometry(feat, 'POINT (79.097653776656188 119.962195062443342 0)'): - return 'fail' + assert not ogrtest.check_feature_geometry(feat, 'POINT (79.097653776656188 119.962195062443342 0)') feat = None @@ -768,46 +633,34 @@ def ogr_dxf_16(): dxf_layer = dxf_ds.GetLayer(0) - if dxf_layer.GetName() != 'blocks': - gdaltest.post_reason('did not get expected layer name.') - return 'fail' + assert dxf_layer.GetName() == 'blocks', 'did not get expected layer name.' # STAR geometry feat = dxf_layer.GetNextFeature() - if feat.GetField('Block') != 'STAR': - gdaltest.post_reason('Did not get expected block name.') - return 'fail' + assert feat.GetField('Block') == 'STAR', 'Did not get expected block name.' - if ogrtest.check_feature_geometry(feat, 'MULTILINESTRING ((-0.028147497671066 1.041457413829428 0,0.619244948763444 -1.069604911500494 0),(0.619244948763444 -1.069604911500494 0,-0.957014920816232 0.478507460408116 0),(-0.957014920816232 0.478507460408116 0,1.041457413829428 0.365917469723853 0),(1.041457413829428 0.365917469723853 0,-0.478507460408116 -1.041457413829428 0),(-0.478507460408116 -1.041457413829428 0,-0.056294995342131 1.013309916158363 0))'): - return 'fail' + assert not ogrtest.check_feature_geometry(feat, 'MULTILINESTRING ((-0.028147497671066 1.041457413829428 0,0.619244948763444 -1.069604911500494 0),(0.619244948763444 -1.069604911500494 0,-0.957014920816232 0.478507460408116 0),(-0.957014920816232 0.478507460408116 0,1.041457413829428 0.365917469723853 0),(1.041457413829428 0.365917469723853 0,-0.478507460408116 -1.041457413829428 0),(-0.478507460408116 -1.041457413829428 0,-0.056294995342131 1.013309916158363 0))') # First MTEXT feat = dxf_layer.GetNextFeature() - if feat.GetField('Text') != gdaltest.sample_text: - gdaltest.post_reason('Did not get expected first mtext.') - return 'fail' + assert feat.GetField('Text') == gdaltest.sample_text, \ + 'Did not get expected first mtext.' expected_style = 'LABEL(f:"Arial",t:"' + gdaltest.sample_style + '",a:45,s:0.5g,p:5,c:#000000)' - if feat.GetStyleString() != expected_style: - gdaltest.post_reason('Got unexpected style string:\n%s\ninstead of:\n%s.' % (feat.GetStyleString(), expected_style)) - return 'fail' + assert feat.GetStyleString() == expected_style, \ + ('Got unexpected style string:\n%s\ninstead of:\n%s.' % (feat.GetStyleString(), expected_style)) - if ogrtest.check_feature_geometry(feat, 'POINT (-1.495452348993292 0.813702013422821 0)'): - return 'fail' + assert not ogrtest.check_feature_geometry(feat, 'POINT (-1.495452348993292 0.813702013422821 0)') # Second MTEXT feat = dxf_layer.GetNextFeature() - if feat.GetField('Text') != 'Second': - gdaltest.post_reason('Did not get expected second mtext.') - return 'fail' + assert feat.GetField('Text') == 'Second', 'Did not get expected second mtext.' - if feat.GetField('SubClasses') != 'AcDbEntity:AcDbMText': - gdaltest.post_reason('Did not get expected subclasses.') - return 'fail' + assert feat.GetField('SubClasses') == 'AcDbEntity:AcDbMText', \ + 'Did not get expected subclasses.' - if ogrtest.check_feature_geometry(feat, 'POINT (0.879677852348995 -0.263903355704699 0)'): - return 'fail' + assert not ogrtest.check_feature_geometry(feat, 'POINT (0.879677852348995 -0.263903355704699 0)') feat = None @@ -815,13 +668,11 @@ def ogr_dxf_16(): gdal.SetConfigOption('DXF_INLINE_BLOCKS', 'TRUE') - return 'success' - ############################################################################### # Write a file with blocks defined from a source blocks layer. -def ogr_dxf_17(): +def test_ogr_dxf_17(): ds = ogr.GetDriverByName('DXF').CreateDataSource('tmp/dxf_17.dxf', ['HEADER=data/header_extended.dxf']) @@ -903,55 +754,44 @@ def ogr_dxf_17(): # Check first feature. feat = lyr.GetNextFeature() - if feat.GetField('SubClasses') != 'AcDbEntity:AcDbBlockReference': - gdaltest.post_reason('Got wrong subclasses for feature 1.') - return 'fail' + assert feat.GetField('SubClasses') == 'AcDbEntity:AcDbBlockReference', \ + 'Got wrong subclasses for feature 1.' - if ogrtest.check_feature_geometry(feat, 'MULTILINESTRING ((200 100,201 101),(201 100,200 101))'): - print('Feature 1') - return 'fail' + assert not ogrtest.check_feature_geometry(feat, 'MULTILINESTRING ((200 100,201 101),(201 100,200 101))'), \ + 'Feature 1' # Check 2nd feature. feat = lyr.GetNextFeature() - if feat.GetField('SubClasses') != 'AcDbEntity:AcDbPoint': - gdaltest.post_reason('Got wrong subclasses for feature 2.') - return 'fail' + assert feat.GetField('SubClasses') == 'AcDbEntity:AcDbPoint', \ + 'Got wrong subclasses for feature 2.' - if ogrtest.check_feature_geometry(feat, 'POINT (300 50)'): - print('Feature 2') - return 'fail' + assert not ogrtest.check_feature_geometry(feat, 'POINT (300 50)'), 'Feature 2' # Check 3rd feature. feat = lyr.GetNextFeature() - if feat.GetField('SubClasses') != 'AcDbEntity:AcDbBlockReference': - gdaltest.post_reason('Got wrong subclasses for feature 3.') - return 'fail' + assert feat.GetField('SubClasses') == 'AcDbEntity:AcDbBlockReference', \ + 'Got wrong subclasses for feature 3.' - if ogrtest.check_feature_geometry(feat, 'MULTILINESTRING ((249.971852502328943 201.04145741382942 0,250.619244948763452 198.930395088499495 0),(250.619244948763452 198.930395088499495 0,249.042985079183779 200.47850746040811 0),(249.042985079183779 200.47850746040811 0,251.04145741382942 200.365917469723854 0),(251.04145741382942 200.365917469723854 0,249.52149253959189 198.95854258617058 0),(249.52149253959189 198.95854258617058 0,249.943705004657858 201.013309916158363 0))'): - print('Feature 3') - return 'fail' + assert not ogrtest.check_feature_geometry(feat, 'MULTILINESTRING ((249.971852502328943 201.04145741382942 0,250.619244948763452 198.930395088499495 0),(250.619244948763452 198.930395088499495 0,249.042985079183779 200.47850746040811 0),(249.042985079183779 200.47850746040811 0,251.04145741382942 200.365917469723854 0),(251.04145741382942 200.365917469723854 0,249.52149253959189 198.95854258617058 0),(249.52149253959189 198.95854258617058 0,249.943705004657858 201.013309916158363 0))'), \ + 'Feature 3' # Check 4th feature (scaled and rotated) feat = lyr.GetNextFeature() - if feat.GetField('SubClasses') != 'AcDbEntity:AcDbBlockReference': - gdaltest.post_reason('Got wrong subclasses for feature 4.') - return 'fail' + assert feat.GetField('SubClasses') == 'AcDbEntity:AcDbBlockReference', \ + 'Got wrong subclasses for feature 4.' - if ogrtest.check_feature_geometry(feat, 'MULTILINESTRING ((300 100,300.964101615137736 106.330127018922198), (303.464101615137736 102.0,297.5 104.330127018922198))'): - print('Feature 4') - return 'fail' + assert not ogrtest.check_feature_geometry(feat, 'MULTILINESTRING ((300 100,300.964101615137736 106.330127018922198), (303.464101615137736 102.0,297.5 104.330127018922198))'), \ + 'Feature 4' # Check 5th feature feat = lyr.GetNextFeature() - if ogrtest.check_feature_geometry(feat, 'MULTIPOLYGON (((360 110,360 120,370 120,370 110,360 110)),((360 90,360 80,370 80,370 90,360 90)))'): - print('Feature 5') - return 'fail' + assert not ogrtest.check_feature_geometry(feat, 'MULTIPOLYGON (((360 110,360 120,370 120,370 110,360 110)),((360 90,360 80,370 80,370 90,360 90)))'), \ + 'Feature 5' # Check 6th feature feat = lyr.GetNextFeature() - if ogrtest.check_feature_geometry(feat, 'GEOMETRYCOLLECTION (POINT (401 102),LINESTRING (400 100,401 101))'): - print('Feature 5') - return 'fail' + assert not ogrtest.check_feature_geometry(feat, 'GEOMETRYCOLLECTION (POINT (401 102),LINESTRING (400 100,401 101))'), \ + 'Feature 5' # Cleanup @@ -960,14 +800,12 @@ def ogr_dxf_17(): os.unlink('tmp/dxf_17.dxf') - return 'success' - ############################################################################### # Write a file with line patterns, and make sure corresponding Linetypes are # created. -def ogr_dxf_18(): +def test_ogr_dxf_18(): ds = ogr.GetDriverByName('DXF').CreateDataSource('tmp/dxf_18.dxf', ['HEADER=data/header_extended.dxf']) @@ -1016,68 +854,45 @@ def ogr_dxf_18(): # Check first feature. feat = lyr.GetNextFeature() - if feat.GetField('Linetype') != 'DASHED': - gdaltest.post_reason('Got wrong linetype. (1)') - return 'fail' + assert feat.GetField('Linetype') == 'DASHED', 'Got wrong linetype. (1)' - if feat.GetStyleString() != 'PEN(c:#ffff00,w:2g,p:"12.7g 6.1234567892g")': - print(feat.GetStyleString()) - gdaltest.post_reason("got wrong style string (1)") - return 'fail' + assert feat.GetStyleString() == 'PEN(c:#ffff00,w:2g,p:"12.7g 6.1234567892g")', \ + "got wrong style string (1)" - if ogrtest.check_feature_geometry(feat, 'LINESTRING (0 0,25 25)'): - return 'fail' + assert not ogrtest.check_feature_geometry(feat, 'LINESTRING (0 0,25 25)') # Check second feature. feat = lyr.GetNextFeature() - if feat.GetField('Linetype') != 'DOTTED': - gdaltest.post_reason('Got wrong linetype. (2)') - return 'fail' + assert feat.GetField('Linetype') == 'DOTTED', 'Got wrong linetype. (2)' - if feat.GetStyleString() != 'PEN(c:#ffff00,w:2g,p:"0g 4g")': - print(feat.GetStyleString()) - gdaltest.post_reason("got wrong style string (2)") - return 'fail' + assert feat.GetStyleString() == 'PEN(c:#ffff00,w:2g,p:"0g 4g")', \ + "got wrong style string (2)" - if ogrtest.check_feature_geometry(feat, 'LINESTRING (5 5,30 30)'): - return 'fail' + assert not ogrtest.check_feature_geometry(feat, 'LINESTRING (5 5,30 30)') # Check third feature. feat = lyr.GetNextFeature() - if feat.GetField('Linetype') != 'AutoLineType-1': - gdaltest.post_reason('Got wrong linetype. (3)') - return 'fail' + assert feat.GetField('Linetype') == 'AutoLineType-1', 'Got wrong linetype. (3)' - if feat.GetStyleString() != 'PEN(c:#ffff00,w:2g,p:"3g 4g")': - print(feat.GetStyleString()) - gdaltest.post_reason("got wrong style string (3)") - return 'fail' + assert feat.GetStyleString() == 'PEN(c:#ffff00,w:2g,p:"3g 4g")', \ + "got wrong style string (3)" - if ogrtest.check_feature_geometry(feat, 'LINESTRING (5 5,40 30)'): - return 'fail' + assert not ogrtest.check_feature_geometry(feat, 'LINESTRING (5 5,40 30)') # Check fourth feature. feat = lyr.GetNextFeature() - if feat.GetField('Linetype') != 'DASHED': - gdaltest.post_reason('Got wrong linetype. (4)') - return 'fail' + assert feat.GetField('Linetype') == 'DASHED', 'Got wrong linetype. (4)' # TODO why did the lineweight go AWOL here? - if feat.GetStyleString() != 'PEN(c:#ffff00,p:"6.35g 3.0617283946g")': - print(feat.GetStyleString()) - gdaltest.post_reason("got wrong style string (4)") - return 'fail' + assert feat.GetStyleString() == 'PEN(c:#ffff00,p:"6.35g 3.0617283946g")', \ + "got wrong style string (4)" # Check fifth feature. feat = lyr.GetNextFeature() - if feat.GetField('Linetype') != 'AutoLineType-1': - gdaltest.post_reason('Got wrong linetype. (5)') - return 'fail' + assert feat.GetField('Linetype') == 'AutoLineType-1', 'Got wrong linetype. (5)' - if feat.GetStyleString() != 'PEN(c:#ffff00,w:0.01g,p:"6g 8g")': - print(feat.GetStyleString()) - gdaltest.post_reason("got wrong style string (5)") - return 'fail' + assert feat.GetStyleString() == 'PEN(c:#ffff00,w:0.01g,p:"6g 8g")', \ + "got wrong style string (5)" # Cleanup @@ -1086,14 +901,12 @@ def ogr_dxf_18(): os.unlink('tmp/dxf_18.dxf') - return 'success' - ############################################################################### # Test writing a file using references to blocks defined entirely in the # template - no blocks layer transferred. -def ogr_dxf_19(): +def test_ogr_dxf_19(): ds = ogr.GetDriverByName('DXF').CreateDataSource('tmp/dxf_19.dxf', ['HEADER=data/header_extended.dxf']) @@ -1117,12 +930,10 @@ def ogr_dxf_19(): # Check first feature. feat = lyr.GetNextFeature() - if feat.GetField('SubClasses') != 'AcDbEntity:AcDbBlockReference': - gdaltest.post_reason('Got wrong subclasses for feature 1.') - return 'fail' + assert feat.GetField('SubClasses') == 'AcDbEntity:AcDbBlockReference', \ + 'Got wrong subclasses for feature 1.' - if ogrtest.check_feature_geometry(feat, 'MULTILINESTRING ((249.971852502328943 201.04145741382942 0,250.619244948763452 198.930395088499495 0),(250.619244948763452 198.930395088499495 0,249.042985079183779 200.47850746040811 0),(249.042985079183779 200.47850746040811 0,251.04145741382942 200.365917469723854 0),(251.04145741382942 200.365917469723854 0,249.52149253959189 198.95854258617058 0),(249.52149253959189 198.95854258617058 0,249.943705004657858 201.013309916158363 0))'): - return 'fail' + assert not ogrtest.check_feature_geometry(feat, 'MULTILINESTRING ((249.971852502328943 201.04145741382942 0,250.619244948763452 198.930395088499495 0),(250.619244948763452 198.930395088499495 0,249.042985079183779 200.47850746040811 0),(249.042985079183779 200.47850746040811 0,251.04145741382942 200.365917469723854 0),(251.04145741382942 200.365917469723854 0,249.52149253959189 198.95854258617058 0),(249.52149253959189 198.95854258617058 0,249.943705004657858 201.013309916158363 0))') # Cleanup @@ -1131,47 +942,39 @@ def ogr_dxf_19(): os.unlink('tmp/dxf_19.dxf') - return 'success' - ############################################################################### # SPLINE -def ogr_dxf_20(): +def test_ogr_dxf_20(): ds = ogr.Open('data/spline_qcad.dxf') lyr = ds.GetLayer(0) feat = lyr.GetNextFeature() - if ogrtest.check_feature_geometry(feat, 'LINESTRING (10.75 62.75,20.637752769146068 63.434832501489716,29.283239084385464 63.396838394381845,36.766943814562865 62.711565975596599,43.169351828522906 61.454563542054103,48.570947995110252 59.70137939067456,53.05221718316956 57.527561818378146,56.693644261545501 55.008659122085049,59.575714099082703 52.220219598715438,61.778911564625851 49.237791545189509,63.383721527019588 46.136923258427423,64.470628855108572 42.993163035349369,65.120118417737459 39.882059172875508,65.412419131869868 36.878358785215056,65.417809785093752 34.025663008687722,65.193643595004147 31.327113252708507,64.796409941597645 28.783146935042897,64.282598204870823 26.394201473456341,63.708697764820236 24.16071428571431,63.131198001442392 22.083122789582241,62.606588294733939 20.161864402825621,62.191358024691354 18.397376543209894,61.941996571311265 16.790096628500525,61.914993314590184 15.340462076462975,62.166837634524704 14.0489103048627,62.754018911111373 12.915878731465167,63.723652286703427 11.940700981548817,65.053571428571416 11.114552964042769,66.690557841792398 10.424954275262921,68.581246558980226 9.859407264767562,70.672272612748785 9.405414282114966,72.910271035711943 9.050477676863418,75.241876860483572 8.782099798571203,77.613725119677511 8.587782996796603,79.97245084590763 8.4550296210979,82.264689071787842 8.371342021033378,84.437074829931987 8.324222546161321,86.436243152953921 8.301173546040012,88.208926721776336 8.289771106365336,89.722559658784164 8.293223374005688,90.990763736417563 8.349615688917151,92.033410218878885 8.501752503862612,92.870370370370395 8.792438271604945,93.521515455094473 9.264477444907039,94.006716737253413 9.960674476531764,94.345845481049565 10.923833819242011,94.558772950685281 12.196759925800654,94.665370410362868 13.82225724897058,94.685509124284636 15.843130241514663,94.639060356652948 18.302183356195791,94.545895371670113 21.242221045776841,94.421471763308503 24.702030018356666,94.215205541358216 28.660279617432039,93.825673773330607 33.049360720184715,93.15014577259474 37.800473760933045,92.085890852519697 42.844819173995376,90.530178326474584 48.113597393690064,88.380277507828495 53.538008854335445,85.533457709950525 59.049253990249873,81.886988246209697 64.578533235751706,77.338138429975174 70.057047025159264,71.784177574615995 75.415995792790937,65.122374993501282 80.586579972965055,57.25 85.5)'): - return 'fail' + assert not ogrtest.check_feature_geometry(feat, 'LINESTRING (10.75 62.75,20.637752769146068 63.434832501489716,29.283239084385464 63.396838394381845,36.766943814562865 62.711565975596599,43.169351828522906 61.454563542054103,48.570947995110252 59.70137939067456,53.05221718316956 57.527561818378146,56.693644261545501 55.008659122085049,59.575714099082703 52.220219598715438,61.778911564625851 49.237791545189509,63.383721527019588 46.136923258427423,64.470628855108572 42.993163035349369,65.120118417737459 39.882059172875508,65.412419131869868 36.878358785215056,65.417809785093752 34.025663008687722,65.193643595004147 31.327113252708507,64.796409941597645 28.783146935042897,64.282598204870823 26.394201473456341,63.708697764820236 24.16071428571431,63.131198001442392 22.083122789582241,62.606588294733939 20.161864402825621,62.191358024691354 18.397376543209894,61.941996571311265 16.790096628500525,61.914993314590184 15.340462076462975,62.166837634524704 14.0489103048627,62.754018911111373 12.915878731465167,63.723652286703427 11.940700981548817,65.053571428571416 11.114552964042769,66.690557841792398 10.424954275262921,68.581246558980226 9.859407264767562,70.672272612748785 9.405414282114966,72.910271035711943 9.050477676863418,75.241876860483572 8.782099798571203,77.613725119677511 8.587782996796603,79.97245084590763 8.4550296210979,82.264689071787842 8.371342021033378,84.437074829931987 8.324222546161321,86.436243152953921 8.301173546040012,88.208926721776336 8.289771106365336,89.722559658784164 8.293223374005688,90.990763736417563 8.349615688917151,92.033410218878885 8.501752503862612,92.870370370370395 8.792438271604945,93.521515455094473 9.264477444907039,94.006716737253413 9.960674476531764,94.345845481049565 10.923833819242011,94.558772950685281 12.196759925800654,94.665370410362868 13.82225724897058,94.685509124284636 15.843130241514663,94.639060356652948 18.302183356195791,94.545895371670113 21.242221045776841,94.421471763308503 24.702030018356666,94.215205541358216 28.660279617432039,93.825673773330607 33.049360720184715,93.15014577259474 37.800473760933045,92.085890852519697 42.844819173995376,90.530178326474584 48.113597393690064,88.380277507828495 53.538008854335445,85.533457709950525 59.049253990249873,81.886988246209697 64.578533235751706,77.338138429975174 70.057047025159264,71.784177574615995 75.415995792790937,65.122374993501282 80.586579972965055,57.25 85.5)') ds = None - return 'success' - ############################################################################### # CIRCLE -def ogr_dxf_21(): +def test_ogr_dxf_21(): ds = ogr.Open('data/circle.dxf') lyr = ds.GetLayer(0) feat = lyr.GetNextFeature() - if ogrtest.check_feature_geometry(feat, 'LINESTRING (5 2 3,4.990256201039297 1.720974105023499 3,4.961072274966281 1.443307596159738 3,4.912590402935223 1.168353236728963 3,4.845046783753276 0.897450576732003 3,4.758770483143634 0.631919426697325 3,4.654181830570403 0.373053427696799 3,4.531790371435708 0.122113748856437 3,4.392192384625703 -0.11967705693282 3,4.23606797749979 -0.351141009169893 3,4.064177772475912 -0.571150438746157 3,3.877359201354605 -0.778633481835989 3,3.676522425435433 -0.972579301909577 3,3.462645901302633 -1.152043014426888 3,3.236771613882987 -1.316150290220167 3,3.0 -1.464101615137754 3,2.75348458715631 -1.595176185196668 3,2.498426373663648 -1.70873541826715 3,2.23606797749979 -1.804226065180614 3,1.967687582398672 -1.881182905103986 3,1.694592710667722 -1.939231012048832 3,1.418113853070614 -1.978087581473093 3,1.139597986810004 -1.997563308076383 3,0.860402013189997 -1.997563308076383 3,0.581886146929387 -1.978087581473094 3,0.305407289332279 -1.939231012048832 3,0.032312417601329 -1.881182905103986 3,-0.236067977499789 -1.804226065180615 3,-0.498426373663648 -1.70873541826715 3,-0.75348458715631 -1.595176185196668 3,-1.0 -1.464101615137755 3,-1.236771613882987 -1.316150290220167 3,-1.462645901302633 -1.152043014426888 3,-1.676522425435433 -0.972579301909577 3,-1.877359201354605 -0.778633481835989 3,-2.064177772475912 -0.571150438746158 3,-2.236067977499789 -0.351141009169893 3,-2.392192384625704 -0.11967705693282 3,-2.531790371435707 0.122113748856436 3,-2.654181830570403 0.373053427696798 3,-2.758770483143633 0.631919426697324 3,-2.845046783753275 0.897450576732001 3,-2.912590402935223 1.168353236728963 3,-2.961072274966281 1.443307596159737 3,-2.990256201039297 1.720974105023498 3,-3.0 2.0 3,-2.990256201039297 2.279025894976499 3,-2.961072274966281 2.556692403840262 3,-2.912590402935223 2.831646763271036 3,-2.845046783753276 3.102549423267996 3,-2.758770483143634 3.368080573302675 3,-2.654181830570404 3.626946572303199 3,-2.531790371435708 3.877886251143563 3,-2.392192384625704 4.119677056932819 3,-2.23606797749979 4.351141009169892 3,-2.064177772475912 4.571150438746157 3,-1.877359201354604 4.778633481835989 3,-1.676522425435434 4.972579301909576 3,-1.462645901302632 5.152043014426889 3,-1.236771613882989 5.316150290220166 3,-1.0 5.464101615137753 3,-0.753484587156311 5.595176185196667 3,-0.498426373663649 5.70873541826715 3,-0.23606797749979 5.804226065180615 3,0.032312417601329 5.881182905103985 3,0.305407289332279 5.939231012048833 3,0.581886146929387 5.978087581473094 3,0.860402013189993 5.997563308076383 3,1.139597986810005 5.997563308076383 3,1.418113853070612 5.978087581473094 3,1.69459271066772 5.939231012048833 3,1.96768758239867 5.881182905103986 3,2.236067977499789 5.804226065180615 3,2.498426373663648 5.70873541826715 3,2.75348458715631 5.595176185196668 3,3.0 5.464101615137754 3,3.236771613882985 5.316150290220168 3,3.462645901302634 5.152043014426887 3,3.676522425435431 4.972579301909578 3,3.877359201354603 4.778633481835991 3,4.064177772475912 4.571150438746159 3,4.23606797749979 4.351141009169893 3,4.392192384625702 4.119677056932823 3,4.531790371435708 3.877886251143563 3,4.654181830570404 3.626946572303201 3,4.758770483143634 3.368080573302675 3,4.845046783753275 3.102549423267999 3,4.912590402935223 2.831646763271039 3,4.961072274966281 2.556692403840263 3,4.990256201039298 2.279025894976499 3,5.0 2.0 3)'): - return 'fail' + assert not ogrtest.check_feature_geometry(feat, 'LINESTRING (5 2 3,4.990256201039297 1.720974105023499 3,4.961072274966281 1.443307596159738 3,4.912590402935223 1.168353236728963 3,4.845046783753276 0.897450576732003 3,4.758770483143634 0.631919426697325 3,4.654181830570403 0.373053427696799 3,4.531790371435708 0.122113748856437 3,4.392192384625703 -0.11967705693282 3,4.23606797749979 -0.351141009169893 3,4.064177772475912 -0.571150438746157 3,3.877359201354605 -0.778633481835989 3,3.676522425435433 -0.972579301909577 3,3.462645901302633 -1.152043014426888 3,3.236771613882987 -1.316150290220167 3,3.0 -1.464101615137754 3,2.75348458715631 -1.595176185196668 3,2.498426373663648 -1.70873541826715 3,2.23606797749979 -1.804226065180614 3,1.967687582398672 -1.881182905103986 3,1.694592710667722 -1.939231012048832 3,1.418113853070614 -1.978087581473093 3,1.139597986810004 -1.997563308076383 3,0.860402013189997 -1.997563308076383 3,0.581886146929387 -1.978087581473094 3,0.305407289332279 -1.939231012048832 3,0.032312417601329 -1.881182905103986 3,-0.236067977499789 -1.804226065180615 3,-0.498426373663648 -1.70873541826715 3,-0.75348458715631 -1.595176185196668 3,-1.0 -1.464101615137755 3,-1.236771613882987 -1.316150290220167 3,-1.462645901302633 -1.152043014426888 3,-1.676522425435433 -0.972579301909577 3,-1.877359201354605 -0.778633481835989 3,-2.064177772475912 -0.571150438746158 3,-2.236067977499789 -0.351141009169893 3,-2.392192384625704 -0.11967705693282 3,-2.531790371435707 0.122113748856436 3,-2.654181830570403 0.373053427696798 3,-2.758770483143633 0.631919426697324 3,-2.845046783753275 0.897450576732001 3,-2.912590402935223 1.168353236728963 3,-2.961072274966281 1.443307596159737 3,-2.990256201039297 1.720974105023498 3,-3.0 2.0 3,-2.990256201039297 2.279025894976499 3,-2.961072274966281 2.556692403840262 3,-2.912590402935223 2.831646763271036 3,-2.845046783753276 3.102549423267996 3,-2.758770483143634 3.368080573302675 3,-2.654181830570404 3.626946572303199 3,-2.531790371435708 3.877886251143563 3,-2.392192384625704 4.119677056932819 3,-2.23606797749979 4.351141009169892 3,-2.064177772475912 4.571150438746157 3,-1.877359201354604 4.778633481835989 3,-1.676522425435434 4.972579301909576 3,-1.462645901302632 5.152043014426889 3,-1.236771613882989 5.316150290220166 3,-1.0 5.464101615137753 3,-0.753484587156311 5.595176185196667 3,-0.498426373663649 5.70873541826715 3,-0.23606797749979 5.804226065180615 3,0.032312417601329 5.881182905103985 3,0.305407289332279 5.939231012048833 3,0.581886146929387 5.978087581473094 3,0.860402013189993 5.997563308076383 3,1.139597986810005 5.997563308076383 3,1.418113853070612 5.978087581473094 3,1.69459271066772 5.939231012048833 3,1.96768758239867 5.881182905103986 3,2.236067977499789 5.804226065180615 3,2.498426373663648 5.70873541826715 3,2.75348458715631 5.595176185196668 3,3.0 5.464101615137754 3,3.236771613882985 5.316150290220168 3,3.462645901302634 5.152043014426887 3,3.676522425435431 4.972579301909578 3,3.877359201354603 4.778633481835991 3,4.064177772475912 4.571150438746159 3,4.23606797749979 4.351141009169893 3,4.392192384625702 4.119677056932823 3,4.531790371435708 3.877886251143563 3,4.654181830570404 3.626946572303201 3,4.758770483143634 3.368080573302675 3,4.845046783753275 3.102549423267999 3,4.912590402935223 2.831646763271039 3,4.961072274966281 2.556692403840263 3,4.990256201039298 2.279025894976499 3,5.0 2.0 3)') ds = None - return 'success' - ############################################################################### # TEXT -def ogr_dxf_22(): +def test_ogr_dxf_22(): # Read MTEXT feature ds = ogr.Open('data/text.dxf') @@ -1185,19 +988,16 @@ def ogr_dxf_22(): feat = lyr.GetNextFeature() if feat.GetFieldAsString('Text') != test_text: - gdaltest.post_reason('bad attribute') feat.DumpReadable() - return 'fail' + pytest.fail('bad attribute') style = feat.GetStyleString() if style != 'LABEL(f:"SwissCheese",bo:1,t:"' + test_text + '",a:45,s:10g,w:51,c:#ff0000)': - gdaltest.post_reason('bad style') feat.DumpReadable() print(style) - return 'fail' + pytest.fail('bad style') if ogrtest.check_feature_geometry(feat, 'POINT(1 2 3)'): - gdaltest.post_reason('bad geometry') feat.DumpReadable() - return 'fail' + pytest.fail('bad geometry') # Write text feature out_ds = ogr.GetDriverByName('DXF').CreateDataSource('/vsimem/ogr_dxf_22.dxf') @@ -1218,19 +1018,16 @@ def ogr_dxf_22(): feat = lyr.GetNextFeature() if feat.GetFieldAsString('Text') != test_text: - gdaltest.post_reason('bad attribute') feat.DumpReadable() - return 'fail' + pytest.fail('bad attribute') style = feat.GetStyleString() if style != 'LABEL(f:"SwissCheese",bo:1,t:"' + test_text + '",a:45,s:10g,w:51,c:#ff0000)': - gdaltest.post_reason('bad style') feat.DumpReadable() print(style) - return 'fail' + pytest.fail('bad style') if ogrtest.check_feature_geometry(feat, 'POINT(1 2 3)'): - gdaltest.post_reason('bad geometry') feat.DumpReadable() - return 'fail' + pytest.fail('bad geometry') ds = None @@ -1244,19 +1041,16 @@ def ogr_dxf_22(): feat = lyr.GetNextFeature() if feat.GetFieldAsString('Text') != '\A1;test^Itext\~\pt0.2;{\H0.7x;\Sab\/c\~d%%p^ ef\^ g.h\#i;} j{\L\Ok\ol}m': - gdaltest.post_reason('bad attribute with DXF_TRANSLATE_ESCAPE_SEQUENCES = FALSE') feat.DumpReadable() - return 'fail' + pytest.fail('bad attribute with DXF_TRANSLATE_ESCAPE_SEQUENCES = FALSE') ds = None - return 'success' - ############################################################################### # POLYGON with hole -def ogr_dxf_23(): +def test_ogr_dxf_23(): # Write polygon out_ds = ogr.GetDriverByName('DXF').CreateDataSource('/vsimem/ogr_dxf_23.dxf') @@ -1278,25 +1072,18 @@ def ogr_dxf_23(): feat = lyr.GetNextFeature() style = feat.GetStyleString() - if style != 'BRUSH(fc:#ff0000)': - gdaltest.post_reason('bad style') - print(style) - return 'fail' - if ogrtest.check_feature_geometry(feat, wkt): - gdaltest.post_reason('bad geometry') - return 'fail' + assert style == 'BRUSH(fc:#ff0000)', 'bad style' + assert not ogrtest.check_feature_geometry(feat, wkt), 'bad geometry' ds = None gdal.Unlink('/vsimem/ogr_dxf_23.dxf') - return 'success' - ############################################################################### # HATCH -def ogr_dxf_24(): +def test_ogr_dxf_24(): ds = ogr.Open('data/hatch.dxf') lyr = ds.GetLayer(0) @@ -1304,27 +1091,22 @@ def ogr_dxf_24(): gdal.SetConfigOption('OGR_ARC_STEPSIZE', '45') feat = lyr.GetNextFeature() gdal.SetConfigOption('OGR_ARC_STEPSIZE', None) - if ogrtest.check_feature_geometry(feat, 'POLYGON ((2 1,1.646446609406726 0.853553390593274,1.5 0.5,1.646446609406726 0.146446609406726,2 0,2.0 0.0,2.146446609406726 -0.353553390593274,2.5 -0.5,2.853553390593274 -0.353553390593274,3.0 -0.0,3 0,3.353553390593274 0.146446609406726,3.5 0.5,3.353553390593274 0.853553390593273,3 1,2.853553390593274 1.353553390593274,2.5 1.5,2.146446609406726 1.353553390593274,2 1))'): - return 'fail' + assert not ogrtest.check_feature_geometry(feat, 'POLYGON ((2 1,1.646446609406726 0.853553390593274,1.5 0.5,1.646446609406726 0.146446609406726,2 0,2.0 0.0,2.146446609406726 -0.353553390593274,2.5 -0.5,2.853553390593274 -0.353553390593274,3.0 -0.0,3 0,3.353553390593274 0.146446609406726,3.5 0.5,3.353553390593274 0.853553390593273,3 1,2.853553390593274 1.353553390593274,2.5 1.5,2.146446609406726 1.353553390593274,2 1))') gdal.SetConfigOption('OGR_ARC_STEPSIZE', '45') feat = lyr.GetNextFeature() gdal.SetConfigOption('OGR_ARC_STEPSIZE', None) - if ogrtest.check_feature_geometry(feat, 'POLYGON ((0.0 0.0 0,-0.353553390593274 0.146446609406726 0,-0.5 0.5 0,-0.353553390593274 0.853553390593274 0,-0.0 1.0 0,0.0 1.0 0,0.146446609406726 1.353553390593274 0,0.5 1.5 0,0.853553390593274 1.353553390593274 0,1.0 1.0 0,1.0 1.0 0,1.353553390593274 0.853553390593274 0,1.5 0.5 0,1.353553390593274 0.146446609406727 0,1.0 0.0 0,1 0 0,0.853553390593274 -0.353553390593274 0,0.5 -0.5 0,0.146446609406726 -0.353553390593274 0,0.0 -0.0 0,0.0 0.0 0))'): - return 'fail' + assert not ogrtest.check_feature_geometry(feat, 'POLYGON ((0.0 0.0 0,-0.353553390593274 0.146446609406726 0,-0.5 0.5 0,-0.353553390593274 0.853553390593274 0,-0.0 1.0 0,0.0 1.0 0,0.146446609406726 1.353553390593274 0,0.5 1.5 0,0.853553390593274 1.353553390593274 0,1.0 1.0 0,1.0 1.0 0,1.353553390593274 0.853553390593274 0,1.5 0.5 0,1.353553390593274 0.146446609406727 0,1.0 0.0 0,1 0 0,0.853553390593274 -0.353553390593274 0,0.5 -0.5 0,0.146446609406726 -0.353553390593274 0,0.0 -0.0 0,0.0 0.0 0))') feat = lyr.GetNextFeature() - if ogrtest.check_feature_geometry(feat, 'POLYGON ((-1 -1,-1 0,0 0,-1 -1))'): - return 'fail' + assert not ogrtest.check_feature_geometry(feat, 'POLYGON ((-1 -1,-1 0,0 0,-1 -1))') ds = None - return 'success' - ############################################################################### # 3DFACE -def ogr_dxf_25(): +def test_ogr_dxf_25(): ds = ogr.Open('data/3dface.dxf') lyr = ds.GetLayer(0) @@ -1332,22 +1114,20 @@ def ogr_dxf_25(): feat = lyr.GetNextFeature() if ogrtest.check_feature_geometry(feat, 'POLYGON ((10 20 30,11 21 31,12 22 32,10 20 30))'): feat.DumpReadable() - return 'fail' + pytest.fail() feat = lyr.GetNextFeature() if ogrtest.check_feature_geometry(feat, 'POLYGON ((10 20 30,11 21 31,12 22 32,13 23 33,10 20 30))'): feat.DumpReadable() - return 'fail' + pytest.fail() ds = None - return 'success' - ############################################################################### # SOLID (#5380) -def ogr_dxf_26(): +def test_ogr_dxf_26(): ds = ogr.Open('data/solid.dxf') lyr = ds.GetLayer(0) @@ -1355,33 +1135,28 @@ def ogr_dxf_26(): feat = lyr.GetNextFeature() if ogrtest.check_feature_geometry(feat, 'POLYGON ((2.716846 2.762514,2.393674 1.647962,4.391042 1.06881,4.714214 2.183362,2.716846 2.762514))'): feat.DumpReadable() - return 'fail' + pytest.fail() ds = None - return 'success' - ############################################################################### # Test reading a DXF file without .dxf extensions (#5994) -def ogr_dxf_27(): +def test_ogr_dxf_27(): gdal.FileFromMemBuffer('/vsimem/a_dxf_without_extension', open('data/solid.dxf').read()) ds = ogr.Open('/vsimem/a_dxf_without_extension') - if ds is None: - return 'fail' + assert ds is not None gdal.Unlink('/vsimem/a_dxf_without_extension') - return 'success' - ############################################################################### # Test reading a ELLIPSE with Z extrusion axis value of -1.0 (#5075) -def ogr_dxf_28(): +def test_ogr_dxf_28(): ds = ogr.Open('data/ellipse_z_extrusion_minus_1.dxf') lyr = ds.GetLayer(0) @@ -1389,22 +1164,20 @@ def ogr_dxf_28(): feat = lyr.GetNextFeature() if ogrtest.check_feature_geometry(feat, 'LINESTRING Z (247.379588068074 525.677518653024 0,247.560245171261 525.685592896308 0,247.739941456101 525.705876573267 0,247.917852718752 525.738276649788 0,248.09316294264 525.782644518081 0,248.265068041245 525.838776678293 0,248.432779546163 525.90641567189 0,248.595528223532 525.985251262527 0,248.752567602242 526.074921858996 0,248.903177397731 526.175016173715 0,249.046666815684 526.285075109164 0,249.182377720457 526.404593863601 0,249.309687653722 526.533024246411 0,249.428012689458 526.669777192466 0,249.536810112221 526.814225463957 0,249.635580906384 526.965706527318 0,249.723872044951 527.123525592032 0)'): feat.DumpReadable() - return 'fail' + pytest.fail() feat = lyr.GetNextFeature() if ogrtest.check_feature_geometry(feat, 'LINESTRING Z (290.988651614349 531.01336644407 0,290.900681473157 531.171364661134 0,290.823607338001 531.334954880971 0,290.757782720911 531.503386772611 0,290.703509536322 531.675887798031 0,290.661036716299 531.85166675552 0,290.630559068775 532.029917408641 0,290.612216384031 532.209822184155 0,290.606092793529 532.390555921946 0,290.612216384031 532.571289659737 0,290.630559068775 532.751194435252 0,290.661036716299 532.929445088373 0,290.703509536321 533.105224045862 0,290.75778272091 533.277725071282 0,290.823607338 533.446156962922 0,290.900681473156 533.60974718276 0,290.988651614348 533.767745399824 0)'): feat.DumpReadable() - return 'fail' + pytest.fail() ds = None - return 'success' - ############################################################################### # SPLINE with weights -def ogr_dxf_29(): +def test_ogr_dxf_29(): ds = ogr.Open('data/spline_weight.dxf') lyr = ds.GetLayer(0) @@ -1413,29 +1186,27 @@ def ogr_dxf_29(): feat = lyr.GetNextFeature() if ogrtest.check_feature_geometry(feat, 'LINESTRING (2 2, 2.10256409645081 2.15371131896973, 2.20512819290161 2.3066132068634, 2.307692527771 2.4578971862793, 2.41025638580322 2.6067533493042, 2.51282024383545 2.75237274169922, 2.61538457870483 2.89394640922546, 2.71794891357422 3.03066444396973, 2.82051301002502 3.16171884536743, 2.92307710647583 3.28629970550537, 3.02564096450806 3.40359783172607, 3.12820529937744 3.51280379295349, 3.23076939582825 3.61310863494873, 3.33333325386047 3.70370388031006, 3.43589782714844 3.78377938270569, 3.53846144676208 3.85252642631531, 3.64102602005005 3.90913581848145, 3.74358987808228 3.95279765129089, 3.84615445137024 3.98270392417908, 3.94871830940247 3.99804472923279, 4.05128240585327 3.99804425239563, 4.15384674072266 3.9827036857605, 4.25641107559204 3.95279765129089, 4.35897541046143 3.90913534164429, 4.46153926849365 3.85252571105957, 4.56410360336304 3.78377866744995, 4.66666793823242 3.70370292663574, 4.76923179626465 3.61310815811157, 4.87179613113403 3.51280236244202, 4.97436046600342 3.40359592437744, 5.07692432403564 3.2862982749939, 5.17948865890503 3.16171741485596, 5.28205299377441 3.03066277503967, 5.38461685180664 2.89394426345825, 5.48718070983887 2.75237035751343, 5.58974552154541 2.60675096511841, 5.69230937957764 2.45789456367493, 5.79487323760986 2.30661058425903, 5.89743757247925 2.15370845794678, 6 2)'): feat.DumpReadable() - return 'fail' + pytest.fail() # spline 261, weight(3) = 2.0 feat = lyr.GetNextFeature() if ogrtest.check_feature_geometry(feat, 'LINESTRING (2 2, 2.10976576805115 2.16451454162598, 2.23113083839417 2.34563326835632, 2.35994720458984 2.53639197349548, 2.49239826202393 2.73041176795959, 2.62522411346436 2.92225241661072, 2.75582838058472 3.10756635665894, 2.88229131698608 3.2831084728241, 3.00331926345825 3.44663000106812, 3.11815142631531 3.59672045707703, 3.2264621257782 3.73262500762939, 3.32825922966003 3.85407567024231, 3.42379808425903 3.96113181114197, 3.51351404190063 4.05405473709106, 3.59796214103699 4.13319540023804, 3.67778849601746 4.19891929626465, 3.75369834899902 4.25152969360352, 3.82645153999329 4.29121112823486, 3.89685702323914 4.31797361373901, 3.96579027175903 4.33159732818604, 4.03421020507812 4.33159732818604, 4.1031436920166 4.31797361373901, 4.17354917526245 4.29121017456055, 4.24630165100098 4.2515287399292, 4.32221221923828 4.19891929626465, 4.40203857421875 4.13319492340088, 4.48648738861084 4.05405378341675, 4.57620286941528 3.96113133430481, 4.67174291610718 3.85407471656799, 4.77353954315186 3.73262333869934, 4.88184928894043 3.59671831130981, 4.99668216705322 3.44662809371948, 5.11771011352539 3.28310608863831, 5.24417400360107 3.10756373405457, 5.37477827072144 2.92224931716919, 5.50760412216187 2.73040890693665, 5.64005517959595 2.5363883972168, 5.76887130737305 2.34562969207764, 5.89023685455322 2.16451120376587, 6 2)'): feat.DumpReadable() - return 'fail' + pytest.fail() # spline 262, weight(3) = 0.5 feat = lyr.GetNextFeature() if ogrtest.check_feature_geometry(feat, 'LINESTRING (2 2, 2.09894275665283 2.14827871322632, 2.19183802604675 2.28667020797729, 2.28029608726501 2.41674375534058, 2.36573505401611 2.53972935676575, 2.4494321346283 2.65657186508179, 2.53256177902222 2.76796913146973, 2.61621570587158 2.87439489364624, 2.70142364501953 2.97611308097839, 2.78915071487427 3.07318329811096, 2.88029623031616 3.16546249389648, 2.97567653656006 3.25260472297668, 3.07599782943726 3.33406257629395, 3.18181824684143 3.40909075737, 3.29349946975708 3.4767644405365, 3.4111499786377 3.53600478172302, 3.53456783294678 3.58562660217285, 3.66318273544312 3.62440752983093, 3.79601716995239 3.6511766910553, 3.93166828155518 3.66492199897766, 4.06833267211914 3.66492199897766, 4.20398426055908 3.65117692947388, 4.33681774139404 3.62440729141235, 4.4654335975647 3.58562660217285, 4.58885097503662 3.53600406646729, 4.70650196075439 3.47676372528076, 4.81818294525146 3.40909028053284, 4.92400360107422 3.33406162261963, 5.02432489395142 3.25260376930237, 5.11970520019531 3.16546106338501, 5.21085071563721 3.07318210601807, 5.29857730865479 2.9761118888855, 5.38378524780273 2.87439346313477, 5.46744012832642 2.76796770095825, 5.55056858062744 2.65656995773315, 5.63426637649536 2.53972721099854, 5.71970558166504 2.41674160957336, 5.8081636428833 2.2866678237915, 5.9010591506958 2.14827609062195, 6 2)'): feat.DumpReadable() - return 'fail' + pytest.fail() ds = None - return 'success' - ############################################################################### # SPLINE closed -def ogr_dxf_30(): +def test_ogr_dxf_30(): ds = ogr.Open('data/spline_closed.dxf') lyr = ds.GetLayer(0) @@ -1444,23 +1215,21 @@ def ogr_dxf_30(): feat = lyr.GetNextFeature() if ogrtest.check_feature_geometry(feat, 'LINESTRING (14 2, 13.9043273925781 2.11115527153015, 13.82310962677 2.23728489875793, 13.7564849853516 2.3759388923645, 13.7045974731445 2.52466750144958, 13.6675891876221 2.68102264404297, 13.6455984115601 2.84255337715149, 13.6387672424316 3.00681042671204, 13.6472396850586 3.17134499549866, 13.6711559295654 3.33370733261108, 13.7106552124023 3.49144792556763, 13.7658815383911 3.64211750030518, 13.8369770050049 3.78326630592346, 13.9240808486938 3.9124448299408, 14.0273275375366 4.0272102355957, 14.1460762023926 4.125901222229, 14.2781581878662 4.20836925506592, 14.4212408065796 4.27464532852173, 14.5729866027832 4.32475566864014, 14.7310619354248 4.35873079299927, 14.8931264877319 4.37659645080566, 15.056845664978 4.37838315963745, 15.2198839187622 4.36411762237549, 15.3799018859863 4.33382892608643, 15.5345678329468 4.2875452041626, 15.681544303894 4.22529458999634, 15.8184909820557 4.14710569381714, 15.9430751800537 4.05300617218018, 16.0530071258545 3.94307255744934, 16.1471080780029 3.81848883628845, 16.2252960205078 3.68154096603394, 16.2875461578369 3.53456616401672, 16.3338298797607 3.37990093231201, 16.3641166687012 3.219881772995, 16.3783836364746 3.05684399604797, 16.3765964508057 2.89312481880188, 16.3587284088135 2.73106050491333, 16.3247547149658 2.57298684120178, 16.2746448516846 2.42124080657959, 16.2083702087402 2.27815842628479, 16.1259021759033 2.146075963974, 16.0272102355957 2.02732920646667, 15.9124450683594 1.92408156394958, 15.7832660675049 1.83697760105133, 15.6421175003052 1.7658828496933, 15.4914503097534 1.71065592765808, 15.3337097167969 1.67115533351898, 15.1713457107544 1.6472395658493, 15.0068111419678 1.63876724243164, 14.8425559997559 1.64559710025787, 14.681022644043 1.66758728027344, 14.5246696472168 1.70459699630737, 14.375940322876 1.75648427009583, 14.2372856140137 1.82310783863068, 14.1111574172974 1.90432631969452, 14 2)'): feat.DumpReadable() - return 'fail' + pytest.fail() # spline 24c, closed, recalculate knots feat = lyr.GetNextFeature() if ogrtest.check_feature_geometry(feat, 'LINESTRING (14 2, 13.9043273925781 2.11115527153015, 13.82310962677 2.23728489875793, 13.7564849853516 2.3759388923645, 13.7045974731445 2.52466750144958, 13.6675891876221 2.68102264404297, 13.6455984115601 2.84255337715149, 13.6387672424316 3.00681042671204, 13.6472396850586 3.17134499549866, 13.6711559295654 3.33370733261108, 13.7106552124023 3.49144792556763, 13.7658815383911 3.64211750030518, 13.8369770050049 3.78326630592346, 13.9240808486938 3.9124448299408, 14.0273275375366 4.0272102355957, 14.1460762023926 4.125901222229, 14.2781581878662 4.20836925506592, 14.4212408065796 4.27464532852173, 14.5729866027832 4.32475566864014, 14.7310619354248 4.35873079299927, 14.8931264877319 4.37659645080566, 15.056845664978 4.37838315963745, 15.2198839187622 4.36411762237549, 15.3799018859863 4.33382892608643, 15.5345678329468 4.2875452041626, 15.681544303894 4.22529458999634, 15.8184909820557 4.14710569381714, 15.9430751800537 4.05300617218018, 16.0530071258545 3.94307255744934, 16.1471080780029 3.81848883628845, 16.2252960205078 3.68154096603394, 16.2875461578369 3.53456616401672, 16.3338298797607 3.37990093231201, 16.3641166687012 3.219881772995, 16.3783836364746 3.05684399604797, 16.3765964508057 2.89312481880188, 16.3587284088135 2.73106050491333, 16.3247547149658 2.57298684120178, 16.2746448516846 2.42124080657959, 16.2083702087402 2.27815842628479, 16.1259021759033 2.146075963974, 16.0272102355957 2.02732920646667, 15.9124450683594 1.92408156394958, 15.7832660675049 1.83697760105133, 15.6421175003052 1.7658828496933, 15.4914503097534 1.71065592765808, 15.3337097167969 1.67115533351898, 15.1713457107544 1.6472395658493, 15.0068111419678 1.63876724243164, 14.8425559997559 1.64559710025787, 14.681022644043 1.66758728027344, 14.5246696472168 1.70459699630737, 14.375940322876 1.75648427009583, 14.2372856140137 1.82310783863068, 14.1111574172974 1.90432631969452, 14 2)'): feat.DumpReadable() - return 'fail' + pytest.fail() ds = None - return 'success' - ############################################################################### # OCS2WCS transformations 1 -def ogr_dxf_31(): +def test_ogr_dxf_31(): ds = ogr.Open('data/ocs2wcs1.dxf') lyr = ds.GetLayer(0) @@ -1473,7 +1242,7 @@ def ogr_dxf_31(): feat = lyr.GetNextFeature() if ogrtest.check_feature_geometry(feat, 'POINT Z (4 4 0)'): feat.DumpReadable() - return 'fail' + pytest.fail() # OGRFeature(entities):1 # EntityHandle (String) = 1F0 @@ -1481,7 +1250,7 @@ def ogr_dxf_31(): feat = lyr.GetNextFeature() if ogrtest.check_feature_geometry(feat, 'LINESTRING Z (0 0 0,1 1 0)'): feat.DumpReadable() - return 'fail' + pytest.fail() # OGRFeature(entities):2 # EntityHandle (String) = 1F1 @@ -1489,7 +1258,7 @@ def ogr_dxf_31(): feat = lyr.GetNextFeature() if ogrtest.check_feature_geometry(feat, 'LINESTRING (1 1,2 1,1 2,1 1)'): feat.DumpReadable() - return 'fail' + pytest.fail() # OGRFeature(entities):3 # EntityHandle (String) = 1F2 @@ -1497,7 +1266,7 @@ def ogr_dxf_31(): feat = lyr.GetNextFeature() if ogrtest.check_feature_geometry(feat, 'LINESTRING Z (1 1 0,1 2 0,2 2 0,1 1 0)'): feat.DumpReadable() - return 'fail' + pytest.fail() # OGRFeature(entities):4 # EntityHandle (String) = 1F7 @@ -1505,7 +1274,7 @@ def ogr_dxf_31(): feat = lyr.GetNextFeature() if ogrtest.check_feature_geometry(feat, 'LINESTRING Z (6 4 0,5.99512810051965 3.86048705251175 0,5.98053613748314 3.72165379807987 0,5.95629520146761 3.58417661836448 0,5.92252339187664 3.448725288366 0,5.87938524157182 3.31595971334866 0,5.8270909152852 3.1865267138484 0,5.76589518571785 3.06105687442822 0,5.69609619231285 2.94016147153359 0,5.61803398874989 2.82442949541505 0,5.53208888623796 2.71442478062692 0,5.4386796006773 2.61068325908201 0,5.33826121271772 2.51371034904521 0,5.23132295065132 2.42397849278656 0,5.11838580694149 2.34192485488992 0,5.0 2.26794919243112 0,4.87674229357815 2.20241190740167 0,4.74921318683182 2.14563229086643 0,4.61803398874989 2.09788696740969 0,4.48384379119934 2.05940854744801 0,4.34729635533386 2.03038449397558 0,4.20905692653531 2.01095620926345 0,4.069798993405 2.00121834596181 0,3.930201006595 2.00121834596181 0,3.79094307346469 2.01095620926345 0,3.65270364466614 2.03038449397558 0,3.51615620880066 2.05940854744801 0,3.38196601125011 2.09788696740969 0,3.25078681316818 2.14563229086643 0,3.12325770642185 2.20241190740167 0,3.0 2.26794919243112 0,2.88161419305851 2.34192485488992 0,2.76867704934868 2.42397849278656 0,2.66173878728228 2.51371034904521 0,2.5613203993227 2.61068325908201 0,2.46791111376204 2.71442478062692 0,2.38196601125011 2.82442949541505 0,2.30390380768715 2.94016147153359 0,2.23410481428215 3.06105687442822 0,2.1729090847148 3.1865267138484 0,2.12061475842818 3.31595971334866 0,2.07747660812336 3.448725288366 0,2.04370479853239 3.58417661836448 0,2.01946386251686 3.72165379807987 0,2.00487189948035 3.86048705251175 0,2.0 4.0 0,2.00487189948035 4.13951294748825 0,2.01946386251686 4.27834620192013 0,2.04370479853239 4.41582338163552 0,2.07747660812336 4.551274711634 0,2.12061475842818 4.68404028665134 0,2.1729090847148 4.8134732861516 0,2.23410481428215 4.93894312557178 0,2.30390380768715 5.05983852846641 0,2.38196601125011 5.17557050458495 0,2.46791111376204 5.28557521937308 0,2.5613203993227 5.38931674091799 0,2.66173878728228 5.48628965095479 0,2.76867704934868 5.57602150721344 0,2.88161419305851 5.65807514511008 0,3.0 5.73205080756888 0,3.12325770642184 5.79758809259833 0,3.25078681316818 5.85436770913357 0,3.38196601125011 5.90211303259031 0,3.51615620880066 5.94059145255199 0,3.65270364466614 5.96961550602442 0,3.79094307346469 5.98904379073655 0,3.930201006595 5.99878165403819 0,4.069798993405 5.99878165403819 0,4.20905692653531 5.98904379073655 0,4.34729635533386 5.96961550602442 0,4.48384379119933 5.94059145255199 0,4.61803398874989 5.90211303259031 0,4.74921318683182 5.85436770913357 0,4.87674229357815 5.79758809259833 0,5.0 5.73205080756888 0,5.11838580694149 5.65807514511008 0,5.23132295065132 5.57602150721344 0,5.33826121271772 5.48628965095479 0,5.4386796006773 5.389316740918 0,5.53208888623796 5.28557521937308 0,5.61803398874989 5.17557050458495 0,5.69609619231285 5.05983852846641 0,5.76589518571785 4.93894312557178 0,5.8270909152852 4.8134732861516 0,5.87938524157182 4.68404028665134 0,5.92252339187664 4.551274711634 0,5.95629520146761 4.41582338163552 0,5.98053613748314 4.27834620192013 0,5.99512810051965 4.13951294748825 0,6.0 4.0 0)'): feat.DumpReadable() - return 'fail' + pytest.fail() # OGRFeature(entities):5 # EntityHandle (String) = 1F8 @@ -1513,7 +1282,7 @@ def ogr_dxf_31(): feat = lyr.GetNextFeature() if ogrtest.check_feature_geometry(feat, 'LINESTRING Z (2 4 0,2.00487189948035 4.06975647374412 0,2.01946386251686 4.13917310096007 0,2.04370479853239 4.20791169081776 0,2.07747660812336 4.275637355817 0,2.12061475842818 4.34202014332567 0,2.1729090847148 4.4067366430758 0,2.23410481428215 4.46947156278589 0,2.30390380768715 4.52991926423321 0,2.38196601125011 4.58778525229247 0,2.46791111376204 4.64278760968654 0,2.5613203993227 4.694658370459 0,2.66173878728228 4.74314482547739 0,2.76867704934868 4.78801075360672 0,2.88161419305851 4.82903757255504 0,3.0 4.86602540378444 0,3.12325770642185 4.89879404629917 0,3.25078681316818 4.92718385456679 0,3.38196601125011 4.95105651629515 0,3.51615620880067 4.970295726276 0,3.65270364466614 4.98480775301221 0,3.79094307346469 4.99452189536827 0,3.930201006595 4.9993908270191 0,4.069798993405 4.9993908270191 0,4.20905692653531 4.99452189536827 0,4.34729635533386 4.98480775301221 0,4.48384379119934 4.970295726276 0,4.61803398874989 4.95105651629515 0,4.74921318683182 4.92718385456679 0,4.87674229357816 4.89879404629917 0,5.0 4.86602540378444 0,5.11838580694149 4.82903757255504 0,5.23132295065132 4.78801075360672 0,5.33826121271772 4.74314482547739 0,5.4386796006773 4.694658370459 0,5.53208888623796 4.64278760968654 0,5.61803398874989 4.58778525229247 0,5.69609619231285 4.5299192642332 0,5.76589518571785 4.46947156278589 0,5.8270909152852 4.4067366430758 0,5.87938524157182 4.34202014332567 0,5.92252339187664 4.275637355817 0,5.95629520146761 4.20791169081776 0,5.98053613748314 4.13917310096006 0,5.99512810051965 4.06975647374412 0,6.0 4.0 0,5.99512810051965 3.93024352625587 0,5.98053613748314 3.86082689903993 0,5.95629520146761 3.79208830918224 0,5.92252339187664 3.724362644183 0,5.87938524157182 3.65797985667433 0,5.8270909152852 3.5932633569242 0,5.76589518571785 3.53052843721411 0,5.69609619231285 3.4700807357668 0,5.61803398874989 3.41221474770753 0,5.53208888623796 3.35721239031346 0,5.4386796006773 3.305341629541 0,5.33826121271772 3.25685517452261 0,5.23132295065132 3.21198924639328 0,5.11838580694149 3.17096242744496 0,5.0 3.13397459621556 0,4.87674229357815 3.10120595370083 0,4.74921318683182 3.07281614543321 0,4.61803398874989 3.04894348370485 0,4.48384379119934 3.029704273724 0,4.34729635533386 3.01519224698779 0,4.20905692653531 3.00547810463173 0,4.069798993405 3.0006091729809 0,3.930201006595 3.0006091729809 0,3.79094307346469 3.00547810463173 0,3.65270364466614 3.01519224698779 0,3.51615620880066 3.029704273724 0,3.38196601125011 3.04894348370485 0,3.25078681316818 3.07281614543321 0,3.12325770642185 3.10120595370083 0,3.0 3.13397459621556 0,2.88161419305851 3.17096242744496 0,2.76867704934868 3.21198924639328 0,2.66173878728228 3.25685517452261 0,2.5613203993227 3.305341629541 0,2.46791111376204 3.35721239031346 0,2.38196601125011 3.41221474770753 0,2.30390380768715 3.4700807357668 0,2.23410481428215 3.53052843721411 0,2.1729090847148 3.5932633569242 0,2.12061475842818 3.65797985667433 0,2.07747660812336 3.724362644183 0,2.04370479853239 3.79208830918224 0,2.01946386251686 3.86082689903993 0,2.00487189948035 3.93024352625587 0,2 4 0)'): feat.DumpReadable() - return 'fail' + pytest.fail() # OGRFeature(entities):6 # EntityHandle (String) = 1F9 @@ -1521,7 +1290,7 @@ def ogr_dxf_31(): feat = lyr.GetNextFeature() if ogrtest.check_feature_geometry(feat, 'LINESTRING Z (2.0 2.0 0,1.96657794502105 2.03582232791524 0,1.93571660708646 2.07387296203834 0,1.90756413746468 2.11396923855471 0,1.88225568337755 2.15591867344963 0,1.85991273921989 2.19951988653655 0,1.84064256332004 2.24456356819194 0,1.8245376630414 2.29083348415575 0,1.81167535069652 2.33810751357387 0,1.80211737240583 2.38615871529951 0,1.79590961168258 2.43475641733454 0,1.79308186916688 2.48366732418105 0,1.79364771956639 2.53265663678705 0,1.79760444649032 2.58148917971011 0,1.80493305548955 2.62993053008785 0,1.81559836524041 2.67774814299566 0,1.8295491764342 2.72471246778926 0,1.84671851756181 2.7705980500731 0,1.86702396641357 2.81518461400453 0,1.89036804575079 2.85825811973811 0,1.91663869124976 2.89961179093366 0,1.94570978947168 2.93904710739563 0,1.97744178327594 2.97637475807832 0,2.01168234177068 3.01141554988232 0,2.04826709158413 3.04400126787917 0,2.08702040594658 3.07397548283483 0,2.12775624779472 3.10119430215541 0,2.17027906285109 3.12552706065018 0,2.2143847183914 3.14685694779575 0,2.25986148319297 3.16508156849045 0,2.30649104396024 3.18011343460661 0,2.35404955334774 3.1918803849814 0,2.40230870454951 3.20032593182975 0,2.45103682729644 3.2054095319166 0,2.5 3.20710678118655 0,2.54896317270356 3.2054095319166 0,2.59769129545049 3.20032593182975 0,2.64595044665226 3.1918803849814 0,2.69350895603976 3.18011343460661 0,2.74013851680703 3.16508156849045 0,2.7856152816086 3.14685694779575 0,2.8297209371489 3.12552706065018 0,2.87224375220528 3.10119430215541 0,2.91297959405342 3.07397548283483 0,2.95173290841587 3.04400126787917 0,2.98831765822932 3.01141554988232 0,3.02255821672406 2.97637475807832 0,3.05429021052832 2.93904710739563 0,3.08336130875024 2.89961179093367 0,3.10963195424921 2.85825811973811 0,3.13297603358643 2.81518461400453 0,3.15328148243819 2.7705980500731 0,3.1704508235658 2.72471246778926 0,3.18440163475959 2.67774814299567 0,3.19506694451045 2.62993053008786 0,3.20239555350968 2.58148917971011 0,3.20635228043361 2.53265663678705 0,3.20691813083312 2.48366732418105 0,3.20409038831742 2.43475641733454 0,3.19788262759417 2.38615871529951 0,3.18832464930348 2.33810751357387 0,3.1754623369586 2.29083348415575 0,3.15935743667996 2.24456356819194 0,3.14008726078011 2.19951988653655 0,3.11774431662245 2.15591867344963 0,3.09243586253532 2.11396923855472 0,3.06428339291354 2.07387296203834 0,3.03342205497895 2.03582232791524 0,3 2 0)'): feat.DumpReadable() - return 'fail' + pytest.fail() # OGRFeature(entities):7 # EntityHandle (String) = 1FA @@ -1529,7 +1298,7 @@ def ogr_dxf_31(): feat = lyr.GetNextFeature() if ogrtest.check_feature_geometry(feat, 'POLYGON Z ((1 2 0,1 3 0,2 3 0,2 2 0,1 2 0))'): feat.DumpReadable() - return 'fail' + pytest.fail() # OGRFeature(entities):8 # EntityHandle (String) = 1FB @@ -1537,7 +1306,7 @@ def ogr_dxf_31(): feat = lyr.GetNextFeature() if ogrtest.check_feature_geometry(feat, 'POLYGON ((3 4,4 4,4 3,3 3,3 4))'): feat.DumpReadable() - return 'fail' + pytest.fail() # OGRFeature(entities):9 # EntityHandle (String) = 1FD @@ -1545,7 +1314,7 @@ def ogr_dxf_31(): feat = lyr.GetNextFeature() if ogrtest.check_feature_geometry(feat, 'POLYGON ((8 8,9 8,9 9,8 9,8 8))'): feat.DumpReadable() - return 'fail' + pytest.fail() # OGRFeature(entities):10 # EntityHandle (String) = 200 @@ -1553,7 +1322,7 @@ def ogr_dxf_31(): feat = lyr.GetNextFeature() if ogrtest.check_feature_geometry(feat, 'LINESTRING (2 2,2.15384615384615 2.15384615384615,2.30769230769231 2.30769230769231,2.46153846153846 2.46153846153846,2.61538461538461 2.61538461538461,2.76923076923077 2.76923076923077,2.92307692307692 2.92307692307692,3.07692307692308 3.07692307692308,3.23076923076923 3.23076923076923,3.38461538461538 3.38461538461538,3.53846153846154 3.53846153846154,3.69230769230769 3.69230769230769,3.84615384615385 3.84615384615385,4 4,4.15384615384615 4.15384615384615,4.30769230769231 4.30769230769231,4.46153846153846 4.46153846153846,4.61538461538462 4.61538461538462,4.76923076923077 4.76923076923077,4.92307692307692 4.92307692307692,5.07692307692308 5.07692307692308,5.23076923076923 5.23076923076923,5.38461538461538 5.38461538461538,5.53846153846154 5.53846153846154,5.69230769230769 5.69230769230769,5.84615384615385 5.84615384615385,6.0 6.0,6.15384615384615 6.15384615384615,6.30769230769231 6.30769230769231,6.46153846153846 6.46153846153846,6.61538461538462 6.61538461538462,6.76923076923077 6.76923076923077,6.92307692307692 6.92307692307692,7.07692307692308 7.07692307692308,7.23076923076923 7.23076923076923,7.38461538461539 7.38461538461539,7.53846153846154 7.53846153846154,7.69230769230769 7.69230769230769,7.84615384615385 7.84615384615385,8 8)'): feat.DumpReadable() - return 'fail' + pytest.fail() # OGRFeature(entities):11 # EntityHandle (String) = 201 @@ -1561,7 +1330,7 @@ def ogr_dxf_31(): feat = lyr.GetNextFeature() if ogrtest.check_feature_geometry(feat, 'LINESTRING (8 1,7.62837370825536 0.987348067229724,7.25775889681215 0.975707614760869,6.88916704597178 0.966090122894857,6.52360963603567 0.959507071933107,6.16209814730525 0.956969942177043,5.80564406008193 0.959490213928084,5.45525885466714 0.968079367487651,5.11195401136229 0.983748883157167,4.77674101046882 1.00751024123805,4.45063133228814 1.04037492203173,4.13463645712167 1.08335440583961,3.82976786527082 1.13746017296313,3.53703703703704 1.2037037037037,3.25745545272173 1.28309647836275,2.99203459262631 1.37664997724169,2.74178593705221 1.48537568064195,2.50772096630085 1.61028506886495,2.29085116067365 1.75238962221211,2.09218800047203 1.91270082098484,1.91270082098485 2.09218800047202,1.75238962221211 2.29085116067364,1.61028506886495 2.50772096630085,1.48537568064195 2.74178593705221,1.37664997724169 2.99203459262631,1.28309647836275 3.25745545272172,1.2037037037037 3.53703703703703,1.13746017296313 3.82976786527082,1.08335440583961 4.13463645712166,1.04037492203173 4.45063133228814,1.00751024123805 4.77674101046882,0.983748883157167 5.11195401136229,0.968079367487652 5.45525885466714,0.959490213928084 5.80564406008193,0.956969942177043 6.16209814730525,0.959507071933108 6.52360963603567,0.966090122894857 6.88916704597178,0.975707614760869 7.25775889681216,0.987348067229724 7.62837370825537,1 8)'): feat.DumpReadable() - return 'fail' + pytest.fail() # OGRFeature(entities):12 # EntityHandle (String) = 202 @@ -1569,7 +1338,7 @@ def ogr_dxf_31(): feat = lyr.GetNextFeature() if ogrtest.check_feature_geometry(feat, 'POINT Z (7 7 0)'): feat.DumpReadable() - return 'fail' + pytest.fail() # OGRFeature(entities):13 # EntityHandle (String) = 203 @@ -1577,7 +1346,7 @@ def ogr_dxf_31(): feat = lyr.GetNextFeature() if ogrtest.check_feature_geometry(feat, 'POINT Z (-4 4 -5e-16)'): feat.DumpReadable() - return 'fail' + pytest.fail() # OGRFeature(entities):14 # EntityHandle (String) = 204 @@ -1585,7 +1354,7 @@ def ogr_dxf_31(): feat = lyr.GetNextFeature() if ogrtest.check_feature_geometry(feat, 'LINESTRING Z (0 0 0,-1 1 -1e-16)'): feat.DumpReadable() - return 'fail' + pytest.fail() # OGRFeature(entities):15 # EntityHandle (String) = 205 @@ -1593,7 +1362,7 @@ def ogr_dxf_31(): feat = lyr.GetNextFeature() if ogrtest.check_feature_geometry(feat, 'LINESTRING (-1 1,-2 1,-1 2,-1 1)'): feat.DumpReadable() - return 'fail' + pytest.fail() # OGRFeature(entities):16 # EntityHandle (String) = 206 @@ -1601,7 +1370,7 @@ def ogr_dxf_31(): feat = lyr.GetNextFeature() if ogrtest.check_feature_geometry(feat, 'LINESTRING Z (-1 1 -1e-16,-1 2 -1e-16,-2 2 -2e-16,-1 1 -1e-16)'): feat.DumpReadable() - return 'fail' + pytest.fail() # OGRFeature(entities):17 # EntityHandle (String) = 20B @@ -1611,7 +1380,7 @@ def ogr_dxf_31(): if ogrtest.check_feature_geometry(feat, 'LINESTRING Z (-6 4 -6e-16,-5.99512810051965 3.86048705251175 -5.99512810051965e-16,-5.98053613748314 3.72165379807987 -5.98053613748314e-16,-5.95629520146761 3.58417661836448 -5.95629520146761e-16,-5.92252339187664 3.448725288366 -5.92252339187664e-16,-5.87938524157182 3.31595971334866 -5.87938524157182e-16,-5.8270909152852 3.1865267138484 -5.8270909152852e-16,-5.76589518571785 3.06105687442822 -5.76589518571785e-16,-5.69609619231285 2.94016147153359 -5.69609619231285e-16,-5.61803398874989 2.82442949541505 -5.61803398874989e-16,-5.53208888623796 2.71442478062692 -5.53208888623796e-16,-5.4386796006773 2.61068325908201 -5.4386796006773e-16,-5.33826121271772 2.51371034904521 -5.33826121271772e-16,-5.23132295065132 2.42397849278656 -5.23132295065132e-16,-5.11838580694149 2.34192485488992 -5.11838580694149e-16,-5.0 2.26794919243112 -5e-16,-4.87674229357815 2.20241190740167 -4.87674229357815e-16,-4.74921318683182 2.14563229086643 -4.74921318683182e-16,-4.61803398874989 2.09788696740969 -4.61803398874989e-16,-4.48384379119934 2.05940854744801 -4.48384379119934e-16,-4.34729635533386 2.03038449397558 -4.34729635533386e-16,-4.20905692653531 2.01095620926345 -4.20905692653531e-16,-4.069798993405 2.00121834596181 -4.069798993405e-16,-3.930201006595 2.00121834596181 -3.930201006595e-16,-3.79094307346469 2.01095620926345 -3.79094307346469e-16,-3.65270364466614 2.03038449397558 -3.65270364466614e-16,-3.51615620880066 2.05940854744801 -3.51615620880066e-16,-3.38196601125011 2.09788696740969 -3.3819660112501e-16,-3.25078681316818 2.14563229086643 -3.25078681316818e-16,-3.12325770642185 2.20241190740167 -3.12325770642185e-16,-3.0 2.26794919243112 -3e-16,-2.88161419305851 2.34192485488992 -2.88161419305851e-16,-2.76867704934868 2.42397849278656 -2.76867704934868e-16,-2.66173878728228 2.51371034904521 -2.66173878728228e-16,-2.5613203993227 2.61068325908201 -2.5613203993227e-16,-2.46791111376204 2.71442478062692 -2.46791111376204e-16,-2.38196601125011 2.82442949541505 -2.3819660112501e-16,-2.30390380768715 2.94016147153359 -2.30390380768715e-16,-2.23410481428215 3.06105687442822 -2.23410481428215e-16,-2.1729090847148 3.1865267138484 -2.1729090847148e-16,-2.12061475842818 3.31595971334866 -2.12061475842818e-16,-2.07747660812336 3.448725288366 -2.07747660812336e-16,-2.04370479853239 3.58417661836448 -2.04370479853239e-16,-2.01946386251686 3.72165379807987 -2.01946386251686e-16,-2.00487189948035 3.86048705251175 -2.00487189948035e-16,-2.0 4.0 -2e-16,-2.00487189948035 4.13951294748825 -2.00487189948035e-16,-2.01946386251686 4.27834620192013 -2.01946386251686e-16,-2.04370479853239 4.41582338163552 -2.04370479853239e-16,' + '-2.07747660812336 4.551274711634 -2.07747660812336e-16,-2.12061475842818 4.68404028665134 -2.12061475842818e-16,-2.1729090847148 4.8134732861516 -2.1729090847148e-16,-2.23410481428215 4.93894312557178 -2.23410481428215e-16,-2.30390380768715 5.05983852846641 -2.30390380768715e-16,-2.38196601125011 5.17557050458495 -2.3819660112501e-16,-2.46791111376204 5.28557521937308 -2.46791111376204e-16,-2.5613203993227 5.38931674091799 -2.5613203993227e-16,-2.66173878728228 5.48628965095479 -2.66173878728228e-16,-2.76867704934868 5.57602150721344 -2.76867704934868e-16,-2.88161419305851 5.65807514511008 -2.88161419305851e-16,-3.0 5.73205080756888 -3e-16,-3.12325770642184 5.79758809259833 -3.12325770642184e-16,-3.25078681316818 5.85436770913357 -3.25078681316817e-16,-3.38196601125011 5.90211303259031 -3.3819660112501e-16,-3.51615620880066 5.94059145255199 -3.51615620880066e-16,-3.65270364466614 5.96961550602442 -3.65270364466614e-16,-3.79094307346469 5.98904379073655 -3.79094307346469e-16,-3.930201006595 5.99878165403819 -3.930201006595e-16,-4.069798993405 5.99878165403819 -4.069798993405e-16,-4.20905692653531 5.98904379073655 -4.20905692653531e-16,-4.34729635533386 5.96961550602442 -4.34729635533386e-16,-4.48384379119933 5.94059145255199 -4.48384379119933e-16,-4.61803398874989 5.90211303259031 -4.61803398874989e-16,-4.74921318683182 5.85436770913357 -4.74921318683182e-16,-4.87674229357815 5.79758809259833 -4.87674229357815e-16,-5.0 5.73205080756888 -5e-16,-5.11838580694149 5.65807514511008 -5.11838580694149e-16,-5.23132295065132 5.57602150721344 -5.23132295065132e-16,-5.33826121271772 5.48628965095479 -5.33826121271772e-16,-5.4386796006773 5.389316740918 -5.4386796006773e-16,-5.53208888623796 5.28557521937308 -5.53208888623796e-16,-5.61803398874989 5.17557050458495 -5.61803398874989e-16,-5.69609619231285 5.05983852846641 -5.69609619231285e-16,-5.76589518571785 4.93894312557178 -5.76589518571785e-16,-5.8270909152852 4.8134732861516 -5.8270909152852e-16,-5.87938524157182 4.68404028665134 -5.87938524157182e-16,-5.92252339187664 4.551274711634 -5.92252339187664e-16,-5.95629520146761 4.41582338163552 -5.95629520146761e-16,-5.98053613748314 4.27834620192013 -5.98053613748314e-16,-5.99512810051965 4.13951294748825 -5.99512810051965e-16,-6.0 4.0 -6e-16)'): feat.DumpReadable() - return 'fail' + pytest.fail() # OGRFeature(entities):18 # EntityHandle (String) = 20C @@ -1621,7 +1390,7 @@ def ogr_dxf_31(): if ogrtest.check_feature_geometry(feat, 'LINESTRING Z (-2 4 -3e-16,-2.00487189948035 4.06975647374412 -3.00487189948035e-16,-2.01946386251686 4.13917310096007 -3.01946386251686e-16,-2.04370479853239 4.20791169081776 -3.04370479853239e-16,-2.07747660812336 4.275637355817 -3.07747660812336e-16,-2.12061475842818 4.34202014332567 -3.12061475842818e-16,-2.1729090847148 4.4067366430758 -3.1729090847148e-16,-2.23410481428215 4.46947156278589 -3.23410481428215e-16,-2.30390380768715 4.52991926423321 -3.30390380768715e-16,-2.38196601125011 4.58778525229247 -3.38196601125011e-16,-2.46791111376204 4.64278760968654 -3.46791111376204e-16,-2.5613203993227 4.694658370459 -3.5613203993227e-16,-2.66173878728228 4.74314482547739 -3.66173878728228e-16,-2.76867704934868 4.78801075360672 -3.76867704934868e-16,-2.88161419305851 4.82903757255504 -3.88161419305851e-16,-3.0 4.86602540378444 -4e-16,-3.12325770642185 4.89879404629917 -4.12325770642185e-16,-3.25078681316818 4.92718385456679 -4.25078681316818e-16,-3.38196601125011 4.95105651629515 -4.38196601125011e-16,-3.51615620880067 4.970295726276 -4.51615620880067e-16,-3.65270364466614 4.98480775301221 -4.65270364466614e-16,-3.79094307346469 4.99452189536827 -4.79094307346469e-16,-3.930201006595 4.9993908270191 -4.930201006595e-16,-4.069798993405 4.9993908270191 -5.069798993405e-16,-4.20905692653531 4.99452189536827 -5.20905692653531e-16,-4.34729635533386 4.98480775301221 -5.34729635533386e-16,-4.48384379119934 4.970295726276 -5.48384379119934e-16,-4.61803398874989 4.95105651629515 -5.6180339887499e-16,-4.74921318683182 4.92718385456679 -5.74921318683183e-16,-4.87674229357816 4.89879404629917 -5.87674229357816e-16,-5.0 4.86602540378444 -6e-16,-5.11838580694149 4.82903757255504 -6.1183858069415e-16,-5.23132295065132 4.78801075360672 -6.23132295065132e-16,-5.33826121271772 4.74314482547739 -6.33826121271772e-16,-5.4386796006773 4.694658370459 -6.4386796006773e-16,-5.53208888623796 4.64278760968654 -6.53208888623796e-16,-5.61803398874989 4.58778525229247 -6.61803398874989e-16,-5.69609619231285 4.5299192642332 -6.69609619231285e-16,-5.76589518571785 4.46947156278589 -6.76589518571785e-16,-5.8270909152852 4.4067366430758 -6.8270909152852e-16,-5.87938524157182 4.34202014332567 -6.87938524157182e-16,-5.92252339187664 4.275637355817 -6.92252339187664e-16,-5.95629520146761 4.20791169081776 -6.95629520146761e-16,-5.98053613748314 4.13917310096006 -6.98053613748314e-16,-5.99512810051965 4.06975647374412 -6.99512810051965e-16,-6.0 4.0 -7e-16,-5.99512810051965 3.93024352625587 -6.99512810051965e-16,-5.98053613748314 3.86082689903993 -6.98053613748314e-16,-5.95629520146761 3.79208830918224 -6.95629520146761e-16,' + '-5.92252339187664 3.724362644183 -6.92252339187664e-16,-5.87938524157182 3.65797985667433 -6.87938524157182e-16,-5.8270909152852 3.5932633569242 -6.8270909152852e-16,-5.76589518571785 3.53052843721411 -6.76589518571785e-16,-5.69609619231285 3.4700807357668 -6.69609619231285e-16,-5.61803398874989 3.41221474770753 -6.61803398874989e-16,-5.53208888623796 3.35721239031346 -6.53208888623796e-16,-5.4386796006773 3.305341629541 -6.4386796006773e-16,-5.33826121271772 3.25685517452261 -6.33826121271772e-16,-5.23132295065132 3.21198924639328 -6.23132295065132e-16,-5.11838580694149 3.17096242744496 -6.11838580694149e-16,-5.0 3.13397459621556 -6e-16,-4.87674229357815 3.10120595370083 -5.87674229357816e-16,-4.74921318683182 3.07281614543321 -5.74921318683182e-16,-4.61803398874989 3.04894348370485 -5.6180339887499e-16,-4.48384379119934 3.029704273724 -5.48384379119934e-16,-4.34729635533386 3.01519224698779 -5.34729635533386e-16,-4.20905692653531 3.00547810463173 -5.20905692653531e-16,-4.069798993405 3.0006091729809 -5.069798993405e-16,-3.930201006595 3.0006091729809 -4.930201006595e-16,-3.79094307346469 3.00547810463173 -4.79094307346469e-16,-3.65270364466614 3.01519224698779 -4.65270364466614e-16,-3.51615620880066 3.029704273724 -4.51615620880066e-16,-3.38196601125011 3.04894348370485 -4.38196601125011e-16,-3.25078681316818 3.07281614543321 -4.25078681316818e-16,-3.12325770642185 3.10120595370083 -4.12325770642185e-16,-3.0 3.13397459621556 -4e-16,-2.88161419305851 3.17096242744496 -3.88161419305851e-16,-2.76867704934868 3.21198924639328 -3.76867704934868e-16,-2.66173878728228 3.25685517452261 -3.66173878728228e-16,-2.5613203993227 3.305341629541 -3.5613203993227e-16,-2.46791111376204 3.35721239031346 -3.46791111376204e-16,-2.38196601125011 3.41221474770753 -3.38196601125011e-16,-2.30390380768715 3.4700807357668 -3.30390380768715e-16,-2.23410481428215 3.53052843721411 -3.23410481428215e-16,-2.1729090847148 3.5932633569242 -3.1729090847148e-16,-2.12061475842818 3.65797985667433 -3.12061475842818e-16,-2.07747660812336 3.724362644183 -3.07747660812336e-16,-2.04370479853239 3.79208830918224 -3.04370479853239e-16,-2.01946386251686 3.86082689903993 -3.01946386251686e-16,-2.00487189948035 3.93024352625587 -3.00487189948035e-16,-2 4 -3e-16)'): feat.DumpReadable() - return 'fail' + pytest.fail() # OGRFeature(entities):19 # EntityHandle (String) = 20D @@ -1630,7 +1399,7 @@ def ogr_dxf_31(): if ogrtest.check_feature_geometry(feat, 'LINESTRING Z (-2.0 2.0 -2e-16,-1.96657794502105 2.03582232791524 -1.96657794502105e-16,-1.93571660708646 2.07387296203834 -1.93571660708646e-16,-1.90756413746468 2.11396923855471 -1.90756413746468e-16,-1.88225568337755 2.15591867344963 -1.88225568337755e-16,-1.85991273921989 2.19951988653655 -1.85991273921989e-16,-1.84064256332004 2.24456356819194 -1.84064256332004e-16,-1.8245376630414 2.29083348415575 -1.8245376630414e-16,-1.81167535069652 2.33810751357387 -1.81167535069652e-16,-1.80211737240583 2.38615871529951 -1.80211737240583e-16,-1.79590961168258 2.43475641733454 -1.79590961168258e-16,-1.79308186916688 2.48366732418105 -1.79308186916688e-16,-1.79364771956639 2.53265663678705 -1.79364771956639e-16,-1.79760444649032 2.58148917971011 -1.79760444649032e-16,-1.80493305548955 2.62993053008785 -1.80493305548955e-16,-1.81559836524041 2.67774814299566 -1.81559836524041e-16,-1.8295491764342 2.72471246778926 -1.8295491764342e-16,-1.84671851756181 2.7705980500731 -1.84671851756181e-16,-1.86702396641357 2.81518461400453 -1.86702396641357e-16,-1.89036804575079 2.85825811973811 -1.89036804575079e-16,-1.91663869124976 2.89961179093366 -1.91663869124976e-16,-1.94570978947168 2.93904710739563 -1.94570978947168e-16,-1.97744178327594 2.97637475807832 -1.97744178327594e-16,-2.01168234177068 3.01141554988232 -2.01168234177068e-16,-2.04826709158413 3.04400126787917 -2.04826709158413e-16,-2.08702040594658 3.07397548283483 -2.08702040594658e-16,-2.12775624779472 3.10119430215541 -2.12775624779472e-16,-2.17027906285109 3.12552706065018 -2.17027906285109e-16,-2.2143847183914 3.14685694779575 -2.2143847183914e-16,-2.25986148319297 3.16508156849045 -2.25986148319297e-16,-2.30649104396024 3.18011343460661 -2.30649104396024e-16,-2.35404955334774 3.1918803849814 -2.35404955334774e-16,-2.40230870454951 3.20032593182975 -2.40230870454951e-16,-2.45103682729644 3.2054095319166 -2.45103682729644e-16,' + '-2.5 3.20710678118655 -2.5e-16,-2.54896317270356 3.2054095319166 -2.54896317270356e-16,-2.59769129545049 3.20032593182975 -2.59769129545049e-16,-2.64595044665226 3.1918803849814 -2.64595044665226e-16,-2.69350895603976 3.18011343460661 -2.69350895603976e-16,-2.74013851680703 3.16508156849045 -2.74013851680703e-16,-2.7856152816086 3.14685694779575 -2.7856152816086e-16,-2.8297209371489 3.12552706065018 -2.8297209371489e-16,-2.87224375220528 3.10119430215541 -2.87224375220528e-16,-2.91297959405342 3.07397548283483 -2.91297959405342e-16,-2.95173290841587 3.04400126787917 -2.95173290841587e-16,-2.98831765822932 3.01141554988232 -2.98831765822932e-16,-3.02255821672406 2.97637475807832 -3.02255821672406e-16,-3.05429021052832 2.93904710739563 -3.05429021052832e-16,-3.08336130875024 2.89961179093367 -3.08336130875024e-16,-3.10963195424921 2.85825811973811 -3.10963195424921e-16,-3.13297603358643 2.81518461400453 -3.13297603358643e-16,-3.15328148243819 2.7705980500731 -3.15328148243819e-16,-3.1704508235658 2.72471246778926 -3.1704508235658e-16,-3.18440163475959 2.67774814299567 -3.18440163475959e-16,-3.19506694451045 2.62993053008786 -3.19506694451045e-16,-3.20239555350968 2.58148917971011 -3.20239555350968e-16,-3.20635228043361 2.53265663678705 -3.20635228043361e-16,-3.20691813083312 2.48366732418105 -3.20691813083312e-16,-3.20409038831742 2.43475641733454 -3.20409038831742e-16,-3.19788262759417 2.38615871529951 -3.19788262759417e-16,-3.18832464930348 2.33810751357387 -3.18832464930349e-16,-3.1754623369586 2.29083348415575 -3.1754623369586e-16,-3.15935743667996 2.24456356819194 -3.15935743667996e-16,-3.14008726078011 2.19951988653655 -3.14008726078011e-16,-3.11774431662245 2.15591867344963 -3.11774431662245e-16,-3.09243586253532 2.11396923855472 -3.09243586253532e-16,-3.06428339291354 2.07387296203834 -3.06428339291354e-16,-3.03342205497895 2.03582232791524 -3.03342205497895e-16,-3 2 -3e-16)'): feat.DumpReadable() - return 'fail' + pytest.fail() # OGRFeature(entities):20 # EntityHandle (String) = 20E @@ -1638,7 +1407,7 @@ def ogr_dxf_31(): feat = lyr.GetNextFeature() if ogrtest.check_feature_geometry(feat, 'POLYGON Z ((-1 2 -1e-16,-1 3 -1e-16,-2 3 -2e-16,-2 2 -2e-16,-1 2 -1e-16))'): feat.DumpReadable() - return 'fail' + pytest.fail() # OGRFeature(entities):21 # EntityHandle (String) = 20F @@ -1646,7 +1415,7 @@ def ogr_dxf_31(): feat = lyr.GetNextFeature() if ogrtest.check_feature_geometry(feat, 'POLYGON ((-3 4,-4 4,-4 3,-3 3,-3 4))'): feat.DumpReadable() - return 'fail' + pytest.fail() # OGRFeature(entities):22 # EntityHandle (String) = 211 @@ -1654,7 +1423,7 @@ def ogr_dxf_31(): feat = lyr.GetNextFeature() if ogrtest.check_feature_geometry(feat, 'POLYGON ((-8 8,-9 8,-9 9,-8 9,-8 8))'): feat.DumpReadable() - return 'fail' + pytest.fail() # OGRFeature(entities):23 # EntityHandle (String) = 212 @@ -1662,7 +1431,7 @@ def ogr_dxf_31(): feat = lyr.GetNextFeature() if ogrtest.check_feature_geometry(feat, 'LINESTRING (-2 2,-2.15384615384615 2.15384615384615,-2.30769230769231 2.30769230769231,-2.46153846153846 2.46153846153846,-2.61538461538461 2.61538461538461,-2.76923076923077 2.76923076923077,-2.92307692307692 2.92307692307692,-3.07692307692308 3.07692307692308,-3.23076923076923 3.23076923076923,-3.38461538461538 3.38461538461538,-3.53846153846154 3.53846153846154,-3.69230769230769 3.69230769230769,-3.84615384615385 3.84615384615385,-4 4,-4.15384615384615 4.15384615384615,-4.30769230769231 4.30769230769231,-4.46153846153846 4.46153846153846,-4.61538461538462 4.61538461538462,-4.76923076923077 4.76923076923077,-4.92307692307692 4.92307692307692,-5.07692307692308 5.07692307692308,-5.23076923076923 5.23076923076923,-5.38461538461538 5.38461538461538,-5.53846153846154 5.53846153846154,-5.69230769230769 5.69230769230769,-5.84615384615385 5.84615384615385,-6.0 6.0,-6.15384615384615 6.15384615384615,-6.30769230769231 6.30769230769231,-6.46153846153846 6.46153846153846,-6.61538461538462 6.61538461538462,-6.76923076923077 6.76923076923077,-6.92307692307692 6.92307692307692,-7.07692307692308 7.07692307692308,-7.23076923076923 7.23076923076923,-7.38461538461539 7.38461538461539,-7.53846153846154 7.53846153846154,-7.69230769230769 7.69230769230769,-7.84615384615385 7.84615384615385,-8 8)'): feat.DumpReadable() - return 'fail' + pytest.fail() # OGRFeature(entities):24 # EntityHandle (String) = 213 @@ -1670,7 +1439,7 @@ def ogr_dxf_31(): feat = lyr.GetNextFeature() if ogrtest.check_feature_geometry(feat, 'LINESTRING (-8 1,-7.62837370825536 0.987348067229724,-7.25775889681215 0.975707614760869,-6.88916704597178 0.966090122894857,-6.52360963603567 0.959507071933107,-6.16209814730525 0.956969942177043,-5.80564406008193 0.959490213928084,-5.45525885466714 0.968079367487651,-5.11195401136229 0.983748883157167,-4.77674101046882 1.00751024123805,-4.45063133228814 1.04037492203173,-4.13463645712167 1.08335440583961,-3.82976786527082 1.13746017296313,-3.53703703703704 1.2037037037037,-3.25745545272173 1.28309647836275,-2.99203459262631 1.37664997724169,-2.74178593705221 1.48537568064195,-2.50772096630085 1.61028506886495,-2.29085116067365 1.75238962221211,-2.09218800047203 1.91270082098484,-1.91270082098485 2.09218800047202,-1.75238962221211 2.29085116067364,-1.61028506886495 2.50772096630085,-1.48537568064195 2.74178593705221,-1.37664997724169 2.99203459262631,-1.28309647836275 3.25745545272172,-1.2037037037037 3.53703703703703,-1.13746017296313 3.82976786527082,-1.08335440583961 4.13463645712166,-1.04037492203173 4.45063133228814,-1.00751024123805 4.77674101046882,-0.983748883157167 5.11195401136229,-0.968079367487652 5.45525885466714,-0.959490213928084 5.80564406008193,-0.956969942177043 6.16209814730525,-0.959507071933108 6.52360963603567,-0.966090122894857 6.88916704597178,-0.975707614760869 7.25775889681216,-0.987348067229724 7.62837370825537,-1 8)'): feat.DumpReadable() - return 'fail' + pytest.fail() # OGRFeature(entities):25 # EntityHandle (String) = 214 @@ -1678,7 +1447,7 @@ def ogr_dxf_31(): feat = lyr.GetNextFeature() if ogrtest.check_feature_geometry(feat, 'POINT Z (-7 7 -7e-16)'): feat.DumpReadable() - return 'fail' + pytest.fail() # OGRFeature(entities):26 # EntityHandle (String) = 215 @@ -1686,7 +1455,7 @@ def ogr_dxf_31(): feat = lyr.GetNextFeature() if ogrtest.check_feature_geometry(feat, 'POINT Z (-4 -4 -1e-15)'): feat.DumpReadable() - return 'fail' + pytest.fail() # OGRFeature(entities):27 # EntityHandle (String) = 216 @@ -1694,7 +1463,7 @@ def ogr_dxf_31(): feat = lyr.GetNextFeature() if ogrtest.check_feature_geometry(feat, 'LINESTRING Z (0 0 -2e-16,-1 -1 -5e-16)'): feat.DumpReadable() - return 'fail' + pytest.fail() # OGRFeature(entities):28 # EntityHandle (String) = 217 @@ -1702,7 +1471,7 @@ def ogr_dxf_31(): feat = lyr.GetNextFeature() if ogrtest.check_feature_geometry(feat, 'LINESTRING (-1 -1,-2 -1,-1 -2,-1 -1)'): feat.DumpReadable() - return 'fail' + pytest.fail() # OGRFeature(entities):29 # EntityHandle (String) = 218 @@ -1710,7 +1479,7 @@ def ogr_dxf_31(): feat = lyr.GetNextFeature() if ogrtest.check_feature_geometry(feat, 'LINESTRING Z (-1 -1 -2e-16,-1 -2 -4e-16,-2 -2 -5e-16,-1 -1 -2e-16)'): feat.DumpReadable() - return 'fail' + pytest.fail() # OGRFeature(entities):30 # EntityHandle (String) = 21D @@ -1718,7 +1487,7 @@ def ogr_dxf_31(): feat = lyr.GetNextFeature() if ogrtest.check_feature_geometry(feat, 'LINESTRING Z (-2 -4 0,-2.00487189948035 -4.13951294748825 0,-2.01946386251686 -4.27834620192013 0,-2.04370479853239 -4.41582338163552 0,-2.07747660812336 -4.551274711634 0,-2.12061475842818 -4.68404028665134 0,-2.1729090847148 -4.8134732861516 0,-2.23410481428215 -4.93894312557178 0,-2.30390380768715 -5.05983852846641 0,-2.38196601125011 -5.17557050458495 0,-2.46791111376204 -5.28557521937308 0,-2.5613203993227 -5.38931674091799 0,-2.66173878728228 -5.48628965095479 0,-2.76867704934868 -5.57602150721344 0,-2.88161419305851 -5.65807514511008 0,-3.0 -5.73205080756888 0,-3.12325770642185 -5.79758809259833 0,-3.25078681316818 -5.85436770913357 0,-3.38196601125011 -5.90211303259031 0,-3.51615620880066 -5.94059145255199 0,-3.65270364466614 -5.96961550602442 0,-3.79094307346469 -5.98904379073655 0,-3.930201006595 -5.99878165403819 0,-4.069798993405 -5.99878165403819 0,-4.20905692653531 -5.98904379073655 0,-4.34729635533386 -5.96961550602442 0,-4.48384379119934 -5.94059145255199 0,-4.61803398874989 -5.90211303259031 0,-4.74921318683182 -5.85436770913357 0,-4.87674229357815 -5.79758809259833 0,-5.0 -5.73205080756888 0,-5.11838580694149 -5.65807514511008 0,-5.23132295065132 -5.57602150721344 0,-5.33826121271772 -5.48628965095479 0,-5.4386796006773 -5.38931674091799 0,-5.53208888623796 -5.28557521937308 0,-5.61803398874989 -5.17557050458495 0,-5.69609619231285 -5.05983852846641 0,-5.76589518571785 -4.93894312557178 0,-5.8270909152852 -4.8134732861516 0,-5.87938524157182 -4.68404028665134 0,-5.92252339187664 -4.551274711634 0,-5.95629520146761 -4.41582338163552 0,-5.98053613748314 -4.27834620192013 0,-5.99512810051965 -4.13951294748825 0,-6 -4 0,-5.99512810051965 -3.86048705251175 0,-5.98053613748314 -3.72165379807987 0,-5.95629520146761 -3.58417661836448 0,-5.92252339187664 -3.448725288366 0,-5.87938524157182 -3.31595971334866 0,-5.8270909152852 -3.1865267138484 0,-5.76589518571785 -3.06105687442822 0,-5.69609619231285 -2.94016147153359 0,-5.61803398874989 -2.82442949541505 0,-5.53208888623796 -2.71442478062692 0,-5.4386796006773 -2.61068325908201 0,-5.33826121271772 -2.51371034904521 0,-5.23132295065132 -2.42397849278656 0,-5.11838580694149 -2.34192485488992 0,-5.0 -2.26794919243112 0,-4.87674229357816 -2.20241190740167 0,-4.74921318683182 -2.14563229086643 0,-4.61803398874989 -2.09788696740969 0,-4.48384379119934 -2.05940854744801 0,-4.34729635533386 -2.03038449397558 0,-4.20905692653531 -2.01095620926345 0,-4.069798993405 -2.00121834596181 0,-3.930201006595 -2.00121834596181 0,-3.79094307346469 -2.01095620926345 0,-3.65270364466614 -2.03038449397558 0,-3.51615620880067 -2.05940854744801 0,-3.38196601125011 -2.09788696740969 0,-3.25078681316818 -2.14563229086643 0,-3.12325770642185 -2.20241190740167 0,-3.0 -2.26794919243112 0,-2.88161419305851 -2.34192485488992 0,-2.76867704934868 -2.42397849278656 0,-2.66173878728228 -2.51371034904521 0,-2.5613203993227 -2.610683259082 0,-2.46791111376204 -2.71442478062692 0,-2.38196601125011 -2.82442949541505 0,-2.30390380768715 -2.94016147153359 0,-2.23410481428215 -3.06105687442822 0,-2.1729090847148 -3.1865267138484 0,-2.12061475842818 -3.31595971334866 0,-2.07747660812336 -3.448725288366 0,-2.04370479853239 -3.58417661836448 0,-2.01946386251686 -3.72165379807987 0,-2.00487189948035 -3.86048705251175 0,-2.0 -4.0 0)'): feat.DumpReadable() - return 'fail' + pytest.fail() # OGRFeature(entities):31 # EntityHandle (String) = 21E @@ -1728,7 +1497,7 @@ def ogr_dxf_31(): if ogrtest.check_feature_geometry(feat, 'LINESTRING Z (-2 -4 -8e-16,-2.00487189948035 -4.06975647374412 -8.07462837322448e-16,-2.01946386251686 -4.13917310096007 -8.15863696347693e-16,-2.04370479853239 -4.20791169081776 -8.25161648935015e-16,-2.07747660812336 -4.275637355817 -8.35311396394036e-16,-2.12061475842818 -4.34202014332567 -8.46263490175385e-16,-2.1729090847148 -4.4067366430758 -8.5796457277906e-16,-2.23410481428215 -4.46947156278589 -8.70357637706804e-16,-2.30390380768715 -4.52991926423321 -8.83382307192036e-16,-2.38196601125011 -4.58778525229247 -8.96975126354258e-16,-2.46791111376204 -4.64278760968654 -9.11069872344859e-16,-2.5613203993227 -4.694658370459 -9.2559787697817e-16,-2.66173878728228 -4.74314482547739 -9.40488361275968e-16,-2.76867704934868 -4.78801075360672 -9.5566878029554e-16,-2.88161419305851 -4.82903757255504 -9.71065176561355e-16,-3.0 -4.86602540378444 -9.86602540378444e-16,-3.12325770642185 -4.89879404629917 -1.0022051752721e-15,-3.25078681316818 -4.92718385456679 -1.0177970667735e-15,-3.38196601125011 -4.95105651629515 -1.03330225275453e-15,-3.51615620880067 -4.970295726276 -1.04864519350767e-15,-3.65270364466614 -4.98480775301221 -1.06375113976783e-15,-3.79094307346469 -4.99452189536827 -1.0785464968833e-15,-3.930201006595 -4.9993908270191 -1.09295918336141e-15,-4.069798993405 -4.9993908270191 -1.10691898204241e-15,-4.20905692653531 -4.99452189536827 -1.12035788219036e-15,-4.34729635533386 -4.98480775301221 -1.13321041083461e-15,-4.48384379119934 -4.970295726276 -1.14541395174753e-15,-4.61803398874989 -4.95105651629515 -1.1569090505045e-15,-4.74921318683182 -4.92718385456679 -1.16763970413986e-15,-4.87674229357816 -4.89879404629917 -1.17755363398773e-15,-5.0 -4.86602540378444 -1.18660254037844e-15,-5.11838580694149 -4.82903757255504 -1.19474233794965e-15,-5.23132295065132 -4.78801075360672 -1.2019333704258e-15,-5.33826121271772 -4.74314482547739 -1.20814060381951e-15,-5.4386796006773 -4.694658370459 -1.21333379711363e-15,-5.53208888623796 -4.64278760968654 -1.21748764959245e-15,-5.61803398874989 -4.58778525229247 -1.22058192410424e-15,-5.69609619231285 -4.5299192642332 -1.22260154565461e-15,-5.76589518571785 -4.46947156278589 -1.22353667485037e-15,-5.8270909152852 -4.4067366430758 -1.2233827558361e-15,-5.87938524157182 -4.34202014332567 -1.22214053848975e-15,-5.92252339187664 -4.275637355817 -1.21981607476936e-15,-5.95629520146761 -4.20791169081776 -1.21642068922854e-15,-5.98053613748314 -4.13917310096007 -1.21197092384432e-15,-5.99512810051965 -4.06975647374412 -1.20648845742638e-15,-6 -4 -1.2e-15,-5.99512810051965 -3.93024352625587 -1.19253716267755e-15,' + '-5.98053613748314 -3.86082689903993 -1.18413630365231e-15,-5.95629520146761 -3.79208830918224 -1.17483835106499e-15,-5.92252339187664 -3.724362644183 -1.16468860360596e-15,-5.87938524157182 -3.65797985667433 -1.15373650982461e-15,-5.8270909152852 -3.5932633569242 -1.14203542722094e-15,-5.76589518571785 -3.53052843721411 -1.1296423622932e-15,-5.69609619231285 -3.4700807357668 -1.11661769280796e-15,-5.61803398874989 -3.41221474770753 -1.10302487364574e-15,-5.53208888623796 -3.35721239031346 -1.08893012765514e-15,-5.4386796006773 -3.305341629541 -1.07440212302183e-15,-5.33826121271772 -3.25685517452261 -1.05951163872403e-15,-5.23132295065132 -3.21198924639328 -1.04433121970446e-15,-5.11838580694149 -3.17096242744496 -1.02893482343865e-15,-5.0 -3.13397459621556 -1.01339745962156e-15,-4.87674229357815 -3.10120595370083 -9.97794824727899e-16,-4.74921318683182 -3.07281614543321 -9.82202933226504e-16,-4.61803398874989 -3.04894348370485 -9.66697747245474e-16,-4.48384379119934 -3.029704273724 -9.51354806492334e-16,-4.34729635533386 -3.01519224698779 -9.36248860232165e-16,-4.20905692653531 -3.00547810463173 -9.21453503116703e-16,-4.069798993405 -3.0006091729809 -9.07040816638591e-16,-3.930201006595 -3.0006091729809 -8.9308101795759e-16,-3.79094307346469 -3.00547810463173 -8.79642117809642e-16,-3.65270364466614 -3.01519224698779 -8.66789589165393e-16,-3.51615620880066 -3.029704273724 -8.54586048252467e-16,-3.38196601125011 -3.04894348370485 -8.43090949495495e-16,-3.25078681316818 -3.07281614543321 -8.32360295860139e-16,-3.12325770642185 -3.10120595370083 -8.22446366012268e-16,-3.0 -3.13397459621556 -8.13397459621556e-16,-2.88161419305851 -3.17096242744496 -8.05257662050347e-16,-2.76867704934868 -3.21198924639328 -7.98066629574196e-16,-2.66173878728228 -3.25685517452261 -7.91859396180489e-16,-2.5613203993227 -3.305341629541 -7.8666620288637e-16,-2.46791111376204 -3.35721239031346 -7.82512350407551e-16,-2.38196601125011 -3.41221474770753 -7.79418075895763e-16,-2.30390380768715 -3.4700807357668 -7.77398454345394e-16,-2.23410481428215 -3.53052843721411 -7.76463325149626e-16,-2.1729090847148 -3.5932633569242 -7.766172441639e-16,-2.12061475842818 -3.65797985667433 -7.77859461510252e-16,-2.07747660812336 -3.724362644183 -7.80183925230636e-16,-2.04370479853239 -3.79208830918224 -7.83579310771463e-16,-2.01946386251686 -3.86082689903993 -7.88029076155679e-16,-2.00487189948035 -3.93024352625587 -7.93511542573623e-16,-2 -4 -8e-16)'): feat.DumpReadable() - return 'fail' + pytest.fail() # OGRFeature(entities):32 # EntityHandle (String) = 21F @@ -1736,7 +1505,7 @@ def ogr_dxf_31(): feat = lyr.GetNextFeature() if ogrtest.check_feature_geometry(feat, 'LINESTRING Z (-2 -2 0,-1.96657794502105 -2.03582232791524 0,-1.93571660708646 -2.07387296203834 0,-1.90756413746468 -2.11396923855472 0,-1.88225568337755 -2.15591867344963 0,-1.85991273921989 -2.19951988653655 0,-1.84064256332004 -2.24456356819194 0,-1.8245376630414 -2.29083348415575 0,-1.81167535069652 -2.33810751357387 0,-1.80211737240583 -2.38615871529951 0,-1.79590961168258 -2.43475641733454 0,-1.79308186916688 -2.48366732418105 0,-1.79364771956639 -2.53265663678705 0,-1.79760444649032 -2.58148917971011 0,-1.80493305548955 -2.62993053008786 0,-1.81559836524041 -2.67774814299567 0,-1.8295491764342 -2.72471246778926 0,-1.84671851756181 -2.7705980500731 0,-1.86702396641357 -2.81518461400453 0,-1.89036804575079 -2.85825811973811 0,-1.91663869124976 -2.89961179093367 0,-1.94570978947168 -2.93904710739563 0,-1.97744178327594 -2.97637475807832 0,-2.01168234177068 -3.01141554988232 0,-2.04826709158413 -3.04400126787917 0,-2.08702040594658 -3.07397548283483 0,-2.12775624779472 -3.10119430215541 0,-2.1702790628511 -3.12552706065018 0,-2.2143847183914 -3.14685694779575 0,-2.25986148319297 -3.16508156849045 0,-2.30649104396024 -3.18011343460661 0,-2.35404955334774 -3.1918803849814 0,-2.40230870454951 -3.20032593182975 0,-2.45103682729644 -3.2054095319166 0,-2.5 -3.20710678118655 0,-2.54896317270356 -3.2054095319166 0,-2.59769129545049 -3.20032593182975 0,-2.64595044665226 -3.1918803849814 0,-2.69350895603976 -3.18011343460661 0,-2.74013851680703 -3.16508156849045 0,-2.7856152816086 -3.14685694779575 0,-2.8297209371489 -3.12552706065018 0,-2.87224375220528 -3.10119430215541 0,-2.91297959405342 -3.07397548283483 0,-2.95173290841587 -3.04400126787917 0,-2.98831765822932 -3.01141554988232 0,-3.02255821672406 -2.97637475807832 0,-3.05429021052832 -2.93904710739563 0,-3.08336130875024 -2.89961179093367 0,-3.10963195424921 -2.85825811973811 0,-3.13297603358643 -2.81518461400453 0,-3.15328148243819 -2.7705980500731 0,-3.1704508235658 -2.72471246778926 0,-3.18440163475959 -2.67774814299567 0,-3.19506694451045 -2.62993053008786 0,-3.20239555350968 -2.58148917971011 0,-3.20635228043361 -2.53265663678705 0,-3.20691813083312 -2.48366732418105 0,-3.20409038831742 -2.43475641733454 0,-3.19788262759417 -2.38615871529951 0,-3.18832464930348 -2.33810751357387 0,-3.1754623369586 -2.29083348415575 0,-3.15935743667996 -2.24456356819194 0,-3.14008726078011 -2.19951988653655 0,-3.11774431662245 -2.15591867344963 0,-3.09243586253532 -2.11396923855472 0,-3.06428339291354 -2.07387296203834 0,-3.03342205497895 -2.03582232791524 0,-3 -2 0)'): feat.DumpReadable() - return 'fail' + pytest.fail() # OGRFeature(entities):33 # EntityHandle (String) = 220 @@ -1744,7 +1513,7 @@ def ogr_dxf_31(): feat = lyr.GetNextFeature() if ogrtest.check_feature_geometry(feat, 'POLYGON Z ((-1 -2 -4e-16,-1 -3 -5e-16,-2 -3 -6e-16,-2 -2 -5e-16,-1 -2 -4e-16))'): feat.DumpReadable() - return 'fail' + pytest.fail() # OGRFeature(entities):34 # EntityHandle (String) = 221 @@ -1752,7 +1521,7 @@ def ogr_dxf_31(): feat = lyr.GetNextFeature() if ogrtest.check_feature_geometry(feat, 'POLYGON ((-3 -4,-4 -4,-4 -3,-3 -3,-3 -4))'): feat.DumpReadable() - return 'fail' + pytest.fail() # OGRFeature(entities):35 # EntityHandle (String) = 223 @@ -1760,7 +1529,7 @@ def ogr_dxf_31(): feat = lyr.GetNextFeature() if ogrtest.check_feature_geometry(feat, 'POLYGON ((-8 -8,-9 -8,-9 -9,-8 -9,-8 -8))'): feat.DumpReadable() - return 'fail' + pytest.fail() # OGRFeature(entities):36 # EntityHandle (String) = 224 @@ -1768,7 +1537,7 @@ def ogr_dxf_31(): feat = lyr.GetNextFeature() if ogrtest.check_feature_geometry(feat, 'LINESTRING (-2 -2,-2.15384615384615 -2.15384615384615,-2.30769230769231 -2.30769230769231,-2.46153846153846 -2.46153846153846,-2.61538461538461 -2.61538461538461,-2.76923076923077 -2.76923076923077,-2.92307692307692 -2.92307692307692,-3.07692307692308 -3.07692307692308,-3.23076923076923 -3.23076923076923,-3.38461538461538 -3.38461538461538,-3.53846153846154 -3.53846153846154,-3.69230769230769 -3.69230769230769,-3.84615384615385 -3.84615384615385,-4 -4,-4.15384615384615 -4.15384615384615,-4.30769230769231 -4.30769230769231,-4.46153846153846 -4.46153846153846,-4.61538461538462 -4.61538461538462,-4.76923076923077 -4.76923076923077,-4.92307692307692 -4.92307692307692,-5.07692307692308 -5.07692307692308,-5.23076923076923 -5.23076923076923,-5.38461538461538 -5.38461538461538,-5.53846153846154 -5.53846153846154,-5.69230769230769 -5.69230769230769,-5.84615384615385 -5.84615384615385,-6.0 -6.0,-6.15384615384615 -6.15384615384615,-6.30769230769231 -6.30769230769231,-6.46153846153846 -6.46153846153846,-6.61538461538462 -6.61538461538462,-6.76923076923077 -6.76923076923077,-6.92307692307692 -6.92307692307692,-7.07692307692308 -7.07692307692308,-7.23076923076923 -7.23076923076923,-7.38461538461539 -7.38461538461539,-7.53846153846154 -7.53846153846154,-7.69230769230769 -7.69230769230769,-7.84615384615385 -7.84615384615385,-8 -8)'): feat.DumpReadable() - return 'fail' + pytest.fail() # OGRFeature(entities):37 # EntityHandle (String) = 225 @@ -1776,7 +1545,7 @@ def ogr_dxf_31(): feat = lyr.GetNextFeature() if ogrtest.check_feature_geometry(feat, 'LINESTRING (-8 -1,-7.62837370825536 -0.987348067229724,-7.25775889681215 -0.975707614760869,-6.88916704597178 -0.966090122894857,-6.52360963603567 -0.959507071933107,-6.16209814730525 -0.956969942177043,-5.80564406008193 -0.959490213928084,-5.45525885466714 -0.968079367487651,-5.11195401136229 -0.983748883157167,-4.77674101046882 -1.00751024123805,-4.45063133228814 -1.04037492203173,-4.13463645712167 -1.08335440583961,-3.82976786527082 -1.13746017296313,-3.53703703703704 -1.2037037037037,-3.25745545272173 -1.28309647836275,-2.99203459262631 -1.37664997724169,-2.74178593705221 -1.48537568064195,-2.50772096630085 -1.61028506886495,-2.29085116067365 -1.75238962221211,-2.09218800047203 -1.91270082098484,-1.91270082098485 -2.09218800047202,-1.75238962221211 -2.29085116067364,-1.61028506886495 -2.50772096630085,-1.48537568064195 -2.74178593705221,-1.37664997724169 -2.99203459262631,-1.28309647836275 -3.25745545272172,-1.2037037037037 -3.53703703703703,-1.13746017296313 -3.82976786527082,-1.08335440583961 -4.13463645712166,-1.04037492203173 -4.45063133228814,-1.00751024123805 -4.77674101046882,-0.983748883157167 -5.11195401136229,-0.968079367487652 -5.45525885466714,-0.959490213928084 -5.80564406008193,-0.956969942177043 -6.16209814730525,-0.959507071933108 -6.52360963603567,-0.966090122894857 -6.88916704597178,-0.975707614760869 -7.25775889681216,-0.987348067229724 -7.62837370825537,-1 -8)'): feat.DumpReadable() - return 'fail' + pytest.fail() # OGRFeature(entities):38 # EntityHandle (String) = 226 @@ -1784,7 +1553,7 @@ def ogr_dxf_31(): feat = lyr.GetNextFeature() if ogrtest.check_feature_geometry(feat, 'POINT Z (-7 -7 0)'): feat.DumpReadable() - return 'fail' + pytest.fail() # OGRFeature(entities):39 # EntityHandle (String) = 227 @@ -1792,7 +1561,7 @@ def ogr_dxf_31(): feat = lyr.GetNextFeature() if ogrtest.check_feature_geometry(feat, 'POINT Z (4 -4 -5e-16)'): feat.DumpReadable() - return 'fail' + pytest.fail() # OGRFeature(entities):40 # EntityHandle (String) = 228 @@ -1800,7 +1569,7 @@ def ogr_dxf_31(): feat = lyr.GetNextFeature() if ogrtest.check_feature_geometry(feat, 'LINESTRING Z (0 0 0,1 -1 -1e-16)'): feat.DumpReadable() - return 'fail' + pytest.fail() # OGRFeature(entities):41 # EntityHandle (String) = 229 @@ -1808,7 +1577,7 @@ def ogr_dxf_31(): feat = lyr.GetNextFeature() if ogrtest.check_feature_geometry(feat, 'LINESTRING (1 -1,2 -1,1 -2,1 -1)'): feat.DumpReadable() - return 'fail' + pytest.fail() # OGRFeature(entities):42 # EntityHandle (String) = 22A @@ -1816,7 +1585,7 @@ def ogr_dxf_31(): feat = lyr.GetNextFeature() if ogrtest.check_feature_geometry(feat, 'LINESTRING Z (1 -1 -1e-16,1 -2 -2e-16,2 -2 -2e-16,1 -1 -1e-16)'): feat.DumpReadable() - return 'fail' + pytest.fail() # OGRFeature(entities):43 # EntityHandle (String) = 22F @@ -1826,7 +1595,7 @@ def ogr_dxf_31(): if ogrtest.check_feature_geometry(feat, 'LINESTRING Z (2 -4 -4e-16,2.00487189948035 -4.13951294748825 -4.13951294748825e-16,2.01946386251686 -4.27834620192013 -4.27834620192013e-16,2.04370479853239 -4.41582338163552 -4.41582338163552e-16,2.07747660812336 -4.551274711634 -4.551274711634e-16,2.12061475842818 -4.68404028665134 -4.68404028665134e-16,2.1729090847148 -4.8134732861516 -4.8134732861516e-16,2.23410481428215 -4.93894312557178 -4.93894312557178e-16,2.30390380768715 -5.05983852846641 -5.05983852846641e-16,2.38196601125011 -5.17557050458495 -5.17557050458495e-16,2.46791111376204 -5.28557521937308 -5.28557521937308e-16,2.5613203993227 -5.38931674091799 -5.38931674091799e-16,2.66173878728228 -5.48628965095479 -5.48628965095479e-16,2.76867704934868 -5.57602150721344 -5.57602150721344e-16,2.88161419305851 -5.65807514511008 -5.65807514511008e-16,3.0 -5.73205080756888 -5.73205080756888e-16,3.12325770642185 -5.79758809259833 -5.79758809259833e-16,3.25078681316818 -5.85436770913357 -5.85436770913357e-16,3.38196601125011 -5.90211303259031 -5.90211303259031e-16,3.51615620880066 -5.94059145255199 -5.94059145255199e-16,3.65270364466614 -5.96961550602442 -5.96961550602442e-16,3.79094307346469 -5.98904379073655 -5.98904379073655e-16,3.930201006595 -5.99878165403819 -5.99878165403819e-16,4.069798993405 -5.99878165403819 -5.99878165403819e-16,4.20905692653531 -5.98904379073655 -5.98904379073655e-16,4.34729635533386 -5.96961550602442 -5.96961550602442e-16,4.48384379119934 -5.94059145255199 -5.94059145255199e-16,4.61803398874989 -5.90211303259031 -5.90211303259031e-16,4.74921318683182 -5.85436770913357 -5.85436770913357e-16,4.87674229357815 -5.79758809259833 -5.79758809259833e-16,5.0 -5.73205080756888 -5.73205080756888e-16,5.11838580694149 -5.65807514511008 -5.65807514511008e-16,5.23132295065132 -5.57602150721344 -5.57602150721344e-16,5.33826121271772 -5.48628965095479 -5.48628965095479e-16,5.4386796006773 -5.38931674091799 -5.38931674091799e-16,5.53208888623796 -5.28557521937308 -5.28557521937308e-16,5.61803398874989 -5.17557050458495 -5.17557050458495e-16,5.69609619231285 -5.05983852846641 -5.05983852846641e-16,5.76589518571785 -4.93894312557178 -4.93894312557178e-16,5.8270909152852 -4.8134732861516 -4.8134732861516e-16,5.87938524157182 -4.68404028665134 -4.68404028665134e-16,5.92252339187664 -4.551274711634 -4.551274711634e-16,5.95629520146761 -4.41582338163552 -4.41582338163552e-16,5.98053613748314 -4.27834620192013 -4.27834620192013e-16,5.99512810051965 -4.13951294748825 -4.13951294748825e-16,6 -4 -4e-16,5.99512810051965 -3.86048705251175 -3.86048705251175e-16,5.98053613748314 -3.72165379807987 -3.72165379807987e-16,5.95629520146761 -3.58417661836448 -3.58417661836448e-16,5.92252339187664 -3.448725288366 -3.448725288366e-16,5.87938524157182 -3.31595971334866 -3.31595971334866e-16,5.8270909152852 -3.1865267138484 -3.1865267138484e-16,5.76589518571785 -3.06105687442822 -3.06105687442822e-16,5.69609619231285 -2.94016147153359 -2.94016147153359e-16,5.61803398874989 -2.82442949541505 -2.82442949541505e-16,5.53208888623796 -2.71442478062692 -2.71442478062692e-16,5.4386796006773 -2.61068325908201 -2.61068325908201e-16,5.33826121271772 -2.51371034904521 -2.51371034904521e-16,' + '5.23132295065132 -2.42397849278656 -2.42397849278656e-16,5.11838580694149 -2.34192485488992 -2.34192485488992e-16,5.0 -2.26794919243112 -2.26794919243112e-16,4.87674229357816 -2.20241190740167 -2.20241190740167e-16,4.74921318683182 -2.14563229086643 -2.14563229086643e-16,4.61803398874989 -2.09788696740969 -2.09788696740969e-16,4.48384379119934 -2.05940854744801 -2.05940854744801e-16,4.34729635533386 -2.03038449397558 -2.03038449397558e-16,4.20905692653531 -2.01095620926345 -2.01095620926345e-16,4.069798993405 -2.00121834596181 -2.00121834596181e-16,3.930201006595 -2.00121834596181 -2.00121834596181e-16,3.79094307346469 -2.01095620926345 -2.01095620926345e-16,3.65270364466614 -2.03038449397558 -2.03038449397558e-16,3.51615620880067 -2.05940854744801 -2.05940854744801e-16,3.38196601125011 -2.09788696740969 -2.09788696740969e-16,3.25078681316818 -2.14563229086643 -2.14563229086643e-16,3.12325770642185 -2.20241190740167 -2.20241190740167e-16,3.0 -2.26794919243112 -2.26794919243112e-16,2.88161419305851 -2.34192485488992 -2.34192485488992e-16,2.76867704934868 -2.42397849278656 -2.42397849278656e-16,2.66173878728228 -2.51371034904521 -2.51371034904521e-16,2.5613203993227 -2.610683259082 -2.610683259082e-16,2.46791111376204 -2.71442478062692 -2.71442478062692e-16,2.38196601125011 -2.82442949541505 -2.82442949541505e-16,2.30390380768715 -2.94016147153359 -2.94016147153359e-16,2.23410481428215 -3.06105687442822 -3.06105687442822e-16,2.1729090847148 -3.1865267138484 -3.1865267138484e-16,2.12061475842818 -3.31595971334866 -3.31595971334866e-16,2.07747660812336 -3.448725288366 -3.448725288366e-16,2.04370479853239 -3.58417661836448 -3.58417661836448e-16,2.01946386251686 -3.72165379807987 -3.72165379807987e-16,2.00487189948035 -3.86048705251175 -3.86048705251175e-16,2.0 -4.0 -4e-16)'): feat.DumpReadable() - return 'fail' + pytest.fail() # OGRFeature(entities):44 # EntityHandle (String) = 230 @@ -1836,7 +1605,7 @@ def ogr_dxf_31(): if ogrtest.check_feature_geometry(feat, 'LINESTRING Z (2 -4 -5e-16,2.00487189948035 -4.06975647374412 -5.06975647374413e-16,2.01946386251686 -4.13917310096007 -5.13917310096007e-16,2.04370479853239 -4.20791169081776 -5.20791169081776e-16,2.07747660812336 -4.275637355817 -5.275637355817e-16,2.12061475842818 -4.34202014332567 -5.34202014332567e-16,2.1729090847148 -4.4067366430758 -5.4067366430758e-16,2.23410481428215 -4.46947156278589 -5.46947156278589e-16,2.30390380768715 -4.52991926423321 -5.52991926423321e-16,2.38196601125011 -4.58778525229247 -5.58778525229247e-16,2.46791111376204 -4.64278760968654 -5.64278760968654e-16,2.5613203993227 -4.694658370459 -5.694658370459e-16,2.66173878728228 -4.74314482547739 -5.7431448254774e-16,2.76867704934868 -4.78801075360672 -5.78801075360672e-16,2.88161419305851 -4.82903757255504 -5.82903757255504e-16,3.0 -4.86602540378444 -5.86602540378444e-16,3.12325770642185 -4.89879404629917 -5.89879404629917e-16,3.25078681316818 -4.92718385456679 -5.92718385456679e-16,3.38196601125011 -4.95105651629515 -5.95105651629515e-16,3.51615620880067 -4.970295726276 -5.970295726276e-16,3.65270364466614 -4.98480775301221 -5.98480775301221e-16,3.79094307346469 -4.99452189536827 -5.99452189536827e-16,3.930201006595 -4.9993908270191 -5.9993908270191e-16,4.069798993405 -4.9993908270191 -5.9993908270191e-16,4.20905692653531 -4.99452189536827 -5.99452189536827e-16,4.34729635533386 -4.98480775301221 -5.98480775301221e-16,4.48384379119934 -4.970295726276 -5.970295726276e-16,4.61803398874989 -4.95105651629515 -5.95105651629515e-16,4.74921318683182 -4.92718385456679 -5.92718385456679e-16,4.87674229357816 -4.89879404629917 -5.89879404629917e-16,5.0 -4.86602540378444 -5.86602540378444e-16,5.11838580694149 -4.82903757255504 -5.82903757255504e-16,5.23132295065132 -4.78801075360672 -5.78801075360672e-16,5.33826121271772 -4.74314482547739 -5.74314482547739e-16,5.4386796006773 -4.694658370459 -5.694658370459e-16,5.53208888623796 -4.64278760968654 -5.64278760968654e-16,5.61803398874989 -4.58778525229247 -5.58778525229247e-16,5.69609619231285 -4.5299192642332 -5.52991926423321e-16,5.76589518571785 -4.46947156278589 -5.46947156278589e-16,5.8270909152852 -4.4067366430758 -5.4067366430758e-16,5.87938524157182 -4.34202014332567 -5.34202014332567e-16,5.92252339187664 -4.275637355817 -5.275637355817e-16,5.95629520146761 -4.20791169081776 -5.20791169081776e-16,5.98053613748314 -4.13917310096007 -5.13917310096007e-16,5.99512810051965 -4.06975647374412 -5.06975647374413e-16,6 -4 -5e-16,5.99512810051965 -3.93024352625587 -4.93024352625588e-16,5.98053613748314 -3.86082689903993 -4.86082689903993e-16,5.95629520146761 -3.79208830918224 -4.79208830918224e-16,5.92252339187664 -3.724362644183 -4.724362644183e-16,5.87938524157182 -3.65797985667433 -4.65797985667433e-16,5.8270909152852 -3.5932633569242 -4.5932633569242e-16,5.76589518571785 -3.53052843721411 -4.53052843721411e-16,5.69609619231285 -3.4700807357668 -4.4700807357668e-16,5.61803398874989 -3.41221474770753 -4.41221474770753e-16,' + '5.53208888623796 -3.35721239031346 -4.35721239031346e-16,5.4386796006773 -3.305341629541 -4.305341629541e-16,5.33826121271772 -3.25685517452261 -4.25685517452261e-16,5.23132295065132 -3.21198924639328 -4.21198924639328e-16,5.11838580694149 -3.17096242744496 -4.17096242744496e-16,5.0 -3.13397459621556 -4.13397459621556e-16,4.87674229357815 -3.10120595370083 -4.10120595370083e-16,4.74921318683182 -3.07281614543321 -4.07281614543321e-16,4.61803398874989 -3.04894348370485 -4.04894348370485e-16,4.48384379119934 -3.029704273724 -4.029704273724e-16,4.34729635533386 -3.01519224698779 -4.01519224698779e-16,4.20905692653531 -3.00547810463173 -4.00547810463173e-16,4.069798993405 -3.0006091729809 -4.0006091729809e-16,3.930201006595 -3.0006091729809 -4.0006091729809e-16,3.79094307346469 -3.00547810463173 -4.00547810463173e-16,3.65270364466614 -3.01519224698779 -4.01519224698779e-16,3.51615620880066 -3.029704273724 -4.029704273724e-16,3.38196601125011 -3.04894348370485 -4.04894348370485e-16,3.25078681316818 -3.07281614543321 -4.07281614543321e-16,3.12325770642185 -3.10120595370083 -4.10120595370083e-16,3.0 -3.13397459621556 -4.13397459621556e-16,2.88161419305851 -3.17096242744496 -4.17096242744496e-16,2.76867704934868 -3.21198924639328 -4.21198924639328e-16,2.66173878728228 -3.25685517452261 -4.25685517452261e-16,2.5613203993227 -3.305341629541 -4.305341629541e-16,2.46791111376204 -3.35721239031346 -4.35721239031346e-16,2.38196601125011 -3.41221474770753 -4.41221474770753e-16,2.30390380768715 -3.4700807357668 -4.4700807357668e-16,2.23410481428215 -3.53052843721411 -4.53052843721411e-16,2.1729090847148 -3.5932633569242 -4.5932633569242e-16,2.12061475842818 -3.65797985667433 -4.65797985667433e-16,2.07747660812336 -3.724362644183 -4.724362644183e-16,2.04370479853239 -3.79208830918224 -4.79208830918224e-16,2.01946386251686 -3.86082689903993 -4.86082689903993e-16,2.00487189948035 -3.93024352625587 -4.93024352625588e-16,2 -4 -5e-16)'): feat.DumpReadable() - return 'fail' + pytest.fail() # OGRFeature(entities):45 # EntityHandle (String) = 231 @@ -1844,7 +1613,7 @@ def ogr_dxf_31(): feat = lyr.GetNextFeature() if ogrtest.check_feature_geometry(feat, 'LINESTRING Z (2 -2 -2e-16,1.96657794502105 -2.03582232791524 -2.03582232791524e-16,1.93571660708646 -2.07387296203834 -2.07387296203834e-16,1.90756413746468 -2.11396923855472 -2.11396923855472e-16,1.88225568337755 -2.15591867344963 -2.15591867344963e-16,1.85991273921989 -2.19951988653655 -2.19951988653655e-16,1.84064256332004 -2.24456356819194 -2.24456356819194e-16,1.8245376630414 -2.29083348415575 -2.29083348415575e-16,1.81167535069652 -2.33810751357387 -2.33810751357387e-16,1.80211737240583 -2.38615871529951 -2.38615871529951e-16,1.79590961168258 -2.43475641733454 -2.43475641733454e-16,1.79308186916688 -2.48366732418105 -2.48366732418105e-16,1.79364771956639 -2.53265663678705 -2.53265663678705e-16,1.79760444649032 -2.58148917971011 -2.58148917971011e-16,1.80493305548955 -2.62993053008786 -2.62993053008786e-16,1.81559836524041 -2.67774814299567 -2.67774814299567e-16,1.8295491764342 -2.72471246778926 -2.72471246778926e-16,1.84671851756181 -2.7705980500731 -2.7705980500731e-16,1.86702396641357 -2.81518461400453 -2.81518461400453e-16,1.89036804575079 -2.85825811973811 -2.85825811973811e-16,1.91663869124976 -2.89961179093367 -2.89961179093367e-16,1.94570978947168 -2.93904710739563 -2.93904710739563e-16,1.97744178327594 -2.97637475807832 -2.97637475807832e-16,2.01168234177068 -3.01141554988232 -3.01141554988232e-16,2.04826709158413 -3.04400126787917 -3.04400126787917e-16,2.08702040594658 -3.07397548283483 -3.07397548283483e-16,2.12775624779472 -3.10119430215541 -3.10119430215541e-16,2.1702790628511 -3.12552706065018 -3.12552706065018e-16,2.2143847183914 -3.14685694779575 -3.14685694779575e-16,2.25986148319297 -3.16508156849045 -3.16508156849045e-16,2.30649104396024 -3.18011343460661 -3.18011343460661e-16,2.35404955334774 -3.1918803849814 -3.1918803849814e-16,2.40230870454951 -3.20032593182975 -3.20032593182975e-16,2.45103682729644 -3.2054095319166 -3.2054095319166e-16,2.5 -3.20710678118655 -3.20710678118655e-16,2.54896317270356 -3.2054095319166 -3.2054095319166e-16,2.59769129545049 -3.20032593182975 -3.20032593182975e-16,2.64595044665226 -3.1918803849814 -3.1918803849814e-16,2.69350895603976 -3.18011343460661 -3.18011343460661e-16,2.74013851680703 -3.16508156849045 -3.16508156849045e-16,2.7856152816086 -3.14685694779575 -3.14685694779575e-16,2.8297209371489 -3.12552706065018 -3.12552706065018e-16,2.87224375220528 -3.10119430215541 -3.10119430215541e-16,2.91297959405342 -3.07397548283483 -3.07397548283483e-16,2.95173290841587 -3.04400126787917 -3.04400126787917e-16,2.98831765822932 -3.01141554988232 -3.01141554988232e-16,3.02255821672406 -2.97637475807832 -2.97637475807832e-16,3.05429021052832 -2.93904710739563 -2.93904710739563e-16,3.08336130875024 -2.89961179093367 -2.89961179093367e-16,3.10963195424921 -2.85825811973811 -2.85825811973811e-16,3.13297603358643 -2.81518461400453 -2.81518461400453e-16,3.15328148243819 -2.7705980500731 -2.7705980500731e-16,3.1704508235658 -2.72471246778926 -2.72471246778926e-16,3.18440163475959 -2.67774814299567 -2.67774814299567e-16,3.19506694451045 -2.62993053008786 -2.62993053008786e-16,3.20239555350968 -2.58148917971011 -2.58148917971011e-16,3.20635228043361 -2.53265663678705 -2.53265663678705e-16,3.20691813083312 -2.48366732418105 -2.48366732418105e-16,3.20409038831742 -2.43475641733454 -2.43475641733454e-16,3.19788262759417 -2.38615871529951 -2.38615871529951e-16,3.18832464930348 -2.33810751357387 -2.33810751357387e-16,3.1754623369586 -2.29083348415575 -2.29083348415575e-16,3.15935743667996 -2.24456356819194 -2.24456356819194e-16,3.14008726078011 -2.19951988653655 -2.19951988653655e-16,3.11774431662245 -2.15591867344963 -2.15591867344963e-16,3.09243586253532 -2.11396923855472 -2.11396923855471e-16,3.06428339291354 -2.07387296203834 -2.07387296203834e-16,3.03342205497895 -2.03582232791524 -2.03582232791524e-16,3 -2 -2e-16)'): feat.DumpReadable() - return 'fail' + pytest.fail() # OGRFeature(entities):46 # EntityHandle (String) = 232 @@ -1852,7 +1621,7 @@ def ogr_dxf_31(): feat = lyr.GetNextFeature() if ogrtest.check_feature_geometry(feat, 'POLYGON Z ((1 -2 -2e-16,1 -3 -4e-16,2 -3 -4e-16,2 -2 -2e-16,1 -2 -2e-16))'): feat.DumpReadable() - return 'fail' + pytest.fail() # OGRFeature(entities):47 # EntityHandle (String) = 233 @@ -1860,7 +1629,7 @@ def ogr_dxf_31(): feat = lyr.GetNextFeature() if ogrtest.check_feature_geometry(feat, 'POLYGON ((3 -4,4 -4,4 -3,3 -3,3 -4))'): feat.DumpReadable() - return 'fail' + pytest.fail() # OGRFeature(entities):48 # EntityHandle (String) = 235 @@ -1868,7 +1637,7 @@ def ogr_dxf_31(): feat = lyr.GetNextFeature() if ogrtest.check_feature_geometry(feat, 'POLYGON ((8 -8,9 -8,9 -9,8 -9,8 -8))'): feat.DumpReadable() - return 'fail' + pytest.fail() # OGRFeature(entities):49 # EntityHandle (String) = 236 @@ -1876,7 +1645,7 @@ def ogr_dxf_31(): feat = lyr.GetNextFeature() if ogrtest.check_feature_geometry(feat, 'LINESTRING (2 -2,2.15384615384615 -2.15384615384615,2.30769230769231 -2.30769230769231,2.46153846153846 -2.46153846153846,2.61538461538461 -2.61538461538461,2.76923076923077 -2.76923076923077,2.92307692307692 -2.92307692307692,3.07692307692308 -3.07692307692308,3.23076923076923 -3.23076923076923,3.38461538461538 -3.38461538461538,3.53846153846154 -3.53846153846154,3.69230769230769 -3.69230769230769,3.84615384615385 -3.84615384615385,4 -4,4.15384615384615 -4.15384615384615,4.30769230769231 -4.30769230769231,4.46153846153846 -4.46153846153846,4.61538461538462 -4.61538461538462,4.76923076923077 -4.76923076923077,4.92307692307692 -4.92307692307692,5.07692307692308 -5.07692307692308,5.23076923076923 -5.23076923076923,5.38461538461538 -5.38461538461538,5.53846153846154 -5.53846153846154,5.69230769230769 -5.69230769230769,5.84615384615385 -5.84615384615385,6.0 -6.0,6.15384615384615 -6.15384615384615,6.30769230769231 -6.30769230769231,6.46153846153846 -6.46153846153846,6.61538461538462 -6.61538461538462,6.76923076923077 -6.76923076923077,6.92307692307692 -6.92307692307692,7.07692307692308 -7.07692307692308,7.23076923076923 -7.23076923076923,7.38461538461539 -7.38461538461539,7.53846153846154 -7.53846153846154,7.69230769230769 -7.69230769230769,7.84615384615385 -7.84615384615385,8 -8)'): feat.DumpReadable() - return 'fail' + pytest.fail() # OGRFeature(entities):50 # EntityHandle (String) = 237 @@ -1884,7 +1653,7 @@ def ogr_dxf_31(): feat = lyr.GetNextFeature() if ogrtest.check_feature_geometry(feat, 'LINESTRING (8 -1,7.62837370825536 -0.987348067229724,7.25775889681215 -0.975707614760869,6.88916704597178 -0.966090122894857,6.52360963603567 -0.959507071933107,6.16209814730525 -0.956969942177043,5.80564406008193 -0.959490213928084,5.45525885466714 -0.968079367487651,5.11195401136229 -0.983748883157167,4.77674101046882 -1.00751024123805,4.45063133228814 -1.04037492203173,4.13463645712167 -1.08335440583961,3.82976786527082 -1.13746017296313,3.53703703703704 -1.2037037037037,3.25745545272173 -1.28309647836275,2.99203459262631 -1.37664997724169,2.74178593705221 -1.48537568064195,2.50772096630085 -1.61028506886495,2.29085116067365 -1.75238962221211,2.09218800047203 -1.91270082098484,1.91270082098485 -2.09218800047202,1.75238962221211 -2.29085116067364,1.61028506886495 -2.50772096630085,1.48537568064195 -2.74178593705221,1.37664997724169 -2.99203459262631,1.28309647836275 -3.25745545272172,1.2037037037037 -3.53703703703703,1.13746017296313 -3.82976786527082,1.08335440583961 -4.13463645712166,1.04037492203173 -4.45063133228814,1.00751024123805 -4.77674101046882,0.983748883157167 -5.11195401136229,0.968079367487652 -5.45525885466714,0.959490213928084 -5.80564406008193,0.956969942177043 -6.16209814730525,0.959507071933108 -6.52360963603567,0.966090122894857 -6.88916704597178,0.975707614760869 -7.25775889681216,0.987348067229724 -7.62837370825537,1 -8)'): feat.DumpReadable() - return 'fail' + pytest.fail() # OGRFeature(entities):51 # EntityHandle (String) = 238 @@ -1892,15 +1661,14 @@ def ogr_dxf_31(): feat = lyr.GetNextFeature() if ogrtest.check_feature_geometry(feat, 'POINT Z (7 -7 -7e-16)'): feat.DumpReadable() - return 'fail' - - return 'success' + pytest.fail() + ############################################################################### # OCS2WCS transformations 2. Also test RawCodeValues -def ogr_dxf_32(): +def test_ogr_dxf_32(): gdal.SetConfigOption('DXF_INCLUDE_RAW_CODE_VALUES', 'TRUE') ds = ogr.Open('data/ocs2wcs2.dxf') @@ -1915,7 +1683,7 @@ def ogr_dxf_32(): feat = lyr.GetNextFeature() if ogrtest.check_feature_geometry(feat, 'POINT Z (4 4 0)'): feat.DumpReadable() - return 'fail' + pytest.fail() # OGRFeature(entities):1 # EntityHandle (String) = 1B2 @@ -1923,7 +1691,7 @@ def ogr_dxf_32(): feat = lyr.GetNextFeature() if ogrtest.check_feature_geometry(feat, 'LINESTRING Z (0 0 0,1 1 0)'): feat.DumpReadable() - return 'fail' + pytest.fail() # OGRFeature(entities):2 # EntityHandle (String) = 1B3 @@ -1932,7 +1700,7 @@ def ogr_dxf_32(): if ogrtest.check_feature_geometry(feat, 'LINESTRING (1 1,2 1,1 2,1 1)') \ or feat.GetField('RawCodeValues') != ['330 1F','43 0.0']: feat.DumpReadable() - return 'fail' + pytest.fail() # OGRFeature(entities):3 # EntityHandle (String) = 1B4 @@ -1941,7 +1709,7 @@ def ogr_dxf_32(): if ogrtest.check_feature_geometry(feat, 'LINESTRING Z (1 1 0,1 2 0,2 2 0,1 1 0)') \ or feat.GetField('RawCodeValues') != ['330 1F','66 1','10 0.0','20 0.0','30 0.0']: feat.DumpReadable() - return 'fail' + pytest.fail() # OGRFeature(entities):4 # EntityHandle (String) = 1B9 @@ -1949,7 +1717,7 @@ def ogr_dxf_32(): feat = lyr.GetNextFeature() if ogrtest.check_feature_geometry(feat, 'LINESTRING Z (6 4 0,5.99512810051965 3.86048705251175 0,5.98053613748314 3.72165379807987 0,5.95629520146761 3.58417661836448 0,5.92252339187664 3.448725288366 0,5.87938524157182 3.31595971334866 0,5.8270909152852 3.1865267138484 0,5.76589518571785 3.06105687442822 0,5.69609619231285 2.94016147153359 0,5.61803398874989 2.82442949541505 0,5.53208888623796 2.71442478062692 0,5.4386796006773 2.61068325908201 0,5.33826121271772 2.51371034904521 0,5.23132295065132 2.42397849278656 0,5.11838580694149 2.34192485488992 0,5.0 2.26794919243112 0,4.87674229357815 2.20241190740167 0,4.74921318683182 2.14563229086643 0,4.61803398874989 2.09788696740969 0,4.48384379119934 2.05940854744801 0,4.34729635533386 2.03038449397558 0,4.20905692653531 2.01095620926345 0,4.069798993405 2.00121834596181 0,3.930201006595 2.00121834596181 0,3.79094307346469 2.01095620926345 0,3.65270364466614 2.03038449397558 0,3.51615620880066 2.05940854744801 0,3.38196601125011 2.09788696740969 0,3.25078681316818 2.14563229086643 0,3.12325770642185 2.20241190740167 0,3.0 2.26794919243112 0,2.88161419305851 2.34192485488992 0,2.76867704934868 2.42397849278656 0,2.66173878728228 2.51371034904521 0,2.5613203993227 2.61068325908201 0,2.46791111376204 2.71442478062692 0,2.38196601125011 2.82442949541505 0,2.30390380768715 2.94016147153359 0,2.23410481428215 3.06105687442822 0,2.1729090847148 3.1865267138484 0,2.12061475842818 3.31595971334866 0,2.07747660812336 3.448725288366 0,2.04370479853239 3.58417661836448 0,2.01946386251686 3.72165379807987 0,2.00487189948035 3.86048705251175 0,2.0 4.0 0,2.00487189948035 4.13951294748825 0,2.01946386251686 4.27834620192013 0,2.04370479853239 4.41582338163552 0,2.07747660812336 4.551274711634 0,2.12061475842818 4.68404028665134 0,2.1729090847148 4.8134732861516 0,2.23410481428215 4.93894312557178 0,2.30390380768715 5.05983852846641 0,2.38196601125011 5.17557050458495 0,2.46791111376204 5.28557521937308 0,2.5613203993227 5.38931674091799 0,2.66173878728228 5.48628965095479 0,2.76867704934868 5.57602150721344 0,2.88161419305851 5.65807514511008 0,3.0 5.73205080756888 0,3.12325770642184 5.79758809259833 0,3.25078681316818 5.85436770913357 0,3.38196601125011 5.90211303259031 0,3.51615620880066 5.94059145255199 0,3.65270364466614 5.96961550602442 0,3.79094307346469 5.98904379073655 0,3.930201006595 5.99878165403819 0,4.069798993405 5.99878165403819 0,4.20905692653531 5.98904379073655 0,4.34729635533386 5.96961550602442 0,4.48384379119933 5.94059145255199 0,4.61803398874989 5.90211303259031 0,4.74921318683182 5.85436770913357 0,4.87674229357815 5.79758809259833 0,5.0 5.73205080756888 0,5.11838580694149 5.65807514511008 0,5.23132295065132 5.57602150721344 0,5.33826121271772 5.48628965095479 0,5.4386796006773 5.389316740918 0,5.53208888623796 5.28557521937308 0,5.61803398874989 5.17557050458495 0,5.69609619231285 5.05983852846641 0,5.76589518571785 4.93894312557178 0,5.8270909152852 4.8134732861516 0,5.87938524157182 4.68404028665134 0,5.92252339187664 4.551274711634 0,5.95629520146761 4.41582338163552 0,5.98053613748314 4.27834620192013 0,5.99512810051965 4.13951294748825 0,6.0 4.0 0)'): feat.DumpReadable() - return 'fail' + pytest.fail() # OGRFeature(entities):5 # EntityHandle (String) = 1BA @@ -1957,7 +1725,7 @@ def ogr_dxf_32(): feat = lyr.GetNextFeature() if ogrtest.check_feature_geometry(feat, 'LINESTRING Z (2 4 0,4 4 0)'): feat.DumpReadable() - return 'fail' + pytest.fail() # OGRFeature(entities):6 # EntityHandle (String) = 1BB @@ -1965,7 +1733,7 @@ def ogr_dxf_32(): feat = lyr.GetNextFeature() if ogrtest.check_feature_geometry(feat, 'LINESTRING Z (4 4 0,6 4 0)'): feat.DumpReadable() - return 'fail' + pytest.fail() # OGRFeature(entities):7 # EntityHandle (String) = 1BC @@ -1973,7 +1741,7 @@ def ogr_dxf_32(): feat = lyr.GetNextFeature() if ogrtest.check_feature_geometry(feat, 'LINESTRING Z (4 3 0,4 4 0)'): feat.DumpReadable() - return 'fail' + pytest.fail() # OGRFeature(entities):8 # EntityHandle (String) = 1BD @@ -1981,7 +1749,7 @@ def ogr_dxf_32(): feat = lyr.GetNextFeature() if ogrtest.check_feature_geometry(feat, 'LINESTRING Z (4 4 0,4 5 0)'): feat.DumpReadable() - return 'fail' + pytest.fail() # OGRFeature(entities):9 # EntityHandle (String) = 1BE @@ -1989,7 +1757,7 @@ def ogr_dxf_32(): feat = lyr.GetNextFeature() if ogrtest.check_feature_geometry(feat, 'LINESTRING Z (2 4 0,2.00487189948035 4.06975647374412 0,2.01946386251686 4.13917310096007 0,2.04370479853239 4.20791169081776 0,2.07747660812336 4.275637355817 0,2.12061475842818 4.34202014332567 0,2.1729090847148 4.4067366430758 0,2.23410481428215 4.46947156278589 0,2.30390380768715 4.52991926423321 0,2.38196601125011 4.58778525229247 0,2.46791111376204 4.64278760968654 0,2.5613203993227 4.694658370459 0,2.66173878728228 4.74314482547739 0,2.76867704934868 4.78801075360672 0,2.88161419305851 4.82903757255504 0,3.0 4.86602540378444 0,3.12325770642185 4.89879404629917 0,3.25078681316818 4.92718385456679 0,3.38196601125011 4.95105651629515 0,3.51615620880067 4.970295726276 0,3.65270364466614 4.98480775301221 0,3.79094307346469 4.99452189536827 0,3.930201006595 4.9993908270191 0,4.069798993405 4.9993908270191 0,4.20905692653531 4.99452189536827 0,4.34729635533386 4.98480775301221 0,4.48384379119934 4.970295726276 0,4.61803398874989 4.95105651629515 0,4.74921318683182 4.92718385456679 0,4.87674229357816 4.89879404629917 0,5.0 4.86602540378444 0,5.11838580694149 4.82903757255504 0,5.23132295065132 4.78801075360672 0,5.33826121271772 4.74314482547739 0,5.4386796006773 4.694658370459 0,5.53208888623796 4.64278760968654 0,5.61803398874989 4.58778525229247 0,5.69609619231285 4.5299192642332 0,5.76589518571785 4.46947156278589 0,5.8270909152852 4.4067366430758 0,5.87938524157182 4.34202014332567 0,5.92252339187664 4.275637355817 0,5.95629520146761 4.20791169081776 0,5.98053613748314 4.13917310096006 0,5.99512810051965 4.06975647374412 0,6.0 4.0 0,5.99512810051965 3.93024352625587 0,5.98053613748314 3.86082689903993 0,5.95629520146761 3.79208830918224 0,5.92252339187664 3.724362644183 0,5.87938524157182 3.65797985667433 0,5.8270909152852 3.5932633569242 0,5.76589518571785 3.53052843721411 0,5.69609619231285 3.4700807357668 0,5.61803398874989 3.41221474770753 0,5.53208888623796 3.35721239031346 0,5.4386796006773 3.305341629541 0,5.33826121271772 3.25685517452261 0,5.23132295065132 3.21198924639328 0,5.11838580694149 3.17096242744496 0,5.0 3.13397459621556 0,4.87674229357815 3.10120595370083 0,4.74921318683182 3.07281614543321 0,4.61803398874989 3.04894348370485 0,4.48384379119934 3.029704273724 0,4.34729635533386 3.01519224698779 0,4.20905692653531 3.00547810463173 0,4.069798993405 3.0006091729809 0,3.930201006595 3.0006091729809 0,3.79094307346469 3.00547810463173 0,3.65270364466614 3.01519224698779 0,3.51615620880066 3.029704273724 0,3.38196601125011 3.04894348370485 0,3.25078681316818 3.07281614543321 0,3.12325770642185 3.10120595370083 0,3.0 3.13397459621556 0,2.88161419305851 3.17096242744496 0,2.76867704934868 3.21198924639328 0,2.66173878728228 3.25685517452261 0,2.5613203993227 3.305341629541 0,2.46791111376204 3.35721239031346 0,2.38196601125011 3.41221474770753 0,2.30390380768715 3.4700807357668 0,2.23410481428215 3.53052843721411 0,2.1729090847148 3.5932633569242 0,2.12061475842818 3.65797985667433 0,2.07747660812336 3.724362644183 0,2.04370479853239 3.79208830918224 0,2.01946386251686 3.86082689903993 0,2.00487189948035 3.93024352625587 0,2 4 0)'): feat.DumpReadable() - return 'fail' + pytest.fail() # OGRFeature(entities):10 # EntityHandle (String) = 1BF @@ -1997,7 +1765,7 @@ def ogr_dxf_32(): feat = lyr.GetNextFeature() if ogrtest.check_feature_geometry(feat, 'LINESTRING Z (2.0 2.0 0,1.96657794502105 2.03582232791524 0,1.93571660708646 2.07387296203834 0,1.90756413746468 2.11396923855471 0,1.88225568337755 2.15591867344963 0,1.85991273921989 2.19951988653655 0,1.84064256332004 2.24456356819194 0,1.8245376630414 2.29083348415575 0,1.81167535069652 2.33810751357387 0,1.80211737240583 2.38615871529951 0,1.79590961168258 2.43475641733454 0,1.79308186916688 2.48366732418105 0,1.79364771956639 2.53265663678705 0,1.79760444649032 2.58148917971011 0,1.80493305548955 2.62993053008785 0,1.81559836524041 2.67774814299566 0,1.8295491764342 2.72471246778926 0,1.84671851756181 2.7705980500731 0,1.86702396641357 2.81518461400453 0,1.89036804575079 2.85825811973811 0,1.91663869124976 2.89961179093366 0,1.94570978947168 2.93904710739563 0,1.97744178327594 2.97637475807832 0,2.01168234177068 3.01141554988232 0,2.04826709158413 3.04400126787917 0,2.08702040594658 3.07397548283483 0,2.12775624779472 3.10119430215541 0,2.17027906285109 3.12552706065018 0,2.2143847183914 3.14685694779575 0,2.25986148319297 3.16508156849045 0,2.30649104396024 3.18011343460661 0,2.35404955334774 3.1918803849814 0,2.40230870454951 3.20032593182975 0,2.45103682729644 3.2054095319166 0,2.5 3.20710678118655 0,2.54896317270356 3.2054095319166 0,2.59769129545049 3.20032593182975 0,2.64595044665226 3.1918803849814 0,2.69350895603976 3.18011343460661 0,2.74013851680703 3.16508156849045 0,2.7856152816086 3.14685694779575 0,2.8297209371489 3.12552706065018 0,2.87224375220528 3.10119430215541 0,2.91297959405342 3.07397548283483 0,2.95173290841587 3.04400126787917 0,2.98831765822932 3.01141554988232 0,3.02255821672406 2.97637475807832 0,3.05429021052832 2.93904710739563 0,3.08336130875024 2.89961179093367 0,3.10963195424921 2.85825811973811 0,3.13297603358643 2.81518461400453 0,3.15328148243819 2.7705980500731 0,3.1704508235658 2.72471246778926 0,3.18440163475959 2.67774814299567 0,3.19506694451045 2.62993053008786 0,3.20239555350968 2.58148917971011 0,3.20635228043361 2.53265663678705 0,3.20691813083312 2.48366732418105 0,3.20409038831742 2.43475641733454 0,3.19788262759417 2.38615871529951 0,3.18832464930348 2.33810751357387 0,3.1754623369586 2.29083348415575 0,3.15935743667996 2.24456356819194 0,3.14008726078011 2.19951988653655 0,3.11774431662245 2.15591867344963 0,3.09243586253532 2.11396923855472 0,3.06428339291354 2.07387296203834 0,3.03342205497895 2.03582232791524 0,3 2 0)'): feat.DumpReadable() - return 'fail' + pytest.fail() # OGRFeature(entities):11 # EntityHandle (String) = 1C0 @@ -2005,7 +1773,7 @@ def ogr_dxf_32(): feat = lyr.GetNextFeature() if ogrtest.check_feature_geometry(feat, 'POLYGON Z ((1 2 0,1 3 0,2 3 0,2 2 0,1 2 0))'): feat.DumpReadable() - return 'fail' + pytest.fail() # OGRFeature(entities):12 # EntityHandle (String) = 1C1 @@ -2013,7 +1781,7 @@ def ogr_dxf_32(): feat = lyr.GetNextFeature() if ogrtest.check_feature_geometry(feat, 'POLYGON ((3 4,4 4,4 3,3 3,3 4))'): feat.DumpReadable() - return 'fail' + pytest.fail() # OGRFeature(entities):13 # EntityHandle (String) = 1C3 @@ -2021,7 +1789,7 @@ def ogr_dxf_32(): feat = lyr.GetNextFeature() if ogrtest.check_feature_geometry(feat, 'POLYGON ((8 8,9 8,9 9,8 9,8 8))'): feat.DumpReadable() - return 'fail' + pytest.fail() # OGRFeature(entities):14 # EntityHandle (String) = 1C6 @@ -2029,7 +1797,7 @@ def ogr_dxf_32(): feat = lyr.GetNextFeature() if ogrtest.check_feature_geometry(feat, 'LINESTRING (2 2,2.15384615384615 2.15384615384615,2.30769230769231 2.30769230769231,2.46153846153846 2.46153846153846,2.61538461538461 2.61538461538461,2.76923076923077 2.76923076923077,2.92307692307692 2.92307692307692,3.07692307692308 3.07692307692308,3.23076923076923 3.23076923076923,3.38461538461538 3.38461538461538,3.53846153846154 3.53846153846154,3.69230769230769 3.69230769230769,3.84615384615385 3.84615384615385,4 4,4.15384615384615 4.15384615384615,4.30769230769231 4.30769230769231,4.46153846153846 4.46153846153846,4.61538461538462 4.61538461538462,4.76923076923077 4.76923076923077,4.92307692307692 4.92307692307692,5.07692307692308 5.07692307692308,5.23076923076923 5.23076923076923,5.38461538461538 5.38461538461538,5.53846153846154 5.53846153846154,5.69230769230769 5.69230769230769,5.84615384615385 5.84615384615385,6.0 6.0,6.15384615384615 6.15384615384615,6.30769230769231 6.30769230769231,6.46153846153846 6.46153846153846,6.61538461538462 6.61538461538462,6.76923076923077 6.76923076923077,6.92307692307692 6.92307692307692,7.07692307692308 7.07692307692308,7.23076923076923 7.23076923076923,7.38461538461539 7.38461538461539,7.53846153846154 7.53846153846154,7.69230769230769 7.69230769230769,7.84615384615385 7.84615384615385,8 8)'): feat.DumpReadable() - return 'fail' + pytest.fail() # OGRFeature(entities):15 # EntityHandle (String) = 1C7 @@ -2037,7 +1805,7 @@ def ogr_dxf_32(): feat = lyr.GetNextFeature() if ogrtest.check_feature_geometry(feat, 'LINESTRING (8 1,7.62837370825536 0.987348067229724,7.25775889681215 0.975707614760869,6.88916704597178 0.966090122894857,6.52360963603567 0.959507071933107,6.16209814730525 0.956969942177043,5.80564406008193 0.959490213928084,5.45525885466714 0.968079367487651,5.11195401136229 0.983748883157167,4.77674101046882 1.00751024123805,4.45063133228814 1.04037492203173,4.13463645712167 1.08335440583961,3.82976786527082 1.13746017296313,3.53703703703704 1.2037037037037,3.25745545272173 1.28309647836275,2.99203459262631 1.37664997724169,2.74178593705221 1.48537568064195,2.50772096630085 1.61028506886495,2.29085116067365 1.75238962221211,2.09218800047203 1.91270082098484,1.91270082098485 2.09218800047202,1.75238962221211 2.29085116067364,1.61028506886495 2.50772096630085,1.48537568064195 2.74178593705221,1.37664997724169 2.99203459262631,1.28309647836275 3.25745545272172,1.2037037037037 3.53703703703703,1.13746017296313 3.82976786527082,1.08335440583961 4.13463645712166,1.04037492203173 4.45063133228814,1.00751024123805 4.77674101046882,0.983748883157167 5.11195401136229,0.968079367487652 5.45525885466714,0.959490213928084 5.80564406008193,0.956969942177043 6.16209814730525,0.959507071933108 6.52360963603567,0.966090122894857 6.88916704597178,0.975707614760869 7.25775889681216,0.987348067229724 7.62837370825537,1 8)'): feat.DumpReadable() - return 'fail' + pytest.fail() # OGRFeature(entities):16 # EntityHandle (String) = 1C8 @@ -2045,7 +1813,7 @@ def ogr_dxf_32(): feat = lyr.GetNextFeature() if ogrtest.check_feature_geometry(feat, 'POINT Z (7 7 0)'): feat.DumpReadable() - return 'fail' + pytest.fail() # OGRFeature(entities):17 # EntityHandle (String) = 1C9 @@ -2053,7 +1821,7 @@ def ogr_dxf_32(): feat = lyr.GetNextFeature() if ogrtest.check_feature_geometry(feat, 'POINT Z (-2.0 4.0 -3.46410161513775)'): feat.DumpReadable() - return 'fail' + pytest.fail() # OGRFeature(entities):18 # EntityHandle (String) = 1CA @@ -2061,7 +1829,7 @@ def ogr_dxf_32(): feat = lyr.GetNextFeature() if ogrtest.check_feature_geometry(feat, 'LINESTRING Z (0 0 0,-0.5 1.0 -0.866025403784439)'): feat.DumpReadable() - return 'fail' + pytest.fail() # OGRFeature(entities):19 # EntityHandle (String) = 1CB @@ -2069,7 +1837,7 @@ def ogr_dxf_32(): feat = lyr.GetNextFeature() if ogrtest.check_feature_geometry(feat, 'LINESTRING Z (-0.5 1.0 -0.866025403784439,-1.0 1.0 -1.73205080756888,-0.5 2.0 -0.866025403784439,-0.5 1.0 -0.866025403784439)'): feat.DumpReadable() - return 'fail' + pytest.fail() # OGRFeature(entities):20 # EntityHandle (String) = 1CC @@ -2077,7 +1845,7 @@ def ogr_dxf_32(): feat = lyr.GetNextFeature() if ogrtest.check_feature_geometry(feat, 'LINESTRING Z (-0.5 1.0 -0.866025403784439,-0.5 2.0 -0.866025403784439,-1.0 2.0 -1.73205080756888,-0.5 1.0 -0.866025403784439)'): feat.DumpReadable() - return 'fail' + pytest.fail() # OGRFeature(entities):21 # EntityHandle (String) = 1D1 @@ -2087,7 +1855,7 @@ def ogr_dxf_32(): if ogrtest.check_feature_geometry(feat, 'LINESTRING Z (-2.0 6.0 -3.46410161513776,-2.06975647374412 5.99512810051965 -3.58492337181942,-2.13917310096006 5.98053613748314 -3.7051564970475,-2.20791169081776 5.95629520146761 -3.82421522712167,-2.275637355817 5.92252339187664 -3.94151951987674,-2.34202014332567 5.87938524157182 -4.0564978805898,-2.4067366430758 5.8270909152852 -4.16859014624505,-2.46947156278589 5.76589518571785 -4.27725021459168,-2.5299192642332 5.69609619231285 -4.38194870469918,-2.58778525229247 5.61803398874989 -4.48217553604801,-2.64278760968654 5.53208888623796 -4.57744241359059,-2.694658370459 5.4386796006773 -4.66728520667574,-2.74314482547739 5.33826121271772 -4.75126621024651,-2.78801075360672 5.23132295065132 -4.82897627729524,-2.82903757255504 5.11838580694149 -4.90003681218666,-2.86602540378444 5.0 -4.96410161513776,-2.89879404629917 4.87674229357815 -5.02085856886833,-2.92718385456679 4.74921318683182 -5.07003115920498,-2.95105651629515 4.61803398874989 -5.11137982223042,-2.970295726276 4.48384379119934 -5.14470311141473,-2.98480775301221 4.34729635533386 -5.16983867904264,-2.99452189536827 4.20905692653531 -5.1866640671553,-2.99939082701909 4.069798993405 -5.19509730415311,-2.99939082701909 3.930201006595 -5.19509730415311,-2.99452189536827 3.79094307346469 -5.1866640671553,-2.98480775301221 3.65270364466614 -5.16983867904264,-2.970295726276 3.51615620880066 -5.14470311141473,-2.95105651629515 3.38196601125011 -5.11137982223042,-2.92718385456679 3.25078681316818 -5.07003115920498,-2.89879404629917 3.12325770642185 -5.02085856886833,-2.86602540378444 3.0 -4.96410161513776,-2.82903757255504 2.88161419305851 -4.90003681218666,-2.78801075360672 2.76867704934868 -4.82897627729524,-2.74314482547739 2.66173878728228 -4.75126621024651,-2.694658370459 2.5613203993227 -4.66728520667574,-2.64278760968654 2.46791111376204 -4.5774424135906,-2.58778525229247 2.38196601125011 -4.48217553604801,-2.5299192642332 2.30390380768715 -4.38194870469918,-2.46947156278589 2.23410481428215 -4.27725021459168,-2.4067366430758 2.1729090847148 -4.16859014624505,-2.34202014332567 2.12061475842818 -4.0564978805898,-2.275637355817 2.07747660812336 -3.94151951987674,-2.20791169081776 2.04370479853239 -3.82421522712167,-2.13917310096006 2.01946386251686 -3.7051564970475,-2.06975647374412 2.00487189948035 -3.58492337181943,-2.0 2.0 -3.46410161513776,-1.93024352625587 2.00487189948035 -3.34327985845609,-1.86082689903993 2.01946386251686 -3.22304673322801,-1.79208830918224 2.04370479853239 -3.10398800315384,-1.724362644183 2.07747660812336 -2.98668371039877,' + '-1.65797985667433 2.12061475842818 -2.87170534968571,-1.5932633569242 2.1729090847148 -2.75961308403046,-1.53052843721411 2.23410481428215 -2.65095301568383,-1.47008073576679 2.30390380768715 -2.54625452557633,-1.41221474770753 2.38196601125011 -2.4460276942275,-1.35721239031346 2.46791111376204 -2.35076081668492,-1.305341629541 2.5613203993227 -2.26091802359977,-1.25685517452261 2.66173878728228 -2.176937020029,-1.21198924639328 2.76867704934868 -2.09922695298027,-1.17096242744496 2.88161419305851 -2.02816641808885,-1.13397459621556 3.0 -1.96410161513776,-1.10120595370083 3.12325770642184 -1.90734466140718,-1.07281614543321 3.25078681316818 -1.85817207107053,-1.04894348370485 3.38196601125011 -1.81682340804509,-1.029704273724 3.51615620880066 -1.78350011886079,-1.01519224698779 3.65270364466614 -1.75836455123287,-1.00547810463173 3.79094307346469 -1.74153916312021,-1.0006091729809 3.930201006595 -1.7331059261224,-1.0006091729809 4.069798993405 -1.7331059261224,-1.00547810463173 4.20905692653531 -1.74153916312021,-1.01519224698779 4.34729635533386 -1.75836455123287,-1.029704273724 4.48384379119933 -1.78350011886078,-1.04894348370485 4.61803398874989 -1.81682340804509,-1.07281614543321 4.74921318683182 -1.85817207107053,-1.10120595370083 4.87674229357815 -1.90734466140718,-1.13397459621556 5.0 -1.96410161513776,-1.17096242744496 5.11838580694149 -2.02816641808885,-1.21198924639328 5.23132295065132 -2.09922695298027,-1.25685517452261 5.33826121271772 -2.176937020029,-1.305341629541 5.4386796006773 -2.26091802359977,-1.35721239031346 5.53208888623796 -2.35076081668492,-1.41221474770753 5.61803398874989 -2.4460276942275,-1.47008073576679 5.69609619231285 -2.54625452557633,-1.53052843721411 5.76589518571785 -2.65095301568383,-1.5932633569242 5.8270909152852 -2.75961308403046,-1.65797985667433 5.87938524157182 -2.87170534968571,-1.724362644183 5.92252339187664 -2.98668371039877,-1.79208830918224 5.95629520146761 -3.10398800315384,-1.86082689903993 5.98053613748314 -3.22304673322801,-1.93024352625587 5.99512810051965 -3.34327985845609,-2.0 6.0 -3.46410161513775)'): feat.DumpReadable() - return 'fail' + pytest.fail() # OGRFeature(entities):22 # EntityHandle (String) = 1D2 @@ -2095,7 +1863,7 @@ def ogr_dxf_32(): feat = lyr.GetNextFeature() if ogrtest.check_feature_geometry(feat, 'LINESTRING Z (-1.0 4.0 -1.73205080756888,-2.0 4.0 -3.46410161513775)'): feat.DumpReadable() - return 'fail' + pytest.fail() # OGRFeature(entities):23 # EntityHandle (String) = 1D3 @@ -2103,7 +1871,7 @@ def ogr_dxf_32(): feat = lyr.GetNextFeature() if ogrtest.check_feature_geometry(feat, 'LINESTRING Z (-2.0 4.0 -3.46410161513775,-3.0 4.0 -5.19615242270663)'): feat.DumpReadable() - return 'fail' + pytest.fail() # OGRFeature(entities):24 # EntityHandle (String) = 1D4 @@ -2111,7 +1879,7 @@ def ogr_dxf_32(): feat = lyr.GetNextFeature() if ogrtest.check_feature_geometry(feat, 'LINESTRING Z (-2.0 3.0 -3.46410161513775,-2.0 4.0 -3.46410161513775)'): feat.DumpReadable() - return 'fail' + pytest.fail() # OGRFeature(entities):25 # EntityHandle (String) = 1D5 @@ -2119,7 +1887,7 @@ def ogr_dxf_32(): feat = lyr.GetNextFeature() if ogrtest.check_feature_geometry(feat, 'LINESTRING Z (-2.0 4.0 -3.46410161513775,-2.0 5.0 -3.46410161513775)'): feat.DumpReadable() - return 'fail' + pytest.fail() # OGRFeature(entities):26 # EntityHandle (String) = 1D6 @@ -2129,7 +1897,7 @@ def ogr_dxf_32(): if ogrtest.check_feature_geometry(feat, 'LINESTRING Z (-1.0 4.0 -1.73205080756888,-1.00243594974018 4.06975647374412 -1.73626999628355,-1.00973193125843 4.13917310096007 -1.74890700696425,-1.02185239926619 4.20791169081776 -1.76990027336521,-1.03873830406168 4.275637355817 -1.79914751840276,-1.06030737921409 4.34202014332567 -1.83650625243901,-1.0864545423574 4.4067366430758 -1.88179446747701,-1.11705240714107 4.46947156278589 -1.93479152388545,-1.15195190384357 4.52991926423321 -1.99523922533277,-1.19098300562505 4.58778525229247 -2.06284307669368,-1.23395555688102 4.64278760968654 -2.13727371879988,-1.28066019966135 4.694658370459 -2.21816853304476,-1.33086939364114 4.74314482547739 -2.30513340802484,-1.38433852467434 4.78801075360672 -2.3977446596109,-1.44080709652925 4.82903757255504 -2.49555109509446,-1.5 4.86602540378444 -2.59807621135332,-1.56162885321092 4.89879404629917 -2.70482051632684,-1.62539340658409 4.92718385456679 -2.8152639624911,-1.69098300562505 4.95105651629515 -2.92886848047812,-1.75807810440033 4.970295726276 -3.04508060049576,-1.82635182233307 4.98480775301221 -3.16333414877688,-1.89547153673235 4.99452189536827 -3.28305300592108,-1.9651005032975 4.99939082701909 -3.40365391369044,-2.0348994967025 4.99939082701909 -3.52454931658507,-2.10452846326765 4.99452189536827 -3.64515022435443,-2.17364817766693 4.98480775301221 -3.76486908149863,-2.24192189559967 4.970295726276 -3.88312262977975,-2.30901699437495 4.95105651629515 -3.99933474979739,-2.37460659341591 4.92718385456679 -4.11293926778441,-2.43837114678908 4.89879404629917 -4.22338271394867,-2.5 4.86602540378444 -4.33012701892219,-2.55919290347075 4.82903757255504 -4.43265213518105,-2.61566147532566 4.78801075360672 -4.53045857066461,-2.66913060635886 4.74314482547739 -4.62306982225067,-2.71933980033865 4.694658370459 -4.71003469723075,-2.76604444311898 4.64278760968654 -4.79092951147563,-2.80901699437495 4.58778525229247 -4.86536015358183,-2.84804809615642 4.5299192642332 -4.93296400494274,-2.88294759285893 4.46947156278589 -4.99341170639005,-2.9135454576426 4.4067366430758 -5.0464087627985,-2.93969262078591 4.34202014332567 -5.0916969778365,-2.96126169593832 4.275637355817 -5.12905571187275,-2.9781476007338 4.20791169081776 -5.1583029569103,-2.99026806874157 4.13917310096007 -5.17929622331126,-2.99756405025982 4.06975647374412 -5.19193323399196,-3.0 4.0 -5.19615242270663,-2.99756405025982 3.93024352625587 -5.19193323399196,-2.99026806874157 3.86082689903993 -5.17929622331126,-2.9781476007338 3.79208830918224 -5.1583029569103,-2.96126169593832 3.724362644183 -5.12905571187275,' + '-2.93969262078591 3.65797985667433 -5.0916969778365,-2.9135454576426 3.5932633569242 -5.0464087627985,-2.88294759285893 3.53052843721411 -4.99341170639005,-2.84804809615642 3.4700807357668 -4.93296400494274,-2.80901699437495 3.41221474770753 -4.86536015358183,-2.76604444311898 3.35721239031346 -4.79092951147563,-2.71933980033865 3.305341629541 -4.71003469723075,-2.66913060635886 3.25685517452261 -4.62306982225067,-2.61566147532566 3.21198924639328 -4.53045857066461,-2.55919290347075 3.17096242744496 -4.43265213518105,-2.5 3.13397459621556 -4.33012701892219,-2.43837114678908 3.10120595370083 -4.22338271394867,-2.37460659341591 3.07281614543321 -4.11293926778441,-2.30901699437495 3.04894348370485 -3.99933474979739,-2.24192189559967 3.029704273724 -3.88312262977975,-2.17364817766693 3.01519224698779 -3.76486908149863,-2.10452846326765 3.00547810463173 -3.64515022435443,-2.0348994967025 3.0006091729809 -3.52454931658507,-1.9651005032975 3.0006091729809 -3.40365391369044,-1.89547153673235 3.00547810463173 -3.28305300592108,-1.82635182233307 3.01519224698779 -3.16333414877688,-1.75807810440033 3.029704273724 -3.04508060049576,-1.69098300562505 3.04894348370485 -2.92886848047812,-1.62539340658409 3.07281614543321 -2.8152639624911,-1.56162885321092 3.10120595370083 -2.70482051632684,-1.5 3.13397459621556 -2.59807621135332,-1.44080709652925 3.17096242744496 -2.49555109509446,-1.38433852467434 3.21198924639328 -2.3977446596109,-1.33086939364114 3.25685517452261 -2.30513340802484,-1.28066019966135 3.305341629541 -2.21816853304476,-1.23395555688102 3.35721239031346 -2.13727371879988,-1.19098300562505 3.41221474770753 -2.06284307669368,-1.15195190384357 3.4700807357668 -1.99523922533277,-1.11705240714107 3.53052843721411 -1.93479152388545,-1.0864545423574 3.5932633569242 -1.88179446747701,-1.06030737921409 3.65797985667433 -1.83650625243901,-1.03873830406168 3.724362644183 -1.79914751840276,-1.02185239926619 3.79208830918224 -1.76990027336521,-1.00973193125843 3.86082689903993 -1.74890700696425,-1.00243594974018 3.93024352625587 -1.73626999628355,-1.0 4.0 -1.73205080756888)'): feat.DumpReadable() - return 'fail' + pytest.fail() # OGRFeature(entities):27 # EntityHandle (String) = 1D7 @@ -2137,7 +1905,7 @@ def ogr_dxf_32(): feat = lyr.GetNextFeature() if ogrtest.check_feature_geometry(feat, 'LINESTRING Z (-1.0 2.0 -1.73205080756888,-0.983288972510522 2.03582232791524 -1.70310645891042,-0.967858303543227 2.07387296203834 -1.67637975626429,-0.953782068732337 2.11396923855472 -1.65199900239256,-0.941127841688774 2.15591867344963 -1.6300812382226,-0.929956369609942 2.19951988653655 -1.61073168098672,-0.92032128166002 2.24456356819194 -1.59404321912206,-0.912268831520699 2.29083348415575 -1.58009596635534,-0.905837675348257 2.33810751357387 -1.56895687711326,-0.901058686202915 2.38615871529951 -1.56067942510471,-0.89795480584129 2.43475641733454 -1.55530334661776,-0.896540934583439 2.48366732418105 -1.5528544497638,-0.896823859783196 2.53265663678705 -1.55334449058452,-0.898802223245158 2.58148917971011 -1.55677111661648,-0.902466527744776 2.62993053008786 -1.56311787818422,-0.907799182620207 2.67774814299567 -1.5723543073677,-0.9147745882171 2.72471246778926 -1.58443606426492,-0.923359258780906 2.7705980500731 -1.59930514984767,-0.933511983206783 2.81518461400453 -1.61689018438853,-0.945184022875394 2.85825811973811 -1.63710675012253,-0.958319345624882 2.89961179093367 -1.65985779649846,-0.972854894735838 2.93904710739563 -1.68503410607454,-0.988720891637972 2.97637475807832 -1.71251481882177,-1.00584117088534 3.01141554988232 -1.74216801231798,-1.02413354579207 3.04400126787917 -1.77385133504753,-1.04351020297329 3.07397548283483 -1.80741268976625,-1.06387812389736 3.10119430215541 -1.84269096365129,-1.08513953142555 3.12552706065018 -1.87951680173053,-1.1071923591957 3.14685694779575 -1.917713419879,-1.12993074159648 3.16508156849045 -1.95709745347909,-1.15324552198012 3.18011343460661 -1.99747983767086,-1.17702477667387 3.1918803849814 -2.03866671496655,-1.20115435227475 3.20032593182975 -2.08046036587236,-1.22551841364822 3.2054095319166 -2.12266015804993,-1.25 3.20710678118655 -2.1650635094611,-1.27448158635178 3.2054095319166 -2.20746686087227,-1.29884564772525 3.20032593182975 -2.24966665304983,-1.32297522332613 3.1918803849814 -2.29146030395564,-1.34675447801988 3.18011343460661 -2.33264718125133,-1.37006925840352 3.16508156849045 -2.3730295654431,-1.3928076408043 3.14685694779575 -2.41241359904319,-1.41486046857445 3.12552706065018 -2.45061021719166,-1.43612187610264 3.10119430215541 -2.48743605527091,-1.45648979702671 3.07397548283483 -2.52271432915594,-1.47586645420793 3.04400126787917 -2.55627568387467,-1.49415882911466 3.01141554988232 -2.58795900660421,-1.51127910836203 2.97637475807832 -2.61761220010042,-1.52714510526416 2.93904710739563 -2.64509291284765,-1.54168065437512 2.89961179093367 -2.67026922242374,-1.55481597712461 2.85825811973811 -2.69302026879967,-1.56648801679322 2.81518461400453 -2.71323683453366,-1.57664074121909 2.7705980500731 -2.73082186907453,-1.5852254117829 2.72471246778926 -2.74569095465728,-1.59220081737979 2.67774814299567 -2.7577727115545,-1.59753347225522 2.62993053008785 -2.76700914073797,-1.60119777675484 2.58148917971011 -2.77335590230571,-1.6031761402168 2.53265663678705 -2.77678252833767,-1.60345906541656 2.48366732418105 -2.77727256915839,-1.60204519415871 2.43475641733454 -2.77482367230443,-1.59894131379708 2.38615871529951 -2.76944759381748,-1.59416232465174 2.33810751357387 -2.76117014180893,-1.5877311684793 2.29083348415575 -2.75003105256685,-1.57967871833998 2.24456356819194 -2.73608379980013,-1.57004363039006 2.19951988653655 -2.71939533793547,-1.55887215831123 2.15591867344963 -2.7000457806996,-1.54621793126766 2.11396923855472 -2.67812801652963,-1.53214169645677 2.07387296203834 -2.6537472626579,-1.51671102748948 2.03582232791524 -2.62702056001177,-1.5 2.0 -2.59807621135332)'): feat.DumpReadable() - return 'fail' + pytest.fail() # OGRFeature(entities):28 # EntityHandle (String) = 1D8 @@ -2145,7 +1913,7 @@ def ogr_dxf_32(): feat = lyr.GetNextFeature() if ogrtest.check_feature_geometry(feat, 'POLYGON Z ((-0.5 2.0 -0.866025403784439,-0.5 3.0 -0.866025403784439,-1.0 3.0 -1.73205080756888,-1.0 2.0 -1.73205080756888,-0.5 2.0 -0.866025403784439))'): feat.DumpReadable() - return 'fail' + pytest.fail() # OGRFeature(entities):29 # EntityHandle (String) = 1D9 @@ -2153,7 +1921,7 @@ def ogr_dxf_32(): feat = lyr.GetNextFeature() if ogrtest.check_feature_geometry(feat, 'POLYGON ((-1.5 4.0 -2.59807621135332,-2.0 4.0 -3.46410161513776,-2.0 3.0 -3.46410161513776,-1.5 3.0 -2.59807621135332,-1.5 4.0 -2.59807621135332))'): feat.DumpReadable() - return 'fail' + pytest.fail() # OGRFeature(entities):30 # EntityHandle (String) = 1DB @@ -2161,7 +1929,7 @@ def ogr_dxf_32(): feat = lyr.GetNextFeature() if ogrtest.check_feature_geometry(feat, 'POLYGON Z ((-4.0 8.0 -6.92820323027551,-4.5 8.0 -7.79422863405995,-4.5 9.0 -7.79422863405995,-4.0 9.0 -6.92820323027551,-4.0 8.0 -6.92820323027551))'): feat.DumpReadable() - return 'fail' + pytest.fail() # OGRFeature(entities):31 # EntityHandle (String) = 1DC @@ -2169,7 +1937,7 @@ def ogr_dxf_32(): feat = lyr.GetNextFeature() if ogrtest.check_feature_geometry(feat, 'LINESTRING (-1.0 2.0,-1.07692307692308 2.15384615384615,-1.15384615384615 2.30769230769231,-1.23076923076923 2.46153846153846,-1.30769230769231 2.61538461538461,-1.38461538461538 2.76923076923077,-1.46153846153846 2.92307692307692,-1.53846153846154 3.07692307692308,-1.61538461538461 3.23076923076923,-1.69230769230769 3.38461538461538,-1.76923076923077 3.53846153846154,-1.84615384615384 3.69230769230769,-1.92307692307692 3.84615384615385,-2.0 4.0,-2.07692307692307 4.15384615384615,-2.15384615384615 4.30769230769231,-2.23076923076923 4.46153846153846,-2.30769230769231 4.61538461538462,-2.38461538461538 4.76923076923077,-2.46153846153846 4.92307692307692,-2.53846153846154 5.07692307692308,-2.61538461538461 5.23076923076923,-2.69230769230769 5.38461538461538,-2.76923076923077 5.53846153846154,-2.84615384615384 5.69230769230769,-2.92307692307692 5.84615384615385,-3.0 6.0,-3.07692307692308 6.15384615384615,-3.15384615384615 6.30769230769231,-3.23076923076923 6.46153846153846,-3.30769230769231 6.61538461538462,-3.38461538461538 6.76923076923077,-3.46153846153846 6.92307692307692,-3.53846153846154 7.07692307692308,-3.61538461538461 7.23076923076923,-3.69230769230769 7.38461538461539,-3.76923076923077 7.53846153846154,-3.84615384615384 7.69230769230769,-3.92307692307692 7.84615384615385,-4.0 8.0)'): feat.DumpReadable() - return 'fail' + pytest.fail() # OGRFeature(entities):32 # EntityHandle (String) = 1DD @@ -2177,7 +1945,7 @@ def ogr_dxf_32(): feat = lyr.GetNextFeature() if ogrtest.check_feature_geometry(feat, 'LINESTRING (-4.0 1.0,-3.81418685412768 0.987348067229724,-3.62887944840607 0.975707614760869,-3.44458352298589 0.966090122894857,-3.26180481801783 0.959507071933107,-3.08104907365262 0.956969942177043,-2.90282203004096 0.959490213928084,-2.72762942733357 0.968079367487651,-2.55597700568115 0.983748883157167,-2.38837050523441 1.00751024123805,-2.22531566614407 1.04037492203173,-2.06731822856083 1.08335440583961,-1.91488393263541 1.13746017296313,-1.76851851851852 1.2037037037037,-1.62872772636086 1.28309647836275,-1.49601729631315 1.37664997724169,-1.3708929685261 1.48537568064195,-1.25386048315042 1.61028506886495,-1.14542558033682 1.75238962221211,-1.04609400023601 1.91270082098484,-0.956350410492422 2.09218800047202,-0.876194811106054 2.29085116067364,-0.805142534432475 2.50772096630085,-0.742687840320977 2.74178593705221,-0.688324988620847 2.99203459262631,-0.641548239181376 3.25745545272172,-0.601851851851852 3.53703703703703,-0.568730086481566 3.82976786527082,-0.541677202919806 4.13463645712166,-0.520187461015863 4.45063133228814,-0.503755120619026 4.77674101046882,-0.491874441578583 5.11195401136229,-0.484039683743826 5.45525885466714,-0.479745106964042 5.80564406008193,-0.478484971088521 6.16209814730525,-0.479753535966554 6.52360963603567,-0.483045061447428 6.88916704597178,-0.487853807380435 7.25775889681216,-0.493674033614862 7.62837370825537,-0.5 8.0)'): feat.DumpReadable() - return 'fail' + pytest.fail() # OGRFeature(entities):33 # EntityHandle (String) = 1DE @@ -2185,7 +1953,7 @@ def ogr_dxf_32(): feat = lyr.GetNextFeature() if ogrtest.check_feature_geometry(feat, 'POINT Z (-3.5 7.0 -6.06217782649107)'): feat.DumpReadable() - return 'fail' + pytest.fail() # OGRFeature(entities):34 # EntityHandle (String) = 1DF @@ -2193,7 +1961,7 @@ def ogr_dxf_32(): feat = lyr.GetNextFeature() if ogrtest.check_feature_geometry(feat, 'POINT Z (1.0 -2.0 -5.19615242270663)'): feat.DumpReadable() - return 'fail' + pytest.fail() # OGRFeature(entities):35 # EntityHandle (String) = 1E0 @@ -2201,7 +1969,7 @@ def ogr_dxf_32(): feat = lyr.GetNextFeature() if ogrtest.check_feature_geometry(feat, 'LINESTRING Z (0 0 0,0.25 -0.5 -1.29903810567666)'): feat.DumpReadable() - return 'fail' + pytest.fail() # OGRFeature(entities):36 # EntityHandle (String) = 1E1 @@ -2209,7 +1977,7 @@ def ogr_dxf_32(): feat = lyr.GetNextFeature() if ogrtest.check_feature_geometry(feat, 'LINESTRING Z (0.25 -0.5 -1.29903810567666,-0.25 -0.5 -2.1650635094611,1.0 -1.0 -1.73205080756888,0.25 -0.5 -1.29903810567666)'): feat.DumpReadable() - return 'fail' + pytest.fail() # OGRFeature(entities):37 # EntityHandle (String) = 1E2 @@ -2217,7 +1985,7 @@ def ogr_dxf_32(): feat = lyr.GetNextFeature() if ogrtest.check_feature_geometry(feat, 'LINESTRING Z (0.25 -0.5 -1.29903810567666,1 -1 -1.73205080756888,0.5 -1.0 -2.59807621135332,0.25 -0.5 -1.29903810567666)'): feat.DumpReadable() - return 'fail' + pytest.fail() # OGRFeature(entities):38 # EntityHandle (String) = 1E7 @@ -2227,7 +1995,7 @@ def ogr_dxf_32(): if ogrtest.check_feature_geometry(feat, 'LINESTRING Z (2.78885438199983 -2.89442719099992 -5.19615242270663,2.76889880091653 -2.9234444547489 -5.33123525325721,2.74032532268425 -2.94796278993866 -5.46565997383582,2.70327315441675 -2.96786274570473 -5.59877168071614,2.65792281055334 -2.98304737146295 -5.72992186704258,2.60449523341074 -2.99344268924297 -5.85847158229053,2.54325071677425 -2.99899805410152 -5.98379454516908,2.47448763777266 -2.99968640085941 -6.1052801948005,2.39854100321483 -2.99550437596044 -6.22233666531148,2.31578081747018 -2.98647235380955 -6.33439366934417,2.22661027984464 -2.97263433751074 -6.44090527643885,2.13146382023413 -2.95405774448845 -6.54135257275227,2.03080498262578 -2.93083307803656 -6.63524618915372,1.92512416675824 -2.90307348639549 -6.72212868538223,1.81493623894341 -2.87091421150532 -6.80157677864958,1.70077802368955 -2.8345119301207 -6.87320340583148,1.58320568834623 -2.79404399049737 -6.93665960920016,1.46279203351292 -2.74970754836936 -6.99163623651142,1.34012370241203 -2.70171860642604 -7.03786544716322,1.21579832282211 -2.65031096196872 -7.07512201708822,1.09042159549536 -2.59573506787371 -7.10322443602275,0.964604343244512 -2.5382568124111 -7.12203579180661,0.838959535075416 -2.47815622386382 -7.13146443740534,0.714099299863701 -2.41572610625796 -7.13146443740534,0.590631944124412 -2.35127061285105 -7.12203579180661,0.469158988403815 -2.28510376432794 -7.10322443602275,0.350272236731764 -2.21754791892355 -7.07512201708822,0.234550893411949 -2.148932201926 -7.03786544716322,0.122558741196756 -2.07959090221128 -6.99163623651142,0.014841394594365 -2.00986184362144 -6.93665960920016,-0.088076358310285 -1.94008473912078 -6.87320340583148,-0.185693112570302 -1.87059953574847 -6.80157677864958,-0.277533289171331 -1.8017447584307 -6.72212868538223,-0.363149452004714 -1.73385586072131 -6.63524618915372,-0.442124487731234 -1.66726359050577 -6.54135257275227,-0.514073637915374 -1.60229237863074 -6.44090527643885,-0.57864637352974 -1.53925875830959 -6.33439366934417,-0.635528102697248 -1.47846982300441 -6.22233666531148,-0.684441703351125 -1.42022173029752 -6.1052801948005,-0.725148873345763 -1.36479825904151 -5.98379454516908,-0.757451291440819 -1.31246942681719 -5.85847158229053,-0.781191583502361 -1.2634901744351 -5.72992186704258,-0.796254089213832 -1.21809912388944 -5.59877168071614,-0.802565425561482 -1.1765174158158 -5.46565997383582,-0.80009484434904 -1.13894763211612 -5.33123525325721,-0.788854381999831 -1.10557280900008 -5.19615242270663,-0.768898800916532 -1.0765555452511 -5.06106959215606,-0.740325322684253 -1.05203721006134 -4.92664487157745,-0.703273154416746 -1.03213725429527 -4.79353316469713,-0.65792281055334 -1.01695262853705 -4.66238297837069,-0.604495233410736 -1.00655731075703 -4.53383326312274,-0.543250716774252 -1.00100194589848 -4.40851030024419,-0.474487637772662 -1.00031359914059 -4.28702465061277,-0.398541003214825 -1.00449562403956 -4.16996818010179,-0.315780817470174 -1.01352764619045 -4.0579111760691,' + '-0.226610279844633 -1.02736566248926 -3.95139956897441,-0.131463820234124 -1.04594225551155 -3.85095227266099,-0.03080498262578 -1.06916692196344 -3.75705865625955,0.074875833241763 -1.09692651360451 -3.67017616003104,0.185063761056595 -1.12908578849468 -3.59072806676368,0.299221976310455 -1.1654880698793 -3.51910143958179,0.416794311653771 -1.20595600950263 -3.45564523621311,0.537207966487078 -1.25029245163064 -3.40066860890185,0.659876297587969 -1.29828139357396 -3.35443939825005,0.784201677177895 -1.34968903803128 -3.31718282832505,0.909578404504639 -1.40426493212629 -3.28908040939052,1.03539565675549 -1.4617431875889 -3.27026905360665,1.16104046492459 -1.52184377613619 -3.26084040800793,1.2859007001363 -1.58427389374204 -3.26084040800793,1.40936805587559 -1.64872938714895 -3.27026905360665,1.53084101159619 -1.71489623567206 -3.28908040939052,1.64972776326824 -1.78245208107646 -3.31718282832505,1.76544910658805 -1.851067798074 -3.35443939825005,1.87744125880325 -1.92040909778872 -3.40066860890185,1.98515860540564 -1.99013815637856 -3.45564523621311,2.08807635831029 -2.05991526087922 -3.51910143958179,2.1856931125703 -2.12940046425153 -3.59072806676368,2.27753328917133 -2.1982552415693 -3.67017616003104,2.36314945200472 -2.26614413927869 -3.75705865625955,2.44212448773124 -2.33273640949423 -3.85095227266099,2.51407363791538 -2.39770762136926 -3.95139956897441,2.57864637352974 -2.46074124169041 -4.0579111760691,2.63552810269725 -2.52153017699559 -4.16996818010179,2.68444170335113 -2.57977826970249 -4.28702465061277,2.72514887334576 -2.63520174095849 -4.40851030024419,2.75745129144082 -2.68753057318281 -4.53383326312274,2.78119158350236 -2.7365098255649 -4.66238297837069,2.79625408921383 -2.78190087611056 -4.79353316469713,2.80256542556148 -2.82348258418421 -4.92664487157744,2.80009484434904 -2.86105236788389 -5.06106959215606,2.78885438199983 -2.89442719099992 -5.19615242270663)'): feat.DumpReadable() - return 'fail' + pytest.fail() # OGRFeature(entities):39 # EntityHandle (String) = 1E8 @@ -2235,7 +2003,7 @@ def ogr_dxf_32(): feat = lyr.GetNextFeature() if ogrtest.check_feature_geometry(feat, 'LINESTRING Z (2.0 -2.0 -3.46410161513775,1.0 -2.0 -5.19615242270663)'): feat.DumpReadable() - return 'fail' + pytest.fail() # OGRFeature(entities):40 # EntityHandle (String) = 1E9 @@ -2243,7 +2011,7 @@ def ogr_dxf_32(): feat = lyr.GetNextFeature() if ogrtest.check_feature_geometry(feat, 'LINESTRING Z (1.0 -2.0 -5.19615242270663,0.0 -2.0 -6.92820323027551)'): feat.DumpReadable() - return 'fail' + pytest.fail() # OGRFeature(entities):41 # EntityHandle (String) = 1EA @@ -2251,7 +2019,7 @@ def ogr_dxf_32(): feat = lyr.GetNextFeature() if ogrtest.check_feature_geometry(feat, 'LINESTRING Z (0.25 -1.5 -4.76313972081441,1.0 -2.0 -5.19615242270663)'): feat.DumpReadable() - return 'fail' + pytest.fail() # OGRFeature(entities):42 # EntityHandle (String) = 1EB @@ -2259,7 +2027,7 @@ def ogr_dxf_32(): feat = lyr.GetNextFeature() if ogrtest.check_feature_geometry(feat, 'LINESTRING Z (1.0 -2.0 -5.19615242270663,1.75 -2.5 -5.62916512459885)'): feat.DumpReadable() - return 'fail' + pytest.fail() # OGRFeature(entities):43 # EntityHandle (String) = 1EC @@ -2269,7 +2037,7 @@ def ogr_dxf_32(): if ogrtest.check_feature_geometry(feat, 'LINESTRING Z (2.0 -2.0 -3.46410161513775,2.04988140556792 -2.03487823687206 -3.49852624302284,2.09464789446162 -2.06958655048003 -3.54122153501056,2.13408136884713 -2.10395584540888 -3.59197948393006,2.16798971280107 -2.1378186779085 -3.65055280215638,2.19620772828016 -2.17101007166283 -3.7166561263709,2.21859793994945 -2.2033683215379 -3.78996740782271,2.23505126494835 -2.23473578139294 -3.87012948131781,2.24548754433133 -2.2649596321166 -3.956751805292,2.2498559335943 -2.29389262614624 -4.04941236449012,2.24813515038388 -2.32139380484327 -4.14765972598196,2.2403335781829 -2.3473291852295 -4.25101523849813,2.2264892254669 -2.3715724127387 -4.35897536437091,2.2066695405307 -2.39400537680336 -4.47101413271915,2.18097108288703 -2.41451878627752 -4.58658570192556,2.14951905283833 -2.43301270189222 -4.70512701892219,2.11246668151345 -2.44939702314958 -4.82606056232836,2.069994484341 -2.46359192728339 -4.94879715607678,2.02230938159631 -2.47552825814758 -5.07273883982016,1.96964369030667 -2.485147863138 -5.19728178213388,1.91225399242609 -2.4924038765061 -5.32181922232198,1.85041988479386 -2.49726094768414 -5.44574442649435,1.78444261696682 -2.49969541350955 -5.56845364351315,1.71464362356182 -2.49969541350955 -5.68934904640778,1.64136295825855 -2.49726094768414 -5.80784164492769,1.56495763709223 -2.4924038765061 -5.92335415504372,1.48579989910733 -2.485147863138 -6.03532381141787,1.40427539284642 -2.47552825814758 -6.14320510913943,1.32078129750918 -2.46359192728339 -6.24647246137009,1.2357243879353 -2.44939702314958 -6.34462275995019,1.14951905283833 -2.43301270189222 -6.43717782649107,1.06258527594554 -2.41451878627752 -6.52368674201215,0.975346589879385 -2.39400537680336 -6.60372804377285,0.888228012749189 -2.3715724127387 -6.67691177859673,0.801653977505599 -2.3473291852295 -6.74288140268412,0.716046264145928 -2.32139380484327 -6.80131551865772,0.631821944844409 -2.29389262614623 -6.85192944137827,0.549391352018479 -2.2649596321166 -6.89447658490197,0.469156079230493 -2.23473578139294 -6.92874966382241,0.391507024664251 -2.2033683215379 -6.9545817031442,0.316822486708345 -2.17101007166283 -6.97184685176839,0.245466320924432 -2.1378186779085 -6.98046099562637,0.177786167379516 -2.10395584540888 -6.98038216747516,0.114111756978481 -2.06958655048003 -6.97161075135758,0.054753305048271 -2.03487823687206 -6.95418948073126,0.0 -2.0 -6.92820323027551,-0.049881405567917 -1.96512176312794 -6.89377860239042,-0.094647894461618 -1.93041344951997 -6.8510833104027,-0.134081368847123 -1.89604415459112 -6.8003253614832,-0.167989712801067 -1.8621813220915 -6.74175204325688,-0.196207728280158 -1.82898992833716 -6.67564871904237,-0.218597939949449 -1.7966316784621 -6.60233743759055,' + '-0.235051264948343 -1.76526421860705 -6.52217536409545,-0.245487544331328 -1.7350403678834 -6.43555304012126,-0.2498559335943 -1.70610737385376 -6.34289248092314,-0.248135150383881 -1.67860619515673 -6.2446451194313,-0.240333578182897 -1.6526708147705 -6.14128960691513,-0.226489225466902 -1.6284275872613 -6.03332948104236,-0.206669540530698 -1.60599462319664 -5.92129071269411,-0.180971082887026 -1.58548121372248 -5.8057191434877,-0.149519052838327 -1.56698729810778 -5.68717782649107,-0.112466681513451 -1.55060297685042 -5.5662442830849,-0.069994484341001 -1.5364080727166 -5.44350768933648,-0.022309381596311 -1.52447174185242 -5.3195660055931,0.030356309693336 -1.514852136862 -5.19502306327939,0.087746007573915 -1.50759612349389 -5.07048562309128,0.149580115206143 -1.50273905231586 -4.94656041891892,0.215557383033179 -1.50030458649045 -4.82385120190011,0.28535637643818 -1.50030458649045 -4.70295579900548,0.35863704174145 -1.50273905231586 -4.58446320048557,0.435042362907775 -1.50759612349389 -4.46895069036954,0.514200100892672 -1.514852136862 -4.35698103399539,0.595724607153583 -1.52447174185242 -4.24909973627383,0.679218702490823 -1.5364080727166 -4.14583238404317,0.764275612064703 -1.55060297685042 -4.04768208546307,0.850480947161672 -1.56698729810778 -3.95512701892219,0.937414724054466 -1.58548121372248 -3.86861810340111,1.02465341012062 -1.60599462319664 -3.78857680164041,1.11177198725081 -1.6284275872613 -3.71539306681653,1.1983460224944 -1.6526708147705 -3.64942344272914,1.28395373585407 -1.67860619515673 -3.59098932675554,1.36817805515559 -1.70610737385376 -3.54037540403499,1.45060864798152 -1.7350403678834 -3.49782826051129,1.53084392076951 -1.76526421860705 -3.46355518159085,1.60849297533575 -1.7966316784621 -3.43772314226906,1.68317751329166 -1.82898992833716 -3.42045799364487,1.75453367907557 -1.8621813220915 -3.41184384978689,1.82221383262049 -1.89604415459112 -3.4119226779381,1.88588824302152 -1.93041344951997 -3.42069409405568,1.94524669495173 -1.96512176312794 -3.438115364682,2.0 -2.0 -3.46410161513775)'): feat.DumpReadable() - return 'fail' + pytest.fail() # OGRFeature(entities):44 # EntityHandle (String) = 1ED @@ -2277,7 +2045,7 @@ def ogr_dxf_32(): feat = lyr.GetNextFeature() if ogrtest.check_feature_geometry(feat, 'LINESTRING Z (0.5 -1.0 -2.59807621135332,0.543577773425908 -1.01791116395762 -2.58464338569351,0.587546417985528 -1.03693648101917 -2.57439309093773,0.631694860183701 -1.05698461927736 -2.56737453409618,0.675811163398452 -1.07795933672482 -2.56362140807291,0.719683545292469 -1.09975994326827 -2.56315172992158,0.763101394483934 -1.12228178409597 -2.5659677543537,0.805856281596113 -1.14541674207787 -2.57205596291479,0.847742959832148 -1.16905375678694 -2.58138712888039,0.888560350271717 -1.19307935764976 -2.59391645756022,0.928112507159618 -1.21737820866727 -2.60958380133721,0.96620955855235 -1.24183366209053 -2.62831394840886,1.00266861780709 -1.26632831839353 -2.65001698384495,1.03731466153743 -1.29074458985506 -2.67458872122829,1.06998136982112 -1.31496526504393 -2.7019112028064,1.10051192462654 -1.33887407149783 -2.73185326575312,1.12875976262485 -1.36235623389463 -2.76427117182176,1.15458927877392 -1.38529902503655 -2.79900929736714,1.17787647729662 -1.40759230700227 -2.83590088042404,1.19850956692819 -1.42912905986906 -2.8747688212557,1.21638949757537 -1.44980589546683 -2.91542653252918,1.23143043581088 -1.46952355369781 -2.95767883503644,1.24356017692077 -1.48818737903916 -3.00132289466106,1.2527204915264 -1.50570777494116 -3.04614919609277,1.25886740511731 -1.52200063393958 -3.09194254861523,1.26197140915283 -1.53698774141742 -3.138483119139,1.2620176027192 -1.55059715107771 -3.18554748752036,1.25900576406208 -1.56276353032509 -3.23290971909991,1.25295035165112 -1.57342847389788 -3.28034244931235,1.24388043477135 -1.58254078424523 -3.32761797516041,1.23183955397484 -1.59005671730331 -3.37450934831362,1.21688551206218 -1.5959401924907 -3.42079146458413,1.19909009659756 -1.60016296591487 -3.46624214454969,1.17853873528923 -1.6027047659583 -3.51064320013621,1.15533008588991 -1.60355339059327 -3.55378148203954,1.12957556258567 -1.6027047659583 -3.59544990295855,1.10139880114707 -1.60016296591487 -3.63544843172717,1.07093506540992 -1.5959401924907 -3.67358505357321,1.03833059793508 -1.59005671730331 -3.70967669189409,1.00374191796432 -1.58254078424523 -3.74355008712442,0.967335070042516 -1.57342847389788 -3.77504262847653,0.929284826913179 -1.56276353032509 -3.80400313456104,0.889773850513921 -1.55059715107771 -3.83029257913998,0.848991815099414 -1.53698774141741 -3.85378475852869,0.807134496701444 -1.52200063393958 -3.87436689744237,0.764402833297081 -1.50570777494116 -3.891940190379,0.72100196019671 -1.48818737903916 -3.90642027593972,0.677140225282558 -1.46952355369781 -3.91773764180954,0.633028188825132 -1.44980589546683 -3.92583795845446,0.588877612678977 -1.42912905986906 -3.93068233993284,0.544900443710183 -1.40759230700227 -3.93224753056917,0.501307796335731 -1.38529902503655 -3.93052601659399,0.458308939059047 -1.36235623389463 -3.92552606221412,0.416110289866958 -1.33887407149783 -3.91727166993992,0.374914425310669 -1.31496526504393 -3.90580246536015,0.334919108027743 -1.29074458985506 -3.89117350691752,0.296316337373485 -1.26632831839353 -3.87345502159809,0.259291427719229 -1.24183366209053 -3.85273206780345,0.224022118842197 -1.21737820866727 -3.82910412702388,0.190677722677547 -1.19307935764975 -3.80268462627299,0.159418310528662 -1.16905375678694 -3.77360039357605,0.13039394463751 -1.14541674207787 -3.7419910491263,0.103743957803975 -1.12228178409597 -3.70800833503176,0.079596284512354 -1.09975994326827 -3.67181538687033,0.058066846776 -1.07795933672482 -3.63358595054991,0.039258997648375 -1.05698461927736 -3.59350354823325,0.023263025071983 -1.03693648101917 -3.55176059733134,0.010155718446952 -1.01791116395762 -3.50855748679486,0.0 -1.0 -3.46410161513776)'): feat.DumpReadable() - return 'fail' + pytest.fail() # OGRFeature(entities):45 # EntityHandle (String) = 1EE @@ -2285,7 +2053,7 @@ def ogr_dxf_32(): feat = lyr.GetNextFeature() if ogrtest.check_feature_geometry(feat, 'POLYGON Z ((1 -1 -1.73205080756888,1.75 -1.5 -2.1650635094611,1.25 -1.5 -3.03108891324553,0.5 -1.0 -2.59807621135332,1 -1 -1.73205080756888))'): feat.DumpReadable() - return 'fail' + pytest.fail() # OGRFeature(entities):46 # EntityHandle (String) = 1EF @@ -2293,7 +2061,7 @@ def ogr_dxf_32(): feat = lyr.GetNextFeature() if ogrtest.check_feature_geometry(feat, 'POLYGON Z ((1.5 -2.0 -4.33012701892219,1.0 -2.0 -5.19615242270663,0.25 -1.5 -4.76313972081441,0.75 -1.5 -3.89711431702997,1.5 -2.0 -4.33012701892219))'): feat.DumpReadable() - return 'fail' + pytest.fail() # OGRFeature(entities):47 # EntityHandle (String) = 1F1 @@ -2301,7 +2069,7 @@ def ogr_dxf_32(): feat = lyr.GetNextFeature() if ogrtest.check_feature_geometry(feat, 'POLYGON Z ((2.0 -4.0 -10.3923048454133,1.5 -4.0 -11.2583302491977,2.25 -4.5 -11.6913429510899,2.75 -4.5 -10.8253175473055,2.0 -4.0 -10.3923048454133))'): feat.DumpReadable() - return 'fail' + pytest.fail() # OGRFeature(entities):48 # EntityHandle (String) = 1F2 @@ -2309,7 +2077,7 @@ def ogr_dxf_32(): feat = lyr.GetNextFeature() if ogrtest.check_feature_geometry(feat, 'LINESTRING (0.5 -1.0,0.53846153846154 -1.07692307692308,0.576923076923078 -1.15384615384615,0.615384615384617 -1.23076923076923,0.653846153846155 -1.30769230769231,0.692307692307694 -1.38461538461538,0.730769230769232 -1.46153846153846,0.769230769230771 -1.53846153846154,0.807692307692309 -1.61538461538462,0.846153846153848 -1.69230769230769,0.884615384615386 -1.76923076923077,0.923076923076924 -1.84615384615385,0.961538461538463 -1.92307692307692,1.0 -2.0,1.03846153846154 -2.07692307692308,1.07692307692308 -2.15384615384615,1.11538461538462 -2.23076923076923,1.15384615384616 -2.30769230769231,1.19230769230769 -2.38461538461538,1.23076923076923 -2.46153846153846,1.26923076923077 -2.53846153846154,1.30769230769231 -2.61538461538461,1.34615384615385 -2.69230769230769,1.38461538461539 -2.76923076923077,1.42307692307693 -2.84615384615385,1.46153846153846 -2.92307692307692,1.5 -3.0,1.53846153846154 -3.07692307692308,1.57692307692308 -3.15384615384615,1.61538461538462 -3.23076923076923,1.65384615384616 -3.30769230769231,1.6923076923077 -3.38461538461539,1.73076923076923 -3.46153846153846,1.76923076923077 -3.53846153846154,1.80769230769231 -3.61538461538461,1.84615384615385 -3.69230769230769,1.88461538461539 -3.76923076923077,1.92307692307693 -3.84615384615385,1.96153846153847 -3.92307692307692,2.0 -4.0)'): feat.DumpReadable() - return 'fail' + pytest.fail() # OGRFeature(entities):49 # EntityHandle (String) = 1F3 @@ -2317,7 +2085,7 @@ def ogr_dxf_32(): feat = lyr.GetNextFeature() if ogrtest.check_feature_geometry(feat, 'LINESTRING (-3.25 -0.5,-3.07367580370539 -0.493674033614862,-2.89709873733542 -0.487853807380434,-2.72001593081474 -0.483045061447428,-2.542174514068 -0.479753535966554,-2.36332161701984 -0.478484971088521,-2.1832043695949 -0.479745106964042,-2.00156990171783 -0.484039683743825,-1.81816534331327 -0.491874441578583,-1.63273782430587 -0.503755120619026,-1.44503447462027 -0.520187461015863,-1.25480242418112 -0.541677202919806,-1.06178880291306 -0.568730086481565,-0.865740740740739 -0.601851851851852,-0.666405367588798 -0.641548239181375,-0.463529813381883 -0.688324988620846,-0.256861208044639 -0.742687840320976,-0.04614668150171 -0.805142534432475,0.168866636322258 -0.876194811106053,0.388431615502622 -0.956350410492422,0.612790589861596 -1.04609400023601,0.841943559399181 -1.14542558033682,1.07564819029316 -1.25386048315042,1.31365161246818 -1.3708929685261,1.55570095584888 -1.49601729631315,1.80154335035992 -1.62872772636086,2.05092592592592 -1.76851851851852,2.30359581247155 -1.91488393263541,2.55930013992144 -2.06731822856083,2.81778603820024 -2.22531566614407,3.07880063723259 -2.38837050523441,3.34209106694314 -2.55597700568115,3.60740445725653 -2.72762942733357,3.87448793809741 -2.90282203004097,4.14308863939042 -3.08104907365262,4.4129536910602 -3.26180481801784,4.68383022303141 -3.44458352298589,4.95546536522868 -3.62887944840608,5.22760624757667 -3.81418685412768,5.5 -4.0)'): feat.DumpReadable() - return 'fail' + pytest.fail() # OGRFeature(entities):50 # EntityHandle (String) = 1F4 @@ -2325,7 +2093,7 @@ def ogr_dxf_32(): feat = lyr.GetNextFeature() if ogrtest.check_feature_geometry(feat, 'POINT Z (1.75 -3.5 -9.09326673973661)'): feat.DumpReadable() - return 'fail' + pytest.fail() # OGRFeature(entities):51 # EntityHandle (String) = 1F5 @@ -2333,7 +2101,7 @@ def ogr_dxf_32(): feat = lyr.GetNextFeature() if ogrtest.check_feature_geometry(feat, 'POINT Z (5.5 1.0 -0.866025403784439)'): feat.DumpReadable() - return 'fail' + pytest.fail() # OGRFeature(entities):52 # EntityHandle (String) = 1F6 @@ -2341,7 +2109,7 @@ def ogr_dxf_32(): feat = lyr.GetNextFeature() if ogrtest.check_feature_geometry(feat, 'LINESTRING Z (0 0 0,1.375 0.25 -0.21650635094611)'): feat.DumpReadable() - return 'fail' + pytest.fail() # OGRFeature(entities):53 # EntityHandle (String) = 1F7 @@ -2349,7 +2117,7 @@ def ogr_dxf_32(): feat = lyr.GetNextFeature() if ogrtest.check_feature_geometry(feat, 'LINESTRING Z (1.375 0.25 -0.21650635094611,2.0 1.0 -9.68245836551854e-17,2.125 -0.25 -0.649519052838329,1.375 0.25 -0.21650635094611)'): feat.DumpReadable() - return 'fail' + pytest.fail() # OGRFeature(entities):54 # EntityHandle (String) = 1F8 @@ -2357,7 +2125,7 @@ def ogr_dxf_32(): feat = lyr.GetNextFeature() if ogrtest.check_feature_geometry(feat, 'LINESTRING Z (1.375 0.25 -0.21650635094611,2.125 -0.25 -0.649519052838329,2.75 0.5 -0.43301270189222,1.375 0.25 -0.21650635094611)'): feat.DumpReadable() - return 'fail' + pytest.fail() # OGRFeature(entities):55 # EntityHandle (String) = 1FD @@ -2367,7 +2135,7 @@ def ogr_dxf_32(): if ogrtest.check_feature_geometry(feat, 'LINESTRING Z (3.71114561800017 0.105572809000085 -0.866025403784439,3.77009625337411 -0.001434563330173 -0.933566819059727,3.83747480591229 -0.103563047131737 -1.00077917934903,3.91295301407961 -0.200315082697444 -1.06733503278919,3.99616315563294 -0.2912193038355 -1.13291012595241,4.08669983912687 -0.37583283431818 -1.19718498357639,4.18412197894014 -0.453743445530294 -1.25984646501566,4.28795494420042 -0.524571564805566 -1.32058928983137,4.39769287113821 -0.587972124666501 -1.37911752508686,4.51280112760429 -0.643636243958462 -1.43514602710321,4.6327189177438 -0.691292732687594 -1.48840183065055,4.75686201413727 -0.730709413231224 -1.53862547880726,4.88462560409789 -0.761694251483893 -1.58557228700798,5.01538723625813 -0.784096292428219 -1.62901353512224,5.14850985309022 -0.797806395572568 -1.66873758175591,5.28334489458639 -0.802757766672552 -1.70455089534686,5.41923545797803 -0.798926283145887 -1.7362789970312,5.55551949809999 -0.786330611595171 -1.76376731068683,5.691533052808 -0.76503211686609 -1.78688191601273,5.82661347773556 -0.735134563084044 -1.80551020097523,5.96010267463067 -0.69678360812577 -1.8195614104425,6.09135029754434 -0.650166093988798 -1.82896708833443,6.2197169212507 -0.595509136516029 -1.83368141113379,6.34457715646241 -0.533079018910172 -1.83368141113379,6.46532269666444 -0.463179894428748 -1.82896708833443,6.58136528172222 -0.386152304579996 -1.8195614104425,6.69213956382591 -0.302371520038872 -1.80551020097523,6.79710586180808 -0.212245712366048 -1.78688191601273,6.89575279041615 -0.116213965437088 -1.76376731068683,6.9875997517299 -0.014744136269953 -1.7362789970312,7.07219927658622 0.091669424327363 -1.70455089534686,7.14913920460393 0.202508280184287 -1.66873758175591,7.2180446921877 0.317232435536567 -1.62901353512224,7.27858003872839 0.435282965831356 -1.58557228700798,7.33045032210263 0.556084740751457 -1.53862547880726,7.37340283550381 0.679049226192411 -1.48840183065055,7.4072283186042 0.803577351541497 -1.43514602710321,7.43176197705028 0.929062428289537 -1.37911752508686,7.44688428532421 1.05489310575633 -1.32058928983137,7.45252156906016 1.18045634952971 -1.25984646501566,7.44864636397843 1.3051404281076 -1.19718498357639,7.43527754968864 1.42833789319235 -1.13291012595241,7.41248025771019 1.54944853911785 -1.06733503278919,7.38036555415802 1.66788232699113 -1.00077917934903,7.33908989863968 1.78306225930261 -0.933566819059728,7.28885438199984 1.89442719099992 -0.86602540378444,7.2299037466259 2.00143456333018 -0.798483988509152,7.16252519408772 2.10356304713174 -0.731271628219845,7.08704698592039 2.20031508269745 -0.664715774779688,' + '7.00383684436707 2.2912193038355 -0.599140681616468,6.91330016087314 2.37583283431818 -0.534865823992492,6.81587802105987 2.4537434455303 -0.472204342553219,6.71204505579959 2.52457156480557 -0.411461517737508,6.6023071288618 2.5879721246665 -0.352933282482017,6.48719887239572 2.64363624395846 -0.296904780465671,6.36728108225621 2.6912927326876 -0.24364897691833,6.24313798586274 2.73070941323123 -0.19342532876162,6.11537439590212 2.7616942514839 -0.146478520560899,5.98461276374187 2.78409629242822 -0.103037272446642,5.85149014690979 2.79780639557257 -0.0633132258129652,5.71665510541362 2.80275776667256 -0.0274999122220189,5.58076454202198 2.79892628314589 0.00422818946232298,5.44448050190002 2.78633061159517 0.0317165031179519,5.30846694719201 2.76503211686609 0.0548311084438533,5.17338652226444 2.73513456308405 0.0734593934063514,5.03989732536933 2.69678360812577 0.0875106028736174,4.90864970245567 2.6501660939888 0.0969162807655497,4.78028307874931 2.59550913651603 0.101630603564914,4.6554228435376 2.53307901891017 0.101630603564914,4.53467730333557 2.46317989442875 0.0969162807655497,4.41863471827779 2.38615230458 0.0875106028736175,4.3078604361741 2.30237152003888 0.0734593934063515,4.20289413819193 2.21224571236605 0.0548311084438534,4.10424720958385 2.11621396543709 0.031716503117952,4.01240024827011 2.01474413626996 0.00422818946232319,3.92780072341379 1.90833057567264 -0.0274999122220187,3.85086079539608 1.79749171981572 -0.0633132258129645,3.7819553078123 1.68276756446344 -0.103037272446642,3.72141996127162 1.56471703416865 -0.146478520560898,3.66954967789738 1.44391525924855 -0.19342532876162,3.6265971644962 1.32095077380759 -0.243648976918329,3.5927716813958 1.19642264845851 -0.296904780465671,3.56823802294973 1.07093757171047 -0.352933282482016,3.5531157146758 0.945106894243672 -0.411461517737508,3.54747843093985 0.819543650470287 -0.472204342553219,3.55135363602158 0.694859571892403 -0.534865823992493,3.56472245031136 0.571662106807651 -0.599140681616467,3.58751974228981 0.450551460882157 -0.664715774779687,3.61963444584198 0.332117673008871 -0.731271628219845,3.66091010136033 0.216937740697387 -0.798483988509152,3.71114561800017 0.105572809000085 -0.866025403784439)'): feat.DumpReadable() - return 'fail' + pytest.fail() # OGRFeature(entities):56 # EntityHandle (String) = 1FE @@ -2375,7 +2143,7 @@ def ogr_dxf_32(): feat = lyr.GetNextFeature() if ogrtest.check_feature_geometry(feat, 'LINESTRING Z (4.25 -0.5 -1.29903810567666,5.5 1.0 -0.866025403784439)'): feat.DumpReadable() - return 'fail' + pytest.fail() # OGRFeature(entities):57 # EntityHandle (String) = 1FF @@ -2383,7 +2151,7 @@ def ogr_dxf_32(): feat = lyr.GetNextFeature() if ogrtest.check_feature_geometry(feat, 'LINESTRING Z (5.5 1.0 -0.866025403784439,6.75 2.5 -0.43301270189222)'): feat.DumpReadable() - return 'fail' + pytest.fail() # OGRFeature(entities):58 # EntityHandle (String) = 200 @@ -2391,7 +2159,7 @@ def ogr_dxf_32(): feat = lyr.GetNextFeature() if ogrtest.check_feature_geometry(feat, 'LINESTRING Z (4.75 1.5 -0.43301270189222,5.5 1.0 -0.866025403784439)'): feat.DumpReadable() - return 'fail' + pytest.fail() # OGRFeature(entities):59 # EntityHandle (String) = 201 @@ -2399,7 +2167,7 @@ def ogr_dxf_32(): feat = lyr.GetNextFeature() if ogrtest.check_feature_geometry(feat, 'LINESTRING Z (5.5 1.0 -0.866025403784439,6.25 0.5 -1.29903810567666)'): feat.DumpReadable() - return 'fail' + pytest.fail() # OGRFeature(entities):60 # EntityHandle (String) = 202 @@ -2409,7 +2177,7 @@ def ogr_dxf_32(): if ogrtest.check_feature_geometry(feat, 'LINESTRING Z (4.25 -0.5 -1.29903810567666,4.30536229248331 -0.531224312261799 -1.32818874766841,4.36654473979309 -0.554988653592388 -1.35508777630525,4.43324926719606 -0.571177246509588 -1.37960414222355,4.50515089693985 -0.579711221815978 -1.40161840415293,4.58189933151187 -0.580549002841697 -1.42102331082214,4.6631206602536 -0.573686508001801 -1.43772432347645,4.74841918101576 -0.559157170681335 -1.451640076461,4.83737932797937 -0.53703177635124 -1.46270277362604,4.92956769625067 -0.507418117708657 -1.47085851862302,5.02453515336618 -0.470460469521736 -1.47606757748212,5.12181902742094 -0.426338885737475 -1.47830457219218,5.22094536115948 -0.375268322276984 -1.47755860433986,5.32143122104797 -0.317497589791849 -1.47383330820552,5.42278705007785 -0.253308141483641 -1.46714683305749,5.52451905283833 -0.183012701892219 -1.45753175473055,5.62613160123803 -0.106953743333199 -1.44503491691981,5.7271296491552 -0.025501817407262 -1.42971720296291,5.82702114425268 0.060946250290002 -1.41165323922251,5.92531942520741 0.151969293462501 -1.39093103151418,6.02154559267549 0.247123856993501 -1.36765153635088,6.11523084244164 0.345946357414384 -1.34192816909299,6.2059187493862 0.4479553414367 -1.31388625140011,6.29316749114245 0.552653831544204 -1.28366240067645,6.37655200061077 0.659531747217344 -1.25140386448466,6.45566603684282 0.768068389994292 -1.21726780317044,6.53012416420658 0.877734980261504 -1.18142052419318,6.59956363019005 0.987997233414845 -1.1440366718927,6.66364613269498 1.09831796284048 -1.10529837663958,6.72205946821072 1.20815969703403 -1.06539436751435,6.77451905283833 1.31698729810778 -1.02451905283833,6.82076930875472 1.4242705689286 -0.982871573035841,6.86058490936212 1.52948683618513 -0.940654830442097,6.89377187705662 1.63212349679959 -0.898074500783399,6.92016852826756 1.73168051527848 -0.855338031145687,6.93964626116363 1.8276728598352 -0.81265362931318,6.95211018218804 1.91963286541618 -0.770229249400985,6.95749956837044 2.00711251211804 -0.72827157872355,6.95578816316308 2.08968560789544 -0.686985030834846,6.9469843043601 2.166949864926 -0.646570749646076,6.93113088347664 2.23852885951603 -0.607225629472764,6.90830513678565 2.30407386599898 -0.569141355785437,6.87861826903058 2.36326555569183 -0.53250347133728,6.84221491164701 2.41581555263232 -0.497490472218499,6.79927241813288 2.46146783851767 -0.464272938241304,6.75 2.5 -0.43301270189222,6.69463770751669 2.5312243122618 -0.40386205990047,' + '6.63345526020692 2.55498865359239 -0.376963031263626,6.56675073280394 2.57117724650959 -0.352446665345325,6.49484910306015 2.57971122181598 -0.330432403415945,6.41810066848813 2.5805490028417 -0.311027496746741,6.3368793397464 2.5736865080018 -0.294326484092429,6.25158081898424 2.55915717068134 -0.280410731107883,6.16262067202063 2.53703177635124 -0.269348033942836,6.07043230374933 2.50741811770866 -0.261192288945857,5.97546484663382 2.47046046952174 -0.255983230086761,5.87818097257907 2.42633888573748 -0.253746235376694,5.77905463884053 2.37526832227698 -0.254492203229023,5.67856877895203 2.31749758979185 -0.258217499363356,5.57721294992215 2.25330814148364 -0.264903974511391,5.47548094716167 2.18301270189222 -0.27451905283833,5.37386839876197 2.1069537433332 -0.287015890649068,5.2728703508448 2.02550181740726 -0.302333604605968,5.17297885574732 1.93905374971 -0.320397568346365,5.07468057479259 1.8480307065375 -0.341119776054697,4.97845440732451 1.7528761430065 -0.364399271218,4.88476915755836 1.65405364258562 -0.390122638475884,4.79408125061381 1.5520446585633 -0.418164556168773,4.70683250885755 1.4473461684558 -0.44838840689243,4.62344799938923 1.34046825278266 -0.48064694308422,4.54433396315718 1.23193161000571 -0.514783004398435,4.46987583579342 1.1222650197385 -0.550630283375696,4.40043636980995 1.01200276658516 -0.588014135676182,4.33635386730502 0.901682037159526 -0.626752430929296,4.27794053178928 0.791840302965968 -0.666656440054525,4.22548094716167 0.68301270189222 -0.707531754730549,4.17923069124529 0.575729431071401 -0.749179234533037,4.13941509063789 0.470513163814874 -0.791395977126782,4.10622812294338 0.36787650320041 -0.833976306785479,4.07983147173244 0.268319484721523 -0.876712776423191,4.06035373883638 0.172327140164803 -0.919397178255699,4.04788981781196 0.080367134583816 -0.961821558167894,4.04250043162957 -0.007112512118036 -1.00377922884533,4.04421183683692 -0.089685607895445 -1.04506577673403,4.0530156956399 -0.166949864926001 -1.0854800579228,4.06886911652336 -0.238528859516028 -1.12482517809611,4.09169486321435 -0.304073865998978 -1.16290945178344,4.12138173096942 -0.363265555691829 -1.1995473362316,4.15778508835299 -0.415815552632322 -1.23456033535038,4.20072758186713 -0.461467838517673 -1.26777786932757,4.25 -0.5 -1.29903810567666)'): feat.DumpReadable() - return 'fail' + pytest.fail() # OGRFeature(entities):61 # EntityHandle (String) = 203 @@ -2417,7 +2185,7 @@ def ogr_dxf_32(): feat = lyr.GetNextFeature() if ogrtest.check_feature_geometry(feat, 'LINESTRING Z (2.75 0.5 -0.43301270189222,2.75597796157458 0.457022294808167 -0.455760312055479,2.76522760095779 0.414850974295674 -0.478918395607368,2.77770451483146 0.37368848382115 -0.502375781105475,2.79334880719819 0.333732425808347 -0.526019860294666,2.81208537691484 0.295174611146642 -0.549737128688177,2.83382427821898 0.258200138394064 -0.573413730451116,2.85846115251769 0.222986505203176 -0.596936004970611,2.88587772936573 0.189702756235451 -0.620191032488805,2.91594239422828 0.15850867165462 -0.643067176179329,2.94851082030252 0.129554000094665 -0.66545461806501,2.98342666136509 0.102977739784634 -0.687245886204105,3.02052230231928 0.078907471281269 -0.708336370614292,3.05961966383903 0.057458745012683 -0.728624825457685,3.10053105724686 0.038734526573237 -0.748013855076124,3.14306008552201 0.022824702432479 -0.766410381543502,3.18700258611332 0.009805648431019 -0.783726091490617,3.23214761103096 -0.00026013686519 -0.79987786005755,3.27827843951188 -0.007324332192091 -0.814788149938374,3.32517361839783 -0.011353025555964 -0.828385383602543,3.37260802523135 -0.012326877029509 -0.84060428690611,3.42035394896652 -0.010241211594056 -0.851386202443257,3.46818218310621 -0.0051060415822 -0.860679371133851,3.51586312601842 0.003053981386852 -0.868439180695292,3.56316788314946 0.014199684748517 -0.874628379805819,3.60986936584274 0.028277563042523 -0.879217256931186,3.65574338148826 0.045220034768334 -0.882183782956251,3.70056970976957 0.064945766813234 -0.883513716936746,3.74413315984144 0.087360064895672 -0.883200674463593,3.78622460336345 0.112355328149502 -0.881246158311542,3.82664197843012 0.139811565666877 -0.87765955122504,3.86519125957839 0.169596972520106 -0.872458070875934,3.90168738921576 0.201568562497258 -0.865666687209244,3.93595516599773 0.235572854514029 -0.857318002573801,3.96783008588991 0.271446609406727 -0.847452095213172,3.99715913187718 0.30901761356937 -0.836116326868217,4.02380150852887 0.348105505672996 -0.823365115414876,4.04762931789371 0.3885226424985 -0.809259673628662,4.06852817347981 0.430074999726512 -0.793867715329923,4.08639774937224 0.472563103360048 -0.777263130320539,4.10115226185219 0.515782987308575 -0.759525629672545,4.1127208812057 0.559527172536592 -0.740740363071464,4.12104807174486 0.603585663076254 -0.720997510051345,4.12609385840951 0.647746954122649 -0.700391847083764,4.1278340186693 0.691799047372318 -0.679022292599034,4.12626019880507 0.735530468730831 -0.656991432123733,4.12137995401128 0.778731283503886 -0.634405025814187,4.11321671212692 0.821194104198432 -0.61137150074998,4.10180966116915 0.862715086095846 -0.588001430424789,4.08721356120934 0.903094905817856 -0.564407003933257,4.06949848149492 0.942139718187561 -0.540701487402092,4.04874946407869 0.979662086792094 -0.516998680250836,4.02506611557057 1.01548188377972 -0.493412368892526,3.99856212897149 1.04942715457186 -0.470055780496802,3.96936473788492 1.08133494333891 -0.447041039437686,3.93761410572614 1.11105207527721 -0.424478629035376,3.9034626528613 1.13843589193168 -0.402476861176005,3.86707432490649 1.16335493603432 -0.381141356355458,3.8286238056993 1.1856895825708 -0.360574536643342,3.78829567872099 1.20533261304587 -0.340875134001137,3.74628354099508 1.22218973019068 -0.322137716314888,3.70278907371594 1.23618001064108 -0.304452233417734,3.65802107406893 1.247236293414 -0.287903585281599,3.61219445288998 1.25530550231681 -0.27257121445099,3.56552920297626 1.26034890074202 -0.258528724675415,3.51824934300062 1.26234227762414 -0.245843527571206,3.47058184209972 1.26127606366599 -0.234576519008966,3.42275553029828 1.2571553772766 -0.224781786780142,3.375 1.25 -0.21650635094611)'): feat.DumpReadable() - return 'fail' + pytest.fail() # OGRFeature(entities):62 # EntityHandle (String) = 204 @@ -2425,7 +2193,7 @@ def ogr_dxf_32(): feat = lyr.GetNextFeature() if ogrtest.check_feature_geometry(feat, 'POLYGON Z ((2.125 -0.25 -0.649519052838329,2.875 -0.75 -1.08253175473055,3.5 0.0 -0.866025403784439,2.75 0.5 -0.43301270189222,2.125 -0.25 -0.649519052838329))'): feat.DumpReadable() - return 'fail' + pytest.fail() # OGRFeature(entities):63 # EntityHandle (String) = 205 @@ -2433,7 +2201,7 @@ def ogr_dxf_32(): feat = lyr.GetNextFeature() if ogrtest.check_feature_geometry(feat, 'POLYGON Z ((4.875 0.25 -1.08253175473055,5.5 1.0 -0.866025403784439,4.75 1.5 -0.43301270189222,4.125 0.75 -0.649519052838329,4.875 0.25 -1.08253175473055))'): feat.DumpReadable() - return 'fail' + pytest.fail() # OGRFeature(entities):64 # EntityHandle (String) = 207 @@ -2441,7 +2209,7 @@ def ogr_dxf_32(): feat = lyr.GetNextFeature() if ogrtest.check_feature_geometry(feat, 'POLYGON Z ((11 2 -1.73205080756888,11.625 2.75 -1.51554445662277,12.375 2.25 -1.94855715851499,11.75 1.5 -2.1650635094611,11 2 -1.73205080756888))'): feat.DumpReadable() - return 'fail' + pytest.fail() # OGRFeature(entities):65 # EntityHandle (String) = 208 @@ -2449,7 +2217,7 @@ def ogr_dxf_32(): feat = lyr.GetNextFeature() if ogrtest.check_feature_geometry(feat, 'LINESTRING (2.75 0.5,2.96153846153846 0.538461538461539,3.17307692307692 0.576923076923077,3.38461538461539 0.615384615384616,3.59615384615385 0.653846153846154,3.80769230769231 0.692307692307693,4.01923076923077 0.730769230769231,4.23076923076923 0.76923076923077,4.44230769230769 0.807692307692308,4.65384615384616 0.846153846153847,4.86538461538462 0.884615384615385,5.07692307692308 0.923076923076924,5.28846153846154 0.961538461538462,5.5 1.0,5.71153846153846 1.03846153846154,5.92307692307693 1.07692307692308,6.13461538461539 1.11538461538462,6.34615384615385 1.15384615384615,6.55769230769231 1.19230769230769,6.76923076923077 1.23076923076923,6.98076923076923 1.26923076923077,7.19230769230769 1.30769230769231,7.40384615384616 1.34615384615385,7.61538461538462 1.38461538461539,7.82692307692308 1.42307692307692,8.03846153846154 1.46153846153846,8.25 1.5,8.46153846153846 1.53846153846154,8.67307692307693 1.57692307692308,8.88461538461539 1.61538461538462,9.09615384615385 1.65384615384615,9.30769230769231 1.69230769230769,9.51923076923077 1.73076923076923,9.73076923076923 1.76923076923077,9.94230769230769 1.80769230769231,10.1538461538462 1.84615384615385,10.3653846153846 1.88461538461539,10.5769230769231 1.92307692307692,10.7884615384615 1.96153846153846,11.0 2.0)'): feat.DumpReadable() - return 'fail' + pytest.fail() # OGRFeature(entities):66 # EntityHandle (String) = 209 @@ -2457,7 +2225,7 @@ def ogr_dxf_32(): feat = lyr.GetNextFeature() if ogrtest.check_feature_geometry(feat, 'LINESTRING (5.75 5.5,5.5082446180819 5.22760624757667,5.26788002157825 4.95546536522868,5.03029699590351 4.68383022303141,4.79688632647213 4.4129536910602,4.56903879869856 4.14308863939042,4.34814519799727 3.87448793809741,4.1355963097827 3.60740445725653,3.93278291946931 3.34209106694314,3.74109581247155 3.07880063723259,3.56192577420388 2.81778603820024,3.39666359008075 2.55930013992144,3.24670004551661 2.30359581247155,3.11342592592593 2.05092592592593,2.99823201672314 1.80154335035992,2.90250910332271 1.55570095584889,2.8276479711391 1.31365161246818,2.77503940558674 1.07564819029316,2.74607419208011 0.84194355939918,2.74214311603365 0.612790589861594,2.76457901346955 0.38843161550262,2.8133818843878 0.168866636322256,2.88721889276623 -0.046146681501713,2.98469925319038 -0.256861208044643,3.10443218024579 -0.463529813381887,3.24502688851802 -0.666405367588803,3.4050925925926 -0.865740740740744,3.58323850705508 -1.06178880291307,3.77807384649101 -1.25480242418113,3.98820782548594 -1.44503447462028,4.21224965862541 -1.63273782430588,4.44880856049496 -1.81816534331328,4.69649374568015 -2.00156990171784,4.95391442876651 -2.18320436959491,5.2196798243396 -2.36332161701985,5.49239914698496 -2.54217451406801,5.77068161128813 -2.72001593081475,6.05313643183467 -2.89709873733543,6.33837282321012 -3.0736758037054,6.625 -3.25)'): feat.DumpReadable() - return 'fail' + pytest.fail() # OGRFeature(entities):67 # EntityHandle (String) = 20A @@ -2465,15 +2233,14 @@ def ogr_dxf_32(): feat = lyr.GetNextFeature() if ogrtest.check_feature_geometry(feat, 'POINT Z (9.625 1.75 -1.51554445662277)'): feat.DumpReadable() - return 'fail' - - return 'success' + pytest.fail() + ############################################################################### # Test 3D entities (polyface mesh, cylinder, 3D solid) -def ogr_dxf_33(): +def test_ogr_dxf_33(): gdal.SetConfigOption('DXF_3D_EXTENSIBLE_MODE', 'TRUE') ds = ogr.Open('data/3d.dxf') @@ -2483,92 +2250,78 @@ def ogr_dxf_33(): # Polyface mesh (POLYLINE) feat = layer.GetNextFeature() - if feat.Layer != '0': - return 'fail' + assert feat.Layer == '0' geom = feat.GetGeometryRef() - if geom.GetGeometryType() != ogr.wkbPolyhedralSurfaceZ: - gdaltest.post_reason('did not get expected geometry type; got %s instead of wkbPolyhedralSurface', geom.GetGeometryType()) - return 'fail' + assert geom.GetGeometryType() == ogr.wkbPolyhedralSurfaceZ, \ + ('did not get expected geometry type; got %s instead of wkbPolyhedralSurface' % geom.GetGeometryType()) wkt_string = geom.ExportToIsoWkt() wkt_string_expected = 'POLYHEDRALSURFACE Z (((0 0 0,1 0 0,1 1 0,0 1 0,0 0 0)),((0 0 0,1 0 0,1 0 1,0 0 1,0 0 0)),((1 0 0,1 1 0,1 1 1,1 0 1,1 0 0)),((1 1 0,1 1 1,0 1 1,0 1 0,1 1 0)),((0 0 0,0 1 0,0 1 1,0 0 1,0 0 0)),((0 0 1,1 0 1,1 1 1,0 1 1,0 0 1)))' if wkt_string != wkt_string_expected: feat.DumpReadable() - gdaltest.post_reason('wrong geometry for polyface mesh') - return 'fail' + pytest.fail('wrong geometry for polyface mesh') faces = geom.GetGeometryCount() - if faces != 6: - gdaltest.post_reason('did not get expected number of faces, got %d instead of %d' % (faces, 6)) - return 'fail' + assert faces == 6, \ + ('did not get expected number of faces, got %d instead of %d' % (faces, 6)) # Cylinder (CIRCLE with thickness) feat = layer.GetNextFeature() - if ogrtest.check_feature_geometry(feat, 'POLYHEDRALSURFACE Z (((2.8 -0.0 1e-31,2.79902562010393 -0.0 -0.0279025894976501,2.79610722749663 -0.0 -0.0556692403840262,2.79125904029352 -0.0 -0.0831646763271037,2.78450467837533 -0.0 -0.1102549423268,2.77587704831436 -0.0 -0.136808057330267,2.76541818305704 -0.0 -0.16269465723032,2.75317903714357 -0.0 -0.187788625114356,2.73921923846257 -0.0 -0.211967705693282,2.72360679774998 0.0 -0.235114100916989,2.70641777724759 0.0 -0.257115043874616,2.68773592013546 0.0 -0.277863348183599,2.66765224254354 0.0 -0.297257930190958,2.64626459013026 0.0 -0.315204301442689,2.6236771613883 0.0 -0.331615029022017,2.6 0.0 -0.346410161513775,2.57534845871563 0.0 -0.359517618519667,2.54984263736636 0.0 -0.370873541826715,2.52360679774998 0.0 -0.380422606518061,2.49676875823987 0.0 -0.388118290510399,2.46945927106677 0.0 -0.393923101204883,2.44181138530706 0.0 -0.397808758147309,2.413959798681 0.0 -0.399756330807638,2.386040201319 0.0 -0.399756330807638,2.35818861469294 0.0 -0.397808758147309,2.33054072893323 0.0 -0.393923101204883,2.30323124176013 0.0 -0.388118290510399,2.27639320225002 0.0 -0.380422606518061,2.25015736263363 0.0 -0.370873541826715,2.22465154128437 0.0 -0.359517618519667,2.2 0.0 -0.346410161513776,2.1763228386117 0.0 -0.331615029022017,2.15373540986974 0.0 -0.315204301442689,2.13234775745646 0.0 -0.297257930190958,2.11226407986454 0.0 -0.277863348183599,2.09358222275241 0.0 -0.257115043874616,2.07639320225002 0.0 -0.235114100916989,2.06078076153743 0.0 -0.211967705693282,2.04682096285643 0.0 -0.187788625114356,2.03458181694296 0.0 -0.16269465723032,2.02412295168564 0.0 -0.136808057330268,2.01549532162467 0.0 -0.1102549423268,2.00874095970648 0.0 -0.0831646763271037,2.00389277250337 0.0 -0.0556692403840263,2.00097437989607 0.0 -0.0279025894976502,' + + assert (not ogrtest.check_feature_geometry(feat, 'POLYHEDRALSURFACE Z (((2.8 -0.0 1e-31,2.79902562010393 -0.0 -0.0279025894976501,2.79610722749663 -0.0 -0.0556692403840262,2.79125904029352 -0.0 -0.0831646763271037,2.78450467837533 -0.0 -0.1102549423268,2.77587704831436 -0.0 -0.136808057330267,2.76541818305704 -0.0 -0.16269465723032,2.75317903714357 -0.0 -0.187788625114356,2.73921923846257 -0.0 -0.211967705693282,2.72360679774998 0.0 -0.235114100916989,2.70641777724759 0.0 -0.257115043874616,2.68773592013546 0.0 -0.277863348183599,2.66765224254354 0.0 -0.297257930190958,2.64626459013026 0.0 -0.315204301442689,2.6236771613883 0.0 -0.331615029022017,2.6 0.0 -0.346410161513775,2.57534845871563 0.0 -0.359517618519667,2.54984263736636 0.0 -0.370873541826715,2.52360679774998 0.0 -0.380422606518061,2.49676875823987 0.0 -0.388118290510399,2.46945927106677 0.0 -0.393923101204883,2.44181138530706 0.0 -0.397808758147309,2.413959798681 0.0 -0.399756330807638,2.386040201319 0.0 -0.399756330807638,2.35818861469294 0.0 -0.397808758147309,2.33054072893323 0.0 -0.393923101204883,2.30323124176013 0.0 -0.388118290510399,2.27639320225002 0.0 -0.380422606518061,2.25015736263363 0.0 -0.370873541826715,2.22465154128437 0.0 -0.359517618519667,2.2 0.0 -0.346410161513776,2.1763228386117 0.0 -0.331615029022017,2.15373540986974 0.0 -0.315204301442689,2.13234775745646 0.0 -0.297257930190958,2.11226407986454 0.0 -0.277863348183599,2.09358222275241 0.0 -0.257115043874616,2.07639320225002 0.0 -0.235114100916989,2.06078076153743 0.0 -0.211967705693282,2.04682096285643 0.0 -0.187788625114356,2.03458181694296 0.0 -0.16269465723032,2.02412295168564 0.0 -0.136808057330268,2.01549532162467 0.0 -0.1102549423268,2.00874095970648 0.0 -0.0831646763271037,2.00389277250337 0.0 -0.0556692403840263,2.00097437989607 0.0 -0.0279025894976502,' + '2.0 0.0 -4.8985871965894e-17,2.00097437989607 0.0 0.0279025894976499,2.00389277250337 0.0 0.0556692403840262,2.00874095970648 0.0 0.0831646763271036,2.01549532162467 0.0 0.1102549423268,2.02412295168564 0.0 0.136808057330267,2.03458181694296 0.0 0.16269465723032,2.04682096285643 0.0 0.187788625114356,2.06078076153743 0.0 0.211967705693282,2.07639320225002 0.0 0.235114100916989,2.09358222275241 0.0 0.257115043874616,2.11226407986454 0.0 0.277863348183599,2.13234775745646 0.0 0.297257930190958,2.15373540986974 0.0 0.315204301442689,2.1763228386117 -0.0 0.331615029022017,2.2 -0.0 0.346410161513775,2.22465154128437 -0.0 0.359517618519667,2.25015736263363 -0.0 0.370873541826715,2.27639320225002 -0.0 0.380422606518061,2.30323124176013 -0.0 0.388118290510399,2.33054072893323 -0.0 0.393923101204883,2.35818861469294 -0.0 0.397808758147309,2.386040201319 -0.0 0.399756330807638,2.413959798681 -0.0 0.399756330807638,2.44181138530706 -0.0 0.397808758147309,2.46945927106677 -0.0 0.393923101204883,2.49676875823987 -0.0 0.388118290510399,2.52360679774998 -0.0 0.380422606518061,2.54984263736636 -0.0 0.370873541826715,2.57534845871563 -0.0 0.359517618519667,2.6 -0.0 0.346410161513775,2.6236771613883 -0.0 0.331615029022017,2.64626459013026 -0.0 0.315204301442689,2.66765224254354 -0.0 0.297257930190958,2.68773592013546 -0.0 0.277863348183599,2.70641777724759 -0.0 0.257115043874616,2.72360679774998 -0.0 0.235114100916989,2.73921923846257 -0.0 0.211967705693282,2.75317903714357 -0.0 0.187788625114356,2.76541818305704 -0.0 0.16269465723032,2.77587704831436 -0.0 0.136808057330267,2.78450467837533 -0.0 0.1102549423268,2.79125904029352 -0.0 0.0831646763271039,2.79610722749663 -0.0 0.0556692403840264,2.79902562010393 -0.0 0.0279025894976499,2.8 -0.0 1e-31)),' + '((2.8 1.8 3.6e-16,2.79902562010393 1.8 -0.0279025894976498,2.79610722749663 1.8 -0.0556692403840258,2.79125904029352 1.8 -0.0831646763271034,2.78450467837533 1.8 -0.110254942326799,2.77587704831436 1.8 -0.136808057330267,2.76541818305704 1.8 -0.16269465723032,2.75317903714357 1.8 -0.187788625114356,2.73921923846257 1.8 -0.211967705693282,2.72360679774998 1.8 -0.235114100916989,2.70641777724759 1.8 -0.257115043874615,2.68773592013546 1.8 -0.277863348183599,2.66765224254354 1.8 -0.297257930190957,2.64626459013026 1.8 -0.315204301442689,2.6236771613883 1.8 -0.331615029022016,2.6 1.8 -0.346410161513775,2.57534845871563 1.8 -0.359517618519667,2.54984263736636 1.8 -0.370873541826715,2.52360679774998 1.8 -0.380422606518061,2.49676875823987 1.8 -0.388118290510398,2.46945927106677 1.8 -0.393923101204883,2.44181138530706 1.8 -0.397808758147309,2.413959798681 1.8 -0.399756330807638,2.386040201319 1.8 -0.399756330807638,2.35818861469294 1.8 -0.397808758147309,2.33054072893323 1.8 -0.393923101204883,2.30323124176013 1.8 -0.388118290510398,2.27639320225002 1.8 -0.380422606518061,2.25015736263363 1.8 -0.370873541826715,2.22465154128437 1.8 -0.359517618519666,2.2 1.8 -0.346410161513775,2.1763228386117 1.8 -0.331615029022016,2.15373540986974 1.8 -0.315204301442689,2.13234775745646 1.8 -0.297257930190957,2.11226407986454 1.8 -0.277863348183599,2.09358222275241 1.8 -0.257115043874615,2.07639320225002 1.8 -0.235114100916989,2.06078076153743 1.8 -0.211967705693282,2.04682096285643 1.8 -0.187788625114356,2.03458181694296 1.8 -0.16269465723032,2.02412295168564 1.8 -0.136808057330267,2.01549532162467 1.8 -0.1102549423268,2.00874095970648 1.8 -0.0831646763271034,2.00389277250337 1.8 -0.0556692403840259,2.00097437989607 1.8 -0.0279025894976499,2.0 1.8 3.11014128034106e-16,' + '2.00097437989607 1.8 0.0279025894976503,2.00389277250337 1.8 0.0556692403840266,2.00874095970648 1.8 0.083164676327104,2.01549532162467 1.8 0.1102549423268,2.02412295168564 1.8 0.136808057330268,2.03458181694296 1.8 0.16269465723032,2.04682096285643 1.8 0.187788625114357,2.06078076153743 1.8 0.211967705693282,2.07639320225002 1.8 0.23511410091699,2.09358222275241 1.8 0.257115043874616,2.11226407986454 1.8 0.277863348183599,2.13234775745646 1.8 0.297257930190958,2.15373540986974 1.8 0.315204301442689,2.1763228386117 1.8 0.331615029022017,2.2 1.8 0.346410161513776,2.22465154128437 1.8 0.359517618519667,2.25015736263363 1.8 0.370873541826715,2.27639320225002 1.8 0.380422606518062,2.30323124176013 1.8 0.388118290510399,2.33054072893323 1.8 0.393923101204884,2.35818861469294 1.8 0.39780875814731,2.386040201319 1.8 0.399756330807639,2.413959798681 1.8 0.399756330807639,2.44181138530706 1.8 0.39780875814731,2.46945927106677 1.8 0.393923101204884,2.49676875823987 1.8 0.388118290510399,2.52360679774998 1.8 0.380422606518062,2.54984263736636 1.8 0.370873541826715,2.57534845871563 1.8 0.359517618519667,2.6 1.8 0.346410161513776,2.6236771613883 1.8 0.331615029022017,2.64626459013026 1.8 0.315204301442689,2.66765224254354 1.8 0.297257930190958,2.68773592013546 1.8 0.277863348183599,2.70641777724759 1.8 0.257115043874616,2.72360679774998 1.8 0.23511410091699,2.73921923846257 1.8 0.211967705693283,2.75317903714357 1.8 0.187788625114357,2.76541818305704 1.8 0.16269465723032,2.77587704831436 1.8 0.136808057330268,2.78450467837533 1.8 0.1102549423268,2.79125904029352 1.8 0.0831646763271043,2.79610722749663 1.8 0.0556692403840267,2.79902562010393 1.8 0.0279025894976503,2.8 1.8 3.6e-16)),' + '((2.0 0.0 -4.8985871965894e-17,2.00097437989607 0.0 -0.0279025894976502,2.00389277250337 0.0 -0.0556692403840263,2.00874095970648 0.0 -0.0831646763271037,2.01549532162467 0.0 -0.1102549423268,2.02412295168564 0.0 -0.136808057330268,2.03458181694296 0.0 -0.16269465723032,2.04682096285643 0.0 -0.187788625114356,2.06078076153743 0.0 -0.211967705693282,2.07639320225002 0.0 -0.235114100916989,2.09358222275241 0.0 -0.257115043874616,2.11226407986454 0.0 -0.277863348183599,2.13234775745646 0.0 -0.297257930190958,2.15373540986974 0.0 -0.315204301442689,2.1763228386117 0.0 -0.331615029022017,2.2 0.0 -0.346410161513776,2.22465154128437 0.0 -0.359517618519667,2.25015736263363 0.0 -0.370873541826715,2.27639320225002 0.0 -0.380422606518061,2.30323124176013 0.0 -0.388118290510399,2.33054072893323 0.0 -0.393923101204883,2.35818861469294 0.0 -0.397808758147309,2.386040201319 0.0 -0.399756330807638,2.413959798681 0.0 -0.399756330807638,2.44181138530706 0.0 -0.397808758147309,2.46945927106677 0.0 -0.393923101204883,2.49676875823987 0.0 -0.388118290510399,2.52360679774998 0.0 -0.380422606518061,2.54984263736636 0.0 -0.370873541826715,2.57534845871563 0.0 -0.359517618519667,2.6 0.0 -0.346410161513775,2.6236771613883 0.0 -0.331615029022017,2.64626459013026 0.0 -0.315204301442689,2.66765224254354 0.0 -0.297257930190958,2.68773592013546 0.0 -0.277863348183599,2.70641777724759 0.0 -0.257115043874616,2.72360679774998 0.0 -0.235114100916989,2.73921923846257 -0.0 -0.211967705693282,2.75317903714357 -0.0 -0.187788625114356,2.76541818305704 -0.0 -0.16269465723032,2.77587704831436 -0.0 -0.136808057330267,2.78450467837533 -0.0 -0.1102549423268,2.79125904029352 -0.0 -0.0831646763271037,2.79610722749663 -0.0 -0.0556692403840262,2.79902562010393 -0.0 -0.0279025894976501,' + '2.8 -0.0 1e-31,2.8 1.8 3.6e-16,2.79902562010393 1.8 -0.0279025894976498,2.79610722749663 1.8 -0.0556692403840258,2.79125904029352 1.8 -0.0831646763271034,2.78450467837533 1.8 -0.110254942326799,2.77587704831436 1.8 -0.136808057330267,2.76541818305704 1.8 -0.16269465723032,2.75317903714357 1.8 -0.187788625114356,2.73921923846257 1.8 -0.211967705693282,2.72360679774998 1.8 -0.235114100916989,2.70641777724759 1.8 -0.257115043874615,2.68773592013546 1.8 -0.277863348183599,2.66765224254354 1.8 -0.297257930190957,2.64626459013026 1.8 -0.315204301442689,2.6236771613883 1.8 -0.331615029022016,2.6 1.8 -0.346410161513775,2.57534845871563 1.8 -0.359517618519667,2.54984263736636 1.8 -0.370873541826715,2.52360679774998 1.8 -0.380422606518061,2.49676875823987 1.8 -0.388118290510398,2.46945927106677 1.8 -0.393923101204883,2.44181138530706 1.8 -0.397808758147309,2.413959798681 1.8 -0.399756330807638,2.386040201319 1.8 -0.399756330807638,2.35818861469294 1.8 -0.397808758147309,2.33054072893323 1.8 -0.393923101204883,2.30323124176013 1.8 -0.388118290510398,2.27639320225002 1.8 -0.380422606518061,2.25015736263363 1.8 -0.370873541826715,2.22465154128437 1.8 -0.359517618519666,2.2 1.8 -0.346410161513775,2.1763228386117 1.8 -0.331615029022016,2.15373540986974 1.8 -0.315204301442689,2.13234775745646 1.8 -0.297257930190957,2.11226407986454 1.8 -0.277863348183599,2.09358222275241 1.8 -0.257115043874615,2.07639320225002 1.8 -0.235114100916989,2.06078076153743 1.8 -0.211967705693282,2.04682096285643 1.8 -0.187788625114356,2.03458181694296 1.8 -0.16269465723032,2.02412295168564 1.8 -0.136808057330267,2.01549532162467 1.8 -0.1102549423268,2.00874095970648 1.8 -0.0831646763271034,2.00389277250337 1.8 -0.0556692403840259,2.00097437989607 1.8 -0.0279025894976499,2.0 1.8 3.11014128034106e-16,2.0 0.0 -4.8985871965894e-17)),' + '((2.8 -0.0 1e-31,2.79902562010393 -0.0 0.0279025894976499,2.79610722749663 -0.0 0.0556692403840264,2.79125904029352 -0.0 0.0831646763271039,2.78450467837533 -0.0 0.1102549423268,2.77587704831436 -0.0 0.136808057330267,2.76541818305704 -0.0 0.16269465723032,2.75317903714357 -0.0 0.187788625114356,2.73921923846257 -0.0 0.211967705693282,2.72360679774998 -0.0 0.235114100916989,2.70641777724759 -0.0 0.257115043874616,2.68773592013546 -0.0 0.277863348183599,2.66765224254354 -0.0 0.297257930190958,2.64626459013026 -0.0 0.315204301442689,2.6236771613883 -0.0 0.331615029022017,2.6 -0.0 0.346410161513775,2.57534845871563 -0.0 0.359517618519667,2.54984263736636 -0.0 0.370873541826715,2.52360679774998 -0.0 0.380422606518061,2.49676875823987 -0.0 0.388118290510399,2.46945927106677 -0.0 0.393923101204883,2.44181138530706 -0.0 0.397808758147309,2.413959798681 -0.0 0.399756330807638,2.386040201319 -0.0 0.399756330807638,2.35818861469294 -0.0 0.397808758147309,2.33054072893323 -0.0 0.393923101204883,2.30323124176013 -0.0 0.388118290510399,2.27639320225002 -0.0 0.380422606518061,2.25015736263363 -0.0 0.370873541826715,2.22465154128437 -0.0 0.359517618519667,2.2 -0.0 0.346410161513775,2.1763228386117 -0.0 0.331615029022017,2.15373540986974 0.0 0.315204301442689,2.13234775745646 0.0 0.297257930190958,2.11226407986454 0.0 0.277863348183599,2.09358222275241 0.0 0.257115043874616,2.07639320225002 0.0 0.235114100916989,2.06078076153743 0.0 0.211967705693282,2.04682096285643 0.0 0.187788625114356,2.03458181694296 0.0 0.16269465723032,2.02412295168564 0.0 0.136808057330267,2.01549532162467 0.0 0.1102549423268,2.00874095970648 0.0 0.0831646763271036,2.00389277250337 0.0 0.0556692403840262,2.00097437989607 0.0 0.0279025894976499,' + - '2.0 0.0 -4.8985871965894e-17,2.0 1.8 3.11014128034106e-16,2.00097437989607 1.8 0.0279025894976503,2.00389277250337 1.8 0.0556692403840266,2.00874095970648 1.8 0.083164676327104,2.01549532162467 1.8 0.1102549423268,2.02412295168564 1.8 0.136808057330268,2.03458181694296 1.8 0.16269465723032,2.04682096285643 1.8 0.187788625114357,2.06078076153743 1.8 0.211967705693282,2.07639320225002 1.8 0.23511410091699,2.09358222275241 1.8 0.257115043874616,2.11226407986454 1.8 0.277863348183599,2.13234775745646 1.8 0.297257930190958,2.15373540986974 1.8 0.315204301442689,2.1763228386117 1.8 0.331615029022017,2.2 1.8 0.346410161513776,2.22465154128437 1.8 0.359517618519667,2.25015736263363 1.8 0.370873541826715,2.27639320225002 1.8 0.380422606518062,2.30323124176013 1.8 0.388118290510399,2.33054072893323 1.8 0.393923101204884,2.35818861469294 1.8 0.39780875814731,2.386040201319 1.8 0.399756330807639,2.413959798681 1.8 0.399756330807639,2.44181138530706 1.8 0.39780875814731,2.46945927106677 1.8 0.393923101204884,2.49676875823987 1.8 0.388118290510399,2.52360679774998 1.8 0.380422606518062,2.54984263736636 1.8 0.370873541826715,2.57534845871563 1.8 0.359517618519667,2.6 1.8 0.346410161513776,2.6236771613883 1.8 0.331615029022017,2.64626459013026 1.8 0.315204301442689,2.66765224254354 1.8 0.297257930190958,2.68773592013546 1.8 0.277863348183599,2.70641777724759 1.8 0.257115043874616,2.72360679774998 1.8 0.23511410091699,2.73921923846257 1.8 0.211967705693283,2.75317903714357 1.8 0.187788625114357,2.76541818305704 1.8 0.16269465723032,2.77587704831436 1.8 0.136808057330268,2.78450467837533 1.8 0.1102549423268,2.79125904029352 1.8 0.0831646763271043,2.79610722749663 1.8 0.0556692403840267,2.79902562010393 1.8 0.0279025894976503,2.8 1.8 3.6e-16,2.8 -0.0 1e-31)))'): - gdaltest.post_reason('wrong geometry for cylinder') - return 'fail' + '2.0 0.0 -4.8985871965894e-17,2.0 1.8 3.11014128034106e-16,2.00097437989607 1.8 0.0279025894976503,2.00389277250337 1.8 0.0556692403840266,2.00874095970648 1.8 0.083164676327104,2.01549532162467 1.8 0.1102549423268,2.02412295168564 1.8 0.136808057330268,2.03458181694296 1.8 0.16269465723032,2.04682096285643 1.8 0.187788625114357,2.06078076153743 1.8 0.211967705693282,2.07639320225002 1.8 0.23511410091699,2.09358222275241 1.8 0.257115043874616,2.11226407986454 1.8 0.277863348183599,2.13234775745646 1.8 0.297257930190958,2.15373540986974 1.8 0.315204301442689,2.1763228386117 1.8 0.331615029022017,2.2 1.8 0.346410161513776,2.22465154128437 1.8 0.359517618519667,2.25015736263363 1.8 0.370873541826715,2.27639320225002 1.8 0.380422606518062,2.30323124176013 1.8 0.388118290510399,2.33054072893323 1.8 0.393923101204884,2.35818861469294 1.8 0.39780875814731,2.386040201319 1.8 0.399756330807639,2.413959798681 1.8 0.399756330807639,2.44181138530706 1.8 0.39780875814731,2.46945927106677 1.8 0.393923101204884,2.49676875823987 1.8 0.388118290510399,2.52360679774998 1.8 0.380422606518062,2.54984263736636 1.8 0.370873541826715,2.57534845871563 1.8 0.359517618519667,2.6 1.8 0.346410161513776,2.6236771613883 1.8 0.331615029022017,2.64626459013026 1.8 0.315204301442689,2.66765224254354 1.8 0.297257930190958,2.68773592013546 1.8 0.277863348183599,2.70641777724759 1.8 0.257115043874616,2.72360679774998 1.8 0.23511410091699,2.73921923846257 1.8 0.211967705693283,2.75317903714357 1.8 0.187788625114357,2.76541818305704 1.8 0.16269465723032,2.77587704831436 1.8 0.136808057330268,2.78450467837533 1.8 0.1102549423268,2.79125904029352 1.8 0.0831646763271043,2.79610722749663 1.8 0.0556692403840267,2.79902562010393 1.8 0.0279025894976503,2.8 1.8 3.6e-16,2.8 -0.0 1e-31)))')), \ + 'wrong geometry for cylinder' # 3DSOLID, plain feat = layer.GetNextFeature() if feat.GetGeometryRef() is not None: feat.DumpReadable() - gdaltest.post_reason('geometry on first 3DSOLID was not empty') - return 'fail' + pytest.fail('geometry on first 3DSOLID was not empty') if feat.GetFieldAsBinary('ASMData') != b'ACIS BinaryFile(U\x00\x00\x00\x00\x00\x00\x02\x00\x00\x00\x0c\x00\x00\x00\x07\x10Autodesk AutoCAD\x07\x13ASM 221.0.0.1871 NT\x07\x18Sun Mar 04 15:10:20 2018\x06ffffff9@\x06\x8d\xed\xb5\xa0\xf7\xc6\xb0>\x06\xbb\xbd\xd7\xd9\xdf|\xdb=\r\tasmheader\x0c\xff\xff\xff\xff\x04\xff\xff\xff\xff\x07\x0c221.0.0.1871\x11\r\x04body\x0c\xff\xff\xff\xff\x04\xff\xff\xff\xff\x0c\xff\xff\xff\xff\x0c\x02\x00\x00\x00\x0c\xff\xff\xff\xff\x0c\x03\x00\x00\x00\x11\r\x04lump\x0c\xff\xff\xff\xff\x04\xff\xff\xff\xff\x0c\xff\xff\xff\xff\x0c\xff\xff\xff\xff\x0c\x04\x00\x00\x00\x0c\x01\x00\x00\x00\x11\r\ttransform\x0c\xff\xff\xff\xff\x04\xff\xff\xff\xff\x14\x00\x00\x00\x00\x00\x00\xf0?\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x14\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xf0?\x00\x00\x00\x00\x00\x00\x00\x00\x14\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xf0?\x14\x00\x00\x00\x00\x00\x00\x10@\x00\x00\x00\x00\x00\x00\xf0?\x00\x00\x00\x00\x00\x00\x00\x00\x06\x00\x00\x00\x00\x00\x00\xf0?\x0b\x0b\x0b\x11\r\x05shell\x0c\xff\xff\xff\xff\x04\xff\xff\xff\xff\x0c\xff\xff\xff\xff\x0c\xff\xff\xff\xff\x0c\xff\xff\xff\xff\x0c\x05\x00\x00\x00\x0c\xff\xff\xff\xff\x0c\x02\x00\x00\x00\x11\r\x04face\x0c\x06\x00\x00\x00\x04\xff\xff\xff\xff\x0c\xff\xff\xff\xff\x0c\xff\xff\xff\xff\x0c\xff\xff\xff\xff\x0c\x04\x00\x00\x00\x0c\xff\xff\xff\xff\x0c\x07\x00\x00\x00\x0b\x0b\x11\x0e\tpersubent\x0e\x10acadSolidHistory\r\x06attrib\x0c\xff\xff\xff\xff\x04\xff\xff\xff\xff\x0c\xff\xff\xff\xff\x0c\xff\xff\xff\xff\x0c\x05\x00\x00\x00\x04\x01\x00\x00\x00\x04\x02\x00\x00\x00\x04\x01\x00\x00\x00\x04\x00\x00\x00\x00\x11\x0e\x06sphere\r\x07surface\x0c\xff\xff\xff\xff\x04\xff\xff\xff\xff\x0c\xff\xff\xff\xff\x13\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x06\xcd;\x7ff\x9e\xa0\xe6?\x14\x00\x00\x00\x00\x00\x00\xf0?\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x14\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xf0?\x0b\x0b\x0b\x0b\x0b\x11\x0e\x03End\x0e\x02of\x0e\x03ASM\r\x04data': feat.DumpReadable() - gdaltest.post_reason('wrong ASMData on first 3DSOLID') - return 'fail' + pytest.fail('wrong ASMData on first 3DSOLID') if feat.GetField('ASMTransform') != [1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0]: feat.DumpReadable() - gdaltest.post_reason('wrong ASMTransform on first 3DSOLID') - return 'fail' + pytest.fail('wrong ASMTransform on first 3DSOLID') if feat.GetStyleString() != 'BRUSH(fc:#000000)': feat.DumpReadable() - gdaltest.post_reason('wrong style string on first 3DSOLID') - return 'fail' + pytest.fail('wrong style string on first 3DSOLID') # 3DSOLID inside a block feat = layer.GetNextFeature() if feat.GetGeometryRef() is not None: feat.DumpReadable() - gdaltest.post_reason('geometry on second 3DSOLID was not empty') - return 'fail' + pytest.fail('geometry on second 3DSOLID was not empty') if feat.GetFieldAsBinary('ASMData') != b'ACIS BinaryFile(U\x00\x00\x00\x00\x00\x00\x02\x00\x00\x00\x0c\x00\x00\x00\x07\x10Autodesk AutoCAD\x07\x13ASM 221.0.0.1871 NT\x07\x18Sun Mar 04 15:10:20 2018\x06ffffff9@\x06\x8d\xed\xb5\xa0\xf7\xc6\xb0>\x06\xbb\xbd\xd7\xd9\xdf|\xdb=\r\tasmheader\x0c\xff\xff\xff\xff\x04\xff\xff\xff\xff\x07\x0c221.0.0.1871\x11\r\x04body\x0c\xff\xff\xff\xff\x04\xff\xff\xff\xff\x0c\xff\xff\xff\xff\x0c\x02\x00\x00\x00\x0c\xff\xff\xff\xff\x0c\x03\x00\x00\x00\x11\r\x04lump\x0c\xff\xff\xff\xff\x04\xff\xff\xff\xff\x0c\xff\xff\xff\xff\x0c\xff\xff\xff\xff\x0c\x04\x00\x00\x00\x0c\x01\x00\x00\x00\x11\r\ttransform\x0c\xff\xff\xff\xff\x04\xff\xff\xff\xff\x14\x00\x00\x00\x00\x00\x00\xf0?\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x14\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xf0?\x00\x00\x00\x00\x00\x00\x00\x00\x14\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xf0?\x14\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x06\x00\x00\x00\x00\x00\x00\xf0?\x0b\x0b\x0b\x11\r\x05shell\x0c\xff\xff\xff\xff\x04\xff\xff\xff\xff\x0c\xff\xff\xff\xff\x0c\xff\xff\xff\xff\x0c\xff\xff\xff\xff\x0c\x05\x00\x00\x00\x0c\xff\xff\xff\xff\x0c\x02\x00\x00\x00\x11\r\x04face\x0c\x06\x00\x00\x00\x04\xff\xff\xff\xff\x0c\xff\xff\xff\xff\x0c\xff\xff\xff\xff\x0c\xff\xff\xff\xff\x0c\x04\x00\x00\x00\x0c\xff\xff\xff\xff\x0c\x07\x00\x00\x00\x0b\x0b\x11\x0e\tpersubent\x0e\x10acadSolidHistory\r\x06attrib\x0c\xff\xff\xff\xff\x04\xff\xff\xff\xff\x0c\xff\xff\xff\xff\x0c\xff\xff\xff\xff\x0c\x05\x00\x00\x00\x04\x01\x00\x00\x00\x04\x04\x00\x00\x00\x04\x01\x00\x00\x00\x04\x00\x00\x00\x00\x11\x0e\x06sphere\r\x07surface\x0c\xff\xff\xff\xff\x04\xff\xff\xff\xff\x0c\xff\xff\xff\xff\x13\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x06\x00\x00\x00\x00\x00\x00\x00@\x14\x00\x00\x00\x00\x00\x00\xf0?\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x14\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xf0?\x0b\x0b\x0b\x0b\x0b\x11\x0e\x03End\x0e\x02of\x0e\x03ASM\r\x04data': feat.DumpReadable() - gdaltest.post_reason('wrong ASMData on second 3DSOLID') - return 'fail' + pytest.fail('wrong ASMData on second 3DSOLID') if feat.GetField('ASMTransform') != [-0.18750000000000006, 0.08660254037844387, 0.0, 0.3247595264191645, 0.05000000000000002, 0.0, 0.0, 0.0, -1.0, 5.75, 1.125, 0.0]: feat.DumpReadable() - gdaltest.post_reason('wrong ASMTransform on second 3DSOLID') - return 'fail' + pytest.fail('wrong ASMTransform on second 3DSOLID') if feat.GetStyleString() != 'BRUSH(fc:#ff0000)': feat.DumpReadable() - gdaltest.post_reason('wrong style string on second 3DSOLID') - return 'fail' - - return 'success' + pytest.fail('wrong style string on second 3DSOLID') + ############################################################################### # Writing Triangle geometry and checking if it is written properly -def ogr_dxf_34(): +def test_ogr_dxf_34(): ds = ogr.GetDriverByName('DXF').CreateDataSource('tmp/triangle_test.dxf') lyr = ds.CreateLayer('entities') dst_feat = ogr.Feature(feature_def=lyr.GetLayerDefn()) @@ -2590,20 +2343,17 @@ def ogr_dxf_34(): expected_wkt = 'POLYGON ((0 0,0 1,1 0,0 0))' received_wkt = geom.ExportToWkt() - if expected_wkt != received_wkt: - gdaltest.post_reason('did not get expected geometry back: got %s' % received_wkt) - return 'fail' + assert expected_wkt == received_wkt, \ + ('did not get expected geometry back: got %s' % received_wkt) ds = None gdal.Unlink('tmp/triangle_test.dxf') - return 'success' - ############################################################################### # Test reading hatch with elliptical harts -def ogr_dxf_35(): +def test_ogr_dxf_35(): ds = ogr.Open('data/elliptical-arc-hatch-min.dxf') lyr = ds.GetLayer(0) @@ -2702,31 +2452,25 @@ def ogr_dxf_35(): "13.3027626235603 8.26630944469236 0," + \ "10.0 5.0 0," + \ "10.0 5.0 0))""" - if ogrtest.check_feature_geometry(feat, expected_wkt) != 0: - return 'fail' - - return 'success' + assert ogrtest.check_feature_geometry(feat, expected_wkt) == 0 ############################################################################### # Test reading files with only INSERT content (#7006) -def ogr_dxf_36(): +def test_ogr_dxf_36(): gdal.SetConfigOption('DXF_MERGE_BLOCK_GEOMETRIES', 'FALSE') ds = ogr.Open('data/insert_only.dxf') gdal.SetConfigOption('DXF_MERGE_BLOCK_GEOMETRIES', None) lyr = ds.GetLayer(0) - if lyr.GetFeatureCount() != 5: - return 'fail' - - return 'success' + assert lyr.GetFeatureCount() == 5 ############################################################################### # Create a blocks layer only -def ogr_dxf_37(): +def test_ogr_dxf_37(): ds = ogr.GetDriverByName('DXF').CreateDataSource('/vsimem/ogr_dxf_37.dxf') @@ -2748,82 +2492,71 @@ def ogr_dxf_37(): # Check first feature feat = lyr.GetNextFeature() - if feat is None: - return 'fail' + assert feat is not None ds = None gdal.Unlink('/vsimem/ogr_dxf_37.dxf') - return 'success' - ############################################################################### # Test degenerated cases of SOLID (#7038) -def ogr_dxf_38(): +def test_ogr_dxf_38(): ds = ogr.Open('data/solid-less-than-4-vertices.dxf') lyr = ds.GetLayer(0) f = lyr.GetNextFeature() if f.GetGeometryRef().ExportToWkt() != 'POINT (0 2)' \ or f.GetStyleString() != 'PEN(c:#000000)': - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' + pytest.fail() f = lyr.GetNextFeature() if f.GetGeometryRef().ExportToWkt() != 'LINESTRING (0.5 2.0,1 2)' \ or f.GetStyleString() != 'PEN(c:#000000)': - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' - - return 'success' + pytest.fail() + ############################################################################### # Test correct reordering of vertices in SOLID (#7038, #7089) -def ogr_dxf_39(): +def test_ogr_dxf_39(): ds = ogr.Open('data/solid-vertex-ordering.dxf') lyr = ds.GetLayer(0) f = lyr.GetNextFeature() if f.GetGeometryRef().ExportToWkt() != 'POLYGON ((0 5,1.5 2.5,1.5 0.0,0.0 2.5,0 5))': - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' + pytest.fail() f = lyr.GetNextFeature() if f.GetGeometryRef().ExportToIsoWkt() != 'POLYGON Z ((-10 13 123,10 10 123,5 12 123,8 13 123,-10 13 123))': - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' - - return 'success' + pytest.fail() + ############################################################################### # Test handing of OCS vs WCS for MTEXT (#7049) -def ogr_dxf_40(): +def test_ogr_dxf_40(): ds = ogr.Open('data/mtext-ocs-reduced.dxf') lyr = ds.GetLayer(0) f = lyr.GetFeature(5) if ogrtest.check_feature_geometry(f, 'POINT (320000.0 5815007.5 0)') != 0: - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' - - return 'success' + pytest.fail() + ############################################################################### # Test handing of OCS vs WCS for SOLID, HATCH and INSERT (#7077, #7098) -def ogr_dxf_41(): +def test_ogr_dxf_41(): ds = ogr.Open('data/ocs2wcs3.dxf') lyr = ds.GetLayer(0) @@ -2831,24 +2564,21 @@ def ogr_dxf_41(): # INSERT #1: OCS normal vector (0,0,-1) f = lyr.GetFeature(1) if ogrtest.check_feature_geometry(f, 'LINESTRING (45 20,25 20,25 40,45 40,45 20)') != 0: - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' + pytest.fail() # INSERT #2: OCS normal vector (0,1/sqrt(2),-1/sqrt(2)) f = lyr.GetFeature(3) if ogrtest.check_feature_geometry(f, 'LINESTRING Z (10.0 18.0 -76.3675323681472,-10.0 18.0 -76.3675323681472,-10.0 32.142135623731 -62.2253967444162,10.0 32.142135623731 -62.2253967444162,10.0 18.0 -76.3675323681472)') != 0: - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' + pytest.fail() # INSERT #3: OCS normal vector (0.6,sqrt(8)/5,sqrt(8)/5) with # Y scale factor of 2 and rotation angle of 45 degrees f = lyr.GetFeature(5) if ogrtest.check_feature_geometry(f, 'LINESTRING Z (49.7198871869889 -21.8420670839387 75.1721817670195,34.1976071850546 -17.0401066991021 86.8340855568821,41.9587471852111 -48.595846365317 110.157893136607,57.4810271871454 -53.3978067501536 98.4959893467447,49.7198871869889 -21.8420670839387 75.1721817670195)') != 0: - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' + pytest.fail() # HATCH f = lyr.GetFeature(7) @@ -2907,31 +2637,27 @@ def ogr_dxf_41(): "-4.0 41.0121933088198 -132.936074863071," + \ "-4.0 41.0121933088198 -132.936074863071))" if ogrtest.check_feature_geometry(f, expected_wkt) != 0: - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' + pytest.fail() # SOLID f = lyr.GetFeature(9) if ogrtest.check_feature_geometry(f, 'POLYGON Z ((-10.0 13.0 124,8.0 13.0 124,5.0 12.0 123,10.0 10.0 121,-10.0 13.0 124))') != 0: - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' - - return 'success' + pytest.fail() + ############################################################################### # Test insertion of blocks within blocks (#7106) -def ogr_dxf_42(): +def test_ogr_dxf_42(): # Inlining, merging ds = ogr.Open('data/block-insert-order.dxf') lyr = ds.GetLayer(0) - if lyr.GetFeatureCount() != 2: - gdaltest.post_reason('Defaults: Expected 2 features, found %d' % lyr.GetFeatureCount()) - return 'fail' + assert lyr.GetFeatureCount() == 2, \ + ('Defaults: Expected 2 features, found %d' % lyr.GetFeatureCount()) # No inlining, merging gdal.SetConfigOption('DXF_INLINE_BLOCKS', 'FALSE') @@ -2939,57 +2665,40 @@ def ogr_dxf_42(): gdal.SetConfigOption('DXF_INLINE_BLOCKS', None) lyr = ds.GetLayerByName('entities') - if lyr.GetFeatureCount() != 2: - gdaltest.post_reason('No inlining: Expected 2 features on entities, found %d' % lyr.GetFeatureCount()) - return 'fail' + assert lyr.GetFeatureCount() == 2, \ + ('No inlining: Expected 2 features on entities, found %d' % lyr.GetFeatureCount()) f = lyr.GetNextFeature() if ogrtest.check_feature_geometry(f, 'POINT Z (8.0 2.5 6)') != 0: - gdaltest.post_reason('Wrong geometry for first insertion point') f.DumpReadable() - return 'fail' + pytest.fail('Wrong geometry for first insertion point') f = lyr.GetNextFeature() if ogrtest.check_feature_geometry(f, 'POINT Z (-1 -2 -3)') != 0: - gdaltest.post_reason('Wrong geometry for second insertion point') f.DumpReadable() - return 'fail' + pytest.fail('Wrong geometry for second insertion point') lyr = ds.GetLayerByName('blocks') - if lyr.GetFeatureCount() != 6: - gdaltest.post_reason('No inlining: Expected 6 feature on blocks, found %d' % lyr.GetFeatureCount()) - return 'fail' + assert lyr.GetFeatureCount() == 6, \ + ('No inlining: Expected 6 feature on blocks, found %d' % lyr.GetFeatureCount()) f = lyr.GetFeature(3) if ogrtest.check_feature_geometry(f, 'POINT Z (5 5 0)') != 0: - gdaltest.post_reason('Wrong geometry for second insertion of BLOCK4 on BLOCK3') f.DumpReadable() - return 'fail' + pytest.fail('Wrong geometry for second insertion of BLOCK4 on BLOCK3') f = lyr.GetFeature(4) if ogrtest.check_feature_geometry(f, 'POINT Z (-5.48795472456028 1.69774937525433 4.12310562561766)') != 0: - gdaltest.post_reason('Wrong geometry for third insertion of BLOCK4 on BLOCK3') - f.DumpReadable() - return 'fail' - - if f.GetField('BlockName') != 'BLOCK4': - gdaltest.post_reason('Wrong BlockName') - return 'fail' - if f.GetField('BlockScale') != [0.4, 1.0, 1.5]: - gdaltest.post_reason('Wrong BlockScale') - return 'fail' - if f.GetField('BlockAngle') != 40: - gdaltest.post_reason('Wrong BlockAngle') - return 'fail' - if f.GetField('BlockOCSNormal') != [0.6, 0.565685424949238, 0.565685424949238]: - gdaltest.post_reason('Wrong BlockOCSNormal') - return 'fail' - if f.GetField('BlockOCSCoords') != [5, 5, 0]: - gdaltest.post_reason('Wrong BlockOCSCoords') - return 'fail' - if f.GetField('Block') != 'BLOCK3': - gdaltest.post_reason('Wrong Block') - return 'fail' + f.DumpReadable() + pytest.fail('Wrong geometry for third insertion of BLOCK4 on BLOCK3') + + assert f.GetField('BlockName') == 'BLOCK4', 'Wrong BlockName' + assert f.GetField('BlockScale') == [0.4, 1.0, 1.5], 'Wrong BlockScale' + assert f.GetField('BlockAngle') == 40, 'Wrong BlockAngle' + assert f.GetField('BlockOCSNormal') == [0.6, 0.565685424949238, 0.565685424949238], \ + 'Wrong BlockOCSNormal' + assert f.GetField('BlockOCSCoords') == [5, 5, 0], 'Wrong BlockOCSCoords' + assert f.GetField('Block') == 'BLOCK3', 'Wrong Block' # Inlining, no merging gdal.SetConfigOption('DXF_MERGE_BLOCK_GEOMETRIES', 'FALSE') @@ -2997,39 +2706,31 @@ def ogr_dxf_42(): gdal.SetConfigOption('DXF_MERGE_BLOCK_GEOMETRIES', None) lyr = ds.GetLayer(0) - if lyr.GetFeatureCount() != 4: - gdaltest.post_reason('Merging: Expected 4 features, found %d' % lyr.GetFeatureCount()) - return 'fail' - - return 'success' + assert lyr.GetFeatureCount() == 4, \ + ('Merging: Expected 4 features, found %d' % lyr.GetFeatureCount()) ############################################################################### # Ensure recursively-included blocks don't fail badly -def ogr_dxf_43(): +def test_ogr_dxf_43(): ds = ogr.Open('data/insert-recursive-pair.dxf') lyr = ds.GetLayer(0) - if lyr.GetFeatureCount() != 1: - return 'fail' - - return 'success' + assert lyr.GetFeatureCount() == 1 ############################################################################### # General tests of LEADER and MULTILEADER entities (#7111) -def ogr_dxf_44(): +def test_ogr_dxf_44(): with gdaltest.config_option('DXF_MAX_BSPLINE_CONTROL_POINTS', '1'): ds = ogr.Open('data/leader-mleader.dxf') lyr = ds.GetLayer(0) with gdaltest.error_handler(): lyr.GetFeatureCount() - if gdal.GetLastErrorMsg().find('DXF_MAX_BSPLINE_CONTROL_POINTS') < 0: - gdaltest.post_reason('fail') - return 'fail' + assert gdal.GetLastErrorMsg().find('DXF_MAX_BSPLINE_CONTROL_POINTS') >= 0 ds = ogr.Open('data/leader-mleader.dxf') lyr = ds.GetLayer(0) @@ -3038,15 +2739,13 @@ def ogr_dxf_44(): # (6.0 arrowhead size and 1.5 scale factor) f = lyr.GetNextFeature() if ogrtest.check_feature_geometry(f, 'LINESTRING Z (21 40 0,10 40 0,19.3125 34.6875 0,10.3125 34.6875 0,-13.5990791268758 34.6875 0)') != 0: - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' + pytest.fail() f = lyr.GetNextFeature() if ogrtest.check_feature_geometry(f, 'POLYGON ((21.0 41.5,30 40,21.0 38.5,21.0 41.5))') != 0: - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' + pytest.fail() # Skip text f = lyr.GetNextFeature() @@ -3055,75 +2754,64 @@ def ogr_dxf_44(): f = lyr.GetNextFeature() if f.GetStyleString() != 'PEN(c:#ff0000)' \ or ogrtest.check_feature_geometry(f, 'LINESTRING Z (-20.9782552979609 38.1443878852919 30,-12.2152357926375 44.793971841437 30,-13.7256166009765 49.0748560186272 30,-13.9025293262723 49.0416613258524 30)') != 0: - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' + pytest.fail() f = lyr.GetNextFeature() if f.GetStyleString() != 'BRUSH(fc:#ff0000)' \ or ogrtest.check_feature_geometry(f, 'POLYGON Z ((-20.9601206293303 38.1204894796201 30,-21.121645731992 38.035579873508 30,-20.9963899665916 38.1682862909638 30,-20.9601206293303 38.1204894796201 30))') != 0: - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' + pytest.fail() # LEADER with a custom arrowhead that consists of a polygon and line f = lyr.GetNextFeature() if f.GetStyleString() != 'PEN(c:#00ff00)' \ or ogrtest.check_feature_geometry(f, 'LINESTRING Z (26.8 77.6 0,10 65 0,25 55 0,25 50 0,40 65 0,48 65 0,169.282571623465 65.0 0)') != 0: - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' + pytest.fail() f = lyr.GetNextFeature() if f.GetStyleString() != 'BRUSH(fc:#00ff00)' \ or ogrtest.check_feature_geometry(f, 'POLYGON ((27.2 80.4,30.4 82.8,32.8 79.6,29.6 77.2,27.2 80.4))') != 0: - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' + pytest.fail() f = lyr.GetNextFeature() if f.GetStyleString() != 'PEN(c:#00ff00)' \ or ogrtest.check_feature_geometry(f, 'LINESTRING Z (28.4 78.8 0,26.8 77.6 0)') != 0: - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' + pytest.fail() # Check that the very long text string in the MTEXT entity associated # to this LEADER is captured correctly f = lyr.GetNextFeature() - if len(f.GetField('Text')) != 319: - gdaltest.post_reason('Wrong text length: got %d' % len(f.GetField('Text'))) - return 'fail' + assert len(f.GetField('Text')) == 319, \ + ('Wrong text length: got %d' % len(f.GetField('Text'))) # MULTILEADER with custom arrowhead f = lyr.GetNextFeature() if ogrtest.check_feature_geometry(f, 'MULTILINESTRING ((26.8 32.6,10 20,25 10,25 5,40 20),(40 20,48 20))') != 0: - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' + pytest.fail() f = lyr.GetNextFeature() if ogrtest.check_feature_geometry(f, 'POLYGON ((27.2 35.4,30.4 37.8,32.8 34.6,29.6 32.2,27.2 35.4))') != 0: - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' + pytest.fail() f = lyr.GetNextFeature() if ogrtest.check_feature_geometry(f, 'LINESTRING Z (28.4 33.8 0,26.8 32.6 0)') != 0: - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' + pytest.fail() f = lyr.GetNextFeature() if ogrtest.check_feature_geometry(f, 'POINT (50.0 22.0327421555252)') != 0: - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' + pytest.fail() if f.GetStyleString() != 'LABEL(f:"Arial",t:"Basic Multileader",p:7,s:4g,c:#000000)': - gdaltest.post_reason('Wrong style string on MULTILEADER text') f.DumpReadable() - return 'fail' + pytest.fail('Wrong style string on MULTILEADER text') # There are three LEADERs, followed by two MULTILEADERs, without arrowheads. # In the first LEADER/MULTILEADER, the arrowhead is set to an empty block. @@ -3133,67 +2821,58 @@ def ogr_dxf_44(): for x in range(3): f = lyr.GetNextFeature() geom = f.GetGeometryRef() - if geom.GetGeometryType() != ogr.wkbLineString25D: - gdaltest.post_reason('Unexpected LEADER geometry, expected wkbLineString25D on iteration %d' % x) - return 'fail' + assert geom.GetGeometryType() == ogr.wkbLineString25D, \ + ('Unexpected LEADER geometry, expected wkbLineString25D on iteration %d' % x) for x in range(2): f = lyr.GetNextFeature() geom = f.GetGeometryRef() - if geom.GetGeometryType() != ogr.wkbMultiLineString: - gdaltest.post_reason('Unexpected MULTILEADER geometry, expected wkbMultiLineString on iteration %d' % x) - return 'fail' + assert geom.GetGeometryType() == ogr.wkbMultiLineString, \ + ('Unexpected MULTILEADER geometry, expected wkbMultiLineString on iteration %d' % x) f = lyr.GetNextFeature() geom = f.GetGeometryRef() - if geom.GetGeometryType() != ogr.wkbPoint: - gdaltest.post_reason('Unexpected MULTILEADER geometry, expected wkbPoint on iteration %d' % x) - return 'fail' + assert geom.GetGeometryType() == ogr.wkbPoint, \ + ('Unexpected MULTILEADER geometry, expected wkbPoint on iteration %d' % x) # MULTILEADER with multiple leader lines and formatted text f = lyr.GetNextFeature() if f.GetStyleString() != 'PEN(c:#0000ff)' \ or ogrtest.check_feature_geometry(f, 'MULTILINESTRING ((7.6425115795681 -8.00285406769102,18.2 -20.0),(19.2913880067389 -13.9367332958948,18.2 -20.0),(18.2 -20.0,38 -20),(54.8204921137545 -22.5800753657327,60.2227692307692 -20.0),(60.2227692307692 -20.0,52.2227692307692 -20.0))') != 0: - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' + pytest.fail() f = lyr.GetNextFeature() if f.GetStyleString() != 'BRUSH(fc:#0000ff)' \ or ogrtest.check_feature_geometry(f, 'POLYGON Z ((7.1420359016196 -8.4432726642857 0,5 -5 0,8.1429872575166 -7.56243547109634 0,7.1420359016196 -8.4432726642857 0))') != 0: - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' + pytest.fail() f = lyr.GetNextFeature() if f.GetStyleString() != 'BRUSH(fc:#0000ff)' \ or ogrtest.check_feature_geometry(f, 'POLYGON Z ((18.6352657907565 -13.8186312970179 0,20 -10 0,19.9475102227214 -14.0548352947716 0,18.6352657907565 -13.8186312970179 0))') != 0: - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' + pytest.fail() # Note, the text actually is nine question marks, this is not an encoding error f = lyr.GetNextFeature() if f.GetStyleString() != 'LABEL(f:"Calibri",it:1,t:"?????????",p:7,s:4g,w:40,c:#0000ff)' \ or ogrtest.check_feature_geometry(f, 'POINT (40.0 -17.9846153846154)') != 0: - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' + pytest.fail() # Rotated MULTILEADER with scaled block content, block attributes, and # different leader color f = lyr.GetNextFeature() if f.GetStyleString() != 'PEN(c:#ff00ff)' \ or ogrtest.check_feature_geometry(f, 'MULTILINESTRING ((-41.8919467995818 -22.8930851139176,-36.1215379759023 -17.6108145786645),(-36.1215379759023 -17.6108145786645,-44.0 -19.0))') != 0: - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' + pytest.fail() f = lyr.GetNextFeature() if ogrtest.check_feature_geometry(f, 'POLYGON ((-40.7553616986189 -14.3661762772835,-44.6945927106677 -15.0607689879512,-44 -19,-40.0607689879512 -18.3054072893323,-40.7553616986189 -14.3661762772835),(-41.9142984770378 -17.0075519687798,-41.126452274628 -16.8686334266463,-40.9875337324945 -17.6564796290561,-41.7753799349043 -17.7953981711896,-41.9142984770378 -17.0075519687798),(-42.0532170191713 -16.2197057663701,-42.1921355613049 -15.4318595639603,-41.4042893588951 -15.2929410218268,-41.2653708167616 -16.0807872242365,-42.0532170191713 -16.2197057663701),(-42.7021446794476 -17.1464705109134,-42.563226137314 -17.9343167133231,-43.3510723397238 -18.0732352554567,-43.4899908818573 -17.2853890530469,-42.7021446794476 -17.1464705109134),(-42.8410632215811 -16.3586243085036,-43.6289094239909 -16.4975428506372,-43.7678279661244 -15.7096966482274,-42.9799817637146 -15.5707781060938,-42.8410632215811 -16.3586243085036))') != 0: - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' + pytest.fail() if version_info >= (3, 0, 0): test_text = 'Apples\u00B1' @@ -3205,16 +2884,14 @@ def ogr_dxf_44(): if f.GetStyleString() != 'LABEL(f:"Arial",t:"' + test_text + '",p:2,s:1g,c:#ff0000,a:10)' \ or f.GetField('Text') != test_text \ or ogrtest.check_feature_geometry(f, 'POINT Z (-42.7597068401767 -14.5165110820149 0)') != 0: - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' + pytest.fail() # MULTILEADER with no dogleg f = lyr.GetNextFeature() if ogrtest.check_feature_geometry(f, 'MULTILINESTRING ((-2.39659963256204 -14.5201521575302,-3.98423252456234 -23.1105237601191),(-26.0282877045921 -20.4748699216691,-3.98423252456233 -23.1105237601191))') != 0: - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' + pytest.fail() for x in range(4): f = lyr.GetNextFeature() @@ -3222,111 +2899,85 @@ def ogr_dxf_44(): # MULTILEADER with no leader lines (block content only) f = lyr.GetNextFeature() if ogrtest.check_feature_geometry(f, 'MULTILINESTRING EMPTY') != 0: - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' + pytest.fail() f = lyr.GetNextFeature() if ogrtest.check_feature_geometry(f, 'POLYGON ((-4.98423252456234 -22.1105237601191,-6.98423252456234 -22.1105237601191,-6.98423252456234 -24.1105237601191,-4.98423252456234 -24.1105237601191,-4.98423252456234 -22.1105237601191),(-5.78423252456234 -23.3105237601191,-5.38423252456234 -23.3105237601191,-5.38423252456234 -23.7105237601191,-5.78423252456234 -23.7105237601191,-5.78423252456234 -23.3105237601191),(-5.78423252456234 -22.9105237601191,-5.78423252456234 -22.5105237601191,-5.38423252456234 -22.5105237601191,-5.38423252456234 -22.9105237601191,-5.78423252456234 -22.9105237601191),(-6.18423252456234 -23.3105237601191,-6.18423252456234 -23.7105237601191,-6.58423252456234 -23.7105237601191,-6.58423252456234 -23.3105237601191,-6.18423252456234 -23.3105237601191),(-6.18423252456234 -22.9105237601191,-6.58423252456234 -22.9105237601191,-6.58423252456234 -22.5105237601191,-6.18423252456234 -22.5105237601191,-6.18423252456234 -22.9105237601191))') != 0: - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' + pytest.fail() f = lyr.GetNextFeature() # LEADER with spline path f = lyr.GetNextFeature() if ogrtest.check_feature_geometry(f, 'LINESTRING Z (75 -5 0,75.3293039686015 -5.27450166567948 0,75.686184437139 -5.54808513378289 0,76.0669570707518 -5.8208730793178 0,76.4679375345795 -6.09298817729179 0,76.8854414937615 -6.36455310271241 0,77.3157846134373 -6.63569053058724 0,77.7552825587464 -6.90652313592384 0,78.2002509948283 -7.17717359372979 0,78.6470055868223 -7.44776457901266 0,79.091861999868 -7.71841876678001 0,79.5311358991048 -7.98925883203941 0,79.9611429496723 -8.26040744979843 0,80.3781988167098 -8.53198729506465 0,80.7786191653568 -8.80412104284562 0,81.1587196607529 -9.07693136814892 0,81.5148159680374 -9.35054094598211 0,81.8432237523498 -9.62507245135277 0,82.1402586788297 -9.90064855926846 0,82.4022364126165 -10.1773919447368 0,82.6254726188496 -10.4554252827652 0,82.8062829626685 -10.7348712483614 0,82.9409831092127 -11.0158525165329 0,83.0258887236216 -11.2984917622873 0,83.0573154710347 -11.5829116606322 0,83.0315790165916 -11.869234886575 0,82.9452821800198 -12.1575745539156 0,82.8004070385963 -12.447864666659 0,82.603711185096 -12.7398802214393 0,82.3621180817583 -13.033390692038 0,82.0825511908225 -13.3281655522369 0,81.7719339745283 -13.6239742758175 0,81.4371898951149 -13.9205863365615 0,81.0852424148219 -14.2177712082505 0,80.7230149958886 -14.515298364666 0,80.3574311005547 -14.8129372795898 0,79.9954141910594 -15.1104574268035 0,79.6438877296422 -15.4076282800887 0,79.3097751785426 -15.704219313227 0,79 -16 0)') != 0: - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' + pytest.fail() # MULTILEADER with spline path including an arrowhead on one leader line, # and text on an angle f = lyr.GetNextFeature() if ogrtest.check_feature_geometry(f, 'MULTILINESTRING ((97.9154085227223 -24.4884177083425,98.2307499443399 -23.8667044316857,98.5274844683239 -23.1977407715784,98.8076056908493 -22.4865892691047,99.0731072080911 -21.7383124653484,99.3259826162243 -20.9579729013935,99.568225511424 -20.1506331183241,99.8018294898652 -19.3213556572241,100.028788147723 -18.4752030591775,100.251095081172 -17.6172378652682,100.470743886388 -16.7525226165803,100.689728159546 -15.8861198541978,100.91004149682 -15.0230921192046,101.133677494386 -14.1685019526847,101.362629748419 -13.327411895722,101.598891855094 -12.5048844894007,101.844457410585 -11.7059822748045,102.101320011068 -10.9357677930177,102.371473252719 -10.199303585124,102.656910731711 -9.50165219220749,102.95962604422 -8.84787615535218,103.281612786421 -8.24303801564202,103.624864554489 -7.69220031416101,103.991374944599 -7.20042559199311,104.383137552927 -6.77277639022231,104.802145975646 -6.41431524993259,105.250393808933 -6.13010471220794,105.729874648962 -5.92520731813233,106.242582091908 -5.80468560878975,106.790509733946 -5.77360212526418,107.375651171252 -5.8370194086396,108.0 -6.0),(99.0 -4.0,99.2390786191346 -4.00918383080352,99.4787687119818 -4.01534615590692,99.7189331856537 -4.01916439926796,99.9594349472622 -4.02131598484443,100.200136903919 -4.02247833659411,100.440901962737 -4.02332887847475,100.681593030828 -4.02454503444416,100.922073015303 -4.02680422846008,101.162204823276 -4.03078388448032,101.401851361856 -4.03716142646263,101.640875538158 -4.0466142783648,101.879140259293 -4.0598198641446,102.116508432372 -4.07745560775981,102.352842964508 -4.1001989331682,102.588006762813 -4.12872726432755,102.821862734399 -4.16371802519564,103.054283542724 -4.20580126092676,103.285277318696 -4.25494915918985,103.514951346557 -4.31065239888725,103.743415181632 -4.37239063008777,103.970778379245 -4.43964350286021,104.19715049472 -4.51189066727337,104.422641083382 -4.58861177339606,104.647359700555 -4.66928647129708,104.871415901564 -4.75339441104525,105.094919241732 -4.84041524270936,105.317979276384 -4.92982861635822,105.540705560844 -5.02111418206063,105.763207650437 -5.11375158988541,105.985595100486 -5.20722048990135,106.207977466317 -5.30100053217725,106.430464303253 -5.39457136678194,106.653165166619 -5.4874126437842,106.876189611739 -5.57900401325284,107.099647193937 -5.66882512525668,107.323647468538 -5.7563556298645,107.548299990866 -5.84107517714513,107.773714316245 -5.92246341716736,108.0 -6.0))') != 0: - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' + pytest.fail() f = lyr.GetNextFeature() if ogrtest.check_feature_geometry(f, 'POLYGON Z ((98.5006722379985 -24.8076524621295 0,96 -28 0,97.330144807446 -24.1691829545554 0,98.5006722379985 -24.8076524621295 0))') != 0: - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' + pytest.fail() f = lyr.GetNextFeature() if f.GetStyleString() != 'LABEL(f:"Arial",t:"Splines",p:7,a:342,s:2g,c:#000000)' \ or ogrtest.check_feature_geometry(f, 'POINT (110.7043505591 -4.20673403616296)') != 0: - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' + pytest.fail() # MULTILEADER with DIMBREAK f = lyr.GetNextFeature() if ogrtest.check_feature_geometry(f, 'MULTILINESTRING ((50.8917622404846 41.5635728657296,51.2877903403879 42.2579494192141),(51.9070696740577 43.3437639093041,54.3108962133801 47.5585173269448,55.9270734326513 48.2521008552884),(57.0757636753042 48.7450620367561,59.4256548786735 49.7535194092661),(60 50,60 50),(60 50,60 50),(60.625 50.0,61.875 50.0),(63.125 50.0,63.6 50.0))') != 0: - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' - - return 'success' + pytest.fail() + ############################################################################### # Test linetype scaling (#7129) and parsing of complex linetypes (#7134) -def ogr_dxf_45(): +def test_ogr_dxf_45(): ds = ogr.Open('data/linetypes.dxf') lyr = ds.GetLayer(0) feat = lyr.GetNextFeature() - if feat.GetField('Linetype') != 'DASHED2': - gdaltest.post_reason('Got wrong linetype (1)') - return 'fail' + assert feat.GetField('Linetype') == 'DASHED2', 'Got wrong linetype (1)' - if feat.GetStyleString() != 'PEN(c:#000000,p:"12.5g 6.25g")': - print(feat.GetStyleString()) - gdaltest.post_reason('Got wrong style string (1)') - return 'fail' + assert feat.GetStyleString() == 'PEN(c:#000000,p:"12.5g 6.25g")', \ + 'Got wrong style string (1)' feat = lyr.GetNextFeature() - if feat.GetField('Linetype') != 'DASHED2': - gdaltest.post_reason('Got wrong linetype (2)') - return 'fail' + assert feat.GetField('Linetype') == 'DASHED2', 'Got wrong linetype (2)' - if feat.GetStyleString() != 'PEN(c:#000000,p:"0.625g 0.3125g")': - print(feat.GetStyleString()) - gdaltest.post_reason('Got wrong style string (2)') - return 'fail' + assert feat.GetStyleString() == 'PEN(c:#000000,p:"0.625g 0.3125g")', \ + 'Got wrong style string (2)' feat = lyr.GetNextFeature() - if feat.GetField('Linetype') != 'DASHED2_FLIPPED': - gdaltest.post_reason('Got wrong linetype (3)') - return 'fail' + assert feat.GetField('Linetype') == 'DASHED2_FLIPPED', 'Got wrong linetype (3)' - if feat.GetStyleString() != 'PEN(c:#000000,p:"0.625g 0.3125g")': - print(feat.GetStyleString()) - gdaltest.post_reason('Got wrong style string (3)') - return 'fail' + assert feat.GetStyleString() == 'PEN(c:#000000,p:"0.625g 0.3125g")', \ + 'Got wrong style string (3)' feat = lyr.GetNextFeature() - if feat.GetField('Linetype') != 'Drain_Pipe_Inv_100': - gdaltest.post_reason('Got wrong linetype (4)') - return 'fail' - - if feat.GetStyleString() != 'PEN(c:#000000,p:"35g 22.5g")': - print(feat.GetStyleString()) - gdaltest.post_reason('Got wrong style string (4)') - return 'fail' + assert feat.GetField('Linetype') == 'Drain_Pipe_Inv_100', 'Got wrong linetype (4)' - return 'success' + assert feat.GetStyleString() == 'PEN(c:#000000,p:"35g 22.5g")', \ + 'Got wrong style string (4)' ############################################################################### # Test handling of DIMENSION anonymous block insertion (#7120) -def ogr_dxf_46(): +def test_ogr_dxf_46(): ds = ogr.Open('data/dimension.dxf') lyr = ds.GetLayer(0) @@ -3334,57 +2985,48 @@ def ogr_dxf_46(): # Extension lines f = lyr.GetNextFeature() if ogrtest.check_feature_geometry(f, 'LINESTRING Z (320000.0 5820010.0625 0,320000.0 5820010.43087258 0)') != 0: - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' + pytest.fail() f = lyr.GetNextFeature() if ogrtest.check_feature_geometry(f, 'LINESTRING Z (320010.0 5820010.0625 0,320010.0 5820010.43087258 0)') != 0: - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' + pytest.fail() # Dimension arrow lines f = lyr.GetNextFeature() if ogrtest.check_feature_geometry(f, 'LINESTRING Z (320000.18 5820010.25087258 0,320004.475225102 5820010.25087258 0)') != 0: - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' + pytest.fail() f = lyr.GetNextFeature() if ogrtest.check_feature_geometry(f, 'LINESTRING Z (320009.82 5820010.25087258 0,320005.524774898 5820010.25087258 0)') != 0: - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' + pytest.fail() # Arrowheads f = lyr.GetNextFeature() if ogrtest.check_feature_geometry(f, 'POLYGON ((320000.18 5820010.28087259,320000.18 5820010.22087258,320000.0 5820010.25087258,320000.18 5820010.28087259))') != 0: - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' + pytest.fail() f = lyr.GetNextFeature() if ogrtest.check_feature_geometry(f, 'POLYGON ((320009.82 5820010.28087259,320009.82 5820010.22087258,320010.0 5820010.25087258,320009.82 5820010.28087259))') != 0: - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' + pytest.fail() # Text f = lyr.GetNextFeature() if ogrtest.check_feature_geometry(f, 'POINT Z (320004.537844475 5820010.16240737 0)') != 0: - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' + pytest.fail() if f.GetStyleString() != 'LABEL(f:"Arial",t:"10.0000",p:1,s:0.18g,c:#000000)': - gdaltest.post_reason('Wrong style string on DIMENSION text from block') f.DumpReadable() - return 'fail' - - return 'success' + pytest.fail('Wrong style string on DIMENSION text from block') + ############################################################################### # Test handling of DIMENSION fallback when there is no anonymous block (#7120) -def ogr_dxf_47(): +def test_ogr_dxf_47(): ds = ogr.Open('data/dimension-entities-only.dxf') lyr = ds.GetLayer(0) @@ -3394,104 +3036,88 @@ def ogr_dxf_47(): # Dimension line and extension lines f = lyr.GetNextFeature() if ogrtest.check_feature_geometry(f, 'MULTILINESTRING ((320010.0 5820010.25087258,320000.0 5820010.25087258),(320010.0 5820010.0625,320010.0 5820010.43087258),(320000.0 5820010.0625,320000.0 5820010.43087258))') != 0: - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' + pytest.fail() # Arrowheads f = lyr.GetNextFeature() if ogrtest.check_feature_geometry(f, 'POLYGON Z ((320009.82 5820010.28087259 0,320010.0 5820010.25087258 0,320009.82 5820010.22087258 0,320009.82 5820010.28087259 0))') != 0: - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' + pytest.fail() f = lyr.GetNextFeature() if ogrtest.check_feature_geometry(f, 'POLYGON Z ((320000.18 5820010.22087258 0,320000.0 5820010.25087258 0,320000.18 5820010.28087259 0,320000.18 5820010.22087258 0))') != 0: - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' + pytest.fail() # Text f = lyr.GetNextFeature() if ogrtest.check_feature_geometry(f, 'POINT (320005.0 5820010.25087258)') != 0: - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' + pytest.fail() if f.GetStyleString() != 'LABEL(f:"Arial",t:"10.0000",p:11,s:0.18g,c:#000000)': - gdaltest.post_reason('Wrong style string on first DIMENSION text') f.DumpReadable() - return 'fail' + pytest.fail('Wrong style string on first DIMENSION text') # DIMENSION with style overrides # Dimension line f = lyr.GetNextFeature() if ogrtest.check_feature_geometry(f, 'MULTILINESTRING ((320005 5820005,320000 5820010))') != 0: - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' + pytest.fail() # Arrowheads f = lyr.GetNextFeature() if ogrtest.check_feature_geometry(f, 'POLYGON Z ((320004.116116524 5820006.23743687 0,320005 5820005 0,320003.762563133 5820005.88388348 0,320004.116116524 5820006.23743687 0))') != 0: - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' + pytest.fail() f = lyr.GetNextFeature() if ogrtest.check_feature_geometry(f, 'POLYGON Z ((320000.883883476 5820008.76256313 0,320000 5820010 0,320001.237436867 5820009.11611652 0,320000.883883476 5820008.76256313 0))') != 0: - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' + pytest.fail() # Text f = lyr.GetNextFeature() if ogrtest.check_feature_geometry(f, 'POINT (320002.5 5820007.5)') != 0: - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' + pytest.fail() if f.GetStyleString() != 'LABEL(f:"Arial",t:"7.1",p:11,a:-45,s:0.48g,c:#000000)': - gdaltest.post_reason('Wrong style string on second DIMENSION text') f.DumpReadable() - return 'fail' + pytest.fail('Wrong style string on second DIMENSION text') # DIMENSION inheriting styles from a custom DIMSTYLE # Dimension line f = lyr.GetNextFeature() if ogrtest.check_feature_geometry(f, 'MULTILINESTRING ((320000.0 5820001.5,320005.0 5820001.5),(320000.0 5820002.4,320000 5820001),(320005.0 5820002.4,320005 5820001))') != 0: - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' + pytest.fail() # Arrowheads f = lyr.GetNextFeature() if ogrtest.check_feature_geometry(f, 'POLYGON Z ((320000.18 5820001.47 0,320000.0 5820001.5 0,320000.18 5820001.53 0,320000.18 5820001.47 0))') != 0: - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' + pytest.fail() f = lyr.GetNextFeature() if ogrtest.check_feature_geometry(f, 'POLYGON Z ((320004.82 5820001.53 0,320005.0 5820001.5 0,320004.82 5820001.47 0,320004.82 5820001.53 0))') != 0: - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' + pytest.fail() # Text f = lyr.GetNextFeature() if ogrtest.check_feature_geometry(f, 'POINT (320001.5 5820001.5)') != 0: - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' + pytest.fail() if f.GetStyleString() != 'LABEL(f:"Arial",t:"±2 3\n\\P4 5.0000",p:11,s:0.18g,c:#000000)': - gdaltest.post_reason('Wrong style string on third DIMENSION text') f.DumpReadable() - return 'fail' - - return 'success' + pytest.fail('Wrong style string on third DIMENSION text') + ############################################################################### # Test ByLayer and ByBlock color values (#7130) -def ogr_dxf_48(): +def test_ogr_dxf_48(): gdal.SetConfigOption('DXF_MERGE_BLOCK_GEOMETRIES', 'FALSE') ds = ogr.Open('data/byblock-bylayer.dxf') @@ -3505,25 +3131,22 @@ def ogr_dxf_48(): # The dimension extension lines are ByBlock; the INSERT is magenta f = lyr.GetFeature(0) if f.GetStyleString() != 'PEN(c:#ff00ff,p:"1.5875g 1.5875g")': - gdaltest.post_reason('Wrong style string on feature 0') f.DumpReadable() - return 'fail' + pytest.fail('Wrong style string on feature 0') # The dimension line is set directly to blue f = lyr.GetFeature(2) if f.GetStyleString() != 'PEN(c:#0000ff)': - gdaltest.post_reason('Wrong style string on feature 2') f.DumpReadable() - return 'fail' + pytest.fail('Wrong style string on feature 2') # The first arrowhead is a custom block; the SOLID in this block is # colored ByLayer; the layer the block is inserted on (_K_POINTS) # is colored red f = lyr.GetFeature(4) if f.GetStyleString() != 'BRUSH(fc:#ff0000)': - gdaltest.post_reason('Wrong style string on feature 4') f.DumpReadable() - return 'fail' + pytest.fail('Wrong style string on feature 4') # The first arrowhead block also contains a line colored ByBlock. # The arrowhead INSERT is blue, so the line should be blue. @@ -3532,98 +3155,83 @@ def ogr_dxf_48(): # block, which is magenta. f = lyr.GetFeature(5) if f.GetStyleString() != 'PEN(c:#0000ff)': - gdaltest.post_reason('Wrong style string on feature 5') f.DumpReadable() - return 'fail' + pytest.fail('Wrong style string on feature 5') # The second arrowhead, like the dimension line, is set directly # to blue f = lyr.GetFeature(6) if f.GetStyleString() != 'BRUSH(fc:#0000ff)': - gdaltest.post_reason('Wrong style string on feature 6') f.DumpReadable() - return 'fail' + pytest.fail('Wrong style string on feature 6') # Like the dimension extension lines, the text is ByBlock (#7099) f = lyr.GetFeature(7) if f.GetStyleString() != 'LABEL(f:"Arial",t:"10.141 (2C)",s:0.4g,p:5,c:#ff00ff)': - gdaltest.post_reason('Wrong style string on feature 7') f.DumpReadable() - return 'fail' + pytest.fail('Wrong style string on feature 7') # ByLayer feature in block f = lyr.GetFeature(11) if f.GetStyleString() != 'PEN(c:#ff0000)': - gdaltest.post_reason('Wrong style string on feature 11') f.DumpReadable() - return 'fail' + pytest.fail('Wrong style string on feature 11') # ByBlock feature in block f = lyr.GetFeature(12) if f.GetStyleString() != 'PEN(c:#a552a5)': - gdaltest.post_reason('Wrong style string on feature 12') f.DumpReadable() - return 'fail' + pytest.fail('Wrong style string on feature 12') # ByLayer feature inserted via an INSERT on yellow layer in block # inserted via an INSERT on red layer: should be yellow f = lyr.GetFeature(13) if f.GetStyleString() != 'PEN(c:#ffff00)': - gdaltest.post_reason('Wrong style string on feature 13') f.DumpReadable() - return 'fail' + pytest.fail('Wrong style string on feature 13') # ByBlock feature inserted via a ByBlock INSERT in block inserted # via a color213 INSERT: should be color213 f = lyr.GetFeature(14) if f.GetStyleString() != 'PEN(c:#a552a5)': - gdaltest.post_reason('Wrong style string on feature 14') f.DumpReadable() - return 'fail' + pytest.fail('Wrong style string on feature 14') # ByBlock entities directly on the canvas show up as black f = lyr.GetFeature(15) if f.GetStyleString() != 'PEN(c:#000000)': - gdaltest.post_reason('Wrong style string on feature 15') f.DumpReadable() - return 'fail' - - return 'success' + pytest.fail('Wrong style string on feature 15') + ############################################################################### # Test block attributes (ATTRIB entities) (#7139) -def ogr_dxf_49(): +def test_ogr_dxf_49(): # Inline blocks mode ds = ogr.Open('data/attrib.dxf') lyr = ds.GetLayer(0) - if lyr.GetFeatureCount() != 6: - gdaltest.post_reason('Wrong feature count, got %d' % lyr.GetFeatureCount()) - return 'fail' + assert lyr.GetFeatureCount() == 6, \ + ('Wrong feature count, got %d' % lyr.GetFeatureCount()) f = lyr.GetFeature(1) if f.GetField('Text') != 'super test': - gdaltest.post_reason('Wrong Text value on first ATTRIB on first INSERT') f.DumpReadable() - return 'fail' + pytest.fail('Wrong Text value on first ATTRIB on first INSERT') if f.GetStyleString() != 'LABEL(f:"Arial",t:"super test",p:2,s:8g,w:234.6,dx:30.293g,c:#ff0000)': - gdaltest.post_reason('Wrong style string on first ATTRIB on first INSERT') f.DumpReadable() - return 'fail' + pytest.fail('Wrong style string on first ATTRIB on first INSERT') f = lyr.GetFeature(4) geom = f.GetGeometryRef() - if geom.GetGeometryType() != ogr.wkbLineString25D: - gdaltest.post_reason('Expected LINESTRING Z') - return 'fail' + assert geom.GetGeometryType() == ogr.wkbLineString25D, 'Expected LINESTRING Z' f = lyr.GetFeature(5) if f.GetField('Text') != '': - gdaltest.post_reason('Wrong Text value on ATTRIB on second INSERT') f.DumpReadable() - return 'fail' + pytest.fail('Wrong Text value on ATTRIB on second INSERT') # No inlining gdal.SetConfigOption('DXF_INLINE_BLOCKS', 'FALSE') @@ -3634,37 +3242,32 @@ def ogr_dxf_49(): f = lyr.GetFeature(0) if f.GetField('BlockAttributes') != ['MYATT1 super test', 'MYATTMULTI_001 Corps', 'MYATTMULTI_002 plpl']: - gdaltest.post_reason('Wrong BlockAttributes value on first INSERT') f.DumpReadable() - return 'fail' + pytest.fail('Wrong BlockAttributes value on first INSERT') f = lyr.GetFeature(1) if f.GetField('BlockAttributes') != ['MYATTMULTI ']: - gdaltest.post_reason('Wrong BlockAttributes value on second INSERT') f.DumpReadable() - return 'fail' + pytest.fail('Wrong BlockAttributes value on second INSERT') lyr = ds.GetLayerByName('blocks') f = lyr.GetFeature(1) if f.GetField('AttributeTag') != 'MYATT1': - gdaltest.post_reason('Wrong AttributeTag value on first ATTDEF') f.DumpReadable() - return 'fail' + pytest.fail('Wrong AttributeTag value on first ATTDEF') f = lyr.GetFeature(2) if f.GetField('AttributeTag') != 'MYATTMULTI': - gdaltest.post_reason('Wrong AttributeTag value on second ATTDEF') f.DumpReadable() - return 'fail' - - return 'success' + pytest.fail('Wrong AttributeTag value on second ATTDEF') + ############################################################################### # Test extended text styling (#7151) and additional ByBlock/ByLayer tests (#7130) -def ogr_dxf_50(): +def test_ogr_dxf_50(): gdal.SetConfigOption('DXF_MERGE_BLOCK_GEOMETRIES', 'FALSE') ds = ogr.Open('data/text-fancy.dxf') @@ -3676,54 +3279,47 @@ def ogr_dxf_50(): # inside block inserted on a blue layer f = lyr.GetFeature(0) if f.GetStyleString() != 'LABEL(f:"Times New Roman",bo:1,it:1,t:"Some nice text",p:5,s:10g,w:190,dx:84.3151g,dy:4.88825g,c:#0000ff)': - gdaltest.post_reason('Wrong style string on feature 0') f.DumpReadable() - return 'fail' + pytest.fail('Wrong style string on feature 0') # Polyline, color and linetype ByBlock inside block with red color # and ByLayer linetype inserted on a layer with DASHED2 linetype f = lyr.GetFeature(1) if f.GetStyleString() != 'PEN(c:#ff0000,w:2.1g,p:"2.5g 1.25g")': - gdaltest.post_reason('Wrong style string on feature 1') f.DumpReadable() - return 'fail' + pytest.fail('Wrong style string on feature 1') # Make sure TEXT objects don't inherit anything other than font name, # bold and italic from their parent STYLE f = lyr.GetFeature(2) if f.GetStyleString() != 'LABEL(f:"Times New Roman",bo:1,it:1,t:"Good text",p:1,s:5g,c:#000000)': - gdaltest.post_reason('Wrong style string on feature 2') f.DumpReadable() - return 'fail' + pytest.fail('Wrong style string on feature 2') # Polyline, color ByBlock, inside block inserted on a blue layer f = lyr.GetFeature(3) if f.GetStyleString() != 'PEN(c:#0000ff,w:2.1g)': - gdaltest.post_reason('Wrong style string on feature 3') f.DumpReadable() - return 'fail' + pytest.fail('Wrong style string on feature 3') # MTEXT stretched 250%, color ByLayer inside block inserted on a blue layer f = lyr.GetFeature(4) if f.GetStyleString() != 'LABEL(f:"Times New Roman",bo:1,it:1,t:"Some nice MTEXT",s:10g,w:250,p:8,c:#0000ff)': - gdaltest.post_reason('Wrong style string on feature 4') f.DumpReadable() - return 'fail' + pytest.fail('Wrong style string on feature 4') # Individually invisible object should be invisible f = lyr.GetFeature(5) if f.GetStyleString() != 'LABEL(f:"Times New Roman",bo:1,it:1,t:"Invisible text",p:1,s:5g,c:#00000000)': - gdaltest.post_reason('Wrong style string on feature 5') f.DumpReadable() - return 'fail' - - return 'success' + pytest.fail('Wrong style string on feature 5') + ############################################################################### # Test transformation of text inside blocks (ACAdjustText function) -def ogr_dxf_51(): +def test_ogr_dxf_51(): ds = ogr.Open('data/text-block-transform.dxf') @@ -3736,22 +3332,19 @@ def ogr_dxf_51(): f = lyr.GetNextFeature() if ogrtest.check_feature_geometry(f, 'POINT Z (2.83231568033604 5.98356393304499 0)') != 0: - gdaltest.post_reason('Wrong geometry on feature %d' % x) f.DumpReadable() - return 'fail' + pytest.fail('Wrong geometry on feature %d' % x) if sorted(f.GetStyleString()[6:-1].split(',')) != wanted_style: - gdaltest.post_reason('Wrong style string on feature %d' % x) f.DumpReadable() - return 'fail' - - return 'success' + pytest.fail('Wrong style string on feature %d' % x) + ############################################################################### # Test HELIX, TRACE, HATCH with spline boundary, MLINE, and INSERT with rows/columns -def ogr_dxf_52(): +def test_ogr_dxf_52(): ds = ogr.Open('data/additional-entities.dxf') lyr = ds.GetLayer(0) @@ -3759,143 +3352,124 @@ def ogr_dxf_52(): # HELIX f = lyr.GetNextFeature() if f.GetField('SubClasses') != 'AcDbEntity:AcDbSpline:AcDbHelix': - gdaltest.post_reason('Wrong SubClasses on HELIX') f.DumpReadable() - return 'fail' + pytest.fail('Wrong SubClasses on HELIX') if ogrtest.check_feature_geometry(f, 'LINESTRING (150 120,149.345876458438 119.778561209114,148.706627788813 119.535836602547,148.082773142501 119.272634882071,147.474831670876 118.989764749454,146.883322525316 118.688034906466,146.308764857195 118.368254054878,145.75167781789 118.03123089646,145.212580558776 117.677774132981,144.691992231228 117.308692466212,144.190431986623 116.924794597921,143.708418976337 116.52688922988,143.246472351745 116.115785063858,142.805226682224 115.692350328976,142.385468357145 115.257680939095,141.987209053809 114.8126724387,141.610382578047 114.358190780749,141.254922735687 113.895101918197,140.920763332559 113.424271804003,140.607838174492 112.946566391121,140.316081067316 112.46285163251,140.04542581686 111.973993481125,139.795806228954 111.480857889924,139.567156109426 110.984310811863,139.359409264107 110.4852181999,139.172499498825 109.98444600699,139.00636061941 109.482860186091,138.860926431692 108.981326690159,138.7361307415 108.480711472151,138.631907354662 107.981880485024,138.54819007701 107.485699681734,138.484912714371 106.993035015239,138.442009072576 106.504752438495,138.419412957453 106.021717904458,138.41678542913 105.544991394258,138.433333223564 105.075482938615,138.468434844937 104.613670677827,138.521471087835 104.160029888371,138.59182274684 103.715035846723,138.678870616536 103.27916382936,138.781995491508 102.852889112758,138.900578166339 102.436686973394,139.033999435614 102.031032687745,139.181640093916 101.636401532287,139.342880935829 101.253268783496,139.517102755937 100.882109717849,139.703686348824 100.523399611823,139.902012509075 100.177613741895,140.111462031272 99.8452273845396,140.33141571 99.5267158162348,140.561254339843 99.2225543134567,140.800358715385 98.933218152682,141.04810963121 98.6591826103871,141.303887881901 98.4009229630486,141.567055122443 98.1589144355755,141.836465751876 97.9334729764931,142.111203876514 97.7245055448538,142.390570491032 97.5318567084626,142.673866590107 97.3553710351246,142.960393168413 97.194893092645,143.249451220625 97.0502674488286,143.54034174142 96.9213386714808,143.832365725473 96.8079513284064,144.124824167458 96.7099499874106,144.417018062052 96.6271792162984,144.708248403929 96.5594835828749,144.997816187765 96.5067076549452,145.285022408236 96.4686960003143,145.569168060017 96.4452931867873,145.849554137782 96.4363437821692,146.125481636209 96.4416923542652,146.396251549971 96.4611834708803,146.661164873745 96.4946616998195,146.919522602205 96.5419716088879,147.170625730027 96.6029577658907,147.413708536343 96.6773765373194,147.64790100184 96.7644518356677,147.872845806317 96.8635266377703,148.088244263586 96.9739879715066,148.293797687463 97.0952228647559,148.48920739176 97.2266183453974,148.674174690292 97.3675614413103,148.848400896871 97.5174391803741,149.011587325312 97.675638590468,149.163435289429 97.8415466994713,149.303646103034 98.0145505352631,149.431921079943 98.194037125723,149.547961533967 98.37939349873,149.651468778922 98.5700066821635,149.742144128621 98.7652637039028,149.819688896877 98.9645515918272,149.883804397505 99.1672573738159,149.934191944317 99.3727680777483,149.970552851128 99.5804707315036,149.992588431751 99.7897523629611,150 100)') != 0: - gdaltest.post_reason('Wrong geometry on HELIX') f.DumpReadable() - return 'fail' + pytest.fail('Wrong geometry on HELIX') # TRACE f = lyr.GetNextFeature() if ogrtest.check_feature_geometry(f, 'POLYGON ((150.0 120.5,150.0 119.5,200.0 119.5,200.0 120.5,150.0 120.5))') != 0: - gdaltest.post_reason('Wrong geometry on TRACE') f.DumpReadable() - return 'fail' + pytest.fail('Wrong geometry on TRACE') # HATCH with a spline boundary path (and OCS as well, just for fun) f = lyr.GetNextFeature() if ogrtest.check_feature_geometry(f, 'POLYGON Z ((47.6969600708475 60.0 15,47.6969600708475 0.0 15,46.1103652823066 -0.466958240734954 14.5010390223444,44.5309994192688 -0.919910449553494 14.0043514365868,42.9660914072371 -1.34485059453921 13.5122106346236,41.4228701717145 -1.72777264377568 13.0268900083519,39.9085646382042 -2.0546705653465 12.5506629496691,38.4304037322091 -2.31153832733525 12.0858028504722,36.9956163792324 -2.48436989782552 11.6345831026584,35.6114315047771 -2.55915924490089 11.1992770981251,34.2850780343463 -2.52190033664495 10.7821582287693,33.0237848934429 -2.3585871411413 10.3854998864882,31.8347810075701 -2.0552136264735 10.011575463179,30.725295302231 -1.59777376072516 9.66265835073903,29.7025567029285 -0.972261511979859 9.34102194106535,28.7737941351658 -0.164670848321179 9.04893962605519,27.9445456607789 0.835923776643351 8.78815304558283,27.2086691364137 2.01916842728349 8.55673058492536,26.5550905172208 3.36572402537053 8.35118961809371,25.9727183005027 4.85621968724478 8.1680420288596,25.450460983562 6.47128452924656 8.00379970099481,24.9772270637013 8.19154766771616 7.85497451827107,24.5419250382231 9.99763821899391 7.71807836446012,24.1334634044299 11.8701852994201 7.58962312333373,23.7407506596245 13.7898180253351 7.46612067866363,23.3526953011092 15.7371655130791 7.34408291422158,22.9582058261868 17.6928568789925 7.22002171377933,22.5461907321598 19.6375212394157 7.09044896110861,22.1055585163308 21.5517877106888 6.95187653998118,21.6252176760022 23.4162854091522 6.80081633416879,21.0940767084768 25.2116434511463 6.63378022744318,20.501044111057 26.9184909530113 6.44728010357611,19.8350283810455 28.5174570310876 6.23782784633932,19.0849380157448 29.9891708017154 6.00193533950455,18.2425220975445 31.3190096857923 5.73700778952582,17.3111586046656 32.5117898949509 5.44410752140743,16.2972009340528 33.5773013324584 5.12523258605305,15.2070024839932 34.5253339038266 4.7823810347885,14.046916652774 35.3656775145671 4.41755091893963,12.8232968386826 36.1081220701913 4.0327402898323,11.5424964400062 36.7624574762111 3.62994719879235,10.2108688550319 37.338473638138 3.21116969714562,8.834767482047 37.8459604614835 2.77840583621797,7.42054571933875 38.2947078517594 2.33365366733523,5.97455696519436 38.6945057144772 1.87891124182326,4.50315461790106 39.0551439551486 1.41617661100791,3.01269207574607 39.3864124792851 0.947447826215011,1.50952273701662 39.6981011923983 0.474722938770421,0 40 0,-0.0 40.0 -2.12999999999989e-15,47.6969600708475 60.0 15))') != 0: - gdaltest.post_reason('Wrong geometry on HATCH 1') f.DumpReadable() - return 'fail' + pytest.fail('Wrong geometry on HATCH 1') # Another HATCH with a spline boundary path f = lyr.GetNextFeature() if ogrtest.check_feature_geometry(f, 'POLYGON ((77.2409948093467 172.430072843974,75.261065049518 171.643815908613,73.2981627172517 170.696359298076,71.3875263981659 169.604375316261,69.5631545040892 168.388782317518,67.8563613292361 167.073645833116,66.2946346031063 165.684923719356,64.9008927779373 164.249191641798,63.6931834376534 162.792474868402,62.6848095284188 161.339284018754,61.8848281190297 159.911914493846,61.298843085132 158.530030785262,60.9300095654357 157.21052494952,60.7801817312349 155.967617443343,60.8511622391671 154.813159397702,61.1453506194465 153.756315627339,61.664528568996 152.803726831033,62.4105189258065 151.964301284269,63.3843801494824 151.249807149788,64.5850174245011 150.674379748575,66.0076885629501 150.253830592488,67.6424701411086 150.004704104407,69.4728079995063 149.943055679116,71.4743351228068 150.082969908572,73.6141841756299 150.434899728198,75.8510314766708 151.003978292885,78.1360638882735 151.788519596984,80.41494916904 152.778958906121,82.6307223520159 153.957467932202,84.7273090430607 155.298400731333,86.6532441052495 156.769592674546,88.3650659486779 158.334376895018,89.8299059955281 159.954044613131,91.0272387483612 161.589690168686,91.957368361883 163.189390065386,92.6421956980388 164.701128484532,93.1110835351921 166.094608264522,93.3942229550992 167.356341648662,93.5189493216415 168.483994478151,93.5079031853763 169.481912548033,93.3782987206629 170.357905428604,93.1417233193846 171.121075154443,92.8040593119231 171.78040251468,92.3652285565357 172.343822183981,91.8186752047856 172.817679470437,91.1571081487304 173.20986823606,90.3766844995721 173.528608818345,89.4716123962251 173.777329886712,88.4346297478537 173.955199520934,87.2580461173156 174.057607166253,85.9350751682361 174.076420167619,84.4616595153474 174.000186427787,82.8389797200317 173.814465060529,81.0767853391384 173.502507153586,79.1975328516125 173.04655812613,77.2409948093467 172.430072843974))') != 0: - gdaltest.post_reason('Wrong geometry on HATCH 2') f.DumpReadable() - return 'fail' + pytest.fail('Wrong geometry on HATCH 2') # Three MLINE objects f = lyr.GetNextFeature() if ogrtest.check_feature_geometry(f, 'MULTILINESTRING Z ((-3.92232270276368 270.388386486182 0,44.2014737139232 260.763627202844 0),(0 290 0,50 280 0),(50 280 0,54.2440667916678 280.848813358334 0),(66.6666666666666 283.333333333333 0,87.2937093466817 287.458741869336 0),(55.335512192016 260.671024384032 0,83.0445264186877 266.212827229366 0),(97.9166666666667 289.583333333333 0,150 300 0),(93.6674837386727 268.337418693363 0,122.93205511402 274.190332968433 0),(150 300 0,140 260 0),(122.93205511402 274.190332968433 0,120.597149997093 264.850712500727 0))') != 0: - gdaltest.post_reason('Wrong geometry on MLINE 1') f.DumpReadable() - return 'fail' + pytest.fail('Wrong geometry on MLINE 1') f = lyr.GetNextFeature() if ogrtest.check_feature_geometry(f, 'MULTILINESTRING Z ((70 290 0,50 250 0),(61.0557280900008 294.472135955 0,41.0557280900008 254.472135955 0))') != 0: - gdaltest.post_reason('Wrong geometry on MLINE 2') f.DumpReadable() - return 'fail' + pytest.fail('Wrong geometry on MLINE 2') f = lyr.GetNextFeature() if ogrtest.check_feature_geometry(f, 'MULTILINESTRING Z ((100 300 0,97.9166666666667 289.583333333333 0),(95.7739043877141 304.364619506534 0,92.6051880066742 288.521037601335 0),(91.5478087754281 308.729239013068 0,87.2937093466817 287.458741869336 0),(93.6674837386727 268.337418693363 0,90 250 0),(88.3560050786802 267.275122961365 0,83.7111464107331 244.050829621629 0),(83.0445264186877 266.212827229366 0,77.4222928214662 238.101659243259 0),(90 250 0,160 260 0),(83.7111464107331 244.050829621629 0,165.0 255.663522991525 0),(77.4222928214662 238.101659243259 0,170.0 251.327045983049 0),(160 260 0,160 310 0),(165.0 255.663522991525 0,165.0 315.902302108582 0),(170.0 251.327045983049 0,170.0 321.804604217164 0),(160 310 0,100 300 0),(165.0 315.902302108582 0,95.7739043877141 304.364619506534 0),(170.0 321.804604217164 0,91.5478087754281 308.729239013068 0))') != 0: - gdaltest.post_reason('Wrong geometry on MLINE 3') f.DumpReadable() - return 'fail' + pytest.fail('Wrong geometry on MLINE 3') # INSERT with rows/columns (MInsert) minsert_attrib_style = 'LABEL(f:"Arial",t:"N",p:5,a:13,s:8g,w:120,dx:2.21818g,dy:4.61732g,c:#000000)' f = lyr.GetNextFeature() if ogrtest.check_feature_geometry(f, 'LINESTRING (57.7504894565613 50.7437006478524,69.4429302339842 53.4431132999787,71.6924407774228 43.6994126521264,60 41,57.7504894565613 50.7437006478524)') != 0: - gdaltest.post_reason('Wrong geometry on INSERT polyline 1') f.DumpReadable() - return 'fail' + pytest.fail('Wrong geometry on INSERT polyline 1') f = lyr.GetNextFeature() if ogrtest.check_feature_geometry(f, 'POINT Z (62.5032851270548 42.604233016948 0)') != 0 \ or f.GetStyleString() != minsert_attrib_style: - gdaltest.post_reason('Wrong geometry on INSERT attribute 1') f.DumpReadable() - return 'fail' + pytest.fail('Wrong geometry on INSERT attribute 1') for _ in range(2): f = lyr.GetNextFeature() f = lyr.GetNextFeature() if ogrtest.check_feature_geometry(f, 'LINESTRING (116.212693343675 64.2407639084843,127.905134121098 66.9401765606106,130.154644664537 57.1964759127583,118.462203887114 54.4970632606319,116.212693343675 64.2407639084843)') != 0: - gdaltest.post_reason('Wrong geometry on INSERT polyline 3') f.DumpReadable() - return 'fail' + pytest.fail('Wrong geometry on INSERT polyline 3') f = lyr.GetNextFeature() if ogrtest.check_feature_geometry(f, 'POINT Z (120.965489014169 56.1012962775799 0)') != 0 \ or f.GetStyleString() != minsert_attrib_style: - gdaltest.post_reason('Wrong geometry on INSERT attribute 3') f.DumpReadable() - return 'fail' + pytest.fail('Wrong geometry on INSERT attribute 3') for _ in range(8): f = lyr.GetNextFeature() f = lyr.GetNextFeature() if ogrtest.check_feature_geometry(f, 'LINESTRING (140.944774200355 90.4766968345049,152.637214977778 93.1761094866313,154.886725521217 83.4324088387789,143.194284743794 80.7329961866526,140.944774200355 90.4766968345049)') != 0: - gdaltest.post_reason('Wrong geometry on INSERT polyline 8') f.DumpReadable() - return 'fail' + pytest.fail('Wrong geometry on INSERT polyline 8') f = lyr.GetNextFeature() if ogrtest.check_feature_geometry(f, 'POINT Z (145.697569870849 82.3372292036006 0)') != 0 \ or f.GetStyleString() != minsert_attrib_style: - gdaltest.post_reason('Wrong geometry on INSERT attribute 8') f.DumpReadable() - return 'fail' + pytest.fail('Wrong geometry on INSERT attribute 8') # Also throw in a test of a weird SPLINE generated by a certain CAD package # with a knot vector that does not start at zero f = lyr.GetNextFeature() if ogrtest.check_feature_geometry(f, 'LINESTRING (0 20,0.513272464826192 19.8251653183892,1.00815682586353 19.629626397244,1.48499546839613 19.4132825350102,1.94413077770813 19.1760330301337,2.38590513908363 18.9177771810603,2.81066093780676 18.6384142862359,3.21874055916165 18.3378436441062,3.61048638843241 18.0159645531172,3.98624081090316 17.6726763117148,4.34634621185803 17.3078782183446,4.69114497658114 16.9214695714527,5.02097949035661 16.5133496694848,5.33619213846856 16.0834178108867,5.63712530620111 15.6315732941045,5.92412137883838 15.1577154175837,6.1975227416645 14.6617434797705,6.45767177996359 14.1435567791104,6.70491087901976 13.6030546140496,6.93958242411715 13.0401362830336,7.16202880053986 12.4547010845085,7.37259239357203 11.8466483169201,7.57161558849776 11.2158772787141,7.7594407706012 10.5622872683365,7.93641032516645 9.88577758423314,8.10286663747763 9.18624752484979,8.25915209281888 8.46359638863234,8.4056090764743 7.71772347402662,8.54257997372803 6.94852807947849,8.67040716986418 6.1559095034338,8.78943305016688 5.33976704433838,8.9 4.5)') != 0: - gdaltest.post_reason('Wrong geometry on SPLINE') f.DumpReadable() - return 'fail' - - return 'success' + pytest.fail('Wrong geometry on SPLINE') + ############################################################################### # Test block base points -def ogr_dxf_53(): +def test_ogr_dxf_53(): ds = ogr.Open('data/block-basepoint.dxf') lyr = ds.GetLayer(0) f = lyr.GetNextFeature() if ogrtest.check_feature_geometry(f, 'MULTILINESTRING Z ((290 160 0,310 140 0),(310 160 0,290 140 0))') != 0: - gdaltest.post_reason('Wrong feature geometry') f.DumpReadable() - return 'fail' - - return 'success' + pytest.fail('Wrong feature geometry') + ############################################################################### -def ogr_dxf_insert_too_many_errors(): +def test_ogr_dxf_insert_too_many_errors(): with gdaltest.error_handler(): ogr.Open('data/insert-too-many-errors.dxf') - return 'success' - + ############################################################################### -def ogr_dxf_write_geometry_collection_of_unsupported_type(): +def test_ogr_dxf_write_geometry_collection_of_unsupported_type(): tmpfile = '/vsimem/ogr_dxf_write_geometry_collection_of_unsupported_type.dxf' @@ -3905,89 +3479,20 @@ def ogr_dxf_write_geometry_collection_of_unsupported_type(): f.SetGeometryDirectly(ogr.CreateGeometryFromWkt('GEOMETRYCOLLECTION(TIN EMPTY)')) with gdaltest.error_handler(): ret = lyr.CreateFeature(f) - if ret == 0: - return 'fail' + assert ret != 0 ds = None gdal.Unlink(tmpfile) - return 'success' - ############################################################################### # cleanup -def ogr_dxf_cleanup(): +def test_ogr_dxf_cleanup(): gdaltest.dxf_layer = None gdaltest.dxf_ds = None - return 'success' - ############################################################################### # -gdaltest_list = [ - ogr_dxf_1, - ogr_dxf_2, - ogr_dxf_3, - ogr_dxf_4, - ogr_dxf_5, - ogr_dxf_6, - ogr_dxf_7, - ogr_dxf_8, - ogr_dxf_9, - ogr_dxf_10, - ogr_dxf_11, - ogr_dxf_12, - ogr_dxf_13, - ogr_dxf_14, - ogr_dxf_15, - ogr_dxf_16, - ogr_dxf_17, - ogr_dxf_18, - ogr_dxf_19, - ogr_dxf_20, - ogr_dxf_21, - ogr_dxf_22, - ogr_dxf_23, - ogr_dxf_24, - ogr_dxf_25, - ogr_dxf_26, - ogr_dxf_27, - ogr_dxf_28, - ogr_dxf_29, - ogr_dxf_30, - ogr_dxf_31, - ogr_dxf_32, - ogr_dxf_33, - ogr_dxf_34, - ogr_dxf_35, - ogr_dxf_36, - ogr_dxf_37, - ogr_dxf_38, - ogr_dxf_39, - ogr_dxf_40, - ogr_dxf_41, - ogr_dxf_42, - ogr_dxf_43, - ogr_dxf_44, - ogr_dxf_45, - ogr_dxf_46, - ogr_dxf_47, - ogr_dxf_48, - ogr_dxf_49, - ogr_dxf_50, - ogr_dxf_51, - ogr_dxf_52, - ogr_dxf_53, - ogr_dxf_insert_too_many_errors, - ogr_dxf_write_geometry_collection_of_unsupported_type, - ogr_dxf_cleanup] - -if __name__ == '__main__': - - gdaltest.setup_run('ogr_dxf') - - gdaltest.run_tests(gdaltest_list) - - sys.exit(gdaltest.summarize()) + diff --git a/autotest/ogr/ogr_edigeo.py b/autotest/ogr/ogr_edigeo.py index 0dd39a6f2a04..a37fdf02e456 100755 --- a/autotest/ogr/ogr_edigeo.py +++ b/autotest/ogr/ogr_edigeo.py @@ -30,18 +30,17 @@ ############################################################################### import os -import sys from osgeo import ogr -sys.path.append('../pymod') import gdaltest import ogrtest +import pytest ############################################################################### -def ogr_edigeo_1(): +def test_ogr_edigeo_1(): filelist = ['E000AB01.THF', 'EDAB01S1.VEC', @@ -58,18 +57,16 @@ def ogr_edigeo_1(): for filename in filelist: if not gdaltest.download_file(base_url + filename, filename): - return 'skip' + pytest.skip() try: for filename in filelist: os.stat('tmp/cache/' + filename) except OSError: - return 'skip' + pytest.skip() ds = ogr.Open('tmp/cache/E000AB01.THF') - if ds.GetLayerCount() != 24: - print(ds.GetLayerCount()) - return 'fail' + assert ds.GetLayerCount() == 24 layers = [('BATIMENT_id', ogr.wkbPolygon, 107), ('BORNE_id', ogr.wkbPoint, 5), @@ -92,46 +89,30 @@ def ogr_edigeo_1(): for l in layers: lyr = ds.GetLayerByName(l[0]) - if lyr.GetLayerDefn().GetGeomType() != l[1]: - return 'fail' - if lyr.GetFeatureCount() != l[2]: - print(lyr.GetFeatureCount()) - return 'fail' + assert lyr.GetLayerDefn().GetGeomType() == l[1] + assert lyr.GetFeatureCount() == l[2] if l[1] != ogr.wkbNone: - if lyr.GetSpatialRef().ExportToWkt().find('Lambert_Conformal_Conic_1SP') == -1: - print(lyr.GetSpatialRef().ExportToWkt()) - return 'fail' + assert lyr.GetSpatialRef().ExportToWkt().find('Lambert_Conformal_Conic_1SP') != -1 lyr = ds.GetLayerByName('BORNE_id') feat = lyr.GetNextFeature() if ogrtest.check_feature_geometry(feat, 'POINT (877171.28 72489.22)'): feat.DumpReadable() - return 'fail' + pytest.fail() lyr = ds.GetLayerByName('BATIMENT_id') feat = lyr.GetNextFeature() if ogrtest.check_feature_geometry(feat, 'POLYGON ((877206.16 71888.82,877193.14 71865.51,877202.95 71860.07,877215.83 71883.5,877206.16 71888.82))'): feat.DumpReadable() - return 'fail' + pytest.fail() lyr = ds.GetLayerByName('ZONCOMMUNI_id') feat = lyr.GetNextFeature() if ogrtest.check_feature_geometry(feat, 'LINESTRING (877929.8 71656.39,877922.38 71663.72,877911.48 71669.51,877884.23 71675.64,877783.07 71694.04,877716.31 71706.98,877707.45 71709.71,877702.0 71713.79,877696.89 71719.58,877671.69 71761.82,877607.99 71865.03,877545.32 71959.04,877499.22 72026.82)'): feat.DumpReadable() - return 'fail' + pytest.fail() ds.Destroy() - return 'success' -gdaltest_list = [ - ogr_edigeo_1] - -if __name__ == '__main__': - - gdaltest.setup_run('ogr_edigeo') - - gdaltest.run_tests(gdaltest_list) - - sys.exit(gdaltest.summarize()) diff --git a/autotest/ogr/ogr_eeda.py b/autotest/ogr/ogr_eeda.py index 0e7cc177c1a1..c7b75c6f12f9 100644 --- a/autotest/ogr/ogr_eeda.py +++ b/autotest/ogr/ogr_eeda.py @@ -30,38 +30,34 @@ ############################################################################### import json -import sys -sys.path.append('../pymod') from osgeo import gdal, ogr -import gdaltest import ogrtest +import pytest ############################################################################### # Find EEDA driver -def eeda_1(): +def test_eeda_1(): ogrtest.eeda_drv = ogr.GetDriverByName('EEDA') if ogrtest.eeda_drv is None: - return 'skip' + pytest.skip() gdal.SetConfigOption('CPL_CURL_ENABLE_VSIMEM', 'YES') - return 'success' - ############################################################################### # Nominal case -def eeda_2(): +def test_eeda_2(): if ogrtest.eeda_drv is None: - return 'skip' + pytest.skip() gdal.FileFromMemBuffer('/vsimem/ee/projects/earthengine-public/assets/collection:listImages?pageSize=1', json.dumps({ 'assets': [ @@ -87,28 +83,15 @@ def eeda_2(): lyr = ds.GetLayer(0) - if lyr.TestCapability(ogr.OLCStringsAsUTF8) != 1: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.TestCapability(ogr.OLCStringsAsUTF8) == 1 - if lyr.TestCapability('foo') != 0: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.TestCapability('foo') == 0 - if lyr.GetLayerDefn().GetFieldCount() != 8 + 7 + 4: - gdaltest.post_reason('fail') - print(lyr.GetLayerDefn().GetFieldCount()) - return 'fail' + assert lyr.GetLayerDefn().GetFieldCount() == 8 + 7 + 4 - if lyr.GetExtent() != (-180.0, 180.0, -90.0, 90.0): - gdaltest.post_reason('fail') - print(lyr.GetExtent()) - return 'fail' + assert lyr.GetExtent() == (-180.0, 180.0, -90.0, 90.0) - if lyr.GetFeatureCount() != -1: - gdaltest.post_reason('fail') - print(lyr.GetFeatureCount()) - return 'fail' + assert lyr.GetFeatureCount() == -1 gdal.FileFromMemBuffer('/vsimem/ee/projects/earthengine-public/assets/collection:listImages', json.dumps({ 'assets': [ @@ -181,15 +164,13 @@ def eeda_2(): f.GetField('double_field') != 1.23 or \ f.GetField('other_properties') != '{ "another_prop": 3 }' or \ f.GetGeometryRef().ExportToWkt() != 'MULTIPOLYGON (((2 49,2.1 49.0,2.1 49.1,2.0 49.1,2 49)))': - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' + pytest.fail() f = lyr.GetNextFeature() if f.GetField('name') != 'projects/earthengine-public/assets/collection/second_feature': - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' + pytest.fail() gdal.FileFromMemBuffer('/vsimem/ee/projects/earthengine-public/assets/collection:listImages?pageToken=myToken', json.dumps({ 'assets': [ @@ -201,22 +182,18 @@ def eeda_2(): f = lyr.GetNextFeature() if f.GetField('name') != 'projects/earthengine-public/assets/collection/third_feature': - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' + pytest.fail() f = lyr.GetNextFeature() - if f is not None: - gdaltest.post_reason('fail') - return 'fail' + assert f is None lyr.ResetReading() f = lyr.GetNextFeature() if f.GetField('name') != 'projects/earthengine-public/assets/collection/first_feature': - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' + pytest.fail() lyr.SetAttributeFilter('EEDA:raw_filter') @@ -229,9 +206,7 @@ def eeda_2(): })) f = lyr.GetNextFeature() - if f.GetField('name') != 'projects/earthengine-public/assets/collection/raw_filter': - gdaltest.post_reason('fail') - return 'fail' + assert f.GetField('name') == 'projects/earthengine-public/assets/collection/raw_filter' lyr.SetAttributeFilter(None) lyr.SetAttributeFilter("time >= '1980-01-01T00:00:00Z' AND " + @@ -274,9 +249,7 @@ def eeda_2(): f = lyr.GetNextFeature() gdal.Unlink(ogrtest.eeda_drv_tmpfile) - if f.GetField('name') != 'projects/earthengine-public/assets/collection/filtered_feature': - gdaltest.post_reason('fail') - return 'fail' + assert f.GetField('name') == 'projects/earthengine-public/assets/collection/filtered_feature' lyr.SetSpatialFilter(None) @@ -299,9 +272,7 @@ def eeda_2(): f = lyr.GetNextFeature() gdal.Unlink(ogrtest.eeda_drv_tmpfile) - if f.GetField('name') != 'projects/earthengine-public/assets/collection/filtered_feature': - gdaltest.post_reason('fail') - return 'fail' + assert f.GetField('name') == 'projects/earthengine-public/assets/collection/filtered_feature' # Test time equality with day granularity lyr.SetAttributeFilter("time = '1980-01-01'") @@ -322,24 +293,20 @@ def eeda_2(): f = lyr.GetNextFeature() gdal.Unlink(ogrtest.eeda_drv_tmpfile) - if f.GetField('name') != 'projects/earthengine-public/assets/collection/filtered_feature': - gdaltest.post_reason('fail') - return 'fail' + assert f.GetField('name') == 'projects/earthengine-public/assets/collection/filtered_feature' ds = None gdal.SetConfigOption('EEDA_BEARER', None) - return 'success' - ############################################################################### # Nominal case where collection is in eedaconf.json -def eeda_3(): +def test_eeda_3(): if ogrtest.eeda_drv is None: - return 'skip' + pytest.skip() gdal.SetConfigOption('EEDA_BEARER', 'mybearer') gdal.SetConfigOption('EEDA_URL', '/vsimem/ee/') @@ -348,24 +315,19 @@ def eeda_3(): lyr = ds.GetLayer(0) - if lyr.GetLayerDefn().GetFieldCount() != 8 + 7 + 4: - gdaltest.post_reason('fail') - print(lyr.GetLayerDefn().GetFieldCount()) - return 'fail' + assert lyr.GetLayerDefn().GetFieldCount() == 8 + 7 + 4 ds = None gdal.SetConfigOption('EEDA_BEARER', None) - return 'success' - ############################################################################### # Test that name and id variants are handled correctly. -def eeda_4(): +def test_eeda_4(): if ogrtest.eeda_drv is None: - return 'skip' + pytest.skip() gdal.SetConfigOption('EEDA_BEARER', 'mybearer') gdal.SetConfigOption('EEDA_URL', '/vsimem/ee/') @@ -379,9 +341,7 @@ def eeda_4(): } ] })) - if not ogr.Open('EEDA:users/foo').GetLayer(0): - gdaltest.post_reason('fail') - return 'fail' + assert ogr.Open('EEDA:users/foo').GetLayer(0) gdal.Unlink(ogrtest.eeda_drv_tmpfile) # Project asset ID ("projects/**"). @@ -394,9 +354,7 @@ def eeda_4(): ] })) ds = ogr.Open('EEDA:projects/foo') - if not ds.GetLayer(0): - gdaltest.post_reason('fail') - return 'fail' + assert ds.GetLayer(0) gdal.Unlink(ogrtest.eeda_drv_tmpfile) ds = None @@ -410,9 +368,7 @@ def eeda_4(): ] })) ds = ogr.Open('EEDA:projects/foo/bar/baz') - if not ds.GetLayer(0): - gdaltest.post_reason('fail') - return 'fail' + assert ds.GetLayer(0) gdal.Unlink(ogrtest.eeda_drv_tmpfile) ds = None @@ -426,9 +382,7 @@ def eeda_4(): ] })) ds = ogr.Open('EEDA:foo') - if not ds.GetLayer(0): - gdaltest.post_reason('fail') - return 'fail' + assert ds.GetLayer(0) gdal.Unlink(ogrtest.eeda_drv_tmpfile) ds = None @@ -442,25 +396,21 @@ def eeda_4(): ] })) ds = ogr.Open('EEDA:projects/foo/assets/bar') - if not ds.GetLayer(0): - gdaltest.post_reason('fail') - return 'fail' + assert ds.GetLayer(0) gdal.Unlink(ogrtest.eeda_drv_tmpfile) ds = None gdal.SetConfigOption('EEDA_BEARER', None) gdal.SetConfigOption('EEDA_URL', None) - return 'success' - ############################################################################### # -def eeda_cleanup(): +def test_eeda_cleanup(): if ogrtest.eeda_drv is None: - return 'skip' + pytest.skip() gdal.SetConfigOption('CPL_CURL_ENABLE_VSIMEM', None) gdal.SetConfigOption('EEDA_BEARER', None) @@ -475,20 +425,5 @@ def eeda_cleanup(): gdal.Unlink('/vsimem/ee/projects/earthengine-public/assets/collection:listImages?pageToken=myToken') gdal.Unlink('/vsimem/ee/projects/earthengine-public/assets/collection:listImages?filter=raw%5Ffilter') - return 'success' - - -gdaltest_list = [ - eeda_1, - eeda_2, - eeda_3, - eeda_4, - eeda_cleanup] - -if __name__ == '__main__': - - gdaltest.setup_run('ogr_eeda') - gdaltest.run_tests(gdaltest_list) - sys.exit(gdaltest.summarize()) diff --git a/autotest/ogr/ogr_elasticsearch.py b/autotest/ogr/ogr_elasticsearch.py index 4c4b6514c729..f82671c8e628 100755 --- a/autotest/ogr/ogr_elasticsearch.py +++ b/autotest/ogr/ogr_elasticsearch.py @@ -28,22 +28,21 @@ # DEALINGS IN THE SOFTWARE. ############################################################################### -import sys -sys.path.append('../pymod') import ogrtest import gdaltest from osgeo import gdal from osgeo import ogr from osgeo import osr +import pytest ############################################################################### # Test driver availability # -def ogr_elasticsearch_init(): +def test_ogr_elasticsearch_init(): ogrtest.elasticsearch_drv = None ogrtest.srs_wgs84 = osr.SpatialReference() @@ -51,122 +50,84 @@ def ogr_elasticsearch_init(): ogrtest.elasticsearch_drv = ogr.GetDriverByName('ElasticSearch') if ogrtest.elasticsearch_drv is None: - return 'skip' + pytest.skip() gdal.SetConfigOption('CPL_CURL_ENABLE_VSIMEM', 'YES') - return 'success' - ############################################################################### # Test writing into an nonexistent ElasticSearch datastore. -def ogr_elasticsearch_nonexistent_server(): +def test_ogr_elasticsearch_nonexistent_server(): if ogrtest.elasticsearch_drv is None: - return 'skip' + pytest.skip() with gdaltest.error_handler(): ds = ogrtest.elasticsearch_drv.CreateDataSource( '/vsimem/nonexistent_host') - if ds is not None: - gdaltest.post_reason( - 'managed to open nonexistent ElasticSearch datastore.') - return 'fail' + assert ds is None, 'managed to open nonexistent ElasticSearch datastore.' with gdaltest.error_handler(): ds = ogrtest.elasticsearch_drv.Open('ES:/vsimem/nonexistent_host') - if ds is not None: - gdaltest.post_reason( - 'managed to open nonexistent ElasticSearch datastore.') - return 'fail' + assert ds is None, 'managed to open nonexistent ElasticSearch datastore.' gdal.FileFromMemBuffer("/vsimem/fakeelasticsearch", """{}""") with gdaltest.error_handler(): ds = ogrtest.elasticsearch_drv.Open('ES:/vsimem/fakeelasticsearch') - if ds is not None: - gdaltest.post_reason( - 'managed to open invalid ElasticSearch datastore.') - return 'fail' + assert ds is None, 'managed to open invalid ElasticSearch datastore.' gdal.FileFromMemBuffer("/vsimem/fakeelasticsearch", """{"version":null}""") with gdaltest.error_handler(): ds = ogrtest.elasticsearch_drv.Open('ES:/vsimem/fakeelasticsearch') - if ds is not None: - gdaltest.post_reason( - 'managed to open invalid ElasticSearch datastore.') - return 'fail' + assert ds is None, 'managed to open invalid ElasticSearch datastore.' gdal.FileFromMemBuffer("/vsimem/fakeelasticsearch", """{"version":{}}""") with gdaltest.error_handler(): ds = ogrtest.elasticsearch_drv.Open('ES:/vsimem/fakeelasticsearch') - if ds is not None: - gdaltest.post_reason( - 'managed to open invalid ElasticSearch datastore.') - return 'fail' + assert ds is None, 'managed to open invalid ElasticSearch datastore.' gdal.FileFromMemBuffer("/vsimem/fakeelasticsearch", """{"version":{"number":null}}""") with gdaltest.error_handler(): ds = ogrtest.elasticsearch_drv.Open('ES:/vsimem/fakeelasticsearch') - if ds is not None: - gdaltest.post_reason( - 'managed to open invalid ElasticSearch datastore.') - return 'fail' - - return 'success' + assert ds is None, 'managed to open invalid ElasticSearch datastore.' ############################################################################### # Simple test -def ogr_elasticsearch_1(): +def test_ogr_elasticsearch_1(): if ogrtest.elasticsearch_drv is None: - return 'skip' + pytest.skip() gdal.FileFromMemBuffer("/vsimem/fakeelasticsearch", """{"version":{"number":"2.0.0"}}""") ds = ogrtest.elasticsearch_drv.CreateDataSource( "/vsimem/fakeelasticsearch") - if ds is None: - gdaltest.post_reason('did not managed to open ElasticSearch datastore') - return 'fail' - - if ds.TestCapability(ogr.ODsCCreateLayer) == 0: - gdaltest.post_reason('fail') - return 'fail' - if ds.TestCapability(ogr.ODsCDeleteLayer) == 0: - gdaltest.post_reason('fail') - return 'fail' - if ds.TestCapability(ogr.ODsCCreateGeomFieldAfterCreateLayer) == 0: - gdaltest.post_reason('fail') - return 'fail' + assert ds is not None, 'did not managed to open ElasticSearch datastore' + + assert ds.TestCapability(ogr.ODsCCreateLayer) != 0 + assert ds.TestCapability(ogr.ODsCDeleteLayer) != 0 + assert ds.TestCapability(ogr.ODsCCreateGeomFieldAfterCreateLayer) != 0 # Failed index creation with gdaltest.error_handler(): lyr = ds.CreateLayer('foo', srs=ogrtest.srs_wgs84, options=['FID=']) - if lyr is not None: - gdaltest.post_reason('fail') - return 'fail' - if gdal.GetLastErrorType() != gdal.CE_Failure: - gdaltest.post_reason('fail') - return 'fail' + assert lyr is None + assert gdal.GetLastErrorType() == gdal.CE_Failure gdal.ErrorReset() # Successful index creation gdal.FileFromMemBuffer( '/vsimem/fakeelasticsearch/foo&CUSTOMREQUEST=PUT', '{}') lyr = ds.CreateLayer('foo', srs=ogrtest.srs_wgs84, options=['FID=']) - if lyr is None: - gdaltest.post_reason('fail') - return 'fail' - if gdal.GetLastErrorType() != gdal.CE_None: - gdaltest.post_reason('fail') - return 'fail' + assert lyr is not None + assert gdal.GetLastErrorType() == gdal.CE_None gdal.FileFromMemBuffer( '/vsimem/fakeelasticsearch/foo/FeatureCollection/_mapping&POSTFIELDS' @@ -176,9 +137,7 @@ def ogr_elasticsearch_1(): # OVERWRITE an nonexistent layer. lyr = ds.CreateLayer('foo', geom_type=ogr.wkbNone, options=['OVERWRITE=TRUE', 'FID=']) - if gdal.GetLastErrorType() != gdal.CE_None: - gdaltest.post_reason('fail') - return 'fail' + assert gdal.GetLastErrorType() == gdal.CE_None # Simulate failed overwrite gdal.FileFromMemBuffer('/vsimem/fakeelasticsearch/foo', @@ -186,9 +145,7 @@ def ogr_elasticsearch_1(): with gdaltest.error_handler(): lyr = ds.CreateLayer('foo', geom_type=ogr.wkbNone, options=['OVERWRITE=TRUE']) - if gdal.GetLastErrorType() != gdal.CE_Failure: - gdaltest.post_reason('fail') - return 'fail' + assert gdal.GetLastErrorType() == gdal.CE_Failure gdal.ErrorReset() # Successful overwrite @@ -198,46 +155,28 @@ def ogr_elasticsearch_1(): '/vsimem/fakeelasticsearch/foo/FeatureCollection/&POSTFIELDS={ }', '{}') lyr = ds.CreateLayer('foo', geom_type=ogr.wkbNone, options=[ 'OVERWRITE=TRUE', 'BULK_INSERT=NO', 'FID=']) - if gdal.GetLastErrorType() != gdal.CE_None: - gdaltest.post_reason('fail') - return 'fail' - - if lyr.TestCapability(ogr.OLCFastFeatureCount) == 0: - gdaltest.post_reason('fail') - return 'fail' - if lyr.TestCapability(ogr.OLCStringsAsUTF8) == 0: - gdaltest.post_reason('fail') - return 'fail' - if lyr.TestCapability(ogr.OLCSequentialWrite) == 0: - gdaltest.post_reason('fail') - return 'fail' - if lyr.TestCapability(ogr.OLCCreateField) == 0: - gdaltest.post_reason('fail') - return 'fail' - if lyr.TestCapability(ogr.OLCCreateGeomField) == 0: - gdaltest.post_reason('fail') - return 'fail' + assert gdal.GetLastErrorType() == gdal.CE_None + + assert lyr.TestCapability(ogr.OLCFastFeatureCount) != 0 + assert lyr.TestCapability(ogr.OLCStringsAsUTF8) != 0 + assert lyr.TestCapability(ogr.OLCSequentialWrite) != 0 + assert lyr.TestCapability(ogr.OLCCreateField) != 0 + assert lyr.TestCapability(ogr.OLCCreateGeomField) != 0 feat = ogr.Feature(lyr.GetLayerDefn()) gdal.FileFromMemBuffer( '/vsimem/fakeelasticsearch/foo/FeatureCollection/&POSTFIELDS={ "properties": { } }', '{}') ret = lyr.CreateFeature(feat) - if ret != 0: - gdaltest.post_reason('fail') - return 'fail' + assert ret == 0 feat = None gdal.FileFromMemBuffer('/vsimem/fakeelasticsearch/foo&CUSTOMREQUEST=PUT', '{"error":"IndexAlreadyExistsException[[foo] already exists]","status":400}') with gdaltest.error_handler(): lyr = ds.CreateLayer('foo', srs=ogrtest.srs_wgs84) - if gdal.GetLastErrorType() != gdal.CE_Failure: - gdaltest.post_reason('fail') - return 'fail' - if lyr is not None: - gdaltest.post_reason('fail') - return 'fail' + assert gdal.GetLastErrorType() == gdal.CE_Failure + assert lyr is None gdal.FileFromMemBuffer( """/vsimem/fakeelasticsearch/foo/FeatureCollection/_mapping&POSTFIELDS={ "FeatureCollection": { "properties": { "type": { "type": "string" }, "properties": { "properties": { } }, "geometry": { "type": "geo_shape" } } } }""", "") @@ -248,9 +187,7 @@ def ogr_elasticsearch_1(): ds.DeleteLayer(-1) ds.DeleteLayer(10) ret = ds.DeleteLayer(0) - if ret != 0: - gdaltest.post_reason('fail') - return 'fail' + assert ret == 0 gdal.FileFromMemBuffer( '/vsimem/fakeelasticsearch/foo2&CUSTOMREQUEST=PUT', '{}') @@ -275,9 +212,7 @@ def ogr_elasticsearch_1(): lyr.CreateField(ogr.FieldDefn('binary_field', ogr.OFTBinary)) ret = lyr.SyncToDisk() - if ret != 0: - gdaltest.post_reason('fail') - return 'fail' + assert ret == 0 feat = ogr.Feature(lyr.GetLayerDefn()) feat.SetField('str_field', 'a') @@ -298,20 +233,14 @@ def ogr_elasticsearch_1(): # Simulate server error with gdaltest.error_handler(): ret = lyr.CreateFeature(feat) - if ret == 0: - gdaltest.post_reason('fail') - return 'fail' + assert ret != 0 # Success gdal.FileFromMemBuffer( '/vsimem/fakeelasticsearch/foo2/FeatureCollection/&POSTFIELDS={ "geometry": { "type": "POINT", "coordinates": [ 0.0, 1.0 ] }, "type": "Feature", "properties": { "str_field": "a", "int_field": 1, "int64_field": 123456789012, "real_field": 2.34, "boolean_field": true, "strlist_field": [ "a", "b" ], "intlist_field": [ 1, 2 ], "int64list_field": [ 123456789012, 2 ], "reallist_field": [ 1.23, 4.56 ], "date_field": "2015\/08\/12", "datetime_field": "2015\/08\/12 12:34:56.789", "time_field": "12:34:56.789", "binary_field": "ASNGV4mrze8=" } }', '{ "_id": "my_id" }') ret = lyr.CreateFeature(feat) - if ret != 0: - gdaltest.post_reason('fail') - return 'fail' - if feat['_id'] != 'my_id': - gdaltest.post_reason('fail') - return 'fail' + assert ret == 0 + assert feat['_id'] == 'my_id' # DateTime with TZ gdal.FileFromMemBuffer( @@ -319,9 +248,7 @@ def ogr_elasticsearch_1(): feat = ogr.Feature(lyr.GetLayerDefn()) feat['datetime_field'] = '2015/08/12 12:34:56.789+0300' ret = lyr.CreateFeature(feat) - if ret != 0: - gdaltest.post_reason('fail') - return 'fail' + assert ret == 0 # CreateFeature() with _id set gdal.FileFromMemBuffer( @@ -329,32 +256,24 @@ def ogr_elasticsearch_1(): feat = ogr.Feature(lyr.GetLayerDefn()) feat['_id'] = 'my_id2' ret = lyr.CreateFeature(feat) - if ret != 0: - gdaltest.post_reason('fail') - return 'fail' + assert ret == 0 # Failed SetFeature because of missing _id feat = ogr.Feature(lyr.GetLayerDefn()) with gdaltest.error_handler(): ret = lyr.SetFeature(feat) - if ret == 0: - gdaltest.post_reason('fail') - return 'fail' + assert ret != 0 # Simulate server error feat['_id'] = 'my_id' with gdaltest.error_handler(): ret = lyr.SetFeature(feat) - if ret == 0: - gdaltest.post_reason('fail') - return 'fail' + assert ret != 0 gdal.FileFromMemBuffer( '/vsimem/fakeelasticsearch/foo2/FeatureCollection/my_id&POSTFIELDS={ "properties": { } }', '{}') ret = lyr.SetFeature(feat) - if ret != 0: - gdaltest.post_reason('fail') - return 'fail' + assert ret == 0 # With explicit GEOM_MAPPING_TYPE=GEO_POINT gdal.FileFromMemBuffer( @@ -369,9 +288,7 @@ def ogr_elasticsearch_1(): feat = ogr.Feature(lyr.GetLayerDefn()) feat.SetGeometry(ogr.CreateGeometryFromWkt('LINESTRING(0 0,1 1)')) ret = lyr.CreateFeature(feat) - if ret != 0: - gdaltest.post_reason('fail') - return 'fail' + assert ret == 0 feat = None # Test explicit MAPPING first with error case @@ -380,18 +297,14 @@ def ogr_elasticsearch_1(): with gdaltest.error_handler(): lyr = ds.CreateLayer('foo4', srs=ogrtest.srs_wgs84, options=[ 'MAPPING={ "FeatureCollection": { "properties": {} }}']) - if lyr is not None: - gdaltest.post_reason('fail') - return 'fail' + assert lyr is None # Test successful explicit MAPPING with inline JSon mapping gdal.FileFromMemBuffer( '/vsimem/fakeelasticsearch/foo4/FeatureCollection/_mapping&POSTFIELDS={ "FeatureCollection": { "properties": {} }}', '{}') lyr = ds.CreateLayer('foo4', srs=ogrtest.srs_wgs84, options=[ 'MAPPING={ "FeatureCollection": { "properties": {} }}']) - if lyr is None: - gdaltest.post_reason('fail') - return 'fail' + assert lyr is not None # Test successful explicit MAPPING with reference to file with mapping gdal.FileFromMemBuffer( @@ -401,9 +314,7 @@ def ogr_elasticsearch_1(): lyr = ds.CreateLayer('foo4', srs=ogrtest.srs_wgs84, options=['MAPPING=/vsimem/map.txt']) gdal.Unlink('/vsimem/map.txt') - if lyr is None: - gdaltest.post_reason('fail') - return 'fail' + assert lyr is not None # Test successful explicit INDEX_DEFINITION with inline JSon mapping gdal.FileFromMemBuffer( @@ -412,9 +323,7 @@ def ogr_elasticsearch_1(): '/vsimem/fakeelasticsearch/foo4/FeatureCollection/_mapping&POSTFIELDS={}', '{}') lyr = ds.CreateLayer('foo4', srs=ogrtest.srs_wgs84, options=[ 'INDEX_DEFINITION={}', 'MAPPING={}']) - if lyr is None: - gdaltest.post_reason('fail') - return 'fail' + assert lyr is not None # Test successful explicit INDEX_DEFINITION with reference to file gdal.FileFromMemBuffer('/vsimem/map.txt', '{"foo":"bar"}') @@ -423,25 +332,19 @@ def ogr_elasticsearch_1(): lyr = ds.CreateLayer('foo4', srs=ogrtest.srs_wgs84, options=['INDEX_DEFINITION=/vsimem/map.txt', 'MAPPING={}']) gdal.Unlink('/vsimem/map.txt') - if lyr is None: - gdaltest.post_reason('fail') - return 'fail' - - return 'success' + assert lyr is not None ############################################################################### # Geo_shape geometries -def ogr_elasticsearch_2(): +def test_ogr_elasticsearch_2(): if ogrtest.elasticsearch_drv is None: - return 'skip' + pytest.skip() ds = ogrtest.elasticsearch_drv.CreateDataSource( "/vsimem/fakeelasticsearch") - if ds is None: - gdaltest.post_reason('did not managed to open ElasticSearch datastore') - return 'fail' + assert ds is not None, 'did not managed to open ElasticSearch datastore' gdal.FileFromMemBuffer( '/vsimem/fakeelasticsearch/foo&CUSTOMREQUEST=PUT', '{}') @@ -457,9 +360,7 @@ def ogr_elasticsearch_2(): gdal.FileFromMemBuffer('/vsimem/fakeelasticsearch/foo/FeatureCollection/&POSTFIELDS={ "geometry": { "type": "geometrycollection", "geometries": [ { "type": "point", "coordinates": [ 0.0, 1.0 ] }, { "type": "linestring", "coordinates": [ [ 0.0, 1.0 ], [ 2.0, 3.0 ] ] }, { "type": "polygon", "coordinates": [ [ [ 0.0, 0.0 ], [ 0.0, 10.0 ], [ 10.0, 10.0 ], [ 0.0, 0.0 ] ], [ [ 1.0, 1.0 ], [ 1.0, 9.0 ], [ 9.0, 9.0 ], [ 1.0, 1.0 ] ] ] }, { "type": "multipoint", "coordinates": [ [ 0.0, 1.0 ], [ 2.0, 3.0 ] ] }, { "type": "multilinestring", "coordinates": [ [ [ 0.0, 1.0 ], [ 2.0, 3.0 ] ], [ [ 4.0, 5.0 ], [ 6.0, 7.0 ] ] ] }, { "type": "multipolygon", "coordinates": [ [ [ [ 0.0, 0.0 ], [ 0.0, 10.0 ], [ 10.0, 10.0 ], [ 0.0, 0.0 ] ], [ [ 1.0, 1.0 ], [ 1.0, 9.0 ], [ 9.0, 9.0 ], [ 1.0, 1.0 ] ] ], [ [ [ -1.0, -1.0 ], [ -1.0, -9.0 ], [ -9.0, -9.0 ], [ -1.0, -1.0 ] ] ] ] } ] }, "type": "Feature", "properties": { } }', '{}') ret = lyr.CreateFeature(feat) - if ret != 0: - gdaltest.post_reason('fail') - return 'fail' + assert ret == 0 feat = None # Same but with explicit GEOM_MAPPING_TYPE=GEO_SHAPE @@ -473,26 +374,20 @@ def ogr_elasticsearch_2(): '/vsimem/fakeelasticsearch/foo/FeatureCollection/_mapping&POSTFIELDS={ "FeatureCollection": { "properties": { "type": { "type": "string" }, "properties": { "properties": { } }, "geometry": { "type": "geo_shape", "precision": "1m" } } } }', '{}') ret = lyr.CreateFeature(feat) - if ret != 0: - gdaltest.post_reason('fail') - return 'fail' + assert ret == 0 feat = None - return 'success' - ############################################################################### # Test bulk insert and layer name laundering -def ogr_elasticsearch_3(): +def test_ogr_elasticsearch_3(): if ogrtest.elasticsearch_drv is None: - return 'skip' + pytest.skip() ds = ogrtest.elasticsearch_drv.CreateDataSource( "/vsimem/fakeelasticsearch") - if ds is None: - gdaltest.post_reason('did not managed to open ElasticSearch datastore') - return 'fail' + assert ds is not None, 'did not managed to open ElasticSearch datastore' gdal.FileFromMemBuffer( '/vsimem/fakeelasticsearch/name_laundering&CUSTOMREQUEST=PUT', '{}') @@ -503,22 +398,16 @@ def ogr_elasticsearch_3(): 'NAME/laundering', srs=ogrtest.srs_wgs84, options=['FID=']) feat = ogr.Feature(lyr.GetLayerDefn()) ret = lyr.CreateFeature(feat) - if ret != 0: - gdaltest.post_reason('fail') - return 'fail' + assert ret == 0 feat = None with gdaltest.error_handler(): ret = lyr.SyncToDisk() - if ret == 0: - gdaltest.post_reason('fail') - return 'fail' + assert ret != 0 feat = ogr.Feature(lyr.GetLayerDefn()) ret = lyr.CreateFeature(feat) - if ret != 0: - gdaltest.post_reason('fail') - return 'fail' + assert ret == 0 feat = None gdal.FileFromMemBuffer("""/vsimem/fakeelasticsearch/_bulk&POSTFIELDS={"index" :{"_index":"name_laundering", "_type":"FeatureCollection"}} @@ -526,39 +415,28 @@ def ogr_elasticsearch_3(): """, '{}') ret = lyr.SyncToDisk() - if ret != 0: - gdaltest.post_reason('fail') - return 'fail' + assert ret == 0 ds = None - return 'success' - ############################################################################### # Test basic read functionality -def ogr_elasticsearch_4(): +def test_ogr_elasticsearch_4(): if ogrtest.elasticsearch_drv is None: - return 'skip' + pytest.skip() with gdaltest.error_handler(): ds = ogr.Open('ES:/vsimem/fakeelasticsearch') - if ds is None: - gdaltest.post_reason('fail') - return 'fail' + assert ds is not None # Test case where there's no index gdal.FileFromMemBuffer( """/vsimem/fakeelasticsearch/_cat/indices?h=i""", '\n') ds = ogr.Open('ES:/vsimem/fakeelasticsearch') - if ds is None: - gdaltest.post_reason('fail') - return 'fail' - if ds.GetLayerCount() != 0: - gdaltest.post_reason('fail') - print(ds.GetLayerCount()) - return 'fail' + assert ds is not None + assert ds.GetLayerCount() == 0 # Test opening a layer by name gdal.FileFromMemBuffer("""/vsimem/fakeelasticsearch/a_layer/_mapping?pretty""", """ @@ -627,49 +505,33 @@ def ogr_elasticsearch_4(): """) ds = ogr.Open('ES:/vsimem/fakeelasticsearch') - if ds is None: - gdaltest.post_reason('fail') - return 'fail' + assert ds is not None lyr = ds.GetLayerByName('a_layer') - if lyr is None: - gdaltest.post_reason('fail') - return 'fail' + assert lyr is not None lyr = ds.GetLayerByName('a_layer') - if lyr is None: - gdaltest.post_reason('fail') - return 'fail' + assert lyr is not None with gdaltest.error_handler(): lyr = ds.GetLayerByName('not_a_layer') - if lyr is not None: - gdaltest.post_reason('fail') - return 'fail' + assert lyr is None ds = None # Test LAYER open option ds = gdal.OpenEx('ES:/vsimem/fakeelasticsearch', open_options=['LAYER=a_layer']) - if ds.GetLayerCount() != 1: - gdaltest.post_reason('fail') - print(ds.GetLayerCount()) - return 'fail' + assert ds.GetLayerCount() == 1 ds = None with gdaltest.error_handler(): ds = gdal.OpenEx('ES:/vsimem/fakeelasticsearch', open_options=['LAYER=not_a_layer']) - if ds is not None: - gdaltest.post_reason('fail') - return 'fail' + assert ds is None ds = None # Test GetLayerByName() and GetLayerCount() ds = ogr.Open('ES:/vsimem/fakeelasticsearch') lyr = ds.GetLayerByName('a_layer') lyr = ds.GetLayerByName('a_layer') - if ds.GetLayerCount() != 1: - gdaltest.post_reason('fail') - print(ds.GetLayerCount()) - return 'fail' + assert ds.GetLayerCount() == 1 ds = None # Test GetLayerCount() @@ -677,28 +539,17 @@ def ogr_elasticsearch_4(): """/vsimem/fakeelasticsearch/_cat/indices?h=i""", 'a_layer \n') ds = ogr.Open('ES:/vsimem/fakeelasticsearch') - if ds is None: - gdaltest.post_reason('fail') - return 'fail' - if ds.GetLayerCount() != 1: - gdaltest.post_reason('fail') - print(ds.GetLayerCount()) - return 'fail' + assert ds is not None + assert ds.GetLayerCount() == 1 lyr = ds.GetLayer(0) with gdaltest.error_handler(): lyr_defn = lyr.GetLayerDefn() idx = lyr_defn.GetFieldIndex("strlist_field") - if lyr_defn.GetFieldDefn(idx).GetType() != ogr.OFTStringList: - gdaltest.post_reason('fail') - return 'fail' + assert lyr_defn.GetFieldDefn(idx).GetType() == ogr.OFTStringList idx = lyr_defn.GetGeomFieldIndex("a_geoshape") - if lyr_defn.GetGeomFieldDefn(idx).GetType() != ogr.wkbLineString: - gdaltest.post_reason('fail') - return 'fail' - if lyr.GetFIDColumn() != 'my_fid': - gdaltest.post_reason('fail') - return 'fail' + assert lyr_defn.GetGeomFieldDefn(idx).GetType() == ogr.wkbLineString + assert lyr.GetFIDColumn() == 'my_fid' gdal.FileFromMemBuffer("""/vsimem/fakeelasticsearch/a_layer/FeatureCollection/_count?pretty""", """{ }""") @@ -724,24 +575,18 @@ def ogr_elasticsearch_4(): } }""") fc = lyr.GetFeatureCount() - if fc != 3: - gdaltest.post_reason('fail') - return 'fail' + assert fc == 3 with gdaltest.error_handler(): f = lyr.GetNextFeature() - if f is not None: - gdaltest.post_reason('fail') - return 'fail' + assert f is None gdal.FileFromMemBuffer("""/vsimem/fakeelasticsearch/a_layer/FeatureCollection/_search?scroll=1m&size=100""", """{ }""") lyr.ResetReading() f = lyr.GetNextFeature() - if f is not None: - gdaltest.post_reason('fail') - return 'fail' + assert f is None gdal.FileFromMemBuffer("""/vsimem/fakeelasticsearch/a_layer/FeatureCollection/_search?scroll=1m&size=100""", """{ "hits": null @@ -807,10 +652,7 @@ def ogr_elasticsearch_4(): ds = ogr.Open('ES:/vsimem/fakeelasticsearch') lyr = ds.GetLayer(0) - if lyr.GetLayerDefn().GetFieldCount() != 15: - gdaltest.post_reason('fail') - print(lyr.GetLayerDefn().GetFieldCount()) - return 'fail' + assert lyr.GetLayerDefn().GetFieldCount() == 15 gdal.FileFromMemBuffer("""/vsimem/fakeelasticsearch/a_layer/FeatureCollection/_search?scroll=1m&size=100""", """{ "_scroll_id": "my_scrollid", @@ -862,9 +704,7 @@ def ogr_elasticsearch_4(): lyr.ResetReading() f = lyr.GetNextFeature() - if f is None: - gdaltest.post_reason('fail') - return 'fail' + assert f is not None if f.GetFID() != 5 or f['_id'] != 'my_id' or f['str_field'] != 'foo' or f['int_field'] != 1 or f['int64_field'] != 123456789012 or \ f['double_field'] != 1.23 or f['float_field'] != 3.45 or f['boolean_field'] != 1 or \ f['binary_field'] != '0123465789ABCDEF' or f['dt_field'] != '2015/08/12 12:34:56.789' or \ @@ -875,16 +715,13 @@ def ogr_elasticsearch_4(): f['doublelist_field'] != [1.23] or \ f['a_geopoint'].ExportToWkt() != 'POINT (2 49)' or \ f['a_geoshape'].ExportToWkt() != 'LINESTRING (2 49,3 50)': - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' + pytest.fail() lyr.ResetReading() lyr.GetNextFeature() f = lyr.GetNextFeature() - if f is None: - gdaltest.post_reason('fail') - return 'fail' + assert f is not None gdal.FileFromMemBuffer("""/vsimem/fakeelasticsearch/_search/scroll?scroll=1m&scroll_id=my_scrollid""", """{ "hits": @@ -902,9 +739,7 @@ def ogr_elasticsearch_4(): } }""") f = lyr.GetNextFeature() - if f['int_field'] != 2: - gdaltest.post_reason('fail') - return 'fail' + assert f['int_field'] == 2 gdal.FileFromMemBuffer("""/vsimem/fakeelasticsearch/_search/scroll?scroll=1m&scroll_id=my_scrollid""", """{ "hits": @@ -913,13 +748,9 @@ def ogr_elasticsearch_4(): } }""") f = lyr.GetNextFeature() - if f is not None: - gdaltest.post_reason('fail') - return 'fail' + assert f is None f = lyr.GetNextFeature() - if f is not None: - gdaltest.post_reason('fail') - return 'fail' + assert f is None lyr.SetSpatialFilterRect(1, 48, 3, 50) lyr.ResetReading() @@ -943,9 +774,7 @@ def ogr_elasticsearch_4(): } }""") f = lyr.GetNextFeature() - if f['int_field'] != 3: - gdaltest.post_reason('fail') - return 'fail' + assert f['int_field'] == 3 lyr.SetSpatialFilterRect(1, 1, 48, 3, 50) lyr.ResetReading() @@ -969,9 +798,7 @@ def ogr_elasticsearch_4(): } }""") f = lyr.GetNextFeature() - if f['int_field'] != 4: - gdaltest.post_reason('fail') - return 'fail' + assert f['int_field'] == 4 gdal.FileFromMemBuffer("""/vsimem/fakeelasticsearch/a_layer/FeatureCollection/_search?pretty&POSTFIELDS={ "size": 0, "query": { "constant_score" : { "filter": { "geo_bounding_box": { "a_geopoint.coordinates": { "top_left": { "lat": 50.0, "lon": 1.0 }, "bottom_right": { "lat": 48.0, "lon": 3.0 } } } } } } }""", """{ "hits": @@ -980,9 +807,7 @@ def ogr_elasticsearch_4(): } }""") fc = lyr.GetFeatureCount() - if fc != 10: - gdaltest.post_reason('fail') - return 'fail' + assert fc == 10 lyr.SetSpatialFilter(None) lyr.SetSpatialFilterRect(-180, -90, 180, 90) @@ -1012,9 +837,7 @@ def ogr_elasticsearch_4(): } }""") f = lyr.GetNextFeature() - if f['int_field'] != 5: - gdaltest.post_reason('fail') - return 'fail' + assert f['int_field'] == 5 lyr.SetAttributeFilter(None) sql_lyr = ds.ExecuteSQL("{ 'FOO' : 'BAR' }", dialect='ES') @@ -1051,9 +874,8 @@ def ogr_elasticsearch_4(): """) f = sql_lyr.GetNextFeature() if f['some_field'] != '5': - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' + pytest.fail() ds.ReleaseResultSet(sql_lyr) # Invalid index @@ -1110,58 +932,41 @@ def ogr_elasticsearch_4(): } }""") bbox = lyr.GetExtent(geom_field=1) - if bbox != (1.0, 2.0, 9.0, 10.0): - gdaltest.post_reason('fail') - print(bbox) - return 'fail' + assert bbox == (1.0, 2.0, 9.0, 10.0) # Operations not available in read-only mode with gdaltest.error_handler(): ret = lyr.CreateField(ogr.FieldDefn('foo', ogr.OFTString)) - if ret == 0: - gdaltest.post_reason('fail') - return 'fail' + assert ret != 0 with gdaltest.error_handler(): ret = lyr.CreateGeomField(ogr.GeomFieldDefn('shape', ogr.wkbPoint)) - if ret == 0: - gdaltest.post_reason('fail') - return 'fail' + assert ret != 0 with gdaltest.error_handler(): ret = lyr.CreateFeature(ogr.Feature(lyr.GetLayerDefn())) - if ret == 0: - gdaltest.post_reason('fail') - return 'fail' + assert ret != 0 lyr.ResetReading() with gdaltest.error_handler(): ret = lyr.SetFeature(lyr.GetNextFeature()) - if ret == 0: - gdaltest.post_reason('fail') - return 'fail' + assert ret != 0 with gdaltest.error_handler(): lyr = ds.CreateLayer('will_not_work') - if lyr is not None: - gdaltest.post_reason('fail') - return 'fail' + assert lyr is None with gdaltest.error_handler(): ret = ds.DeleteLayer(0) - if ret == 0: - gdaltest.post_reason('fail') - return 'fail' - - return 'success' + assert ret != 0 ############################################################################### # Write documents with non geojson structure -def ogr_elasticsearch_5(): +def test_ogr_elasticsearch_5(): if ogrtest.elasticsearch_drv is None: - return 'skip' + pytest.skip() gdal.FileFromMemBuffer("/vsimem/fakeelasticsearch/_stats", """{"_shards":{"total":0,"successful":0,"failed":0},"indices":{}}""") @@ -1183,9 +988,7 @@ def ogr_elasticsearch_5(): gdal.FileFromMemBuffer( '/vsimem/fakeelasticsearch/non_geojson/my_mapping/&POSTFIELDS={ "ogc_fid": 5, "str": "foo" }', '{}') ret = lyr.CreateFeature(feat) - if ret != 0: - gdaltest.post_reason('fail') - return 'fail' + assert ret == 0 feat = None ds = None @@ -1294,9 +1097,7 @@ def ogr_elasticsearch_5(): } }""") index = lyr.GetLayerDefn().GetFieldIndex('another_field') - if index < 0: - gdaltest.post_reason('fail') - return 'fail' + assert index >= 0 f = lyr.GetNextFeature() if f['str_field'] != 'foo' or \ f['superobject.subfield'] != '5' or \ @@ -1307,36 +1108,30 @@ def ogr_elasticsearch_5(): f['a_geoshape'].ExportToWkt() != 'LINESTRING (2 49,3 50)' or \ f['superobject.another_geoshape'].ExportToWkt() != 'POINT (3 50)' or \ f['superobject.another_geoshape2'].ExportToWkt() != 'POINT (2 50)': - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' + pytest.fail() f['_id'] = 'my_id' gdal.FileFromMemBuffer( """/vsimem/fakeelasticsearch/non_geojson/my_mapping/my_id&POSTFIELDS={ "a_geoshape": { "type": "linestring", "coordinates": [ [ 2.0, 49.0 ], [ 3.0, 50.0 ] ] }, "a_geopoint": { "type": "POINT", "coordinates": [ 2.0, 49.0 ] }, "another_geopoint": [ 2.5, 49.5 ], "superobject": { "another_geoshape": { "type": "point", "coordinates": [ 3.0, 50.0 ] }, "another_geoshape2": { "type": "point", "coordinates": [ 2.0, 50.0 ] }, "subfield": "5", "subobject": { "subfield": "foo", "another_subfield": 6 } }, "str_field": "foo" }""", "{}") ret = lyr.SetFeature(f) - if ret != 0: - gdaltest.post_reason('failure') - return 'fail' + assert ret == 0 f = lyr.GetNextFeature() if f['another_geopoint'].ExportToWkt() != 'POINT (2.1 49.1)': - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' + pytest.fail() f = lyr.GetNextFeature() if f['another_geopoint'].ExportToWkt() != 'POINT (2.2 49.2)': - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' + pytest.fail() # Test geohash f = lyr.GetNextFeature() if ogrtest.check_feature_geometry(f['another_geopoint'], 'POINT (2 49)') != 0: - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' + pytest.fail() f = None lyr.CreateField(ogr.FieldDefn('superobject.subfield2', ogr.OFTString)) @@ -1363,25 +1158,21 @@ def ogr_elasticsearch_5(): f['a_geopoint'].ExportToWkt() != 'POINT (2 49)' or \ f['a_geoshape'].ExportToWkt() != 'LINESTRING (2 49,3 50)' or \ f['superobject.another_geoshape'].ExportToWkt() != 'POINT (3 50)': - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' + pytest.fail() ds = gdal.OpenEx("ES:/vsimem/fakeelasticsearch", open_options=[ 'FEATURE_COUNT_TO_ESTABLISH_FEATURE_DEFN=0', 'FLATTEN_NESTED_ATTRIBUTES=FALSE']) lyr = ds.GetLayer(0) index = lyr.GetLayerDefn().GetFieldIndex('another_field') - if index >= 0: - gdaltest.post_reason('fail') - return 'fail' + assert index < 0 f = lyr.GetNextFeature() if f['str_field'] != 'foo' or \ f['superobject'] != '{ "subfield": 5, "subobject": { "subfield": "foo", "another_subfield": 6 }, "another_geoshape": { "type": "point", "coordinates": [ 3, 50 ] }, "another_geoshape2": { "type": "point", "coordinates": [ 2, 50 ] } }' or \ f['a_geopoint'].ExportToWkt() != 'POINT (2 49)' or \ f['a_geoshape'].ExportToWkt() != 'LINESTRING (2 49,3 50)': - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' + pytest.fail() ds = gdal.OpenEx("ES:/vsimem/fakeelasticsearch", gdal.OF_UPDATE, open_options=['JSON_FIELD=YES']) @@ -1393,28 +1184,23 @@ def ogr_elasticsearch_5(): f['a_geopoint'].ExportToWkt() != 'POINT (2 49)' or \ f['a_geoshape'].ExportToWkt() != 'LINESTRING (2 49,3 50)' or \ f['superobject.another_geoshape'].ExportToWkt() != 'POINT (3 50)': - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' + pytest.fail() f['_id'] = 'my_id' f['_json'] = '{ "foo": "bar" }' gdal.FileFromMemBuffer( """/vsimem/fakeelasticsearch/non_geojson/my_mapping/my_id&POSTFIELDS={ "foo": "bar" }""", "{}") ret = lyr.SetFeature(f) - if ret != 0: - gdaltest.post_reason('fail') - return 'fail' - - return 'success' + assert ret == 0 ############################################################################### # Test reading circle and envelope geometries -def ogr_elasticsearch_6(): +def test_ogr_elasticsearch_6(): if ogrtest.elasticsearch_drv is None: - return 'skip' + pytest.skip() gdal.FileFromMemBuffer( """/vsimem/fakeelasticsearch/_cat/indices?h=i""", 'non_standard_geometries\n') @@ -1484,38 +1270,33 @@ def ogr_elasticsearch_6(): }""") f = lyr.GetNextFeature() if f['geometry'].ExportToWkt() != 'POLYGON ((2 49,3 49,3 50,2 50,2 49))': - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' + pytest.fail() f = lyr.GetNextFeature() ref_txt = f['geometry'].ExportToWkt() if ref_txt.find('POLYGON ((') != 0: - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' + pytest.fail() f = lyr.GetNextFeature() if f['geometry'].ExportToWkt() != ref_txt: - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' + pytest.fail() f = lyr.GetNextFeature() if f['geometry'].ExportToWkt() != ref_txt: - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' - - return 'success' + pytest.fail() + ############################################################################### # Test WRITE_MAPPING option -def ogr_elasticsearch_7(): +def test_ogr_elasticsearch_7(): if ogrtest.elasticsearch_drv is None: - return 'skip' + pytest.skip() gdal.FileFromMemBuffer("/vsimem/fakeelasticsearch/_stats", """{"_shards":{"total":0,"successful":0,"failed":0},"indices":{}}""") @@ -1532,28 +1313,21 @@ def ogr_elasticsearch_7(): ds = None f = gdal.VSIFOpenL('/vsimem/map.txt', 'rb') - if f is None: - gdaltest.post_reason('fail') - return 'fail' + assert f is not None data = gdal.VSIFReadL(1, 10000, f).decode('ascii') gdal.VSIFCloseL(f) gdal.Unlink('/vsimem/map.txt') - if data != '{ "FeatureCollection": { "properties": { "type": { "type": "string" }, "properties": { "properties": { } }, "geometry": { "type": "geo_shape" } } } }': - gdaltest.post_reason('fail') - print(data) - return 'fail' - - return 'success' + assert data == '{ "FeatureCollection": { "properties": { "type": { "type": "string" }, "properties": { "properties": { } }, "geometry": { "type": "geo_shape" } } } }' ############################################################################### # Test SRS support -def ogr_elasticsearch_8(): +def test_ogr_elasticsearch_8(): if ogrtest.elasticsearch_drv is None: - return 'skip' + pytest.skip() gdal.FileFromMemBuffer("/vsimem/fakeelasticsearch/_stats", """{"_shards":{"total":0,"successful":0,"failed":0},"indices":{}}""") @@ -1568,9 +1342,7 @@ def ogr_elasticsearch_8(): gdal.ErrorReset() with gdaltest.error_handler(): lyr = ds.CreateLayer('no_srs') - if gdal.GetLastErrorType() != gdal.CE_Warning: - gdaltest.post_reason('warning expected') - return 'fail' + assert gdal.GetLastErrorType() == gdal.CE_Warning, 'warning expected' f = ogr.Feature(lyr.GetLayerDefn()) f.SetGeometry(ogr.CreateGeometryFromWkt('POINT (-100 -200)')) gdal.FileFromMemBuffer( @@ -1583,12 +1355,8 @@ def ogr_elasticsearch_8(): gdal.ErrorReset() with gdaltest.error_handler(): ret = lyr.CreateFeature(f) - if gdal.GetLastErrorType() != gdal.CE_Warning: - gdaltest.post_reason('warning expected') - return 'fail' - if ret != 0: - gdaltest.post_reason('fail') - return 'fail' + assert gdal.GetLastErrorType() == gdal.CE_Warning, 'warning expected' + assert ret == 0 # Non EPSG-4326 SRS other_srs = osr.SpatialReference() @@ -1605,19 +1373,15 @@ def ogr_elasticsearch_8(): """, "{}") ret = lyr.CreateFeature(f) - if ret != 0: - gdaltest.post_reason('fail') - return 'fail' - - return 'success' + assert ret == 0 ############################################################################### # Test ElasticSearch 5.X -def ogr_elasticsearch_9(): +def test_ogr_elasticsearch_9(): if ogrtest.elasticsearch_drv is None: - return 'skip' + pytest.skip() ogr_elasticsearch_delete_files() @@ -1691,9 +1455,7 @@ def ogr_elasticsearch_9(): }""") count = lyr.GetFeatureCount() - if count != 2: - gdaltest.post_reason('fail') - return 'fail' + assert count == 2 gdal.FileFromMemBuffer("""/vsimem/fakeelasticsearch/a_layer/FeatureCollection/_search?scroll=1m&size=100&POSTFIELDS={ "query": { "constant_score" : { "filter": { "geo_shape": { "a_geoshape": { "shape": { "type": "envelope", "coordinates": [ [ 2.0, 50.0 ], [ 3.0, 49.0 ] ] } } } } } } }""", """{ @@ -1717,19 +1479,15 @@ def ogr_elasticsearch_9(): } }""") f = lyr.GetNextFeature() - if f is None: - gdaltest.post_reason('fail') - return 'fail' - - return 'success' + assert f is not None ############################################################################### # Test SQL -def ogr_elasticsearch_10(): +def test_ogr_elasticsearch_10(): if ogrtest.elasticsearch_drv is None: - return 'skip' + pytest.skip() ogr_elasticsearch_delete_files() @@ -1803,9 +1561,7 @@ def ogr_elasticsearch_10(): } }""") f = lyr.GetNextFeature() - if f is None: - gdaltest.post_reason('fail') - return 'fail' + assert f is not None lyr.SetAttributeFilter("text_field = 'foo'") gdal.FileFromMemBuffer("""/vsimem/fakeelasticsearch/a_layer/FeatureCollection/_search?scroll=1m&size=100&POSTFIELDS={ "query": { "constant_score" : { "filter": { "match": { "properties.text_field": "foo" } } } } }""", @@ -1826,9 +1582,7 @@ def ogr_elasticsearch_10(): } }""") f = lyr.GetNextFeature() - if f is None: - gdaltest.post_reason('fail') - return 'fail' + assert f is not None lyr.SetAttributeFilter("text_field_with_raw = 'foo'") gdal.FileFromMemBuffer("""/vsimem/fakeelasticsearch/a_layer/FeatureCollection/_search?scroll=1m&size=100&POSTFIELDS={ "query": { "constant_score" : { "filter": { "term": { "properties.text_field_with_raw.raw": "foo" } } } } }""", @@ -1849,9 +1603,7 @@ def ogr_elasticsearch_10(): } }""") f = lyr.GetNextFeature() - if f is None: - gdaltest.post_reason('fail') - return 'fail' + assert f is not None lyr.SetAttributeFilter("\"_id\" = 'my_id2'") gdal.FileFromMemBuffer("""/vsimem/fakeelasticsearch/a_layer/FeatureCollection/_search?scroll=1m&size=100&POSTFIELDS={ "query": { "constant_score" : { "filter": { "ids": { "values": [ "my_id2" ] } } } } }""", @@ -1871,9 +1623,7 @@ def ogr_elasticsearch_10(): } }""") f = lyr.GetNextFeature() - if f is None: - gdaltest.post_reason('fail') - return 'fail' + assert f is not None lyr.SetAttributeFilter("keyword_field != 'foo'") gdal.FileFromMemBuffer("""/vsimem/fakeelasticsearch/a_layer/FeatureCollection/_search?scroll=1m&size=100&POSTFIELDS={ "query": { "constant_score" : { "filter": { "bool": { "must_not": { "term": { "properties.keyword_field": "foo" } } } } } } }""", @@ -1894,9 +1644,7 @@ def ogr_elasticsearch_10(): } }""") f = lyr.GetNextFeature() - if f is None: - gdaltest.post_reason('fail') - return 'fail' + assert f is not None lyr.SetAttributeFilter("keyword_field IS NULL") gdal.FileFromMemBuffer("""/vsimem/fakeelasticsearch/a_layer/FeatureCollection/_search?scroll=1m&size=100&POSTFIELDS={ "query": { "constant_score" : { "filter": { "bool": { "must_not": { "exists": { "field": "properties.keyword_field" } } } } } } }""", @@ -1916,9 +1664,7 @@ def ogr_elasticsearch_10(): } }""") f = lyr.GetNextFeature() - if f is None: - gdaltest.post_reason('fail') - return 'fail' + assert f is not None lyr.SetAttributeFilter("keyword_field BETWEEN 'bar' AND 'foo'") gdal.FileFromMemBuffer("""/vsimem/fakeelasticsearch/a_layer/FeatureCollection/_search?scroll=1m&size=100&POSTFIELDS={ "query": { "constant_score" : { "filter": { "range": { "properties.keyword_field": { "gte": "bar", "lte": "foo" } } } } } }""", @@ -1939,9 +1685,7 @@ def ogr_elasticsearch_10(): } }""") f = lyr.GetNextFeature() - if f is None: - gdaltest.post_reason('fail') - return 'fail' + assert f is not None lyr.SetAttributeFilter("keyword_field IN ('foo', 'bar')") gdal.FileFromMemBuffer("""/vsimem/fakeelasticsearch/a_layer/FeatureCollection/_search?scroll=1m&size=100&POSTFIELDS={ "query": { "constant_score" : { "filter": { "terms": { "properties.keyword_field": [ "foo", "bar" ] } } } } }""", @@ -1962,9 +1706,7 @@ def ogr_elasticsearch_10(): } }""") f = lyr.GetNextFeature() - if f is None: - gdaltest.post_reason('fail') - return 'fail' + assert f is not None lyr.SetAttributeFilter("text_field IN ('foo', 'bar')") gdal.FileFromMemBuffer("""/vsimem/fakeelasticsearch/a_layer/FeatureCollection/_search?scroll=1m&size=100&POSTFIELDS={ "query": { "constant_score" : { "filter": { "bool": { "should": [ { "match": { "properties.text_field": "foo" } }, { "match": { "properties.text_field": "bar" } } ] } } } } }""", @@ -1985,9 +1727,7 @@ def ogr_elasticsearch_10(): } }""") f = lyr.GetNextFeature() - if f is None: - gdaltest.post_reason('fail') - return 'fail' + assert f is not None lyr.SetAttributeFilter("text_field_with_raw IN ('foo', 'bar')") gdal.FileFromMemBuffer("""/vsimem/fakeelasticsearch/a_layer/FeatureCollection/_search?scroll=1m&size=100&POSTFIELDS={ "query": { "constant_score" : { "filter": { "terms": { "properties.text_field_with_raw.raw": [ "foo", "bar" ] } } } } }""", @@ -2008,9 +1748,7 @@ def ogr_elasticsearch_10(): } }""") f = lyr.GetNextFeature() - if f is None: - gdaltest.post_reason('fail') - return 'fail' + assert f is not None lyr.SetAttributeFilter("\"_id\" IN ('my_id', 'bar')") gdal.FileFromMemBuffer("""/vsimem/fakeelasticsearch/a_layer/FeatureCollection/_search?scroll=1m&size=100&POSTFIELDS={ "query": { "constant_score" : { "filter": { "ids": { "values": [ "my_id", "bar" ] } } } } }""", @@ -2031,9 +1769,7 @@ def ogr_elasticsearch_10(): } }""") f = lyr.GetNextFeature() - if f is None: - gdaltest.post_reason('fail') - return 'fail' + assert f is not None lyr.SetAttributeFilter( "int_field >= 2 OR long_field >= 9876543210 OR double_field <= 3.123456") @@ -2057,9 +1793,7 @@ def ogr_elasticsearch_10(): } }""") f = lyr.GetNextFeature() - if f is None: - gdaltest.post_reason('fail') - return 'fail' + assert f is not None lyr.SetAttributeFilter("dt_field > '2016/01/01 12:34:56.123'") gdal.FileFromMemBuffer("""/vsimem/fakeelasticsearch/a_layer/FeatureCollection/_search?scroll=1m&size=100&POSTFIELDS={ "query": { "constant_score" : { "filter": { "range": { "properties.dt_field": { "gt": "2016\/01\/01 12:34:56.123" } } } } } }""", @@ -2080,9 +1814,7 @@ def ogr_elasticsearch_10(): } }""") f = lyr.GetNextFeature() - if f is None: - gdaltest.post_reason('fail') - return 'fail' + assert f is not None lyr.SetAttributeFilter("NOT dt_field < '2016/01/01 12:34:56.123'") gdal.FileFromMemBuffer("""/vsimem/fakeelasticsearch/a_layer/FeatureCollection/_search?scroll=1m&size=100&POSTFIELDS={ "query": { "constant_score" : { "filter": { "bool": { "must_not": { "range": { "properties.dt_field": { "lt": "2016\/01\/01 12:34:56.123" } } } } } } } }""", @@ -2103,9 +1835,7 @@ def ogr_elasticsearch_10(): } }""") f = lyr.GetNextFeature() - if f is None: - gdaltest.post_reason('fail') - return 'fail' + assert f is not None lyr.SetAttributeFilter("keyword_field LIKE '_o%'") gdal.FileFromMemBuffer("""/vsimem/fakeelasticsearch/a_layer/FeatureCollection/_search?scroll=1m&size=100&POSTFIELDS={ "query": { "constant_score" : { "filter": { "wildcard": { "properties.keyword_field": "?o*" } } } } }""", @@ -2126,9 +1856,7 @@ def ogr_elasticsearch_10(): } }""") f = lyr.GetNextFeature() - if f is None: - gdaltest.post_reason('fail') - return 'fail' + assert f is not None # Evaluated client-side since the pattern uses ? or * lyr.SetAttributeFilter("text_field LIKE '?*'") @@ -2150,9 +1878,7 @@ def ogr_elasticsearch_10(): } }""") f = lyr.GetNextFeature() - if f is None: - gdaltest.post_reason('fail') - return 'fail' + assert f is not None # Evaluated client-side since the field is analyzed lyr.SetAttributeFilter("text_field LIKE '_Z%'") @@ -2174,9 +1900,7 @@ def ogr_elasticsearch_10(): } }""") f = lyr.GetNextFeature() - if f is None: - gdaltest.post_reason('fail') - return 'fail' + assert f is not None lyr.SetAttributeFilter("text_field_with_raw LIKE '_xo%' ESCAPE 'x'") gdal.FileFromMemBuffer("""/vsimem/fakeelasticsearch/a_layer/FeatureCollection/_search?scroll=1m&size=100&POSTFIELDS={ "query": { "constant_score" : { "filter": { "wildcard": { "properties.text_field_with_raw.raw": "?o*" } } } } }""", @@ -2197,9 +1921,7 @@ def ogr_elasticsearch_10(): } }""") f = lyr.GetNextFeature() - if f is None: - gdaltest.post_reason('fail') - return 'fail' + assert f is not None lyr.SetAttributeFilter("keyword_field = 'foo' AND 1 = 1") gdal.FileFromMemBuffer("""/vsimem/fakeelasticsearch/a_layer/FeatureCollection/_search?scroll=1m&size=100&POSTFIELDS={ "query": { "constant_score" : { "filter": { "term": { "properties.keyword_field": "foo" } } } } }""", @@ -2220,15 +1942,11 @@ def ogr_elasticsearch_10(): } }""") f = lyr.GetNextFeature() - if f is None: - gdaltest.post_reason('fail') - return 'fail' + assert f is not None lyr.SetAttributeFilter("1 = 1 AND keyword_field = 'foo'") f = lyr.GetNextFeature() - if f is None: - gdaltest.post_reason('fail') - return 'fail' + assert f is not None lyr.SetAttributeFilter("keyword_field = 'bar' OR 1 = 0") gdal.FileFromMemBuffer("""/vsimem/fakeelasticsearch/a_layer/FeatureCollection/_search?scroll=1m&size=100""", @@ -2249,9 +1967,7 @@ def ogr_elasticsearch_10(): } }""") f = lyr.GetNextFeature() - if f is None: - gdaltest.post_reason('fail') - return 'fail' + assert f is not None lyr.SetAttributeFilter("keyword_field = 'foo2'") lyr.SetSpatialFilterRect(2, 49, 2, 49) @@ -2277,17 +1993,13 @@ def ogr_elasticsearch_10(): } }""") f = lyr.GetNextFeature() - if f is None: - gdaltest.post_reason('fail') - return 'fail' + assert f is not None # SQL with WHERE sql_lyr = ds.ExecuteSQL( "SELECT * FROM a_layer WHERE keyword_field = 'foo'") f = sql_lyr.GetNextFeature() - if f is None: - gdaltest.post_reason('fail') - return 'fail' + assert f is not None ds.ReleaseResultSet(sql_lyr) # SQL with WHERE and ORDER BY @@ -2311,9 +2023,7 @@ def ogr_elasticsearch_10(): } }""") f = sql_lyr.GetNextFeature() - if f is None: - gdaltest.post_reason('fail') - return 'fail' + assert f is not None ds.ReleaseResultSet(sql_lyr) # SQL with ORDER BY only @@ -2336,9 +2046,7 @@ def ogr_elasticsearch_10(): } }""") f = sql_lyr.GetNextFeature() - if f is None: - gdaltest.post_reason('fail') - return 'fail' + assert f is not None ds.ReleaseResultSet(sql_lyr) # SQL with ORDER BY on a text field with a raw sub-field @@ -2361,20 +2069,16 @@ def ogr_elasticsearch_10(): } }""") f = sql_lyr.GetNextFeature() - if f is None: - gdaltest.post_reason('fail') - return 'fail' + assert f is not None ds.ReleaseResultSet(sql_lyr) - return 'success' - ############################################################################### # Test isnull and unset -def ogr_elasticsearch_11(): +def test_ogr_elasticsearch_11(): if ogrtest.elasticsearch_drv is None: - return 'skip' + pytest.skip() ogr_elasticsearch_delete_files() @@ -2457,21 +2161,18 @@ def ogr_elasticsearch_11(): f = lyr.GetNextFeature() if f['str_field'] != 'foo': - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' + pytest.fail() f = lyr.GetNextFeature() if f['str_field'] is not None: - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' + pytest.fail() f = lyr.GetNextFeature() if f.IsFieldSet('str_field'): - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' + pytest.fail() gdal.FileFromMemBuffer("""/vsimem/fakeelasticsearch/a_layer/FeatureCollection/_count?pretty""", """{ "hits": @@ -2491,30 +2192,22 @@ def ogr_elasticsearch_11(): f = ogr.Feature(lyr.GetLayerDefn()) f.SetFieldNull('str_field') ret = lyr.CreateFeature(f) - if ret != 0: - gdaltest.post_reason('fail') - return 'fail' + assert ret == 0 f = None f = ogr.Feature(lyr.GetLayerDefn()) ret = lyr.CreateFeature(f) - if ret != 0: - gdaltest.post_reason('fail') - return 'fail' + assert ret == 0 f = None - if lyr.SyncToDisk() != 0: - gdaltest.post_reason('fail') - return 'fail' - - return 'success' + assert lyr.SyncToDisk() == 0 ############################################################################### # Test authentication -def ogr_elasticsearch_authentication(): +def test_ogr_elasticsearch_authentication(): if ogrtest.elasticsearch_drv is None: - return 'skip' + pytest.skip() ogr_elasticsearch_delete_files() @@ -2550,11 +2243,7 @@ def ogr_elasticsearch_authentication(): ds = gdal.OpenEx('ES:/vsimem/fakeelasticsearch', open_options=['USERPWD=user:pwd']) - if ds is None: - gdaltest.post_reason('fail') - return 'fail' - - return 'success' + assert ds is not None ############################################################################### # Cleanup @@ -2584,41 +2273,10 @@ def ogr_elasticsearch_delete_files(): gdal.Unlink('/vsimem/fakeelasticsearch&USERPWD=user:pwd') -def ogr_elasticsearch_cleanup(): +def test_ogr_elasticsearch_cleanup(): if ogrtest.elasticsearch_drv is None: - return 'skip' + pytest.skip() ogr_elasticsearch_delete_files() gdal.SetConfigOption('CPL_CURL_ENABLE_VSIMEM', None) - - return 'success' - - -gdaltest_list = [ - ogr_elasticsearch_init, - ogr_elasticsearch_nonexistent_server, - ogr_elasticsearch_1, - ogr_elasticsearch_2, - ogr_elasticsearch_3, - ogr_elasticsearch_4, - ogr_elasticsearch_5, - ogr_elasticsearch_6, - ogr_elasticsearch_7, - ogr_elasticsearch_8, - ogr_elasticsearch_9, - ogr_elasticsearch_10, - ogr_elasticsearch_11, - ogr_elasticsearch_authentication, - ogr_elasticsearch_cleanup, -] - -# gdaltest_list = [ ogr_elasticsearch_init, ogr_elasticsearch_10 ] - -if __name__ == '__main__': - - gdaltest.setup_run('ogr_elasticsearch') - - gdaltest.run_tests(gdaltest_list) - - sys.exit(gdaltest.summarize()) diff --git a/autotest/ogr/ogr_factory.py b/autotest/ogr/ogr_factory.py index 31e23c084b90..b3b19ee4803b 100755 --- a/autotest/ogr/ogr_factory.py +++ b/autotest/ogr/ogr_factory.py @@ -30,14 +30,12 @@ # DEALINGS IN THE SOFTWARE. ############################################################################### -import sys -sys.path.append('../pymod') import ogrtest -import gdaltest from osgeo import gdal from osgeo import ogr +import pytest def save_as_csv(geom, filename): @@ -48,21 +46,19 @@ def save_as_csv(geom, filename): # 30 degree rotated ellipse, just one quarter. -def ogr_factory_1(): +def test_ogr_factory_1(): geom = ogr.ApproximateArcAngles(20, 30, 40, 7, 3.5, 30.0, 270.0, 360.0, 6.0) expected_geom = 'LINESTRING (21.75 33.031088913245533 40,22.374083449152831 32.648634669593925 40,22.972155943227843 32.237161430239802 40,23.537664874825239 31.801177382099848 40,24.064414409750082 31.345459257641004 40,24.546633369868303 30.875 40,24.979038463342047 30.394954059253475 40,25.356892169480634 29.910580919184319 40,25.676054644008637 29.427187473276717 40,25.933029076066084 28.95006988128063 40,26.125 28.484455543377237 40,26.249864142195264 28.035445827688662 40,26.306253464980482 27.607960178621322 40,26.293550155134998 27.206682218403525 40,26.211893392779814 26.836008432340218 40,26.062177826491073 26.5 40)' - if ogrtest.check_feature_geometry(geom, expected_geom): - return 'fail' - return 'success' + assert not ogrtest.check_feature_geometry(geom, expected_geom) ############################################################################### # Test forceToPolygon() -def ogr_factory_2(): +def test_ogr_factory_2(): src_wkt = 'MULTIPOLYGON (((0 0,100 0,100 100,0 0)))' exp_wkt = 'POLYGON((0 0,100 0,100 100,0 0))' @@ -70,9 +66,7 @@ def ogr_factory_2(): src_geom = ogr.CreateGeometryFromWkt(src_wkt) dst_geom = ogr.ForceToPolygon(src_geom) - if ogrtest.check_feature_geometry(dst_geom, exp_wkt): - print(dst_geom.ExportToWkt()) - return 'fail' + assert not ogrtest.check_feature_geometry(dst_geom, exp_wkt), dst_geom.ExportToWkt() src_wkt = 'MULTISURFACE (((0 0,100 0,100 100,0 0)))' exp_wkt = 'POLYGON((0 0,100 0,100 100,0 0))' @@ -80,9 +74,7 @@ def ogr_factory_2(): src_geom = ogr.CreateGeometryFromWkt(src_wkt) dst_geom = ogr.ForceToPolygon(src_geom) - if ogrtest.check_feature_geometry(dst_geom, exp_wkt): - print(dst_geom.ExportToWkt()) - return 'fail' + assert not ogrtest.check_feature_geometry(dst_geom, exp_wkt), dst_geom.ExportToWkt() src_wkt = 'CURVEPOLYGON ((0 0,100 0,100 100,0 0))' exp_wkt = 'POLYGON((0 0,100 0,100 100,0 0))' @@ -90,9 +82,7 @@ def ogr_factory_2(): src_geom = ogr.CreateGeometryFromWkt(src_wkt) dst_geom = ogr.ForceToPolygon(src_geom) - if ogrtest.check_feature_geometry(dst_geom, exp_wkt): - print(dst_geom.ExportToWkt()) - return 'fail' + assert not ogrtest.check_feature_geometry(dst_geom, exp_wkt), dst_geom.ExportToWkt() src_wkt = 'CURVEPOLYGON (CIRCULARSTRING(0 0,0 1,0 2,1 2,2 2,2 1,2 0,1 0,0 0))' exp_wkt = 'POLYGON ((0 0,0 1,0 2,1 2,2 2,2 1,2 0,1 0,0 0))' @@ -100,17 +90,13 @@ def ogr_factory_2(): src_geom = ogr.CreateGeometryFromWkt(src_wkt) dst_geom = ogr.ForceToPolygon(src_geom) - if ogrtest.check_feature_geometry(dst_geom, exp_wkt): - print(dst_geom.ExportToWkt()) - return 'fail' - - return 'success' + assert not ogrtest.check_feature_geometry(dst_geom, exp_wkt), dst_geom.ExportToWkt() ############################################################################### # Test forceToMultiPolygon() -def ogr_factory_3(): +def test_ogr_factory_3(): src_wkt = 'POLYGON((0 0,100 0,100 100,0 0))' exp_wkt = 'MULTIPOLYGON (((0 0,100 0,100 100,0 0)))' @@ -118,9 +104,7 @@ def ogr_factory_3(): src_geom = ogr.CreateGeometryFromWkt(src_wkt) dst_geom = ogr.ForceToMultiPolygon(src_geom) - if ogrtest.check_feature_geometry(dst_geom, exp_wkt): - print(dst_geom.ExportToWkt()) - return 'fail' + assert not ogrtest.check_feature_geometry(dst_geom, exp_wkt), dst_geom.ExportToWkt() src_wkt = 'GEOMETRYCOLLECTION(POLYGON((0 0,100 0,100 100,0 0)))' exp_wkt = 'MULTIPOLYGON (((0 0,100 0,100 100,0 0)))' @@ -128,9 +112,7 @@ def ogr_factory_3(): src_geom = ogr.CreateGeometryFromWkt(src_wkt) dst_geom = ogr.ForceToMultiPolygon(src_geom) - if ogrtest.check_feature_geometry(dst_geom, exp_wkt): - print(dst_geom.ExportToWkt()) - return 'fail' + assert not ogrtest.check_feature_geometry(dst_geom, exp_wkt), dst_geom.ExportToWkt() src_wkt = 'CURVEPOLYGON ((0 0,100 0,100 100,0 0))' exp_wkt = 'MULTIPOLYGON (((0 0,100 0,100 100,0 0)))' @@ -138,9 +120,7 @@ def ogr_factory_3(): src_geom = ogr.CreateGeometryFromWkt(src_wkt) dst_geom = ogr.ForceToMultiPolygon(src_geom) - if ogrtest.check_feature_geometry(dst_geom, exp_wkt): - print(dst_geom.ExportToWkt()) - return 'fail' + assert not ogrtest.check_feature_geometry(dst_geom, exp_wkt), dst_geom.ExportToWkt() src_wkt = 'MULTISURFACE (((0 0,100 0,100 100,0 0)))' exp_wkt = 'MULTIPOLYGON (((0 0,100 0,100 100,0 0)))' @@ -148,17 +128,13 @@ def ogr_factory_3(): src_geom = ogr.CreateGeometryFromWkt(src_wkt) dst_geom = ogr.ForceToMultiPolygon(src_geom) - if ogrtest.check_feature_geometry(dst_geom, exp_wkt): - print(dst_geom.ExportToWkt()) - return 'fail' - - return 'success' + assert not ogrtest.check_feature_geometry(dst_geom, exp_wkt), dst_geom.ExportToWkt() ############################################################################### # Test forceToMultiPoint() -def ogr_factory_4(): +def test_ogr_factory_4(): src_wkt = 'POINT(2 5 3)' exp_wkt = 'MULTIPOINT(2 5 3)' @@ -166,9 +142,7 @@ def ogr_factory_4(): src_geom = ogr.CreateGeometryFromWkt(src_wkt) dst_geom = ogr.ForceToMultiPoint(src_geom) - if ogrtest.check_feature_geometry(dst_geom, exp_wkt): - print(dst_geom.ExportToWkt()) - return 'fail' + assert not ogrtest.check_feature_geometry(dst_geom, exp_wkt), dst_geom.ExportToWkt() src_wkt = 'GEOMETRYCOLLECTION(POINT(2 5 3),POINT(4 5 5))' exp_wkt = 'MULTIPOINT(2 5 3,4 5 5)' @@ -176,17 +150,13 @@ def ogr_factory_4(): src_geom = ogr.CreateGeometryFromWkt(src_wkt) dst_geom = ogr.ForceToMultiPoint(src_geom) - if ogrtest.check_feature_geometry(dst_geom, exp_wkt): - print(dst_geom.ExportToWkt()) - return 'fail' - - return 'success' + assert not ogrtest.check_feature_geometry(dst_geom, exp_wkt), dst_geom.ExportToWkt() ############################################################################### # Test forceToMultiLineString() -def ogr_factory_5(): +def test_ogr_factory_5(): src_wkt = 'LINESTRING(2 5,10 20)' exp_wkt = 'MULTILINESTRING((2 5,10 20))' @@ -194,9 +164,7 @@ def ogr_factory_5(): src_geom = ogr.CreateGeometryFromWkt(src_wkt) dst_geom = ogr.ForceToMultiLineString(src_geom) - if ogrtest.check_feature_geometry(dst_geom, exp_wkt): - print(dst_geom.ExportToWkt()) - return 'fail' + assert not ogrtest.check_feature_geometry(dst_geom, exp_wkt), dst_geom.ExportToWkt() src_wkt = 'GEOMETRYCOLLECTION(LINESTRING(2 5,10 20),LINESTRING(0 0,10 10))' exp_wkt = 'MULTILINESTRING((2 5,10 20),(0 0,10 10))' @@ -204,9 +172,7 @@ def ogr_factory_5(): src_geom = ogr.CreateGeometryFromWkt(src_wkt) dst_geom = ogr.ForceToMultiLineString(src_geom) - if ogrtest.check_feature_geometry(dst_geom, exp_wkt): - print(dst_geom.ExportToWkt()) - return 'fail' + assert not ogrtest.check_feature_geometry(dst_geom, exp_wkt), dst_geom.ExportToWkt() src_wkt = 'POLYGON((2 5,10 20),(0 0,10 10))' exp_wkt = 'MULTILINESTRING((2 5,10 20),(0 0,10 10))' @@ -214,9 +180,7 @@ def ogr_factory_5(): src_geom = ogr.CreateGeometryFromWkt(src_wkt) dst_geom = ogr.ForceToMultiLineString(src_geom) - if ogrtest.check_feature_geometry(dst_geom, exp_wkt): - print(dst_geom.ExportToWkt()) - return 'fail' + assert not ogrtest.check_feature_geometry(dst_geom, exp_wkt), dst_geom.ExportToWkt() src_wkt = 'MULTIPOLYGON(((2 5,10 20),(0 0,10 10)),((2 5,10 20)))' exp_wkt = 'MULTILINESTRING((2 5,10 20),(0 0,10 10),(2 5,10 20))' @@ -224,16 +188,13 @@ def ogr_factory_5(): src_geom = ogr.CreateGeometryFromWkt(src_wkt) dst_geom = ogr.ForceToMultiLineString(src_geom) - if ogrtest.check_feature_geometry(dst_geom, exp_wkt): - print(dst_geom.ExportToWkt()) - return 'fail' - return 'success' + assert not ogrtest.check_feature_geometry(dst_geom, exp_wkt), dst_geom.ExportToWkt() ############################################################################### # Test robustness of forceToXXX() primitives with various inputs (#3504) -def ogr_factory_6(): +def test_ogr_factory_6(): src_wkt_list = [None, 'POINT EMPTY', @@ -294,13 +255,12 @@ def ogr_factory_6(): gdal.PopErrorHandler() # print(src_geom.ExportToWkt(), dst_geom1.ExportToWkt(), dst_geom2.ExportToWkt(), dst_geom3.ExportToWkt(), dst_geom4.ExportToWkt()) - return 'success' - + ############################################################################### # Test forceToLineString() -def ogr_factory_7(): +def test_ogr_factory_7(): src_wkt = 'LINESTRING(2 5,10 20)' exp_wkt = 'LINESTRING(2 5,10 20)' @@ -308,9 +268,7 @@ def ogr_factory_7(): src_geom = ogr.CreateGeometryFromWkt(src_wkt) dst_geom = ogr.ForceToLineString(src_geom) - if ogrtest.check_feature_geometry(dst_geom, exp_wkt): - print(dst_geom.ExportToWkt()) - return 'fail' + assert not ogrtest.check_feature_geometry(dst_geom, exp_wkt), dst_geom.ExportToWkt() src_wkt = 'MULTILINESTRING((2 5,10 20))' exp_wkt = 'LINESTRING(2 5,10 20)' @@ -318,9 +276,7 @@ def ogr_factory_7(): src_geom = ogr.CreateGeometryFromWkt(src_wkt) dst_geom = ogr.ForceToLineString(src_geom) - if ogrtest.check_feature_geometry(dst_geom, exp_wkt): - print(dst_geom.ExportToWkt()) - return 'fail' + assert not ogrtest.check_feature_geometry(dst_geom, exp_wkt), dst_geom.ExportToWkt() src_wkt = 'MULTICURVE((2 5,10 20))' exp_wkt = 'LINESTRING(2 5,10 20)' @@ -328,9 +284,7 @@ def ogr_factory_7(): src_geom = ogr.CreateGeometryFromWkt(src_wkt) dst_geom = ogr.ForceToLineString(src_geom) - if ogrtest.check_feature_geometry(dst_geom, exp_wkt): - print(dst_geom.ExportToWkt()) - return 'fail' + assert not ogrtest.check_feature_geometry(dst_geom, exp_wkt), dst_geom.ExportToWkt() src_wkt = 'MULTICURVE(COMPOUNDCURVE((2 5,10 20)))' exp_wkt = 'LINESTRING(2 5,10 20)' @@ -338,9 +292,7 @@ def ogr_factory_7(): src_geom = ogr.CreateGeometryFromWkt(src_wkt) dst_geom = ogr.ForceToLineString(src_geom) - if ogrtest.check_feature_geometry(dst_geom, exp_wkt): - print(dst_geom.ExportToWkt()) - return 'fail' + assert not ogrtest.check_feature_geometry(dst_geom, exp_wkt), dst_geom.ExportToWkt() src_wkt = 'MULTILINESTRING((2 5,10 20),(3 4,30 40))' exp_wkt = 'MULTILINESTRING((2 5,10 20),(3 4,30 40))' @@ -348,9 +300,7 @@ def ogr_factory_7(): src_geom = ogr.CreateGeometryFromWkt(src_wkt) dst_geom = ogr.ForceToLineString(src_geom) - if ogrtest.check_feature_geometry(dst_geom, exp_wkt): - print(dst_geom.ExportToWkt()) - return 'fail' + assert not ogrtest.check_feature_geometry(dst_geom, exp_wkt), dst_geom.ExportToWkt() src_wkt = 'MULTILINESTRING((2 5,10 20),(10 20,30 40))' exp_wkt = 'LINESTRING (2 5,10 20,30 40)' @@ -358,9 +308,7 @@ def ogr_factory_7(): src_geom = ogr.CreateGeometryFromWkt(src_wkt) dst_geom = ogr.ForceToLineString(src_geom) - if ogrtest.check_feature_geometry(dst_geom, exp_wkt): - print(dst_geom.ExportToWkt()) - return 'fail' + assert not ogrtest.check_feature_geometry(dst_geom, exp_wkt), dst_geom.ExportToWkt() src_wkt = 'GEOMETRYCOLLECTION(LINESTRING(2 5,10 20),LINESTRING(10 20,30 40))' exp_wkt = 'LINESTRING (2 5,10 20,30 40)' @@ -368,9 +316,7 @@ def ogr_factory_7(): src_geom = ogr.CreateGeometryFromWkt(src_wkt) dst_geom = ogr.ForceToLineString(src_geom) - if ogrtest.check_feature_geometry(dst_geom, exp_wkt): - print(dst_geom.ExportToWkt()) - return 'fail' + assert not ogrtest.check_feature_geometry(dst_geom, exp_wkt), dst_geom.ExportToWkt() src_wkt = 'MULTILINESTRING((2 5,10 20),(10 20))' exp_wkt = 'MULTILINESTRING((2 5,10 20),(10 20))' @@ -378,9 +324,7 @@ def ogr_factory_7(): src_geom = ogr.CreateGeometryFromWkt(src_wkt) dst_geom = ogr.ForceToLineString(src_geom) - if ogrtest.check_feature_geometry(dst_geom, exp_wkt): - print(dst_geom.ExportToWkt()) - return 'fail' + assert not ogrtest.check_feature_geometry(dst_geom, exp_wkt), dst_geom.ExportToWkt() src_wkt = 'MULTILINESTRING((2 5,10 20),(10 20,30 40),(30 40,50 60))' exp_wkt = 'LINESTRING (2 5,10 20,30 40,50 60)' @@ -388,9 +332,7 @@ def ogr_factory_7(): src_geom = ogr.CreateGeometryFromWkt(src_wkt) dst_geom = ogr.ForceToLineString(src_geom) - if ogrtest.check_feature_geometry(dst_geom, exp_wkt): - print(dst_geom.ExportToWkt()) - return 'fail' + assert not ogrtest.check_feature_geometry(dst_geom, exp_wkt), dst_geom.ExportToWkt() src_wkt = 'POLYGON ((0 0,0 1,1 1,1 0,0 0))' exp_wkt = 'LINESTRING (0 0,0 1,1 1,1 0,0 0)' @@ -398,9 +340,7 @@ def ogr_factory_7(): src_geom = ogr.CreateGeometryFromWkt(src_wkt) dst_geom = ogr.ForceToLineString(src_geom) - if ogrtest.check_feature_geometry(dst_geom, exp_wkt): - print(dst_geom.ExportToWkt()) - return 'fail' + assert not ogrtest.check_feature_geometry(dst_geom, exp_wkt), dst_geom.ExportToWkt() src_wkt = 'CURVEPOLYGON ((0 0,0 1,1 1,1 0,0 0))' exp_wkt = 'LINESTRING (0 0,0 1,1 1,1 0,0 0)' @@ -408,9 +348,7 @@ def ogr_factory_7(): src_geom = ogr.CreateGeometryFromWkt(src_wkt) dst_geom = ogr.ForceToLineString(src_geom) - if ogrtest.check_feature_geometry(dst_geom, exp_wkt): - print(dst_geom.ExportToWkt()) - return 'fail' + assert not ogrtest.check_feature_geometry(dst_geom, exp_wkt), dst_geom.ExportToWkt() src_wkt = 'CURVEPOLYGON (COMPOUNDCURVE((0 0,0 1,1 1,1 0,0 0)))' exp_wkt = 'LINESTRING (0 0,0 1,1 1,1 0,0 0)' @@ -418,17 +356,13 @@ def ogr_factory_7(): src_geom = ogr.CreateGeometryFromWkt(src_wkt) dst_geom = ogr.ForceToLineString(src_geom) - if ogrtest.check_feature_geometry(dst_geom, exp_wkt): - print(dst_geom.ExportToWkt()) - return 'fail' - - return 'success' + assert not ogrtest.check_feature_geometry(dst_geom, exp_wkt), dst_geom.ExportToWkt() ############################################################################### # Test forceTo() -def ogr_factory_8(): +def test_ogr_factory_8(): tests = [('POINT(2 5)', 'MULTIPOINT (2 5)', ogr.wkbMultiPoint), @@ -585,37 +519,15 @@ def ogr_factory_8(): if exp_wkt is None: exp_wkt = src_wkt elif target_type != ogr.wkbUnknown and dst_geom.GetGeometryType() != target_type: - gdaltest.post_reason('fail') - print(src_wkt) print(target_type) print(dst_geom.ExportToWkt()) - return 'fail' + pytest.fail(src_wkt) if ogrtest.check_feature_geometry(dst_geom, exp_wkt): - gdaltest.post_reason('fail') print(src_wkt) print(target_type) - print(dst_geom.ExportToWkt()) - return 'fail' - - return 'success' - - -gdaltest_list = [ - ogr_factory_1, - ogr_factory_2, - ogr_factory_3, - ogr_factory_4, - ogr_factory_5, - ogr_factory_6, - ogr_factory_7, - ogr_factory_8, -] - -if __name__ == '__main__': + pytest.fail(dst_geom.ExportToWkt()) - gdaltest.setup_run('ogr_factory') + - gdaltest.run_tests(gdaltest_list) - sys.exit(gdaltest.summarize()) diff --git a/autotest/ogr/ogr_feature.py b/autotest/ogr/ogr_feature.py index 5552e8f659be..27d4a5c5308d 100755 --- a/autotest/ogr/ogr_feature.py +++ b/autotest/ogr/ogr_feature.py @@ -31,11 +31,11 @@ import sys -sys.path.append('../pymod') from osgeo import gdal from osgeo import ogr import gdaltest +import pytest ############################################################################### # Create a destination feature type with one field for each field in the source @@ -111,7 +111,6 @@ def mk_src_feature(): expected_vals = [2011, 11, 11, 14, 10, 35.123, 0] for i, exp_val in enumerate(expected_vals): if abs(got_vals[i] - exp_val) > 1e-4: - gdaltest.post_reason('fail') print(got_vals) print(expected_vals) src_feature.field_integerlist = '(3:10,20,30)' @@ -139,7 +138,7 @@ def check(feat, fieldname, value): # Copy to Integer -def ogr_feature_cp_integer(): +def test_ogr_feature_cp_integer(): src_feature = mk_src_feature() src_feature.field_integerlist = [15] src_feature.field_reallist = [17.5] @@ -149,58 +148,41 @@ def ogr_feature_cp_integer(): dst_feature.SetFrom(src_feature) gdal.PopErrorHandler() - if not check(dst_feature, 'field_integer', 17): - return 'fail' + assert check(dst_feature, 'field_integer', 17) - if not check(dst_feature, 'field_integer64', 2147483647): - return 'fail' + assert check(dst_feature, 'field_integer64', 2147483647) - if not check(dst_feature, 'field_real', 18): - return 'fail' + assert check(dst_feature, 'field_real', 18) - if not check(dst_feature, 'field_string', 0): - return 'fail' + assert check(dst_feature, 'field_string', 0) - if not check(dst_feature, 'field_binary', None): - return 'fail' + assert check(dst_feature, 'field_binary', None) - if not check(dst_feature, 'field_date', None): - return 'fail' + assert check(dst_feature, 'field_date', None) - if not check(dst_feature, 'field_time', None): - return 'fail' + assert check(dst_feature, 'field_time', None) - if not check(dst_feature, 'field_datetime', None): - return 'fail' + assert check(dst_feature, 'field_datetime', None) - if not check(dst_feature, 'field_integerlist', 15): - return 'fail' + assert check(dst_feature, 'field_integerlist', 15) - if not check(dst_feature, 'field_integer64list', 2147483647): - return 'fail' + assert check(dst_feature, 'field_integer64list', 2147483647) - if not check(dst_feature, 'field_reallist', 17): - return 'fail' + assert check(dst_feature, 'field_reallist', 17) - if not check(dst_feature, 'field_stringlist', None): - return 'fail' + assert check(dst_feature, 'field_stringlist', None) vals = [] for val in dst_feature: vals.append(val) - if vals != [17, 2147483647, 18, 0, None, None, None, None, 15, - 2147483647, 17, None]: - gdaltest.post_reason('fail') - print(vals) - return 'fail' - - return 'success' + assert (vals == [17, 2147483647, 18, 0, None, None, None, None, 15, + 2147483647, 17, None]) ############################################################################### # Copy to Integer64 -def ogr_feature_cp_integer64(): +def test_ogr_feature_cp_integer64(): src_feature = mk_src_feature() src_feature.field_integerlist = [15] src_feature.field_reallist = [17.5] @@ -208,56 +190,40 @@ def ogr_feature_cp_integer64(): dst_feature = mk_dst_feature(src_feature, ogr.OFTInteger64) dst_feature.SetFrom(src_feature) - if not check(dst_feature, 'field_integer', 17): - return 'fail' + assert check(dst_feature, 'field_integer', 17) - if not check(dst_feature, 'field_integer64', 9876543210): - return 'fail' + assert check(dst_feature, 'field_integer64', 9876543210) gdal.PushErrorHandler() int32_ovflw = dst_feature.GetFieldAsInteger('field_integer64') gdal.PopErrorHandler() - if int32_ovflw != 2147483647: - gdaltest.post_reason('fail') - return 'fail' - - if not check(dst_feature, 'field_real', 18): - return 'fail' + assert int32_ovflw == 2147483647 - if not check(dst_feature, 'field_string', 0): - return 'fail' + assert check(dst_feature, 'field_real', 18) - if not check(dst_feature, 'field_binary', None): - return 'fail' + assert check(dst_feature, 'field_string', 0) - if not check(dst_feature, 'field_date', None): - return 'fail' + assert check(dst_feature, 'field_binary', None) - if not check(dst_feature, 'field_time', None): - return 'fail' + assert check(dst_feature, 'field_date', None) - if not check(dst_feature, 'field_datetime', None): - return 'fail' + assert check(dst_feature, 'field_time', None) - if not check(dst_feature, 'field_integerlist', 15): - return 'fail' + assert check(dst_feature, 'field_datetime', None) - if not check(dst_feature, 'field_integer64list', 9876543210): - return 'fail' + assert check(dst_feature, 'field_integerlist', 15) - if not check(dst_feature, 'field_reallist', 17): - return 'fail' + assert check(dst_feature, 'field_integer64list', 9876543210) - if not check(dst_feature, 'field_stringlist', None): - return 'fail' + assert check(dst_feature, 'field_reallist', 17) - return 'success' + assert check(dst_feature, 'field_stringlist', None) ############################################################################### # Copy to Real -def ogr_feature_cp_real(): +def test_ogr_feature_cp_real(): src_feature = mk_src_feature() src_feature.field_integerlist = [15] src_feature.field_reallist = [17.5] @@ -266,291 +232,207 @@ def ogr_feature_cp_real(): with gdaltest.error_handler(): dst_feature.SetFrom(src_feature) - if not check(dst_feature, 'field_integer', 17.0): - return 'fail' - - if not check(dst_feature, 'field_real', 18.4): - return 'fail' + assert check(dst_feature, 'field_integer', 17.0) - if not check(dst_feature, 'field_string', 0): - return 'fail' + assert check(dst_feature, 'field_real', 18.4) - if not check(dst_feature, 'field_binary', None): - return 'fail' + assert check(dst_feature, 'field_string', 0) - if not check(dst_feature, 'field_date', None): - return 'fail' + assert check(dst_feature, 'field_binary', None) - if not check(dst_feature, 'field_time', None): - return 'fail' + assert check(dst_feature, 'field_date', None) - if not check(dst_feature, 'field_datetime', None): - return 'fail' + assert check(dst_feature, 'field_time', None) - if not check(dst_feature, 'field_integerlist', 15.0): - return 'fail' + assert check(dst_feature, 'field_datetime', None) - if not check(dst_feature, 'field_reallist', 17.5): - return 'fail' + assert check(dst_feature, 'field_integerlist', 15.0) - if not check(dst_feature, 'field_stringlist', None): - return 'fail' + assert check(dst_feature, 'field_reallist', 17.5) - return 'success' + assert check(dst_feature, 'field_stringlist', None) ############################################################################### # Copy to String -def ogr_feature_cp_string(): +def test_ogr_feature_cp_string(): src_feature = mk_src_feature() dst_feature = mk_dst_feature(src_feature, ogr.OFTString) dst_feature.SetFrom(src_feature) - if not check(dst_feature, 'field_integer', '17'): - return 'fail' + assert check(dst_feature, 'field_integer', '17') - if not check(dst_feature, 'field_integer64', '9876543210'): - return 'fail' + assert check(dst_feature, 'field_integer64', '9876543210') - if not check(dst_feature, 'field_real', '18.4'): - return 'fail' + assert check(dst_feature, 'field_real', '18.4') - if not check(dst_feature, 'field_string', 'abc def'): - return 'fail' + assert check(dst_feature, 'field_string', 'abc def') - if not check(dst_feature, 'field_binary', '0123465789ABCDEF'): - return 'fail' + assert check(dst_feature, 'field_binary', '0123465789ABCDEF') - if not check(dst_feature, 'field_date', '2011/11/11'): - return 'fail' + assert check(dst_feature, 'field_date', '2011/11/11') - if not check(dst_feature, 'field_time', '14:10:35'): - return 'fail' + assert check(dst_feature, 'field_time', '14:10:35') - if not check(dst_feature, 'field_datetime', '2011/11/11 14:10:35.123'): - return 'fail' + assert check(dst_feature, 'field_datetime', '2011/11/11 14:10:35.123') - if not check(dst_feature, 'field_integerlist', '(3:10,20,30)'): - return 'fail' + assert check(dst_feature, 'field_integerlist', '(3:10,20,30)') - if not check(dst_feature, 'field_integer64list', '(1:9876543210)'): - return 'fail' + assert check(dst_feature, 'field_integer64list', '(1:9876543210)') - if not check(dst_feature, 'field_reallist', '(2:123.5,567)'): - return 'fail' + assert check(dst_feature, 'field_reallist', '(2:123.5,567)') - if not check(dst_feature, 'field_stringlist', '(2:abc,def)'): - return 'fail' - - return 'success' + assert check(dst_feature, 'field_stringlist', '(2:abc,def)') ############################################################################### # Copy to Binary -def ogr_feature_cp_binary(): +def test_ogr_feature_cp_binary(): src_feature = mk_src_feature() dst_feature = mk_dst_feature(src_feature, ogr.OFTBinary) dst_feature.SetFrom(src_feature) - if not check(dst_feature, 'field_integer', None): - return 'fail' + assert check(dst_feature, 'field_integer', None) - if not check(dst_feature, 'field_integer64', None): - return 'fail' + assert check(dst_feature, 'field_integer64', None) - if not check(dst_feature, 'field_real', None): - return 'fail' + assert check(dst_feature, 'field_real', None) - if not check(dst_feature, 'field_string', None): - return 'fail' + assert check(dst_feature, 'field_string', None) - if not check(dst_feature, 'field_binary', '0123465789ABCDEF'): - return 'fail' + assert check(dst_feature, 'field_binary', '0123465789ABCDEF') expected = '\x01\x23\x46\x57\x89\xAB\xCD\xEF' if sys.version_info >= (3, 0, 0): expected = expected.encode('LATIN1') - if dst_feature.GetFieldAsBinary('field_binary') != expected: - return 'fail' - if dst_feature.GetFieldAsBinary(dst_feature.GetDefnRef().GetFieldIndex('field_binary')) != expected: - return 'fail' - - if not check(dst_feature, 'field_date', None): - return 'fail' + assert dst_feature.GetFieldAsBinary('field_binary') == expected + assert dst_feature.GetFieldAsBinary(dst_feature.GetDefnRef().GetFieldIndex('field_binary')) == expected - if not check(dst_feature, 'field_time', None): - return 'fail' + assert check(dst_feature, 'field_date', None) - if not check(dst_feature, 'field_datetime', None): - return 'fail' + assert check(dst_feature, 'field_time', None) - if not check(dst_feature, 'field_integerlist', None): - return 'fail' + assert check(dst_feature, 'field_datetime', None) - if not check(dst_feature, 'field_integer64list', None): - return 'fail' + assert check(dst_feature, 'field_integerlist', None) - if not check(dst_feature, 'field_reallist', None): - return 'fail' + assert check(dst_feature, 'field_integer64list', None) - if not check(dst_feature, 'field_stringlist', None): - return 'fail' + assert check(dst_feature, 'field_reallist', None) - return 'success' + assert check(dst_feature, 'field_stringlist', None) ############################################################################### # Copy to date -def ogr_feature_cp_date(): +def test_ogr_feature_cp_date(): src_feature = mk_src_feature() dst_feature = mk_dst_feature(src_feature, ogr.OFTDate) dst_feature.SetFrom(src_feature) - if not check(dst_feature, 'field_integer', None): - return 'fail' - - if not check(dst_feature, 'field_integer64', None): - return 'fail' + assert check(dst_feature, 'field_integer', None) - if not check(dst_feature, 'field_real', None): - return 'fail' + assert check(dst_feature, 'field_integer64', None) - if not check(dst_feature, 'field_string', None): - return 'fail' + assert check(dst_feature, 'field_real', None) - if not check(dst_feature, 'field_binary', None): - return 'fail' + assert check(dst_feature, 'field_string', None) - if not check(dst_feature, 'field_date', '2011/11/11'): - return 'fail' + assert check(dst_feature, 'field_binary', None) - if not check(dst_feature, 'field_time', '0000/00/00'): - return 'fail' + assert check(dst_feature, 'field_date', '2011/11/11') - if not check(dst_feature, 'field_datetime', '2011/11/11'): - return 'fail' + assert check(dst_feature, 'field_time', '0000/00/00') - if not check(dst_feature, 'field_integerlist', None): - return 'fail' + assert check(dst_feature, 'field_datetime', '2011/11/11') - if not check(dst_feature, 'field_integer64list', None): - return 'fail' + assert check(dst_feature, 'field_integerlist', None) - if not check(dst_feature, 'field_reallist', None): - return 'fail' + assert check(dst_feature, 'field_integer64list', None) - if not check(dst_feature, 'field_stringlist', None): - return 'fail' + assert check(dst_feature, 'field_reallist', None) - return 'success' + assert check(dst_feature, 'field_stringlist', None) ############################################################################### # Copy to time -def ogr_feature_cp_time(): +def test_ogr_feature_cp_time(): src_feature = mk_src_feature() dst_feature = mk_dst_feature(src_feature, ogr.OFTTime) dst_feature.SetFrom(src_feature) - if not check(dst_feature, 'field_integer', None): - return 'fail' + assert check(dst_feature, 'field_integer', None) - if not check(dst_feature, 'field_integer64', None): - return 'fail' + assert check(dst_feature, 'field_integer64', None) - if not check(dst_feature, 'field_real', None): - return 'fail' + assert check(dst_feature, 'field_real', None) - if not check(dst_feature, 'field_string', None): - return 'fail' + assert check(dst_feature, 'field_string', None) - if not check(dst_feature, 'field_binary', None): - return 'fail' + assert check(dst_feature, 'field_binary', None) - if not check(dst_feature, 'field_date', '00:00:00'): - return 'fail' + assert check(dst_feature, 'field_date', '00:00:00') - if not check(dst_feature, 'field_time', '14:10:35'): - return 'fail' + assert check(dst_feature, 'field_time', '14:10:35') - if not check(dst_feature, 'field_datetime', '14:10:35.123'): - return 'fail' + assert check(dst_feature, 'field_datetime', '14:10:35.123') - if not check(dst_feature, 'field_integerlist', None): - return 'fail' + assert check(dst_feature, 'field_integerlist', None) - if not check(dst_feature, 'field_integer64list', None): - return 'fail' + assert check(dst_feature, 'field_integer64list', None) - if not check(dst_feature, 'field_reallist', None): - return 'fail' + assert check(dst_feature, 'field_reallist', None) - if not check(dst_feature, 'field_stringlist', None): - return 'fail' - - return 'success' + assert check(dst_feature, 'field_stringlist', None) ############################################################################### # Copy to datetime -def ogr_feature_cp_datetime(): +def test_ogr_feature_cp_datetime(): src_feature = mk_src_feature() dst_feature = mk_dst_feature(src_feature, ogr.OFTDateTime) dst_feature.SetFrom(src_feature) - if not check(dst_feature, 'field_integer', None): - return 'fail' - - if not check(dst_feature, 'field_integer64', None): - return 'fail' + assert check(dst_feature, 'field_integer', None) - if not check(dst_feature, 'field_real', None): - return 'fail' + assert check(dst_feature, 'field_integer64', None) - if not check(dst_feature, 'field_string', None): - return 'fail' + assert check(dst_feature, 'field_real', None) - if not check(dst_feature, 'field_binary', None): - return 'fail' + assert check(dst_feature, 'field_string', None) - if not check(dst_feature, 'field_date', '2011/11/11 00:00:00'): - return 'fail' + assert check(dst_feature, 'field_binary', None) - if not check(dst_feature, 'field_time', '0000/00/00 14:10:35'): - return 'fail' + assert check(dst_feature, 'field_date', '2011/11/11 00:00:00') - if not check(dst_feature, 'field_datetime', '2011/11/11 14:10:35.123'): - return 'fail' + assert check(dst_feature, 'field_time', '0000/00/00 14:10:35') - if not check(dst_feature, 'field_integerlist', None): - return 'fail' + assert check(dst_feature, 'field_datetime', '2011/11/11 14:10:35.123') - if not check(dst_feature, 'field_integer64list', None): - return 'fail' + assert check(dst_feature, 'field_integerlist', None) - if not check(dst_feature, 'field_reallist', None): - return 'fail' + assert check(dst_feature, 'field_integer64list', None) - if not check(dst_feature, 'field_stringlist', None): - return 'fail' + assert check(dst_feature, 'field_reallist', None) - return 'success' + assert check(dst_feature, 'field_stringlist', None) ############################################################################### # Copy to integerlist -def ogr_feature_cp_integerlist(): +def test_ogr_feature_cp_integerlist(): src_feature = mk_src_feature() dst_feature = mk_dst_feature(src_feature, ogr.OFTIntegerList) @@ -558,195 +440,139 @@ def ogr_feature_cp_integerlist(): dst_feature.SetFrom(src_feature) gdal.PopErrorHandler() - if not check(dst_feature, 'field_integer', [17]): - return 'fail' - - if not check(dst_feature, 'field_integer64', [2147483647]): - return 'fail' + assert check(dst_feature, 'field_integer', [17]) - if not check(dst_feature, 'field_real', [18]): - return 'fail' + assert check(dst_feature, 'field_integer64', [2147483647]) - if not check(dst_feature, 'field_string', None): - return 'fail' + assert check(dst_feature, 'field_real', [18]) - if not check(dst_feature, 'field_binary', None): - return 'fail' + assert check(dst_feature, 'field_string', None) - if not check(dst_feature, 'field_date', None): - return 'fail' + assert check(dst_feature, 'field_binary', None) - if not check(dst_feature, 'field_time', None): - return 'fail' + assert check(dst_feature, 'field_date', None) - if not check(dst_feature, 'field_datetime', None): - return 'fail' + assert check(dst_feature, 'field_time', None) - if not check(dst_feature, 'field_integerlist', [10, 20, 30]): - return 'fail' + assert check(dst_feature, 'field_datetime', None) - if not check(dst_feature, 'field_integer64list', [2147483647]): - return 'fail' + assert check(dst_feature, 'field_integerlist', [10, 20, 30]) - if not check(dst_feature, 'field_reallist', [123, 567]): - return 'fail' + assert check(dst_feature, 'field_integer64list', [2147483647]) - if not check(dst_feature, 'field_stringlist', None): - return 'fail' + assert check(dst_feature, 'field_reallist', [123, 567]) - return 'success' + assert check(dst_feature, 'field_stringlist', None) ############################################################################### # Copy to integer64list -def ogr_feature_cp_integer64list(): +def test_ogr_feature_cp_integer64list(): src_feature = mk_src_feature() dst_feature = mk_dst_feature(src_feature, ogr.OFTInteger64List) dst_feature.SetFrom(src_feature) - if not check(dst_feature, 'field_integer', [17]): - return 'fail' + assert check(dst_feature, 'field_integer', [17]) - if not check(dst_feature, 'field_integer64', [9876543210]): - return 'fail' + assert check(dst_feature, 'field_integer64', [9876543210]) - if not check(dst_feature, 'field_real', [18]): - return 'fail' + assert check(dst_feature, 'field_real', [18]) - if not check(dst_feature, 'field_string', None): - return 'fail' + assert check(dst_feature, 'field_string', None) - if not check(dst_feature, 'field_binary', None): - return 'fail' + assert check(dst_feature, 'field_binary', None) - if not check(dst_feature, 'field_date', None): - return 'fail' + assert check(dst_feature, 'field_date', None) - if not check(dst_feature, 'field_time', None): - return 'fail' + assert check(dst_feature, 'field_time', None) - if not check(dst_feature, 'field_datetime', None): - return 'fail' + assert check(dst_feature, 'field_datetime', None) - if not check(dst_feature, 'field_integerlist', [10, 20, 30]): - return 'fail' + assert check(dst_feature, 'field_integerlist', [10, 20, 30]) - if not check(dst_feature, 'field_integer64list', [9876543210]): - return 'fail' + assert check(dst_feature, 'field_integer64list', [9876543210]) - if not check(dst_feature, 'field_reallist', [123, 567]): - return 'fail' + assert check(dst_feature, 'field_reallist', [123, 567]) - if not check(dst_feature, 'field_stringlist', None): - return 'fail' - - return 'success' + assert check(dst_feature, 'field_stringlist', None) ############################################################################### # Copy to reallist -def ogr_feature_cp_reallist(): +def test_ogr_feature_cp_reallist(): src_feature = mk_src_feature() dst_feature = mk_dst_feature(src_feature, ogr.OFTRealList) dst_feature.SetFrom(src_feature) - if not check(dst_feature, 'field_integer', [17.0]): - return 'fail' - - if not check(dst_feature, 'field_integer64', [9876543210.0]): - return 'fail' + assert check(dst_feature, 'field_integer', [17.0]) - if not check(dst_feature, 'field_real', [18.4]): - return 'fail' + assert check(dst_feature, 'field_integer64', [9876543210.0]) - if not check(dst_feature, 'field_string', None): - return 'fail' + assert check(dst_feature, 'field_real', [18.4]) - if not check(dst_feature, 'field_binary', None): - return 'fail' + assert check(dst_feature, 'field_string', None) - if not check(dst_feature, 'field_date', None): - return 'fail' + assert check(dst_feature, 'field_binary', None) - if not check(dst_feature, 'field_time', None): - return 'fail' + assert check(dst_feature, 'field_date', None) - if not check(dst_feature, 'field_datetime', None): - return 'fail' + assert check(dst_feature, 'field_time', None) - if not check(dst_feature, 'field_integerlist', [10.0, 20.0, 30.0]): - return 'fail' + assert check(dst_feature, 'field_datetime', None) - if not check(dst_feature, 'field_integer64list', [9876543210.0]): - return 'fail' + assert check(dst_feature, 'field_integerlist', [10.0, 20.0, 30.0]) - if not check(dst_feature, 'field_reallist', [123.5, 567.0]): - return 'fail' + assert check(dst_feature, 'field_integer64list', [9876543210.0]) - if not check(dst_feature, 'field_stringlist', None): - return 'fail' + assert check(dst_feature, 'field_reallist', [123.5, 567.0]) - return 'success' + assert check(dst_feature, 'field_stringlist', None) ############################################################################### # Copy to stringlist -def ogr_feature_cp_stringlist(): +def test_ogr_feature_cp_stringlist(): src_feature = mk_src_feature() dst_feature = mk_dst_feature(src_feature, ogr.OFTStringList) dst_feature.SetFrom(src_feature) - if not check(dst_feature, 'field_integer', ["17"]): - return 'fail' + assert check(dst_feature, 'field_integer', ["17"]) - if not check(dst_feature, 'field_integer64', ["9876543210"]): - return 'fail' + assert check(dst_feature, 'field_integer64', ["9876543210"]) - if not check(dst_feature, 'field_real', ["18.4"]): - return 'fail' + assert check(dst_feature, 'field_real', ["18.4"]) - if not check(dst_feature, 'field_string', ['abc def']): - return 'fail' + assert check(dst_feature, 'field_string', ['abc def']) - if not check(dst_feature, 'field_binary', ['0123465789ABCDEF']): - return 'fail' + assert check(dst_feature, 'field_binary', ['0123465789ABCDEF']) - if not check(dst_feature, 'field_date', ['2011/11/11']): - return 'fail' + assert check(dst_feature, 'field_date', ['2011/11/11']) - if not check(dst_feature, 'field_time', ['14:10:35']): - return 'fail' + assert check(dst_feature, 'field_time', ['14:10:35']) - if not check(dst_feature, 'field_datetime', ['2011/11/11 14:10:35.123']): - return 'fail' + assert check(dst_feature, 'field_datetime', ['2011/11/11 14:10:35.123']) - if not check(dst_feature, 'field_integerlist', ['10', '20', '30']): - return 'fail' + assert check(dst_feature, 'field_integerlist', ['10', '20', '30']) - if not check(dst_feature, 'field_integer64list', ['9876543210']): - return 'fail' + assert check(dst_feature, 'field_integer64list', ['9876543210']) - if not check(dst_feature, 'field_reallist', ['123.5', '567']): - return 'fail' + assert check(dst_feature, 'field_reallist', ['123.5', '567']) - if not check(dst_feature, 'field_stringlist', ['abc', 'def']): - return 'fail' - - return 'success' + assert check(dst_feature, 'field_stringlist', ['abc', 'def']) ############################################################################### # Test SetField() / GetField() with unicode string -def ogr_feature_unicode(): +def test_ogr_feature_unicode(): if sys.version_info >= (3, 0, 0): - return 'skip' + pytest.skip() feat_def = ogr.FeatureDefn('test') @@ -758,41 +584,33 @@ def ogr_feature_unicode(): src_feature = ogr.Feature(feat_def) src_feature.SetField('field_string', 'abc def'.decode('utf-8')) - if src_feature.GetField('field_string') != 'abc def': - return 'fail' - if src_feature.GetField('field_string'.decode('utf-8')) != 'abc def': - return 'fail' + assert src_feature.GetField('field_string') == 'abc def' + assert src_feature.GetField('field_string'.decode('utf-8')) == 'abc def' src_feature = ogr.Feature(feat_def) src_feature.SetField('field_string'.decode('utf-8'), 'abc def'.decode('utf-8')) - if src_feature.GetField('field_string') != 'abc def': - return 'fail' + assert src_feature.GetField('field_string') == 'abc def' src_feature = ogr.Feature(feat_def) src_feature.SetField('field_integer64'.decode('utf-8'), 1) - if src_feature.GetField('field_integer64') != 1: - return 'fail' - - return 'success' + assert src_feature.GetField('field_integer64') == 1 ############################################################################### # Test 64bit FID -def ogr_feature_64bit_fid(): +def test_ogr_feature_64bit_fid(): feat_def = ogr.FeatureDefn('test') f = ogr.Feature(feat_def) f.SetFID(123456789012345) - if f.GetFID() != 123456789012345: - return 'fail' - return 'success' + assert f.GetFID() == 123456789012345 ############################################################################### # Test 64bit integer -def ogr_feature_overflow_64bit_integer(): +def test_ogr_feature_overflow_64bit_integer(): feat_def = ogr.FeatureDefn('test') feat_def.AddFieldDefn(ogr.FieldDefn('test', ogr.OFTInteger64)) @@ -801,60 +619,45 @@ def ogr_feature_overflow_64bit_integer(): f.SetField(0, '9999999999999999999') gdal.PopErrorHandler() if f.GetField(0) != 9223372036854775807: - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' + pytest.fail() gdal.PushErrorHandler() f.SetField(0, '-9999999999999999999') gdal.PopErrorHandler() if f.GetField(0) != -9223372036854775808: - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' - return 'success' - + pytest.fail() + ############################################################################### # Test SetNullable(), IsNullable() and Validate() -def ogr_feature_nullable_validate(): +def test_ogr_feature_nullable_validate(): # No fields feat_def = ogr.FeatureDefn('test') f = ogr.Feature(feat_def) - if f.Validate() != 1: - gdaltest.post_reason('fail') - return 'fail' + assert f.Validate() == 1 # Field with default parameter and empty feature feat_def = ogr.FeatureDefn('test') field_def = ogr.FieldDefn('field_string', ogr.OFTString) - if field_def.IsNullable() != 1: - gdaltest.post_reason('fail') - return 'fail' - if feat_def.GetGeomFieldDefn(0).IsNullable() != 1: - gdaltest.post_reason('fail') - return 'fail' + assert field_def.IsNullable() == 1 + assert feat_def.GetGeomFieldDefn(0).IsNullable() == 1 feat_def.AddFieldDefn(field_def) f = ogr.Feature(feat_def) - if f.Validate() != 1: - gdaltest.post_reason('fail') - return 'fail' + assert f.Validate() == 1 # Field with not NULL constraint and empty feature feat_def = ogr.FeatureDefn('test') field_def = ogr.FieldDefn('field_string', ogr.OFTString) field_def.SetNullable(0) - if field_def.IsNullable() != 0: - gdaltest.post_reason('fail') - return 'fail' + assert field_def.IsNullable() == 0 feat_def.AddFieldDefn(field_def) f = ogr.Feature(feat_def) gdal.PushErrorHandler() ret = f.Validate() gdal.PopErrorHandler() - if ret != 0: - gdaltest.post_reason('fail') - return 'fail' + assert ret == 0 # Field with not NULL constraint and non-empty feature feat_def = ogr.FeatureDefn('test') @@ -863,9 +666,7 @@ def ogr_feature_nullable_validate(): feat_def.AddFieldDefn(field_def) f = ogr.Feature(feat_def) f.SetField(0, 'foo') - if f.Validate() != 1: - gdaltest.post_reason('fail') - return 'fail' + assert f.Validate() == 1 # Field with width constraint that is met feat_def = ogr.FeatureDefn('test') @@ -874,9 +675,7 @@ def ogr_feature_nullable_validate(): feat_def.AddFieldDefn(field_def) f = ogr.Feature(feat_def) f.SetField(0, 'foo') - if f.Validate() != 1: - gdaltest.post_reason('fail') - return 'fail' + assert f.Validate() == 1 # Field with width constraint that is not met feat_def = ogr.FeatureDefn('test') @@ -888,24 +687,18 @@ def ogr_feature_nullable_validate(): gdal.PushErrorHandler() ret = f.Validate() gdal.PopErrorHandler() - if ret != 0: - gdaltest.post_reason('fail') - return 'fail' + assert ret == 0 # Geometry field with not-null geometry constraint that is met feat_def = ogr.FeatureDefn('test') feat_def.SetGeomType(ogr.wkbNone) gfield_def = ogr.GeomFieldDefn('test', ogr.wkbUnknown) gfield_def.SetNullable(0) - if gfield_def.IsNullable() != 0: - gdaltest.post_reason('fail') - return 'fail' + assert gfield_def.IsNullable() == 0 feat_def.AddGeomFieldDefn(gfield_def) f = ogr.Feature(feat_def) f.SetGeometry(ogr.CreateGeometryFromWkt('POINT(0 1)')) - if f.Validate() != 1: - gdaltest.post_reason('fail') - return 'fail' + assert f.Validate() == 1 # Geometry field with not-null geometry constraint that is not met feat_def = ogr.FeatureDefn('test') @@ -917,18 +710,14 @@ def ogr_feature_nullable_validate(): gdal.PushErrorHandler() ret = f.Validate() gdal.PopErrorHandler() - if ret != 0: - gdaltest.post_reason('fail') - return 'fail' + assert ret == 0 # Geometry field with Point geometry type that is met feat_def = ogr.FeatureDefn('test') feat_def.SetGeomType(ogr.wkbPoint) f = ogr.Feature(feat_def) f.SetGeometry(ogr.CreateGeometryFromWkt('POINT(0 1)')) - if f.Validate() != 1: - gdaltest.post_reason('fail') - return 'fail' + assert f.Validate() == 1 # Geometry field with LineString geometry type that is not met feat_def = ogr.FeatureDefn('test') @@ -938,62 +727,40 @@ def ogr_feature_nullable_validate(): gdal.PushErrorHandler() ret = f.Validate() gdal.PopErrorHandler() - if ret != 0: - gdaltest.post_reason('fail') - return 'fail' - - return 'success' + assert ret == 0 ############################################################################### # Test SetDefault(), GetDefault(), IsDefaultDriverSpecific() and FillUnsetWithDefault() -def ogr_feature_default(): +def test_ogr_feature_default(): feat_def = ogr.FeatureDefn('test') field_def = ogr.FieldDefn('field_string', ogr.OFTString) - if field_def.GetDefault() is not None: - gdaltest.post_reason('fail') - return 'fail' - if field_def.IsDefaultDriverSpecific(): - gdaltest.post_reason('fail') - return 'fail' + assert field_def.GetDefault() is None + assert not field_def.IsDefaultDriverSpecific() field_def.SetDefault("(some_expr)") - if field_def.GetDefault() != "(some_expr)": - gdaltest.post_reason('fail') - return 'fail' - if not field_def.IsDefaultDriverSpecific(): - gdaltest.post_reason('fail') - return 'fail' + assert field_def.GetDefault() == "(some_expr)" + assert field_def.IsDefaultDriverSpecific() field_def.SetDefault("'a") - if field_def.GetDefault() != "'a": - gdaltest.post_reason('fail') - return 'fail' + assert field_def.GetDefault() == "'a" gdal.PushErrorHandler() field_def.SetDefault("'a''") gdal.PopErrorHandler() - if field_def.GetDefault() is not None: - gdaltest.post_reason('fail') - return 'fail' + assert field_def.GetDefault() is None gdal.PushErrorHandler() field_def.SetDefault("'a'b'") gdal.PopErrorHandler() - if field_def.GetDefault() is not None: - gdaltest.post_reason('fail') - return 'fail' + assert field_def.GetDefault() is None field_def.SetDefault("'a''b'''") - if field_def.GetDefault() != "'a''b'''": - gdaltest.post_reason('fail') - return 'fail' - if field_def.IsDefaultDriverSpecific(): - gdaltest.post_reason('fail') - return 'fail' + assert field_def.GetDefault() == "'a''b'''" + assert not field_def.IsDefaultDriverSpecific() feat_def.AddFieldDefn(field_def) field_def = ogr.FieldDefn('field_datetime', ogr.OFTDateTime) @@ -1019,68 +786,44 @@ def ogr_feature_default(): f.GetField('field_int') != 123 or \ f.IsFieldSet('field_nodefault'): f.DumpReadable() - gdaltest.post_reason('fail') - return 'fail' + pytest.fail() f = ogr.Feature(feat_def) f.SetField('field_string', 'b') f.FillUnsetWithDefault() if f.GetField('field_string') != 'b': f.DumpReadable() - gdaltest.post_reason('fail') - return 'fail' - - return 'success' + pytest.fail() + ############################################################################### # Test GetNativeData(), SetNativeData(), GetNativeMediaType(), SetNativeMediaType(): -def ogr_feature_native_data(): +def test_ogr_feature_native_data(): feat_def = ogr.FeatureDefn('test') f = ogr.Feature(feat_def) - if f.GetNativeData() is not None: - gdaltest.post_reason('fail') - return 'fail' - if f.GetNativeMediaType() is not None: - gdaltest.post_reason('fail') - return 'fail' + assert f.GetNativeData() is None + assert f.GetNativeMediaType() is None f.SetNativeData('native_data') - if f.GetNativeData() != 'native_data': - gdaltest.post_reason('fail') - return 'fail' + assert f.GetNativeData() == 'native_data' f.SetNativeMediaType('native_media_type') - if f.GetNativeMediaType() != 'native_media_type': - gdaltest.post_reason('fail') - print(f.GetNativeMediaType()) - return 'fail' + assert f.GetNativeMediaType() == 'native_media_type' f2 = ogr.Feature(feat_def) f2.SetFrom(f) - if f2.GetNativeData() != 'native_data': - gdaltest.post_reason('fail') - return 'fail' - if f2.GetNativeMediaType() != 'native_media_type': - gdaltest.post_reason('fail') - return 'fail' + assert f2.GetNativeData() == 'native_data' + assert f2.GetNativeMediaType() == 'native_media_type' f_clone = f.Clone() - if f_clone.GetNativeData() != 'native_data': - gdaltest.post_reason('fail') - return 'fail' - if f_clone.GetNativeMediaType() != 'native_media_type': - gdaltest.post_reason('fail') - return 'fail' + assert f_clone.GetNativeData() == 'native_data' + assert f_clone.GetNativeMediaType() == 'native_media_type' f_clone.SetNativeData(None) f_clone.SetNativeMediaType(None) - if f_clone.GetNativeData() is not None: - gdaltest.post_reason('fail') - return 'fail' - if f_clone.GetNativeMediaType() is not None: - gdaltest.post_reason('fail') - return 'fail' + assert f_clone.GetNativeData() is None + assert f_clone.GetNativeMediaType() is None ds = ogr.GetDriverByName('Memory').CreateDataSource('') lyr = ds.CreateLayer('test') @@ -1098,37 +841,20 @@ def ogr_feature_native_data(): for dialect in dialects: sql_lyr = ds.ExecuteSQL('SELECT * FROM %s' % lyr.GetName(), dialect=dialect) native_data = sql_lyr.GetMetadataItem('NATIVE_DATA', 'NATIVE_DATA') - if native_data != 'native_data': - gdaltest.post_reason('fail') - print(dialect) - print(native_data) - return 'fail' + assert native_data == 'native_data', dialect native_media_type = sql_lyr.GetMetadataItem('NATIVE_MEDIA_TYPE', 'NATIVE_DATA') - if native_media_type != 'native_media_type': - gdaltest.post_reason('fail') - print(dialect) - print(native_media_type) - return 'fail' + assert native_media_type == 'native_media_type', dialect f = sql_lyr.GetNextFeature() - if f.GetNativeData() != 'native_data': - gdaltest.post_reason('fail') - print(dialect) - print(f.GetNativeData()) - return 'fail' - if f.GetNativeMediaType() != 'native_media_type': - gdaltest.post_reason('fail') - print(dialect) - print(f.GetNativeMediaType()) - return 'fail' + assert f.GetNativeData() == 'native_data', dialect + assert f.GetNativeMediaType() == 'native_media_type', dialect ds.ReleaseResultSet(sql_lyr) - return 'success' - + ############################################################################### # Test assigning our geometry to ourselves -def ogr_feature_set_geometry_self(): +def test_ogr_feature_set_geometry_self(): feat_def = ogr.FeatureDefn('test') f = ogr.Feature(feat_def) @@ -1137,40 +863,26 @@ def ogr_feature_set_geometry_self(): f.SetGeometryDirectly(f.GetGeometryRef()) f.SetGeometry(f.GetGeometryRef()) f.SetGeometry(f.GetGeometryRef()) - if f.GetGeometryRef().ExportToWkt() != 'POINT (2 49)': - gdaltest.post_reason('fail') - return 'fail' - - return 'success' + assert f.GetGeometryRef().ExportToWkt() == 'POINT (2 49)' ############################################################################### # Test SetFieldNull(), IsFieldNull() -def ogr_feature_null_field(): +def test_ogr_feature_null_field(): feat_def = ogr.FeatureDefn('test') field_def = ogr.FieldDefn('field_string', ogr.OFTString) feat_def.AddFieldDefn(field_def) f = ogr.Feature(feat_def) - if f.IsFieldNull(feat_def.GetFieldIndex("field_string")): - gdaltest.post_reason('fail') - return 'fail' - if f.IsFieldNull("field_string"): - gdaltest.post_reason('fail') - return 'fail' + assert not f.IsFieldNull(feat_def.GetFieldIndex("field_string")) + assert not f.IsFieldNull("field_string") f.SetFieldNull(feat_def.GetFieldIndex("field_string")) - if f.IsFieldNull(feat_def.GetFieldIndex("field_string")) == 0: - gdaltest.post_reason('fail') - return 'fail' + assert f.IsFieldNull(feat_def.GetFieldIndex("field_string")) != 0 f.SetField("field_string", "foo") - if f.IsFieldNull("field_string"): - gdaltest.post_reason('fail') - return 'fail' + assert not f.IsFieldNull("field_string") f.SetFieldNull("field_string") - if f.IsFieldNull(feat_def.GetFieldIndex("field_string")) == 0: - gdaltest.post_reason('fail') - return 'fail' + assert f.IsFieldNull(feat_def.GetFieldIndex("field_string")) != 0 f = None field_def = ogr.FieldDefn('field_binary', ogr.OFTBinary) @@ -1194,89 +906,32 @@ def ogr_feature_null_field(): f.field_integer64list = [9876543210] f.field_reallist = [123.5, 567.0] f.field_stringlist = ['abc', 'def'] - if f.IsFieldNull('field_binary') != 0: - gdaltest.post_reason('fail') - return 'fail' - if f.IsFieldNull('field_integerlist') != 0: - gdaltest.post_reason('fail') - return 'fail' - if f.IsFieldNull('field_integer64list') != 0: - gdaltest.post_reason('fail') - return 'fail' - if f.IsFieldNull('field_reallist') != 0: - gdaltest.post_reason('fail') - return 'fail' - if f.IsFieldNull('field_stringlist') != 0: - gdaltest.post_reason('fail') - return 'fail' + assert f.IsFieldNull('field_binary') == 0 + assert f.IsFieldNull('field_integerlist') == 0 + assert f.IsFieldNull('field_integer64list') == 0 + assert f.IsFieldNull('field_reallist') == 0 + assert f.IsFieldNull('field_stringlist') == 0 f.SetField('field_binary', None) f.SetFieldNull('field_integerlist') f.SetFieldNull('field_integer64list') f.SetFieldNull('field_reallist') f.SetFieldNull('field_stringlist') - if f.IsFieldNull('field_binary') == 0: - gdaltest.post_reason('fail') - return 'fail' - if f.IsFieldNull('field_integerlist') == 0: - gdaltest.post_reason('fail') - return 'fail' - if f.IsFieldNull('field_integer64list') == 0: - gdaltest.post_reason('fail') - return 'fail' - if f.IsFieldNull('field_reallist') == 0: - gdaltest.post_reason('fail') - return 'fail' - if f.IsFieldNull('field_stringlist') == 0: - gdaltest.post_reason('fail') - return 'fail' + assert f.IsFieldNull('field_binary') != 0 + assert f.IsFieldNull('field_integerlist') != 0 + assert f.IsFieldNull('field_integer64list') != 0 + assert f.IsFieldNull('field_reallist') != 0 + assert f.IsFieldNull('field_stringlist') != 0 f_clone = f.Clone() - if f_clone.IsFieldNull('field_binary') == 0: - gdaltest.post_reason('fail') - return 'fail' - if not f.Equal(f_clone): - gdaltest.post_reason('fail') - return 'fail' + assert f_clone.IsFieldNull('field_binary') != 0 + assert f.Equal(f_clone) f = None - return 'success' - -def ogr_feature_cleanup(): +def test_ogr_feature_cleanup(): gdaltest.src_feature = None - return 'success' - - -gdaltest_list = [ - ogr_feature_cp_integer, - ogr_feature_cp_integer64, - ogr_feature_cp_real, - ogr_feature_cp_string, - ogr_feature_cp_binary, - ogr_feature_cp_date, - ogr_feature_cp_time, - ogr_feature_cp_datetime, - ogr_feature_cp_integerlist, - ogr_feature_cp_integer64list, - ogr_feature_cp_reallist, - ogr_feature_cp_stringlist, - ogr_feature_unicode, - ogr_feature_64bit_fid, - ogr_feature_overflow_64bit_integer, - ogr_feature_nullable_validate, - ogr_feature_default, - ogr_feature_native_data, - ogr_feature_set_geometry_self, - ogr_feature_null_field, - ogr_feature_cleanup] - -if __name__ == '__main__': - - gdaltest.setup_run('ogr_feature') - - gdaltest.run_tests(gdaltest_list) - - sys.exit(gdaltest.summarize()) + + diff --git a/autotest/ogr/ogr_fgdb.py b/autotest/ogr/ogr_fgdb.py index b854ec4cb126..8497cdba8726 100755 --- a/autotest/ogr/ogr_fgdb.py +++ b/autotest/ogr/ogr_fgdb.py @@ -30,28 +30,27 @@ ############################################################################### import os -import sys import shutil -sys.path.append('../pymod') import gdaltest import ogrtest from osgeo import gdal from osgeo import ogr from osgeo import osr +import pytest ############################################################################### # Test if driver is available -def ogr_fgdb_init(): +def test_ogr_fgdb_init(): ogrtest.fgdb_drv = None ogrtest.fgdb_drv = ogr.GetDriverByName('FileGDB') if ogrtest.fgdb_drv is None: - return 'skip' + pytest.skip() ogrtest.openfilegdb_drv = ogr.GetDriverByName('OpenFileGDB') if ogrtest.openfilegdb_drv is not None: @@ -62,8 +61,7 @@ def ogr_fgdb_init(): except OSError: pass - return 'success' - + ############################################################################### @@ -97,9 +95,9 @@ def ogr_fgdb_is_sdk_1_4_or_later(): ############################################################################### # Write and read back various geometry types -def ogr_fgdb_1(): +def test_ogr_fgdb_1(): if ogrtest.fgdb_drv is None: - return 'skip' + pytest.skip() srs = osr.SpatialReference() srs.SetFromUserInput("WGS84") @@ -175,10 +173,7 @@ def ogr_fgdb_1(): for data in datalist: lyr = ds.GetLayerByName(data[0]) if data[1] != ogr.wkbNone: - if lyr.GetSpatialRef().IsSame(srs) != 1: - gdaltest.post_reason('fail') - print(lyr.GetSpatialRef()) - return 'fail' + assert lyr.GetSpatialRef().IsSame(srs) == 1 feat = lyr.GetNextFeature() if data[1] != ogr.wkbNone: try: @@ -187,15 +182,11 @@ def ogr_fgdb_1(): expected_wkt = data[2] if expected_wkt is None: if feat.GetGeometryRef() is not None: - gdaltest.post_reason('fail') - print(data) feat.DumpReadable() - return 'fail' + pytest.fail(data) elif ogrtest.check_feature_geometry(feat, expected_wkt) != 0: - gdaltest.post_reason('fail') - print(data) feat.DumpReadable() - return 'fail' + pytest.fail(data) if feat.GetField('id') != 1 or \ feat.GetField('smallint') != -13 or \ @@ -208,83 +199,52 @@ def ogr_fgdb_1(): feat.GetField('binary') != "00FF7F" or \ feat.GetField('binary2') != "123456" or \ feat.GetField('smallint2') != -32768: - gdaltest.post_reason('fail') feat.DumpReadable() - return 'fail' + pytest.fail() sql_lyr = ds.ExecuteSQL("GetLayerDefinition %s" % lyr.GetName()) - if sql_lyr is None: - gdaltest.post_reason('failure') - return 'fail' + assert sql_lyr is not None feat = sql_lyr.GetNextFeature() - if feat is None: - gdaltest.post_reason('failure') - return 'fail' + assert feat is not None feat = sql_lyr.GetNextFeature() - if feat is not None: - gdaltest.post_reason('failure') - return 'fail' + assert feat is None lyr.ResetReading() lyr.TestCapability("foo") ds.ReleaseResultSet(sql_lyr) sql_lyr = ds.ExecuteSQL("GetLayerMetadata %s" % lyr.GetName()) - if sql_lyr is None: - gdaltest.post_reason('failure') - return 'fail' + assert sql_lyr is not None feat = sql_lyr.GetNextFeature() - if feat is None: - gdaltest.post_reason('failure') - return 'fail' + assert feat is not None ds.ReleaseResultSet(sql_lyr) sql_lyr = ds.ExecuteSQL("GetLayerDefinition foo") - if sql_lyr is not None: - gdaltest.post_reason('failure') - return 'fail' + assert sql_lyr is None sql_lyr = ds.ExecuteSQL("GetLayerMetadata foo") - if sql_lyr is not None: - gdaltest.post_reason('failure') - return 'fail' + assert sql_lyr is None ds = None - return 'success' - ############################################################################### # Test DeleteField() -def ogr_fgdb_DeleteField(): +def test_ogr_fgdb_DeleteField(): if ogrtest.fgdb_drv is None: - return 'skip' + pytest.skip() ds = ogr.Open("tmp/test.gdb", update=1) lyr = ds.GetLayerByIndex(0) - if lyr.GetLayerDefn().GetFieldDefn(lyr.GetLayerDefn().GetFieldIndex('smallint')).GetSubType() != ogr.OFSTInt16: - gdaltest.post_reason('fail') - return 'fail' - if lyr.GetLayerDefn().GetFieldDefn(lyr.GetLayerDefn().GetFieldIndex('smallint2')).GetSubType() != ogr.OFSTInt16: - gdaltest.post_reason('fail') - return 'fail' - if lyr.GetLayerDefn().GetFieldDefn(lyr.GetLayerDefn().GetFieldIndex('float')).GetSubType() != ogr.OFSTFloat32: - gdaltest.post_reason('fail') - return 'fail' - if lyr.GetLayerDefn().GetFieldDefn(lyr.GetLayerDefn().GetFieldIndex('float2')).GetSubType() != ogr.OFSTFloat32: - gdaltest.post_reason('fail') - return 'fail' - - if lyr.GetLayerDefn().GetFieldDefn(lyr.GetLayerDefn().GetFieldIndex('smallint')).GetWidth() != 0: - gdaltest.post_reason('failure') - return 'fail' - if lyr.GetLayerDefn().GetFieldDefn(lyr.GetLayerDefn().GetFieldIndex('str')).GetWidth() != 0: - gdaltest.post_reason('failure') - return 'fail' - if lyr.DeleteField(lyr.GetLayerDefn().GetFieldIndex('str')) != 0: - gdaltest.post_reason('failure') - return 'fail' + assert lyr.GetLayerDefn().GetFieldDefn(lyr.GetLayerDefn().GetFieldIndex('smallint')).GetSubType() == ogr.OFSTInt16 + assert lyr.GetLayerDefn().GetFieldDefn(lyr.GetLayerDefn().GetFieldIndex('smallint2')).GetSubType() == ogr.OFSTInt16 + assert lyr.GetLayerDefn().GetFieldDefn(lyr.GetLayerDefn().GetFieldIndex('float')).GetSubType() == ogr.OFSTFloat32 + assert lyr.GetLayerDefn().GetFieldDefn(lyr.GetLayerDefn().GetFieldIndex('float2')).GetSubType() == ogr.OFSTFloat32 + + assert lyr.GetLayerDefn().GetFieldDefn(lyr.GetLayerDefn().GetFieldIndex('smallint')).GetWidth() == 0 + assert lyr.GetLayerDefn().GetFieldDefn(lyr.GetLayerDefn().GetFieldIndex('str')).GetWidth() == 0 + assert lyr.DeleteField(lyr.GetLayerDefn().GetFieldIndex('str')) == 0 # Needed since FileGDB v1.4, otherwise crash/error ... if True: # pylint: disable=using-constant-test @@ -300,65 +260,51 @@ def ogr_fgdb_DeleteField(): # Test updating non-existing feature feat.SetFID(-10) - if lyr.SetFeature(feat) != ogr.OGRERR_NON_EXISTING_FEATURE: - gdaltest.post_reason('Expected failure of SetFeature().') - return 'fail' + assert lyr.SetFeature(feat) == ogr.OGRERR_NON_EXISTING_FEATURE, \ + 'Expected failure of SetFeature().' # Test deleting non-existing feature - if lyr.DeleteFeature(-10) != ogr.OGRERR_NON_EXISTING_FEATURE: - gdaltest.post_reason('Expected failure of DeleteFeature().') - return 'fail' + assert lyr.DeleteFeature(-10) == ogr.OGRERR_NON_EXISTING_FEATURE, \ + 'Expected failure of DeleteFeature().' feat = None ds = None ds = ogr.Open("tmp/test.gdb") lyr = ds.GetLayerByIndex(0) - if lyr.GetLayerDefn().GetFieldDefn(lyr.GetLayerDefn().GetFieldIndex('str2')).GetWidth() != 80: - gdaltest.post_reason('failure') - return 'fail' - if lyr.GetLayerDefn().GetFieldIndex('str') != -1: - gdaltest.post_reason('failure') - return 'fail' + assert lyr.GetLayerDefn().GetFieldDefn(lyr.GetLayerDefn().GetFieldIndex('str2')).GetWidth() == 80 + assert lyr.GetLayerDefn().GetFieldIndex('str') == -1 feat = lyr.GetNextFeature() - if feat.GetFieldAsString("str2") != "foo2_\xc3\xa9": - gdaltest.post_reason('failure') - return 'fail' + assert feat.GetFieldAsString("str2") == "foo2_\xc3\xa9" ds = None - return 'success' - ############################################################################### # Run test_ogrsf -def ogr_fgdb_2(): +def test_ogr_fgdb_2(): if ogrtest.fgdb_drv is None: - return 'skip' + pytest.skip() import test_cli_utilities if test_cli_utilities.get_test_ogrsf_path() is None: - return 'skip' + pytest.skip() ret = gdaltest.runexternal(test_cli_utilities.get_test_ogrsf_path() + ' -ro tmp/test.gdb --config OGR_SKIP OpenFileGDB') - if ret.find('INFO') == -1 or ret.find('ERROR') != -1: - print(ret) - return 'fail' - - return 'success' + assert ret.find('INFO') != -1 and ret.find('ERROR') == -1 ############################################################################### # Run ogr2ogr -def ogr_fgdb_3(): +def test_ogr_fgdb_3(): if ogrtest.fgdb_drv is None: - return 'skip' + pytest.skip() import test_cli_utilities if test_cli_utilities.get_ogr2ogr_path() is None: - return 'skip' + pytest.skip() try: shutil.rmtree("tmp/poly.gdb") @@ -368,34 +314,28 @@ def ogr_fgdb_3(): gdaltest.runexternal(test_cli_utilities.get_ogr2ogr_path() + ' -f filegdb tmp/poly.gdb data/poly.shp -nlt MULTIPOLYGON -a_srs None') ds = ogr.Open('tmp/poly.gdb') - if ds is None or ds.GetLayerCount() == 0: - gdaltest.post_reason('ogr2ogr failed') - return 'fail' + assert not (ds is None or ds.GetLayerCount() == 0), 'ogr2ogr failed' ds = None if test_cli_utilities.get_test_ogrsf_path() is None: - return 'skip' + pytest.skip() ret = gdaltest.runexternal(test_cli_utilities.get_test_ogrsf_path() + ' tmp/poly.gdb') # print ret - if ret.find('INFO') == -1 or ret.find('ERROR') != -1: - print(ret) - return 'fail' - - return 'success' + assert ret.find('INFO') != -1 and ret.find('ERROR') == -1 ############################################################################### # Test SQL support -def ogr_fgdb_sql(): +def test_ogr_fgdb_sql(): if ogrtest.fgdb_drv is None: - return 'skip' + pytest.skip() import test_cli_utilities if test_cli_utilities.get_ogr2ogr_path() is None: - return 'skip' + pytest.skip() ds = ogr.Open('tmp/poly.gdb') @@ -403,24 +343,20 @@ def ogr_fgdb_sql(): sql_lyr = ds.ExecuteSQL("SELECT * FROM POLY WHERE EAS_ID = 170", dialect='FileGDB') feat = sql_lyr.GetNextFeature() - if feat is None: - return 'fail' + assert feat is not None feat = sql_lyr.GetNextFeature() - if feat is not None: - return 'fail' + assert feat is None feat = None ds.ReleaseResultSet(sql_lyr) ds = None - return 'success' - ############################################################################### # Test delete layer -def ogr_fgdb_4(): +def test_ogr_fgdb_4(): if ogrtest.fgdb_drv is None: - return 'skip' + pytest.skip() for j in range(2): @@ -450,40 +386,32 @@ def ogr_fgdb_4(): lyr = ds.GetLayerByName('layer_to_remove') ds = None - if lyr is not None: - gdaltest.post_reason('failed at iteration %d' % j) - return 'fail' - - return 'success' + assert lyr is None, ('failed at iteration %d' % j) + ############################################################################### # Test DeleteDataSource() -def ogr_fgdb_5(): +def test_ogr_fgdb_5(): if ogrtest.fgdb_drv is None: - return 'skip' + pytest.skip() - if ogrtest.fgdb_drv.DeleteDataSource("tmp/test.gdb") != 0: - gdaltest.post_reason('DeleteDataSource() failed') - return 'fail' + assert ogrtest.fgdb_drv.DeleteDataSource("tmp/test.gdb") == 0, \ + 'DeleteDataSource() failed' - try: + with pytest.raises(OSError, message="tmp/test.gdb still existing"): os.stat("tmp/test.gdb") - gdaltest.post_reason("tmp/test.gdb still existing") - return 'fail' - except OSError: - pass - - return 'success' + + ############################################################################### # Test adding a layer to an existing feature dataset -def ogr_fgdb_6(): +def test_ogr_fgdb_6(): if ogrtest.fgdb_drv is None: - return 'skip' + pytest.skip() srs = osr.SpatialReference() srs.SetFromUserInput("WGS84") @@ -494,19 +422,16 @@ def ogr_fgdb_6(): ds = None ds = ogr.Open('tmp/test.gdb') - if ds.GetLayerCount() != 2: - return 'fail' + assert ds.GetLayerCount() == 2 ds = None - return 'success' - ############################################################################### # Test bulk loading (#4420) -def ogr_fgdb_7(): +def test_ogr_fgdb_7(): if ogrtest.fgdb_drv is None: - return 'skip' + pytest.skip() try: shutil.rmtree("tmp/test.gdb") @@ -530,21 +455,18 @@ def ogr_fgdb_7(): lyr.ResetReading() feat = lyr.GetNextFeature() - if feat.GetField(0) != 0: - return 'fail' + assert feat.GetField(0) == 0 ds = None gdal.SetConfigOption('FGDB_BULK_LOAD', None) - return 'success' - ############################################################################### # Test field name laundering (#4458) -def ogr_fgdb_8(): +def test_ogr_fgdb_8(): if ogrtest.fgdb_drv is None: - return 'skip' + pytest.skip() try: shutil.rmtree("tmp/test.gdb") @@ -571,19 +493,17 @@ def ogr_fgdb_8(): 'A1234567890123456789012345678901234567890123456789012345678901_1', 'A1234567890123456789012345678901234567890123456789012345678901_2'] for i in range(5): - if lyr_defn.GetFieldIndex(expected_names[i]) != i: - gdaltest.post_reason('did not find %s' % expected_names[i]) - return 'fail' - - return 'success' + assert lyr_defn.GetFieldIndex(expected_names[i]) == i, \ + ('did not find %s' % expected_names[i]) + ############################################################################### # Test layer name laundering (#4466) -def ogr_fgdb_9(): +def test_ogr_fgdb_9(): if ogrtest.fgdb_drv is None: - return 'skip' + pytest.skip() try: shutil.rmtree("tmp/test.gdb") @@ -619,19 +539,16 @@ def ogr_fgdb_9(): _160char[0:158] + '_1', _160char[0:158] + '_2'] for i, exp_name in enumerate(expected_names): - if ds.GetLayerByIndex(i).GetName() != exp_name: - gdaltest.post_reason('did not find %s' % exp_name) - return 'fail' - - return 'success' + assert ds.GetLayerByIndex(i).GetName() == exp_name, ('did not find %s' % exp_name) + ############################################################################### # Test SRS support -def ogr_fgdb_10(): +def test_ogr_fgdb_10(): if ogrtest.fgdb_drv is None: - return 'skip' + pytest.skip() try: shutil.rmtree("tmp/test.gdb") @@ -705,36 +622,24 @@ def ogr_fgdb_10(): ds = ogr.Open('tmp/test.gdb') lyr = ds.GetLayerByName("srs_exact_4326") - if lyr.GetSpatialRef().ExportToWkt().find('4326') == -1: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.GetSpatialRef().ExportToWkt().find('4326') != -1 lyr = ds.GetLayerByName("srs_approx_4326") - if lyr.GetSpatialRef().ExportToWkt().find('4326') == -1: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.GetSpatialRef().ExportToWkt().find('4326') != -1 lyr = ds.GetLayerByName("srs_exact_2193") - if lyr.GetSpatialRef().ExportToWkt().find('2193') == -1: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.GetSpatialRef().ExportToWkt().find('2193') != -1 lyr = ds.GetLayerByName("srs_approx_2193") - if lyr.GetSpatialRef().ExportToWkt().find('2193') == -1: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.GetSpatialRef().ExportToWkt().find('2193') != -1 lyr = ds.GetLayerByName("srs_approx_4230") - if lyr.GetSpatialRef().ExportToWkt().find('4230') == -1: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.GetSpatialRef().ExportToWkt().find('4230') != -1 ds = None - return 'success' - ############################################################################### # Test all data types -def ogr_fgdb_11(): +def test_ogr_fgdb_11(): if ogrtest.fgdb_drv is None: - return 'skip' + pytest.skip() try: shutil.rmtree("tmp/test.gdb") @@ -784,35 +689,31 @@ def ogr_fgdb_11(): feat.GetField('esriFieldTypeGUID') != '{12345678-9ABC-DEF0-1234-567890ABCDEF}' or \ (not feat.IsFieldSet('esriFieldTypeGlobalID')): feat.DumpReadable() - return 'fail' + pytest.fail() feat = lyr.GetNextFeature() if not feat.IsFieldSet('esriFieldTypeGlobalID'): feat.DumpReadable() - return 'fail' + pytest.fail() lyr = ds.GetLayerByName('test2') feat = lyr.GetNextFeature() if not feat.IsFieldSet('global_id'): feat.DumpReadable() - return 'fail' + pytest.fail() ds = None - return 'success' - ############################################################################### # Test failed Open() -def ogr_fgdb_12(): +def test_ogr_fgdb_12(): if ogrtest.fgdb_drv is None: - return 'skip' + pytest.skip() ds = ogr.Open('tmp/non_existing.gdb') - if ds is not None: - gdaltest.post_reason('fail') - return 'fail' + assert ds is None gdal.Unlink('tmp/dummy.gdb') try: @@ -824,9 +725,7 @@ def ogr_fgdb_12(): f.close() ds = ogr.Open('tmp/dummy.gdb') - if ds is not None: - gdaltest.post_reason('fail') - return 'fail' + assert ds is None os.unlink('tmp/dummy.gdb') @@ -835,28 +734,22 @@ def ogr_fgdb_12(): gdal.PushErrorHandler('CPLQuietErrorHandler') ds = ogr.Open('tmp/dummy.gdb') gdal.PopErrorHandler() - if ds is not None: - gdaltest.post_reason('fail') - return 'fail' + assert ds is None shutil.rmtree('tmp/dummy.gdb') - return 'success' - ############################################################################### # Test failed CreateDataSource() and DeleteDataSource() -def ogr_fgdb_13(): +def test_ogr_fgdb_13(): if ogrtest.fgdb_drv is None: - return 'skip' + pytest.skip() gdal.PushErrorHandler('CPLQuietErrorHandler') ds = ogrtest.fgdb_drv.CreateDataSource('tmp/foo') gdal.PopErrorHandler() - if ds is not None: - gdaltest.post_reason('fail') - return 'fail' + assert ds is None f = open('tmp/dummy.gdb', 'wb') f.close() @@ -864,9 +757,7 @@ def ogr_fgdb_13(): gdal.PushErrorHandler('CPLQuietErrorHandler') ds = ogrtest.fgdb_drv.CreateDataSource('tmp/dummy.gdb') gdal.PopErrorHandler() - if ds is not None: - gdaltest.post_reason('fail') - return 'fail' + assert ds is None os.unlink('tmp/dummy.gdb') @@ -880,48 +771,37 @@ def ogr_fgdb_13(): gdal.PushErrorHandler('CPLQuietErrorHandler') ds = ogrtest.fgdb_drv.CreateDataSource(name) gdal.PopErrorHandler() - if ds is not None: - gdaltest.post_reason('fail') - return 'fail' + assert ds is None gdal.PushErrorHandler('CPLQuietErrorHandler') ret = ogrtest.fgdb_drv.DeleteDataSource(name) gdal.PopErrorHandler() - if ret == 0: - gdaltest.post_reason('fail') - return 'fail' - - return 'success' + assert ret != 0 ############################################################################### # Test interleaved opening and closing of databases (#4270) -def ogr_fgdb_14(): +def test_ogr_fgdb_14(): if ogrtest.fgdb_drv is None: - return 'skip' + pytest.skip() for _ in range(3): ds1 = ogr.Open("tmp/test.gdb") - if ds1 is None: - gdaltest.post_reason('fail') - return 'fail' + assert ds1 is not None ds2 = ogr.Open("tmp/test.gdb") - if ds2 is None: - gdaltest.post_reason('fail') - return 'fail' + assert ds2 is not None ds2 = None ds1 = None - return 'success' - + ############################################################################### # Test opening a FGDB with both SRID and LatestSRID set (#5638) -def ogr_fgdb_15(): +def test_ogr_fgdb_15(): if ogrtest.fgdb_drv is None: - return 'skip' + pytest.skip() try: shutil.rmtree('tmp/test3005.gdb') @@ -934,22 +814,16 @@ def ogr_fgdb_15(): sr = osr.SpatialReference() sr.ImportFromEPSG(3005) expected_wkt = sr.ExportToWkt() - if got_wkt != expected_wkt: - gdaltest.post_reason('fail') - print(got_wkt) - print(expected_wkt) - return 'fail' + assert got_wkt == expected_wkt ds = None - return 'success' - ############################################################################### # Test fix for #5674 -def ogr_fgdb_16(): +def test_ogr_fgdb_16(): if ogrtest.fgdb_drv is None or ogrtest.openfilegdb_drv is None: - return 'skip' + pytest.skip() try: gdaltest.unzip('tmp/cache', 'data/ESSENCE_NAIPF_ORI_PROV_sub93.gdb.zip') @@ -958,7 +832,7 @@ def ogr_fgdb_16(): try: os.stat('tmp/cache/ESSENCE_NAIPF_ORI_PROV_sub93.gdb') except OSError: - return 'skip' + pytest.skip() ogrtest.fgdb_drv.Deregister() @@ -983,10 +857,10 @@ def ogr_fgdb_16(): # Test not nullable fields -def ogr_fgdb_17(): +def test_ogr_fgdb_17(): if ogrtest.fgdb_drv is None: - return 'skip' + pytest.skip() try: shutil.rmtree("tmp/test.gdb") @@ -997,9 +871,7 @@ def ogr_fgdb_17(): sr = osr.SpatialReference() sr.ImportFromEPSG(4326) lyr = ds.CreateLayer('test', geom_type=ogr.wkbPoint, srs=sr, options=['GEOMETRY_NULLABLE=NO']) - if lyr.GetLayerDefn().GetGeomFieldDefn(0).IsNullable() != 0: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.GetLayerDefn().GetGeomFieldDefn(0).IsNullable() == 0 field_defn = ogr.FieldDefn('field_not_nullable', ogr.OFTString) field_defn.SetNullable(0) lyr.CreateField(field_defn) @@ -1010,9 +882,7 @@ def ogr_fgdb_17(): f.SetField('field_not_nullable', 'not_null') f.SetGeometryDirectly(ogr.CreateGeometryFromWkt('POINT(0 0)')) ret = lyr.CreateFeature(f) - if ret != 0: - gdaltest.post_reason('fail') - return 'fail' + assert ret == 0 f = None # Error case: missing geometry @@ -1021,9 +891,7 @@ def ogr_fgdb_17(): gdal.PushErrorHandler() ret = lyr.CreateFeature(f) gdal.PopErrorHandler() - if ret == 0: - gdaltest.post_reason('fail') - return 'fail' + assert ret != 0 f = None # Error case: missing non-nullable field @@ -1032,37 +900,27 @@ def ogr_fgdb_17(): gdal.PushErrorHandler() ret = lyr.CreateFeature(f) gdal.PopErrorHandler() - if ret == 0: - gdaltest.post_reason('fail') - return 'fail' + assert ret != 0 f = None ds = None ds = ogr.Open('tmp/test.gdb', update=1) lyr = ds.GetLayerByName('test') - if lyr.GetLayerDefn().GetFieldDefn(lyr.GetLayerDefn().GetFieldIndex('field_not_nullable')).IsNullable() != 0: - gdaltest.post_reason('fail') - return 'fail' - if lyr.GetLayerDefn().GetFieldDefn(lyr.GetLayerDefn().GetFieldIndex('field_nullable')).IsNullable() != 1: - gdaltest.post_reason('fail') - return 'fail' - if lyr.GetLayerDefn().GetGeomFieldDefn(0).IsNullable() != 0: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.GetLayerDefn().GetFieldDefn(lyr.GetLayerDefn().GetFieldIndex('field_not_nullable')).IsNullable() == 0 + assert lyr.GetLayerDefn().GetFieldDefn(lyr.GetLayerDefn().GetFieldIndex('field_nullable')).IsNullable() == 1 + assert lyr.GetLayerDefn().GetGeomFieldDefn(0).IsNullable() == 0 ds = None - return 'success' - ############################################################################### # Test default values -def ogr_fgdb_18(): +def test_ogr_fgdb_18(): if ogrtest.fgdb_drv is None: - return 'skip' + pytest.skip() try: shutil.rmtree("tmp/test.gdb") @@ -1114,20 +972,11 @@ def ogr_fgdb_18_test_results(): ds = ogr.Open('tmp/test.gdb', update=1) lyr = ds.GetLayerByName('test') - if lyr.GetLayerDefn().GetFieldDefn(lyr.GetLayerDefn().GetFieldIndex('field_string')).GetDefault() != "'a''b'": - gdaltest.post_reason('fail') - return 'fail' + assert lyr.GetLayerDefn().GetFieldDefn(lyr.GetLayerDefn().GetFieldIndex('field_string')).GetDefault() == "'a''b'" if ogrtest.openfilegdb_drv is not None: - if lyr.GetLayerDefn().GetFieldDefn(lyr.GetLayerDefn().GetFieldIndex('field_int')).GetDefault() != '123': - gdaltest.post_reason('fail') - return 'fail' - if lyr.GetLayerDefn().GetFieldDefn(lyr.GetLayerDefn().GetFieldIndex('field_real')).GetDefault() != '1.23': - print(lyr.GetLayerDefn().GetFieldDefn(lyr.GetLayerDefn().GetFieldIndex('field_real')).GetDefault()) - gdaltest.post_reason('fail') - return 'fail' - if lyr.GetLayerDefn().GetFieldDefn(lyr.GetLayerDefn().GetFieldIndex('field_nodefault')).GetDefault() is not None: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.GetLayerDefn().GetFieldDefn(lyr.GetLayerDefn().GetFieldIndex('field_int')).GetDefault() == '123' + assert lyr.GetLayerDefn().GetFieldDefn(lyr.GetLayerDefn().GetFieldIndex('field_real')).GetDefault() == '1.23' + assert lyr.GetLayerDefn().GetFieldDefn(lyr.GetLayerDefn().GetFieldIndex('field_nodefault')).GetDefault() is None # if lyr.GetLayerDefn().GetFieldDefn(lyr.GetLayerDefn().GetFieldIndex('field_datetime')).GetDefault() != 'CURRENT_TIMESTAMP': # gdaltest.post_reason('fail') # return 'fail' @@ -1140,13 +989,10 @@ def ogr_fgdb_18_test_results(): f.GetField('field_real') != 1.23 or \ not f.IsFieldNull('field_nodefault') or not f.IsFieldSet('field_datetime') or \ f.GetField('field_datetime2') != '2015/06/30 12:34:56': - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' + pytest.fail() ds = None - return 'success' - ############################################################################### # Test transaction support @@ -1174,17 +1020,17 @@ def ogr_fgdb_19_open_update(filename): return (bPerLayerCopyingForTransaction, ds) -def ogr_fgdb_19(): +def test_ogr_fgdb_19(): if ogrtest.fgdb_drv is None: - return 'skip' + pytest.skip() # FIXME likely due to too old FileGDB SDK on those targets # fails with ERROR 1: Failed to open Geodatabase (The system cannot find the file specified.) # File "ogr_fgdb.py", line 1664, in ogr_fgdb_19 # if ds.StartTransaction(force=True) != 0: if gdaltest.is_travis_branch('ubuntu_1804') or gdaltest.is_travis_branch('ubuntu_1604') or gdaltest.is_travis_branch('trusty_clang') or gdaltest.is_travis_branch('python3') or gdaltest.is_travis_branch('trunk_with_coverage'): - return 'skip' + pytest.skip() try: shutil.rmtree("tmp/test.gdb.ogrtmp") @@ -1200,59 +1046,45 @@ def ogr_fgdb_19(): gdal.PushErrorHandler() ret = ds.StartTransaction(force=True) gdal.PopErrorHandler() - if ret == 0: - gdaltest.post_reason('fail') - return 'fail' + assert ret != 0 ds = None (bPerLayerCopyingForTransaction, ds) = ogr_fgdb_19_open_update('tmp/test.gdb') - if ds.TestCapability(ogr.ODsCEmulatedTransactions) != 1: - gdaltest.post_reason('fail') - return 'fail' + assert ds.TestCapability(ogr.ODsCEmulatedTransactions) == 1 # Error case: try in non-forced mode gdal.PushErrorHandler() ret = ds.StartTransaction(force=False) gdal.PopErrorHandler() - if ret == 0: - gdaltest.post_reason('fail') - return 'fail' + assert ret != 0 # Error case: try StartTransaction() with a ExecuteSQL layer still active sql_lyr = ds.ExecuteSQL('SELECT * FROM test') gdal.PushErrorHandler() ret = ds.StartTransaction(force=True) gdal.PopErrorHandler() - if ret == 0: - gdaltest.post_reason('fail') - return 'fail' + assert ret != 0 ds.ReleaseResultSet(sql_lyr) # Error case: call CommitTransaction() while there is no transaction gdal.PushErrorHandler() ret = ds.CommitTransaction() gdal.PopErrorHandler() - if ret == 0: - gdaltest.post_reason('fail') - return 'fail' + assert ret != 0 # Error case: call RollbackTransaction() while there is no transaction gdal.PushErrorHandler() ret = ds.RollbackTransaction() gdal.PopErrorHandler() - if ret == 0: - gdaltest.post_reason('fail') - return 'fail' + assert ret != 0 # Error case: try StartTransaction() with another active connection ds2 = ogr.Open('tmp/test.gdb', update=1) gdal.PushErrorHandler() ret = ds2.StartTransaction(force=True) gdal.PopErrorHandler() - if ret == 0: - gdaltest.post_reason('fail') - return 'fail' + assert ret != 0 ds2 = None # Successful StartTransaction() finally! @@ -1263,72 +1095,49 @@ def ogr_fgdb_19(): layer_created_before_transaction = ds.CreateLayer('layer_created_before_transaction', geom_type=ogr.wkbNone) layer_created_before_transaction_defn = layer_created_before_transaction.GetLayerDefn() - if ds.StartTransaction(force=True) != 0: - gdaltest.post_reason('fail') - return 'fail' + assert ds.StartTransaction(force=True) == 0 try: os.stat('tmp/test.gdb.ogredited') except OSError: - gdaltest.post_reason('fail') - return 'fail' - try: + pytest.fail() + with pytest.raises(OSError): os.stat('tmp/test.gdb.ogrtmp') - gdaltest.post_reason('fail') - return 'fail' - except OSError: - pass + ret = lyr.CreateField(ogr.FieldDefn('foobar', ogr.OFTString)) - if ret != 0: - gdaltest.post_reason('fail') - return 'fail' + assert ret == 0 ret = lyr.DeleteField(lyr.GetLayerDefn().GetFieldIndex('foobar')) - if ret != 0: - gdaltest.post_reason('fail') - return 'fail' + assert ret == 0 gdal.PushErrorHandler() ret = lyr.CreateGeomField(ogr.GeomFieldDefn('foobar', ogr.wkbPoint)) gdal.PopErrorHandler() - if ret == 0: - gdaltest.post_reason('fail') - return 'fail' + assert ret != 0 gdal.PushErrorHandler() ret = lyr.ReorderFields([i for i in range(lyr.GetLayerDefn().GetFieldCount())]) gdal.PopErrorHandler() - if ret == 0: - gdaltest.post_reason('fail') - return 'fail' + assert ret != 0 gdal.PushErrorHandler() ret = lyr.AlterFieldDefn(0, ogr.FieldDefn('foo', ogr.OFTString), 0) gdal.PopErrorHandler() - if ret == 0: - gdaltest.post_reason('fail') - return 'fail' + assert ret != 0 f = ogr.Feature(lyr_defn) f.SetField('field_string', 'foo') lyr.CreateFeature(f) lyr.SetFeature(f) fid = f.GetFID() - if fid <= 0: - gdaltest.post_reason('fail') - print(fid) - return 'fail' + assert fid > 0 lyr.ResetReading() for i in range(fid): f = lyr.GetNextFeature() - if f.GetFID() != fid or f.GetField('field_string') != 'foo': - gdaltest.post_reason('fail') - return 'fail' + assert f.GetFID() == fid and f.GetField('field_string') == 'foo' f = lyr.GetFeature(fid) - if f.GetFID() != fid or f.GetField('field_string') != 'foo': - gdaltest.post_reason('fail') - return 'fail' + assert f.GetFID() == fid and f.GetField('field_string') == 'foo' f = ogr.Feature(layer_created_before_transaction_defn) layer_created_before_transaction.CreateFeature(f) @@ -1337,18 +1146,14 @@ def ogr_fgdb_19(): gdal.PushErrorHandler() ret = ds.StartTransaction(force=True) gdal.PopErrorHandler() - if ret == 0: - gdaltest.post_reason('fail') - return 'fail' + assert ret != 0 # Error case: try CommitTransaction() with a ExecuteSQL layer still active sql_lyr = ds.ExecuteSQL('SELECT * FROM test') gdal.PushErrorHandler() ret = ds.CommitTransaction() gdal.PopErrorHandler() - if ret == 0: - gdaltest.post_reason('fail') - return 'fail' + assert ret != 0 ds.ReleaseResultSet(sql_lyr) # Error case: try RollbackTransaction() with a ExecuteSQL layer still active @@ -1356,48 +1161,31 @@ def ogr_fgdb_19(): gdal.PushErrorHandler() ret = ds.RollbackTransaction() gdal.PopErrorHandler() - if ret == 0: - gdaltest.post_reason('fail') - return 'fail' + assert ret != 0 ds.ReleaseResultSet(sql_lyr) # Test that CommitTransaction() works - if ds.CommitTransaction() != 0: - gdaltest.post_reason('fail') - return 'fail' + assert ds.CommitTransaction() == 0 - try: + with pytest.raises(OSError): os.stat('tmp/test.gdb.ogredited') - gdaltest.post_reason('fail') - return 'fail' - except OSError: - pass + - try: + with pytest.raises(OSError): os.stat('tmp/test.gdb.ogrtmp') - gdaltest.post_reason('fail') - return 'fail' - except OSError: - pass + lst = gdal.ReadDir('tmp/test.gdb') for filename in lst: - if filename.find('.tmp') >= 0: - gdaltest.post_reason('fail') - print(lst) - return 'fail' + assert filename.find('.tmp') < 0, lst lyr_tmp = ds.GetLayer(0) lyr_tmp = ds.GetLayer(0) new_count = lyr_tmp.GetFeatureCount() - if new_count != old_count + 1: - gdaltest.post_reason('fail') - return 'fail' + assert new_count == old_count + 1 old_count = new_count - if layer_created_before_transaction.GetFeatureCount() != 1: - gdaltest.post_reason('fail') - return 'fail' + assert layer_created_before_transaction.GetFeatureCount() == 1 for i in range(ds.GetLayerCount()): if ds.GetLayer(i).GetName() == layer_created_before_transaction.GetName(): @@ -1409,24 +1197,16 @@ def ogr_fgdb_19(): lyr_count = ds.GetLayerCount() ds.CreateLayer('layer_tmp', geom_type=ogr.wkbNone) ret = ds.StartTransaction(force=True) - if ret != 0: - gdaltest.post_reason('fail') - return 'fail' + assert ret == 0 ds.DeleteLayer(ds.GetLayerCount() - 1) - if ds.CommitTransaction() != 0: - gdaltest.post_reason('fail') - return 'fail' + assert ds.CommitTransaction() == 0 new_lyr_count = ds.GetLayerCount() - if new_lyr_count != lyr_count: - gdaltest.post_reason('fail') - return 'fail' + assert new_lyr_count == lyr_count # Test that RollbackTransaction() works ret = ds.StartTransaction(force=True) - if ret != 0: - gdaltest.post_reason('fail') - return 'fail' + assert ret == 0 f = ogr.Feature(lyr_defn) lyr.CreateFeature(f) @@ -1434,38 +1214,22 @@ def ogr_fgdb_19(): layer_created_during_transaction = ds.CreateLayer('layer_created_during_transaction', geom_type=ogr.wkbNone) layer_created_during_transaction.CreateField(ogr.FieldDefn('foo', ogr.OFTString)) - if ds.RollbackTransaction() != 0: - gdaltest.post_reason('fail') - return 'fail' + assert ds.RollbackTransaction() == 0 - try: + with pytest.raises(OSError): os.stat('tmp/test.gdb.ogredited') - gdaltest.post_reason('fail') - return 'fail' - except OSError: - pass + - try: + with pytest.raises(OSError): os.stat('tmp/test.gdb.ogrtmp') - gdaltest.post_reason('fail') - return 'fail' - except OSError: - pass + - if lyr.GetFeatureCount() != old_count: - gdaltest.post_reason('fail') - print(lyr.GetFeatureCount()) - print(old_count) - return 'fail' + assert lyr.GetFeatureCount() == old_count # Cannot retrieve the layer any more from fresh - if ds.GetLayerByName('layer_created_during_transaction') is not None: - gdaltest.post_reason('fail') - return 'fail' + assert ds.GetLayerByName('layer_created_during_transaction') is None # Pointer is in ghost state - if layer_created_during_transaction.GetLayerDefn().GetFieldCount() != 0: - gdaltest.post_reason('fail') - return 'fail' + assert layer_created_during_transaction.GetLayerDefn().GetFieldCount() == 0 # Simulate an error case where StartTransaction() cannot copy backup files lyr_count = ds.GetLayerCount() @@ -1474,15 +1238,9 @@ def ogr_fgdb_19(): ret = ds.StartTransaction(force=True) gdal.PopErrorHandler() gdal.SetConfigOption('FGDB_SIMUL_FAIL', None) - if ret == 0: - gdaltest.post_reason('fail') - return 'fail' + assert ret != 0 - if ds.GetLayerCount() != lyr_count: - gdaltest.post_reason('fail') - print(lyr_count) - print(ds.GetLayerCount()) - return 'fail' + assert ds.GetLayerCount() == lyr_count # Simulate an error case where StartTransaction() cannot reopen database gdal.SetConfigOption('FGDB_SIMUL_FAIL', 'CASE2') @@ -1490,13 +1248,9 @@ def ogr_fgdb_19(): ret = ds.StartTransaction(force=True) gdal.PopErrorHandler() gdal.SetConfigOption('FGDB_SIMUL_FAIL', None) - if ret == 0: - gdaltest.post_reason('fail') - return 'fail' + assert ret != 0 - if ds.GetLayerCount() != 0: - gdaltest.post_reason('fail') - return 'fail' + assert ds.GetLayerCount() == 0 shutil.rmtree('tmp/test.gdb.ogredited') # Test method on ghost datasource and layer @@ -1568,9 +1322,7 @@ def ogr_fgdb_19(): layer_tmp = ds.CreateLayer('layer_tmp', geom_type=ogr.wkbNone) layer_tmp.CreateField(ogr.FieldDefn('foo', ogr.OFTString)) - if ds.StartTransaction(force=True) != 0: - gdaltest.post_reason('fail') - return 'fail' + assert ds.StartTransaction(force=True) == 0 ds.DeleteLayer(ds.GetLayerCount() - 1) @@ -1579,9 +1331,7 @@ def ogr_fgdb_19(): ret = ds.CommitTransaction() gdal.PopErrorHandler() gdal.SetConfigOption('FGDB_SIMUL_FAIL', None) - if ret == 0: - gdaltest.post_reason('fail') - return 'fail' + assert ret != 0 ds = None @@ -1589,10 +1339,7 @@ def ogr_fgdb_19(): lst = gdal.ReadDir('tmp/test.gdb') for filename in lst: - if filename.find('.tmp') >= 0: - gdaltest.post_reason('fail') - print(lst) - return 'fail' + assert filename.find('.tmp') < 0, lst # Test an error case where we simulate a failure in renaming # a file in original directory @@ -1603,9 +1350,7 @@ def ogr_fgdb_19(): ds.DeleteLayer(i) break - if ds.StartTransaction(force=True) != 0: - gdaltest.post_reason('fail') - return 'fail' + assert ds.StartTransaction(force=True) == 0 lyr = ds.GetLayer(0) f = lyr.GetNextFeature() @@ -1617,9 +1362,7 @@ def ogr_fgdb_19(): ret = ds.CommitTransaction() gdal.PopErrorHandler() gdal.SetConfigOption('FGDB_SIMUL_FAIL', None) - if ret == 0: - gdaltest.post_reason('fail') - return 'fail' + assert ret != 0 ds = None @@ -1627,18 +1370,13 @@ def ogr_fgdb_19(): lst = gdal.ReadDir('tmp/test.gdb') for filename in lst: - if filename.find('.tmp') >= 0: - gdaltest.post_reason('fail') - print(lst) - return 'fail' + assert filename.find('.tmp') < 0, lst # Test an error case where we simulate a failure in moving # a file into original directory (bPerLayerCopyingForTransaction, ds) = ogr_fgdb_19_open_update('tmp/test.gdb') - if ds.StartTransaction(force=True) != 0: - gdaltest.post_reason('fail') - return 'fail' + assert ds.StartTransaction(force=True) == 0 lyr = ds.GetLayer(0) f = lyr.GetNextFeature() @@ -1650,9 +1388,7 @@ def ogr_fgdb_19(): ret = ds.CommitTransaction() gdal.PopErrorHandler() gdal.SetConfigOption('FGDB_SIMUL_FAIL', None) - if ret == 0: - gdaltest.post_reason('fail') - return 'fail' + assert ret != 0 ds = None @@ -1668,9 +1404,7 @@ def ogr_fgdb_19(): for case in ('CASE4', 'CASE5'): (bPerLayerCopyingForTransaction, ds) = ogr_fgdb_19_open_update('tmp/test.gdb') - if ds.StartTransaction(force=True) != 0: - gdaltest.post_reason('fail') - return 'fail' + assert ds.StartTransaction(force=True) == 0 lyr = ds.GetLayer(0) f = lyr.GetNextFeature() @@ -1682,21 +1416,14 @@ def ogr_fgdb_19(): ret = ds.CommitTransaction() gdal.PopErrorHandler() gdal.SetConfigOption('FGDB_SIMUL_FAIL', None) - if ret != 0: - gdaltest.post_reason('fail') - print(case) - return 'fail' + assert ret == 0, case ds = None if case == 'CASE4': - try: + with pytest.raises(OSError, message=case): os.stat('tmp/test.gdb.ogredited') - gdaltest.post_reason('fail') - print(case) - return 'fail' - except OSError: - pass + else: shutil.rmtree('tmp/test.gdb.ogredited') @@ -1712,18 +1439,14 @@ def ogr_fgdb_19(): lyr = ds.GetLayer(0) lyr_defn = lyr.GetLayerDefn() - if ds.StartTransaction(force=True) != 0: - gdaltest.post_reason('fail') - return 'fail' + assert ds.StartTransaction(force=True) == 0 gdal.SetConfigOption('FGDB_SIMUL_FAIL', 'CASE1') gdal.PushErrorHandler() ret = ds.CommitTransaction() gdal.PopErrorHandler() gdal.SetConfigOption('FGDB_SIMUL_FAIL', None) - if ret == 0: - gdaltest.post_reason('fail') - return 'fail' + assert ret != 0 ds = None @@ -1732,18 +1455,14 @@ def ogr_fgdb_19(): lyr = ds.GetLayer(0) lyr_defn = lyr.GetLayerDefn() - if ds.StartTransaction(force=True) != 0: - gdaltest.post_reason('fail') - return 'fail' + assert ds.StartTransaction(force=True) == 0 gdal.SetConfigOption('FGDB_SIMUL_FAIL', 'CASE2') gdal.PushErrorHandler() ret = ds.CommitTransaction() gdal.PopErrorHandler() gdal.SetConfigOption('FGDB_SIMUL_FAIL', None) - if ret == 0: - gdaltest.post_reason('fail') - return 'fail' + assert ret != 0 ds = None os.rename('tmp/test.gdb.ogrtmp', 'tmp/test.gdb') @@ -1753,18 +1472,14 @@ def ogr_fgdb_19(): lyr = ds.GetLayer(0) lyr_defn = lyr.GetLayerDefn() - if ds.StartTransaction(force=True) != 0: - gdaltest.post_reason('fail') - return 'fail' + assert ds.StartTransaction(force=True) == 0 gdal.SetConfigOption('FGDB_SIMUL_FAIL', 'CASE3') gdal.PushErrorHandler() ret = ds.CommitTransaction() gdal.PopErrorHandler() gdal.SetConfigOption('FGDB_SIMUL_FAIL', None) - if ret != 0: - gdaltest.post_reason('fail') - return 'fail' + assert ret == 0 ds = None shutil.rmtree('tmp/test.gdb.ogrtmp') @@ -1774,22 +1489,16 @@ def ogr_fgdb_19(): lyr = ds.GetLayer(0) lyr_defn = lyr.GetLayerDefn() - if ds.StartTransaction(force=True) != 0: - gdaltest.post_reason('fail') - return 'fail' + assert ds.StartTransaction(force=True) == 0 gdal.SetConfigOption('FGDB_SIMUL_FAIL', 'CASE_REOPEN') gdal.PushErrorHandler() ret = ds.CommitTransaction() gdal.PopErrorHandler() gdal.SetConfigOption('FGDB_SIMUL_FAIL', None) - if ret == 0: - gdaltest.post_reason('fail') - return 'fail' + assert ret != 0 - if ds.GetLayerCount() != 0: - gdaltest.post_reason('fail') - return 'fail' + assert ds.GetLayerCount() == 0 ds = None @@ -1798,18 +1507,14 @@ def ogr_fgdb_19(): lyr = ds.GetLayer(0) lyr_defn = lyr.GetLayerDefn() - if ds.StartTransaction(force=True) != 0: - gdaltest.post_reason('fail') - return 'fail' + assert ds.StartTransaction(force=True) == 0 gdal.SetConfigOption('FGDB_SIMUL_FAIL', 'CASE1') gdal.PushErrorHandler() ret = ds.RollbackTransaction() gdal.PopErrorHandler() gdal.SetConfigOption('FGDB_SIMUL_FAIL', None) - if ret == 0: - gdaltest.post_reason('fail') - return 'fail' + assert ret != 0 ds = None shutil.rmtree('tmp/test.gdb.ogredited') @@ -1819,49 +1524,42 @@ def ogr_fgdb_19(): lyr = ds.GetLayer(0) lyr_defn = lyr.GetLayerDefn() - if ds.StartTransaction(force=True) != 0: - gdaltest.post_reason('fail') - return 'fail' + assert ds.StartTransaction(force=True) == 0 gdal.SetConfigOption('FGDB_SIMUL_FAIL', 'CASE2') gdal.PushErrorHandler() ret = ds.RollbackTransaction() gdal.PopErrorHandler() gdal.SetConfigOption('FGDB_SIMUL_FAIL', None) - if ret == 0: - gdaltest.post_reason('fail') - return 'fail' + assert ret != 0 - if ds.GetLayerCount() != 0: - gdaltest.post_reason('fail') - return 'fail' + assert ds.GetLayerCount() == 0 ds = None if ogrtest.openfilegdb_drv is not None: ogrtest.openfilegdb_drv.Deregister() - return 'success' - + # Same, but retry without per-layer copying optimization (in the case # this was what was tested in previous step) -def ogr_fgdb_19bis(): +def test_ogr_fgdb_19bis(): if ogrtest.fgdb_drv is None: - return 'skip' + pytest.skip() if gdaltest.is_travis_branch('ubuntu_1804') or gdaltest.is_travis_branch('ubuntu_1604') or gdaltest.is_travis_branch('trusty_clang') or gdaltest.is_travis_branch('python3') or gdaltest.is_travis_branch('trunk_with_coverage'): - return 'skip' + pytest.skip() (bPerLayerCopyingForTransaction, ds) = ogr_fgdb_19_open_update('tmp/test.gdb') del ds if not bPerLayerCopyingForTransaction: - return 'skip' + pytest.skip() gdal.SetConfigOption('FGDB_PER_LAYER_COPYING_TRANSACTION', 'FALSE') - ret = ogr_fgdb_19() + ret = test_ogr_fgdb_19() gdal.SetConfigOption('FGDB_PER_LAYER_COPYING_TRANSACTION', None) return ret @@ -1869,16 +1567,16 @@ def ogr_fgdb_19bis(): # Test CreateFeature() with user defined FID -def ogr_fgdb_20(): +def test_ogr_fgdb_20(): if ogrtest.fgdb_drv is None: - return 'skip' + pytest.skip() if ogrtest.openfilegdb_drv is None: - return 'skip' + pytest.skip() if gdaltest.is_travis_branch('ubuntu_1804') or gdaltest.is_travis_branch('ubuntu_1604') or gdaltest.is_travis_branch('trusty_clang') or gdaltest.is_travis_branch('python3') or gdaltest.is_travis_branch('trunk_with_coverage'): - return 'skip' + pytest.skip() if not os.path.exists('tmp/test.gdb'): ds = ogrtest.fgdb_drv.CreateDataSource("tmp/test.gdb") @@ -1902,17 +1600,13 @@ def ogr_fgdb_20(): f = ogr.Feature(lyr.GetLayerDefn()) f.SetField('id', 1) ret = lyr.CreateFeature(f) - if ret != 0 or f.GetFID() != 1 or lyr.GetMetadataItem('1', 'MAP_OGR_FID_TO_FGDB_FID') is not None: - gdaltest.post_reason('fail') - return 'fail' + assert ret == 0 and f.GetFID() == 1 and lyr.GetMetadataItem('1', 'MAP_OGR_FID_TO_FGDB_FID') is None # Existing FID gdal.PushErrorHandler() ret = lyr.CreateFeature(f) gdal.PopErrorHandler() - if ret == 0: - gdaltest.post_reason('fail') - return 'fail' + assert ret != 0 for invalid_fid in [-2, 0, 9876543210]: f = ogr.Feature(lyr.GetLayerDefn()) @@ -1920,19 +1614,15 @@ def ogr_fgdb_20(): gdal.PushErrorHandler() ret = lyr.CreateFeature(f) gdal.PopErrorHandler() - if ret == 0: - gdaltest.post_reason('fail') - print(invalid_fid) - return 'fail' + assert ret != 0, invalid_fid f = ogr.Feature(lyr.GetLayerDefn()) f.SetFID(2) f.SetField('id', 2) ret = lyr.CreateFeature(f) if ret != 0 or f.GetFID() != 2 or lyr.GetMetadataItem('2', 'MAP_OGR_FID_TO_FGDB_FID') is not None: - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' + pytest.fail() # OGR FID = 4, FileGDB FID = 3 f = ogr.Feature(lyr.GetLayerDefn()) @@ -1944,49 +1634,35 @@ def ogr_fgdb_20(): gdal.PushErrorHandler() ret = lyr.CreateFeature(f) gdal.PopErrorHandler() - if ret == 0: - gdaltest.post_reason('fail') - return 'fail' + assert ret != 0 ds2 = None ret = lyr.CreateFeature(f) if ret != 0 or f.GetFID() != 4 or lyr.GetMetadataItem('4', 'MAP_OGR_FID_TO_FGDB_FID') != '3': - gdaltest.post_reason('fail') f.DumpReadable() - print(lyr.GetMetadataItem('4', 'MAP_OGR_FID_TO_FGDB_FID')) - return 'fail' + pytest.fail(lyr.GetMetadataItem('4', 'MAP_OGR_FID_TO_FGDB_FID')) # Cannot open geodatabase at the moment since it is in 'FID hack mode' gdal.PushErrorHandler() ds2 = ogr.Open('tmp/test.gdb', update=1) gdal.PopErrorHandler() - if ds2 is not None: - gdaltest.post_reason('fail') - return 'fail' + assert ds2 is None ds2 = None # Existing FID, but only in OGR space gdal.PushErrorHandler() ret = lyr.CreateFeature(f) gdal.PopErrorHandler() - if ret == 0: - gdaltest.post_reason('fail') - return 'fail' + assert ret != 0 # This FID exists as a FGDB ID, but should not be user visible. f.SetFID(3) ret = lyr.SetFeature(f) - if ret != ogr.OGRERR_NON_EXISTING_FEATURE: - gdaltest.post_reason('fail') - return 'fail' + assert ret == ogr.OGRERR_NON_EXISTING_FEATURE ret = lyr.DeleteFeature(3) - if ret != ogr.OGRERR_NON_EXISTING_FEATURE: - gdaltest.post_reason('fail') - return 'fail' + assert ret == ogr.OGRERR_NON_EXISTING_FEATURE ret = lyr.GetFeature(3) - if ret is not None: - gdaltest.post_reason('fail') - return 'fail' + assert ret is None # Trying to set OGR FID = 3 --> FileGDB FID = 4 f = ogr.Feature(lyr.GetLayerDefn()) @@ -1995,9 +1671,8 @@ def ogr_fgdb_20(): ret = lyr.CreateFeature(f) if ret != 0 or f.GetFID() != 3 or lyr.GetMetadataItem('3', 'MAP_OGR_FID_TO_FGDB_FID') != '4': - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' + pytest.fail() lyr.ResetReading() expected = [(1, None), (2, None), (4, 3), (3, 4)] @@ -2007,65 +1682,44 @@ def ogr_fgdb_20(): f = lyr.GetNextFeature() else: f = lyr.GetFeature(fid) - if f is None: - gdaltest.post_reason('fail') - return 'fail' + assert f is not None if f.GetFID() != fid or f.GetField('id') != fid: - gdaltest.post_reason('fail') f.DumpReadable() - print(fid) - return 'fail' + pytest.fail(fid) got_fgdb_fid = lyr.GetMetadataItem(str(f.GetFID()), 'MAP_OGR_FID_TO_FGDB_FID') if got_fgdb_fid is None: - if fgdb_fid is not None: - gdaltest.post_reason('fail') - return 'fail' + assert fgdb_fid is None elif int(got_fgdb_fid) != fgdb_fid: - gdaltest.post_reason('fail') - print(got_fgdb_fid) print(fgdb_fid) - return 'fail' + pytest.fail(got_fgdb_fid) for fid in [-9876543210, 0, 100]: f = lyr.GetFeature(fid) if f is not None: - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' + pytest.fail() for invalid_fid in [-2, 0, 9876543210]: f = ogr.Feature(lyr.GetLayerDefn()) f.SetFID(invalid_fid) ret = lyr.SetFeature(f) - if ret != ogr.OGRERR_NON_EXISTING_FEATURE: - gdaltest.post_reason('fail') - return 'fail' + assert ret == ogr.OGRERR_NON_EXISTING_FEATURE ret = lyr.DeleteFeature(invalid_fid) - if ret != ogr.OGRERR_NON_EXISTING_FEATURE: - gdaltest.post_reason('fail') - return 'fail' + assert ret == ogr.OGRERR_NON_EXISTING_FEATURE f = lyr.GetFeature(3) f.SetField('str', '3') ret = lyr.SetFeature(f) - if ret != 0: - gdaltest.post_reason('fail') - return 'fail' + assert ret == 0 f = lyr.GetFeature(3) - if f.GetField('str') != '3': - gdaltest.post_reason('fail') - return 'fail' + assert f.GetField('str') == '3' ret = lyr.DeleteFeature(1) - if ret != 0: - gdaltest.post_reason('fail') - return 'fail' + assert ret == 0 ret = lyr.DeleteFeature(3) - if ret != 0: - gdaltest.post_reason('fail') - return 'fail' + assert ret == 0 for (fid, fgdb_fid) in [(3, 5), (2049, 6), (10, 7), (7, 8), (9, None), (8, 10), (12, 11)]: f = ogr.Feature(lyr.GetLayerDefn()) @@ -2073,19 +1727,16 @@ def ogr_fgdb_20(): f.SetField('id', fid) ret = lyr.CreateFeature(f) if ret != 0 or f.GetFID() != fid or str(lyr.GetMetadataItem(str(fid), 'MAP_OGR_FID_TO_FGDB_FID')) != str(fgdb_fid): - gdaltest.post_reason('fail') f.DumpReadable() - print(fid) print(lyr.GetMetadataItem(str(fid), 'MAP_OGR_FID_TO_FGDB_FID')) - return 'fail' + pytest.fail(fid) # Normally 12 should be attributed, but it has already been reserved f = ogr.Feature(lyr.GetLayerDefn()) ret = lyr.CreateFeature(f) if ret != 0 or f.GetFID() != 13: - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' + pytest.fail() f.SetField('id', f.GetFID()) lyr.SetFeature(f) @@ -2093,32 +1744,26 @@ def ogr_fgdb_20(): expected = [(2, None), (4, 3), (3, 5), (2049, 6), (10, 7), (7, 8), (9, None), (8, 10)] for (fid, fgdb_fid) in expected: f = lyr.GetNextFeature() - if f is None: - gdaltest.post_reason('fail') - return 'fail' + assert f is not None if f.GetFID() != fid or f.GetField('id') != fid or str(lyr.GetMetadataItem(str(fid), 'MAP_OGR_FID_TO_FGDB_FID')) != str(fgdb_fid): - gdaltest.post_reason('fail') f.DumpReadable() - print(fid) print(lyr.GetMetadataItem(str(fid), 'MAP_OGR_FID_TO_FGDB_FID')) - return 'fail' + pytest.fail(fid) lyr.SetAttributeFilter('id = 3') lyr.ResetReading() f = lyr.GetNextFeature() if f.GetFID() != 3: - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' + pytest.fail() # This will cause a resync of indexes lyr.SetAttributeFilter('OBJECTID = 3') lyr.ResetReading() f = lyr.GetNextFeature() if f.GetFID() != 3: - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' + pytest.fail() # No sparse pages lyr = ds.CreateLayer('ogr_fgdb_20_simple', geom_type=ogr.wkbNone) @@ -2133,9 +1778,8 @@ def ogr_fgdb_20(): sql_lyr = ds.ExecuteSQL('SELECT * FROM ogr_fgdb_20_simple') f = sql_lyr.GetNextFeature() if f.GetFID() != 2: - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' + pytest.fail() # Do not allow user set FID while a select layer is in progress f = ogr.Feature(lyr.GetLayerDefn()) @@ -2144,9 +1788,7 @@ def ogr_fgdb_20(): gdal.PushErrorHandler() ret = lyr.CreateFeature(f) gdal.PopErrorHandler() - if ret == 0: - gdaltest.post_reason('fail') - return 'fail' + assert ret != 0 ds.ReleaseResultSet(sql_lyr) @@ -2184,46 +1826,30 @@ def ogr_fgdb_20(): for update in [0, 1]: ds = ogr.Open('tmp/test.gdb', update=update) lyr = ds.GetLayerByName('ogr_fgdb_20') - if lyr.GetFeatureCount() != 10: - gdaltest.post_reason('fail') - print(lyr.GetFeatureCount()) - return 'fail' + assert lyr.GetFeatureCount() == 10 lyr.ResetReading() expected = [2, 3, 4, 7, 8, 9, 10, 12, 13, 2049] for fid in expected: f = lyr.GetNextFeature() - if gdal.GetLastErrorType() != 0: - gdaltest.post_reason('fail') - return 'fail' - if f is None: - gdaltest.post_reason('fail') - print(fid) - return 'fail' + assert gdal.GetLastErrorType() == 0 + assert f is not None, fid if f.GetFID() != fid or f.GetField('id') != fid: - gdaltest.post_reason('fail') f.DumpReadable() - print(fid) - return 'fail' + pytest.fail(fid) for fid in expected: lyr.SetAttributeFilter('id = %d' % fid) lyr.ResetReading() f = lyr.GetNextFeature() if f.GetFID() != fid or f.GetField('id') != fid: - gdaltest.post_reason('fail') f.DumpReadable() - print(fid) - return 'fail' + pytest.fail(fid) lyr = ds.GetLayerByName('ogr_fgdb_20_simple') f = lyr.GetNextFeature() - if f.GetFID() != 2: - gdaltest.post_reason('fail') - return 'fail' + assert f.GetFID() == 2 f = lyr.GetNextFeature() - if f.GetFID() != 3: - gdaltest.post_reason('fail') - return 'fail' + assert f.GetFID() == 3 # Check attribute index lyr = ds.GetLayerByName('ogr_fgdb_20_indexes') @@ -2232,11 +1858,7 @@ def ogr_fgdb_20(): lyr.SetAttributeFilter('id = %d' % fid) lyr.ResetReading() f = lyr.GetNextFeature() - if f.GetFID() != fid: - gdaltest.post_reason('fail') - print(f.GetFID()) - print(fid) - return 'fail' + assert f.GetFID() == fid # Check spatial index lyr.SetAttributeFilter(None) @@ -2246,11 +1868,7 @@ def ogr_fgdb_20(): lyr.SetSpatialFilterRect(i - 0.01, -0.01, i + 0.01, 0.01) lyr.ResetReading() f = lyr.GetNextFeature() - if f.GetFID() != fid: - gdaltest.post_reason('fail') - print(f.GetFID()) - print(fid) - return 'fail' + assert f.GetFID() == fid # Insert new features ds = ogr.Open('tmp/test.gdb', update=1) @@ -2261,10 +1879,8 @@ def ogr_fgdb_20(): f.SetField('id', fid) ret = lyr.CreateFeature(f) if ret != 0 or f.GetFID() != fid or str(lyr.GetMetadataItem(str(fid), 'MAP_OGR_FID_TO_FGDB_FID')) != str(fgdb_fid): - gdaltest.post_reason('fail') f.DumpReadable() - print(lyr.GetMetadataItem(str(fid), 'MAP_OGR_FID_TO_FGDB_FID')) - return 'fail' + pytest.fail(lyr.GetMetadataItem(str(fid), 'MAP_OGR_FID_TO_FGDB_FID')) ds = None @@ -2278,10 +1894,8 @@ def ogr_fgdb_20(): f.SetField('id', fid) ret = lyr.CreateFeature(f) if ret != 0 or f.GetFID() != fid or lyr.GetMetadataItem(str(fid), 'MAP_OGR_FID_TO_FGDB_FID') != str(fgdb_fid): - gdaltest.post_reason('fail') f.DumpReadable() - print(lyr.GetMetadataItem(str(fid), 'MAP_OGR_FID_TO_FGDB_FID')) - return 'fail' + pytest.fail(lyr.GetMetadataItem(str(fid), 'MAP_OGR_FID_TO_FGDB_FID')) ds = None # Check consistency after re-opening @@ -2289,26 +1903,16 @@ def ogr_fgdb_20(): for update in [0, 1]: ds = ogr.Open('tmp/test.gdb', update=update) lyr = ds.GetLayerByName('ogr_fgdb_20') - if lyr.GetFeatureCount() != 16: - gdaltest.post_reason('fail') - print(lyr.GetFeatureCount()) - return 'fail' + assert lyr.GetFeatureCount() == 16 lyr.ResetReading() expected = [2, 3, 4, 7, 8, 9, 10, 12, 13, 2049, 8191, 16384, 1000000, 1000001, 10000000, 10000001] for fid in expected: f = lyr.GetNextFeature() - if gdal.GetLastErrorType() != 0: - gdaltest.post_reason('fail') - return 'fail' - if f is None: - gdaltest.post_reason('fail') - print(fid) - return 'fail' + assert gdal.GetLastErrorType() == 0 + assert f is not None, fid if f.GetFID() != fid or f.GetField('id') != fid: - gdaltest.post_reason('fail') f.DumpReadable() - print(fid) - return 'fail' + pytest.fail(fid) # Simulate different errors when database reopening is done # to sync ids @@ -2333,70 +1937,45 @@ def ogr_fgdb_20(): gdal.SetConfigOption('FGDB_SIMUL_FAIL_REOPEN', None) gdal.PopErrorHandler() if case == 'CASE3': - if sql_lyr is None: - gdaltest.post_reason('fail') - print(case) - return 'fail' + assert sql_lyr is not None, case ds.ReleaseResultSet(sql_lyr) else: - if sql_lyr is not None: - gdaltest.post_reason('fail') - print(case) - return 'fail' + assert sql_lyr is None, case # Everything will fail, but hopefully without crashing lyr.ResetReading() - if lyr.GetNextFeature() is not None: - gdaltest.post_reason('fail') - return 'fail' - if lyr.GetFeature(1) is not None: - gdaltest.post_reason('fail') - return 'fail' - if lyr.DeleteFeature(1) == 0: - gdaltest.post_reason('fail') - return 'fail' - if lyr.CreateFeature(f) == 0: - gdaltest.post_reason('fail') - return 'fail' - if lyr.SetFeature(f) == 0: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.GetNextFeature() is None + assert lyr.GetFeature(1) is None + assert lyr.DeleteFeature(1) != 0 + assert lyr.CreateFeature(f) != 0 + assert lyr.SetFeature(f) != 0 if case != 'CASE3': - if ds.CreateLayer('bar', geom_type=ogr.wkbNone) is not None: - gdaltest.post_reason('fail') - return 'fail' - if ds.DeleteLayer(0) == 0: - gdaltest.post_reason('fail') - return 'fail' + assert ds.CreateLayer('bar', geom_type=ogr.wkbNone) is None + assert ds.DeleteLayer(0) != 0 sql_lyr = ds.ExecuteSQL('SELECT * FROM foo') - if case != 'CASE3' and sql_lyr is not None: - gdaltest.post_reason('fail') - print(case) - return 'fail' + assert case == 'CASE3' or sql_lyr is None ds.ReleaseResultSet(sql_lyr) ds = None # sys.exit(0) - return 'success' - + ############################################################################### # Test M support -def ogr_fgdb_21(): +def test_ogr_fgdb_21(): if ogrtest.fgdb_drv is None: - return 'skip' + pytest.skip() if not ogr_fgdb_is_sdk_1_4_or_later(): - print('SDK 1.4 required') - return 'skip' + pytest.skip('SDK 1.4 required') # Fails on MULTIPOINT ZM if gdaltest.is_travis_branch('ubuntu_1804') or gdaltest.is_travis_branch('ubuntu_1604'): - return 'skip' + pytest.skip() try: shutil.rmtree("tmp/test.gdb") @@ -2446,11 +2025,7 @@ def ogr_fgdb_21(): elif expected_geom_type == ogr.wkbPolygonZM: expected_geom_type = ogr.wkbMultiPolygonZM - if lyr.GetGeomType() != expected_geom_type: - gdaltest.post_reason('fail') - print(data) - print(lyr.GetGeomType()) - return 'fail' + assert lyr.GetGeomType() == expected_geom_type, data feat = lyr.GetNextFeature() try: expected_wkt = data[3] @@ -2458,26 +2033,21 @@ def ogr_fgdb_21(): expected_wkt = data[2] if expected_wkt is None: if feat.GetGeometryRef() is not None: - gdaltest.post_reason('fail') - print(data) feat.DumpReadable() - return 'fail' + pytest.fail(data) elif ogrtest.check_feature_geometry(feat, expected_wkt) != 0: - gdaltest.post_reason('fail') - print(data) feat.DumpReadable() - return 'fail' - - return 'success' + pytest.fail(data) + ############################################################################### # Read curves -def ogr_fgdb_22(): +def test_ogr_fgdb_22(): if ogrtest.fgdb_drv is None: - return 'skip' + pytest.skip() ds = ogr.Open('data/curves.gdb') lyr = ds.GetLayerByName('line') @@ -2486,10 +2056,8 @@ def ogr_fgdb_22(): for f in lyr: f_ref = lyr_ref.GetNextFeature() if ogrtest.check_feature_geometry(f, f_ref.GetGeometryRef()) != 0: - gdaltest.post_reason('fail') print(f.GetGeometryRef().ExportToWkt()) - print(f_ref.GetGeometryRef().ExportToWkt()) - return 'fail' + pytest.fail(f_ref.GetGeometryRef().ExportToWkt()) lyr = ds.GetLayerByName('polygon') ds_ref = ogr.Open('data/curves_polygon.csv') @@ -2497,10 +2065,8 @@ def ogr_fgdb_22(): for f in lyr: f_ref = lyr_ref.GetNextFeature() if ogrtest.check_feature_geometry(f, f_ref.GetGeometryRef()) != 0: - gdaltest.post_reason('fail') print(f.GetGeometryRef().ExportToWkt()) - print(f_ref.GetGeometryRef().ExportToWkt()) - return 'fail' + pytest.fail(f_ref.GetGeometryRef().ExportToWkt()) ds = ogr.Open('data/curve_circle_by_center.gdb') lyr = ds.GetLayer(0) @@ -2509,36 +2075,30 @@ def ogr_fgdb_22(): for f in lyr: f_ref = lyr_ref.GetNextFeature() if ogrtest.check_feature_geometry(f, f_ref.GetGeometryRef()) != 0: - gdaltest.post_reason('fail') print(f.GetGeometryRef().ExportToWkt()) - print(f_ref.GetGeometryRef().ExportToWkt()) - return 'fail' - - return 'success' + pytest.fail(f_ref.GetGeometryRef().ExportToWkt()) + ############################################################################### # Test opening '.' -def ogr_fgdb_23(): +def test_ogr_fgdb_23(): if ogrtest.fgdb_drv is None: - return 'skip' + pytest.skip() os.chdir('data/curves.gdb') ds = ogr.Open('.') os.chdir('../..') - if ds is None: - return 'fail' - - return 'success' + assert ds is not None ############################################################################### # Read polygons with M component where the M of the closing point is not the # one of the starting point (#7017) -def ogr_fgdb_24(): +def test_ogr_fgdb_24(): ds = ogr.Open('data/filegdb_polygonzm_m_not_closing_with_curves.gdb') lyr = ds.GetLayer(0) @@ -2547,10 +2107,8 @@ def ogr_fgdb_24(): for f in lyr: f_ref = lyr_ref.GetNextFeature() if ogrtest.check_feature_geometry(f, f_ref.GetGeometryRef()) != 0: - gdaltest.post_reason('fail') print(f.GetGeometryRef().ExportToIsoWkt()) - print(f_ref.GetGeometryRef().ExportToIsoWkt()) - return 'fail' + pytest.fail(f_ref.GetGeometryRef().ExportToIsoWkt()) ds = ogr.Open('data/filegdb_polygonzm_nan_m_with_curves.gdb') lyr = ds.GetLayer(0) @@ -2559,52 +2117,42 @@ def ogr_fgdb_24(): for f in lyr: f_ref = lyr_ref.GetNextFeature() if ogrtest.check_feature_geometry(f, f_ref.GetGeometryRef()) != 0: - gdaltest.post_reason('fail') print(f.GetGeometryRef().ExportToIsoWkt()) - print(f_ref.GetGeometryRef().ExportToIsoWkt()) - return 'fail' - - return 'success' + pytest.fail(f_ref.GetGeometryRef().ExportToIsoWkt()) + ############################################################################### # Test selecting FID column with OGRSQL -def ogr_fgdb_25(): +def test_ogr_fgdb_25(): ds = ogr.Open('data/curves.gdb') sql_lyr = ds.ExecuteSQL('SELECT OBJECTID FROM polygon WHERE OBJECTID = 2') - if sql_lyr is None: - gdaltest.post_reason('fail') - return 'fail' + assert sql_lyr is not None f = sql_lyr.GetNextFeature() if f.GetFID() != 2: - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' + pytest.fail() f = sql_lyr.GetNextFeature() - if f is not None: - gdaltest.post_reason('fail') - return 'fail' + assert f is None ds.ReleaseResultSet(sql_lyr) lyr = ds.GetLayerByName('polygon') lyr.SetAttributeFilter('OBJECTID = 2') f = lyr.GetNextFeature() if f.GetFID() != 2: - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' - - return 'success' + pytest.fail() + ############################################################################### # Cleanup -def ogr_fgdb_cleanup(): +def test_ogr_fgdb_cleanup(): if ogrtest.fgdb_drv is None: - return 'skip' + pytest.skip() try: shutil.rmtree("tmp/test.gdb") @@ -2629,53 +2177,3 @@ def ogr_fgdb_cleanup(): # Force OpenFileGDB first ogrtest.openfilegdb_drv.Register() ogrtest.fgdb_drv.Register() - - return 'success' - - -gdaltest_list = [ - ogr_fgdb_init, - ogr_fgdb_1, - ogr_fgdb_DeleteField, - ogr_fgdb_2, - ogr_fgdb_3, - ogr_fgdb_sql, - ogr_fgdb_4, - ogr_fgdb_5, - ogr_fgdb_6, - ogr_fgdb_7, - ogr_fgdb_8, - ogr_fgdb_9, - ogr_fgdb_10, - ogr_fgdb_11, - ogr_fgdb_12, - ogr_fgdb_13, - ogr_fgdb_14, - ogr_fgdb_15, - ogr_fgdb_16, - ogr_fgdb_17, - ogr_fgdb_18, - ogr_fgdb_19, - ogr_fgdb_19bis, - ogr_fgdb_20, - ogr_fgdb_21, - ogr_fgdb_22, - ogr_fgdb_23, - ogr_fgdb_24, - ogr_fgdb_25, - ogr_fgdb_cleanup, -] - -disabled_gdaltest_list = [ - ogr_fgdb_init, - ogr_fgdb_20, - ogr_fgdb_cleanup -] - -if __name__ == '__main__': - - gdaltest.setup_run('ogr_fgdb') - - gdaltest.run_tests(gdaltest_list) - - sys.exit(gdaltest.summarize()) diff --git a/autotest/ogr/ogr_fgdb_stress_test.py b/autotest/ogr/ogr_fgdb_stress_test.py index cd9f262ecfdd..8a286316ecca 100755 --- a/autotest/ogr/ogr_fgdb_stress_test.py +++ b/autotest/ogr/ogr_fgdb_stress_test.py @@ -31,22 +31,21 @@ import random -import sys import shutil -sys.path.append('../pymod') -import gdaltest import ogrtest from osgeo import gdal from osgeo import ogr from osgeo import osr +import pytest ############################################################################### # Test if driver is available -def ogr_fgdb_stress_test_init(): +@pytest.mark.skip() +def test_ogr_fgdb_stress_init(): ogrtest.fgdb_drv = None ogrtest.openfilegdb_drv = None @@ -57,11 +56,11 @@ def ogr_fgdb_stress_test_init(): ogrtest.openfilegdb_drv = ogr.GetDriverByName('OpenFileGDB') if ogrtest.fgdb_drv is None: - return 'skip' + pytest.skip() if ogrtest.reference_drv is None: - return 'skip' + pytest.skip() if ogrtest.openfilegdb_drv is None: - return 'skip' + pytest.skip() try: shutil.rmtree("tmp/test.gdb") @@ -70,15 +69,14 @@ def ogr_fgdb_stress_test_init(): gdal.Unlink("tmp/test." + ogrtest.reference_ext) - return 'success' - ############################################################################### # Generate databases from random operations -def ogr_fgdb_stress_test_1(): +@pytest.mark.skip() +def test_ogr_fgdb_stress_1(): if ogrtest.fgdb_drv is None: - return 'skip' + pytest.skip() verbose = False @@ -126,10 +124,7 @@ def ogr_fgdb_stress_test_1(): # So to ensure lyr_ref will use the same FID as the tested layer fid = f.GetFID() # print("created %d" % fid) - if ret[0] != ret[1]: - gdaltest.post_reason('fail') - print(ret) - return 'fail' + assert ret[0] == ret[1] if ret[0] == 0: nfeatures_created += 1 # For some odd reason, the .spx file is no longer updated when doing @@ -148,10 +143,7 @@ def ogr_fgdb_stress_test_1(): # gdal.PushErrorHandler() ret.append(lyr.SetFeature(f)) # gdal.PopErrorHandler() - if ret[0] != ret[1]: - gdaltest.post_reason('fail') - print(ret) - return 'fail' + assert ret[0] == ret[1] # Same for DeleteFeature() elif nfeatures_created >= 2: ret = [] @@ -162,23 +154,20 @@ def ogr_fgdb_stress_test_1(): # gdal.PushErrorHandler() ret.append(lyr.DeleteFeature(fid)) # gdal.PopErrorHandler() - if ret[0] != ret[1]: - gdaltest.post_reason('fail') - print(ret) - return 'fail' + assert ret[0] == ret[1] if in_transaction: ds_test.CommitTransaction() - return 'success' - + ############################################################################### # Compare databases -def ogr_fgdb_stress_test_2(): +@pytest.mark.skip() +def test_ogr_fgdb_stress_2(): if ogrtest.fgdb_drv is None: - return 'skip' + pytest.skip() ds_test = ogr.Open('tmp/test.gdb') ds_ref = ogr.Open('tmp/test.' + ogrtest.reference_ext) @@ -189,40 +178,32 @@ def ogr_fgdb_stress_test_2(): while True: f_test = lyr_test.GetNextFeature() f_ref = lyr_ref.GetNextFeature() - if (f_test is None and f_ref is not None) or (f_test is not None and f_ref is None): - gdaltest.post_reason('fail') - return 'fail' + assert not (f_test is None and f_ref is not None) or (f_test is not None and f_ref is None) if f_test is None: break if f_test.GetFID() != f_ref.GetFID() or \ f_test['str'] != f_ref['str'] or \ ogrtest.check_feature_geometry(f_test, f_ref.GetGeometryRef()) != 0: - gdaltest.post_reason('fail') f_test.DumpReadable() f_ref.DumpReadable() - return 'fail' + pytest.fail() for val in range(1000): lyr_test.SetAttributeFilter("str = '%d'" % val) lyr_ref.SetAttributeFilter("str = '%d'" % val) - if lyr_test.GetFeatureCount() != lyr_ref.GetFeatureCount(): - gdaltest.post_reason('fail') - print(val) - print(lyr_test.GetFeatureCount()) - print(lyr_ref.GetFeatureCount()) - return 'fail' + assert lyr_test.GetFeatureCount() == lyr_ref.GetFeatureCount(), val # sys.exit(0) - return 'success' - + ############################################################################### # Cleanup -def ogr_fgdb_stress_test_cleanup(): +@pytest.mark.skip() +def test_ogr_fgdb_stress_cleanup(): if ogrtest.fgdb_drv is None: - return 'skip' + pytest.skip() try: shutil.rmtree("tmp/test.gdb") @@ -230,22 +211,3 @@ def ogr_fgdb_stress_test_cleanup(): pass gdal.Unlink("tmp/test." + ogrtest.reference_ext) - - return 'success' - - -# Do nothing in whole run of the suite -gdaltest_list = [] - -explicit_gdaltest_list = [ogr_fgdb_stress_test_init, - ogr_fgdb_stress_test_1, - ogr_fgdb_stress_test_2, - ogr_fgdb_stress_test_cleanup] - -if __name__ == '__main__': - - gdaltest.setup_run('ogr_fgdb_stress_test') - - gdaltest.run_tests(explicit_gdaltest_list) - - sys.exit(gdaltest.summarize()) diff --git a/autotest/ogr/ogr_geoconcept.py b/autotest/ogr/ogr_geoconcept.py index 102ddacf7dc5..25f9e18bbcf9 100755 --- a/autotest/ogr/ogr_geoconcept.py +++ b/autotest/ogr/ogr_geoconcept.py @@ -30,38 +30,30 @@ ############################################################################### import os -import sys -sys.path.append('../pymod') import gdaltest import ogrtest from osgeo import ogr from osgeo import osr +import pytest ############################################################################### # Simple read test of known file. -def ogr_gxt_1(): +def test_ogr_gxt_1(): gdaltest.gxt_ds = ogr.Open('data/expected_000_GRD.gxt') - if gdaltest.gxt_ds is None: - return 'fail' + assert gdaltest.gxt_ds is not None - if gdaltest.gxt_ds.GetLayerCount() != 1: - gdaltest.post_reason('Got wrong layer count.') - return 'fail' + assert gdaltest.gxt_ds.GetLayerCount() == 1, 'Got wrong layer count.' lyr = gdaltest.gxt_ds.GetLayer(0) - if lyr.GetName() != '000_GRD.000_GRD': - gdaltest.post_reason('got unexpected layer name.') - return 'fail' + assert lyr.GetName() == '000_GRD.000_GRD', 'got unexpected layer name.' - if lyr.GetFeatureCount() != 10: - gdaltest.post_reason('got wrong feature count.') - return 'fail' + assert lyr.GetFeatureCount() == 10, 'got wrong feature count.' expect = ['000-2007-0050-7130-LAMB93', '000-2007-0595-7130-LAMB93', @@ -75,50 +67,37 @@ def ogr_gxt_1(): '000-2007-0050-6585-LAMB93'] tr = ogrtest.check_features_against_list(lyr, 'idSel', expect) - if not tr: - return 'fail' + assert tr lyr.ResetReading() feat = lyr.GetNextFeature() - if ogrtest.check_feature_geometry(feat, + assert (ogrtest.check_feature_geometry(feat, 'MULTIPOLYGON (((50000 7130000,600000 7130000,600000 6580000,50000 6580000,50000 7130000)))', - max_error=0.000000001) != 0: - return 'fail' + max_error=0.000000001) == 0) srs = osr.SpatialReference() srs.SetFromUserInput('PROJCS["Lambert 93",GEOGCS["unnamed",DATUM["ITRS-89",SPHEROID["GRS 80",6378137,298.257222099657],TOWGS84[0,0,0,0,0,0,0]],PRIMEM["Greenwich",0],UNIT["degree",0.0174532925199433]],PROJECTION["Lambert_Conformal_Conic_2SP"],PARAMETER["standard_parallel_1",44],PARAMETER["standard_parallel_2",49],PARAMETER["latitude_of_origin",46.5],PARAMETER["central_meridian",3],PARAMETER["false_easting",700000],PARAMETER["false_northing",6600000]]') - if not lyr.GetSpatialRef().IsSame(srs): - gdaltest.post_reason('SRS is not the one expected.') - return 'fail' - - return 'success' + assert lyr.GetSpatialRef().IsSame(srs), 'SRS is not the one expected.' ############################################################################### # Similar test than previous one with TAB separator. -def ogr_gxt_2(): +def test_ogr_gxt_2(): gdaltest.gxt_ds = ogr.Open('data/expected_000_GRD_TAB.txt') - if gdaltest.gxt_ds is None: - return 'fail' + assert gdaltest.gxt_ds is not None - if gdaltest.gxt_ds.GetLayerCount() != 1: - gdaltest.post_reason('Got wrong layer count.') - return 'fail' + assert gdaltest.gxt_ds.GetLayerCount() == 1, 'Got wrong layer count.' lyr = gdaltest.gxt_ds.GetLayer(0) - if lyr.GetName() != '000_GRD.000_GRD': - gdaltest.post_reason('got unexpected layer name.') - return 'fail' + assert lyr.GetName() == '000_GRD.000_GRD', 'got unexpected layer name.' - if lyr.GetFeatureCount() != 5: - gdaltest.post_reason('got wrong feature count.') - return 'fail' + assert lyr.GetFeatureCount() == 5, 'got wrong feature count.' expect = ['000-2007-0050-7130-LAMB93', '000-2007-0595-7130-LAMB93', @@ -127,25 +106,21 @@ def ogr_gxt_2(): '000-2007-0050-6585-LAMB93'] tr = ogrtest.check_features_against_list(lyr, 'idSel', expect) - if not tr: - return 'fail' + assert tr lyr.ResetReading() feat = lyr.GetNextFeature() - if ogrtest.check_feature_geometry(feat, + assert (ogrtest.check_feature_geometry(feat, 'MULTIPOLYGON (((50000 7130000,600000 7130000,600000 6580000,50000 6580000,50000 7130000)))', - max_error=0.000000001) != 0: - return 'fail' - - return 'success' + max_error=0.000000001) == 0) ############################################################################### # Read a GXT file containing 2 points, duplicate it, and check the newly written file -def ogr_gxt_3(): +def test_ogr_gxt_3(): gdaltest.gxt_ds = None @@ -177,9 +152,7 @@ def ogr_gxt_3(): feat = src_lyr.GetNextFeature() while feat is not None: dst_feat.SetFrom(feat) - if gxt_lyr.CreateFeature(dst_feat) != 0: - gdaltest.post_reason('CreateFeature failed.') - return 'fail' + assert gxt_lyr.CreateFeature(dst_feat) == 0, 'CreateFeature failed.' feat = src_lyr.GetNextFeature() @@ -189,53 +162,44 @@ def ogr_gxt_3(): gdaltest.gxt_ds = ogr.Open('tmp/tmp.gxt') gxt_lyr = gdaltest.gxt_ds.GetLayerByName('points.points') - if not gxt_lyr.GetSpatialRef().IsSame(srs): - gdaltest.post_reason('Output SRS is not the one expected.') - return 'fail' + assert gxt_lyr.GetSpatialRef().IsSame(srs), 'Output SRS is not the one expected.' expect = ['PID1', 'PID2'] tr = ogrtest.check_features_against_list(gxt_lyr, 'Primary_ID', expect) - if not tr: - return 'fail' + assert tr gxt_lyr.ResetReading() expect = ['SID1', 'SID2'] tr = ogrtest.check_features_against_list(gxt_lyr, 'Secondary_ID', expect) - if not tr: - return 'fail' + assert tr gxt_lyr.ResetReading() expect = ['TID1', None] tr = ogrtest.check_features_against_list(gxt_lyr, 'Third_ID', expect) - if not tr: - return 'fail' + assert tr gxt_lyr.ResetReading() feat = gxt_lyr.GetNextFeature() - if ogrtest.check_feature_geometry(feat, 'POINT(0 1)', - max_error=0.000000001) != 0: - return 'fail' + assert (ogrtest.check_feature_geometry(feat, 'POINT(0 1)', + max_error=0.000000001) == 0) feat = gxt_lyr.GetNextFeature() - if ogrtest.check_feature_geometry(feat, 'POINT(2 3)', - max_error=0.000000001) != 0: - return 'fail' - - return 'success' + assert (ogrtest.check_feature_geometry(feat, 'POINT(2 3)', + max_error=0.000000001) == 0) ############################################################################### # -def ogr_gxt_multipolygon_singlepart_nohole(): +def test_ogr_gxt_multipolygon_singlepart_nohole(): ds = ogr.Open('data/geoconcept_multipolygon_singlepart_nohole.txt') lyr = ds.GetLayer(0) @@ -244,18 +208,17 @@ def ogr_gxt_multipolygon_singlepart_nohole(): if ogrtest.check_feature_geometry(feat, 'MULTIPOLYGON (((0 0,0 1,1 1,1 0,0 0)))', max_error=0.000000001) != 0: feat.DumpReadable() - return 'fail' - - return 'success' + pytest.fail() + ############################################################################### # -def ogr_gxt_multipolygon_singlepart_hole(): +def test_ogr_gxt_multipolygon_singlepart_hole(): if not ogrtest.have_geos(): - return 'skip' + pytest.skip() ds = ogr.Open('data/geoconcept_multipolygon_singlepart_hole.txt') lyr = ds.GetLayer(0) @@ -264,18 +227,17 @@ def ogr_gxt_multipolygon_singlepart_hole(): if ogrtest.check_feature_geometry(feat, 'MULTIPOLYGON (((0 0,0 1,1 1,1 0,0 0),(0.1 0.1,0.1 0.9,0.9 0.9,0.1 0.1)))', max_error=0.000000001) != 0: feat.DumpReadable() - return 'fail' - - return 'success' + pytest.fail() + ############################################################################### # -def ogr_gxt_multipolygon_twoparts_second_with_hole(): +def test_ogr_gxt_multipolygon_twoparts_second_with_hole(): if not ogrtest.have_geos(): - return 'skip' + pytest.skip() ds = ogr.Open('data/geoconcept_multipolygon_twoparts_second_with_hole.txt') lyr = ds.GetLayer(0) @@ -284,18 +246,17 @@ def ogr_gxt_multipolygon_twoparts_second_with_hole(): if ogrtest.check_feature_geometry(feat, 'MULTIPOLYGON (((-10 -10,-10 -9,-9 -9,-10 -10)),((0 0,0 1,1 1,1 0,0 0),(0.1 0.1,0.1 0.9,0.9 0.9,0.1 0.1)))', max_error=0.000000001) != 0: feat.DumpReadable() - return 'fail' - - return 'success' + pytest.fail() + ############################################################################### # -def ogr_gxt_line(): +def test_ogr_gxt_line(): if not ogrtest.have_geos(): - return 'skip' + pytest.skip() ds = ogr.Open('data/line.gxt') lyr = ds.GetLayer(0) @@ -304,39 +265,20 @@ def ogr_gxt_line(): if ogrtest.check_feature_geometry(feat, 'LINESTRING (440720 3751320,441920 3750120)', max_error=0.000000001) != 0: feat.DumpReadable() - return 'fail' - - return 'success' + pytest.fail() + ############################################################################### # -def ogr_gxt_cleanup(): +def test_ogr_gxt_cleanup(): gdaltest.gxt_ds = None try: os.remove('tmp/tmp.gxt') except OSError: pass - return 'success' - - -gdaltest_list = [ - ogr_gxt_1, - ogr_gxt_2, - ogr_gxt_3, - ogr_gxt_multipolygon_singlepart_nohole, - ogr_gxt_multipolygon_singlepart_hole, - ogr_gxt_multipolygon_twoparts_second_with_hole, - ogr_gxt_line, - ogr_gxt_cleanup, - None] - -if __name__ == '__main__': - - gdaltest.setup_run('ogr_gxt') + - gdaltest.run_tests(gdaltest_list) - sys.exit(gdaltest.summarize()) diff --git a/autotest/ogr/ogr_geojson.py b/autotest/ogr/ogr_geojson.py index 6ed3b96a0798..6f38468ff64d 100755 --- a/autotest/ogr/ogr_geojson.py +++ b/autotest/ogr/ogr_geojson.py @@ -31,9 +31,7 @@ import json import math import os -import sys -sys.path.append('../pymod') from osgeo import osr from osgeo import ogr @@ -41,6 +39,7 @@ import gdaltest import ogrtest +import pytest ############################################################################### # Test utilities @@ -204,253 +203,190 @@ def copy_shape_to_geojson(gjname, compress=None): # Find GeoJSON driver -def ogr_geojson_1(): +def test_ogr_geojson_1(): gdaltest.geojson_drv = ogr.GetDriverByName('GeoJSON') if gdaltest.geojson_drv is not None: - return 'success' - return 'fail' + return + pytest.fail() ############################################################################### # Test file-based DS with standalone "Point" feature object. -def ogr_geojson_2(): +def test_ogr_geojson_2(): if gdaltest.geojson_drv is None: - return 'skip' + pytest.skip() ds = ogr.Open('data/point.geojson') - if ds is None: - gdaltest.post_reason('Failed to open datasource') - return 'fail' + assert ds is not None, 'Failed to open datasource' - if ds.GetLayerCount() is not 1: - gdaltest.post_reason('Wrong number of layers') - return 'fail' + assert ds.GetLayerCount() is 1, 'Wrong number of layers' lyr = ds.GetLayerByName('point') - if lyr is None: - gdaltest.post_reason('Missing layer called point') - return 'fail' + assert lyr is not None, 'Missing layer called point' extent = (100.0, 100.0, 0.0, 0.0) rc = validate_layer(lyr, 'point', 1, ogr.wkbPoint, 0, extent) - if not rc: - return 'fail' + assert rc lyr = None - return 'success' - ############################################################################### # Test file-based DS with standalone "LineString" feature object. -def ogr_geojson_3(): +def test_ogr_geojson_3(): if gdaltest.geojson_drv is None: - return 'skip' + pytest.skip() ds = ogr.Open('data/linestring.geojson') - if ds is None: - gdaltest.post_reason('Failed to open datasource') - return 'fail' + assert ds is not None, 'Failed to open datasource' - if ds.GetLayerCount() is not 1: - gdaltest.post_reason('Wrong number of layers') - return 'fail' + assert ds.GetLayerCount() is 1, 'Wrong number of layers' lyr = ds.GetLayerByName('linestring') - if lyr is None: - gdaltest.post_reason('Missing layer called linestring') - return 'fail' + assert lyr is not None, 'Missing layer called linestring' extent = (100.0, 101.0, 0.0, 1.0) rc = validate_layer(lyr, 'linestring', 1, ogr.wkbLineString, 0, extent) - if not rc: - return 'fail' + assert rc lyr = None - return 'success' - ############################################################################## # Test file-based DS with standalone "Polygon" feature object. -def ogr_geojson_4(): +def test_ogr_geojson_4(): if gdaltest.geojson_drv is None: - return 'skip' + pytest.skip() ds = ogr.Open('data/polygon.geojson') - if ds is None: - gdaltest.post_reason('Failed to open datasource') - return 'fail' + assert ds is not None, 'Failed to open datasource' - if ds.GetLayerCount() is not 1: - gdaltest.post_reason('Wrong number of layers') - return 'fail' + assert ds.GetLayerCount() is 1, 'Wrong number of layers' lyr = ds.GetLayerByName('polygon') - if lyr is None: - gdaltest.post_reason('Missing layer called polygon') - return 'fail' + assert lyr is not None, 'Missing layer called polygon' extent = (100.0, 101.0, 0.0, 1.0) rc = validate_layer(lyr, 'polygon', 1, ogr.wkbPolygon, 0, extent) - if not rc: - return 'fail' + assert rc lyr = None - return 'success' - ############################################################################## # Test file-based DS with standalone "GeometryCollection" feature object. -def ogr_geojson_5(): +def test_ogr_geojson_5(): if gdaltest.geojson_drv is None: - return 'skip' + pytest.skip() ds = ogr.Open('data/geometrycollection.geojson') - if ds is None: - gdaltest.post_reason('Failed to open datasource') - return 'fail' + assert ds is not None, 'Failed to open datasource' - if ds.GetLayerCount() is not 1: - gdaltest.post_reason('Wrong number of layers') - return 'fail' + assert ds.GetLayerCount() is 1, 'Wrong number of layers' lyr = ds.GetLayerByName('geometrycollection') - if lyr is None: - gdaltest.post_reason('Missing layer called geometrycollection') - return 'fail' + assert lyr is not None, 'Missing layer called geometrycollection' extent = (100.0, 102.0, 0.0, 1.0) rc = validate_layer(lyr, 'geometrycollection', 1, ogr.wkbGeometryCollection, 0, extent) - if not rc: - return 'fail' + assert rc lyr = None - return 'success' - ############################################################################## # Test file-based DS with standalone "MultiPoint" feature object. -def ogr_geojson_6(): +def test_ogr_geojson_6(): if gdaltest.geojson_drv is None: - return 'skip' + pytest.skip() ds = ogr.Open('data/multipoint.geojson') - if ds is None: - gdaltest.post_reason('Failed to open datasource') - return 'fail' + assert ds is not None, 'Failed to open datasource' - if ds.GetLayerCount() is not 1: - gdaltest.post_reason('Wrong number of layers') - return 'fail' + assert ds.GetLayerCount() is 1, 'Wrong number of layers' lyr = ds.GetLayerByName('multipoint') - if lyr is None: - gdaltest.post_reason('Missing layer called multipoint') - return 'fail' + assert lyr is not None, 'Missing layer called multipoint' extent = (100.0, 101.0, 0.0, 1.0) rc = validate_layer(lyr, 'multipoint', 1, ogr.wkbMultiPoint, 0, extent) - if not rc: - return 'fail' + assert rc lyr = None - return 'success' - ############################################################################## # Test file-based DS with standalone "MultiLineString" feature object. -def ogr_geojson_7(): +def test_ogr_geojson_7(): if gdaltest.geojson_drv is None: - return 'skip' + pytest.skip() ds = ogr.Open('data/multilinestring.geojson') - if ds is None: - gdaltest.post_reason('Failed to open datasource') - return 'fail' + assert ds is not None, 'Failed to open datasource' - if ds.GetLayerCount() is not 1: - gdaltest.post_reason('Wrong number of layers') - return 'fail' + assert ds.GetLayerCount() is 1, 'Wrong number of layers' lyr = ds.GetLayerByName('multilinestring') - if lyr is None: - gdaltest.post_reason('Missing layer called multilinestring') - return 'fail' + assert lyr is not None, 'Missing layer called multilinestring' extent = (100.0, 103.0, 0.0, 3.0) rc = validate_layer(lyr, 'multilinestring', 1, ogr.wkbMultiLineString, 0, extent) - if not rc: - return 'fail' + assert rc lyr = None - return 'success' - ############################################################################## # Test file-based DS with standalone "MultiPolygon" feature object. -def ogr_geojson_8(): +def test_ogr_geojson_8(): if gdaltest.geojson_drv is None: - return 'skip' + pytest.skip() ds = ogr.Open('data/multipolygon.geojson') - if ds is None: - gdaltest.post_reason('Failed to open datasource') - return 'fail' + assert ds is not None, 'Failed to open datasource' - if ds.GetLayerCount() is not 1: - gdaltest.post_reason('Wrong number of layers') - return 'fail' + assert ds.GetLayerCount() is 1, 'Wrong number of layers' lyr = ds.GetLayerByName('multipolygon') - if lyr is None: - gdaltest.post_reason('Missing layer called multipolygon') - return 'fail' + assert lyr is not None, 'Missing layer called multipolygon' extent = (100.0, 103.0, 0.0, 3.0) rc = validate_layer(lyr, 'multipolygon', 1, ogr.wkbMultiPolygon, 0, extent) - if not rc: - return 'fail' + assert rc lyr = None - return 'success' - ############################################################################## # Test translation of data/gjpoint.shp to GeoJSON file -def ogr_geojson_9(): +def test_ogr_geojson_9(): if gdaltest.geojson_drv is None: - return 'skip' + pytest.skip() gdaltest.tests = [ ['gjpoint', [1], ['Point 1']], @@ -465,25 +401,20 @@ def ogr_geojson_9(): test = gdaltest.tests[i] rc = copy_shape_to_geojson(test[0]) - if not rc: - gdaltest.post_reason('Failed making copy of ' + test[0] + '.shp') - return 'fail' + assert rc, ('Failed making copy of ' + test[0] + '.shp') rc = verify_geojson_copy(test[0], test[1], test[2]) - if not rc: - gdaltest.post_reason('Verification of copy of ' + test[0] + '.shp failed') - return 'fail' - - return 'success' + assert rc, ('Verification of copy of ' + test[0] + '.shp failed') + ############################################################################## # Test translation of data/gjpoint.shp to GZip compressed GeoJSON file -def ogr_geojson_10(): +def test_ogr_geojson_10(): if gdaltest.geojson_drv is None: - return 'skip' + pytest.skip() gdaltest.tests = [ ['gjpoint', [1], ['Point 1']], @@ -498,117 +429,91 @@ def ogr_geojson_10(): test = gdaltest.tests[i] rc = copy_shape_to_geojson(test[0], '/vsigzip/') - if not rc: - gdaltest.post_reason('Failed making copy of ' + test[0] + '.shp') - return 'fail' + assert rc, ('Failed making copy of ' + test[0] + '.shp') rc = verify_geojson_copy(test[0], test[1], test[2]) - if not rc: - gdaltest.post_reason('Verification of copy of ' + test[0] + '.shp failed') - return 'fail' - - return 'success' + assert rc, ('Verification of copy of ' + test[0] + '.shp failed') + ############################################################################### -def ogr_geojson_11(): +def test_ogr_geojson_11(): if gdaltest.geojson_drv is None: - return 'skip' + pytest.skip() ds = ogr.Open('data/srs_name.geojson') - if ds is None: - gdaltest.post_reason('Failed to open datasource') - return 'fail' + assert ds is not None, 'Failed to open datasource' - if ds.GetLayerCount() is not 1: - gdaltest.post_reason('Wrong number of layers') - return 'fail' + assert ds.GetLayerCount() is 1, 'Wrong number of layers' lyr = ds.GetLayerByName('srs_name') - if lyr is None: - gdaltest.post_reason('Missing layer called srs_name') - return 'fail' + assert lyr is not None, 'Missing layer called srs_name' extent = (100.0, 102.0, 0.0, 1.0) rc = validate_layer(lyr, 'srs_name', 1, ogr.wkbGeometryCollection, 0, extent) - if not rc: - return 'fail' + assert rc ref = lyr.GetSpatialRef() pcs = int(ref.GetAuthorityCode('PROJCS')) - if pcs != 26915: - gdaltest.post_reason('Spatial reference was not valid') - return 'fail' + assert pcs == 26915, 'Spatial reference was not valid' feature = lyr.GetNextFeature() geometry = feature.GetGeometryRef().GetGeometryRef(0) srs = geometry.GetSpatialReference() pcs = int(srs.GetAuthorityCode('PROJCS')) - if pcs != 26916: - gdaltest.post_reason('Spatial reference for individual geometry was not valid') - return 'fail' + assert pcs == 26916, 'Spatial reference for individual geometry was not valid' lyr = None - return 'success' - ############################################################################### # Test DS passed as name with standalone "Point" feature object (#3377) -def ogr_geojson_12(): +def test_ogr_geojson_12(): if gdaltest.geojson_drv is None: - return 'skip' + pytest.skip() if os.name == 'nt': - return 'skip' + pytest.skip() import test_cli_utilities if test_cli_utilities.get_ogrinfo_path() is None: - return 'skip' + pytest.skip() ret = gdaltest.runexternal(test_cli_utilities.get_ogrinfo_path() + ' -ro -al \'{"type": "Point","coordinates": [100.0, 0.0]}\'') - if ret.find(' POINT (100 0)') == -1: - print(ret) - return 'fail' - - return 'success' + assert ret.find(' POINT (100 0)') != -1 ############################################################################### # Test writing to stdout (#3381) -def ogr_geojson_13(): +def test_ogr_geojson_13(): if gdaltest.geojson_drv is None: - return 'skip' + pytest.skip() test = ['gjpoint', [1], ['Point 1']] rc = copy_shape_to_geojson(test[0], '/vsistdout/') - if not rc: - gdaltest.post_reason('Failed making copy of ' + test[0] + '.shp') - return 'fail' - - return 'success' + assert rc, ('Failed making copy of ' + test[0] + '.shp') ############################################################################### # Test reading & writing various degenerated geometries -def ogr_geojson_14(): +def test_ogr_geojson_14(): if gdaltest.geojson_drv is None: - return 'skip' + pytest.skip() if int(gdal.VersionInfo('VERSION_NUM')) < 1800: - return 'skip' + pytest.skip() with gdaltest.error_handler(): ds = ogr.Open('data/ogr_geojson_14.geojson') @@ -628,13 +533,11 @@ def ogr_geojson_14(): out_ds = None - return 'success' - ############################################################################### # Test Feature.ExportToJson (#3870) -def ogr_geojson_15(): +def test_ogr_geojson_15(): feature_defn = ogr.FeatureDefn() feature_defn.AddFieldDefn(ogr.FieldDefn("foo")) @@ -653,122 +556,98 @@ def ogr_geojson_15(): try: out = feature.ExportToJson() except ImportError: - return 'skip' + pytest.skip() expected_out = """{"geometry": {"type": "Point", "coordinates": [1.0, 2.0]}, "type": "Feature", "properties": {"foo": "bar", "boolfield": true}, "id": 0}""" if out != expected_out: out_json = json.loads(out) expected_out_json = json.loads(expected_out) - if out_json != expected_out_json: - gdaltest.post_reason('fail') - print(out) - return 'fail' + assert out_json == expected_out_json, out out = feature.ExportToJson(as_object=True) expected_out = {'geometry': {'type': 'Point', 'coordinates': [1.0, 2.0]}, 'type': 'Feature', 'properties': {'foo': 'bar', "boolfield": True}, 'id': 0} - if out != expected_out: - gdaltest.post_reason('fail') - print(out) - return 'fail' - - return 'success' + assert out == expected_out ############################################################################### # Test reading ESRI point file -def ogr_geojson_16(): +def test_ogr_geojson_16(): if gdaltest.geojson_drv is None: - return 'skip' + pytest.skip() ds = ogr.Open('data/esripoint.json') - if ds is None: - gdaltest.post_reason('Failed to open datasource') - return 'fail' + assert ds is not None, 'Failed to open datasource' - if ds.GetLayerCount() is not 1: - gdaltest.post_reason('Wrong number of layers') - return 'fail' + assert ds.GetLayerCount() is 1, 'Wrong number of layers' lyr = ds.GetLayerByName('esripoint') - if lyr is None: - gdaltest.post_reason('Missing layer called esripoint') - return 'fail' + assert lyr is not None, 'Missing layer called esripoint' extent = (2, 2, 49, 49) rc = validate_layer(lyr, 'esripoint', 1, ogr.wkbPoint, 4, extent) - if not rc: - return 'fail' + assert rc ref = lyr.GetSpatialRef() gcs = int(ref.GetAuthorityCode('GEOGCS')) - if gcs != 4326: - gdaltest.post_reason("Spatial reference was not valid") - return 'fail' + assert gcs == 4326, "Spatial reference was not valid" feature = lyr.GetNextFeature() ref_geom = ogr.CreateGeometryFromWkt('POINT(2 49)') if ogrtest.check_feature_geometry(feature, ref_geom) != 0: feature.DumpReadable() - return 'fail' + pytest.fail() if feature.GetFID() != 1: feature.DumpReadable() - return 'fail' + pytest.fail() if feature.GetFieldAsInteger('fooInt') != 2: feature.DumpReadable() - return 'fail' + pytest.fail() if feature.GetFieldAsDouble('fooDouble') != 3.4: feature.DumpReadable() - return 'fail' + pytest.fail() if feature.GetFieldAsString('fooString') != '56': feature.DumpReadable() - return 'fail' + pytest.fail() lyr = None ds = None - return 'success' - ############################################################################### # Test reading ESRI linestring file -def ogr_geojson_17(): +def test_ogr_geojson_17(): if gdaltest.geojson_drv is None: - return 'skip' + pytest.skip() ds = ogr.Open('data/esrilinestring.json') - if ds is None: - gdaltest.post_reason('Failed to open datasource') - return 'fail' + assert ds is not None, 'Failed to open datasource' - if ds.GetLayerCount() is not 1: - gdaltest.post_reason('Wrong number of layers') - return 'fail' + assert ds.GetLayerCount() is 1, 'Wrong number of layers' lyr = ds.GetLayer(0) extent = (2, 3, 49, 50) rc = validate_layer(lyr, None, 1, ogr.wkbLineString, 0, extent) - if not rc: - return 'fail' + assert rc feature = lyr.GetNextFeature() ref_geom = ogr.CreateGeometryFromWkt('LINESTRING (2 49,3 50)') if ogrtest.check_feature_geometry(feature, ref_geom) != 0: feature.DumpReadable() - return 'fail' + pytest.fail() lyr = None ds = None @@ -793,105 +672,88 @@ def ogr_geojson_17(): ref_geom = ogr.CreateGeometryFromWkt('MULTILINESTRING ((2 49,2.1 49.1),(3 50,3.1 50.1))') if ogrtest.check_feature_geometry(feature, ref_geom) != 0: feature.DumpReadable() - return 'fail' - - return 'success' + pytest.fail() + ############################################################################### # Test reading ESRI polygon file -def ogr_geojson_18(): +def test_ogr_geojson_18(): if gdaltest.geojson_drv is None: - return 'skip' + pytest.skip() ds = ogr.Open('data/esripolygon.json') - if ds is None: - gdaltest.post_reason('Failed to open datasource') - return 'fail' + assert ds is not None, 'Failed to open datasource' - if ds.GetLayerCount() is not 1: - gdaltest.post_reason('Wrong number of layers') - return 'fail' + assert ds.GetLayerCount() is 1, 'Wrong number of layers' lyr = ds.GetLayer(0) extent = (-3, 3, 49, 50) rc = validate_layer(lyr, None, 1, ogr.wkbPolygon, 0, extent) - if not rc: - return 'fail' + assert rc feature = lyr.GetNextFeature() ref_geom = ogr.CreateGeometryFromWkt('MULTIPOLYGON (((2 49,2 50,3 50,3 49,2 49),(2.1 49.1,2.1 49.9,2.9 49.9,2.9 49.1,2.1 49.1)),((-2 49,-2 50,-3 50,-3 49,-2 49)))') if ogrtest.check_feature_geometry(feature, ref_geom) != 0: feature.DumpReadable() - return 'fail' + pytest.fail() lyr = None ds = None ds = ogr.Open('data/esripolygonempty.json') - if ds is None: - gdaltest.post_reason('Failed to open datasource') - return 'fail' + assert ds is not None, 'Failed to open datasource' lyr = ds.GetLayer(0) feature = lyr.GetNextFeature() if feature.GetGeometryRef().ExportToWkt() != 'POLYGON EMPTY': feature.DumpReadable() - return 'fail' + pytest.fail() lyr = None ds = None - return 'success' - ############################################################################### # Test reading ESRI multipoint file -def ogr_geojson_19(): +def test_ogr_geojson_19(): if gdaltest.geojson_drv is None: - return 'skip' + pytest.skip() ds = ogr.Open('data/esrimultipoint.json') - if ds is None: - gdaltest.post_reason('Failed to open datasource') - return 'fail' + assert ds is not None, 'Failed to open datasource' - if ds.GetLayerCount() is not 1: - gdaltest.post_reason('Wrong number of layers') - return 'fail' + assert ds.GetLayerCount() is 1, 'Wrong number of layers' lyr = ds.GetLayer(0) extent = (2, 3, 49, 50) rc = validate_layer(lyr, None, 1, ogr.wkbMultiPoint, 4, extent) - if not rc: - return 'fail' + assert rc feature = lyr.GetNextFeature() ref_geom = ogr.CreateGeometryFromWkt('MULTIPOINT (2 49,3 50)') if ogrtest.check_feature_geometry(feature, ref_geom) != 0: feature.DumpReadable() - return 'fail' + pytest.fail() lyr = None ds = None - return 'success' - ############################################################################### # Test reading files with no extension (#4314) -def ogr_geojson_20(): +def test_ogr_geojson_20(): if gdaltest.geojson_drv is None: - return 'skip' + pytest.skip() from glob import glob @@ -912,31 +774,27 @@ def ogr_geojson_20(): if ds is None: print(gj) print(data.decode('LATIN1')) - gdaltest.post_reason('Failed to open datasource') - return 'fail' + pytest.fail('Failed to open datasource') ds = None gdal.Unlink('/vsimem/testgj') - return 'success' - + ############################################################################### # Test reading output of geocouch spatiallist -def ogr_geojson_21(): +def test_ogr_geojson_21(): if gdaltest.geojson_drv is None: - return 'skip' + pytest.skip() ds = ogr.Open("""{"type": "FeatureCollection", "features":[ {"type": "Feature", "geometry": {"type":"Point","coordinates":[1,2]}, "properties": {"_id":"aid", "_rev":"arev", "type":"Feature", "properties":{"intvalue" : 2, "floatvalue" : 3.2, "strvalue" : "foo", "properties": { "foo": "bar"}}}}]}""") - if ds is None: - gdaltest.post_reason('Failed to open datasource') - return 'fail' + assert ds is not None, 'Failed to open datasource' lyr = ds.GetLayerByName('OGRGeoJSON') @@ -947,21 +805,19 @@ def ogr_geojson_21(): feature.GetFieldAsInteger("intvalue") != 2 or \ ogrtest.check_feature_geometry(feature, ref_geom) != 0: feature.DumpReadable() - return 'fail' + pytest.fail() lyr = None ds = None - return 'success' - ############################################################################### # Same as ogr_geojson_21 with several features -def ogr_geojson_22(): +def test_ogr_geojson_22(): if gdaltest.geojson_drv is None: - return 'skip' + pytest.skip() ds = ogr.Open("""{"type": "FeatureCollection", "features":[ {"type": "Feature", @@ -972,9 +828,7 @@ def ogr_geojson_22(): "geometry": {"type":"Point","coordinates":[3,4]}, "properties": {"_id":"aid2", "_rev":"arev2", "type":"Feature", "properties":{"intvalue" : 3.5, "str2value" : "bar"}}}]}""") - if ds is None: - gdaltest.post_reason('Failed to open datasource') - return 'fail' + assert ds is not None, 'Failed to open datasource' lyr = ds.GetLayerByName('OGRGeoJSON') @@ -985,7 +839,7 @@ def ogr_geojson_22(): feature.GetFieldAsDouble("intvalue") != 2 or \ ogrtest.check_feature_geometry(feature, ref_geom) != 0: feature.DumpReadable() - return 'fail' + pytest.fail() feature = lyr.GetNextFeature() ref_geom = ogr.CreateGeometryFromWkt('POINT (3 4)') @@ -995,21 +849,19 @@ def ogr_geojson_22(): feature.GetFieldAsString("str2value") != 'bar' or \ ogrtest.check_feature_geometry(feature, ref_geom) != 0: feature.DumpReadable() - return 'fail' + pytest.fail() lyr = None ds = None - return 'success' - ############################################################################### # Write GeoJSON with bbox and test SRS writing&reading back -def ogr_geojson_23(): +def test_ogr_geojson_23(): if gdaltest.geojson_drv is None: - return 'skip' + pytest.skip() ds = gdaltest.geojson_drv.CreateDataSource('/vsimem/ogr_geojson_23.json') sr = osr.SpatialReference() @@ -1029,10 +881,7 @@ def ogr_geojson_23(): sr_got = lyr.GetSpatialRef() ds = None - if sr_got.ExportToWkt() != sr.ExportToWkt(): - gdaltest.post_reason('did not get expected SRS') - print(sr_got) - return 'fail' + assert sr_got.ExportToWkt() == sr.ExportToWkt(), 'did not get expected SRS' fp = gdal.VSIFOpenL('/vsimem/ogr_geojson_23.json', 'rb') data = gdal.VSIFReadL(1, 10000, fp).decode('ascii') @@ -1040,26 +889,19 @@ def ogr_geojson_23(): gdal.Unlink('/vsimem/ogr_geojson_23.json') - if data.find('"bbox": [ 1, 10, 2, 20 ]') == -1: - gdaltest.post_reason('did not find global bbox') - print(data) - return 'fail' - - if data.find('"bbox": [ 1.0, 10.0, 1.0, 10.0 ]') == -1: - gdaltest.post_reason('did not find first feature bbox') - print(data) - return 'fail' + assert data.find('"bbox": [ 1, 10, 2, 20 ]') != -1, 'did not find global bbox' - return 'success' + assert data.find('"bbox": [ 1.0, 10.0, 1.0, 10.0 ]') != -1, \ + 'did not find first feature bbox' ############################################################################### # Test alternate form of geojson -def ogr_geojson_24(): +def test_ogr_geojson_24(): if gdaltest.geojson_drv is None: - return 'skip' + pytest.skip() content = """loadGeoJSON({"layerFoo": { "type": "Feature", "geometry": { @@ -1084,60 +926,47 @@ def ogr_geojson_24(): ds = ogr.Open('/vsimem/ogr_geojson_24.js') gdal.Unlink('/vsimem/ogr_geojson_24.js') - if ds is None: - gdaltest.post_reason('Failed to open datasource') - return 'fail' + assert ds is not None, 'Failed to open datasource' lyr = ds.GetLayerByName('layerFoo') - if lyr is None: - gdaltest.post_reason('cannot find layer') - return 'fail' + assert lyr is not None, 'cannot find layer' feature = lyr.GetNextFeature() ref_geom = ogr.CreateGeometryFromWkt('POINT (2 49)') if feature.GetFieldAsString("name") != 'bar' or \ ogrtest.check_feature_geometry(feature, ref_geom) != 0: feature.DumpReadable() - return 'fail' + pytest.fail() lyr = ds.GetLayerByName('layerBar') - if lyr is None: - gdaltest.post_reason('cannot find layer') - return 'fail' + assert lyr is not None, 'cannot find layer' feature = lyr.GetNextFeature() ref_geom = ogr.CreateGeometryFromWkt('POINT (2 49)') if feature.GetFieldAsString("other_name") != 'baz' or \ ogrtest.check_feature_geometry(feature, ref_geom) != 0: feature.DumpReadable() - return 'fail' + pytest.fail() ds = None - return 'success' - + ############################################################################### # Test TopoJSON -def ogr_geojson_25(): +def test_ogr_geojson_25(): if gdaltest.geojson_drv is None: - return 'skip' + pytest.skip() ds = ogr.Open('data/topojson1.topojson') lyr = ds.GetLayer(0) - if lyr.GetName() != 'a_layer': - gdaltest.post_reason('failure') - return 'fail' + assert lyr.GetName() == 'a_layer' feat = lyr.GetNextFeature() - if ogrtest.check_feature_geometry(feat, 'LINESTRING (100 1000,110 1000,110 1100)') != 0: - gdaltest.post_reason('failure') - return 'fail' + assert ogrtest.check_feature_geometry(feat, 'LINESTRING (100 1000,110 1000,110 1100)') == 0 lyr = ds.GetLayer(1) - if lyr.GetName() != 'TopoJSON': - gdaltest.post_reason('failure') - return 'fail' + assert lyr.GetName() == 'TopoJSON' expected_results = [ (None, None, 'POINT EMPTY'), (None, None, 'POINT EMPTY'), @@ -1175,69 +1004,48 @@ def ogr_geojson_25(): (None, None, 'MULTILINESTRING ((100 1000,110 1000,110 1100,100 1100,100 1000))'), (None, None, 'MULTILINESTRING ((100 1000,110 1000,110 1100,100 1100,100 1000),(101 1010,101 1090,109 1090,109 1010,101 1010))'), ] - if lyr.GetFeatureCount() != len(expected_results): - gdaltest.post_reason('failure') - return 'fail' + assert lyr.GetFeatureCount() == len(expected_results) for i, exp_result in enumerate(expected_results): feat = lyr.GetNextFeature() if feat.GetField('id') != exp_result[0] or \ feat.GetField('name') != exp_result[1] or \ feat.GetGeometryRef().ExportToWkt() != exp_result[2]: - gdaltest.post_reason('failure at feat index %d' % i) feat.DumpReadable() print(exp_result) print(feat.GetField('name')) - return 'fail' + pytest.fail('failure at feat index %d' % i) ds = None ds = ogr.Open('data/topojson2.topojson') lyr = ds.GetLayer(0) - if lyr.GetName() != 'a_layer': - gdaltest.post_reason('failure') - return 'fail' + assert lyr.GetName() == 'a_layer' feat = lyr.GetNextFeature() - if ogrtest.check_feature_geometry(feat, 'LINESTRING (100 1000,110 1000,110 1100)') != 0: - gdaltest.post_reason('failure') - return 'fail' + assert ogrtest.check_feature_geometry(feat, 'LINESTRING (100 1000,110 1000,110 1100)') == 0 lyr = ds.GetLayer(1) - if lyr.GetName() != 'TopoJSON': - gdaltest.post_reason('failure') - return 'fail' + assert lyr.GetName() == 'TopoJSON' feat = lyr.GetNextFeature() - if ogrtest.check_feature_geometry(feat, 'LINESTRING (100 1000,110 1000,110 1100)') != 0: - gdaltest.post_reason('failure') - return 'fail' + assert ogrtest.check_feature_geometry(feat, 'LINESTRING (100 1000,110 1000,110 1100)') == 0 ds = None ds = ogr.Open('data/topojson3.topojson') lyr = ds.GetLayer(0) - if lyr.GetName() != 'a_layer': - gdaltest.post_reason('failure') - return 'fail' + assert lyr.GetName() == 'a_layer' feat = lyr.GetNextFeature() - if ogrtest.check_feature_geometry(feat, 'LINESTRING (0 0,10 0,0 10,10 0,0 0)') != 0: - gdaltest.post_reason('failure') - return 'fail' + assert ogrtest.check_feature_geometry(feat, 'LINESTRING (0 0,10 0,0 10,10 0,0 0)') == 0 lyr = ds.GetLayer(1) - if lyr.GetName() != 'TopoJSON': - gdaltest.post_reason('failure') - return 'fail' + assert lyr.GetName() == 'TopoJSON' feat = lyr.GetNextFeature() - if ogrtest.check_feature_geometry(feat, 'LINESTRING (0 0,10 0,0 10,10 0,0 0)') != 0: - gdaltest.post_reason('failure') - return 'fail' + assert ogrtest.check_feature_geometry(feat, 'LINESTRING (0 0,10 0,0 10,10 0,0 0)') == 0 ds = None - return 'success' - ############################################################################### # Test 64bit support -def ogr_geojson_26(): +def test_ogr_geojson_26(): if gdaltest.geojson_drv is None: - return 'skip' + pytest.skip() ds = ogr.Open("""{"type": "FeatureCollection", "features":[ {"type": "Feature", "id": 1, @@ -1247,42 +1055,32 @@ def ogr_geojson_26(): "geometry": {"type":"Point","coordinates":[3,4]}, "properties": { "intvalue" : 1234567890123, "intlist" : [1, 1234567890123] }}, ]}""") - if ds is None: - gdaltest.post_reason('Failed to open datasource') - return 'fail' + assert ds is not None, 'Failed to open datasource' lyr = ds.GetLayerByName('OGRGeoJSON') - if lyr.GetMetadataItem(ogr.OLMD_FID64) is None: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.GetMetadataItem(ogr.OLMD_FID64) is not None feature = lyr.GetNextFeature() if feature.GetFID() != 1: - gdaltest.post_reason('fail') feature.DumpReadable() - return 'fail' + pytest.fail() if feature.GetField("intvalue") != 1: - gdaltest.post_reason('fail') feature.DumpReadable() - return 'fail' + pytest.fail() if feature.GetField("int64") != 1234567890123: - gdaltest.post_reason('fail') feature.DumpReadable() - return 'fail' + pytest.fail() feature = lyr.GetNextFeature() if feature.GetFID() != 1234567890123: - gdaltest.post_reason('fail') feature.DumpReadable() - return 'fail' + pytest.fail() if feature.GetField("intvalue") != 1234567890123: - gdaltest.post_reason('fail') feature.DumpReadable() - return 'fail' + pytest.fail() if feature.GetField("intlist") != [1, 1234567890123]: - gdaltest.post_reason('fail') feature.DumpReadable() - return 'fail' + pytest.fail() lyr = None ds = None @@ -1305,21 +1103,16 @@ def ogr_geojson_26(): gdal.Unlink('/vsimem/ogr_geojson_26.json') - if data.find('{ "type": "Feature", "id": 1234567890123, "properties": { "int64": 1234567890123, "int64list": [ 1234567890123 ] }, "geometry": null }') < 0: - gdaltest.post_reason('failure') - print(data) - return 'fail' - - return 'success' + assert data.find('{ "type": "Feature", "id": 1234567890123, "properties": { "int64": 1234567890123, "int64list": [ 1234567890123 ] }, "geometry": null }') >= 0 ############################################################################### # Test workaround for 64bit values (returned as strings) -def ogr_geojson_27(): +def test_ogr_geojson_27(): if gdaltest.geojson_drv is None: - return 'skip' + pytest.skip() gdal.PushErrorHandler('CPLQuietErrorHandler') # Warning 1: Integer values probably ranging out of 64bit integer range @@ -1333,44 +1126,36 @@ def ogr_geojson_27(): "properties": { "intvalue" : 12345678901231234567890123 }}, ]}""") gdal.PopErrorHandler() - if ds is None: - gdaltest.post_reason('Failed to open datasource') - return 'fail' + assert ds is not None, 'Failed to open datasource' lyr = ds.GetLayerByName('OGRGeoJSON') feature = lyr.GetNextFeature() if feature.GetField("intvalue") != 1: feature.DumpReadable() - return 'fail' + pytest.fail() feature = lyr.GetNextFeature() if feature.GetField("intvalue") != 9223372036854775807: feature.DumpReadable() - return 'fail' + pytest.fail() lyr = None ds = None - return 'success' - ############################################################################### # Test reading ESRI point file with z value -def ogr_geojson_28(): +def test_ogr_geojson_28(): if gdaltest.geojson_drv is None: - return 'skip' + pytest.skip() ds = ogr.Open('data/esrizpoint.json') - if ds is None: - gdaltest.post_reason('Failed to open datasource') - return 'fail' + assert ds is not None, 'Failed to open datasource' - if ds.GetLayerCount() is not 1: - gdaltest.post_reason('Wrong number of layers') - return 'fail' + assert ds.GetLayerCount() is 1, 'Wrong number of layers' lyr = ds.GetLayer(0) @@ -1378,60 +1163,51 @@ def ogr_geojson_28(): extent = (2, 2, 49, 49, 1, 1) rc = validate_layer(lyr, None, 1, ogr.wkbPoint, 4, extent) - if not rc: - return 'fail' + assert rc ref = lyr.GetSpatialRef() gcs = int(ref.GetAuthorityCode('GEOGCS')) - if gcs != 4326: - gdaltest.post_reason("Spatial reference was not valid") - return 'fail' + assert gcs == 4326, "Spatial reference was not valid" feature = lyr.GetNextFeature() ref_geom = ogr.CreateGeometryFromWkt('POINT(2 49 1)') if ogrtest.check_feature_geometry(feature, ref_geom) != 0: feature.DumpReadable() - return 'fail' + pytest.fail() if feature.GetFID() != 1: feature.DumpReadable() - return 'fail' + pytest.fail() if feature.GetFieldAsInteger('fooInt') != 2: feature.DumpReadable() - return 'fail' + pytest.fail() if feature.GetFieldAsDouble('fooDouble') != 3.4: feature.DumpReadable() - return 'fail' + pytest.fail() if feature.GetFieldAsString('fooString') != '56': feature.DumpReadable() - return 'fail' + pytest.fail() lyr = None ds = None - return 'success' - ############################################################################### # Test reading ESRI linestring file with z -def ogr_geojson_29(): +def test_ogr_geojson_29(): if gdaltest.geojson_drv is None: - return 'skip' + pytest.skip() ds = ogr.Open('data/esrizlinestring.json') - if ds is None: - gdaltest.post_reason('Failed to open datasource') - return 'fail' + assert ds is not None, 'Failed to open datasource' - if ds.GetLayerCount() is not 1: - gdaltest.post_reason('Wrong number of layers') - return 'fail' + assert ds.GetLayerCount() is 1, 'Wrong number of layers' lyr = ds.GetLayer(0) @@ -1439,37 +1215,30 @@ def ogr_geojson_29(): extent = (2, 3, 49, 50, 1, 2) rc = validate_layer(lyr, None, 1, ogr.wkbLineString, 0, extent) - if not rc: - return 'fail' + assert rc feature = lyr.GetNextFeature() ref_geom = ogr.CreateGeometryFromWkt('LINESTRING (2 49 1,3 50 2)') if ogrtest.check_feature_geometry(feature, ref_geom) != 0: feature.DumpReadable() - return 'fail' + pytest.fail() lyr = None ds = None - return 'success' - ############################################################################### # Test reading ESRI multipoint file with z -def ogr_geojson_30(): +def test_ogr_geojson_30(): if gdaltest.geojson_drv is None: - return 'skip' + pytest.skip() ds = ogr.Open('data/esrizmultipoint.json') - if ds is None: - gdaltest.post_reason('Failed to open datasource') - return 'fail' + assert ds is not None, 'Failed to open datasource' - if ds.GetLayerCount() is not 1: - gdaltest.post_reason('Wrong number of layers') - return 'fail' + assert ds.GetLayerCount() is 1, 'Wrong number of layers' lyr = ds.GetLayer(0) @@ -1477,37 +1246,30 @@ def ogr_geojson_30(): extent = (2, 3, 49, 50, 1, 2) rc = validate_layer(lyr, None, 1, ogr.wkbMultiPoint, 4, extent) - if not rc: - return 'fail' + assert rc feature = lyr.GetNextFeature() ref_geom = ogr.CreateGeometryFromWkt('MULTIPOINT (2 49 1,3 50 2)') if ogrtest.check_feature_geometry(feature, ref_geom) != 0: feature.DumpReadable() - return 'fail' + pytest.fail() lyr = None ds = None - return 'success' - ############################################################################### # Test reading ESRI polygon file with z -def ogr_geojson_31(): +def test_ogr_geojson_31(): if gdaltest.geojson_drv is None: - return 'skip' + pytest.skip() ds = ogr.Open('data/esrizpolygon.json') - if ds is None: - gdaltest.post_reason('Failed to open datasource') - return 'fail' + assert ds is not None, 'Failed to open datasource' - if ds.GetLayerCount() is not 1: - gdaltest.post_reason('Wrong number of layers') - return 'fail' + assert ds.GetLayerCount() is 1, 'Wrong number of layers' lyr = ds.GetLayer(0) @@ -1515,139 +1277,115 @@ def ogr_geojson_31(): extent = (2, 3, 49, 50, 1, 4) rc = validate_layer(lyr, None, 1, ogr.wkbPolygon, 0, extent) - if not rc: - return 'fail' + assert rc feature = lyr.GetNextFeature() ref_geom = ogr.CreateGeometryFromWkt('POLYGON ((2 49 1,2 50 2,3 50 3,3 49 4,2 49 1))') if ogrtest.check_feature_geometry(feature, ref_geom) != 0: feature.DumpReadable() - return 'fail' + pytest.fail() lyr = None ds = None - return 'success' - ############################################################################### # Test reading ESRI multipoint file with m, but no z (hasM=true, hasZ omitted) -def ogr_geojson_32(): +def test_ogr_geojson_32(): if gdaltest.geojson_drv is None: - return 'skip' + pytest.skip() ds = ogr.Open('data/esrihasmnozmultipoint.json') - if ds is None: - gdaltest.post_reason('Failed to open datasource') - return 'fail' + assert ds is not None, 'Failed to open datasource' - if ds.GetLayerCount() is not 1: - gdaltest.post_reason('Wrong number of layers') - return 'fail' + assert ds.GetLayerCount() is 1, 'Wrong number of layers' lyr = ds.GetLayer(0) extent = (2, 3, 49, 50) rc = validate_layer(lyr, None, 1, ogr.wkbMultiPoint, 4, extent) - if not rc: - return 'fail' + assert rc feature = lyr.GetNextFeature() ref_geom = ogr.CreateGeometryFromWkt('MULTIPOINT M ((2 49 1),(3 50 2))') if ogrtest.check_feature_geometry(feature, ref_geom) != 0: feature.DumpReadable() - return 'fail' + pytest.fail() lyr = None ds = None - return 'success' - ############################################################################### # Test reading ESRI multipoint file with hasZ=true, but only 2 components. -def ogr_geojson_33(): +def test_ogr_geojson_33(): if gdaltest.geojson_drv is None: - return 'skip' + pytest.skip() ds = ogr.Open('data/esriinvalidhaszmultipoint.json') - if ds is None: - gdaltest.post_reason('Failed to open datasource') - return 'fail' + assert ds is not None, 'Failed to open datasource' - if ds.GetLayerCount() is not 1: - gdaltest.post_reason('Wrong number of layers') - return 'fail' + assert ds.GetLayerCount() is 1, 'Wrong number of layers' lyr = ds.GetLayer(0) extent = (2, 3, 49, 50) rc = validate_layer(lyr, None, 1, ogr.wkbMultiPoint, 4, extent) - if not rc: - return 'fail' + assert rc feature = lyr.GetNextFeature() ref_geom = ogr.CreateGeometryFromWkt('MULTIPOINT (2 49,3 50)') if ogrtest.check_feature_geometry(feature, ref_geom) != 0: feature.DumpReadable() - return 'fail' + pytest.fail() lyr = None ds = None - return 'success' - ############################################################################### # Test reading ESRI multipoint file with z and m -def ogr_geojson_34(): +def test_ogr_geojson_34(): if gdaltest.geojson_drv is None: - return 'skip' + pytest.skip() ds = ogr.Open('data/esrizmmultipoint.json') - if ds is None: - gdaltest.post_reason('Failed to open datasource') - return 'fail' + assert ds is not None, 'Failed to open datasource' - if ds.GetLayerCount() is not 1: - gdaltest.post_reason('Wrong number of layers') - return 'fail' + assert ds.GetLayerCount() is 1, 'Wrong number of layers' lyr = ds.GetLayer(0) extent = (2, 3, 49, 50) rc = validate_layer(lyr, None, 1, ogr.wkbMultiPoint, 4, extent) - if not rc: - return 'fail' + assert rc feature = lyr.GetNextFeature() ref_geom = ogr.CreateGeometryFromWkt('MULTIPOINT ZM ((2 49 1 100),(3 50 2 100))') if ogrtest.check_feature_geometry(feature, ref_geom) != 0: feature.DumpReadable() - return 'fail' + pytest.fail() lyr = None ds = None - return 'success' - ############################################################################### # Test handling of huge coordinates (#5377) -def ogr_geojson_35(): +def test_ogr_geojson_35(): if gdaltest.geojson_drv is None: - return 'skip' + pytest.skip() ds = gdaltest.geojson_drv.CreateDataSource('/vsimem/ogr_geojson_35.json') lyr = ds.CreateLayer('foo') @@ -1732,43 +1470,32 @@ def ogr_geojson_35(): gdal.Unlink('/vsimem/ogr_geojson_35.json') - if data.find('-1.79') == -1 and data.find('e+308') == -1: - gdaltest.post_reason('fail') - print(data) - return 'fail' + assert not (data.find('-1.79') == -1 and data.find('e+308') == -1) for ident in range(2, 8): - if data.find('{ "type": "Feature", "id": %d, "properties": { }, "geometry": null }' % ident) == -1: - gdaltest.post_reason('fail') - print(data) - return 'fail' - - return 'success' + assert data.find('{ "type": "Feature", "id": %d, "properties": { }, "geometry": null }' % ident) != -1 + ############################################################################### # Test reading file with UTF-8 BOM (which is supposed to be illegal in JSON...) (#5630) -def ogr_geojson_36(): +def test_ogr_geojson_36(): if gdaltest.geojson_drv is None: - return 'skip' + pytest.skip() ds = ogr.Open('data/point_with_utf8bom.json') - if ds is None: - gdaltest.post_reason('Failed to open datasource') - return 'fail' + assert ds is not None, 'Failed to open datasource' ds = None - return 'success' - ######################################################################### # Test boolean type support -def ogr_geojson_37(): +def test_ogr_geojson_37(): if gdaltest.geojson_drv is None: - return 'skip' + pytest.skip() # Test read support ds = ogr.Open("""{"type": "FeatureCollection","features": [ @@ -1777,25 +1504,16 @@ def ogr_geojson_37(): ] }""") lyr = ds.GetLayer(0) feat_defn = lyr.GetLayerDefn() - if feat_defn.GetFieldDefn(feat_defn.GetFieldIndex('bool')).GetType() != ogr.OFTInteger or \ - feat_defn.GetFieldDefn(feat_defn.GetFieldIndex('bool')).GetSubType() != ogr.OFSTBoolean: - gdaltest.post_reason('failure') - return 'fail' - if feat_defn.GetFieldDefn(feat_defn.GetFieldIndex('not_bool')).GetSubType() != ogr.OFSTNone: - gdaltest.post_reason('failure') - return 'fail' - if feat_defn.GetFieldDefn(feat_defn.GetFieldIndex('bool_list')).GetType() != ogr.OFTIntegerList or \ - feat_defn.GetFieldDefn(feat_defn.GetFieldIndex('bool_list')).GetSubType() != ogr.OFSTBoolean: - gdaltest.post_reason('failure') - return 'fail' - if feat_defn.GetFieldDefn(feat_defn.GetFieldIndex('notbool_list')).GetSubType() != ogr.OFSTNone: - gdaltest.post_reason('failure') - return 'fail' + assert (feat_defn.GetFieldDefn(feat_defn.GetFieldIndex('bool')).GetType() == ogr.OFTInteger and \ + feat_defn.GetFieldDefn(feat_defn.GetFieldIndex('bool')).GetSubType() == ogr.OFSTBoolean) + assert feat_defn.GetFieldDefn(feat_defn.GetFieldIndex('not_bool')).GetSubType() == ogr.OFSTNone + assert (feat_defn.GetFieldDefn(feat_defn.GetFieldIndex('bool_list')).GetType() == ogr.OFTIntegerList and \ + feat_defn.GetFieldDefn(feat_defn.GetFieldIndex('bool_list')).GetSubType() == ogr.OFSTBoolean) + assert feat_defn.GetFieldDefn(feat_defn.GetFieldIndex('notbool_list')).GetSubType() == ogr.OFSTNone f = lyr.GetNextFeature() if f.GetField('bool') != 0 or f.GetField('bool_list') != [0, 1]: - gdaltest.post_reason('failure') f.DumpReadable() - return 'fail' + pytest.fail() out_ds = ogr.GetDriverByName('GeoJSON').CreateDataSource('/vsimem/ogr_geojson_37.json') out_lyr = out_ds.CreateLayer('test') @@ -1812,21 +1530,16 @@ def ogr_geojson_37(): gdal.Unlink('/vsimem/ogr_geojson_37.json') - if data.find('"bool": false, "not_bool": 0, "bool_list": [ false, true ], "notbool_list": [ 0, 3 ]') < 0: - gdaltest.post_reason('failure') - print(data) - return 'fail' - - return 'success' + assert data.find('"bool": false, "not_bool": 0, "bool_list": [ false, true ], "notbool_list": [ 0, 3 ]') >= 0 ############################################################################### # Test datetime/date/time type support -def ogr_geojson_38(): +def test_ogr_geojson_38(): if gdaltest.geojson_drv is None: - return 'skip' + pytest.skip() # Test read support ds = ogr.Open("""{"type": "FeatureCollection", "features": [ @@ -1835,61 +1548,43 @@ def ogr_geojson_38(): ] }""") lyr = ds.GetLayer(0) feat_defn = lyr.GetLayerDefn() - if feat_defn.GetFieldDefn(feat_defn.GetFieldIndex('dt')).GetType() != ogr.OFTDateTime: - gdaltest.post_reason('failure') - return 'fail' - if feat_defn.GetFieldDefn(feat_defn.GetFieldIndex('dt2')).GetType() != ogr.OFTDateTime: - gdaltest.post_reason('failure') - return 'fail' - if feat_defn.GetFieldDefn(feat_defn.GetFieldIndex('date')).GetType() != ogr.OFTDate: - gdaltest.post_reason('failure') - return 'fail' - if feat_defn.GetFieldDefn(feat_defn.GetFieldIndex('time')).GetType() != ogr.OFTTime: - gdaltest.post_reason('failure') - return 'fail' - if feat_defn.GetFieldDefn(feat_defn.GetFieldIndex('no_dt')).GetType() != ogr.OFTString: - gdaltest.post_reason('failure') - return 'fail' - if feat_defn.GetFieldDefn(feat_defn.GetFieldIndex('no_dt2')).GetType() != ogr.OFTString: - gdaltest.post_reason('failure') - return 'fail' + assert feat_defn.GetFieldDefn(feat_defn.GetFieldIndex('dt')).GetType() == ogr.OFTDateTime + assert feat_defn.GetFieldDefn(feat_defn.GetFieldIndex('dt2')).GetType() == ogr.OFTDateTime + assert feat_defn.GetFieldDefn(feat_defn.GetFieldIndex('date')).GetType() == ogr.OFTDate + assert feat_defn.GetFieldDefn(feat_defn.GetFieldIndex('time')).GetType() == ogr.OFTTime + assert feat_defn.GetFieldDefn(feat_defn.GetFieldIndex('no_dt')).GetType() == ogr.OFTString + assert feat_defn.GetFieldDefn(feat_defn.GetFieldIndex('no_dt2')).GetType() == ogr.OFTString f = lyr.GetNextFeature() if f.GetField('dt') != '2014/11/20 12:34:56+01' or f.GetField('dt2') != '2014/11/20 00:00:00' or \ f.GetField('date') != '2014/11/20' or f.GetField('time') != '12:34:56': - gdaltest.post_reason('failure') f.DumpReadable() - return 'fail' + pytest.fail() f = lyr.GetNextFeature() if f.GetField('dt') != '2014/11/20 00:00:00' or f.GetField('dt2') != '2014/11/20 12:34:56+00' or \ f.GetField('date') != '2014/11/20' or f.GetField('time') != '12:34:56': - gdaltest.post_reason('failure') f.DumpReadable() - return 'fail' - - return 'success' + pytest.fail() + ############################################################################### # Test id top-object level -def ogr_geojson_39(): +def test_ogr_geojson_39(): if gdaltest.geojson_drv is None: - return 'skip' + pytest.skip() ds = ogr.Open("""{"type": "FeatureCollection", "features": [ { "type": "Feature", "id" : "foo", "properties": { "bar" : "baz" }, "geometry": null }, ] }""") lyr = ds.GetLayer(0) feat_defn = lyr.GetLayerDefn() - if feat_defn.GetFieldDefn(0).GetName() != 'id' or feat_defn.GetFieldDefn(0).GetType() != ogr.OFTString: - gdaltest.post_reason('fail') - return 'fail' + assert feat_defn.GetFieldDefn(0).GetName() == 'id' and feat_defn.GetFieldDefn(0).GetType() == ogr.OFTString feat = lyr.GetNextFeature() if feat.GetField('id') != 'foo' or feat.GetField('bar') != 'baz': - gdaltest.post_reason('fail') feat.DumpReadable() - return 'fail' + pytest.fail() # Crazy case: properties.id has the precedence because we arbitrarily decided that... ds = ogr.Open("""{"type": "FeatureCollection", "features": [ @@ -1897,14 +1592,11 @@ def ogr_geojson_39(): ] }""") lyr = ds.GetLayer(0) feat_defn = lyr.GetLayerDefn() - if feat_defn.GetFieldDefn(0).GetName() != 'id' or feat_defn.GetFieldDefn(0).GetType() != ogr.OFTInteger: - gdaltest.post_reason('fail') - return 'fail' + assert feat_defn.GetFieldDefn(0).GetName() == 'id' and feat_defn.GetFieldDefn(0).GetType() == ogr.OFTInteger feat = lyr.GetNextFeature() if feat.GetField('id') != 6: - gdaltest.post_reason('fail') feat.DumpReadable() - return 'fail' + pytest.fail() # Same with 2 features ds = ogr.Open("""{"type": "FeatureCollection", "features": [ @@ -1913,14 +1605,11 @@ def ogr_geojson_39(): ] }""") lyr = ds.GetLayer(0) feat_defn = lyr.GetLayerDefn() - if feat_defn.GetFieldDefn(0).GetName() != 'id' or feat_defn.GetFieldDefn(0).GetType() != ogr.OFTInteger: - gdaltest.post_reason('fail') - return 'fail' + assert feat_defn.GetFieldDefn(0).GetName() == 'id' and feat_defn.GetFieldDefn(0).GetType() == ogr.OFTInteger feat = lyr.GetNextFeature() if feat.GetField('id') != 6: - gdaltest.post_reason('fail') feat.DumpReadable() - return 'fail' + pytest.fail() # Crazy case: properties.id has the precedence because we arbitrarily decided that... ds = ogr.Open("""{"type": "FeatureCollection", "features": [ @@ -1928,14 +1617,11 @@ def ogr_geojson_39(): ] }""") lyr = ds.GetLayer(0) feat_defn = lyr.GetLayerDefn() - if feat_defn.GetFieldDefn(0).GetName() != 'id' or feat_defn.GetFieldDefn(0).GetType() != ogr.OFTString: - gdaltest.post_reason('fail') - return 'fail' + assert feat_defn.GetFieldDefn(0).GetName() == 'id' and feat_defn.GetFieldDefn(0).GetType() == ogr.OFTString feat = lyr.GetNextFeature() if feat.GetField('id') != 'baz': - gdaltest.post_reason('fail') feat.DumpReadable() - return 'fail' + pytest.fail() # id and properties.ID (#6538) ds = ogr.Open("""{"type": "FeatureCollection", "features": [ @@ -1943,14 +1629,11 @@ def ogr_geojson_39(): ] }""") lyr = ds.GetLayer(0) feat_defn = lyr.GetLayerDefn() - if feat_defn.GetFieldDefn(0).GetName() != 'ID' or feat_defn.GetFieldDefn(0).GetType() != ogr.OFTInteger: - gdaltest.post_reason('fail') - return 'fail' + assert feat_defn.GetFieldDefn(0).GetName() == 'ID' and feat_defn.GetFieldDefn(0).GetType() == ogr.OFTInteger feat = lyr.GetNextFeature() if feat.GetFID() != 1 or feat.GetField('ID') != 2: - gdaltest.post_reason('fail') feat.DumpReadable() - return 'fail' + pytest.fail() # Test handling of duplicated id gdal.ErrorReset() @@ -1960,26 +1643,21 @@ def ogr_geojson_39(): { "type": "Feature", "id" : 1, "properties": { "foo": "baz" }, "geometry": null }, { "type": "Feature", "id" : 2, "properties": { "foo": "baw" }, "geometry": null } ] }""") - if gdal.GetLastErrorMsg() == '': - gdaltest.post_reason('expected warning') - return 'fail' + assert gdal.GetLastErrorMsg() != '', 'expected warning' lyr = ds.GetLayer(0) feat_defn = lyr.GetLayerDefn() feat = lyr.GetNextFeature() if feat.GetFID() != 1 or feat.GetField('foo') != 'bar': - gdaltest.post_reason('fail') feat.DumpReadable() - return 'fail' + pytest.fail() feat = lyr.GetNextFeature() if feat.GetFID() != 2 or feat.GetField('foo') != 'baz': - gdaltest.post_reason('fail') feat.DumpReadable() - return 'fail' + pytest.fail() feat = lyr.GetNextFeature() if feat.GetFID() != 3 or feat.GetField('foo') != 'baw': - gdaltest.post_reason('fail') feat.DumpReadable() - return 'fail' + pytest.fail() # negative id ds = ogr.Open("""{"type": "FeatureCollection", "features": [ @@ -1987,14 +1665,11 @@ def ogr_geojson_39(): ] }""") lyr = ds.GetLayer(0) feat_defn = lyr.GetLayerDefn() - if feat_defn.GetFieldDefn(0).GetName() != 'id' or feat_defn.GetFieldDefn(0).GetType() != ogr.OFTInteger: - gdaltest.post_reason('fail') - return 'fail' + assert feat_defn.GetFieldDefn(0).GetName() == 'id' and feat_defn.GetFieldDefn(0).GetType() == ogr.OFTInteger feat = lyr.GetNextFeature() if feat.GetField('id') != -1: - gdaltest.post_reason('fail') feat.DumpReadable() - return 'fail' + pytest.fail() # negative id 64bit ds = ogr.Open("""{"type": "FeatureCollection", "features": [ @@ -2003,14 +1678,11 @@ def ogr_geojson_39(): ] }""") lyr = ds.GetLayer(0) feat_defn = lyr.GetLayerDefn() - if feat_defn.GetFieldDefn(0).GetName() != 'id' or feat_defn.GetFieldDefn(0).GetType() != ogr.OFTInteger64: - gdaltest.post_reason('fail') - return 'fail' + assert feat_defn.GetFieldDefn(0).GetName() == 'id' and feat_defn.GetFieldDefn(0).GetType() == ogr.OFTInteger64 feat = lyr.GetNextFeature() if feat.GetField('id') != -1234567890123: - gdaltest.post_reason('fail') feat.DumpReadable() - return 'fail' + pytest.fail() # negative id ds = ogr.Open("""{"type": "FeatureCollection", "features": [ @@ -2019,14 +1691,11 @@ def ogr_geojson_39(): ] }""") lyr = ds.GetLayer(0) feat_defn = lyr.GetLayerDefn() - if feat_defn.GetFieldDefn(0).GetName() != 'id' or feat_defn.GetFieldDefn(0).GetType() != ogr.OFTInteger64: - gdaltest.post_reason('fail') - return 'fail' + assert feat_defn.GetFieldDefn(0).GetName() == 'id' and feat_defn.GetFieldDefn(0).GetType() == ogr.OFTInteger64 feat = lyr.GetNextFeature() if feat.GetField('id') != -2: - gdaltest.post_reason('fail') feat.DumpReadable() - return 'fail' + pytest.fail() # positive and then negative id ds = ogr.Open("""{"type": "FeatureCollection", "features": [ @@ -2035,14 +1704,11 @@ def ogr_geojson_39(): ] }""") lyr = ds.GetLayer(0) feat_defn = lyr.GetLayerDefn() - if feat_defn.GetFieldDefn(1).GetName() != 'id' or feat_defn.GetFieldDefn(1).GetType() != ogr.OFTInteger: - gdaltest.post_reason('fail') - return 'fail' + assert feat_defn.GetFieldDefn(1).GetName() == 'id' and feat_defn.GetFieldDefn(1).GetType() == ogr.OFTInteger feat = lyr.GetNextFeature() if feat.GetField('id') != 1: - gdaltest.post_reason('fail') feat.DumpReadable() - return 'fail' + pytest.fail() # mix of int and string id ds = ogr.Open("""{"type": "FeatureCollection", "features": [ @@ -2052,25 +1718,21 @@ def ogr_geojson_39(): ] }""") lyr = ds.GetLayer(0) feat_defn = lyr.GetLayerDefn() - if feat_defn.GetFieldDefn(0).GetName() != 'id' or feat_defn.GetFieldDefn(0).GetType() != ogr.OFTString: - gdaltest.post_reason('fail') - return 'fail' + assert feat_defn.GetFieldDefn(0).GetName() == 'id' and feat_defn.GetFieldDefn(0).GetType() == ogr.OFTString feat = lyr.GetNextFeature() if feat.GetField('id') != '-2': - gdaltest.post_reason('fail') feat.DumpReadable() - return 'fail' - - return 'success' + pytest.fail() + ############################################################################### # Test nested attributes -def ogr_geojson_40(): +def test_ogr_geojson_40(): if gdaltest.geojson_drv is None: - return 'skip' + pytest.skip() ds = gdal.OpenEx("""{ "type": "FeatureCollection", @@ -2111,57 +1773,45 @@ def ogr_geojson_40(): feat = lyr.GetNextFeature() if feat.GetField('a_property') != 'foo' or feat.GetField('some_object.a_property') != 1 or \ feat.GetField('some_object.another_property') != 2.34: - gdaltest.post_reason('fail') feat.DumpReadable() - return 'fail' - - return 'success' + pytest.fail() + ############################################################################### # Test ogr.CreateGeometryFromJson() -def ogr_geojson_41(): +def test_ogr_geojson_41(): if gdaltest.geojson_drv is None: - return 'skip' + pytest.skip() # Check that by default we return a WGS 84 SRS g = ogr.CreateGeometryFromJson("{ 'type': 'Point', 'coordinates' : [ 2, 49] }") - if g.ExportToWkt() != 'POINT (2 49)': - gdaltest.post_reason('fail') - return 'fail' + assert g.ExportToWkt() == 'POINT (2 49)' srs = g.GetSpatialReference() g = None - if srs.ExportToWkt().find('WGS 84') < 0: - gdaltest.post_reason('fail') - return 'fail' + assert srs.ExportToWkt().find('WGS 84') >= 0 # But if a crs object is set (allowed originally, but not recommended!), we use it g = ogr.CreateGeometryFromJson('{ "type": "Point", "coordinates" : [ 2, 49], "crs": { "type": "name", "properties": { "name": "urn:ogc:def:crs:EPSG::4322" } } }') srs = g.GetSpatialReference() - if srs.ExportToWkt().find('4322') < 0: - gdaltest.post_reason('fail') - return 'fail' + assert srs.ExportToWkt().find('4322') >= 0 # But if a crs object is set to null, set no crs g = ogr.CreateGeometryFromJson('{ "type": "Point", "coordinates" : [ 2, 49], "crs": null }') srs = g.GetSpatialReference() - if srs: - gdaltest.post_reason('fail') - return 'fail' - - return 'success' + assert not srs ############################################################################### # Test ESRI FeatureService scrolling -def ogr_geojson_42(): +def test_ogr_geojson_42(): if gdaltest.geojson_drv is None: - return 'skip' + pytest.skip() gdal.SetConfigOption('CPL_CURL_ENABLE_VSIMEM', 'YES') @@ -2188,13 +1838,9 @@ def ogr_geojson_42(): ds = ogr.Open('/vsimem/geojson/test.json?resultRecordCount=1') lyr = ds.GetLayer(0) f = lyr.GetNextFeature() - if f is None or f.GetFID() != 1: - gdaltest.post_reason('fail') - return 'fail' + assert f is not None and f.GetFID() == 1 f = lyr.GetNextFeature() - if f is not None: - gdaltest.post_reason('fail') - return 'fail' + assert f is None ds = None gdal.Unlink('/vsimem/geojson/test.json?resultRecordCount=1') @@ -2204,13 +1850,9 @@ def ogr_geojson_42(): gdal.PopErrorHandler() lyr = ds.GetLayer(0) f = lyr.GetNextFeature() - if f is None or f.GetFID() != 1: - gdaltest.post_reason('fail') - return 'fail' + assert f is not None and f.GetFID() == 1 f = lyr.GetNextFeature() - if f is not None: - gdaltest.post_reason('fail') - return 'fail' + assert f is None ds = None gdal.Unlink('/vsimem/geojson/test.json?resultRecordCount=10') @@ -2220,18 +1862,12 @@ def ogr_geojson_42(): ds = ogr.Open('/vsimem/geojson/test.json?') lyr = ds.GetLayer(0) f = lyr.GetNextFeature() - if f is None or f.GetFID() != 1: - gdaltest.post_reason('fail') - return 'fail' + assert f is not None and f.GetFID() == 1 f = lyr.GetNextFeature() - if f is not None: - gdaltest.post_reason('fail') - return 'fail' + assert f is None lyr.ResetReading() f = lyr.GetNextFeature() - if f is None or f.GetFID() != 1: - gdaltest.post_reason('fail') - return 'fail' + assert f is not None and f.GetFID() == 1 resultOffset1 = """ { "type":"FeatureCollection", @@ -2250,55 +1886,35 @@ def ogr_geojson_42(): } ] }""" gdal.FileFromMemBuffer('/vsimem/geojson/test.json?resultRecordCount=1&resultOffset=1', resultOffset1) f = lyr.GetNextFeature() - if f is None or f.GetFID() != 2: - gdaltest.post_reason('fail') - return 'fail' + assert f is not None and f.GetFID() == 2 f = lyr.GetNextFeature() - if f is not None: - gdaltest.post_reason('fail') - return 'fail' + assert f is None gdal.PushErrorHandler() fc = lyr.GetFeatureCount() gdal.PopErrorHandler() - if fc != 2: - gdaltest.post_reason('fail') - return 'fail' + assert fc == 2 gdal.FileFromMemBuffer('/vsimem/geojson/test.json?resultRecordCount=1&returnCountOnly=true', """{ "count": 123456}""") fc = lyr.GetFeatureCount() - if fc != 123456: - gdaltest.post_reason('fail') - return 'fail' + assert fc == 123456 gdal.PushErrorHandler() extent = lyr.GetExtent() gdal.PopErrorHandler() - if extent != (2, 2, 49, 49): - gdaltest.post_reason('fail') - print(extent) - return 'fail' + assert extent == (2, 2, 49, 49) gdal.FileFromMemBuffer('/vsimem/geojson/test.json?resultRecordCount=1&returnExtentOnly=true&f=geojson', """{"type":"FeatureCollection","bbox":[1, 2, 3, 4],"features":[]}""") extent = lyr.GetExtent() - if extent != (1.0, 3.0, 2.0, 4.0): - gdaltest.post_reason('fail') - print(extent) - return 'fail' + assert extent == (1.0, 3.0, 2.0, 4.0) - if lyr.TestCapability(ogr.OLCFastFeatureCount) != 1: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.TestCapability(ogr.OLCFastFeatureCount) == 1 - if lyr.TestCapability(ogr.OLCFastGetExtent) != 0: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.TestCapability(ogr.OLCFastGetExtent) == 0 - if lyr.TestCapability('foo') != 0: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.TestCapability('foo') == 0 # Test scrolling with ESRI json resultOffset0 = """ @@ -2357,65 +1973,54 @@ def ogr_geojson_42(): ds = ogr.Open('/vsimem/geojson/test.json?resultRecordCount=1') lyr = ds.GetLayer(0) f = lyr.GetNextFeature() - if f is None or f.GetFID() != 1: - gdaltest.post_reason('fail') - return 'fail' + assert f is not None and f.GetFID() == 1 f = lyr.GetNextFeature() - if f is None or f.GetFID() != 20: - gdaltest.post_reason('fail') - return 'fail' + assert f is not None and f.GetFID() == 20 ds = None gdal.Unlink('/vsimem/geojson/test.json?resultRecordCount=1') gdal.Unlink('/vsimem/geojson/test.json?resultRecordCount=1&resultOffset=1') - return 'success' - ############################################################################### # Test Feature without geometry -def ogr_geojson_43(): +def test_ogr_geojson_43(): if gdaltest.geojson_drv is None: - return 'skip' + pytest.skip() ds = ogr.Open("""{"type": "FeatureCollection", "features":[ {"type": "Feature", "properties": {"foo": "bar"}}]}""") - if ds is None: - gdaltest.post_reason('Failed to open datasource') - return 'fail' + assert ds is not None, 'Failed to open datasource' lyr = ds.GetLayerByName('OGRGeoJSON') feature = lyr.GetNextFeature() if feature.GetFieldAsString("foo") != 'bar': feature.DumpReadable() - return 'fail' + pytest.fail() lyr = None ds = None - return 'success' - ############################################################################### # Test null Feature (#6166) -def ogr_geojson_44(): +def test_ogr_geojson_44(): if gdaltest.geojson_drv is None: - return 'skip' + pytest.skip() with gdaltest.error_handler(): ogr.Open("""{"type": "FeatureCollection", "features":[ null ]}""") - return 'success' - + ############################################################################### # Test native data support -def ogr_geojson_45(): +def test_ogr_geojson_45(): if gdaltest.geojson_drv is None: - return 'skip' + pytest.skip() # Test read support content = """{"type": "FeatureCollection", "foo": "bar", "bar": "baz", @@ -2428,15 +2033,9 @@ def ogr_geojson_45(): ds = gdal.OpenEx('/vsimem/ogr_geojson_45.json', gdal.OF_VECTOR, open_options=['NATIVE_DATA=YES']) lyr = ds.GetLayer(0) native_data = lyr.GetMetadataItem("NATIVE_DATA", "NATIVE_DATA") - if native_data != '{ "foo": "bar", "bar": "baz" }': - gdaltest.post_reason('fail') - print(native_data) - return 'fail' + assert native_data == '{ "foo": "bar", "bar": "baz" }' native_media_type = lyr.GetMetadataItem("NATIVE_MEDIA_TYPE", "NATIVE_DATA") - if native_media_type != 'application/vnd.geo+json': - gdaltest.post_reason('fail') - print(native_media_type) - return 'fail' + assert native_media_type == 'application/vnd.geo+json' f = lyr.GetNextFeature() native_data = f.GetNativeData() if i == 0: @@ -2445,15 +2044,9 @@ def ogr_geojson_45(): '{ "type": "Feature", "foo": [ "bar", "baz", 1.0, true, false, [ ], { } ], "properties": { "myprop": "myvalue" }, "geometry": null }'] else: expected = ['{"type":"Feature","foo":["bar","baz",1.0,true,false,[],{}],"properties":{"myprop":"myvalue"},"geometry":null}'] - if native_data not in expected: - gdaltest.post_reason('fail') - print(native_data) - return 'fail' + assert native_data in expected native_media_type = f.GetNativeMediaType() - if native_media_type != 'application/vnd.geo+json': - gdaltest.post_reason('fail') - print(native_media_type) - return 'fail' + assert native_media_type == 'application/vnd.geo+json' ds = None if i == 1: gdal.Unlink('/vsimem/ogr_geojson_45.json') @@ -2483,19 +2076,16 @@ def ogr_geojson_45(): gdal.Unlink('/vsimem/ogr_geojson_45.json') - if data.find('"bbox": [ 0, 1, 2, 0, 1, 2 ],') < 0 or \ - data.find('"foo": "bar"') < 0 or data.find('"bar": "baz"') < 0 or \ - data.find('"foo_feature": "bar_feature"') < 0 or \ - data.find('"foo_gc": "bar_gc"') < 0 or \ - data.find('"foo_point": "bar_point"') < 0 or data.find('3') < 0 or \ - data.find('"foo_linestring": "bar_linestring"') < 0 or data.find('4') < 0 or \ - data.find('"foo_multipoint": "bar_multipoint"') < 0 or data.find('5') < 0 or \ - data.find('"foo_multilinestring": "bar_multilinestring"') < 0 or data.find('6') < 0 or \ - data.find('"foo_polygon": "bar_polygon"') < 0 or data.find('7') < 0 or \ - data.find('"foo_multipolygon": "bar_multipolygon"') < 0 or data.find('8') < 0: - gdaltest.post_reason('fail') - print(data) - return 'fail' + assert (data.find('"bbox": [ 0, 1, 2, 0, 1, 2 ],') >= 0 and \ + data.find('"foo": "bar"') >= 0 and data.find('"bar": "baz"') >= 0 and \ + data.find('"foo_feature": "bar_feature"') >= 0 and \ + data.find('"foo_gc": "bar_gc"') >= 0 and \ + data.find('"foo_point": "bar_point"') >= 0 and data.find('3') >= 0 and \ + data.find('"foo_linestring": "bar_linestring"') >= 0 and data.find('4') >= 0 and \ + data.find('"foo_multipoint": "bar_multipoint"') >= 0 and data.find('5') >= 0 and \ + data.find('"foo_multilinestring": "bar_multilinestring"') >= 0 and data.find('6') >= 0 and \ + data.find('"foo_polygon": "bar_polygon"') >= 0 and data.find('7') >= 0 and \ + data.find('"foo_multipolygon": "bar_multipolygon"') >= 0 and data.find('8') >= 0) # Test native support with string id src_ds = gdal.OpenEx("""{ @@ -2520,10 +2110,7 @@ def ogr_geojson_45(): ] } """ - if json.loads(got) != json.loads(expected): - gdaltest.post_reason('fail') - print(got) - return 'fail' + assert json.loads(got) == json.loads(expected) # Test native support with numeric id src_ds = gdal.OpenEx("""{ @@ -2548,20 +2135,15 @@ def ogr_geojson_45(): ] } """ - if json.loads(got) != json.loads(expected): - gdaltest.post_reason('fail') - print(got) - return 'fail' - - return 'success' + assert json.loads(got) == json.loads(expected) ############################################################################### # Test that writing JSon content as value of a string field is serialized as it -def ogr_geojson_46(): +def test_ogr_geojson_46(): if gdaltest.geojson_drv is None: - return 'skip' + pytest.skip() ds = ogr.GetDriverByName('GeoJSON').CreateDataSource('/vsimem/ogr_geojson_46.json') lyr = ds.CreateLayer('test') @@ -2577,27 +2159,20 @@ def ogr_geojson_46(): gdal.Unlink('/vsimem/ogr_geojson_46.json') - if data.find('{ "myprop": { "a": "b" } }') < 0: - gdaltest.post_reason('fail') - print(data) - return 'fail' - - return 'success' + assert data.find('{ "myprop": { "a": "b" } }') >= 0 ############################################################################### # Test update support -def ogr_geojson_47(): +def test_ogr_geojson_47(): if gdaltest.geojson_drv is None: - return 'skip' + pytest.skip() # ERROR 6: Update from inline definition not supported with gdaltest.error_handler(): ds = ogr.Open('{"type": "FeatureCollection", "features":[]}', update=1) - if ds is not None: - gdaltest.post_reason('fail') - return 'fail' + assert ds is None gdal.FileFromMemBuffer('/vsimem/ogr_geojson_47.json', """{"type": "FeatureCollection", "foo": "bar", @@ -2619,12 +2194,9 @@ def ogr_geojson_47(): data = None # we don't want crs if there's no in the source - if data.find('"foo": "bar"') < 0 or data.find('"bar": "baz"') < 0 or \ - data.find('crs') >= 0 or \ - data.find('"myprop": "another_value"') < 0: - gdaltest.post_reason('fail') - print(data) - return 'fail' + assert (data.find('"foo": "bar"') >= 0 and data.find('"bar": "baz"') >= 0 and \ + data.find('crs') < 0 and \ + data.find('"myprop": "another_value"') >= 0) # Test append support ds = ogr.Open('/vsimem/ogr_geojson_47.json', update=1) @@ -2633,17 +2205,15 @@ def ogr_geojson_47(): f.SetGeometry(ogr.CreateGeometryFromWkt('POINT(1 2)')) lyr.CreateFeature(f) if f.GetFID() != 1: - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' + pytest.fail() f = ogr.Feature(lyr.GetLayerDefn()) f.SetGeometry(ogr.CreateGeometryFromWkt('POINT(2 3)')) lyr.CreateFeature(f) f = lyr.GetNextFeature() if f.GetFID() != 0: - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' + pytest.fail() ds = None # Test append support @@ -2658,9 +2228,7 @@ def ogr_geojson_47(): ds = ogr.Open('/vsimem/ogr_geojson_47.json') lyr = ds.GetLayer(0) - if lyr.GetFeatureCount() != 4: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.GetFeatureCount() == 4 ds = None fp = gdal.VSIFOpenL('/vsimem/ogr_geojson_47.json', 'rb') @@ -2671,14 +2239,11 @@ def ogr_geojson_47(): data = None # we don't want crs if there's no in the source - if data.find('"foo": "bar"') < 0 or data.find('"bar": "baz"') < 0 or \ - data.find('crs') >= 0 or \ - data.find('"myprop": "another_value"') < 0 or \ - data.find('"myprop": "value_of_point_4_5"') < 0 or \ - data.find('id') >= 0: - gdaltest.post_reason('fail') - print(data) - return 'fail' + assert (data.find('"foo": "bar"') >= 0 and data.find('"bar": "baz"') >= 0 and \ + data.find('crs') < 0 and \ + data.find('"myprop": "another_value"') >= 0 and \ + data.find('"myprop": "value_of_point_4_5"') >= 0 and \ + data.find('id') < 0) gdal.Unlink('/vsimem/ogr_geojson_47.json') @@ -2691,9 +2256,7 @@ def ogr_geojson_47(): ds = None ds = ogr.Open('/vsimem/ogr_geojson_47.json') lyr = ds.GetLayer(0) - if lyr.GetFeatureCount() != 1: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.GetFeatureCount() == 1 ds = None # Test appending to array ending with non feature @@ -2705,9 +2268,7 @@ def ogr_geojson_47(): ds = None ds = ogr.Open('/vsimem/ogr_geojson_47.json') lyr = ds.GetLayer(0) - if lyr.GetFeatureCount() != 1: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.GetFeatureCount() == 1 ds = None # Test appending to feature collection not ending with "features" @@ -2719,9 +2280,7 @@ def ogr_geojson_47(): ds = None ds = ogr.Open('/vsimem/ogr_geojson_47.json') lyr = ds.GetLayer(0) - if lyr.GetFeatureCount() != 1: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.GetFeatureCount() == 1 ds = None fp = gdal.VSIFOpenL('/vsimem/ogr_geojson_47.json', 'rb') @@ -2731,10 +2290,7 @@ def ogr_geojson_47(): else: data = None - if data.find('something') < 0: - gdaltest.post_reason('fail') - print(data) - return 'fail' + assert data.find('something') >= 0 # Test appending to feature collection with "bbox" gdal.FileFromMemBuffer('/vsimem/ogr_geojson_47.json', """{ "type": "FeatureCollection", "bbox": [0,0,0,0], "features": [ { "type": "Feature", "geometry": { "type": "Point", "coordinates": [0,0]} } ]}""") @@ -2745,9 +2301,7 @@ def ogr_geojson_47(): ds = None ds = ogr.Open('/vsimem/ogr_geojson_47.json') lyr = ds.GetLayer(0) - if lyr.GetFeatureCount() != 2: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.GetFeatureCount() == 2 ds = None fp = gdal.VSIFOpenL('/vsimem/ogr_geojson_47.json', 'rb') @@ -2757,22 +2311,17 @@ def ogr_geojson_47(): else: data = None - if data.find('bbox') < 0: - gdaltest.post_reason('fail') - print(data) - return 'fail' + assert data.find('bbox') >= 0 gdal.Unlink('/vsimem/ogr_geojson_47.json') - return 'success' - ############################################################################### # Test update support with file that has a single feature not in a FeatureCollection -def ogr_geojson_48(): +def test_ogr_geojson_48(): if gdaltest.geojson_drv is None: - return 'skip' + pytest.skip() gdal.FileFromMemBuffer('/vsimem/ogr_geojson_48.json', """{ "type": "Feature", "bar": "baz", "bbox": [2,49,2,49], "properties": { "myprop": "myvalue" }, "geometry": {"type": "Point", "coordinates": [ 2, 49]} }""") @@ -2796,24 +2345,19 @@ def ogr_geojson_48(): gdal.Unlink('/vsimem/ogr_geojson_48.json') # we don't want crs if there's no in the source - if data.find('"bar": "baz"') < 0 or \ - data.find('"bbox": [ 3.0, 50.0, 3.0, 50.0 ]') < 0 or \ - data.find('crs') >= 0 or \ - data.find('FeatureCollection') >= 0 or \ - data.find('"myprop": "another_value"') < 0: - gdaltest.post_reason('fail') - print(data) - return 'fail' - - return 'success' + assert (data.find('"bar": "baz"') >= 0 and \ + data.find('"bbox": [ 3.0, 50.0, 3.0, 50.0 ]') >= 0 and \ + data.find('crs') < 0 and \ + data.find('FeatureCollection') < 0 and \ + data.find('"myprop": "another_value"') >= 0) ############################################################################### # Test ARRAY_AS_STRING -def ogr_geojson_49(): +def test_ogr_geojson_49(): if gdaltest.geojson_drv is None: - return 'skip' + pytest.skip() gdal.FileFromMemBuffer('/vsimem/ogr_geojson_49.json', """{ "type": "Feature", "properties": { "foo": ["bar"] }, "geometry": null }""") @@ -2821,27 +2365,22 @@ def ogr_geojson_49(): # Test read support ds = gdal.OpenEx('/vsimem/ogr_geojson_49.json', open_options=['ARRAY_AS_STRING=YES']) lyr = ds.GetLayer(0) - if lyr.GetLayerDefn().GetFieldDefn(0).GetType() != ogr.OFTString: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.GetLayerDefn().GetFieldDefn(0).GetType() == ogr.OFTString f = lyr.GetNextFeature() if f['foo'] != '[ "bar" ]': - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' + pytest.fail() ds = None gdal.Unlink('/vsimem/ogr_geojson_49.json') - return 'success' - ############################################################################### # Test that we serialize floating point values with enough significant figures -def ogr_geojson_50(): +def test_ogr_geojson_50(): if gdaltest.geojson_drv is None: - return 'skip' + pytest.skip() ds = ogr.GetDriverByName('GeoJSON').CreateDataSource('/vsimem/ogr_geojson_50.json') lyr = ds.CreateLayer('test') @@ -2862,10 +2401,7 @@ def ogr_geojson_50(): gdal.Unlink('/vsimem/ogr_geojson_50.json') - if data.find('1.23456789012456') < 0 and data.find('5268.813 ') < 0: - gdaltest.post_reason('fail') - print(data) - return 'fail' + assert data.find('1.23456789012456') >= 0 or data.find('5268.813 ') >= 0 # If SIGNIFICANT_FIGURES is explicitly specified, and COORDINATE_PRECISION not, # then it also applies to coordinates @@ -2884,10 +2420,7 @@ def ogr_geojson_50(): gdal.Unlink('/vsimem/ogr_geojson_50.json') - if data.find('1.23456789012456') < 0 and data.find('-5') < 0: - gdaltest.post_reason('fail') - print(data) - return 'fail' + assert data.find('1.23456789012456') >= 0 or data.find('-5') >= 0 # If SIGNIFICANT_FIGURES is explicitly specified, and COORDINATE_PRECISION too, # then SIGNIFICANT_FIGURES only applies to non-coordinates floating point values. @@ -2907,20 +2440,15 @@ def ogr_geojson_50(): gdal.Unlink('/vsimem/ogr_geojson_50.json') - if data.find('0.00001234') < 0 or data.find('1.23456789012456') < 0: - gdaltest.post_reason('fail') - print(data) - return 'fail' - - return 'success' + assert data.find('0.00001234') >= 0 and data.find('1.23456789012456') >= 0 ############################################################################### # Test writing empty geometries -def ogr_geojson_51(): +def test_ogr_geojson_51(): if gdaltest.geojson_drv is None: - return 'skip' + pytest.skip() ds = ogr.GetDriverByName('GeoJSON').CreateDataSource('/vsimem/ogr_geojson_51.json') lyr = ds.CreateLayer('test') @@ -2962,90 +2490,53 @@ def ogr_geojson_51(): gdal.Unlink('/vsimem/ogr_geojson_51.json') - if data.find('{ "id": 1 }, "geometry": null') < 0: - gdaltest.post_reason('fail') - print(data) - return 'fail' - - if data.find('{ "id": 2 }, "geometry": { "type": "LineString", "coordinates": [ ] } }') < 0: - gdaltest.post_reason('fail') - print(data) - return 'fail' + assert data.find('{ "id": 1 }, "geometry": null') >= 0 - if data.find('{ "id": 3 }, "geometry": { "type": "Polygon", "coordinates": [ ] } }') < 0: - gdaltest.post_reason('fail') - print(data) - return 'fail' + assert data.find('{ "id": 2 }, "geometry": { "type": "LineString", "coordinates": [ ] } }') >= 0 - if data.find('{ "id": 4 }, "geometry": { "type": "MultiPoint", "coordinates": [ ] } }') < 0: - gdaltest.post_reason('fail') - print(data) - return 'fail' + assert data.find('{ "id": 3 }, "geometry": { "type": "Polygon", "coordinates": [ ] } }') >= 0 - if data.find('{ "id": 5 }, "geometry": { "type": "MultiLineString", "coordinates": [ ] } }') < 0: - gdaltest.post_reason('fail') - print(data) - return 'fail' + assert data.find('{ "id": 4 }, "geometry": { "type": "MultiPoint", "coordinates": [ ] } }') >= 0 - if data.find('{ "id": 6 }, "geometry": { "type": "MultiPolygon", "coordinates": [ ] } }') < 0: - gdaltest.post_reason('fail') - print(data) - return 'fail' + assert data.find('{ "id": 5 }, "geometry": { "type": "MultiLineString", "coordinates": [ ] } }') >= 0 - if data.find('{ "id": 7 }, "geometry": { "type": "GeometryCollection", "geometries": [ ] } }') < 0: - gdaltest.post_reason('fail') - print(data) - return 'fail' + assert data.find('{ "id": 6 }, "geometry": { "type": "MultiPolygon", "coordinates": [ ] } }') >= 0 - return 'success' + assert data.find('{ "id": 7 }, "geometry": { "type": "GeometryCollection", "geometries": [ ] } }') >= 0 ############################################################################### # Test NULL type detection -def ogr_geojson_52(): +def test_ogr_geojson_52(): if gdaltest.geojson_drv is None: - return 'skip' + pytest.skip() ds = ogr.Open('data/nullvalues.geojson') - if ds is None: - gdaltest.post_reason('Failed to open datasource') - return 'fail' + assert ds is not None, 'Failed to open datasource' - if ds.GetLayerCount() is not 1: - gdaltest.post_reason('Wrong number of layers') - return 'fail' + assert ds.GetLayerCount() is 1, 'Wrong number of layers' lyr = ds.GetLayerByName('nullvalues') - if lyr is None: - gdaltest.post_reason('Missing layer called nullvalues') - return 'fail' + assert lyr is not None, 'Missing layer called nullvalues' fld = lyr.GetLayerDefn().GetFieldDefn(0) - if fld.GetNameRef() != 'int': - return 'fail' - if fld.GetType() != ogr.OFTInteger: - return 'fail' + assert fld.GetNameRef() == 'int' + assert fld.GetType() == ogr.OFTInteger fld = lyr.GetLayerDefn().GetFieldDefn(1) - if fld.GetNameRef() != 'string': - return 'fail' - if fld.GetType() != ogr.OFTString: - return 'fail' + assert fld.GetNameRef() == 'string' + assert fld.GetType() == ogr.OFTString fld = lyr.GetLayerDefn().GetFieldDefn(2) - if fld.GetNameRef() != 'double': - return 'fail' - if fld.GetType() != ogr.OFTReal: - return 'fail' - - return 'success' + assert fld.GetNameRef() == 'double' + assert fld.GetType() == ogr.OFTReal ############################################################################### # Test that M is ignored (this is a test of OGRLayer::CreateFeature() actually) -def ogr_geojson_53(): +def test_ogr_geojson_53(): if gdaltest.geojson_drv is None: - return 'skip' + pytest.skip() ds = ogr.GetDriverByName('GeoJSON').CreateDataSource('/vsimem/ogr_geojson_53.json') lyr = ds.CreateLayer('test') @@ -3060,20 +2551,15 @@ def ogr_geojson_53(): gdal.Unlink('/vsimem/ogr_geojson_53.json') - if data.find('{ "type": "Point", "coordinates": [ 1.0, 2.0, 3.0 ] }') < 0: - gdaltest.post_reason('fail') - print(data) - return 'fail' - - return 'success' + assert data.find('{ "type": "Point", "coordinates": [ 1.0, 2.0, 3.0 ] }') >= 0 ############################################################################### # Test NULL type detection when first value is null -def ogr_geojson_54(): +def test_ogr_geojson_54(): if gdaltest.geojson_drv is None: - return 'skip' + pytest.skip() ds = ogr.Open("""{ "type": "FeatureCollection", @@ -3087,36 +2573,19 @@ def ogr_geojson_54(): lyr = ds.GetLayer(0) fld = lyr.GetLayerDefn().GetFieldDefn(0) - if fld.GetType() != ogr.OFTInteger: - gdaltest.post_reason('fail') - return 'fail' + assert fld.GetType() == ogr.OFTInteger fld = lyr.GetLayerDefn().GetFieldDefn(1) - if fld.GetType() != ogr.OFTString: - gdaltest.post_reason('fail') - return 'fail' + assert fld.GetType() == ogr.OFTString fld = lyr.GetLayerDefn().GetFieldDefn(2) - if fld.GetType() != ogr.OFTReal: - gdaltest.post_reason('fail') - return 'fail' + assert fld.GetType() == ogr.OFTReal fld = lyr.GetLayerDefn().GetFieldDefn(3) - if fld.GetType() != ogr.OFTDateTime: - gdaltest.post_reason('fail') - return 'fail' + assert fld.GetType() == ogr.OFTDateTime fld = lyr.GetLayerDefn().GetFieldDefn(4) - if fld.GetType() != ogr.OFTInteger: - gdaltest.post_reason('fail') - return 'fail' - if fld.GetSubType() != ogr.OFSTBoolean: - gdaltest.post_reason('fail') - return 'fail' - if fld.GetWidth() != 1: - gdaltest.post_reason('fail') - return 'fail' + assert fld.GetType() == ogr.OFTInteger + assert fld.GetSubType() == ogr.OFSTBoolean + assert fld.GetWidth() == 1 fld = lyr.GetLayerDefn().GetFieldDefn(5) - if fld.GetType() != ogr.OFTString: - gdaltest.post_reason('fail') - return 'fail' - return 'success' + assert fld.GetType() == ogr.OFTString ############################################################################### # Test RFC 7946 @@ -3131,9 +2600,9 @@ def read_file(filename): return content -def ogr_geojson_55(): +def test_ogr_geojson_55(): if gdaltest.geojson_drv is None: - return 'skip' + pytest.skip() # Basic test for standard bbox and coordinate truncation gdal.VectorTranslate('/vsimem/out.json', """{ @@ -3155,10 +2624,7 @@ def ogr_geojson_55(): ] } """ - if json.loads(got) != json.loads(expected): - gdaltest.post_reason('fail') - print(got) - return 'fail' + assert json.loads(got) == json.loads(expected) # Test polygon winding order gdal.VectorTranslate('/vsimem/out.json', """{ @@ -3181,10 +2647,7 @@ def ogr_geojson_55(): ] } """ - if json.loads(got) != json.loads(expected): - gdaltest.post_reason('fail') - print(got) - return 'fail' + assert json.loads(got) == json.loads(expected) # Test foreign member src_ds = gdal.OpenEx("""{ @@ -3233,22 +2696,17 @@ def ogr_geojson_55(): ] } """ - if json.loads(got) != json.loads(expected): - gdaltest.post_reason('fail') - print(got) - return 'fail' - - return 'success' + assert json.loads(got) == json.loads(expected) ############################################################################### # Test RFC 7946 (that require geos) -def ogr_geojson_56(): +def test_ogr_geojson_56(): if gdaltest.geojson_drv is None: - return 'skip' + pytest.skip() if not ogrtest.have_geos(): - return 'skip' + pytest.skip() # Test offsetting longitudes beyond antimeridian gdal.VectorTranslate('/vsimem/out.json', """{ @@ -3278,10 +2736,7 @@ def ogr_geojson_56(): ] } """ - if json.loads(got) != json.loads(expected): - gdaltest.post_reason('fail') - print(got) - return 'fail' + assert json.loads(got) == json.loads(expected) # Test geometries across the antimeridian gdal.VectorTranslate('/vsimem/out.json', """{ @@ -3309,22 +2764,17 @@ def ogr_geojson_56(): ] } """ - if json.loads(got) != json.loads(expected): - gdaltest.post_reason('fail') - print(got) - return 'fail' - - return 'success' + assert json.loads(got) == json.loads(expected) ############################################################################### # Test RFC 7946 and reprojection -def ogr_geojson_57(): +def test_ogr_geojson_57(): if gdaltest.geojson_drv is None: - return 'skip' + pytest.skip() if not ogrtest.have_geos(): - return 'skip' + pytest.skip() # Standard case: EPSG:32662: WGS 84 / Plate Carre src_ds = gdal.GetDriverByName('Memory').Create('', 0, 0, 0) @@ -3347,10 +2797,7 @@ def ogr_geojson_57(): ] } """ - if json.loads(got) != json.loads(expected): - gdaltest.post_reason('fail') - print(got) - return 'fail' + assert json.loads(got) == json.loads(expected) # Polar case: EPSG:3995: WGS 84 / Arctic Polar Stereographic src_ds = gdal.GetDriverByName('Memory').Create('', 0, 0, 0) @@ -3377,10 +2824,7 @@ def ogr_geojson_57(): ] } """ - if json.loads(got) != json.loads(expected): - gdaltest.post_reason('fail') - print(got) - return 'fail' + assert json.loads(got) == json.loads(expected) # Polar case: slice of spherical cap (not intersecting antimeridian, west hemisphere) src_ds = gdal.GetDriverByName('Memory').Create('', 0, 0, 0) @@ -3403,10 +2847,7 @@ def ogr_geojson_57(): ] } """ - if json.loads(got) != json.loads(expected): - gdaltest.post_reason('fail') - print(got) - return 'fail' + assert json.loads(got) == json.loads(expected) # Polar case: slice of spherical cap (not intersecting antimeridian, east hemisphere) src_ds = gdal.GetDriverByName('Memory').Create('', 0, 0, 0) @@ -3429,10 +2870,7 @@ def ogr_geojson_57(): ] } """ - if json.loads(got) != json.loads(expected): - gdaltest.post_reason('fail') - print(got) - return 'fail' + assert json.loads(got) == json.loads(expected) # Polar case: slice of spherical cap crossing the antimeridian src_ds = gdal.GetDriverByName('Memory').Create('', 0, 0, 0) @@ -3455,10 +2893,7 @@ def ogr_geojson_57(): ] } """ - if json.loads(got) != json.loads(expected): - gdaltest.post_reason('fail') - print(got) - return 'fail' + assert json.loads(got) == json.loads(expected) # Polar case: EPSG:3031: WGS 84 / Antarctic Polar Stereographic src_ds = gdal.GetDriverByName('Memory').Create('', 0, 0, 0) @@ -3481,10 +2916,7 @@ def ogr_geojson_57(): ] } """ - if json.loads(got) != json.loads(expected): - gdaltest.post_reason('fail') - print(got) - return 'fail' + assert json.loads(got) == json.loads(expected) # Antimeridian case: EPSG:32660: WGS 84 / UTM zone 60N with polygon and line crossing src_ds = gdal.GetDriverByName('Memory').Create('', 0, 0, 0) @@ -3528,10 +2960,7 @@ def ogr_geojson_57(): } """ - if json.loads(got) != json.loads(expected) and json.loads(got) != json.loads(expected2): - gdaltest.post_reason('fail') - print(got) - return 'fail' + assert json.loads(got) == json.loads(expected) or json.loads(got) == json.loads(expected2) # Antimeridian case: EPSG:32660: WGS 84 / UTM zone 60N wit polygon on west of antimeridian src_ds = gdal.GetDriverByName('Memory').Create('', 0, 0, 0) @@ -3554,61 +2983,45 @@ def ogr_geojson_57(): ] } """ - if json.loads(got) != json.loads(expected): - gdaltest.post_reason('fail') - print(got) - return 'fail' - - return 'success' + assert json.loads(got) == json.loads(expected) ############################################################################### # Test using the name member of FeatureCollection -def ogr_geojson_58(): +def test_ogr_geojson_58(): if gdaltest.geojson_drv is None: - return 'skip' + pytest.skip() ds = ogr.Open('{ "type": "FeatureCollection", "name": "layer_name", "features": []}') - if ds is None: - gdaltest.post_reason('Failed to open datasource') - return 'fail' + assert ds is not None, 'Failed to open datasource' lyr = ds.GetLayerByName('layer_name') - if lyr is None: - gdaltest.post_reason('Missing layer called layer_name') - return 'fail' + assert lyr is not None, 'Missing layer called layer_name' ds = None ds = ogr.GetDriverByName('GeoJSON').CreateDataSource('/vsimem/ogr_geojson_58.json') lyr = ds.CreateLayer('foo') ds = None ds = ogr.Open('/vsimem/ogr_geojson_58.json') - if ds.GetLayerByName('foo') is None: - gdaltest.post_reason('Missing layer called foo') - return 'fail' + assert ds.GetLayerByName('foo') is not None, 'Missing layer called foo' ds = None gdal.Unlink('/vsimem/ogr_geojson_58.json') - return 'success' - ############################################################################### # Test using the description member of FeatureCollection -def ogr_geojson_59(): +def test_ogr_geojson_59(): if gdaltest.geojson_drv is None: - return 'skip' + pytest.skip() ds = ogr.Open('{ "type": "FeatureCollection", "description": "my_description", "features": []}') - if ds is None: - gdaltest.post_reason('Failed to open datasource') - return 'fail' + assert ds is not None, 'Failed to open datasource' lyr = ds.GetLayer(0) - if lyr.GetMetadataItem('DESCRIPTION') != 'my_description': - gdaltest.post_reason('Did not get DESCRIPTION') - return 'fail' + assert lyr.GetMetadataItem('DESCRIPTION') == 'my_description', \ + 'Did not get DESCRIPTION' ds = None ds = ogr.GetDriverByName('GeoJSON').CreateDataSource('/vsimem/ogr_geojson_59.json') @@ -3616,21 +3029,17 @@ def ogr_geojson_59(): ds = None ds = ogr.Open('/vsimem/ogr_geojson_59.json') lyr = ds.GetLayerByName('foo') - if lyr.GetMetadataItem('DESCRIPTION') != 'my desc': - gdaltest.post_reason('Did not get DESCRIPTION') - return 'fail' + assert lyr.GetMetadataItem('DESCRIPTION') == 'my desc', 'Did not get DESCRIPTION' ds = None gdal.Unlink('/vsimem/ogr_geojson_59.json') - return 'success' - ############################################################################### # Test null vs unset field -def ogr_geojson_60(): +def test_ogr_geojson_60(): if gdaltest.geojson_drv is None: - return 'skip' + pytest.skip() ds = gdal.OpenEx("""{ "type": "FeatureCollection", "features": [ { "type": "Feature", "properties" : { "foo" : "bar" } }, @@ -3639,19 +3048,16 @@ def ogr_geojson_60(): lyr = ds.GetLayer(0) f = lyr.GetNextFeature() if f['foo'] != 'bar': - gdaltest.post_reason('failure') f.DumpReadable() - return 'fail' + pytest.fail() f = lyr.GetNextFeature() if not f.IsFieldNull('foo'): - gdaltest.post_reason('failure') f.DumpReadable() - return 'fail' + pytest.fail() f = lyr.GetNextFeature() if f.IsFieldSet('foo'): - gdaltest.post_reason('failure') f.DumpReadable() - return 'fail' + pytest.fail() # Test writing side gdal.VectorTranslate('/vsimem/ogr_geojson_60.json', ds, format='GeoJSON') @@ -3661,37 +3067,28 @@ def ogr_geojson_60(): gdal.VSIFCloseL(fp) gdal.Unlink('/vsimem/ogr_geojson_60.json') - if data.find('"properties": { "foo": "bar" }') < 0 or \ - data.find('"properties": { "foo": null }') < 0 or \ - data.find('"properties": { }') < 0: - gdaltest.post_reason('failure') - print(data) - return 'fail' - - return 'success' + assert (data.find('"properties": { "foo": "bar" }') >= 0 and \ + data.find('"properties": { "foo": null }') >= 0 and \ + data.find('"properties": { }') >= 0) ############################################################################### # Test corner cases -def ogr_geojson_61(): +def test_ogr_geojson_61(): # Invalid JSon gdal.FileFromMemBuffer('/vsimem/ogr_geojson_61.json', """{ "type": "FeatureCollection", "features": [""") with gdaltest.error_handler(): ds = gdal.OpenEx('/vsimem/ogr_geojson_61.json') - if ds is not None: - gdaltest.post_reason('failure') - return 'fail' + assert ds is None gdal.Unlink('/vsimem/ogr_geojson_61.json') # Invalid single geometry with gdaltest.error_handler(): ds = gdal.OpenEx("""{ "type": "Point", "x" : { "coordinates" : null } } """) - if ds is not None: - gdaltest.post_reason('failure') - return 'fail' + assert ds is None # Empty property name gdal.FileFromMemBuffer('/vsimem/ogr_geojson_61.json', @@ -3699,19 +3096,15 @@ def ogr_geojson_61(): ds = gdal.OpenEx('/vsimem/ogr_geojson_61.json') lyr = ds.GetLayer(0) f = lyr.GetNextFeature() - if f.GetField("") != 1: - gdaltest.post_reason('failure') - return 'fail' + assert f.GetField("") == 1 ds = None gdal.Unlink('/vsimem/ogr_geojson_61.json') - return 'success' - ############################################################################### # Test crs object -def ogr_geojson_62(): +def test_ogr_geojson_62(): # crs type=name tests gdal.OpenEx("""{ "type": "FeatureCollection", "crs": { "type":"name" }, "features":[] }""") @@ -3729,9 +3122,7 @@ def ogr_geojson_62(): ds = gdal.OpenEx("""{ "type": "FeatureCollection", "crs": { "type":"name", "properties":{"name": "urn:ogc:def:crs:EPSG::32631"} }, "features":[] }""") lyr = ds.GetLayer(0) srs = lyr.GetSpatialRef() - if srs.ExportToWkt().find('32631') < 0: - gdaltest.post_reason('failure') - return 'fail' + assert srs.ExportToWkt().find('32631') >= 0 # crs type=EPSG (not even documented in GJ2008 spec!) tests. Just for coverage completeness gdal.OpenEx("""{ "type": "FeatureCollection", "crs": { "type":"EPSG" }, "features":[] }""") @@ -3751,9 +3142,7 @@ def ogr_geojson_62(): ds = gdal.OpenEx("""{ "type": "FeatureCollection", "crs": { "type":"EPSG", "properties":{"code": 32631} }, "features":[] }""") lyr = ds.GetLayer(0) srs = lyr.GetSpatialRef() - if srs.ExportToWkt().find('32631') < 0: - gdaltest.post_reason('failure') - return 'fail' + assert srs.ExportToWkt().find('32631') >= 0 # crs type=link tests gdal.OpenEx("""{ "type": "FeatureCollection", "crs": { "type":"link" }, "features":[] }""") @@ -3788,17 +3177,13 @@ def ogr_geojson_62(): ds = gdal.OpenEx("""{ "type": "FeatureCollection", "crs": { "type":"OGC", "properties":{"urn": "urn:ogc:def:crs:EPSG::32631"} }, "features":[] }""") lyr = ds.GetLayer(0) srs = lyr.GetSpatialRef() - if srs.ExportToWkt().find('32631') < 0: - gdaltest.post_reason('failure') - return 'fail' - - return 'success' + assert srs.ExportToWkt().find('32631') >= 0 ############################################################################### # Extensive test of field tye promotion -def ogr_geojson_63(): +def test_ogr_geojson_63(): ds_ref = ogr.Open('data/test_type_promotion_ref.json') lyr_ref = ds_ref.GetLayer(0) @@ -3810,36 +3195,30 @@ def ogr_geojson_63(): # Test exporting XYM / XYZM (#6935) -def ogr_geojson_64(): +def test_ogr_geojson_64(): g = ogr.CreateGeometryFromWkt('POINT ZM(1 2 3 4)') - if ogrtest.check_feature_geometry(ogr.CreateGeometryFromJson(g.ExportToJson()), - ogr.CreateGeometryFromWkt('POINT Z(1 2 3)')) != 0: - return 'fail' + assert (ogrtest.check_feature_geometry(ogr.CreateGeometryFromJson(g.ExportToJson()), + ogr.CreateGeometryFromWkt('POINT Z(1 2 3)')) == 0) g = ogr.CreateGeometryFromWkt('POINT M(1 2 3)') - if ogrtest.check_feature_geometry(ogr.CreateGeometryFromJson(g.ExportToJson()), - ogr.CreateGeometryFromWkt('POINT (1 2)')) != 0: - return 'fail' + assert (ogrtest.check_feature_geometry(ogr.CreateGeometryFromJson(g.ExportToJson()), + ogr.CreateGeometryFromWkt('POINT (1 2)')) == 0) g = ogr.CreateGeometryFromWkt('LINESTRING ZM(1 2 3 4,5 6 7 8)') - if ogrtest.check_feature_geometry(ogr.CreateGeometryFromJson(g.ExportToJson()), - ogr.CreateGeometryFromWkt('LINESTRING Z(1 2 3,5 6 7)')) != 0: - return 'fail' + assert (ogrtest.check_feature_geometry(ogr.CreateGeometryFromJson(g.ExportToJson()), + ogr.CreateGeometryFromWkt('LINESTRING Z(1 2 3,5 6 7)')) == 0) g = ogr.CreateGeometryFromWkt('LINESTRING M(1 2 3,4 5 6)') - if ogrtest.check_feature_geometry(ogr.CreateGeometryFromJson(g.ExportToJson()), - ogr.CreateGeometryFromWkt('LINESTRING (1 2,4 5)')) != 0: - return 'fail' - - return 'success' + assert (ogrtest.check_feature_geometry(ogr.CreateGeometryFromJson(g.ExportToJson()), + ogr.CreateGeometryFromWkt('LINESTRING (1 2,4 5)')) == 0) ############################################################################### # Test feature geometry CRS when CRS set on the FeatureCollection # See https://github.com/r-spatial/sf/issues/449#issuecomment-319369945 -def ogr_geojson_65(): +def test_ogr_geojson_65(): ds = ogr.Open("""{ "type": "FeatureCollection", @@ -3855,17 +3234,13 @@ def ogr_geojson_65(): f = lyr.GetNextFeature() srs = f.GetGeometryRef().GetSpatialReference() pcs = int(srs.GetAuthorityCode('PROJCS')) - if pcs != 32631: - gdaltest.post_reason('Spatial reference for individual geometry was not valid') - return 'fail' - - return 'success' + assert pcs == 32631, 'Spatial reference for individual geometry was not valid' ############################################################################### # Test features with properties not being a dictionary -def ogr_geojson_66(): +def test_ogr_geojson_66(): ds = ogr.Open("""{ "type": "FeatureCollection", @@ -3882,191 +3257,127 @@ def ogr_geojson_66(): } ]}""") lyr = ds.GetLayer(0) - if lyr.GetLayerDefn().GetFieldCount() != 0: - return 'fail' - - return 'success' + assert lyr.GetLayerDefn().GetFieldCount() == 0 ############################################################################### # Test reading GeoJSON files starting with {"features":[{"geometry":.... (#7198) -def ogr_geojson_67(): +def test_ogr_geojson_67(): ds = ogr.Open('data/grenada.geojson') - if ds is None: - gdaltest.post_reason('fail') - return 'fail' - if ds.GetDriver().GetName() != 'GeoJSON': - gdaltest.post_reason('fail') - return 'fail' + assert ds is not None + assert ds.GetDriver().GetName() == 'GeoJSON' lyr = ds.GetLayer(0) - if lyr.GetFeatureCount() != 1: - gdaltest.post_reason('fail') - return 'fail' - return 'success' + assert lyr.GetFeatureCount() == 1 ############################################################################### # Test reading ESRIJSON files starting with {"features":[{"geometry":.... (#7198) -def ogr_geojson_68(): +def test_ogr_geojson_68(): ds = ogr.Open('data/esrijsonstartingwithfeaturesgeometry.json') - if ds is None: - gdaltest.post_reason('fail') - return 'fail' - if ds.GetDriver().GetName() != 'ESRIJSON': - gdaltest.post_reason('fail') - return 'fail' + assert ds is not None + assert ds.GetDriver().GetName() == 'ESRIJSON' lyr = ds.GetLayer(0) - if lyr.GetFeatureCount() != 1: - gdaltest.post_reason('fail') - return 'fail' - return 'success' + assert lyr.GetFeatureCount() == 1 ############################################################################### -def ogr_geojson_id_field_and_id_type(): +def test_ogr_geojson_id_field_and_id_type(): gdal.VectorTranslate('/vsimem/out.json', 'data/poly.shp', options='-f GeoJSON -lco ID_TYPE=String -preserve_fid -limit 1 -fid 2') got = read_file('/vsimem/out.json') - if got.find('"id": "2", "properties": { "AREA": 261752.781, "EAS_ID": 171, "PRFEDEA": "35043414" }') < 0: - gdaltest.post_reason('fail') - print(got) - return 'fail' + assert got.find('"id": "2", "properties": { "AREA": 261752.781, "EAS_ID": 171, "PRFEDEA": "35043414" }') >= 0 gdal.VectorTranslate('/vsimem/out.json', 'data/poly.shp', options='-f GeoJSON -lco ID_TYPE=Integer -preserve_fid -limit 1 -fid 2') got = read_file('/vsimem/out.json') - if got.find('"id": 2, "properties": { "AREA": 261752.781, "EAS_ID": 171, "PRFEDEA": "35043414" }') < 0: - gdaltest.post_reason('fail') - print(got) - return 'fail' + assert got.find('"id": 2, "properties": { "AREA": 261752.781, "EAS_ID": 171, "PRFEDEA": "35043414" }') >= 0 gdal.VectorTranslate('/vsimem/out.json', 'data/poly.shp', format='GeoJSON', layerCreationOptions=['ID_FIELD=EAS_ID'], limit=1) got = read_file('/vsimem/out.json') - if got.find('"id": 168, "properties": { "AREA": 215229.266, "PRFEDEA": "35043411" }') < 0: - gdaltest.post_reason('fail') - print(got) - return 'fail' + assert got.find('"id": 168, "properties": { "AREA": 215229.266, "PRFEDEA": "35043411" }') >= 0 src_ds = gdal.OpenEx('/vsimem/out.json', open_options=['NATIVE_DATA=YES']) gdal.VectorTranslate('/vsimem/out2.json', src_ds, format='GeoJSON') src_ds = None got = read_file('/vsimem/out2.json') gdal.Unlink('/vsimem/out2.json') - if got.find('"id": 168, "properties": { "AREA": 215229.266, "PRFEDEA": "35043411" }') < 0: - gdaltest.post_reason('fail') - print(got) - return 'fail' + assert got.find('"id": 168, "properties": { "AREA": 215229.266, "PRFEDEA": "35043411" }') >= 0 src_ds = gdal.OpenEx('/vsimem/out.json', open_options=['NATIVE_DATA=YES']) gdal.VectorTranslate('/vsimem/out2.json', src_ds, format='GeoJSON', layerCreationOptions=['ID_TYPE=String']) src_ds = None got = read_file('/vsimem/out2.json') gdal.Unlink('/vsimem/out2.json') - if got.find('"id": "168", "properties": { "AREA": 215229.266, "PRFEDEA": "35043411" }') < 0: - gdaltest.post_reason('fail') - print(got) - return 'fail' + assert got.find('"id": "168", "properties": { "AREA": 215229.266, "PRFEDEA": "35043411" }') >= 0 src_ds = gdal.OpenEx('/vsimem/out.json', open_options=['NATIVE_DATA=YES']) gdal.VectorTranslate('/vsimem/out2.json', src_ds, format='GeoJSON', layerCreationOptions=['ID_TYPE=Integer']) src_ds = None got = read_file('/vsimem/out2.json') gdal.Unlink('/vsimem/out2.json') - if got.find('"id": 168, "properties": { "AREA": 215229.266, "PRFEDEA": "35043411" }') < 0: - gdaltest.post_reason('fail') - print(got) - return 'fail' + assert got.find('"id": 168, "properties": { "AREA": 215229.266, "PRFEDEA": "35043411" }') >= 0 gdal.Unlink('/vsimem/out.json') gdal.VectorTranslate('/vsimem/out.json', 'data/poly.shp', format='GeoJSON', layerCreationOptions=['ID_FIELD=EAS_ID', 'ID_TYPE=String'], limit=1) got = read_file('/vsimem/out.json') - if got.find('"id": "168", "properties": { "AREA": 215229.266, "PRFEDEA": "35043411" }') < 0: - gdaltest.post_reason('fail') - print(got) - return 'fail' + assert got.find('"id": "168", "properties": { "AREA": 215229.266, "PRFEDEA": "35043411" }') >= 0 src_ds = gdal.OpenEx('/vsimem/out.json', open_options=['NATIVE_DATA=YES']) gdal.VectorTranslate('/vsimem/out2.json', src_ds, format='GeoJSON') src_ds = None got = read_file('/vsimem/out2.json') gdal.Unlink('/vsimem/out2.json') - if got.find('"id": "168", "properties": { "AREA": 215229.266, "PRFEDEA": "35043411" }') < 0: - gdaltest.post_reason('fail') - print(got) - return 'fail' + assert got.find('"id": "168", "properties": { "AREA": 215229.266, "PRFEDEA": "35043411" }') >= 0 src_ds = gdal.OpenEx('/vsimem/out.json', open_options=['NATIVE_DATA=YES']) gdal.VectorTranslate('/vsimem/out2.json', src_ds, format='GeoJSON', layerCreationOptions=['ID_TYPE=String']) src_ds = None got = read_file('/vsimem/out2.json') gdal.Unlink('/vsimem/out2.json') - if got.find('"id": "168", "properties": { "AREA": 215229.266, "PRFEDEA": "35043411" }') < 0: - gdaltest.post_reason('fail') - print(got) - return 'fail' + assert got.find('"id": "168", "properties": { "AREA": 215229.266, "PRFEDEA": "35043411" }') >= 0 src_ds = gdal.OpenEx('/vsimem/out.json', open_options=['NATIVE_DATA=YES']) gdal.VectorTranslate('/vsimem/out2.json', src_ds, format='GeoJSON', layerCreationOptions=['ID_TYPE=Integer']) src_ds = None got = read_file('/vsimem/out2.json') gdal.Unlink('/vsimem/out2.json') - if got.find('"id": 168, "properties": { "AREA": 215229.266, "PRFEDEA": "35043411" }') < 0: - gdaltest.post_reason('fail') - print(got) - return 'fail' + assert got.find('"id": 168, "properties": { "AREA": 215229.266, "PRFEDEA": "35043411" }') >= 0 gdal.Unlink('/vsimem/out.json') gdal.VectorTranslate('/vsimem/out.json', 'data/poly.shp', format='GeoJSON', layerCreationOptions=['ID_FIELD=PRFEDEA'], limit=1) got = read_file('/vsimem/out.json') gdal.Unlink('/vsimem/out.json') - if got.find('"id": "35043411", "properties": { "AREA": 215229.266, "EAS_ID": 168 }') < 0: - gdaltest.post_reason('fail') - print(got) - return 'fail' + assert got.find('"id": "35043411", "properties": { "AREA": 215229.266, "EAS_ID": 168 }') >= 0 gdal.VectorTranslate('/vsimem/out.json', 'data/poly.shp', format='GeoJSON', layerCreationOptions=['ID_FIELD=PRFEDEA', 'ID_TYPE=Integer'], limit=1) got = read_file('/vsimem/out.json') gdal.Unlink('/vsimem/out.json') - if got.find('"id": 35043411, "properties": { "AREA": 215229.266, "EAS_ID": 168 }') < 0: - gdaltest.post_reason('fail') - print(got) - return 'fail' - - return 'success' + assert got.find('"id": 35043411, "properties": { "AREA": 215229.266, "EAS_ID": 168 }') >= 0 ############################################################################### -def ogr_geojson_geom_export_failure(): +def test_ogr_geojson_geom_export_failure(): g = ogr.CreateGeometryFromWkt('POINT EMPTY') geojson = g.ExportToJson() - if geojson is not None: - gdaltest.post_reason('fail') - print(geojson) - return 'fail' + assert geojson is None g = ogr.CreateGeometryFromWkt('GEOMETRYCOLLECTION(TIN EMPTY)') geojson = json.loads(g.ExportToJson()) - if geojson != {"type": "GeometryCollection", "geometries": None}: - gdaltest.post_reason('fail') - print(geojson) - return 'fail' + assert geojson == {"type": "GeometryCollection", "geometries": None} g = ogr.Geometry(ogr.wkbLineString) g.AddPoint_2D(float('nan'), 0) with gdaltest.error_handler(): geojson = g.ExportToJson() - if geojson is not None: - gdaltest.post_reason('fail') - print(geojson) - return 'fail' + assert geojson is None g = ogr.Geometry(ogr.wkbPolygon) lr = ogr.Geometry(ogr.wkbLinearRing) @@ -4083,17 +3394,12 @@ def ogr_geojson_geom_export_failure(): g.AddGeometry(lr) with gdaltest.error_handler(): geojson = g.ExportToJson() - if geojson is not None: - gdaltest.post_reason('fail') - print(geojson) - return 'fail' - - return 'success' + assert geojson is None ############################################################################### -def ogr_geojson_starting_with_crs(): +def test_ogr_geojson_starting_with_crs(): ds = ogr.Open("""{ "crs": { "type": "name", "properties": { "name": "urn:ogc:def:crs:EPSG::32631" } }, @@ -4105,16 +3411,13 @@ def ogr_geojson_starting_with_crs(): "coordinates": [500000,4500000]}, "properties": { }}]}""") - if ds is None: - return 'fail' - - return 'success' + assert ds is not None ############################################################################### # Test we properly flush the file in SyncToDisk() in append situations -def ogr_geojson_append_flush(): +def test_ogr_geojson_append_flush(): tmpfilename = 'tmp/ogr_geojson_append_flush.json' f = gdal.VSIFOpenL(tmpfilename, 'wb') @@ -4136,32 +3439,26 @@ def ogr_geojson_append_flush(): lyr = ds2.GetLayer(0) lyr.GetNextFeature() f = lyr.GetNextFeature() - if f is None or f['x'] != 10: - return 'fail' + assert f is not None and f['x'] == 10 ds = None ds2 = None gdal.Unlink(tmpfilename) - return 'success' - ############################################################################### -def ogr_geojson_empty_geometrycollection(): +def test_ogr_geojson_empty_geometrycollection(): g = ogr.CreateGeometryFromJson('{"type": "GeometryCollection", "geometries": []}') - if g.ExportToWkt() != 'GEOMETRYCOLLECTION EMPTY': - print(g.ExportToWkt()) - return 'fail' - return 'success' + assert g.ExportToWkt() == 'GEOMETRYCOLLECTION EMPTY' ############################################################################### -def ogr_esrijson_without_geometryType(): +def test_ogr_esrijson_without_geometryType(): ds = ogr.Open("""{ "spatialReference" : { @@ -4183,16 +3480,13 @@ def ogr_esrijson_without_geometryType(): """) lyr = ds.GetLayer(0) f = lyr.GetNextFeature() - if f.GetGeometryRef() is None: - return 'fail' - - return 'success' + assert f.GetGeometryRef() is not None ############################################################################### -def ogr_geojson_read_fields_with_different_case(): +def test_ogr_geojson_read_fields_with_different_case(): ds = ogr.Open("""{ "type": "FeatureCollection", @@ -4205,18 +3499,17 @@ def ogr_geojson_read_fields_with_different_case(): f = lyr.GetNextFeature() if f.GetField(0) != 'my_id' or f.GetField(1) != 'MY_ID' or f.GetField(2) != 'foo' or f.GetField(3) != 'FOO': f.DumpReadable() - return 'fail' - - return 'success' + pytest.fail() + ############################################################################### # Test bugfix for https://github.com/OSGeo/gdal/issues/1068 -def ogr_geojson_clip_geometries_rfc7946(): +def test_ogr_geojson_clip_geometries_rfc7946(): if not ogrtest.have_geos(): - return 'skip' + pytest.skip() tmpfilename = '/vsimem/out.json' gdal.VectorTranslate(tmpfilename, """{ @@ -4235,29 +3528,28 @@ def ogr_geojson_clip_geometries_rfc7946(): ref_geom = ogr.CreateGeometryFromWkt('MULTIPOLYGON (((-180 30,-180 -20,16 -20,16 30,-180 30)),((140 -20,180 -20,180 30,140 30,140 -20)))') if ogrtest.check_feature_geometry(f, ref_geom) != 0: f.DumpReadable() - return 'fail' + pytest.fail() f = lyr.GetNextFeature() ref_geom = ogr.CreateGeometryFromWkt('MULTIPOLYGON (((180 40,180 70,-16 70,-16 40,180 40)),((-180 70,-180 40,-140 40,-140 70,-180 70)))') if ogrtest.check_feature_geometry(f, ref_geom) != 0: f.DumpReadable() - return 'fail' + pytest.fail() f = lyr.GetNextFeature() ref_geom = ogr.CreateGeometryFromWkt('POLYGON ((170 -40,-16 -40,-16 70,170 -70,170 -40))') if ogrtest.check_feature_geometry(f, ref_geom) != 0: f.DumpReadable() - return 'fail' + pytest.fail() ds = None gdal.Unlink(tmpfilename) - return 'success' ############################################################################### # Test bugfix for https://github.com/OSGeo/gdal/issues/1109 -def ogr_geojson_non_finite(): +def test_ogr_geojson_non_finite(): json_content = """{ "type": "FeatureCollection", @@ -4269,28 +3561,21 @@ def ogr_geojson_non_finite(): ds = ogr.Open(json_content) if ds is None: # Might fail with older libjson-c versions - return 'skip' + pytest.skip() lyr = ds.GetLayer(0) f = lyr.GetNextFeature() for i in range(3): - if lyr.GetLayerDefn().GetFieldDefn(i).GetType() != ogr.OFTReal: - gdaltest.post_reason('fail') - print(i) - return 'fail' + assert lyr.GetLayerDefn().GetFieldDefn(i).GetType() == ogr.OFTReal if f['inf_prop'] != float('inf'): - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' + pytest.fail() if f['minus_inf_prop'] != float('-inf'): - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' + pytest.fail() if not math.isnan(f['nan_prop']): - gdaltest.post_reason('fail') - print(str(f['nan_prop'])) f.DumpReadable() - return 'fail' + pytest.fail(str(f['nan_prop'])) ds = None tmpfilename = '/vsimem/out.json' @@ -4299,40 +3584,31 @@ def ogr_geojson_non_finite(): gdal.VectorTranslate(tmpfilename, json_content, options='-f GeoJSON') ds = ogr.Open(tmpfilename) lyr = ds.GetLayer(0) - if lyr.GetLayerDefn().GetFieldCount() != 0: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.GetLayerDefn().GetFieldCount() == 0 ds = None gdal.VectorTranslate(tmpfilename, json_content, options='-f GeoJSON -lco WRITE_NON_FINITE_VALUES=YES') ds = ogr.Open(tmpfilename) lyr = ds.GetLayer(0) - if lyr.GetLayerDefn().GetFieldCount() != 3: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.GetLayerDefn().GetFieldCount() == 3 f = lyr.GetNextFeature() if f['inf_prop'] != float('inf'): - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' + pytest.fail() if f['minus_inf_prop'] != float('-inf'): - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' + pytest.fail() if not math.isnan(f['nan_prop']): - gdaltest.post_reason('fail') - print(str(f['nan_prop'])) f.DumpReadable() - return 'fail' + pytest.fail(str(f['nan_prop'])) ds = None gdal.Unlink(tmpfilename) - return 'success' ############################################################################### -def ogr_geojson_cleanup(): +def test_ogr_geojson_cleanup(): gdal.SetConfigOption('CPL_CURL_ENABLE_VSIMEM', None) @@ -4364,93 +3640,6 @@ def ogr_geojson_cleanup(): for f in gdal.ReadDir('/vsimem/geojson'): gdal.Unlink('/vsimem/geojson/' + f) - return 'success' - - -gdaltest_list = [ - ogr_geojson_1, - ogr_geojson_2, - ogr_geojson_3, - ogr_geojson_4, - ogr_geojson_5, - ogr_geojson_6, - ogr_geojson_7, - ogr_geojson_8, - ogr_geojson_9, - ogr_geojson_10, - ogr_geojson_11, - ogr_geojson_12, - ogr_geojson_13, - ogr_geojson_14, - ogr_geojson_15, - ogr_geojson_16, - ogr_geojson_17, - ogr_geojson_18, - ogr_geojson_19, - ogr_geojson_20, - ogr_geojson_21, - ogr_geojson_22, - ogr_geojson_23, - ogr_geojson_24, - ogr_geojson_25, - ogr_geojson_26, - ogr_geojson_27, - ogr_geojson_28, - ogr_geojson_29, - ogr_geojson_30, - ogr_geojson_31, - ogr_geojson_32, - ogr_geojson_33, - ogr_geojson_34, - ogr_geojson_35, - ogr_geojson_36, - ogr_geojson_37, - ogr_geojson_38, - ogr_geojson_39, - ogr_geojson_40, - ogr_geojson_41, - ogr_geojson_42, - ogr_geojson_43, - ogr_geojson_44, - ogr_geojson_45, - ogr_geojson_46, - ogr_geojson_47, - ogr_geojson_48, - ogr_geojson_49, - ogr_geojson_50, - ogr_geojson_51, - ogr_geojson_52, - ogr_geojson_53, - ogr_geojson_54, - ogr_geojson_55, - ogr_geojson_56, - ogr_geojson_57, - ogr_geojson_58, - ogr_geojson_59, - ogr_geojson_60, - ogr_geojson_61, - ogr_geojson_62, - ogr_geojson_63, - ogr_geojson_64, - ogr_geojson_65, - ogr_geojson_66, - ogr_geojson_67, - ogr_geojson_68, - ogr_geojson_id_field_and_id_type, - ogr_geojson_geom_export_failure, - ogr_geojson_starting_with_crs, - ogr_geojson_append_flush, - ogr_geojson_empty_geometrycollection, - ogr_esrijson_without_geometryType, - ogr_geojson_read_fields_with_different_case, - ogr_geojson_clip_geometries_rfc7946, - ogr_geojson_non_finite, - ogr_geojson_cleanup] - -if __name__ == '__main__': - - gdaltest.setup_run('ogr_geojson') - - gdaltest.run_tests(gdaltest_list) - - sys.exit(gdaltest.summarize()) + + + diff --git a/autotest/ogr/ogr_geojsonseq.py b/autotest/ogr/ogr_geojsonseq.py index 11636e8585f1..d1e222dcbd75 100755 --- a/autotest/ogr/ogr_geojsonseq.py +++ b/autotest/ogr/ogr_geojsonseq.py @@ -28,15 +28,14 @@ # DEALINGS IN THE SOFTWARE. ############################################################################### -import sys -sys.path.append('../pymod') from osgeo import gdal from osgeo import osr from osgeo import ogr import gdaltest +import pytest def _ogr_geojsonseq_create(filename, lco, expect_rs): @@ -57,14 +56,10 @@ def _ogr_geojsonseq_create(filename, lco, expect_rs): f.SetGeometry(ogr.CreateGeometryFromWkt('POINT(3 4)')) lyr.CreateFeature(f) - if ds.TestCapability(ogr.ODsCCreateLayer): - gdaltest.post_reason('fail') - return 'fail' + assert not ds.TestCapability(ogr.ODsCCreateLayer) with gdaltest.error_handler(): - if ds.CreateLayer('foo') is not None: - gdaltest.post_reason('fail') - return 'fail' + assert ds.CreateLayer('foo') is None ds = None @@ -72,89 +67,69 @@ def _ogr_geojsonseq_create(filename, lco, expect_rs): first = gdal.VSIFReadL(1, 1, f).decode('ascii') gdal.VSIFCloseL(f) if expect_rs: - if first != '\x1e': - gdaltest.post_reason('fail') - return 'fail' + assert first == '\x1e' else: - if first != '{': - gdaltest.post_reason('fail') - return 'fail' + assert first == '{' ds = ogr.Open(filename) lyr = ds.GetLayer(0) f = lyr.GetNextFeature() if f['foo'] != 'bar"d' or \ f.GetGeometryRef().ExportToWkt() != 'POINT (1 2)': - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' + pytest.fail() f = lyr.GetNextFeature() if f['foo'] != 'baz' or f.GetGeometryRef().ExportToWkt() != 'POINT (3 4)': - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' - if lyr.GetNextFeature() is not None: - gdaltest.post_reason('fail') - return 'fail' + pytest.fail() + assert lyr.GetNextFeature() is None ds = None ogr.GetDriverByName('GeoJSONSeq').DeleteDataSource(filename) - return 'success' - -def ogr_geojsonseq_lf(): +def test_ogr_geojsonseq_lf(): return _ogr_geojsonseq_create('/vsimem/test', [], False) -def ogr_geojsonseq_rs(): +def test_ogr_geojsonseq_rs(): return _ogr_geojsonseq_create('/vsimem/test', ['RS=YES'], True) -def ogr_geojsonseq_rs_auto(): +def test_ogr_geojsonseq_rs_auto(): return _ogr_geojsonseq_create('/vsimem/test.geojsons', [], True) -def ogr_geojsonseq_inline(): +def test_ogr_geojsonseq_inline(): ds = ogr.Open("""{"type":"Feature","properties":{},"geometry":null} {"type":"Feature","properties":{},"geometry":null}""") lyr = ds.GetLayer(0) - if lyr.GetFeatureCount() != 2: - print(lyr.GetFeatureCount()) - return 'fail' - return 'success' + assert lyr.GetFeatureCount() == 2 -def ogr_geojsonseq_prefix(): +def test_ogr_geojsonseq_prefix(): ds = ogr.Open("""GeoJSONSeq:data/test.geojsonl""") lyr = ds.GetLayer(0) - if lyr.GetFeatureCount() != 2: - print(lyr.GetFeatureCount()) - return 'fail' - return 'success' + assert lyr.GetFeatureCount() == 2 -def ogr_geojsonseq_seq_geometries(): +def test_ogr_geojsonseq_seq_geometries(): with gdaltest.config_option('OGR_GEOJSONSEQ_CHUNK_SIZE', '10'): ds = ogr.Open("""{"type":"Point","coordinates":[2,49]} {"type":"Point","coordinates":[3,50]}""") lyr = ds.GetLayer(0) - if lyr.GetFeatureCount() != 2: - print(lyr.GetFeatureCount()) - return 'fail' + assert lyr.GetFeatureCount() == 2 f = lyr.GetNextFeature() if f.GetGeometryRef().ExportToWkt() != 'POINT (2 49)': - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' - - return 'success' + pytest.fail() + -def ogr_geojsonseq_reprojection(): +def test_ogr_geojsonseq_reprojection(): filename = '/vsimem/ogr_geojsonseq_reprojection.geojsonl' ds = ogr.GetDriverByName('GeoJSONSeq').CreateDataSource(filename) @@ -172,69 +147,39 @@ def ogr_geojsonseq_reprojection(): lyr = ds.GetLayer(0) f = lyr.GetNextFeature() if f.GetGeometryRef().ExportToWkt() != 'POINT (2 49)': - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' + pytest.fail() ds = None ogr.GetDriverByName('GeoJSONSeq').DeleteDataSource(filename) - return 'success' - -def ogr_geojsonseq_read_rs_json_pretty(): +def test_ogr_geojsonseq_read_rs_json_pretty(): ds = ogr.Open('data/test.geojsons') lyr = ds.GetLayer(0) f = lyr.GetNextFeature() if f['foo'] != 'bar' or \ f.GetGeometryRef().ExportToWkt() != 'POINT (1 2)': - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' + pytest.fail() f = lyr.GetNextFeature() if f['foo'] != 'baz' or f.GetGeometryRef().ExportToWkt() != 'POINT (3 4)': - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' - if lyr.GetNextFeature() is not None: - gdaltest.post_reason('fail') - return 'fail' - return 'success' + pytest.fail() + assert lyr.GetNextFeature() is None -def ogr_geojsonseq_test_ogrsf(): +def test_ogr_geojsonseq_test_ogrsf(): import test_cli_utilities if test_cli_utilities.get_test_ogrsf_path() is None: - return 'skip' + pytest.skip() ret = gdaltest.runexternal( test_cli_utilities.get_test_ogrsf_path() + ' -ro data/test.geojsonl') - if ret.find('INFO') == -1 or ret.find('ERROR') != -1: - print(ret) - return 'fail' - - return 'success' - - -gdaltest_list = [ - ogr_geojsonseq_lf, - ogr_geojsonseq_rs, - ogr_geojsonseq_rs_auto, - ogr_geojsonseq_inline, - ogr_geojsonseq_prefix, - ogr_geojsonseq_seq_geometries, - ogr_geojsonseq_reprojection, - ogr_geojsonseq_read_rs_json_pretty, - ogr_geojsonseq_test_ogrsf, -] - -if __name__ == '__main__': + assert ret.find('INFO') != -1 and ret.find('ERROR') == -1 - gdaltest.setup_run('ogr_geojsonseq') - gdaltest.run_tests(gdaltest_list) - sys.exit(gdaltest.summarize()) diff --git a/autotest/ogr/ogr_geom.py b/autotest/ogr/ogr_geom.py index 8e92bbd24a66..1e39f1c61693 100755 --- a/autotest/ogr/ogr_geom.py +++ b/autotest/ogr/ogr_geom.py @@ -32,43 +32,37 @@ import random import sys -sys.path.append('../pymod') import gdaltest import ogrtest from osgeo import ogr from osgeo import osr from osgeo import gdal +import pytest ############################################################################### # Test Area calculation for a MultiPolygon (which exercises lower level # get_Area() methods as well). -def ogr_geom_area(): +def test_ogr_geom_area(): geom_wkt = 'MULTIPOLYGON( ((0 0,1 1,1 0,0 0)),((0 0,10 0, 10 10, 0 10),(1 1,1 2,2 2,2 1)) )' geom = ogr.CreateGeometryFromWkt(geom_wkt) area = geom.GetArea() - if abs(area - 99.5) > 0.00000000001: - gdaltest.post_reason('GetArea() result wrong, got %g.' % area) - return 'fail' + assert abs(area - 99.5) <= 0.00000000001, ('GetArea() result wrong, got %g.' % area) # OGR >= 1.8.0 area = geom.Area() - if abs(area - 99.5) > 0.00000000001: - gdaltest.post_reason('Area() result wrong, got %g.' % area) - return 'fail' - - return 'success' + assert abs(area - 99.5) <= 0.00000000001, ('Area() result wrong, got %g.' % area) ############################################################################### # Test Area calculation for a LinearRing (which exercises special case of # getGeometryType value). -def ogr_geom_area_linearring(): +def test_ogr_geom_area_linearring(): geom = ogr.Geometry(type=ogr.wkbLinearRing) geom.AddPoint_2D(0, 0) @@ -78,35 +72,27 @@ def ogr_geom_area_linearring(): geom.AddPoint_2D(0, 0) area = geom.GetArea() - if abs(area - 100.0) > 0.00000000001: - gdaltest.post_reason('Area result wrong, got %g.' % area) - return 'fail' - - return 'success' + assert abs(area - 100.0) <= 0.00000000001, ('Area result wrong, got %g.' % area) ############################################################################### # Test Area calculation for a GeometryCollection -def ogr_geom_area_geometrycollection(): +def test_ogr_geom_area_geometrycollection(): # OGR >= 1.8.0 geom_wkt = 'GEOMETRYCOLLECTION( POLYGON((0 0,1 1,1 0,0 0)), MULTIPOLYGON(((0 0,1 1,1 0,0 0))), LINESTRING(0 0,1 1), POINT(0 0), GEOMETRYCOLLECTION EMPTY )' geom = ogr.CreateGeometryFromWkt(geom_wkt) area = geom.Area() - if abs(area - 1) > 0.00000000001: - gdaltest.post_reason('Area() result wrong, got %g.' % area) - return 'fail' - - return 'success' + assert abs(area - 1) <= 0.00000000001, ('Area() result wrong, got %g.' % area) ############################################################################### # Test Area calculation for a LinearRing whose coordinates are shifted by a # huge value With algorithm prior to #3556, this would return 0. -def ogr_geom_area_linearring_big_offset(): +def test_ogr_geom_area_linearring_big_offset(): geom = ogr.Geometry(type=ogr.wkbLinearRing) BIGOFFSET = 1.0e11 @@ -117,105 +103,76 @@ def ogr_geom_area_linearring_big_offset(): geom.AddPoint_2D(BIGOFFSET + 0, BIGOFFSET + 0) area = geom.GetArea() - if abs(area - 100.0) > 0.00000000001: - gdaltest.post_reason('Area result wrong, got %g.' % area) - return 'fail' - - return 'success' + assert abs(area - 100.0) <= 0.00000000001, ('Area result wrong, got %g.' % area) ############################################################################### # Test Area calculation for a Triangle -def ogr_geom_area_triangle(): +def test_ogr_geom_area_triangle(): geom_wkt = 'TRIANGLE((0 0,100 0,0 100,0 0))' geom = ogr.CreateGeometryFromWkt(geom_wkt) area = geom.GetArea() - if abs(area - 4999.5) < 0.00000000001: - gdaltest.post_reason('GetArea() result wrong, got %g.' % area) - return 'fail' + assert abs(area - 4999.5) >= 0.00000000001, \ + ('GetArea() result wrong, got %g.' % area) # OGR >= 1.8.0 area = geom.Area() - if abs(area - 4999.5) < 0.00000000001: - gdaltest.post_reason('Area() result wrong, got %g.' % area) - return 'fail' + assert abs(area - 4999.5) >= 0.00000000001, ('Area() result wrong, got %g.' % area) - return 'success' - -def ogr_geom_is_empty(): +def test_ogr_geom_is_empty(): geom_wkt = 'LINESTRING EMPTY' geom = ogr.CreateGeometryFromWkt(geom_wkt) - if not geom.IsEmpty(): - gdaltest.post_reason("IsEmpty returning false for an empty geometry") - return 'fail' + assert geom.IsEmpty(), "IsEmpty returning false for an empty geometry" geom_wkt = 'POINT( 1 2 )' geom = ogr.CreateGeometryFromWkt(geom_wkt) - if not geom: - gdaltest.post_reason("A geometry could not be created from wkt: %s" % geom_wkt) - return 'fail' + assert geom, ("A geometry could not be created from wkt: %s" % geom_wkt) - if geom.IsEmpty(): - gdaltest.post_reason("IsEmpty returning true for a non-empty geometry") - return 'fail' - return 'success' + assert not geom.IsEmpty(), "IsEmpty returning true for a non-empty geometry" ############################################################################### # Test if a Triangle is Empty -def ogr_geom_is_empty_triangle(): +def test_ogr_geom_is_empty_triangle(): geom_wkt = 'TRIANGLE EMPTY' geom = ogr.CreateGeometryFromWkt(geom_wkt) - if not geom.IsEmpty(): - gdaltest.post_reason("IsEmpty returning false for an empty geometry") - return 'fail' + assert geom.IsEmpty(), "IsEmpty returning false for an empty geometry" geom = ogr.CreateGeometryFromWkb(geom.ExportToWkb()) - if not geom.IsEmpty(): - gdaltest.post_reason("IsEmpty returning false for an empty geometry") - return 'fail' + assert geom.IsEmpty(), "IsEmpty returning false for an empty geometry" geom_wkt = 'TRIANGLE((0 0,100 0,0 100,0 0))' geom = ogr.CreateGeometryFromWkt(geom_wkt) - if not geom: - gdaltest.post_reason("A geometry could not be created from wkt: %s" % geom_wkt) - return 'fail' + assert geom, ("A geometry could not be created from wkt: %s" % geom_wkt) - if geom.IsEmpty(): - gdaltest.post_reason("IsEmpty returning true for a non-empty geometry") - return 'fail' - return 'success' + assert not geom.IsEmpty(), "IsEmpty returning true for a non-empty geometry" -def ogr_geom_pickle(): +def test_ogr_geom_pickle(): geom_wkt = 'MULTIPOLYGON( ((0 0,1 1,1 0,0 0)),((0 0,10 0, 10 10, 0 10),(1 1,1 2,2 2,2 1)) )' geom = ogr.CreateGeometryFromWkt(geom_wkt) p = pickle.dumps(geom) with gdaltest.error_handler(): g = pickle.loads(p) - if not geom.Equal(g): - gdaltest.post_reason("pickled geometries were not equal") - return 'fail' - - return 'success' + assert geom.Equal(g), "pickled geometries were not equal" ############################################################################### # Test suite for PolyhedralSurface -def ogr_geom_polyhedral_surface(): +def test_ogr_geom_polyhedral_surface(): wkt_original = 'POLYHEDRALSURFACE Z (((0 0 0,0 0 1,0 1 1,0 1 0,0 0 0)),\ ((0 0 0,0 1 0,1 1 0,1 0 0,0 0 0)),\ @@ -228,37 +185,23 @@ def ogr_geom_polyhedral_surface(): wkb_string = ps.ExportToWkb(ogr.wkbXDR) geom = ogr.CreateGeometryFromWkb(wkb_string) wkt_string = geom.ExportToWkt() - if wkt_string != wkt_original: - gdaltest.post_reason("Failure in Wkb methods of PolyhedralSurface") - return 'fail' + assert wkt_string == wkt_original, "Failure in Wkb methods of PolyhedralSurface" wkt_string = geom.Clone().ExportToWkt() - if wkt_string != wkt_original: - gdaltest.post_reason("Failure in Clone()") - return 'fail' + assert wkt_string == wkt_original, "Failure in Clone()" polygon_wkt = ogr.ForceTo(geom.Clone(), ogr.wkbPolygon).ExportToWkt() - if polygon_wkt != wkt_original: - gdaltest.post_reason("fail") - print(polygon_wkt) - return 'fail' + assert polygon_wkt == wkt_original polygon_wkt = ogr.ForceTo(geom.Clone(), ogr.wkbMultiPolygon).ExportToWkt() - if polygon_wkt != 'MULTIPOLYGON (((0 0 0,0 0 1,0 1 1,0 1 0,0 0 0)),((0 0 0,0 1 0,1 1 0,1 0 0,0 0 0)),((0 0 0,1 0 0,1 0 1,0 0 1,0 0 0)),((1 1 0,1 1 1,1 0 1,1 0 0,1 1 0)),((0 1 0,0 1 1,1 1 1,1 1 0,0 1 0)),((0 0 1,1 0 1,1 1 1,0 1 1,0 0 1)))': - gdaltest.post_reason("fail") - print(polygon_wkt) - return 'fail' + assert polygon_wkt == 'MULTIPOLYGON (((0 0 0,0 0 1,0 1 1,0 1 0,0 0 0)),((0 0 0,0 1 0,1 1 0,1 0 0,0 0 0)),((0 0 0,1 0 0,1 0 1,0 0 1,0 0 0)),((1 1 0,1 1 1,1 0 1,1 0 0,1 1 0)),((0 1 0,0 1 1,1 1 1,1 1 0,0 1 0)),((0 0 1,1 0 1,1 1 1,0 1 1,0 0 1)))' if ogrtest.have_sfcgal(): area = ps.Area() - if area != 6.0: - gdaltest.post_reason("Wrong area of PolyhedralSurface") - return 'fail' + assert area == 6.0, "Wrong area of PolyhedralSurface" size = ps.WkbSize() - if size != 807: - gdaltest.post_reason("Wrong WkbSize() of PolyhedralSurface") - return 'fail' + assert size == 807, "Wrong WkbSize() of PolyhedralSurface" # if ogrtest.have_sfcgal(): # geom = ps.DelaunayTriangulation(0.0,True) @@ -271,24 +214,17 @@ def ogr_geom_polyhedral_surface(): if ogrtest.have_geos() or ogrtest.have_sfcgal(): geom = ogr.CreateGeometryFromWkb(wkb_string) - if not ps.Contains(geom): - gdaltest.post_reason("Failure in Contains() of PolyhedralSurface") - return 'fail' + assert ps.Contains(geom), "Failure in Contains() of PolyhedralSurface" - if ps.IsEmpty(): - gdaltest.post_reason("Failure in IsEmpty() of PolyhedralSurface") - return 'fail' + assert not ps.IsEmpty(), "Failure in IsEmpty() of PolyhedralSurface" ps.Empty() wkt_string = ps.ExportToWkt() - if wkt_string != 'POLYHEDRALSURFACE Z EMPTY': - gdaltest.post_reason("Failure in Empty() of PolyhedralSurface") - return 'fail' + assert wkt_string == 'POLYHEDRALSURFACE Z EMPTY', \ + "Failure in Empty() of PolyhedralSurface" g = ogr.CreateGeometryFromWkt('POLYHEDRALSURFACE (((0 0 0,0 0 1,0 1 1,0 1 0,0 0 0)))') - if g.Equals(g) == 0: - gdaltest.post_reason("fail") - return 'fail' + assert g.Equals(g) != 0 for wkt in ['MULTIPOLYGON (((0 0 0,0 0 1,0 1 1,0 1 0,0 0 0)))', 'POLYHEDRALSURFACE (((0 0 0,0 0 1,0 1 1,0 0 0)))', @@ -296,37 +232,27 @@ def ogr_geom_polyhedral_surface(): 'POLYHEDRALSURFACE EMPTY']: g2 = ogr.CreateGeometryFromWkt(wkt) if g.Equals(g2): - gdaltest.post_reason("Unexpected true Equals() return") print(wkt) - return 'fail' + pytest.fail("Unexpected true Equals() return") # Error - if g.AddGeometry(ogr.CreateGeometryFromWkt('POINT (0 0)')) == 0: - gdaltest.post_reason("fail") - return 'fail' + assert g.AddGeometry(ogr.CreateGeometryFromWkt('POINT (0 0)')) != 0 # Error - if g.AddGeometryDirectly(ogr.CreateGeometryFromWkt('POINT (0 0)')) == 0: - gdaltest.post_reason("fail") - return 'fail' + assert g.AddGeometryDirectly(ogr.CreateGeometryFromWkt('POINT (0 0)')) != 0 # Test dimension promotion g = ogr.CreateGeometryFromWkt('POLYHEDRALSURFACE EMPTY') g.AddGeometryDirectly(ogr.CreateGeometryFromWkt('POLYGON ZM ((0 0 1 2,0 1 1 2,1 1 1 2,0 0 1 2))')) g.AddGeometryDirectly(ogr.CreateGeometryFromWkt('POLYGON ((10 10,10 11,11 11,10 10))')) wkt = g.ExportToIsoWkt() - if wkt != 'POLYHEDRALSURFACE ZM (((0 0 1 2,0 1 1 2,1 1 1 2,0 0 1 2)),((10 10 0 0,10 11 0 0,11 11 0 0,10 10 0 0)))': - gdaltest.post_reason("fail") - print(wkt) - return 'fail' - - return 'success' + assert wkt == 'POLYHEDRALSURFACE ZM (((0 0 1 2,0 1 1 2,1 1 1 2,0 0 1 2)),((10 10 0 0,10 11 0 0,11 11 0 0,10 10 0 0)))' ############################################################################### # Test suite for TIN -def ogr_geom_tin(): +def test_ogr_geom_tin(): poly1 = ogr.CreateGeometryFromWkt("TRIANGLE ((0 0 0,0 0 1,0 1 0,0 0 0))") poly2 = ogr.CreateGeometryFromWkt("TRIANGLE ((0 0 0,0 1 0,1 1 0,0 0 0))") tin = ogr.Geometry(ogr.wkbTIN) @@ -336,9 +262,7 @@ def ogr_geom_tin(): for i in range(0, tin.GetGeometryCount()): geom = tin.GetGeometryRef(i) wkt_geom = geom.ExportToWkt() - if polygon_wkt[i] != wkt_geom: - gdaltest.post_reason("Failure in getting geometries of TIN") - return 'fail' + assert polygon_wkt[i] == wkt_geom, "Failure in getting geometries of TIN" wkt_original = 'TIN Z (((0 0 0,0 0 1,0 1 0,0 0 0)),((0 0 0,0 1 0,1 1 0,0 0 0)))' tin = ogr.CreateGeometryFromWkt(wkt_original) @@ -346,25 +270,17 @@ def ogr_geom_tin(): wkb_string = tin.ExportToWkb(ogr.wkbXDR) geom = ogr.CreateGeometryFromWkb(wkb_string) wkt_string = geom.ExportToWkt() - if wkt_string != wkt_original: - gdaltest.post_reason("Failure in Wkb methods of TIN") - return 'fail' + assert wkt_string == wkt_original, "Failure in Wkb methods of TIN" wkt_string = geom.Clone().ExportToWkt() - if wkt_string != wkt_original: - gdaltest.post_reason("Failure in Clone()") - return 'fail' + assert wkt_string == wkt_original, "Failure in Clone()" if ogrtest.have_sfcgal(): area = 12.3 * tin.Area() - if area != 12.3: - gdaltest.post_reason("Wrong area of TIN") - return 'fail' + assert area == 12.3, "Wrong area of TIN" size = tin.WkbSize() - if size != 227: - gdaltest.post_reason("Wrong WkbSize() of TIN") - return 'fail' + assert size == 227, "Wrong WkbSize() of TIN" # geom = tin.DelaunayTriangulation(0.0,True) # wkt_geom_dt = 'MULTILINESTRING ((0 1 0,1 1 0),(0 0 0,0 1 0),(0 0 0,1 1 0))' @@ -379,33 +295,26 @@ def ogr_geom_tin(): # gdaltest.post_reason ("Failure in Contains() of TIN") # return 'fail' - if tin.IsEmpty(): - gdaltest.post_reason("Failure in IsEmpty() of TIN") - return 'fail' + assert not tin.IsEmpty(), "Failure in IsEmpty() of TIN" tin.Empty() wkt_string = tin.ExportToWkt() - if wkt_string != 'TIN Z EMPTY': - gdaltest.post_reason("Failure in Empty() of TIN") - return 'fail' + assert wkt_string == 'TIN Z EMPTY', "Failure in Empty() of TIN" wrong_polygon = ogr.CreateGeometryFromWkt('POLYGON ((0 0 0,0 1 0,1 1 0,0 0 1))') geom_count = tin.GetGeometryCount() gdal.PushErrorHandler('CPLQuietErrorHandler') x = tin.AddGeometry(wrong_polygon) gdal.PopErrorHandler() - if tin.GetGeometryCount() != geom_count: - gdaltest.post_reason("Added wrong geometry in TIN, error has code " + str(x)) - return 'fail' + assert tin.GetGeometryCount() == geom_count, \ + ("Added wrong geometry in TIN, error has code " + str(x)) if ogrtest.have_geos() or ogrtest.have_sfcgal(): point = tin.PointOnSurface() point_wkt = point.ExportToWkt() point_correct_wkt = 'POINT EMPTY' - if point_wkt != point_correct_wkt: - gdaltest.post_reason("Wrong Point Obtained for PointOnSurface() in TIN") - print(point_wkt) - return 'fail' + assert point_wkt == point_correct_wkt, \ + "Wrong Point Obtained for PointOnSurface() in TIN" tin = ogr.CreateGeometryFromWkt(wkt_original) # point = tin.PointOnSurface() @@ -417,151 +326,118 @@ def ogr_geom_tin(): # return 'fail' tin.FlattenTo2D() - if tin.IsValid(): - gdaltest.post_reason("Problem with IsValid() in TIN") - return 'fail' + assert not tin.IsValid(), "Problem with IsValid() in TIN" # 4 points invalid_wkt = 'TIN (((0 0,0 1,1 1,1 0,0 0)))' with gdaltest.error_handler(): g = ogr.CreateGeometryFromWkt(invalid_wkt) - if g is not None: - gdaltest.post_reason('fail') - return 'fail' + assert g is None # hole invalid_wkt = 'TIN(((0 0,0 1,1 1,0 0),(0.1 0.1,0.1 0.2,0.2 0.2,0.1 0.1)))' with gdaltest.error_handler(): g = ogr.CreateGeometryFromWkt(invalid_wkt) - if g is not None: - gdaltest.post_reason('fail') - return 'fail' + assert g is None invalid_wkt = 'TIN (POLYGON((0 0,0 1,1 1,0 0)))' with gdaltest.error_handler(): g = ogr.CreateGeometryFromWkt(invalid_wkt) - if g is not None: - gdaltest.post_reason('fail') - return 'fail' + assert g is None # Add a POLYGON that can be cast as a TRIANGLE g = ogr.Geometry(ogr.wkbTIN) - if g.AddGeometry(ogr.CreateGeometryFromWkt('POLYGON ((0 0,0 1,1 1,0 0))')) != 0: - gdaltest.post_reason('fail') - return 'fail' - if g.ExportToIsoWkt() != 'TIN (((0 0,0 1,1 1,0 0)))': - gdaltest.post_reason('fail') - return 'fail' - - return 'success' + assert g.AddGeometry(ogr.CreateGeometryFromWkt('POLYGON ((0 0,0 1,1 1,0 0))')) == 0 + assert g.ExportToIsoWkt() == 'TIN (((0 0,0 1,1 1,0 0)))' ############################################################################### # Test OGRGeometry::getBoundary() result for point. -def ogr_geom_boundary_point(): +def test_ogr_geom_boundary_point(): if not ogrtest.have_geos(): - return 'skip' + pytest.skip() geom_wkt = 'POINT(1 1)' geom = ogr.CreateGeometryFromWkt(geom_wkt) bnd = geom.GetBoundary() - if bnd.GetGeometryType() != ogr.wkbGeometryCollection: - gdaltest.post_reason('GetBoundary not reported as GEOMETRYCOLLECTION EMPTY') - return 'fail' + assert bnd.GetGeometryType() == ogr.wkbGeometryCollection, \ + 'GetBoundary not reported as GEOMETRYCOLLECTION EMPTY' bnd = geom.Boundary() - if bnd.GetGeometryType() != ogr.wkbGeometryCollection: - gdaltest.post_reason('Boundary not reported as GEOMETRYCOLLECTION EMPTY') - return 'fail' - - return 'success' + assert bnd.GetGeometryType() == ogr.wkbGeometryCollection, \ + 'Boundary not reported as GEOMETRYCOLLECTION EMPTY' ############################################################################### # Test OGRGeometry::getBoundary() result for multipoint. -def ogr_geom_boundary_multipoint(): +def test_ogr_geom_boundary_multipoint(): if not ogrtest.have_geos(): - return 'skip' + pytest.skip() geom_wkt = 'MULTIPOINT((0 0),(1 1))' geom = ogr.CreateGeometryFromWkt(geom_wkt) bnd = geom.GetBoundary() - if bnd.GetGeometryType() != ogr.wkbGeometryCollection: - gdaltest.post_reason('Boundary not reported as GEOMETRYCOLLECTION EMPTY') - return 'fail' - - return 'success' + assert bnd.GetGeometryType() == ogr.wkbGeometryCollection, \ + 'Boundary not reported as GEOMETRYCOLLECTION EMPTY' ############################################################################### # Test OGRGeometry::getBoundary() result for linestring. -def ogr_geom_boundary_linestring(): +def test_ogr_geom_boundary_linestring(): if not ogrtest.have_geos(): - return 'skip' + pytest.skip() geom_wkt = 'LINESTRING(0 0, 1 1, 2 2, 3 2, 4 2)' geom = ogr.CreateGeometryFromWkt(geom_wkt) bnd = geom.GetBoundary() - if bnd.GetGeometryType() != ogr.wkbMultiPoint: - gdaltest.post_reason('Boundary not reported as MULTIPOINT') - print(bnd) - return 'fail' + assert bnd.GetGeometryType() == ogr.wkbMultiPoint, \ + 'Boundary not reported as MULTIPOINT' - if bnd.GetGeometryCount() != 2: - gdaltest.post_reason('Boundary not reported as MULTIPOINT consisting of 2 points') - return 'fail' + assert bnd.GetGeometryCount() == 2, \ + 'Boundary not reported as MULTIPOINT consisting of 2 points' geom_wkt = 'LINESTRING(0 0, 1 0, 1 1, 0 1, 0 0)' geom = ogr.CreateGeometryFromWkt(geom_wkt) bnd = geom.GetBoundary() - if bnd.GetGeometryType() != ogr.wkbMultiPoint: - gdaltest.post_reason('Boundary not reported as MULTIPOINT') - return 'fail' + assert bnd.GetGeometryType() == ogr.wkbMultiPoint, \ + 'Boundary not reported as MULTIPOINT' - if bnd.GetGeometryCount() != 0: - gdaltest.post_reason('Boundary not reported as MULTIPOINT EMPTY') - return 'fail' - - return 'success' + assert bnd.GetGeometryCount() == 0, 'Boundary not reported as MULTIPOINT EMPTY' ############################################################################### # Test OGRGeometry::getBoundary() result for polygon. -def ogr_geom_boundary_polygon(): +def test_ogr_geom_boundary_polygon(): if not ogrtest.have_geos(): - return 'skip' + pytest.skip() geom_wkt = 'POLYGON((0 0,1 1,1 0,0 0))' geom = ogr.CreateGeometryFromWkt(geom_wkt) bnd = geom.GetBoundary() - if bnd.GetGeometryType() != ogr.wkbLineString: - gdaltest.post_reason('Boundary not reported as non-empty LINESTRING') - print(bnd) - return 'fail' - - return 'success' + assert bnd.GetGeometryType() == ogr.wkbLineString, \ + 'Boundary not reported as non-empty LINESTRING' ############################################################################### # Test OGRBuildPolygonFromEdges() on a geometry collection of line strings -def ogr_geom_build_from_edges_1(): +def test_ogr_geom_build_from_edges_1(): if not ogrtest.have_geos(): - return 'skip' + pytest.skip() link_coll = ogr.Geometry(type=ogr.wkbGeometryCollection) @@ -580,21 +456,19 @@ def ogr_geom_build_from_edges_1(): try: poly = ogr.BuildPolygonFromEdges(link_coll) - if poly is None: - return 'fail' + assert poly is not None except: - return 'fail' - - return 'success' + pytest.fail() + ############################################################################### # Test OGRBuildPolygonFromEdges() on a multilinestring -def ogr_geom_build_from_edges_2(): +def test_ogr_geom_build_from_edges_2(): if not ogrtest.have_geos(): - return 'skip' + pytest.skip() link_coll = ogr.Geometry(type=ogr.wkbMultiLineString) @@ -612,29 +486,26 @@ def ogr_geom_build_from_edges_2(): try: poly = ogr.BuildPolygonFromEdges(link_coll) - if poly is None: - return 'fail' + assert poly is not None except: - return 'fail' - - return 'success' + pytest.fail() + ############################################################################### # Test OGRBuildPolygonFromEdges() on invalid geometries -def ogr_geom_build_from_edges_3(): +def test_ogr_geom_build_from_edges_3(): if not ogrtest.have_geos(): - return 'skip' + pytest.skip() src_geom = ogr.CreateGeometryFromWkt('POINT (0 1)') try: gdal.PushErrorHandler('CPLQuietErrorHandler') poly = ogr.BuildPolygonFromEdges(src_geom) gdal.PopErrorHandler() - if poly is not None: - return 'fail' + assert poly is None except: pass @@ -643,25 +514,22 @@ def ogr_geom_build_from_edges_3(): gdal.PushErrorHandler('CPLQuietErrorHandler') poly = ogr.BuildPolygonFromEdges(src_geom) gdal.PopErrorHandler() - if poly is not None: - return 'fail' + assert poly is None except: pass - return 'success' - + ############################################################################### # Test OGRBuildPolygonFromEdges() and identify exterior ring (#3610) -def ogr_geom_build_from_edges_4(): +def test_ogr_geom_build_from_edges_4(): if int(gdal.VersionInfo('VERSION_NUM')) < 1900: - gdaltest.post_reason('would crash') - return 'skip' + pytest.skip('would crash') if not ogrtest.have_geos(): - return 'skip' + pytest.skip() link_coll = ogr.Geometry(type=ogr.wkbGeometryCollection) @@ -685,36 +553,29 @@ def ogr_geom_build_from_edges_4(): try: poly = ogr.BuildPolygonFromEdges(link_coll) - if poly is None: - return 'fail' + assert poly is not None wkt = poly.ExportToWkt() - if wkt != 'POLYGON ((0 0,0 10,10 10,10 0,0 0),(1 1,1 2,2 2,2 1,1 1))': - print(wkt) - return 'fail' + assert wkt == 'POLYGON ((0 0,0 10,10 10,10 0,0 0),(1 1,1 2,2 2,2 1,1 1))' except: - return 'fail' - - return 'success' + pytest.fail() + ############################################################################### # Test GetArea() on empty linear ring (#2792) -def ogr_geom_area_empty_linearring(): +def test_ogr_geom_area_empty_linearring(): geom = ogr.Geometry(type=ogr.wkbLinearRing) area = geom.GetArea() - if area != 0: - return 'fail' - - return 'success' + assert area == 0 ############################################################################### # Test TransformTo() -def ogr_geom_transform_to(): +def test_ogr_geom_transform_to(): # Somewhere in Paris suburbs... geom = ogr.CreateGeometryFromWkt('POINT(2 49)') @@ -729,27 +590,21 @@ def ogr_geom_transform_to(): sr2.ImportFromEPSG(32631) ret = geom.TransformTo(sr2) - if ret != 0 or abs(geom.GetX() - 426857) > 1 or abs(geom.GetY() - 5427937) > 1: - gdaltest.post_reason('failure') - print(geom.ExportToWkt()) - return 'fail' + assert ret == 0 and abs(geom.GetX() - 426857) <= 1 and abs(geom.GetY() - 5427937) <= 1, \ + geom.ExportToWkt() # Geometry without SRS geom = ogr.CreateGeometryFromWkt('POINT(2 49)') gdal.ErrorReset() with gdaltest.error_handler(): ret = geom.TransformTo(sr2) - if ret == 0 or gdal.GetLastErrorMsg() == '': - gdaltest.post_reason('failure') - return 'fail' - - return 'success' + assert not (ret == 0 or gdal.GetLastErrorMsg() == '') ############################################################################### # Test Transform() -def ogr_geom_transform(): +def test_ogr_geom_transform(): # Somewhere in Paris suburbs... geom = ogr.CreateGeometryFromWkt('POINT(2 49)') @@ -766,51 +621,38 @@ def ogr_geom_transform(): geom.Transform(ct) - if abs(geom.GetX() - 426857) > 1 or abs(geom.GetY() - 5427937) > 1: - print(geom.ExportToWkt()) - return 'fail' - - return 'success' + assert abs(geom.GetX() - 426857) <= 1 and abs(geom.GetY() - 5427937) <= 1, \ + geom.ExportToWkt() ############################################################################### # Test CloseRings() -def ogr_geom_closerings(): +def test_ogr_geom_closerings(): geom = ogr.CreateGeometryFromWkt('POLYGON((0 0,0 1,1 1,1 0))') geom.CloseRings() - if geom.ExportToWkt() != 'POLYGON ((0 0,0 1,1 1,1 0,0 0))': - print(geom.ExportToWkt()) - return 'fail' + assert geom.ExportToWkt() == 'POLYGON ((0 0,0 1,1 1,1 0,0 0))' geom.CloseRings() - if geom.ExportToWkt() != 'POLYGON ((0 0,0 1,1 1,1 0,0 0))': - print(geom.ExportToWkt()) - return 'fail' - - return 'success' + assert geom.ExportToWkt() == 'POLYGON ((0 0,0 1,1 1,1 0,0 0))' ############################################################################### # Test Segmentize() -def ogr_geom_segmentize(): +def test_ogr_geom_segmentize(): geom = ogr.CreateGeometryFromWkt('LINESTRING(0 0,0 10)') geom.Segmentize(1.00001) - if geom.ExportToWkt() != 'LINESTRING (0 0,0 1,0 2,0 3,0 4,0 5,0 6,0 7,0 8,0 9,0 10)': - print(geom.ExportToWkt()) - return 'fail' + assert geom.ExportToWkt() == 'LINESTRING (0 0,0 1,0 2,0 3,0 4,0 5,0 6,0 7,0 8,0 9,0 10)' geom = ogr.CreateGeometryFromWkt('LINESTRING(0 0 1,0 10 1)') geom.Segmentize(1.00001) - if geom.ExportToWkt() != 'LINESTRING (0 0 1,0 1 1,0 2 1,0 3 1,0 4 1,0 5 1,0 6 1,0 7 1,0 8 1,0 9 1,0 10 1)': - print(geom.ExportToWkt()) - return 'fail' + assert geom.ExportToWkt() == 'LINESTRING (0 0 1,0 1 1,0 2 1,0 3 1,0 4 1,0 5 1,0 6 1,0 7 1,0 8 1,0 9 1,0 10 1)' # Check segmentize symmetry : do exact binary comparison. in_wkt = 'LINESTRING (0 0,1.2 1,2 0)' @@ -821,250 +663,172 @@ def ogr_geom_segmentize(): g2.Segmentize(0.25) for i in range(g1.GetPointCount()): if g1.GetPoint(i) != g2.GetPoint(g1.GetPointCount() - 1 - i): - gdaltest.post_reason('fail') - print(i) print('%.18g' % (g1.GetPoint(i)[0] - g2.GetPoint(g1.GetPointCount() - 1 - i)[0])) - print('%.18g' % (g1.GetPoint(i)[1] - g2.GetPoint(g1.GetPointCount() - 1 - i)[1])) - print(g1) - print(g2) - return 'fail' - - return 'success' + pytest.fail('%.18g' % (g1.GetPoint(i)[1] - g2.GetPoint(g1.GetPointCount() - 1 - i)[1])) + ############################################################################### # Test Value() -def ogr_geom_value(): +def test_ogr_geom_value(): geom = ogr.CreateGeometryFromWkt('LINESTRING(2 3,5 3,5 0)') p = geom.Value(-1e-3) expected_p = ogr.CreateGeometryFromWkt('POINT (2 3)') - if ogrtest.check_feature_geometry(p, expected_p) != 0: - gdaltest.post_reason('fail') - print(p) - return 'fail' + assert ogrtest.check_feature_geometry(p, expected_p) == 0 p = geom.Value(geom.Length() / 4) expected_p = ogr.CreateGeometryFromWkt('POINT (3.5 3)') - if ogrtest.check_feature_geometry(p, expected_p) != 0: - gdaltest.post_reason('fail') - print(p) - return 'fail' + assert ogrtest.check_feature_geometry(p, expected_p) == 0 p = geom.Value(geom.Length() / 2) expected_p = ogr.CreateGeometryFromWkt('POINT (5 3)') - if ogrtest.check_feature_geometry(p, expected_p) != 0: - gdaltest.post_reason('fail') - print(p) - return 'fail' + assert ogrtest.check_feature_geometry(p, expected_p) == 0 p = geom.Value(3 * geom.Length() / 4) expected_p = ogr.CreateGeometryFromWkt('POINT (5 1.5)') - if ogrtest.check_feature_geometry(p, expected_p) != 0: - gdaltest.post_reason('fail') - print(p) - return 'fail' + assert ogrtest.check_feature_geometry(p, expected_p) == 0 p = geom.Value(geom.Length() + 1e-3) expected_p = ogr.CreateGeometryFromWkt('POINT (5 0)') - if ogrtest.check_feature_geometry(p, expected_p) != 0: - gdaltest.post_reason('fail') - print(p) - return 'fail' - - return 'success' + assert ogrtest.check_feature_geometry(p, expected_p) == 0 ############################################################################### # Test FlattenTo2D(), GetDimension() and GetCoordinateDimension() -def ogr_geom_flattenTo2D(): +def test_ogr_geom_flattenTo2D(): geom = ogr.CreateGeometryFromWkt('POINT (1 2 3)') # Point is 0 dimension, LineString 1, ... - if geom.GetDimension() != 0: - gdaltest.post_reason('fail') - print(geom.GetDimension()) - return 'fail' + assert geom.GetDimension() == 0 - if geom.GetCoordinateDimension() != 3: - gdaltest.post_reason('fail') - print(geom.GetCoordinateDimension()) - return 'fail' + assert geom.GetCoordinateDimension() == 3 geom.FlattenTo2D() - if geom.GetCoordinateDimension() != 2: - gdaltest.post_reason('fail') - print(geom.GetCoordinateDimension()) - return 'fail' - - if geom.ExportToWkt() != 'POINT (1 2)': - gdaltest.post_reason('fail') - print(geom.ExportToWkt()) - return 'fail' + assert geom.GetCoordinateDimension() == 2 - return 'success' + assert geom.ExportToWkt() == 'POINT (1 2)' ############################################################################### # Test FlattenTo2D(), GetDimension() and GetCoordinateDimension() for Triangle -def ogr_geom_flattenTo2D_triangle(): +def test_ogr_geom_flattenTo2D_triangle(): geom = ogr.CreateGeometryFromWkt('TRIANGLE ((0 0 0,100 0 100,0 100 100,0 0 0))') # Point is 0 dimension, LineString 1, ... - if geom.GetDimension() != 2: - gdaltest.post_reason('fail') - print(geom.GetDimension()) - return 'fail' + assert geom.GetDimension() == 2 - if geom.GetCoordinateDimension() != 3: - gdaltest.post_reason('fail') - print(geom.GetCoordinateDimension()) - return 'fail' + assert geom.GetCoordinateDimension() == 3 geom.FlattenTo2D() - if geom.GetCoordinateDimension() != 2: - gdaltest.post_reason('fail') - print(geom.GetCoordinateDimension()) - return 'fail' + assert geom.GetCoordinateDimension() == 2 - if geom.ExportToWkt() != 'TRIANGLE ((0 0,100 0,0 100,0 0))': - gdaltest.post_reason('fail') - print(geom.ExportToWkt()) - return 'fail' - - return 'success' + assert geom.ExportToWkt() == 'TRIANGLE ((0 0,100 0,0 100,0 0))' ############################################################################### -def ogr_geom_linestring_limits(): +def test_ogr_geom_linestring_limits(): geom = ogr.CreateGeometryFromWkt('LINESTRING EMPTY') - if geom.Length() != 0: - return 'fail' + assert geom.Length() == 0 gdal.ErrorReset() gdal.PushErrorHandler('CPLQuietErrorHandler') geom.GetPoint(-1) gdal.PopErrorHandler() - if gdal.GetLastErrorType() == 0: - return 'fail' + assert gdal.GetLastErrorType() != 0 gdal.ErrorReset() gdal.PushErrorHandler('CPLQuietErrorHandler') geom.GetPoint(0) gdal.PopErrorHandler() - if gdal.GetLastErrorType() == 0: - return 'fail' + assert gdal.GetLastErrorType() != 0 gdal.ErrorReset() gdal.PushErrorHandler('CPLQuietErrorHandler') geom.GetPoint_2D(-1) gdal.PopErrorHandler() - if gdal.GetLastErrorType() == 0: - return 'fail' + assert gdal.GetLastErrorType() != 0 gdal.ErrorReset() gdal.PushErrorHandler('CPLQuietErrorHandler') geom.GetPoint_2D(0) gdal.PopErrorHandler() - if gdal.GetLastErrorType() == 0: - return 'fail' + assert gdal.GetLastErrorType() != 0 gdal.ErrorReset() gdal.PushErrorHandler('CPLQuietErrorHandler') geom.SetPoint(-1, 5, 6, 7) gdal.PopErrorHandler() - if gdal.GetLastErrorType() == 0: - return 'fail' + assert gdal.GetLastErrorType() != 0 gdal.ErrorReset() gdal.PushErrorHandler('CPLQuietErrorHandler') geom.SetPoint_2D(-1, 5, 6) gdal.PopErrorHandler() - if gdal.GetLastErrorType() == 0: - return 'fail' + assert gdal.GetLastErrorType() != 0 if False: # pylint: disable=using-constant-test gdal.ErrorReset() gdal.PushErrorHandler('CPLQuietErrorHandler') geom.SetPoint(2147000000, 5, 6, 7) gdal.PopErrorHandler() - if gdal.GetLastErrorType() == 0: - return 'fail' + assert gdal.GetLastErrorType() != 0 gdal.ErrorReset() gdal.PushErrorHandler('CPLQuietErrorHandler') geom.SetPoint_2D(2147000000, 5, 6) gdal.PopErrorHandler() - if gdal.GetLastErrorType() == 0: - return 'fail' + assert gdal.GetLastErrorType() != 0 geom = ogr.CreateGeometryFromWkt('LINESTRING(0 0)') - if geom.Length() != 0: - return 'fail' + assert geom.Length() == 0 geom = ogr.CreateGeometryFromWkt('LINESTRING(0 0, 1 0)') - if geom.Length() != 1: - return 'fail' - - return 'success' + assert geom.Length() == 1 ############################################################################### -def ogr_geom_coord_round(): +def test_ogr_geom_coord_round(): geom = ogr.CreateGeometryFromWkt('POINT(370441.860 5591000.590)') wkt = geom.ExportToWkt() - if wkt != 'POINT (370441.86 5591000.59)': - gdaltest.post_reason('did not get expected WKT') - print(wkt) - return 'fail' - - return 'success' + assert wkt == 'POINT (370441.86 5591000.59)', 'did not get expected WKT' ############################################################################### -def ogr_geom_coord_round_2(): +def test_ogr_geom_coord_round_2(): geom = ogr.CreateGeometryFromWkt('POINT(1.0 169.600374)') wkt = geom.ExportToWkt() - if wkt != 'POINT (1.0 169.600374)': - gdaltest.post_reason('did not get expected WKT') - print(wkt) - return 'fail' - - return 'success' + assert wkt == 'POINT (1.0 169.600374)', 'did not get expected WKT' ############################################################################### # Test Area calculation for a Point -def ogr_geom_area_point(): +def test_ogr_geom_area_point(): geom_wkt = 'POINT(0 0)' geom = ogr.CreateGeometryFromWkt(geom_wkt) with gdaltest.error_handler(): area = geom.Area() - if area != 0: - gdaltest.post_reason('Area() result wrong, got %g.' % area) - return 'fail' - - return 'success' + assert area == 0, ('Area() result wrong, got %g.' % area) ############################################################################### # Test Length calculation for a Point -def ogr_geom_length_point(): +def test_ogr_geom_length_point(): # OGR >= 1.8.0 geom_wkt = 'POINT(0 0)' @@ -1072,243 +836,163 @@ def ogr_geom_length_point(): with gdaltest.error_handler(): length = geom.Length() - if length != 0: - gdaltest.post_reason('Length() result wrong, got %g.' % length) - return 'fail' - - return 'success' + assert length == 0, ('Length() result wrong, got %g.' % length) ############################################################################### # Test Length calculation for a MultiLineString -def ogr_geom_length_multilinestring(): +def test_ogr_geom_length_multilinestring(): # OGR >= 1.8.0 geom_wkt = 'MULTILINESTRING((0 0,0 1),(0 0,0 1))' geom = ogr.CreateGeometryFromWkt(geom_wkt) length = geom.Length() - if abs(length - 2) > 0.00000000001: - gdaltest.post_reason('Length() result wrong, got %g.' % length) - return 'fail' - - return 'success' + assert abs(length - 2) <= 0.00000000001, ('Length() result wrong, got %g.' % length) ############################################################################### # Test Length calculation for a GeometryCollection -def ogr_geom_length_geometrycollection(): +def test_ogr_geom_length_geometrycollection(): # OGR >= 1.8.0 geom_wkt = 'GEOMETRYCOLLECTION( POLYGON((0 0,0 1,1 1,1 0,0 0)), MULTILINESTRING((0 0,0 1),(0 0,0 1)), LINESTRING(0 0,0 1), LINESTRING(0 0,0 1), POINT(0 0), GEOMETRYCOLLECTION EMPTY )' geom = ogr.CreateGeometryFromWkt(geom_wkt) length = geom.Length() - if abs(length - 4) > 0.00000000001: - gdaltest.post_reason('Length() result wrong, got %g.' % length) - return 'fail' - - return 'success' + assert abs(length - 4) <= 0.00000000001, ('Length() result wrong, got %g.' % length) ############################################################################### # Test Geometry.GetPoints() (#4016) -def ogr_geom_getpoints(): +def test_ogr_geom_getpoints(): geom = ogr.CreateGeometryFromWkt('LINESTRING(0 1,2 3)') points = geom.GetPoints() - if points != [(0.0, 1.0), (2.0, 3.0)]: - gdaltest.post_reason('did not get expected points (1)') - print(points) - return 'fail' + assert points == [(0.0, 1.0), (2.0, 3.0)], 'did not get expected points (1)' points = geom.GetPoints(nCoordDimension=3) - if points != [(0.0, 1.0, 0.0), (2.0, 3.0, 0.0)]: - gdaltest.post_reason('did not get expected points (2)') - print(points) - return 'fail' + assert points == [(0.0, 1.0, 0.0), (2.0, 3.0, 0.0)], \ + 'did not get expected points (2)' geom = ogr.CreateGeometryFromWkt('LINESTRING(0 1 2,3 4 5)') points = geom.GetPoints() - if points != [(0.0, 1.0, 2.0), (3.0, 4.0, 5.0)]: - gdaltest.post_reason('did not get expected points (3)') - print(points) - return 'fail' + assert points == [(0.0, 1.0, 2.0), (3.0, 4.0, 5.0)], \ + 'did not get expected points (3)' points = geom.GetPoints(nCoordDimension=2) - if points != [(0.0, 1.0), (3.0, 4.0)]: - gdaltest.post_reason('did not get expected points (4)') - print(points) - return 'fail' + assert points == [(0.0, 1.0), (3.0, 4.0)], 'did not get expected points (4)' geom = ogr.CreateGeometryFromWkt('POINT(0 1)') points = geom.GetPoints() - if points != [(0.0, 1.0)]: - gdaltest.post_reason('did not get expected points (5)') - print(points) - return 'fail' + assert points == [(0.0, 1.0)], 'did not get expected points (5)' points = geom.GetPoints(nCoordDimension=3) - if points != [(0.0, 1.0, 0.0)]: - gdaltest.post_reason('did not get expected points (6)') - print(points) - return 'fail' + assert points == [(0.0, 1.0, 0.0)], 'did not get expected points (6)' geom = ogr.CreateGeometryFromWkt('POINT(0 1 2)') points = geom.GetPoints() - if points != [(0.0, 1.0, 2.0)]: - gdaltest.post_reason('did not get expected points (7)') - print(points) - return 'fail' + assert points == [(0.0, 1.0, 2.0)], 'did not get expected points (7)' points = geom.GetPoints(nCoordDimension=2) - if points != [(0.0, 1.0)]: - gdaltest.post_reason('did not get expected points (8)') - print(points) - return 'fail' - - return 'success' + assert points == [(0.0, 1.0)], 'did not get expected points (8)' ############################################################################### # Test OGRGeometry::empty() -def ogr_geom_empty(): +def test_ogr_geom_empty(): g1 = ogr.CreateGeometryFromWkt('POLYGON((0 0,1 1,1 2,1 1,0 0))') g1.Empty() wkt = g1.ExportToWkt() - if wkt != 'POLYGON EMPTY': - return 'fail' - - return 'success' + assert wkt == 'POLYGON EMPTY' ############################################################################### # Test OGRGeometry::empty() for Triangle -def ogr_geom_empty_triangle(): +def test_ogr_geom_empty_triangle(): g1 = ogr.CreateGeometryFromWkt('TRIANGLE ((0 0,100 0,0 100,0 0))') g1.Empty() wkt = g1.ExportToWkt() - if wkt != 'TRIANGLE EMPTY': - return 'fail' - - return 'success' + assert wkt == 'TRIANGLE EMPTY' ############################################################################### # Test parsing WKT made of 2D and 3D parts -def ogr_geom_mixed_coordinate_dimension(): +def test_ogr_geom_mixed_coordinate_dimension(): # first part is 3D, second part is 2D of same length wkt = 'MULTIPOLYGON (((1 2 -4,1 3 -3,2 3 -3,2 2 -3,1 2 -6)),((-1 -2,-1 -3,-2 -3,-2 -2,-1 -2,50 60)))' expected_wkt = 'MULTIPOLYGON (((1 2 -4,1 3 -3,2 3 -3,2 2 -3,1 2 -6)),((-1 -2 0,-1 -3 0,-2 -3 0,-2 -2 0,-1 -2 0,50 60 0)))' g = ogr.CreateGeometryFromWkt(wkt) got_wkt = g.ExportToWkt() - if got_wkt != expected_wkt: - gdaltest.post_reason('for %s: got %s, expected %s' % (wkt, got_wkt, expected_wkt)) - return 'fail' + assert got_wkt == expected_wkt, \ + ('for %s: got %s, expected %s' % (wkt, got_wkt, expected_wkt)) # first part is 3D, second part is 2D of same length, except the last point which is 3D wkt = 'MULTIPOLYGON (((1 2 -4,1 3 -3,2 3 -3,2 2 -3,1 2 -6)),((-1 -2,-1 -3,-2 -3,-2 -2,-1 -2,50 60 7)))' expected_wkt = 'MULTIPOLYGON (((1 2 -4,1 3 -3,2 3 -3,2 2 -3,1 2 -6)),((-1 -2 0,-1 -3 0,-2 -3 0,-2 -2 0,-1 -2 0,50 60 7)))' g = ogr.CreateGeometryFromWkt(wkt) got_wkt = g.ExportToWkt() - if got_wkt != expected_wkt: - gdaltest.post_reason('for %s: got %s, expected %s' % (wkt, got_wkt, expected_wkt)) - return 'fail' - - return 'success' + assert got_wkt == expected_wkt, \ + ('for %s: got %s, expected %s' % (wkt, got_wkt, expected_wkt)) ############################################################################### # Test GetEnvelope3D() -def ogr_geom_getenvelope3d(): +def test_ogr_geom_getenvelope3d(): g = ogr.CreateGeometryFromWkt('POINT EMPTY') envelope = g.GetEnvelope3D() expected_envelope = (0.0, 0.0, 0.0, 0.0, 0.0, 0.0) - if envelope != expected_envelope: - gdaltest.post_reason('did not get expected envelope (1)') - print(envelope) - print(expected_envelope) - return 'fail' + assert envelope == expected_envelope, 'did not get expected envelope (1)' g = ogr.CreateGeometryFromWkt('POINT(1 2)') envelope = g.GetEnvelope3D() expected_envelope = (1.0, 1.0, 2.0, 2.0, 0.0, 0.0) - if envelope != expected_envelope: - gdaltest.post_reason('did not get expected envelope (2)') - print(envelope) - print(expected_envelope) - return 'fail' + assert envelope == expected_envelope, 'did not get expected envelope (2)' g = ogr.CreateGeometryFromWkt('POINT(1 2 3)') envelope = g.GetEnvelope3D() expected_envelope = (1.0, 1.0, 2.0, 2.0, 3.0, 3.0) - if envelope != expected_envelope: - gdaltest.post_reason('did not get expected envelope (3)') - print(envelope) - print(expected_envelope) - return 'fail' + assert envelope == expected_envelope, 'did not get expected envelope (3)' g = ogr.CreateGeometryFromWkt('POLYGON EMPTY') envelope = g.GetEnvelope3D() expected_envelope = (0.0, 0.0, 0.0, 0.0, 0.0, 0.0) - if envelope != expected_envelope: - gdaltest.post_reason('did not get expected envelope (4)') - print(envelope) - print(expected_envelope) - return 'fail' + assert envelope == expected_envelope, 'did not get expected envelope (4)' g = ogr.CreateGeometryFromWkt('LINESTRING(1 2,3 4)') envelope = g.GetEnvelope3D() expected_envelope = (1, 3, 2, 4, 0, 0) - if envelope != expected_envelope: - gdaltest.post_reason('did not get expected envelope (5)') - print(envelope) - print(expected_envelope) - return 'fail' + assert envelope == expected_envelope, 'did not get expected envelope (5)' g = ogr.CreateGeometryFromWkt('MULTIPOLYGON(((1 2 3,-1 2 3,-1 -2 3,-1 2 3,1 2 3),(0.1 0.2 0.3,-0.1 0.2 0.3,-0.1 -0.2 0.3,-0.1 0.2 0.3,0.1 0.2 0.3)),((10 20 -30,-10 20 -30,-10 -20 -30,-10 20 -30,10 20 -30)))') envelope = g.GetEnvelope3D() expected_envelope = (-10, 10, -20, 20, -30, 3.0) - if envelope != expected_envelope: - gdaltest.post_reason('did not get expected envelope (6)') - print(envelope) - print(expected_envelope) - return 'fail' + assert envelope == expected_envelope, 'did not get expected envelope (6)' g = ogr.CreateGeometryFromWkt('MULTIPOLYGON EMPTY') envelope = g.GetEnvelope3D() expected_envelope = (0.0, 0.0, 0.0, 0.0, 0.0, 0.0) - if envelope != expected_envelope: - gdaltest.post_reason('did not get expected envelope (7)') - print(envelope) - print(expected_envelope) - return 'fail' + assert envelope == expected_envelope, 'did not get expected envelope (7)' g = ogr.CreateGeometryFromWkt('TRIANGLE ((0 0 0,100 0 100,0 100 100,0 0 0))') envelope = g.GetEnvelope3D() expected_envelope = (0.0, 100.0, 0.0, 100.0, 0.0, 100.0) - if envelope != expected_envelope: - gdaltest.post_reason('did not get expected envelope (8)') - print(envelope) - print(expected_envelope) - return 'fail' - - return 'success' + assert envelope == expected_envelope, 'did not get expected envelope (8)' ############################################################################### # Test importing/exporting XXX Z EMPTY -def ogr_geom_z_empty(): +def test_ogr_geom_z_empty(): for geom in ['POINT', 'LINESTRING', 'POLYGON', 'MULTIPOINT', 'MULTILINESTRING', 'MULTIPOLYGON', 'GEOMETRYCOLLECTION', 'CIRCULARSTRING', 'COMPOUNDCURVE', @@ -1316,25 +1000,18 @@ def ogr_geom_z_empty(): in_wkt = geom + ' Z EMPTY' g1 = ogr.CreateGeometryFromWkt(in_wkt) out_wkt = g1.ExportToIsoWkt() - if in_wkt != out_wkt: - gdaltest.post_reason('fail') - print(out_wkt) - return 'fail' + assert in_wkt == out_wkt g2 = ogr.CreateGeometryFromWkb(g1.ExportToIsoWkb()) out_wkt = g2.ExportToIsoWkt() - if in_wkt != out_wkt: - gdaltest.post_reason('fail') - print(out_wkt) - return 'fail' - - return 'success' + assert in_wkt == out_wkt + ############################################################################### # Test HasCurveGeometry and GetLinearGeometry -def ogr_geom_getlineargeometry(): +def test_ogr_geom_getlineargeometry(): for geom in ['POINT', 'LINESTRING', 'POLYGON', 'MULTIPOINT', 'MULTILINESTRING', 'MULTIPOLYGON', 'GEOMETRYCOLLECTION', @@ -1350,39 +1027,22 @@ def ogr_geom_getlineargeometry(): in_wkt = geom_in + ' EMPTY' g = ogr.CreateGeometryFromWkt(in_wkt) g2 = g.GetLinearGeometry() - if geom_in != geom_out and not g.HasCurveGeometry(): - gdaltest.post_reason('fail') - print(g) - return 'fail' - if g2.ExportToWkt() != geom_out + ' EMPTY': - gdaltest.post_reason('fail') - print(g) - print(g2) - return 'fail' + assert geom_in == geom_out or g.HasCurveGeometry() + assert g2.ExportToWkt() == geom_out + ' EMPTY', g g = ogr.CreateGeometryFromWkt('GEOMETRYCOLLECTION(POINT (0 1))') - if g.HasCurveGeometry(): - gdaltest.post_reason('fail') - return 'fail' - if g.HasCurveGeometry(True): - gdaltest.post_reason('fail') - return 'fail' + assert not g.HasCurveGeometry() + assert not g.HasCurveGeometry(True) g = ogr.CreateGeometryFromWkt('GEOMETRYCOLLECTION(CIRCULARSTRING (0 0,0 1,0 0))') - if not g.HasCurveGeometry(): - gdaltest.post_reason('fail') - return 'fail' - if not g.HasCurveGeometry(True): - gdaltest.post_reason('fail') - return 'fail' - - return 'success' + assert g.HasCurveGeometry() + assert g.HasCurveGeometry(True) ############################################################################### # Test GetDimension() -def ogr_geom_getdimension(): +def test_ogr_geom_getdimension(): for (geom, dim) in [('POINT EMPTY', 0), ('LINESTRING EMPTY', 1), ('POLYGON EMPTY', 2), @@ -1399,29 +1059,19 @@ def ogr_geom_getdimension(): ('POLYHEDRALSURFACE EMPTY', 2), ('TIN EMPTY', 2)]: g = ogr.CreateGeometryFromWkt(geom) - if g.GetDimension() != dim: - gdaltest.post_reason('fail') - print(g) - print(dim) - return 'fail' + assert g.GetDimension() == dim g = ogr.CreateGeometryFromWkt('GEOMETRYCOLLECTION(LINESTRING EMPTY, POINT (0 1))') - if g.GetDimension() != 1: - gdaltest.post_reason('fail') - return 'fail' + assert g.GetDimension() == 1 g = ogr.CreateGeometryFromWkt('GEOMETRYCOLLECTION(POINT (0 1), LINESTRING EMPTY, POLYGON EMPTY)') - if g.GetDimension() != 2: - gdaltest.post_reason('fail') - return 'fail' - - return 'success' + assert g.GetDimension() == 2 ############################################################################### # Test triangle -def ogr_geom_triangle(): +def test_ogr_geom_triangle(): wkt_original = 'TRIANGLE ((0 0,0 1,1 1,0 0))' geom = ogr.CreateGeometryFromWkt(wkt_original) @@ -1429,229 +1079,147 @@ def ogr_geom_triangle(): wkb_string = geom.ExportToWkb(ogr.wkbXDR) geom = ogr.CreateGeometryFromWkb(wkb_string) wkt_string = geom.ExportToWkt() - if wkt_string != wkt_original: - gdaltest.post_reason("Failure in Wkb methods of Triangle") - return 'fail' + assert wkt_string == wkt_original, "Failure in Wkb methods of Triangle" wkt_string = geom.Clone().ExportToWkt() - if wkt_string != wkt_original: - gdaltest.post_reason("Failure in Clone()") - return 'fail' + assert wkt_string == wkt_original, "Failure in Clone()" polygon_wkt = ogr.ForceTo(geom.Clone(), ogr.wkbPolygon).ExportToWkt() - if polygon_wkt != 'POLYGON ((0 0,0 1,1 1,0 0))': - gdaltest.post_reason("fail") - print(polygon_wkt) - return 'fail' + assert polygon_wkt == 'POLYGON ((0 0,0 1,1 1,0 0))' polygon_wkt = ogr.ForceTo(geom.Clone(), ogr.wkbMultiPolygon).ExportToWkt() - if polygon_wkt != 'MULTIPOLYGON (((0 0,0 1,1 1,0 0)))': - gdaltest.post_reason("fail") - print(polygon_wkt) - return 'fail' - - return 'success' + assert polygon_wkt == 'MULTIPOLYGON (((0 0,0 1,1 1,0 0)))' ############################################################################### # Test importing invalid triangle WKT -def ogr_geom_triangle_invalid_wkt(): +def test_ogr_geom_triangle_invalid_wkt(): geom_wkt = 'TRIANGLE (0 0)' with gdaltest.error_handler(): geom = ogr.CreateGeometryFromWkt(geom_wkt) - if geom is not None: - gdaltest.post_reason('fail') - return 'fail' + assert geom is None geom_wkt = 'TRIANGLE ((0 0))' with gdaltest.error_handler(): geom = ogr.CreateGeometryFromWkt(geom_wkt) - if geom is not None: - gdaltest.post_reason('fail') - print(geom) - return 'fail' + assert geom is None geom_wkt = 'TRIANGLE ((0 0,0 1,1 1,1 0))' with gdaltest.error_handler(): geom = ogr.CreateGeometryFromWkt(geom_wkt) - if geom is not None: - gdaltest.post_reason('fail') - print(geom) - return 'fail' + assert geom is None geom_wkt = 'TRIANGLE ((0 0,0 1,1 1,1 0,0 0))' with gdaltest.error_handler(): geom = ogr.CreateGeometryFromWkt(geom_wkt) - if geom is not None: - gdaltest.post_reason('fail') - print(geom) - return 'fail' + assert geom is None geom_wkt = 'TRIANGLE ((0 0,0 1,1 1,0 0),(0 0,0 1,1 1,0 0))' with gdaltest.error_handler(): geom = ogr.CreateGeometryFromWkt(geom_wkt) - if geom is not None: - gdaltest.post_reason('fail') - print(geom) - return 'fail' - - return 'success' + assert geom is None ############################################################################### # Test OGRTriangle. Tests if the GEOS/SFCGAL methods are working -def ogr_geom_triangle_sfcgal(): +def test_ogr_geom_triangle_sfcgal(): if not ogrtest.have_sfcgal(): - return 'skip' + pytest.skip() g1 = ogr.CreateGeometryFromWkt('TRIANGLE ((0 0,100 0 100,0 100 100,0 0))') g2 = ogr.CreateGeometryFromWkt('TRIANGLE ((-1 -1,100 0 100,0 100 100,-1 -1))') - if not g2.Intersects(g1): - gdaltest.post_reason('fail') - return 'fail' + assert g2.Intersects(g1) g1 = ogr.CreateGeometryFromWkt('TRIANGLE ((0 0,1 0,0 1,0 0))') g2 = ogr.CreateGeometryFromWkt('TRIANGLE ((0 0,1 0,1 1,0 0))') g3 = g1.Intersection(g2) g4 = ogr.CreateGeometryFromWkt('TRIANGLE ((0.5 0.5 0,0 0 0,1 0 0,0.5 0.5 0))') - if not g4.Equals(g3): - gdaltest.post_reason('fail') - return 'fail' - - return 'success' + assert g4.Equals(g3) ############################################################################### # Test OGRCircularString -def ogr_geom_circularstring(): +def test_ogr_geom_circularstring(): in_wkt = 'CIRCULARSTRING (0 0,1 1,1 -1)' # Test export/import Wkt g1 = ogr.CreateGeometryFromWkt(in_wkt) - if g1.GetGeometryType() != ogr.wkbCircularString: - gdaltest.post_reason('fail') - return 'fail' + assert g1.GetGeometryType() == ogr.wkbCircularString out_wkt = g1.ExportToWkt() - if in_wkt != out_wkt: - gdaltest.post_reason('fail') - print(out_wkt) - return 'fail' + assert in_wkt == out_wkt if ogrtest.have_geos(): - if not g1.IsValid(): - gdaltest.post_reason('fail') - return 'fail' + assert g1.IsValid() # Test GetEnvelope() env = g1.GetEnvelope() expected_env = (0.0, 2.0, -1.0, 1.0) for i in range(4): - if abs(env[i] - expected_env[i]) > 1e-8: - gdaltest.post_reason('fail') - print(env) - return 'fail' + assert abs(env[i] - expected_env[i]) <= 1e-8 # Test Length() length = g1.Length() expected_length = 1.5 * math.pi - if abs(length - expected_length) > 1e-8: - gdaltest.post_reason('fail') - print(length) - return 'fail' + assert abs(length - expected_length) <= 1e-8 # Test Value() p = g1.Value(-1) expected_p = ogr.CreateGeometryFromWkt('POINT (0 0)') - if ogrtest.check_feature_geometry(p, expected_p) != 0: - gdaltest.post_reason('fail') - print(p) - return 'fail' + assert ogrtest.check_feature_geometry(p, expected_p) == 0 p = g1.Value(0) expected_p = ogr.CreateGeometryFromWkt('POINT (0 0)') - if ogrtest.check_feature_geometry(p, expected_p) != 0: - gdaltest.post_reason('fail') - print(p) - return 'fail' + assert ogrtest.check_feature_geometry(p, expected_p) == 0 p = g1.Value(length / 6.0) expected_p = ogr.CreateGeometryFromWkt('POINT (0.292893218813453 0.707106781186548)') if ogrtest.check_feature_geometry(p, expected_p) != 0: - gdaltest.post_reason('fail') print(p) p = g1.Value(length / 3.0) expected_p = ogr.CreateGeometryFromWkt('POINT (1 1)') - if ogrtest.check_feature_geometry(p, expected_p) != 0: - gdaltest.post_reason('fail') - print(p) - return 'fail' + assert ogrtest.check_feature_geometry(p, expected_p) == 0 p = g1.Value(length / 2.0) expected_p = ogr.CreateGeometryFromWkt('POINT (1.707106781186547 0.707106781186547)') - if ogrtest.check_feature_geometry(p, expected_p) != 0: - gdaltest.post_reason('fail') - print(p) - return 'fail' + assert ogrtest.check_feature_geometry(p, expected_p) == 0 p = g1.Value(2 * length / 3.0) expected_p = ogr.CreateGeometryFromWkt('POINT (2 0)') - if ogrtest.check_feature_geometry(p, expected_p) != 0: - gdaltest.post_reason('fail') - print(p) - return 'fail' + assert ogrtest.check_feature_geometry(p, expected_p) == 0 p = g1.Value(length) expected_p = ogr.CreateGeometryFromWkt('POINT (1 -1)') - if ogrtest.check_feature_geometry(p, expected_p) != 0: - gdaltest.post_reason('fail') - print(p) - return 'fail' + assert ogrtest.check_feature_geometry(p, expected_p) == 0 p = g1.Value(length + 1) expected_p = ogr.CreateGeometryFromWkt('POINT (1 -1)') - if ogrtest.check_feature_geometry(p, expected_p) != 0: - gdaltest.post_reason('fail') - print(p) - return 'fail' + assert ogrtest.check_feature_geometry(p, expected_p) == 0 # Test export/import Wkb g2 = ogr.CreateGeometryFromWkb(g1.ExportToWkb()) out_wkt = g2.ExportToWkt() - if in_wkt != out_wkt: - gdaltest.post_reason('fail') - print(out_wkt) - return 'fail' + assert in_wkt == out_wkt # With Z in_wkt = 'CIRCULARSTRING Z (0 0 10,1 1 20,2 0 30)' g1 = ogr.CreateGeometryFromWkt(in_wkt) - if g1.GetGeometryType() != ogr.wkbCircularStringZ: - gdaltest.post_reason('fail') - return 'fail' + assert g1.GetGeometryType() == ogr.wkbCircularStringZ out_wkt = g1.ExportToWkt() - if in_wkt != out_wkt: - gdaltest.post_reason('fail') - print(out_wkt) - return 'fail' + assert in_wkt == out_wkt wkb = g1.ExportToWkb() isowkb = g1.ExportToIsoWkb() - if wkb != isowkb: - gdaltest.post_reason('fail') - return 'fail' + assert wkb == isowkb g2 = ogr.CreateGeometryFromWkb(wkb) out_wkt = g2.ExportToWkt() - if in_wkt != out_wkt: - gdaltest.post_reason('fail') - print(out_wkt) - return 'fail' + assert in_wkt == out_wkt # Test stroking gdal.SetConfigOption('OGR_STROKE_CURVE', 'TRUE') @@ -1662,10 +1230,7 @@ def ogr_geom_circularstring(): gdal.SetConfigOption('OGR_ARC_STEPSIZE', None) expected_g = ogr.CreateGeometryFromWkt('LINESTRING (0 0,0.218168517531969 0.623489801858729,0.777479066043687 0.974927912181831,1.433883739117561 0.900968867902435,1.900968867902463 0.433883739117562,1.974927912181821 -0.222520933956316,1.623489801858719 -0.78183148246804,1 -1)') - if ogrtest.check_feature_geometry(g1, expected_g) != 0: - gdaltest.post_reason('fail') - print(g1) - return 'fail' + assert ogrtest.check_feature_geometry(g1, expected_g) == 0 in_wkt = 'CIRCULARSTRING (0 0,1 1,1 -1)' g1 = ogr.CreateGeometryFromWkt(in_wkt) @@ -1677,51 +1242,33 @@ def ogr_geom_circularstring(): gdal.SetConfigOption('OGR_STROKE_CURVE', 'FALSE') gdal.SetConfigOption('OGR_ARC_STEPSIZE', None) - if ogrtest.check_feature_geometry(g2, expected_g) != 0: - gdaltest.post_reason('fail') - print(g2) - return 'fail' + assert ogrtest.check_feature_geometry(g2, expected_g) == 0 # Test HasCurveGeometry - if not g1.HasCurveGeometry(): - gdaltest.post_reason('fail') - return 'fail' - if not g1.HasCurveGeometry(True): - gdaltest.post_reason('fail') - return 'fail' + assert g1.HasCurveGeometry() + assert g1.HasCurveGeometry(True) # Test GetLinearGeometry g2 = g1.GetLinearGeometry(45) - if ogrtest.check_feature_geometry(g2, expected_g) != 0: - gdaltest.post_reason('fail') - print(g2) - return 'fail' + assert ogrtest.check_feature_geometry(g2, expected_g) == 0 # Test ForceToLineString gdal.SetConfigOption('OGR_ARC_STEPSIZE', '45') g2 = ogr.ForceToLineString(g1) gdal.SetConfigOption('OGR_ARC_STEPSIZE', None) - if ogrtest.check_feature_geometry(g2, expected_g) != 0: - gdaltest.post_reason('fail') - print(g2) - return 'fail' + assert ogrtest.check_feature_geometry(g2, expected_g) == 0 # Test ForceToMultiLineString gdal.SetConfigOption('OGR_ARC_STEPSIZE', '45') expected_g2 = ogr.CreateGeometryFromWkt('MULTILINESTRING ((0 0,0.218168517531969 0.623489801858729,0.777479066043687 0.974927912181831,1.433883739117561 0.900968867902435,1.900968867902463 0.433883739117562,1.974927912181821 -0.222520933956316,1.623489801858719 -0.78183148246804,1 -1))') g2 = ogr.ForceToMultiLineString(g1) gdal.SetConfigOption('OGR_ARC_STEPSIZE', None) - if ogrtest.check_feature_geometry(g2, expected_g2) != 0: - gdaltest.post_reason('fail') - print(g2) - return 'fail' + assert ogrtest.check_feature_geometry(g2, expected_g2) == 0 # Test GEOS operations if ogrtest.have_geos(): g2 = g1.Intersection(g1) - if g2 is None: - gdaltest.post_reason('fail') - return 'fail' + assert g2 is not None # Test CIRCULARSTRING wrapped in a GEOMETRYCOLLECTION in_wkt = 'GEOMETRYCOLLECTION(CIRCULARSTRING (0 0,1 1,1 -1))' @@ -1730,27 +1277,19 @@ def ogr_geom_circularstring(): # Test GEOS operations if ogrtest.have_geos(): g2 = g1.Intersection(g1) - if g2 is None: - gdaltest.post_reason('fail') - return 'fail' + assert g2 is not None # Test ForceToLineString gdal.SetConfigOption('OGR_ARC_STEPSIZE', '45') g2 = ogr.ForceToLineString(g1) gdal.SetConfigOption('OGR_ARC_STEPSIZE', None) - if ogrtest.check_feature_geometry(g2, expected_g) != 0: - gdaltest.post_reason('fail') - print(g2) - return 'fail' + assert ogrtest.check_feature_geometry(g2, expected_g) == 0 # Test ForceToMultiLineString gdal.SetConfigOption('OGR_ARC_STEPSIZE', '45') g2 = ogr.ForceToMultiLineString(g1) gdal.SetConfigOption('OGR_ARC_STEPSIZE', None) - if ogrtest.check_feature_geometry(g2, expected_g2) != 0: - gdaltest.post_reason('fail') - print(g2) - return 'fail' + assert ogrtest.check_feature_geometry(g2, expected_g2) == 0 # Test stroking of full circle with 3 points. ISO draft # mentions that this should define a full circle, but there's an @@ -1761,50 +1300,32 @@ def ogr_geom_circularstring(): g1 = ogr.CreateGeometryFromWkt(in_wkt) expected_g = ogr.CreateGeometryFromWkt('LINESTRING (0 0,0.116977778440514 -0.321393804843282,0.413175911166547 -0.49240387650611,0.75 -0.433012701892224,0.969846310392967 -0.171010071662835,0.969846310392967 0.171010071662835,0.75 0.433012701892224,0.413175911166547 0.49240387650611,0.116977778440514 0.321393804843282,0 0)') g2 = g1.GetLinearGeometry(45) - if ogrtest.check_feature_geometry(g2, expected_g) != 0: - gdaltest.post_reason('fail') - print(g2) - return 'fail' + assert ogrtest.check_feature_geometry(g2, expected_g) == 0 length = g1.Length() expected_length = 2 * math.pi * 0.5 - if abs(length - expected_length) > 1e-8: - gdaltest.post_reason('fail') - print(length) - return 'fail' + assert abs(length - expected_length) <= 1e-8 # Test stroking of full circle (well defined) in_wkt = 'CIRCULARSTRING (0 0,0.5 0.5,1.0 0.0,0.5 -0.5,0.0 0.0)' g1 = ogr.CreateGeometryFromWkt(in_wkt) expected_g = ogr.CreateGeometryFromWkt('LINESTRING (0 0,0.049515566048791 0.216941869558781,0.188255099070638 0.390915741234018,0.388739533021848 0.48746395609092,0.611260466978166 0.48746395609092,0.811744900929369 0.390915741234018,0.950484433951232 0.216941869558781,1 0,0.950484433951232 -0.216941869558781,0.811744900929369 -0.390915741234018,0.611260466978166 -0.48746395609092,0.388739533021848 -0.48746395609092,0.188255099070638 -0.390915741234018,0.049515566048791 -0.216941869558781,0 0)') g2 = g1.GetLinearGeometry(45) - if ogrtest.check_feature_geometry(g2, expected_g) != 0: - gdaltest.post_reason('fail') - print(g2) - return 'fail' + assert ogrtest.check_feature_geometry(g2, expected_g) == 0 length = g1.Length() expected_length = 2 * math.pi * 0.5 - if abs(length - expected_length) > 1e-8: - gdaltest.post_reason('fail') - print(length) - return 'fail' + assert abs(length - expected_length) <= 1e-8 # Check segmentize g1.Segmentize(0.5) expected_g = ogr.CreateGeometryFromWkt('CIRCULARSTRING (0 0,0.146446609406726 0.353553390593274,0.5 0.5,0.853553390593274 0.353553390593274,1 0,0.853553390593274 -0.353553390593274,0.5 -0.5,0.146446609406726 -0.353553390593274,0 0)') - if ogrtest.check_feature_geometry(g1, expected_g) != 0: - gdaltest.post_reason('fail') - print(g1) - return 'fail' + assert ogrtest.check_feature_geometry(g1, expected_g) == 0 # Sanity check: the length must remain the same length = g1.Length() expected_length = 2 * math.pi * 0.5 - if abs(length - expected_length) > 1e-8: - gdaltest.post_reason('fail') - print(length) - return 'fail' + assert abs(length - expected_length) <= 1e-8 # Check segmentize symmetry : do exact binary comparison in_wkt = 'CIRCULARSTRING (0 0,1.2 1,2 0)' @@ -1815,127 +1336,80 @@ def ogr_geom_circularstring(): g2.Segmentize(0.25) for i in range(g1.GetPointCount()): if g1.GetPoint(i) != g2.GetPoint(g1.GetPointCount() - 1 - i): - gdaltest.post_reason('fail') - print(i) print('%.18g' % (g1.GetPoint(i)[0] - g2.GetPoint(g1.GetPointCount() - 1 - i)[0])) - print('%.18g' % (g1.GetPoint(i)[1] - g2.GetPoint(g1.GetPointCount() - 1 - i)[1])) - print(g1) - print(g2) - return 'fail' + pytest.fail('%.18g' % (g1.GetPoint(i)[1] - g2.GetPoint(g1.GetPointCount() - 1 - i)[1])) # Test stroking of full circle with Z in_wkt = 'CIRCULARSTRING (0 0 1,1 0 2,0 0 1)' g1 = ogr.CreateGeometryFromWkt(in_wkt) expected_g = ogr.CreateGeometryFromWkt('LINESTRING (0 0 1,0.116977778440514 -0.321393804843282 1,0.413175911166547 -0.49240387650611 1,0.75 -0.433012701892224 1,0.969846310392967 -0.171010071662835 1,0.969846310392967 0.171010071662835 1,0.75 0.433012701892224 1,0.413175911166547 0.49240387650611 1,0.116977778440514 0.321393804843282 1,0 0 1)') g2 = g1.GetLinearGeometry(45) - if ogrtest.check_feature_geometry(g2, expected_g) != 0: - gdaltest.post_reason('fail') - print(g2) - return 'fail' + assert ogrtest.check_feature_geometry(g2, expected_g) == 0 # Check segmentize g1.Segmentize(0.5) expected_g = ogr.CreateGeometryFromWkt('CIRCULARSTRING Z (0 0 1,0.146446609406726 -0.353553390593274 1.25,0.5 -0.5 1.5,0.853553390593274 -0.353553390593274 1.75,1 0 2,0.853553390593274 0.353553390593274 1.75,0.5 0.5 1.5,0.146446609406727 0.353553390593274 1.25,0 0 1)') - if ogrtest.check_feature_geometry(g1, expected_g) != 0: - gdaltest.post_reason('fail') - print(g1) - return 'fail' + assert ogrtest.check_feature_geometry(g1, expected_g) == 0 # Same as above but reverse order in_wkt = 'CIRCULARSTRING (0 0,0.5 -0.5,1.0 0.0,0.5 0.5,0.0 0.0)' g1 = ogr.CreateGeometryFromWkt(in_wkt) expected_g = ogr.CreateGeometryFromWkt('LINESTRING (0 0,0.049515566048791 -0.216941869558781,0.188255099070638 -0.390915741234018,0.388739533021848 -0.48746395609092,0.611260466978166 -0.48746395609092,0.811744900929369 -0.390915741234018,0.950484433951232 -0.216941869558781,1 0,0.950484433951232 0.216941869558781,0.811744900929369 0.390915741234018,0.611260466978166 0.48746395609092,0.388739533021848 0.48746395609092,0.188255099070638 0.390915741234018,0.049515566048791 0.216941869558781,0 0)') g2 = g1.GetLinearGeometry(45) - if ogrtest.check_feature_geometry(g2, expected_g) != 0: - gdaltest.post_reason('fail') - print(g2) - return 'fail' + assert ogrtest.check_feature_geometry(g2, expected_g) == 0 length = g1.Length() expected_length = 2 * math.pi * 0.5 - if abs(length - expected_length) > 1e-8: - gdaltest.post_reason('fail') - print(length) - return 'fail' + assert abs(length - expected_length) <= 1e-8 # Test stroking of a circular string with 3 colinear points in_wkt = 'CIRCULARSTRING (0 0,1 1,2 2)' g1 = ogr.CreateGeometryFromWkt(in_wkt) expected_g = ogr.CreateGeometryFromWkt('LINESTRING (0 0,1 1,2 2)') g2 = g1.GetLinearGeometry(45) - if ogrtest.check_feature_geometry(g2, expected_g) != 0: - gdaltest.post_reason('fail') - print(g2) - return 'fail' + assert ogrtest.check_feature_geometry(g2, expected_g) == 0 length = g1.Length() expected_length = 2 * math.sqrt(2) - if abs(length - expected_length) > 1e-8: - gdaltest.post_reason('fail') - print(length) - return 'fail' + assert abs(length - expected_length) <= 1e-8 # Test Value() p = g1.Value(length / 4.0) expected_p = ogr.CreateGeometryFromWkt('POINT (0.5 0.5)') - if ogrtest.check_feature_geometry(p, expected_p) != 0: - gdaltest.post_reason('fail') - print(p) - return 'fail' + assert ogrtest.check_feature_geometry(p, expected_p) == 0 p = g1.Value(3.0 * length / 4.0) expected_p = ogr.CreateGeometryFromWkt('POINT (1.5 1.5)') - if ogrtest.check_feature_geometry(p, expected_p) != 0: - gdaltest.post_reason('fail') - print(p) - return 'fail' + assert ogrtest.check_feature_geometry(p, expected_p) == 0 # Check segmentize g1.Segmentize(0.5) expected_g = ogr.CreateGeometryFromWkt('CIRCULARSTRING (0 0,0.166666666666667 0.166666666666667,0.333333333333333 0.333333333333333,0.5 0.5,0.666666666666667 0.666666666666667,0.833333333333333 0.833333333333333,1 1,1.166666666666667 1.166666666666667,1.333333333333333 1.333333333333333,1.5 1.5,1.666666666666667 1.666666666666667,1.833333333333333 1.833333333333333,2 2)') - if ogrtest.check_feature_geometry(g1, expected_g) != 0: - gdaltest.post_reason('fail') - print(g1) - return 'fail' + assert ogrtest.check_feature_geometry(g1, expected_g) == 0 # Sanity check: the length must remain the same length = g1.Length() expected_length = 2 * math.sqrt(2) - if abs(length - expected_length) > 1e-8: - gdaltest.post_reason('fail') - print(length) - return 'fail' + assert abs(length - expected_length) <= 1e-8 # Same with Z in_wkt = 'CIRCULARSTRING (0 0 1,1 1 2,2 2 1)' g1 = ogr.CreateGeometryFromWkt(in_wkt) expected_g = ogr.CreateGeometryFromWkt('LINESTRING (0 0 1,1 1 2,2 2 1)') g2 = g1.GetLinearGeometry(45) - if ogrtest.check_feature_geometry(g2, expected_g) != 0: - gdaltest.post_reason('fail') - print(g2) - return 'fail' + assert ogrtest.check_feature_geometry(g2, expected_g) == 0 # Check segmentize g1.Segmentize(0.5) expected_g = ogr.CreateGeometryFromWkt('CIRCULARSTRING Z (0 0 1,0.166666666666667 0.166666666666667 1.166666666666667,0.333333333333333 0.333333333333333 1.333333333333333,0.5 0.5 1.5,0.666666666666667 0.666666666666667 1.666666666666667,0.833333333333333 0.833333333333333 1.833333333333333,1 1 2,1.166666666666667 1.166666666666667 1.833333333333333,1.333333333333333 1.333333333333333 1.666666666666667,1.5 1.5 1.5,1.666666666666667 1.666666666666667 1.333333333333333,1.833333333333333 1.833333333333333 1.166666666666667,2 2 1)') - if ogrtest.check_feature_geometry(g1, expected_g) != 0: - gdaltest.post_reason('fail') - print(g1) - return 'fail' + assert ogrtest.check_feature_geometry(g1, expected_g) == 0 # Test Value() p = g1.Value(length / 4.0) expected_p = ogr.CreateGeometryFromWkt('POINT (0.5 0.5 1.5)') - if ogrtest.check_feature_geometry(p, expected_p) != 0: - gdaltest.post_reason('fail') - print(p) - return 'fail' + assert ogrtest.check_feature_geometry(p, expected_p) == 0 p = g1.Value(3.0 * length / 4.0) expected_p = ogr.CreateGeometryFromWkt('POINT (1.5 1.5 1.5)') - if ogrtest.check_feature_geometry(p, expected_p) != 0: - gdaltest.post_reason('fail') - print(p) - return 'fail' + assert ogrtest.check_feature_geometry(p, expected_p) == 0 in_wkt = 'CIRCULARSTRING (0 0,1 1,1 -1)' # Test GetEnvelope() in various cases @@ -1955,10 +1429,7 @@ def ogr_geom_circularstring(): env = g1.GetEnvelope() expected_env = (cx + r * math.cos(a0), cx + r * math.cos(a2), cy + r * math.sin(a2), cy + r * math.sin(a0)) for i in range(4): - if abs(env[i] - expected_env[i]) > 1e-8: - gdaltest.post_reason('fail') - print(env) - return 'fail' + assert abs(env[i] - expected_env[i]) <= 1e-8 # From quadrant 0 to quadrant -1 a0 = math.pi / 3 @@ -1972,10 +1443,7 @@ def ogr_geom_circularstring(): env = g1.GetEnvelope() expected_env = (cx + r * math.cos(a0), cx + r, cy + r * math.sin(a2), cy + r * math.sin(a0)) for i in range(4): - if abs(env[i] - expected_env[i]) > 1e-8: - gdaltest.post_reason('fail') - print(env) - return 'fail' + assert abs(env[i] - expected_env[i]) <= 1e-8 # From quadrant 0 to quadrant 3 a0 = math.pi / 3 @@ -1989,10 +1457,7 @@ def ogr_geom_circularstring(): env = g1.GetEnvelope() expected_env = (cx - r, cx + r * math.cos(a2), cy - r, cy + r) for i in range(4): - if abs(env[i] - expected_env[i]) > 1e-8: - gdaltest.post_reason('fail') - print(env) - return 'fail' + assert abs(env[i] - expected_env[i]) <= 1e-8 # From quadrant 0 to quadrant 4 a0 = math.pi / 3 @@ -2006,10 +1471,7 @@ def ogr_geom_circularstring(): env = g1.GetEnvelope() expected_env = (cx - r, cx + r, cy - r, cy + r) for i in range(4): - if abs(env[i] - expected_env[i]) > 1e-8: - gdaltest.post_reason('fail') - print(env) - return 'fail' + assert abs(env[i] - expected_env[i]) <= 1e-8 # Full circle a0 = math.pi / 3 @@ -2023,229 +1485,134 @@ def ogr_geom_circularstring(): env = g1.GetEnvelope() expected_env = (cx - r, cx + r, cy - r, cy + r) for i in range(4): - if abs(env[i] - expected_env[i]) > 1e-8: - gdaltest.post_reason('fail') - print(env) - return 'fail' + assert abs(env[i] - expected_env[i]) <= 1e-8 # Error case : not enough points in_wkt = 'CIRCULARSTRING (0 0)' gdal.PushErrorHandler('CPLQuietErrorHandler') g = ogr.CreateGeometryFromWkt(in_wkt) gdal.PopErrorHandler() - if g is not None: - gdaltest.post_reason('fail') - return 'fail' + assert g is None # EMPTY for in_wkt in ['CIRCULARSTRING EMPTY', 'CIRCULARSTRING Z EMPTY']: g1 = ogr.CreateGeometryFromWkt(in_wkt) out_wkt = g1.ExportToWkt() - if in_wkt != out_wkt: - gdaltest.post_reason('fail') - print(in_wkt) - print(out_wkt) - return 'fail' - if g1.Length() != 0.0: - gdaltest.post_reason('fail') - print(in_wkt) - return 'fail' + assert in_wkt == out_wkt + assert g1.Length() == 0.0, in_wkt g2 = ogr.CreateGeometryFromWkb(g1.ExportToWkb()) out_wkt = g2.ExportToWkt() - if in_wkt != out_wkt: - gdaltest.post_reason('fail') - print(in_wkt) - print(out_wkt) - return 'fail' - - return 'success' + assert in_wkt == out_wkt + ############################################################################### # Test OGRCompoundCurve -def ogr_geom_compoundcurve(): +def test_ogr_geom_compoundcurve(): in_wkt = 'COMPOUNDCURVE (CIRCULARSTRING (0 0,1 1,1 -1))' g1 = ogr.CreateGeometryFromWkt(in_wkt) - if g1.GetGeometryType() != ogr.wkbCompoundCurve: - gdaltest.post_reason('fail') - return 'fail' + assert g1.GetGeometryType() == ogr.wkbCompoundCurve out_wkt = g1.ExportToWkt() - if in_wkt != out_wkt: - gdaltest.post_reason('fail') - print(out_wkt) - return 'fail' - - if g1.GetGeometryCount() != 1: - gdaltest.post_reason('fail') - return 'fail' - if g1.GetGeometryRef(0).ExportToWkt() != 'CIRCULARSTRING (0 0,1 1,1 -1)': - gdaltest.post_reason('fail') - return 'fail' + assert in_wkt == out_wkt + + assert g1.GetGeometryCount() == 1 + assert g1.GetGeometryRef(0).ExportToWkt() == 'CIRCULARSTRING (0 0,1 1,1 -1)' env = g1.GetEnvelope() expected_env = (0.0, 2.0, -1.0, 1.0) for i in range(4): - if abs(env[i] - expected_env[i]) > 1e-8: - gdaltest.post_reason('fail') - print(env) - return 'fail' + assert abs(env[i] - expected_env[i]) <= 1e-8 length = g1.Length() expected_length = 1.5 * math.pi - if abs(length - expected_length) > 1e-8: - gdaltest.post_reason('fail') - print(length) - return 'fail' + assert abs(length - expected_length) <= 1e-8 g2 = ogr.CreateGeometryFromWkb(g1.ExportToWkb()) out_wkt = g2.ExportToWkt() - if in_wkt != out_wkt: - gdaltest.post_reason('fail') - print(out_wkt) - return 'fail' + assert in_wkt == out_wkt g1 = ogr.CreateGeometryFromWkt(in_wkt) - if not g1.HasCurveGeometry(): - gdaltest.post_reason('fail') - return 'fail' - if not g1.HasCurveGeometry(True): - gdaltest.post_reason('fail') - return 'fail' + assert g1.HasCurveGeometry() + assert g1.HasCurveGeometry(True) # CreateGeometryFromWkt of LINESTRING in_wkt = 'COMPOUNDCURVE ((0 0,0 10))' g1 = ogr.CreateGeometryFromWkt(in_wkt) - if not g1.HasCurveGeometry(): - gdaltest.post_reason('fail') - return 'fail' - if g1.HasCurveGeometry(True): - gdaltest.post_reason('fail') - return 'fail' + assert g1.HasCurveGeometry() + assert not g1.HasCurveGeometry(True) # With Z in_wkt = 'COMPOUNDCURVE Z (CIRCULARSTRING Z (0 0 10,1 1 20,2 0 30),(2 0 30,0 0 10))' g1 = ogr.CreateGeometryFromWkt(in_wkt) - if g1.GetGeometryType() != ogr.wkbCompoundCurveZ: - gdaltest.post_reason('fail') - return 'fail' + assert g1.GetGeometryType() == ogr.wkbCompoundCurveZ out_wkt = g1.ExportToWkt() - if in_wkt != out_wkt: - gdaltest.post_reason('fail') - print(out_wkt) - return 'fail' + assert in_wkt == out_wkt env = g1.GetEnvelope() expected_env = (0.0, 2.0, 0.0, 1.0) for i in range(4): - if abs(env[i] - expected_env[i]) > 1e-8: - gdaltest.post_reason('fail') - print(env) - return 'fail' + assert abs(env[i] - expected_env[i]) <= 1e-8 env = g1.GetEnvelope3D() expected_env = (0.0, 2.0, 0.0, 1.0, 10, 30) for i in range(6): - if abs(env[i] - expected_env[i]) > 1e-8: - gdaltest.post_reason('fail') - print(env) - return 'fail' + assert abs(env[i] - expected_env[i]) <= 1e-8 # Test Value() p = g1.Value(-1e-3) expected_p = ogr.CreateGeometryFromWkt('POINT (0 0 10)') - if ogrtest.check_feature_geometry(p, expected_p) != 0: - gdaltest.post_reason('fail') - print(p) - return 'fail' + assert ogrtest.check_feature_geometry(p, expected_p) == 0 p = g1.Value(math.pi / 2.0) expected_p = ogr.CreateGeometryFromWkt('POINT (1 1 20)') - if ogrtest.check_feature_geometry(p, expected_p) != 0: - gdaltest.post_reason('fail') - print(p) - return 'fail' + assert ogrtest.check_feature_geometry(p, expected_p) == 0 p = g1.Value(math.pi) expected_p = ogr.CreateGeometryFromWkt('POINT (2 0 30)') - if ogrtest.check_feature_geometry(p, expected_p) != 0: - gdaltest.post_reason('fail') - print(p) - return 'fail' + assert ogrtest.check_feature_geometry(p, expected_p) == 0 p = g1.Value(math.pi + 1) expected_p = ogr.CreateGeometryFromWkt('POINT (1 0 20)') - if ogrtest.check_feature_geometry(p, expected_p) != 0: - gdaltest.post_reason('fail') - print(p) - return 'fail' + assert ogrtest.check_feature_geometry(p, expected_p) == 0 p = g1.Value(math.pi + 2 + 1e-3) expected_p = ogr.CreateGeometryFromWkt('POINT (0 0 10)') - if ogrtest.check_feature_geometry(p, expected_p) != 0: - gdaltest.post_reason('fail') - print(p) - return 'fail' + assert ogrtest.check_feature_geometry(p, expected_p) == 0 wkb = g1.ExportToWkb() isowkb = g1.ExportToIsoWkb() - if wkb != isowkb: - gdaltest.post_reason('fail') - return 'fail' + assert wkb == isowkb g2 = ogr.CreateGeometryFromWkb(wkb) out_wkt = g2.ExportToWkt() - if in_wkt != out_wkt: - gdaltest.post_reason('fail') - print(out_wkt) - return 'fail' + assert in_wkt == out_wkt # Several parts in_wkt = 'COMPOUNDCURVE (CIRCULARSTRING (0 0,1 1,1 -1),(1 -1,0 0))' g1 = ogr.CreateGeometryFromWkt(in_wkt) - if g1.GetGeometryType() != ogr.wkbCompoundCurve: - gdaltest.post_reason('fail') - return 'fail' + assert g1.GetGeometryType() == ogr.wkbCompoundCurve out_wkt = g1.ExportToWkt() - if in_wkt != out_wkt: - gdaltest.post_reason('fail') - print(out_wkt) - return 'fail' + assert in_wkt == out_wkt - if not g1.Equals(g1): - gdaltest.post_reason('fail') - return 'fail' + assert g1.Equals(g1) - if not g1.Equals(g1.Clone()): - gdaltest.post_reason('fail') - return 'fail' + assert g1.Equals(g1.Clone()) - if g1.Equals(ogr.CreateGeometryFromWkt('POINT(0 0)')): - gdaltest.post_reason('fail') - return 'fail' + assert not g1.Equals(ogr.CreateGeometryFromWkt('POINT(0 0)')) - if g1.Equals(ogr.CreateGeometryFromWkt('COMPOUNDCURVE (CIRCULARSTRING (0 0,1 1,1 -1))')): - gdaltest.post_reason('fail') - return 'fail' + assert not g1.Equals(ogr.CreateGeometryFromWkt('COMPOUNDCURVE (CIRCULARSTRING (0 0,1 1,1 -1))')) - if g1.Equals(ogr.CreateGeometryFromWkt('COMPOUNDCURVE (CIRCULARSTRING (0 0,1 1,1 -1),(1 -1,0 1))')): - gdaltest.post_reason('fail') - return 'fail' + assert not g1.Equals(ogr.CreateGeometryFromWkt('COMPOUNDCURVE (CIRCULARSTRING (0 0,1 1,1 -1),(1 -1,0 1))')) length = g1.Length() expected_length = 1.5 * math.pi + math.sqrt(2) - if abs(length - expected_length) > 1e-8: - gdaltest.post_reason('fail') - print(length) - return 'fail' + assert abs(length - expected_length) <= 1e-8 g2 = ogr.CreateGeometryFromWkb(g1.ExportToWkb()) out_wkt = g2.ExportToWkt() - if in_wkt != out_wkt: - gdaltest.post_reason('fail') - print(out_wkt) - return 'fail' + assert in_wkt == out_wkt # Test stroking gdal.SetConfigOption('OGR_STROKE_CURVE', 'TRUE') @@ -2256,10 +1623,7 @@ def ogr_geom_compoundcurve(): gdal.SetConfigOption('OGR_ARC_STEPSIZE', None) expected_g = ogr.CreateGeometryFromWkt('LINESTRING (0 0,0.218168517531969 0.623489801858729,0.777479066043687 0.974927912181831,1.433883739117561 0.900968867902435,1.900968867902463 0.433883739117562,1.974927912181821 -0.222520933956316,1.623489801858719 -0.78183148246804,1 -1)') - if ogrtest.check_feature_geometry(g1, expected_g) != 0: - gdaltest.post_reason('fail') - print(g1) - return 'fail' + assert ogrtest.check_feature_geometry(g1, expected_g) == 0 in_wkt = 'COMPOUNDCURVE (CIRCULARSTRING (0 0,1 1,1 -1))' g1 = ogr.CreateGeometryFromWkt(in_wkt) @@ -2272,135 +1636,93 @@ def ogr_geom_compoundcurve(): gdal.SetConfigOption('OGR_ARC_STEPSIZE', None) expected_g = ogr.CreateGeometryFromWkt('LINESTRING (0 0,0.218168517531969 0.623489801858729,0.777479066043687 0.974927912181831,1.433883739117561 0.900968867902435,1.900968867902463 0.433883739117562,1.974927912181821 -0.222520933956316,1.623489801858719 -0.78183148246804,1 -1)') - if ogrtest.check_feature_geometry(g2, expected_g) != 0: - gdaltest.post_reason('fail') - print(g2) - return 'fail' + assert ogrtest.check_feature_geometry(g2, expected_g) == 0 g2 = g1.GetLinearGeometry(45) - if ogrtest.check_feature_geometry(g2, expected_g) != 0: - gdaltest.post_reason('fail') - print(g2) - return 'fail' + assert ogrtest.check_feature_geometry(g2, expected_g) == 0 - if not g1.HasCurveGeometry(): - gdaltest.post_reason('fail') - return 'fail' + assert g1.HasCurveGeometry() - if not g1.HasCurveGeometry(True): - gdaltest.post_reason('fail') - return 'fail' + assert g1.HasCurveGeometry(True) g2 = g1.GetLinearGeometry(45) - if ogrtest.check_feature_geometry(g2, expected_g) != 0: - gdaltest.post_reason('fail') - print(g2) - return 'fail' + assert ogrtest.check_feature_geometry(g2, expected_g) == 0 gdal.SetConfigOption('OGR_ARC_STEPSIZE', '45') g2 = ogr.ForceToLineString(g1) gdal.SetConfigOption('OGR_ARC_STEPSIZE', None) - if ogrtest.check_feature_geometry(g2, expected_g) != 0: - gdaltest.post_reason('fail') - print(g2) - return 'fail' + assert ogrtest.check_feature_geometry(g2, expected_g) == 0 gdal.SetConfigOption('OGR_ARC_STEPSIZE', '45') expected_g = ogr.CreateGeometryFromWkt('MULTILINESTRING ((0 0,0.218168517531969 0.623489801858729,0.777479066043687 0.974927912181831,1.433883739117561 0.900968867902435,1.900968867902463 0.433883739117562,1.974927912181821 -0.222520933956316,1.623489801858719 -0.78183148246804,1 -1))') g2 = ogr.ForceToMultiLineString(g1) gdal.SetConfigOption('OGR_ARC_STEPSIZE', None) - if ogrtest.check_feature_geometry(g2, expected_g) != 0: - gdaltest.post_reason('fail') - print(g2) - return 'fail' + assert ogrtest.check_feature_geometry(g2, expected_g) == 0 # Check segmentize g1.Segmentize(0.5) expected_g = ogr.CreateGeometryFromWkt('COMPOUNDCURVE (CIRCULARSTRING (0 0,0.076120467488713 0.38268343236509,0.292893218813453 0.707106781186548,0.61731656763491 0.923879532511287,1 1,1.38268343236509 0.923879532511287,1.707106781186547 0.707106781186547,1.923879532511287 0.38268343236509,2 0,1.923879532511287 -0.38268343236509,1.707106781186547 -0.707106781186547,1.38268343236509 -0.923879532511287,1 -1))') - if ogrtest.check_feature_geometry(g1, expected_g) != 0: - gdaltest.post_reason('fail') - print(g1) - return 'fail' + assert ogrtest.check_feature_geometry(g1, expected_g) == 0 # Error case : not enough points in_wkt = 'COMPOUNDCURVE ((0 0))' gdal.PushErrorHandler('CPLQuietErrorHandler') g = ogr.CreateGeometryFromWkt(in_wkt) gdal.PopErrorHandler() - if g is not None: - gdaltest.post_reason('fail') - return 'fail' + assert g is None # Error case : invalid curve in_wkt = 'COMPOUNDCURVE (COMPOUNDCURVE EMPTY)' gdal.PushErrorHandler('CPLQuietErrorHandler') g = ogr.CreateGeometryFromWkt(in_wkt) gdal.PopErrorHandler() - if g is not None: - gdaltest.post_reason('fail') - return 'fail' + assert g is None # Error case : non contiguous curves in_wkt = 'COMPOUNDCURVE ((0 0,1 1),(2 2,3 3))' gdal.PushErrorHandler('CPLQuietErrorHandler') g = ogr.CreateGeometryFromWkt(in_wkt) gdal.PopErrorHandler() - if g is not None: - gdaltest.post_reason('fail') - return 'fail' + assert g is None # Error case : non contiguous curves in_wkt = 'COMPOUNDCURVE (EMPTY,(2 2,3 3))' gdal.PushErrorHandler('CPLQuietErrorHandler') g = ogr.CreateGeometryFromWkt(in_wkt) gdal.PopErrorHandler() - if g is not None: - gdaltest.post_reason('fail') - return 'fail' + assert g is None # Error case : non contiguous curves in_wkt = 'COMPOUNDCURVE ((2 2,3 3), EMPTY)' gdal.PushErrorHandler('CPLQuietErrorHandler') g = ogr.CreateGeometryFromWkt(in_wkt) gdal.PopErrorHandler() - if g is not None: - gdaltest.post_reason('fail') - return 'fail' + assert g is None g = ogr.Geometry(ogr.wkbCompoundCurve) g.AddGeometry(ogr.CreateGeometryFromWkt('LINESTRING(0 0,1 1)')) - if g.ExportToWkt() != 'COMPOUNDCURVE ((0 0,1 1))': - gdaltest.post_reason('fail') - return 'fail' + assert g.ExportToWkt() == 'COMPOUNDCURVE ((0 0,1 1))' gdal.PushErrorHandler('CPLQuietErrorHandler') g.AddGeometry(ogr.CreateGeometryFromWkt('LINESTRING(0 0,1 1)')) gdal.PopErrorHandler() - if g.ExportToWkt() != 'COMPOUNDCURVE ((0 0,1 1),(1 1,0 0))': - gdaltest.post_reason('fail') - return 'fail' + assert g.ExportToWkt() == 'COMPOUNDCURVE ((0 0,1 1),(1 1,0 0))' g = ogr.Geometry(ogr.wkbCompoundCurve) g.AddGeometryDirectly(ogr.CreateGeometryFromWkt('LINESTRING(0 0,1 1)')) - if g.ExportToWkt() != 'COMPOUNDCURVE ((0 0,1 1))': - gdaltest.post_reason('fail') - return 'fail' + assert g.ExportToWkt() == 'COMPOUNDCURVE ((0 0,1 1))' gdal.PushErrorHandler('CPLQuietErrorHandler') g.AddGeometryDirectly(ogr.CreateGeometryFromWkt('LINESTRING(0 0,1 1)')) gdal.PopErrorHandler() - if g.ExportToWkt() != 'COMPOUNDCURVE ((0 0,1 1),(1 1,0 0))': - gdaltest.post_reason('fail') - return 'fail' + assert g.ExportToWkt() == 'COMPOUNDCURVE ((0 0,1 1),(1 1,0 0))' # Cannot add compoundcurve in compoundcurve g = ogr.Geometry(ogr.wkbCompoundCurve) gdal.PushErrorHandler('CPLQuietErrorHandler') g.AddGeometryDirectly(ogr.CreateGeometryFromWkt('COMPOUNDCURVE((1 1,2 2))')) gdal.PopErrorHandler() - if g.ExportToWkt() != 'COMPOUNDCURVE EMPTY': - gdaltest.post_reason('fail') - return 'fail' + assert g.ExportToWkt() == 'COMPOUNDCURVE EMPTY' # Check that discretization is not sensitive to winding order g1 = ogr.CreateGeometryFromWkt('COMPOUNDCURVE((-1 0,0 1),CIRCULARSTRING (0 1,0.25 0,0.1 -0.5),(0.1 -0.5,-1 0))') @@ -2413,13 +1735,8 @@ def ogr_geom_compoundcurve(): # The curves must be exactly the same, despite our stealth mode if g2.GetX(i) != g3.GetX(p_count - 1 - i) or \ g2.GetY(i) != g3.GetY(p_count - 1 - i): - gdaltest.post_reason('fail') - print(g2) - print(g3) - print(i) print(abs(g2.GetX(i) - g3.GetX(p_count - 1 - i))) - print(abs(g2.GetY(i) - g3.GetY(p_count - 1 - i))) - return 'fail' + pytest.fail(abs(g2.GetY(i) - g3.GetY(p_count - 1 - i))) # Test Transform sr = osr.SpatialReference() @@ -2440,115 +1757,68 @@ def ogr_geom_compoundcurve(): gdal.PushErrorHandler('CPLQuietErrorHandler') g = ogr.CreateGeometryFromWkb(wkb) gdal.PopErrorHandler() - if g is not None: - gdaltest.post_reason('fail') - print(wkb) - return 'fail' + assert g is None, wkb # EMPTY for in_wkt in ['COMPOUNDCURVE EMPTY', 'COMPOUNDCURVE Z EMPTY']: g1 = ogr.CreateGeometryFromWkt(in_wkt) out_wkt = g1.ExportToWkt() - if in_wkt != out_wkt: - gdaltest.post_reason('fail') - print(in_wkt) - print(out_wkt) - return 'fail' - if g1.Length() != 0.0: - gdaltest.post_reason('fail') - print(in_wkt) - return 'fail' + assert in_wkt == out_wkt + assert g1.Length() == 0.0, in_wkt g2 = ogr.CreateGeometryFromWkb(g1.ExportToWkb()) out_wkt = g2.ExportToWkt() - if in_wkt != out_wkt: - gdaltest.post_reason('fail') - print(in_wkt) - print(out_wkt) - return 'fail' - - return 'success' + assert in_wkt == out_wkt + ############################################################################### # Test OGRCurvePolygon -def ogr_geom_curvepolygon(): +def test_ogr_geom_curvepolygon(): in_wkt = 'CURVEPOLYGON (CIRCULARSTRING (0 0,1 0,0 0))' g1 = ogr.CreateGeometryFromWkt(in_wkt) - if g1.GetGeometryType() != ogr.wkbCurvePolygon: - gdaltest.post_reason('fail') - return 'fail' + assert g1.GetGeometryType() == ogr.wkbCurvePolygon out_wkt = g1.ExportToWkt() - if in_wkt != out_wkt: - gdaltest.post_reason('fail') - print(out_wkt) - return 'fail' + assert in_wkt == out_wkt if ogrtest.have_geos(): p1 = g1.PointOnSurface() - if (p1.GetX() - 0.5) * (p1.GetX() - 0.5) + p1.GetY() * p1.GetY() > 0.5 * 0.5: - gdaltest.post_reason('fail') - print(p1) - return 'fail' + assert (p1.GetX() - 0.5) * (p1.GetX() - 0.5) + p1.GetY() * p1.GetY() <= 0.5 * 0.5 env = g1.GetEnvelope() expected_env = (0.0, 1.0, -0.5, 0.5) for i in range(4): - if abs(env[i] - expected_env[i]) > 1e-8: - gdaltest.post_reason('fail') - print(env) - return 'fail' + assert abs(env[i] - expected_env[i]) <= 1e-8 area = g1.Area() expected_area = math.pi * 0.5 * 0.5 - if abs(area - expected_area) > 1e-8: - gdaltest.post_reason('fail') - print(area) - print(expected_area) - return 'fail' + assert abs(area - expected_area) <= 1e-8 g2 = ogr.CreateGeometryFromWkb(g1.ExportToWkb()) out_wkt = g2.ExportToWkt() - if in_wkt != out_wkt: - gdaltest.post_reason('fail') - print(out_wkt) - return 'fail' + assert in_wkt == out_wkt # CURVEPOLYGON of LINESTRING in_wkt = 'CURVEPOLYGON ((0 0,0 10,10 10,10 0,0 0))' g1 = ogr.CreateGeometryFromWkt(in_wkt) - if not g1.HasCurveGeometry(): - gdaltest.post_reason('fail') - return 'fail' - if g1.HasCurveGeometry(True): - gdaltest.post_reason('fail') - return 'fail' + assert g1.HasCurveGeometry() + assert not g1.HasCurveGeometry(True) # With Z in_wkt = 'CURVEPOLYGON Z (CIRCULARSTRING Z (0 0 10,1 0 10,0 0 10))' g1 = ogr.CreateGeometryFromWkt(in_wkt) - if g1.GetGeometryType() != ogr.wkbCurvePolygonZ: - gdaltest.post_reason('fail') - return 'fail' + assert g1.GetGeometryType() == ogr.wkbCurvePolygonZ out_wkt = g1.ExportToWkt() - if in_wkt != out_wkt: - gdaltest.post_reason('fail') - print(out_wkt) - return 'fail' + assert in_wkt == out_wkt wkb = g1.ExportToWkb() isowkb = g1.ExportToIsoWkb() - if wkb != isowkb: - gdaltest.post_reason('fail') - return 'fail' + assert wkb == isowkb g2 = ogr.CreateGeometryFromWkb(wkb) out_wkt = g2.ExportToWkt() - if in_wkt != out_wkt: - gdaltest.post_reason('fail') - print(out_wkt) - return 'fail' + assert in_wkt == out_wkt # Test stroking gdal.SetConfigOption('OGR_STROKE_CURVE', 'TRUE') @@ -2559,10 +1829,7 @@ def ogr_geom_curvepolygon(): gdal.SetConfigOption('OGR_ARC_STEPSIZE', None) expected_g = ogr.CreateGeometryFromWkt('POLYGON ((0 0,0.116977778440514 -0.321393804843282,0.413175911166547 -0.49240387650611,0.75 -0.433012701892224,0.969846310392967 -0.171010071662835,0.969846310392967 0.171010071662835,0.75 0.433012701892224,0.413175911166547 0.49240387650611,0.116977778440514 0.321393804843282,0 0))') - if ogrtest.check_feature_geometry(g1, expected_g) != 0: - gdaltest.post_reason('fail') - print(g1) - return 'fail' + assert ogrtest.check_feature_geometry(g1, expected_g) == 0 in_wkt = 'CURVEPOLYGON (CIRCULARSTRING (0 0,1 0,0 0))' g1 = ogr.CreateGeometryFromWkt(in_wkt) @@ -2574,170 +1841,113 @@ def ogr_geom_curvepolygon(): gdal.SetConfigOption('OGR_STROKE_CURVE', 'FALSE') gdal.SetConfigOption('OGR_ARC_STEPSIZE', None) - if ogrtest.check_feature_geometry(g2, expected_g) != 0: - gdaltest.post_reason('fail') - print(g2) - return 'fail' + assert ogrtest.check_feature_geometry(g2, expected_g) == 0 # Test HasCurveGeometry - if not g1.HasCurveGeometry(): - gdaltest.post_reason('fail') - return 'fail' - if not g1.HasCurveGeometry(True): - gdaltest.post_reason('fail') - return 'fail' + assert g1.HasCurveGeometry() + assert g1.HasCurveGeometry(True) # Test GetLinearGeometry g2 = g1.GetLinearGeometry(45) - if ogrtest.check_feature_geometry(g2, expected_g) != 0: - gdaltest.post_reason('fail') - print(g2) - return 'fail' + assert ogrtest.check_feature_geometry(g2, expected_g) == 0 # Test ForceToPolygon gdal.SetConfigOption('OGR_ARC_STEPSIZE', '45') g2 = ogr.ForceToPolygon(g1) gdal.SetConfigOption('OGR_ARC_STEPSIZE', None) - if ogrtest.check_feature_geometry(g2, expected_g) != 0: - gdaltest.post_reason('fail') - print(g2) - return 'fail' + assert ogrtest.check_feature_geometry(g2, expected_g) == 0 # Test ForceToMultiPolygon gdal.SetConfigOption('OGR_ARC_STEPSIZE', '45') expected_g2 = ogr.CreateGeometryFromWkt('MULTIPOLYGON (((0 0,0.116977778440514 -0.321393804843282,0.413175911166547 -0.49240387650611,0.75 -0.433012701892224,0.969846310392967 -0.171010071662835,0.969846310392967 0.171010071662835,0.75 0.433012701892224,0.413175911166547 0.49240387650611,0.116977778440514 0.321393804843282,0 0)))') g2 = ogr.ForceToMultiPolygon(g1) gdal.SetConfigOption('OGR_ARC_STEPSIZE', None) - if ogrtest.check_feature_geometry(g2, expected_g2) != 0: - gdaltest.post_reason('fail') - print(g2) - return 'fail' + assert ogrtest.check_feature_geometry(g2, expected_g2) == 0 # Test ForceToMultiLineString gdal.SetConfigOption('OGR_ARC_STEPSIZE', '45') g2 = ogr.ForceToMultiLineString(g1) gdal.SetConfigOption('OGR_ARC_STEPSIZE', None) expected_g3 = ogr.CreateGeometryFromWkt('MULTILINESTRING ((0 0,0.116977778440514 -0.321393804843282,0.413175911166547 -0.49240387650611,0.75 -0.433012701892224,0.969846310392967 -0.171010071662835,0.969846310392967 0.171010071662835,0.75 0.433012701892224,0.413175911166547 0.49240387650611,0.116977778440514 0.321393804843282,0 0))') - if ogrtest.check_feature_geometry(g2, expected_g3) != 0: - gdaltest.post_reason('fail') - print(g2) - return 'fail' + assert ogrtest.check_feature_geometry(g2, expected_g3) == 0 # Test GEOS operations if ogrtest.have_geos(): g2 = g1.Intersection(g1) - if g2 is None: - gdaltest.post_reason('fail') - return 'fail' + assert g2 is not None # Test CURVEPOLYGON and COMPOUNDCURVE, CIRCULARSTRING, LINESTRING in_wkt = 'CURVEPOLYGON (COMPOUNDCURVE (CIRCULARSTRING (0 0,1 1,2 0),(2 0,0 0)),(0.1 0.1,0.1 0.2,0.2 0.2,0.2 0.1,0.1 0.1),CIRCULARSTRING (0.25 0.25,0.75 0.25,0.25 0.25))' g1 = ogr.CreateGeometryFromWkt(in_wkt) g2 = ogr.CreateGeometryFromWkb(g1.ExportToWkb()) - if g2.ExportToWkt() != in_wkt: - gdaltest.post_reason('fail') - print(g2) - return 'fail' + assert g2.ExportToWkt() == in_wkt # Test CURVEPOLYGON wrapped in a GEOMETRYCOLLECTION in_wkt = 'GEOMETRYCOLLECTION(CURVEPOLYGON(CIRCULARSTRING (0 0,1 0,0 0)))' g1 = ogr.CreateGeometryFromWkt(in_wkt) g2 = ogr.CreateGeometryFromWkb(g1.ExportToWkb()) - if not g1.Equals(g2): - gdaltest.post_reason('fail') - print(g2) - return 'fail' + assert g1.Equals(g2) # Test GEOS operations if ogrtest.have_geos(): g2 = g1.Intersection(g1) - if g2 is None: - gdaltest.post_reason('fail') - return 'fail' + assert g2 is not None # Test ForceToPolygon gdal.SetConfigOption('OGR_ARC_STEPSIZE', '45') g2 = ogr.ForceToPolygon(g1) gdal.SetConfigOption('OGR_ARC_STEPSIZE', None) - if ogrtest.check_feature_geometry(g2, expected_g) != 0: - gdaltest.post_reason('fail') - print(g2) - return 'fail' + assert ogrtest.check_feature_geometry(g2, expected_g) == 0 # Test ForceToMultiPolygon gdal.SetConfigOption('OGR_ARC_STEPSIZE', '45') g2 = ogr.ForceToMultiPolygon(g1) gdal.SetConfigOption('OGR_ARC_STEPSIZE', None) - if ogrtest.check_feature_geometry(g2, expected_g2) != 0: - gdaltest.post_reason('fail') - print(g2) - return 'fail' + assert ogrtest.check_feature_geometry(g2, expected_g2) == 0 # Error case : not enough points in_wkt = 'CURVEPOLYGON ((0 0,0 1,0 0))' gdal.PushErrorHandler('CPLQuietErrorHandler') g = ogr.CreateGeometryFromWkt(in_wkt) gdal.PopErrorHandler() - if g is not None: - gdaltest.post_reason('fail') - return 'fail' + assert g is None # Error case : wrong sub-geometry type in_wkt = 'CURVEPOLYGON (POINT EMPTY)' gdal.PushErrorHandler('CPLQuietErrorHandler') g = ogr.CreateGeometryFromWkt(in_wkt) gdal.PopErrorHandler() - if g is not None: - gdaltest.post_reason('fail') - return 'fail' + assert g is None # Error case: non closed ring in_wkt = 'CURVEPOLYGON ((0 0,0 1,1 1,1 0))' gdal.PushErrorHandler('CPLQuietErrorHandler') g = ogr.CreateGeometryFromWkt(in_wkt) gdal.PopErrorHandler() - if g is not None: - gdaltest.post_reason('fail') - return 'fail' + assert g is None # Area g = ogr.CreateGeometryFromWkt('CURVEPOLYGON ((0 0,1 1,1 0,0 0))') - if g.Area() != 0.5: - gdaltest.post_reason('fail') - return 'fail' + assert g.Area() == 0.5 g = ogr.CreateGeometryFromWkt('CURVEPOLYGON (COMPOUNDCURVE((0 0,1 1,1 0,0 0)))') - if g.Area() != 0.5: - gdaltest.post_reason('fail') - return 'fail' + assert g.Area() == 0.5 g = ogr.CreateGeometryFromWkt('CURVEPOLYGON (COMPOUNDCURVE((0 0,1 1),(1 1,1 0,0 0)))') - if g.Area() != 0.5: - gdaltest.post_reason('fail') - return 'fail' + assert g.Area() == 0.5 g = ogr.CreateGeometryFromWkt('CURVEPOLYGON ((100000000 100000000,100000001 100000001,100000001 100000000,100000000 100000000))') - if g.Area() != 0.5: - gdaltest.post_reason('fail') - return 'fail' + assert g.Area() == 0.5 # Equals g1 = ogr.CreateGeometryFromWkt('CURVEPOLYGON ((0 0,1 1,1 0,0 0),CIRCULARSTRING(0.75 0.5,0.85 0.5,0.75 0.5))') - if not g1.Equals(g1): - gdaltest.post_reason('fail') - return 'fail' + assert g1.Equals(g1) - if not g1.Equals(g1.Clone()): - gdaltest.post_reason('fail') - return 'fail' + assert g1.Equals(g1.Clone()) - if g1.Equals(ogr.CreateGeometryFromWkt('POINT(0 0)')): - gdaltest.post_reason('fail') - return 'fail' + assert not g1.Equals(ogr.CreateGeometryFromWkt('POINT(0 0)')) - if g1.Equals(ogr.CreateGeometryFromWkt('CURVEPOLYGON ((0 0,1 1,1 0,0 0))')): - gdaltest.post_reason('fail') - return 'fail' + assert not g1.Equals(ogr.CreateGeometryFromWkt('CURVEPOLYGON ((0 0,1 1,1 0,0 0))')) # Intersects optimizations on a circle g1 = ogr.CreateGeometryFromWkt('CURVEPOLYGON (CIRCULARSTRING (0 0,2 0,0 0))') @@ -2750,383 +1960,236 @@ def ogr_geom_curvepolygon(): res = res & g1.Contains(p1) res = res & p1.Within(g1) gdal.SetConfigOption('OGR_ARC_STEPSIZE', None) - if not res: - gdaltest.post_reason('fail') - return 'fail' + assert res # Test point slightly outside circle p2 = ogr.CreateGeometryFromWkt('POINT (%.16g %.16g)' % (1 + math.cos(math.pi / 6) + 1e-4, math.sin(math.pi / 6))) - if p2.Within(g1): - gdaltest.post_reason('fail') - return 'fail' + assert not p2.Within(g1) # Full circle defined by 2 arcs g1 = ogr.CreateGeometryFromWkt('CURVEPOLYGON (CIRCULARSTRING (0 0,1 1,2 0,1 -1,0 0))') - if not p1.Within(g1): - gdaltest.post_reason('fail') - return 'fail' + assert p1.Within(g1) # Same but in reverse order g1 = ogr.CreateGeometryFromWkt('CURVEPOLYGON (CIRCULARSTRING (0 0,1 -1,2 0,1 1,0 0))') - if not p1.Within(g1): - gdaltest.post_reason('fail') - return 'fail' + assert p1.Within(g1) # This is not a circle p2 = ogr.CreateGeometryFromWkt('POINT (%.16g %.16g)' % (1 + math.cos(math.pi / 6) - 1e-2, math.sin(math.pi / 6))) g1 = ogr.CreateGeometryFromWkt('CURVEPOLYGON (CIRCULARSTRING (0 0,1 1,2 0,1 1,0 0))') - if p2.Within(g1): - gdaltest.post_reason('fail') - return 'fail' + assert not p2.Within(g1) # Test area on circle in 2 pieces g1 = ogr.CreateGeometryFromWkt('CURVEPOLYGON (CIRCULARSTRING (0 0,1 1,2 0,1 -1,0 0))') area = g1.Area() expected_area = math.pi - if abs(area - expected_area) > 1e-10: - gdaltest.post_reason('fail') - print(area) - print(expected_area) - return 'fail' + assert abs(area - expected_area) <= 1e-10 # Test area on hippodrome g1 = ogr.CreateGeometryFromWkt('CURVEPOLYGON (CIRCULARSTRING (0 0,1 1,2 0,2 -1,2 -2,1 -3,0 -2,0 -1,0 0))') area = g1.Area() expected_area = math.pi + 2 * 2 - if abs(area - expected_area) > 1e-10: - gdaltest.post_reason('fail') - print(area) - print(expected_area) - return 'fail' + assert abs(area - expected_area) <= 1e-10 # Same hippodrome but with different WKT g1 = ogr.CreateGeometryFromWkt('CURVEPOLYGON (COMPOUNDCURVE(CIRCULARSTRING (0 0,1 1,2 0),(2 0,2 -2),CIRCULARSTRING(2 -2,1 -3,0 -2),(0 -2,0 0)))') area = g1.Area() expected_area = math.pi + 2 * 2 - if abs(area - expected_area) > 1e-10: - gdaltest.post_reason('fail') - print(area) - print(expected_area) - return 'fail' + assert abs(area - expected_area) <= 1e-10 # Similar, but with concave part (does not trigger optimization) g1 = ogr.CreateGeometryFromWkt('CURVEPOLYGON (COMPOUNDCURVE(CIRCULARSTRING (0 0,1 1,2 0),(2 0,2 -2),CIRCULARSTRING(2 -2,1 -1,0 -2),(0 -2,0 0)))') area = g1.Area() expected_area = 2 * 2 - if abs(area - expected_area) > 1e-10: - gdaltest.post_reason('fail') - print(area) - print(expected_area) - return 'fail' + assert abs(area - expected_area) <= 1e-10 # EMPTY for in_wkt in ['CURVEPOLYGON EMPTY', 'CURVEPOLYGON Z EMPTY']: g1 = ogr.CreateGeometryFromWkt(in_wkt) out_wkt = g1.ExportToWkt() - if in_wkt != out_wkt: - gdaltest.post_reason('fail') - print(in_wkt) - print(out_wkt) - return 'fail' - if g1.Area() != 0.0: - gdaltest.post_reason('fail') - print(in_wkt) - return 'fail' + assert in_wkt == out_wkt + assert g1.Area() == 0.0, in_wkt g2 = ogr.CreateGeometryFromWkb(g1.ExportToWkb()) out_wkt = g2.ExportToWkt() - if in_wkt != out_wkt: - gdaltest.post_reason('fail') - print(in_wkt) - print(out_wkt) - return 'fail' + assert in_wkt == out_wkt # Empty CircularString g = ogr.Geometry(ogr.wkbCurvePolygon) g.AddGeometry(ogr.Geometry(ogr.wkbCircularString)) - if g.Area() != 0: - gdaltest.post_reason('fail') - print(g.Area()) - return 'fail' + assert g.Area() == 0 # Non-convex CircularString g = ogr.CreateGeometryFromWkt('CURVEPOLYGON( COMPOUNDCURVE( CIRCULARSTRING(0 0,0.5 -0.5,1 0,1.5 0.5,2 0), (2 0,2 1,0 1,0 0) ) )') - if abs(g.Area() - 2.0) > 1e-10: - gdaltest.post_reason('fail') - print(g.Area()) - return 'fail' - - return 'success' + assert abs(g.Area() - 2.0) <= 1e-10 ############################################################################### # Test OGRMultiCurve -def ogr_geom_multicurve(): +def test_ogr_geom_multicurve(): # Simple test in_wkt = 'MULTICURVE (CIRCULARSTRING (0 0,1 0,0 0))' g1 = ogr.CreateGeometryFromWkt(in_wkt) - if g1.GetGeometryType() != ogr.wkbMultiCurve: - gdaltest.post_reason('fail') - return 'fail' + assert g1.GetGeometryType() == ogr.wkbMultiCurve out_wkt = g1.ExportToWkt() - if in_wkt != out_wkt: - gdaltest.post_reason('fail') - print(out_wkt) - return 'fail' + assert in_wkt == out_wkt - if g1.GetDimension() != 1: - print(g1.GetDimension()) - return 'fail' + assert g1.GetDimension() == 1 env = g1.GetEnvelope() expected_env = (0.0, 1.0, -0.5, 0.5) for i in range(4): - if abs(env[i] - expected_env[i]) > 1e-8: - gdaltest.post_reason('fail') - print(env) - return 'fail' + assert abs(env[i] - expected_env[i]) <= 1e-8 length = g1.Length() expected_length = 2 * math.pi * 0.5 - if abs(length - expected_length) > 1e-8: - gdaltest.post_reason('fail') - print(length) - return 'fail' + assert abs(length - expected_length) <= 1e-8 g2 = ogr.CreateGeometryFromWkb(g1.ExportToWkb()) out_wkt = g2.ExportToWkt() - if in_wkt != out_wkt: - gdaltest.post_reason('fail') - print(out_wkt) - return 'fail' - - if not g1.HasCurveGeometry(): - gdaltest.post_reason('fail') - return 'fail' - if not g1.HasCurveGeometry(True): - gdaltest.post_reason('fail') - return 'fail' + assert in_wkt == out_wkt + + assert g1.HasCurveGeometry() + assert g1.HasCurveGeometry(True) # MULTICURVE of LINESTRING in_wkt = 'MULTICURVE ((0 0,1 0))' g1 = ogr.CreateGeometryFromWkt(in_wkt) - if not g1.HasCurveGeometry(): - gdaltest.post_reason('fail') - return 'fail' - if g1.HasCurveGeometry(True): - gdaltest.post_reason('fail') - return 'fail' + assert g1.HasCurveGeometry() + assert not g1.HasCurveGeometry(True) # Z in_wkt = 'MULTICURVE Z (CIRCULARSTRING Z (0 0 10,1 0 10,0 0 10))' g1 = ogr.CreateGeometryFromWkt(in_wkt) - if g1.GetGeometryType() != ogr.wkbMultiCurveZ: - gdaltest.post_reason('fail') - return 'fail' + assert g1.GetGeometryType() == ogr.wkbMultiCurveZ out_wkt = g1.ExportToWkt() - if in_wkt != out_wkt: - gdaltest.post_reason('fail') - print(out_wkt) - return 'fail' + assert in_wkt == out_wkt g2 = ogr.CreateGeometryFromWkb(g1.ExportToWkb()) out_wkt = g2.ExportToWkt() - if in_wkt != out_wkt: - gdaltest.post_reason('fail') - print(out_wkt) - return 'fail' + assert in_wkt == out_wkt # WKT with all possible sub geometries in_wkt = 'MULTICURVE (CIRCULARSTRING (0 0,1 0,0 0),(0 0,1 1),COMPOUNDCURVE ((0 0,1 1),CIRCULARSTRING (1 1,2 2,3 3)))' g1 = ogr.CreateGeometryFromWkt(in_wkt) out_wkt = g1.ExportToWkt() - if in_wkt != out_wkt: - gdaltest.post_reason('fail') - print(out_wkt) - return 'fail' + assert in_wkt == out_wkt g2 = ogr.CreateGeometryFromWkb(g1.ExportToWkb()) out_wkt = g2.ExportToWkt() - if in_wkt != out_wkt: - gdaltest.post_reason('fail') - print(out_wkt) - return 'fail' + assert in_wkt == out_wkt # Test ForceToMultiLineString gdal.SetConfigOption('OGR_ARC_STEPSIZE', '45') g2 = ogr.ForceToMultiLineString(g1) gdal.SetConfigOption('OGR_ARC_STEPSIZE', None) expected_g = 'MULTILINESTRING ((0 0,0.116977778440514 -0.321393804843282,0.413175911166547 -0.49240387650611,0.75 -0.433012701892224,0.969846310392967 -0.171010071662835,0.969846310392967 0.171010071662835,0.75 0.433012701892224,0.413175911166547 0.49240387650611,0.116977778440514 0.321393804843282,0 0),(0 0,1 1),(0 0,1 1,2 2,3 3))' - if ogrtest.check_feature_geometry(g2, expected_g) != 0: - gdaltest.post_reason('fail') - print(g2) - return 'fail' + assert ogrtest.check_feature_geometry(g2, expected_g) == 0 # Test GetLinearGeometry g2 = g1.GetLinearGeometry(45) - if ogrtest.check_feature_geometry(g2, expected_g) != 0: - gdaltest.post_reason('fail') - print(g2) - return 'fail' + assert ogrtest.check_feature_geometry(g2, expected_g) == 0 # Error case : wrong sub-geometry type in_wkt = 'MULTILINESTRING (POINT EMPTY)' gdal.PushErrorHandler('CPLQuietErrorHandler') g = ogr.CreateGeometryFromWkt(in_wkt) gdal.PopErrorHandler() - if g is not None: - gdaltest.post_reason('fail') - return 'fail' - - return 'success' + assert g is None ############################################################################### # Test OGRMultiSurface -def ogr_geom_multisurface(): +def test_ogr_geom_multisurface(): # Simple test in_wkt = 'MULTISURFACE (CURVEPOLYGON (CIRCULARSTRING (0 0,1 0,0 0)))' g1 = ogr.CreateGeometryFromWkt(in_wkt) - if g1.GetGeometryType() != ogr.wkbMultiSurface: - gdaltest.post_reason('fail') - return 'fail' + assert g1.GetGeometryType() == ogr.wkbMultiSurface out_wkt = g1.ExportToWkt() - if in_wkt != out_wkt: - gdaltest.post_reason('fail') - print(out_wkt) - return 'fail' + assert in_wkt == out_wkt - if g1.GetDimension() != 2: - print(g1.GetDimension()) - return 'fail' + assert g1.GetDimension() == 2 env = g1.GetEnvelope() expected_env = (0.0, 1.0, -0.5, 0.5) for i in range(4): - if abs(env[i] - expected_env[i]) > 1e-8: - gdaltest.post_reason('fail') - print(env) - return 'fail' + assert abs(env[i] - expected_env[i]) <= 1e-8 area = g1.Area() expected_area = math.pi * 0.5 * 0.5 - if abs(area - expected_area) > 1e-8: - gdaltest.post_reason('fail') - print(area) - return 'fail' + assert abs(area - expected_area) <= 1e-8 g2 = ogr.CreateGeometryFromWkb(g1.ExportToWkb()) out_wkt = g2.ExportToWkt() - if in_wkt != out_wkt: - gdaltest.post_reason('fail') - print(out_wkt) - return 'fail' - - if not g1.HasCurveGeometry(): - gdaltest.post_reason('fail') - return 'fail' - if not g1.HasCurveGeometry(True): - gdaltest.post_reason('fail') - return 'fail' + assert in_wkt == out_wkt + + assert g1.HasCurveGeometry() + assert g1.HasCurveGeometry(True) # Z in_wkt = 'MULTISURFACE Z (CURVEPOLYGON Z (CIRCULARSTRING Z (0 0 10,1 0 10,0 0 10)))' g1 = ogr.CreateGeometryFromWkt(in_wkt) - if g1.GetGeometryType() != ogr.wkbMultiSurfaceZ: - gdaltest.post_reason('fail') - return 'fail' + assert g1.GetGeometryType() == ogr.wkbMultiSurfaceZ out_wkt = g1.ExportToWkt() - if in_wkt != out_wkt: - gdaltest.post_reason('fail') - print(out_wkt) - return 'fail' + assert in_wkt == out_wkt g2 = ogr.CreateGeometryFromWkb(g1.ExportToWkb()) out_wkt = g2.ExportToWkt() - if in_wkt != out_wkt: - gdaltest.post_reason('fail') - print(out_wkt) - return 'fail' + assert in_wkt == out_wkt # MULTISURFACE of POLYGON in_wkt = 'MULTISURFACE (((0 0,0 10,10 10,10 0,0 0)))' g1 = ogr.CreateGeometryFromWkt(in_wkt) - if not g1.HasCurveGeometry(): - gdaltest.post_reason('fail') - return 'fail' - if g1.HasCurveGeometry(True): - gdaltest.post_reason('fail') - return 'fail' + assert g1.HasCurveGeometry() + assert not g1.HasCurveGeometry(True) # WKT with all possible sub geometries in_wkt = 'MULTISURFACE (((0 0,0 10,10 10,10 0,0 0)),CURVEPOLYGON (CIRCULARSTRING (0 0,1 0,0 0)))' g1 = ogr.CreateGeometryFromWkt(in_wkt) out_wkt = g1.ExportToWkt() - if in_wkt != out_wkt: - gdaltest.post_reason('fail') - print(out_wkt) - return 'fail' + assert in_wkt == out_wkt g2 = ogr.CreateGeometryFromWkb(g1.ExportToWkb()) out_wkt = g2.ExportToWkt() - if in_wkt != out_wkt: - gdaltest.post_reason('fail') - print(out_wkt) - return 'fail' + assert in_wkt == out_wkt # Test ForceToMultiPolygon gdal.SetConfigOption('OGR_ARC_STEPSIZE', '45') g2 = ogr.ForceToMultiPolygon(g1) gdal.SetConfigOption('OGR_ARC_STEPSIZE', None) expected_g = 'MULTIPOLYGON (((0 0,0 10,10 10,10 0,0 0)),((0 0,0.116977778440514 -0.321393804843282,0.413175911166547 -0.49240387650611,0.75 -0.433012701892224,0.969846310392967 -0.171010071662835,0.969846310392967 0.171010071662835,0.75 0.433012701892224,0.413175911166547 0.49240387650611,0.116977778440514 0.321393804843282,0 0)))' - if ogrtest.check_feature_geometry(g2, expected_g) != 0: - gdaltest.post_reason('fail') - print(g2) - return 'fail' + assert ogrtest.check_feature_geometry(g2, expected_g) == 0 # Test GetLinearGeometry g2 = g1.GetLinearGeometry(45) - if ogrtest.check_feature_geometry(g2, expected_g) != 0: - gdaltest.post_reason('fail') - print(g2) - return 'fail' + assert ogrtest.check_feature_geometry(g2, expected_g) == 0 # Check that GetLinearGeometry() is idem-potent on MULTIPOLYGON g3 = g2.GetLinearGeometry(45) - if not g3.Equals(g2): - gdaltest.post_reason('fail') - print(g3) - return 'fail' + assert g3.Equals(g2) # PointOnSurface if ogrtest.have_geos(): in_wkt = 'MULTISURFACE (((0 0,0 10,10 10,10 0,0 0),(1 1,1 9,9 9,9 1,1 1)),((10 0,10 10,20 10,20 0,10 0),(11 1,11 9,19 9,19 1,11 1)))' g1 = ogr.CreateGeometryFromWkt(in_wkt) p1 = g1.PointOnSurface() - if p1.ExportToWkt() != 'POINT (0.5 5.0)': - gdaltest.post_reason('fail') - print(p1) - return 'fail' + assert p1.ExportToWkt() == 'POINT (0.5 5.0)' # Error case : wrong sub-geometry type in_wkt = 'MULTIPOLYGON (POINT EMPTY)' gdal.PushErrorHandler('CPLQuietErrorHandler') g = ogr.CreateGeometryFromWkt(in_wkt) gdal.PopErrorHandler() - if g is not None: - gdaltest.post_reason('fail') - return 'fail' - - return 'success' + assert g is None ############################################################################### # Test GetCurveGeometry -def ogr_geom_getcurvegeometry(): +def test_ogr_geom_getcurvegeometry(): for geom in ['POINT', 'LINESTRING', 'POLYGON', 'MULTIPOINT', 'MULTILINESTRING', 'MULTIPOLYGON', 'GEOMETRYCOLLECTION', @@ -3138,64 +2201,43 @@ def ogr_geom_getcurvegeometry(): in_wkt = geom + ' EMPTY' g = ogr.CreateGeometryFromWkt(in_wkt) g2 = g.GetCurveGeometry() - if g2.ExportToWkt() != in_wkt: - gdaltest.post_reason('fail') - print(g) - print(g2) - return 'fail' + assert g2.ExportToWkt() == in_wkt, g g = ogr.CreateGeometryFromWkt('GEOMETRYCOLLECTION(POINT (0 1))') g2 = g.GetCurveGeometry() - if not g.Equals(g2): - gdaltest.post_reason('fail') - return 'fail' + assert g.Equals(g2) g = ogr.CreateGeometryFromWkt('GEOMETRYCOLLECTION(LINESTRING (0 0,0 1,0 0))') g2 = g.GetCurveGeometry() - if not g.Equals(g2): - gdaltest.post_reason('fail') - return 'fail' + assert g.Equals(g2) g = ogr.CreateGeometryFromWkt('POLYGON((0 0,0 1,1 1,1 0,0 0))') g2 = g.GetCurveGeometry() - if not g.Equals(g2): - gdaltest.post_reason('fail') - return 'fail' + assert g.Equals(g2) g = ogr.CreateGeometryFromWkt('POLYGON Z ((0 0 10,0 1 10,1 1 10,1 0 10,0 0 10))') g2 = g.GetCurveGeometry() - if not g.Equals(g2): - gdaltest.post_reason('fail') - return 'fail' + assert g.Equals(g2) # CircularString with large step g1 = ogr.CreateGeometryFromWkt('CIRCULARSTRING (0 0,1 1,2 0)') g2 = g1.GetLinearGeometry(15) g3 = g2.GetCurveGeometry() - if g3.GetGeometryType() != ogr.wkbCircularString or \ - g1.GetPoint(0) != g3.GetPoint(0) or g1.GetPoint(2) != g3.GetPoint(2) or \ - abs((g3.GetX(1) - 1) * (g3.GetX(1) - 1) + g3.GetY(1) * g3.GetY(1) - 1) > 1e-8: - gdaltest.post_reason('fail') - print(g3) - return 'fail' + assert (g3.GetGeometryType() == ogr.wkbCircularString and \ + g1.GetPoint(0) == g3.GetPoint(0) and g1.GetPoint(2) == g3.GetPoint(2) and \ + abs((g3.GetX(1) - 1) * (g3.GetX(1) - 1) + g3.GetY(1) * g3.GetY(1) - 1) <= 1e-8) # CurvePolygon with large step g1 = ogr.CreateGeometryFromWkt('CURVEPOLYGON( CIRCULARSTRING (0 0,1 1,0 0))') g2 = g1.GetLinearGeometry(15) g3 = g2.GetCurveGeometry() - if not g3.Equals(g1): - gdaltest.post_reason('fail') - print(g3) - return 'fail' + assert g3.Equals(g1) # This is a straight line g1 = ogr.CreateGeometryFromWkt('CIRCULARSTRING (1 2,3 4,5 6)') g2 = g1.GetLinearGeometry() g3 = g2.GetCurveGeometry() - if g3.ExportToWkt() != 'LINESTRING (1 2,3 4,5 6)': - gdaltest.post_reason('fail') - print(g3) - return 'fail' + assert g3.ExportToWkt() == 'LINESTRING (1 2,3 4,5 6)' # "Random" arcs for wkt in ['CIRCULARSTRING (1 2,3 1,5 6)', @@ -3214,11 +2256,7 @@ def ogr_geom_getcurvegeometry(): g1 = ogr.CreateGeometryFromWkt(wkt) g2 = g1.GetLinearGeometry() g3 = g2.GetCurveGeometry() - if not g3.Equals(g1): - gdaltest.post_reason('fail') - print(g1) - print(g3) - return 'fail' + assert g3.Equals(g1) # Really random arcs with coordinates in the [-1000,1000] range for i in range(1000): @@ -3280,26 +2318,18 @@ def ogr_geom_getcurvegeometry(): g1 = ogr.CreateGeometryFromWkt('CIRCULARSTRING (0 0,0.5 -0.5,1 0,0.5 0.5,0 0)') g2 = g1.GetLinearGeometry() g3 = g2.GetCurveGeometry() - if not g3.Equals(g1): - gdaltest.post_reason('fail') - print(g3) - return 'fail' + assert g3.Equals(g1) # 3 points full circle g1 = ogr.CreateGeometryFromWkt('CIRCULARSTRING (0 0,1 0,0 0)') g2 = g1.GetLinearGeometry() g3 = g2.GetCurveGeometry() - if g3.GetGeometryType() != ogr.wkbCircularString or \ - g1.GetPoint(0) != g3.GetPoint(0) or \ - g1.GetPoint(1) != g3.GetPoint(2) or \ - g1.GetPoint(2) != g3.GetPoint(4) or \ - abs((g3.GetX(1) - 0.5) * (g3.GetX(1) - 0.5) + g3.GetY(1) * g3.GetY(1) - 0.5 * 0.5) > 1e-12 or \ - abs((g3.GetX(3) - 0.5) * (g3.GetX(3) - 0.5) + g3.GetY(3) * g3.GetY(3) - 0.5 * 0.5) > 1e-12: - gdaltest.post_reason('fail') - print(g3) - # print(abs((g3.GetX(1) - 0.5)*(g3.GetX(1) - 0.5)+g3.GetY(1)*g3.GetY(1) - 0.5*0.5)) - # print(abs((g3.GetX(3) - 0.5)*(g3.GetX(3) - 0.5)+g3.GetY(3)*g3.GetY(3) - 0.5*0.5)) - return 'fail' + assert (g3.GetGeometryType() == ogr.wkbCircularString and \ + g1.GetPoint(0) == g3.GetPoint(0) and \ + g1.GetPoint(1) == g3.GetPoint(2) and \ + g1.GetPoint(2) == g3.GetPoint(4) and \ + abs((g3.GetX(1) - 0.5) * (g3.GetX(1) - 0.5) + g3.GetY(1) * g3.GetY(1) - 0.5 * 0.5) <= 1e-12 and \ + abs((g3.GetX(3) - 0.5) * (g3.GetX(3) - 0.5) + g3.GetY(3) * g3.GetY(3) - 0.5 * 0.5) <= 1e-12) # 3 points full circle in a CurvePolygon for wkt in ['CURVEPOLYGON( CIRCULARSTRING (0 0,1 0,0 0))', @@ -3309,165 +2339,110 @@ def ogr_geom_getcurvegeometry(): g1 = ogr.CreateGeometryFromWkt(wkt) g2 = g1.GetLinearGeometry() g3 = g2.GetCurveGeometry() - if not g3.Equals(g1): - gdaltest.post_reason('fail') - print(g1) - print(g3) - return 'fail' + assert g3.Equals(g1) # 2 curves in the CircularString g1 = ogr.CreateGeometryFromWkt('CIRCULARSTRING (0 0,1 1,2 0,3 -1,4 0)') g2 = g1.GetLinearGeometry() g3 = g2.GetCurveGeometry() - if not g3.Equals(g1): - gdaltest.post_reason('fail') - print(g3) - return 'fail' + assert g3.Equals(g1) # 3 curves in the CircularString g1 = ogr.CreateGeometryFromWkt('CIRCULARSTRING (0 0,1 1,2 0,3 -1,4 0,5 1,6 0)') g2 = g1.GetLinearGeometry() g3 = g2.GetCurveGeometry() - if not g3.Equals(g1): - gdaltest.post_reason('fail') - print(g3) - return 'fail' + assert g3.Equals(g1) # CircularString, LineString, CircularString g1 = ogr.CreateGeometryFromWkt('COMPOUNDCURVE (CIRCULARSTRING (0 0,1 1,2 0),(2 0,3 0,4 0),CIRCULARSTRING (4 0,5 1,6 0))') g2 = g1.GetLinearGeometry() g3 = g2.GetCurveGeometry() - if not g3.Equals(g1): - gdaltest.post_reason('fail') - print(g3) - return 'fail' + assert g3.Equals(g1) # LineString, CircularString, LineString, CircularString, LineString g1 = ogr.CreateGeometryFromWkt('COMPOUNDCURVE ((-1 0,-0.5 0.5,0 0),CIRCULARSTRING (0 0,1 1,2 0),(2 0,3 0,4 0),CIRCULARSTRING (4 0,5 1,6 0),(6 0,7 0))') g2 = g1.GetLinearGeometry() g3 = g2.GetCurveGeometry() - if not g3.Equals(g1): - gdaltest.post_reason('fail') - print(g3) - return 'fail' + assert g3.Equals(g1) # Check with default discretization method g1 = ogr.CreateGeometryFromWkt('CIRCULARSTRING (0 0,1.2 1.0,2 0)') g2 = ogr.CreateGeometryFromWkt('LINESTRING (0 0,0.000997093138961 0.068920262501281,0.006738548124866 0.137608197923873,0.017197098230267 0.205737600590167,0.032323074784779 0.272984917348872,0.052044643056421 0.339030784160355,0.076268143401735 0.403561542787492,0.104878536064531 0.466270730389102,0.137739947510866 0.526860534941749,0.174696315705653 0.585043209577972,0.215572131266425 0.640542439124111,0.260173270974444 0.693094652347904,0.30828791968472 0.742450273683876,0.359687576256715 0.788374908491942,0.414128138728451 0.830650456220319,0.471351063580441 0.869076146186235,0.531084593583979 0.903469491055406,0.593045048402615 0.933667153492107,0.656938171817632 0.959525721864054,0.722460529179411 0.980922391318168,0.789300948448056 0.99775554699276,0.857141997979641 1.009945246596371,0.925661494039921 1.017433600061489,0.994534030886182 1.020185044470095,1.063432526150724 1.01818651294542,1.132029774186796 1.01144749670781,1.2 1.0,1.267547127648721 0.983752320094182,1.333803428245673 0.962854851656094,1.398449236893265 0.937408418110045,1.461172658788815 0.907535790143504,1.521671074014578 0.873381093378847,1.579652597579492 0.835109113014538,1.634837487668428 0.792904498790658,1.686959495304612 0.746970874114522,1.73576714891352 0.697529853644598,1.781024967590663 0.644819974072535,1.822514597219645 0.589095543261942,1.860035863959079 0.53062541329644,1.89340774001566 0.469691683356621,1.922469217043826 0.406588338684124,1.94708008295817 0.341619832199361,1.967121598410718 0.27509961561613,1.982497069669296 0.207348627140011,1.993132315133044 0.138693743046887,1.998976023234287 0.069466200612231,2 0)') g3 = g2.GetCurveGeometry() - if not g3.Equals(g1): - gdaltest.post_reason('fail') - print(g3) - return 'fail' + assert g3.Equals(g1) # Check with alternate discretization method : ROUND_ANGLE_METHOD g1 = ogr.CreateGeometryFromWkt('CIRCULARSTRING (0 0,1.2 1.0,2 0)') g2 = ogr.CreateGeometryFromWkt('LINESTRING (0 0,-0.000199980003999 0.02,0.002236456877416 0.089770423644023,0.009533897446083 0.159200932797352,0.021656789305088 0.227953268998521,0.038546070943884 0.295692477776518,0.060119459480029 0.362088540515299,0.086271851533127 0.426817982271309,0.116875835277923 0.489565447710894,0.151782311181914 0.550025237489786,0.190821218403283 0.607902797589577,0.233802363310224 0.662916154355295,0.280516346085201 0.7147972882427,0.330735580899807 0.763293439582565,0.384215404690045 0.80816834000038,0.440695269130182 0.849203363492117,0.499900009998002 0.886198591548151,0.561541187747236 0.918973787136141,0.62531849275604 0.947369272797732,0.690921208405283 0.971246708581086,0.758029724858684 0.990489766019218,0.826317096169807 1.005004694870594,0.895450633129846 1.014720779860886,0.965093524096011 1.019590685200679,1.034906475903993 1.019590685200679,1.104549366870158 1.014720779860886,1.173682903830197 1.005004694870593,1.2 1.0,1.241970275141317 0.990489766019217,1.309078791594718 0.971246708581085,1.374681507243961 0.947369272797731,1.438458812252765 0.91897378713614,1.500099990002 0.886198591548151,1.559304730869819 0.849203363492116,1.615784595309956 0.808168340000379,1.669264419100194 0.763293439582565,1.7194836539148 0.714797288242699,1.766197636689777 0.662916154355294,1.809178781596718 0.607902797589576,1.848217688818087 0.550025237489785,1.883124164722078 0.489565447710893,1.913728148466874 0.426817982271308,1.939880540519971 0.362088540515298,1.961453929056117 0.295692477776516,1.978343210694912 0.227953268998519,1.990466102553917 0.15920093279735,1.997763543122584 0.089770423644022,2.000199980003999 0.02,2 0)') g3 = g2.GetCurveGeometry() - if not g3.Equals(g1): - gdaltest.post_reason('fail') - print(g3) - return 'fail' + assert g3.Equals(g1) # Check with PostgreSQL output of SELECT ST_CurveToLine(ST_GeomFromText('CIRCULARSTRING (0 0,1.2 1.0,2 0)')) g1 = ogr.CreateGeometryFromWkt('CIRCULARSTRING (0 0,1.2 1.0,2 0)') g2 = ogr.CreateGeometryFromWkt('LINESTRING (0 0,0.000223190308279 0.049091765203314,0.002854930521212 0.098113445796116,0.007888880546112 0.146946944256066,0.015312913156447 0.195474616408063,0.025109143207391 0.243579554839372,0.037253970722702 0.291145870539817,0.051718137749134 0.338058972088558,0.068466798841411 0.384205841714863,0.08745960500795 0.429475307567812,0.108650800915124 0.473758311539029,0.131989335115863 0.516948171993215,0.157418983037062 0.558940840773549,0.184878482429505 0.599635153862819,0.214301680953989 0.638933075096389,0.245617695548099 0.676739932339917,0.27875108318972 0.712964645562815,0.31362202264588 0.747519946258017,0.350146506769097 0.780322587679462,0.388236544877951 0.811293545390794,0.427800374734344 0.840358207642151,0.46874268360677 0.867446555116406,0.510964837887032 0.892493329611833,0.554365120707246 0.915438191254836,0.598838976984681 0.936225863863983,0.644279265304116 0.954806268115175,0.690576516030889 0.971134642187118,0.737619195032841 0.985171649596477,0.785293972375802 0.996883473962907,0.833485995345338 1.006241900475673,0.88207916513699 1.013224383865605,0.930956416548473 1.017814102718623,0.98 1.02,1.029091765203309 1.019776809691721,1.078113445796111 1.017145069478788,1.12694694425606 1.012111119453889,1.175474616408058 1.004687086843554,1.223579554839367 0.994890856792611,1.271145870539812 0.9827460292773,1.318058972088553 0.968281862250867,1.364205841714858 0.951533201158591,1.409475307567807 0.932540394992052,1.453758311539024 0.911349199084878,1.49694817199321 0.88801066488414,1.538940840773545 0.862581016962941,1.579635153862814 0.835121517570498,1.618933075096384 0.805698319046015,1.656739932339913 0.774382304451905,1.692964645562811 0.741248916810284,1.727519946258013 0.706377977354124,1.760322587679458 0.669853493230907,1.791293545390791 0.631763455122053,1.820358207642148 0.59219962526566,1.847446555116403 0.551257316393235,1.872493329611831 0.509035162112973,1.895438191254833 0.465634879292759,1.916225863863981 0.421161023015324,1.934806268115173 0.37572073469589,1.951134642187117 0.329423483969116,1.965171649596476 0.282380804967164,1.976883473962906 0.234706027624203,1.986241900475672 0.186514004654668,1.993224383865604 0.137920834863015,1.997814102718623 0.089043583451532,2.0 0.04,2 0)') g3 = g2.GetCurveGeometry() g1_expected = ogr.CreateGeometryFromWkt('CIRCULARSTRING (0 0,0.98 1.02,2 0)') - if not g3.Equals(g1_expected): - gdaltest.post_reason('fail') - print(g3) - return 'fail' + assert g3.Equals(g1_expected) # Test default ( implicit option ADD_INTERMEDIATE_POINT=STEALTH ) g1 = ogr.CreateGeometryFromWkt('CIRCULARSTRING (0 0,1.2 1.0,2 0)') g2 = g1.GetLinearGeometry() g3 = g2.GetCurveGeometry() - if not g3.Equals(g1): - gdaltest.post_reason('fail') - print(g3) - return 'fail' + assert g3.Equals(g1) # Test with Z g1 = ogr.CreateGeometryFromWkt('CIRCULARSTRING (0 0 1,1 1 2,2 0 3)') g2 = g1.GetLinearGeometry() g3 = g2.GetCurveGeometry() - if not g3.Equals(g1): - gdaltest.post_reason('fail') - print(g3) - return 'fail' + assert g3.Equals(g1) g1 = ogr.CreateGeometryFromWkt('CIRCULARSTRING (2 0 3,1 1 2,0 0 1)') g2 = g1.GetLinearGeometry() g3 = g2.GetCurveGeometry() - if not g3.Equals(g1): - gdaltest.post_reason('fail') - print(g3) - return 'fail' + assert g3.Equals(g1) # Test option ADD_INTERMEDIATE_POINT=STEALTH g1 = ogr.CreateGeometryFromWkt('CIRCULARSTRING (0 0,1.2 1.0,2 0)') g2 = g1.GetLinearGeometry(options=['ADD_INTERMEDIATE_POINT=STEALTH']) g3 = g2.GetCurveGeometry() - if not g3.Equals(g1): - gdaltest.post_reason('fail') - print(g3) - return 'fail' + assert g3.Equals(g1) # Test option ADD_INTERMEDIATE_POINT=YES g1 = ogr.CreateGeometryFromWkt('CIRCULARSTRING (0 0,1.2 1.0,2 0)') g2 = g1.GetLinearGeometry(options=['ADD_INTERMEDIATE_POINT=YES']) g3 = g2.GetCurveGeometry() - if not g3.Equals(g1): - gdaltest.post_reason('fail') - print(g3) - return 'fail' + assert g3.Equals(g1) # Test with big coordinates. The points are (2,49),(3,50),(4,49) reprojected from EPSG:4326 to EPSG:32631 g1 = ogr.CreateGeometryFromWkt('CIRCULARSTRING (426857.987717275 5427937.52346616,500000.000000001 5538630.70286887,573142.012282726 5427937.52346616)') g2 = g1.GetLinearGeometry() g3 = g2.GetCurveGeometry() - if ogrtest.check_feature_geometry(g3, g1) != 0: - gdaltest.post_reason('fail') - print(g3) - return 'fail' + assert ogrtest.check_feature_geometry(g3, g1) == 0 # Same with integer coordinates g1 = ogr.CreateGeometryFromWkt('CIRCULARSTRING (426858 5427938,500000 5538632,573142 5427938)') g2 = g1.GetLinearGeometry() g3 = g2.GetCurveGeometry() - if not g3.Equals(g1): - gdaltest.post_reason('fail') - print(g3) - return 'fail' + assert g3.Equals(g1) # Test option ADD_INTERMEDIATE_POINT=FALSE g1 = ogr.CreateGeometryFromWkt('CIRCULARSTRING (0 0,1.2 1.0,2 0)') g2 = g1.GetLinearGeometry(options=['ADD_INTERMEDIATE_POINT=FALSE']) g3 = g2.GetCurveGeometry() g1_expected = ogr.CreateGeometryFromWkt('CIRCULARSTRING (0 0,1.0 1.020199980003999,2 0)') - if ogrtest.check_feature_geometry(g3, g1_expected) != 0: - gdaltest.post_reason('fail') - print(g3) - return 'fail' + assert ogrtest.check_feature_geometry(g3, g1_expected) == 0 # Test with unrecognized options gdal.PushErrorHandler('CPLQuietErrorHandler') g2_new = g1.GetLinearGeometry(options=['bla', 'ADD_INTERMEDIATE_POINT=FALSE', 'foo=bar']) gdal.PopErrorHandler() - if not g2_new.Equals(g2): - gdaltest.post_reason('fail') - print(g2_new) - return 'fail' + assert g2_new.Equals(g2) # Add repeated point at end of line g2 = g1.GetLinearGeometry() g2.AddPoint_2D(2 - 1e-9, 0) g3 = g2.GetCurveGeometry() - if not g3.Equals(g1): - gdaltest.post_reason('fail') - print(g3) - return 'fail' + assert g3.Equals(g1) # Add repeated point at end of line g2 = g1.GetLinearGeometry() @@ -3476,10 +2451,7 @@ def ogr_geom_getcurvegeometry(): for i in range(g2.GetPointCount()): g2_new.AddPoint_2D(g2.GetX(i), g2.GetY(i)) g3 = g2_new.GetCurveGeometry() - if not g3.Equals(g1): - gdaltest.post_reason('fail') - print(g3) - return 'fail' + assert g3.Equals(g1) # Test various configurations for (wkt, eps) in [('CIRCULARSTRING (0 0,0.5 0.5,0 1,-0.5 0.5,0 0)', 0), @@ -3505,89 +2477,59 @@ def ogr_geom_getcurvegeometry(): g1 = ogr.CreateGeometryFromWkt(wkt) g2 = g1.GetLinearGeometry() g3 = g2.GetCurveGeometry() - if (eps == 0 and not g3.Equals(g1)) or (eps > 0 and ogrtest.check_feature_geometry(g3, g1, eps) != 0): - gdaltest.post_reason('fail') - print('') - print(g1) - print(g3) - print(ogrtest.check_feature_geometry(g3, g1, 1e-6)) - return 'fail' + assert not (eps == 0 and not g3.Equals(g1)) or (eps > 0 and ogrtest.check_feature_geometry(g3, g1, eps) != 0), \ + '' # Test with GEOMETRYCOLLECTION container g1 = ogr.CreateGeometryFromWkt('GEOMETRYCOLLECTION(CIRCULARSTRING (0 0,0.5 0.5,0 1,-0.5 0.5,0 0))') g2 = g1.GetLinearGeometry() g3 = g2.GetCurveGeometry() - if not g3.Equals(g1): - gdaltest.post_reason('fail') - print(g3) - return 'fail' + assert g3.Equals(g1) # Test with MULTICURVE container g1 = ogr.CreateGeometryFromWkt('MULTICURVE(CIRCULARSTRING (0 0,0.5 0.5,0 1,-0.5 0.5,0 0))') g2 = g1.GetLinearGeometry() g3 = g2.GetCurveGeometry() - if not g3.Equals(g1): - gdaltest.post_reason('fail') - print(g3) - return 'fail' + assert g3.Equals(g1) # Test with MULTISURFACE container g1 = ogr.CreateGeometryFromWkt('MULTISURFACE(CURVEPOLYGON(COMPOUNDCURVE(CIRCULARSTRING (0 0,0.5 0.5,1 0),(1 0,0 0))))') g2 = g1.GetLinearGeometry() g3 = g2.GetCurveGeometry() - if not g3.Equals(g1): - gdaltest.post_reason('fail') - print(g3) - return 'fail' + assert g3.Equals(g1) if ogrtest.have_geos(): g1 = ogr.CreateGeometryFromWkt('CURVEPOLYGON(CIRCULARSTRING (0 0,2 0,0 0))') g2 = ogr.CreateGeometryFromWkt('CURVEPOLYGON(CIRCULARSTRING (1 0,3 1,1 0))') g3 = g1.Intersection(g2) - if g3.GetGeometryType() != ogr.wkbCurvePolygon: - gdaltest.post_reason('fail') - print(g3) - return 'fail' + assert g3.GetGeometryType() == ogr.wkbCurvePolygon g1 = ogr.CreateGeometryFromWkt('CURVEPOLYGON(CIRCULARSTRING (0 0,2 0,0 0))') g2 = ogr.CreateGeometryFromWkt('CURVEPOLYGON((1 -1,1 1,3 1,3 -1,1 -1))') g3 = g1.Intersection(g2) - if g3.GetGeometryType() != ogr.wkbCurvePolygon: - gdaltest.post_reason('fail') - print(g3) - return 'fail' + assert g3.GetGeometryType() == ogr.wkbCurvePolygon g1 = ogr.CreateGeometryFromWkt('CURVEPOLYGON(CIRCULARSTRING (0 0,2 0,0 0))') g2 = ogr.CreateGeometryFromWkt('CURVEPOLYGON(CIRCULARSTRING (3 0,5 0,3 0))') g3 = g1.Union(g2) - if g3.ExportToWkt() != 'MULTISURFACE (CURVEPOLYGON (CIRCULARSTRING (0 0,2 0,0 0)),CURVEPOLYGON (CIRCULARSTRING (3 0,5 0,3 0)))': - gdaltest.post_reason('fail') - print(g3) - return 'fail' + assert g3.ExportToWkt() == 'MULTISURFACE (CURVEPOLYGON (CIRCULARSTRING (0 0,2 0,0 0)),CURVEPOLYGON (CIRCULARSTRING (3 0,5 0,3 0)))' g1 = ogr.CreateGeometryFromWkt('CIRCULARSTRING (0 0,1 1,2 0))') g2 = ogr.CreateGeometryFromWkt('CIRCULARSTRING (2 0,1 -1,0 0))') g3 = g1.Union(g2) - if g3.ExportToWkt() != 'MULTICURVE (CIRCULARSTRING (0 0,1 1,2 0),CIRCULARSTRING (2 0,1 -1,0 0))': - gdaltest.post_reason('fail') - print(g3) - return 'fail' + assert g3.ExportToWkt() == 'MULTICURVE (CIRCULARSTRING (0 0,1 1,2 0),CIRCULARSTRING (2 0,1 -1,0 0))' g1 = ogr.CreateGeometryFromWkt('POINT(1 2)') g1 = g1.Buffer(0.5) g1 = g1.GetCurveGeometry() - if g1.ExportToWkt() != 'CURVEPOLYGON (CIRCULARSTRING (1.5 2.0,0.5 2.0,1.5 2.0))': - gdaltest.post_reason('fail') - print(g1) - return 'fail' - - return 'success' + assert g1.ExportToWkt() == 'CURVEPOLYGON (CIRCULARSTRING (1.5 2.0,0.5 2.0,1.5 2.0))' + ############################################################################### # Test OGR_GT_ functions -def ogr_geom_gt_functions(): +def test_ogr_geom_gt_functions(): # GT_HasZ tuples = [(ogr.wkbPoint, 0), @@ -3599,10 +2541,7 @@ def ogr_geom_gt_functions(): (ogr.wkbCircularStringM, 0), (ogr.wkbCircularStringZM, 1)] for (gt, res) in tuples: - if ogr.GT_HasZ(gt) != res: - gdaltest.post_reason('fail') - print(gt) - return 'fail' + assert ogr.GT_HasZ(gt) == res # GT_SetZ tuples = [(ogr.wkbPoint, ogr.wkbPoint25D), @@ -3614,10 +2553,7 @@ def ogr_geom_gt_functions(): (ogr.wkbCircularStringM, ogr.wkbCircularStringZM), (ogr.wkbCircularStringZM, ogr.wkbCircularStringZM)] for (gt, res) in tuples: - if ogr.GT_SetZ(gt) != res: - gdaltest.post_reason('fail') - print(gt) - return 'fail' + assert ogr.GT_SetZ(gt) == res # GT_HasM tuples = [(ogr.wkbPoint, 0), @@ -3629,10 +2565,7 @@ def ogr_geom_gt_functions(): (ogr.wkbCircularStringM, 1), (ogr.wkbCircularStringZM, 1)] for (gt, res) in tuples: - if ogr.GT_HasM(gt) != res: - gdaltest.post_reason('fail') - print(gt) - return 'fail' + assert ogr.GT_HasM(gt) == res # GT_SetM tuples = [(ogr.wkbPoint, ogr.wkbPointM), @@ -3644,10 +2577,7 @@ def ogr_geom_gt_functions(): (ogr.wkbCircularStringM, ogr.wkbCircularStringM), (ogr.wkbCircularStringZM, ogr.wkbCircularStringZM)] for (gt, res) in tuples: - if ogr.GT_SetM(gt) != res: - gdaltest.post_reason('fail') - print(gt) - return 'fail' + assert ogr.GT_SetM(gt) == res # OGR_GT_SetModifier tuples = [(ogr.wkbPoint, 0, 0, ogr.wkbPoint), @@ -3669,10 +2599,7 @@ def ogr_geom_gt_functions(): (ogr.wkbCircularString, 0, 0, ogr.wkbCircularString), (ogr.wkbCircularStringZ, 0, 0, ogr.wkbCircularString)] for (gt, modZ, modM, res) in tuples: - if ogr.GT_SetModifier(gt, modZ, modM) != res: - gdaltest.post_reason('fail') - print(gt) - return 'fail' + assert ogr.GT_SetModifier(gt, modZ, modM) == res # GT_Flatten tuples = [(ogr.wkbPoint, ogr.wkbPoint), @@ -3685,10 +2612,7 @@ def ogr_geom_gt_functions(): (ogr.wkbCircularStringM, ogr.wkbCircularString), (ogr.wkbCircularStringZM, ogr.wkbCircularString)] for (gt, res) in tuples: - if ogr.GT_Flatten(gt) != res: - gdaltest.post_reason('fail') - print(gt) - return 'fail' + assert ogr.GT_Flatten(gt) == res # GT_IsSubClassOf tuples = [(ogr.wkbPoint, ogr.wkbPoint, 1), @@ -3707,11 +2631,7 @@ def ogr_geom_gt_functions(): (ogr.wkbPolyhedralSurface, ogr.wkbTIN, 0), ] for (gt, gt2, res) in tuples: - if ogr.GT_IsSubClassOf(gt, gt2) != res: - gdaltest.post_reason('fail') - print(gt) - print(gt2) - return 'fail' + assert ogr.GT_IsSubClassOf(gt, gt2) == res # GT_IsCurve tuples = [(ogr.wkbPoint, 0), @@ -3730,10 +2650,7 @@ def ogr_geom_gt_functions(): (ogr.wkbPolyhedralSurface, 0), (ogr.wkbTIN, 0)] for (gt, res) in tuples: - if ogr.GT_IsCurve(gt) != res: - gdaltest.post_reason('fail') - print(gt) - return 'fail' + assert ogr.GT_IsCurve(gt) == res # GT_IsSurface tuples = [(ogr.wkbPoint, 0), @@ -3750,10 +2667,7 @@ def ogr_geom_gt_functions(): (ogr.wkbPolyhedralSurface, 1), (ogr.wkbTIN, 1)] for (gt, res) in tuples: - if ogr.GT_IsSurface(gt) != res: - gdaltest.post_reason('fail') - print(gt) - return 'fail' + assert ogr.GT_IsSurface(gt) == res # GT_GetCollection tuples = [(ogr.wkbPoint, ogr.wkbMultiPoint), @@ -3766,10 +2680,7 @@ def ogr_geom_gt_functions(): (ogr.wkbLineString, ogr.wkbMultiLineString), (ogr.wkbPolygon, ogr.wkbMultiPolygon)] for (gt, res) in tuples: - if ogr.GT_GetCollection(gt) != res: - gdaltest.post_reason('fail') - print(gt) - return 'fail' + assert ogr.GT_GetCollection(gt) == res # GT_IsNonLinear tuples = [(ogr.wkbPoint, 0), @@ -3788,10 +2699,7 @@ def ogr_geom_gt_functions(): (ogr.wkbPolygon, 0), (ogr.wkbTriangle, 0)] for (gt, res) in tuples: - if ogr.GT_IsNonLinear(gt) != res: - gdaltest.post_reason('fail') - print(gt) - return 'fail' + assert ogr.GT_IsNonLinear(gt) == res # GT_GetCurve tuples = [(ogr.wkbPoint, ogr.wkbPoint), @@ -3811,10 +2719,7 @@ def ogr_geom_gt_functions(): (ogr.wkbMultiCurve, ogr.wkbMultiCurve), (ogr.wkbMultiSurface, ogr.wkbMultiSurface)] for (gt, res) in tuples: - if ogr.GT_GetCurve(gt) != res: - gdaltest.post_reason('fail') - print(gt) - return 'fail' + assert ogr.GT_GetCurve(gt) == res # GT_GetLinear tuples = [(ogr.wkbPoint, ogr.wkbPoint), @@ -3834,18 +2739,14 @@ def ogr_geom_gt_functions(): (ogr.wkbMultiCurve, ogr.wkbMultiLineString), (ogr.wkbMultiSurface, ogr.wkbMultiPolygon)] for (gt, res) in tuples: - if ogr.GT_GetLinear(gt) != res: - gdaltest.post_reason('fail') - print(gt) - return 'fail' - - return 'success' + assert ogr.GT_GetLinear(gt) == res + ############################################################################### # Limit cases -def ogr_geom_api_limit_tests(): +def test_ogr_geom_api_limit_tests(): p = ogr.Geometry(ogr.wkbPoint) lyr = ogr.Geometry(ogr.wkbLineString) @@ -3888,84 +2789,47 @@ def ogr_geom_api_limit_tests(): p.AddGeometryDirectly(p) - return 'success' - + ############################################################################### # Test Equals -def ogr_geom_equals(): +def test_ogr_geom_equals(): p_empty = ogr.Geometry(ogr.wkbPoint) p_0 = ogr.CreateGeometryFromWkt('POINT (0 0)') p_1 = ogr.CreateGeometryFromWkt('POINT (1 1)') - if not p_empty.Equals(p_empty): - gdaltest.post_reason('fail') - return 'fail' - if not p_0.Equals(p_0): - gdaltest.post_reason('fail') - return 'fail' - if not p_0.Equals(p_0.Clone()): - gdaltest.post_reason('fail') - return 'fail' - if p_empty.Equals(p_0): - gdaltest.post_reason('fail') - return 'fail' - if p_0.Equals(p_empty): - gdaltest.post_reason('fail') - return 'fail' - if p_0.Equals(p_1): - gdaltest.post_reason('fail') - return 'fail' + assert p_empty.Equals(p_empty) + assert p_0.Equals(p_0) + assert p_0.Equals(p_0.Clone()) + assert not p_empty.Equals(p_0) + assert not p_0.Equals(p_empty) + assert not p_0.Equals(p_1) l_empty = ogr.Geometry(ogr.wkbLineString) l_0_1 = ogr.CreateGeometryFromWkt('LINESTRING (0 0,1 1)') l_0_1_2 = ogr.CreateGeometryFromWkt('LINESTRING (0 0,1 1,2 2)') - if not l_0_1.Equals(l_0_1): - gdaltest.post_reason('fail') - return 'fail' - if not l_0_1.Equals(l_0_1.Clone()): - gdaltest.post_reason('fail') - return 'fail' - if l_empty.Equals(l_0_1): - gdaltest.post_reason('fail') - return 'fail' - if l_0_1.Equals(l_empty): - gdaltest.post_reason('fail') - return 'fail' - if l_0_1.Equals(l_0_1_2): - gdaltest.post_reason('fail') - return 'fail' + assert l_0_1.Equals(l_0_1) + assert l_0_1.Equals(l_0_1.Clone()) + assert not l_empty.Equals(l_0_1) + assert not l_0_1.Equals(l_empty) + assert not l_0_1.Equals(l_0_1_2) gc_empty = ogr.Geometry(ogr.wkbGeometryCollection) gc_p_0 = ogr.CreateGeometryFromWkt('GEOMETRYCOLLECTION (POINT (0 0))') gc_p_1 = ogr.CreateGeometryFromWkt('GEOMETRYCOLLECTION (POINT (1 1))') - if not gc_empty.Equals(gc_empty): - gdaltest.post_reason('fail') - return 'fail' - if not gc_p_0.Equals(gc_p_0): - gdaltest.post_reason('fail') - return 'fail' - if not gc_p_0.Equals(gc_p_0.Clone()): - gdaltest.post_reason('fail') - return 'fail' - if gc_empty.Equals(gc_p_0): - gdaltest.post_reason('fail') - return 'fail' - if gc_p_0.Equals(gc_empty): - gdaltest.post_reason('fail') - return 'fail' - if gc_p_0.Equals(gc_p_1): - gdaltest.post_reason('fail') - return 'fail' - - return 'success' + assert gc_empty.Equals(gc_empty) + assert gc_p_0.Equals(gc_p_0) + assert gc_p_0.Equals(gc_p_0.Clone()) + assert not gc_empty.Equals(gc_p_0) + assert not gc_p_0.Equals(gc_empty) + assert not gc_p_0.Equals(gc_p_1) ############################################################################### # Test FlattenTo2D(), SetCoordinateDimension(2) and SetCoordinateDimension(3) with Measured geometries -def ogr_geom_measured_geometries_to_2D_or_3D(): +def test_ogr_geom_measured_geometries_to_2D_or_3D(): list_wkt = [['POINT M (1 2 3)', 'POINT (1 2)', 'POINT Z (1 2 0)'], ['POINT ZM (1 2 3 4)', 'POINT (1 2)', 'POINT Z (1 2 3)'], @@ -4003,96 +2867,57 @@ def ogr_geom_measured_geometries_to_2D_or_3D(): geom2 = ogr.CreateGeometryFromWkb(wkb) if not geom.Equals(geom2): print(before) - print(geom2.ExportToIsoWkt()) - return 'fail' + pytest.fail(geom2.ExportToIsoWkt()) geom = ogr.CreateGeometryFromWkt(before) geom.FlattenTo2D() - if geom.ExportToIsoWkt() != after_2D: - gdaltest.post_reason('fail') - print(before) - print(after_2D) - print(geom.ExportToIsoWkt()) - return 'fail' + assert geom.ExportToIsoWkt() == after_2D, before geom = ogr.CreateGeometryFromWkt(before) geom.SetCoordinateDimension(2) - if geom.ExportToIsoWkt() != after_2D: - gdaltest.post_reason('fail') - print(before) - print(after_2D) - print(geom.ExportToIsoWkt()) - return 'fail' + assert geom.ExportToIsoWkt() == after_2D, before geom = ogr.CreateGeometryFromWkt(before) geom.SetCoordinateDimension(3) - if geom.ExportToIsoWkt() != after_3D: - gdaltest.post_reason('fail') - print(before) - print(after_3D) - print(geom.ExportToIsoWkt()) - return 'fail' + assert geom.ExportToIsoWkt() == after_3D, before # Test no-op geom = ogr.CreateGeometryFromWkt(before) geom.Set3D(geom.Is3D()) geom.SetMeasured(geom.IsMeasured()) - if geom.ExportToIsoWkt() != before: - gdaltest.post_reason('fail') - print(before) - print(geom.ExportToIsoWkt()) - return 'fail' + assert geom.ExportToIsoWkt() == before - if ogr.CreateGeometryFromWkt('POINT (1 2)').CoordinateDimension() != 2: - gdaltest.post_reason('fail') - return 'fail' + assert ogr.CreateGeometryFromWkt('POINT (1 2)').CoordinateDimension() == 2 - if ogr.CreateGeometryFromWkt('POINT M (1 2 3)').CoordinateDimension() != 3: - gdaltest.post_reason('fail') - return 'fail' + assert ogr.CreateGeometryFromWkt('POINT M (1 2 3)').CoordinateDimension() == 3 - if ogr.CreateGeometryFromWkt('POINT Z (1 2 3)').CoordinateDimension() != 3: - gdaltest.post_reason('fail') - return 'fail' + assert ogr.CreateGeometryFromWkt('POINT Z (1 2 3)').CoordinateDimension() == 3 - if ogr.CreateGeometryFromWkt('POINT ZM (1 2 3 4)').CoordinateDimension() != 4: - gdaltest.post_reason('fail') - return 'fail' + assert ogr.CreateGeometryFromWkt('POINT ZM (1 2 3 4)').CoordinateDimension() == 4 # Unrelated test. Test old-style unqualified non-bracketted ZM import g = ogr.CreateGeometryFromWkt('MULTIPOINT (1 2 3 4)') - if g.ExportToIsoWkt() != 'MULTIPOINT ZM ((1 2 3 4))': - gdaltest.post_reason('fail') - print(g.ExportToIsoWkt()) - return 'fail' - - return 'success' + assert g.ExportToIsoWkt() == 'MULTIPOINT ZM ((1 2 3 4))' ############################################################################### # Test PostGIS EWKT with XYM -def ogr_geom_postgis_ewkt_xym(): +def test_ogr_geom_postgis_ewkt_xym(): list_wkt = [['POINTM(1 2 3)', 'POINT M (1 2 3)'], ['GEOMETRYCOLLECTIONM(POINTM(1 2 3))', 'GEOMETRYCOLLECTION M (POINT M (1 2 3))'], ] for (before, after) in list_wkt: geom = ogr.CreateGeometryFromWkt(before) - if geom.ExportToIsoWkt() != after: - gdaltest.post_reason('fail') - print(before) - print(after) - print(geom.ExportToIsoWkt()) - return 'fail' - - return 'success' + assert geom.ExportToIsoWkt() == after, before + ############################################################################### # Test ogr.wkbCurve / ogr.wkbSurface -def ogr_geom_curve_surface(): +def test_ogr_geom_curve_surface(): tests = [[ogr.wkbCurve, "Curve"], [ogr.wkbCurveZ, "3D Curve"], @@ -4104,20 +2929,14 @@ def ogr_geom_curve_surface(): [ogr.wkbSurfaceZM, "3D Measured Surface"]] for (wkb_type, name) in tests: - if ogr.GeometryTypeToName(wkb_type) != name: - gdaltest.post_reason('fail') - print(wkb_type) - print(name) - print(ogr.GeometryTypeToName(wkb_type)) - return 'fail' - - return 'success' + assert ogr.GeometryTypeToName(wkb_type) == name + ############################################################################### # Test importing corrupted WKB -def ogr_geom_import_corrupted_wkb(): +def test_ogr_geom_import_corrupted_wkb(): list_wkt = ['POINT ZM (1 2 3 4)' 'LINESTRING ZM (1 2 3 4)' @@ -4158,10 +2977,7 @@ def ogr_geom_import_corrupted_wkb(): g = ogr.CreateGeometryFromWkb(str(wkb)) if g: g2 = ogr.CreateGeometryFromWkb(g.ExportToIsoWkb()) - if not g.Equals(g2): - gdaltest.post_reason('fail') - print(wkt, i, method) - return 'fail' + assert g.Equals(g2), (wkt, i, method) wkb[i] = init_val # Test truncation of the WKB @@ -4171,18 +2987,14 @@ def ogr_geom_import_corrupted_wkb(): g = ogr.CreateGeometryFromWkb(bytes(wkb[0:i])) else: g = ogr.CreateGeometryFromWkb(str(wkb[0:i])) - if g is not None: - gdaltest.post_reason('fail') - print(wkt, i) - return 'fail' - - return 'success' + assert g is None, (wkt, i) + ############################################################################### # Test conversions from/into triangle, TIN, PS -def ogr_geom_triangle_ps_tin_conversion(): +def test_ogr_geom_triangle_ps_tin_conversion(): wkts = ["TRIANGLE ((0 0,0 1,1 1,0 0))", "POLYGON ((0 0,0 1,1 1,0 0))", @@ -4204,120 +3016,74 @@ def ogr_geom_triangle_ps_tin_conversion(): wkt_expected = wkt_target if (g.GetGeometryType() == ogr.wkbTIN or g.GetGeometryType() == ogr.wkbPolyhedralSurface) and g2.GetGeometryType() == ogr.wkbCurvePolygon: wkt_expected = wkt - if got_wkt != wkt_expected: - gdaltest.post_reason('fail') - print(wkt, wkt_target, got_wkt, wkt_expected) - return 'fail' + assert got_wkt == wkt_expected, (wkt, wkt_target, got_wkt, wkt_expected) g = ogr.ForceTo(ogr.CreateGeometryFromWkt('POLYGON ((0 0,0 1,1 1,1 0,0 0))'), ogr.wkbTriangle) - if g.GetGeometryType() != ogr.wkbPolygon: - gdaltest.post_reason('fail') - print(g.ExportToWkt()) - return 'fail' + assert g.GetGeometryType() == ogr.wkbPolygon, g.ExportToWkt() g = ogr.ForceTo(ogr.CreateGeometryFromWkt('POLYHEDRALSURFACE (((0 0,0 1,1 1,1 0,0 0)))'), ogr.wkbTIN) - if g.GetGeometryType() != ogr.wkbPolyhedralSurface: - gdaltest.post_reason('fail') - print(g.ExportToWkt()) - return 'fail' + assert g.GetGeometryType() == ogr.wkbPolyhedralSurface, g.ExportToWkt() g = ogr.ForceTo(ogr.CreateGeometryFromWkt('GEOMETRYCOLLECTION (POLYHEDRALSURFACE (((0 0,0 1,1 1,1 0,0 0))))'), ogr.wkbMultiPolygon) - if g.ExportToWkt() != 'MULTIPOLYGON (((0 0,0 1,1 1,1 0,0 0)))': - gdaltest.post_reason('fail') - print(g.ExportToWkt()) - return 'fail' + assert g.ExportToWkt() == 'MULTIPOLYGON (((0 0,0 1,1 1,1 0,0 0)))' g = ogr.ForceTo(ogr.CreateGeometryFromWkt('GEOMETRYCOLLECTION (TRIANGLE ((0 0,0 1,1 1,0 0)))'), ogr.wkbMultiPolygon) - if g.ExportToWkt() != 'MULTIPOLYGON (((0 0,0 1,1 1,0 0)))': - gdaltest.post_reason('fail') - print(g.ExportToWkt()) - return 'fail' + assert g.ExportToWkt() == 'MULTIPOLYGON (((0 0,0 1,1 1,0 0)))' g = ogr.ForceTo(ogr.CreateGeometryFromWkt('MULTIPOLYGON (((0 0,0 1,1 1,0 0)))'), ogr.wkbGeometryCollection) - if g.ExportToWkt() != 'GEOMETRYCOLLECTION (POLYGON ((0 0,0 1,1 1,0 0)))': - gdaltest.post_reason('fail') - print(g.ExportToWkt()) - return 'fail' + assert g.ExportToWkt() == 'GEOMETRYCOLLECTION (POLYGON ((0 0,0 1,1 1,0 0)))' g = ogr.ForceTo(ogr.CreateGeometryFromWkt('TRIANGLE ((0 0,0 1,1 1,0 0))'), ogr.wkbGeometryCollection) - if g.ExportToWkt() != 'GEOMETRYCOLLECTION (TRIANGLE ((0 0,0 1,1 1,0 0)))': - gdaltest.post_reason('fail') - print(g.ExportToWkt()) - return 'fail' + assert g.ExportToWkt() == 'GEOMETRYCOLLECTION (TRIANGLE ((0 0,0 1,1 1,0 0)))' g = ogr.ForceTo(ogr.CreateGeometryFromWkt('TIN (((0 0,0 1,1 1,0 0)))'), ogr.wkbGeometryCollection) - if g.ExportToWkt() != 'GEOMETRYCOLLECTION (POLYGON ((0 0,0 1,1 1,0 0)))': - gdaltest.post_reason('fail') - print(g.ExportToWkt()) - return 'fail' + assert g.ExportToWkt() == 'GEOMETRYCOLLECTION (POLYGON ((0 0,0 1,1 1,0 0)))' g = ogr.ForceTo(ogr.CreateGeometryFromWkt('POLYHEDRALSURFACE (((0 0,0 1,1 1,0 0)))'), ogr.wkbGeometryCollection) - if g.ExportToWkt() != 'GEOMETRYCOLLECTION (POLYGON ((0 0,0 1,1 1,0 0)))': - gdaltest.post_reason('fail') - print(g.ExportToWkt()) - return 'fail' - - return 'success' + assert g.ExportToWkt() == 'GEOMETRYCOLLECTION (POLYGON ((0 0,0 1,1 1,0 0)))' ############################################################################### -def ogr_geom_multipoint_envelope_bug(): +def test_ogr_geom_multipoint_envelope_bug(): g = ogr.CreateGeometryFromWkt('MULTIPOINT(0 0,1 1)') minx, maxx, miny, maxy = g.GetEnvelope() - if (minx, maxx, miny, maxy) != (0, 1, 0, 1): - gdaltest.post_reason('fail') - print(minx, maxx, miny, maxy) - return 'fail' + assert (minx, maxx, miny, maxy) == (0, 1, 0, 1) g = ogr.CreateGeometryFromWkt('MULTIPOINT(0 0 0,1 1 1)') minx, maxx, miny, maxy, minz, maxz = g.GetEnvelope3D() - if (minx, maxx, miny, maxy, minz, maxz) != (0, 1, 0, 1, 0, 1): - gdaltest.post_reason('fail') - print(minx, maxx, miny, maxy, minz, maxz) - return 'fail' - - return 'success' + assert (minx, maxx, miny, maxy, minz, maxz) == (0, 1, 0, 1, 0, 1) ############################################################################### -def ogr_geom_polygon_empty_ring(): +def test_ogr_geom_polygon_empty_ring(): g = ogr.Geometry(ogr.wkbPolygon) g2 = ogr.Geometry(ogr.wkbLinearRing) g.AddGeometryDirectly(g2) - if not g.IsEmpty(): - return 'fail' - - return 'success' + assert g.IsEmpty() ############################################################################### -def ogr_geom_polygon_intersects_point(): +def test_ogr_geom_polygon_intersects_point(): if not ogrtest.have_geos(): - return 'skip' + pytest.skip() poly = ogr.CreateGeometryFromWkt('POLYGON((0 0,5 5,10 0,0 0))') point = ogr.Geometry(ogr.wkbPoint) point.AddPoint(10, 0) - if poly.Intersects(point) != 1: - gdaltest.post_reason('fail') - return 'fail' - if poly.Contains(point) != 0: - gdaltest.post_reason('fail') - return 'fail' - - return 'success' + assert poly.Intersects(point) == 1 + assert poly.Contains(point) == 0 ############################################################################### # Test fix for #7128 -def ogr_geom_geometrycollection(): +def test_ogr_geom_geometrycollection(): wkt_list = ['GEOMETRYCOLLECTION (POINT EMPTY)', 'GEOMETRYCOLLECTION (LINESTRING EMPTY)', @@ -4336,171 +3102,96 @@ def ogr_geom_geometrycollection(): 'GEOMETRYCOLLECTION (TIN EMPTY)'] for wkt in wkt_list: g = ogr.CreateGeometryFromWkt(wkt) - if g.ExportToWkt() != wkt: - print(g.ExportToWkt(), wkt) - return 'fail' - - return 'success' + assert g.ExportToWkt() == wkt + ############################################################################### # Test fix for #7126 -def ogr_geom_assignspatialref(): +def test_ogr_geom_assignspatialref(): g = ogr.CreateGeometryFromWkt('GEOMETRYCOLLECTION(POLYGON((0 0,0 1,1 1,0 0)),COMPOUNDCURVE(CIRCULARSTRING(0 0,1 1,2 0)),POLYHEDRALSURFACE(((0 0,0 1,1 1,0 0))))') sr = osr.SpatialReference() sr.ImportFromEPSG(4326) g.AssignSpatialReference(sr) - if g.GetGeometryRef(0).GetSpatialReference().ExportToWkt() != sr.ExportToWkt(): - return 'fail' - if g.GetGeometryRef(0).GetGeometryRef(0).GetSpatialReference().ExportToWkt() != sr.ExportToWkt(): - return 'fail' - if g.GetGeometryRef(1).GetSpatialReference().ExportToWkt() != sr.ExportToWkt(): - return 'fail' - if g.GetGeometryRef(1).GetGeometryRef(0).GetSpatialReference().ExportToWkt() != sr.ExportToWkt(): - return 'fail' - if g.GetGeometryRef(2).GetSpatialReference().ExportToWkt() != sr.ExportToWkt(): - return 'fail' - if g.GetGeometryRef(2).GetGeometryRef(0).GetSpatialReference().ExportToWkt() != sr.ExportToWkt(): - return 'fail' - - return 'success' + assert g.GetGeometryRef(0).GetSpatialReference().ExportToWkt() == sr.ExportToWkt() + assert g.GetGeometryRef(0).GetGeometryRef(0).GetSpatialReference().ExportToWkt() == sr.ExportToWkt() + assert g.GetGeometryRef(1).GetSpatialReference().ExportToWkt() == sr.ExportToWkt() + assert g.GetGeometryRef(1).GetGeometryRef(0).GetSpatialReference().ExportToWkt() == sr.ExportToWkt() + assert g.GetGeometryRef(2).GetSpatialReference().ExportToWkt() == sr.ExportToWkt() + assert g.GetGeometryRef(2).GetGeometryRef(0).GetSpatialReference().ExportToWkt() == sr.ExportToWkt() ############################################################################### -def ogr_geom_swapxy(): +def test_ogr_geom_swapxy(): g = ogr.CreateGeometryFromWkt('GEOMETRYCOLLECTION(POINT(1 2),LINESTRING(1 2,2 3),POLYGON((0 0,0 1,1 1,0 0)),COMPOUNDCURVE(CIRCULARSTRING(0 0,1 1,2 0)),POLYHEDRALSURFACE(((0 0,0 1,1 1,0 0))))') g.SwapXY() - if g.ExportToWkt() != 'GEOMETRYCOLLECTION (POINT (2 1),LINESTRING (2 1,3 2),POLYGON ((0 0,1 0,1 1,0 0)),COMPOUNDCURVE (CIRCULARSTRING (0 0,1 1,0 2)),POLYHEDRALSURFACE (((0 0,1 0,1 1,0 0))))': - print(g) - return 'fail' - - return 'success' + assert g.ExportToWkt() == 'GEOMETRYCOLLECTION (POINT (2 1),LINESTRING (2 1,3 2),POLYGON ((0 0,1 0,1 1,0 0)),COMPOUNDCURVE (CIRCULARSTRING (0 0,1 1,0 2)),POLYHEDRALSURFACE (((0 0,1 0,1 1,0 0))))' ############################################################################### -def ogr_geom_remove_geometry(): +def test_ogr_geom_remove_geometry(): # With GEOMETRYCOLLECTION g = ogr.CreateGeometryFromWkt('GEOMETRYCOLLECTION (POINT (1 2),LINESTRING (1 2,2 3),POINT (3 4))') - if g.RemoveGeometry(3) == 0 or g.RemoveGeometry(-2) == 0: - gdaltest.post_reason('fail') - return 'fail' - - if g.RemoveGeometry(1) != 0: - gdaltest.post_reason('fail') - return 'fail' - if g.ExportToWkt() != 'GEOMETRYCOLLECTION (POINT (1 2),POINT (3 4))': - gdaltest.post_reason('fail') - print(g) - return 'fail' - - if g.RemoveGeometry(1) != 0: - gdaltest.post_reason('fail') - return 'fail' - if g.ExportToWkt() != 'GEOMETRYCOLLECTION (POINT (1 2))': - gdaltest.post_reason('fail') - print(g) - return 'fail' - - if g.RemoveGeometry(0) != 0: - gdaltest.post_reason('fail') - return 'fail' - if g.ExportToWkt() != 'GEOMETRYCOLLECTION EMPTY': - gdaltest.post_reason('fail') - print(g) - return 'fail' + assert not (g.RemoveGeometry(3) == 0 or g.RemoveGeometry(-2) == 0) + + assert g.RemoveGeometry(1) == 0 + assert g.ExportToWkt() == 'GEOMETRYCOLLECTION (POINT (1 2),POINT (3 4))' + + assert g.RemoveGeometry(1) == 0 + assert g.ExportToWkt() == 'GEOMETRYCOLLECTION (POINT (1 2))' + + assert g.RemoveGeometry(0) == 0 + assert g.ExportToWkt() == 'GEOMETRYCOLLECTION EMPTY' g = ogr.CreateGeometryFromWkt('GEOMETRYCOLLECTION (POINT (1 2),LINESTRING (1 2,2 3),POINT (3 4))') - if g.RemoveGeometry(-1) != 0: - gdaltest.post_reason('fail') - return 'fail' - if g.ExportToWkt() != 'GEOMETRYCOLLECTION EMPTY': - gdaltest.post_reason('fail') - print(g) - return 'fail' + assert g.RemoveGeometry(-1) == 0 + assert g.ExportToWkt() == 'GEOMETRYCOLLECTION EMPTY' # With POLYHEDRALSURFACE/TIN g = ogr.CreateGeometryFromWkt('TIN (((0 0,0 1,1 1,0 0)),((0 0,1 0,1 1,0 0)))') - if g.RemoveGeometry(2) == 0 or g.RemoveGeometry(-2) == 0: - gdaltest.post_reason('fail') - return 'fail' - - if g.RemoveGeometry(1) != 0: - gdaltest.post_reason('fail') - return 'fail' - if g.ExportToWkt() != 'TIN (((0 0,0 1,1 1,0 0)))': - gdaltest.post_reason('fail') - print(g) - return 'fail' - - if g.RemoveGeometry(0) != 0: - gdaltest.post_reason('fail') - return 'fail' - if g.ExportToWkt() != 'TIN EMPTY': - gdaltest.post_reason('fail') - print(g) - return 'fail' + assert not (g.RemoveGeometry(2) == 0 or g.RemoveGeometry(-2) == 0) + + assert g.RemoveGeometry(1) == 0 + assert g.ExportToWkt() == 'TIN (((0 0,0 1,1 1,0 0)))' + + assert g.RemoveGeometry(0) == 0 + assert g.ExportToWkt() == 'TIN EMPTY' g = ogr.CreateGeometryFromWkt('TIN (((0 0,0 1,1 1,0 0)),((0 0,1 0,1 1,0 0)))') - if g.RemoveGeometry(-1) != 0: - gdaltest.post_reason('fail') - return 'fail' - if g.ExportToWkt() != 'TIN EMPTY': - gdaltest.post_reason('fail') - print(g) - return 'fail' + assert g.RemoveGeometry(-1) == 0 + assert g.ExportToWkt() == 'TIN EMPTY' # With POLYGON g = ogr.CreateGeometryFromWkt('POLYGON ((0 0,0 10,10 10,10 0,0 0),(1 1,1 9,9 9,1 1))') - if g.RemoveGeometry(2) == 0 or g.RemoveGeometry(-2) == 0: - gdaltest.post_reason('fail') - return 'fail' - - if g.RemoveGeometry(1) != 0: - gdaltest.post_reason('fail') - return 'fail' - if g.ExportToWkt() != 'POLYGON ((0 0,0 10,10 10,10 0,0 0))': - gdaltest.post_reason('fail') - print(g) - return 'fail' - - if g.RemoveGeometry(0) != 0: - gdaltest.post_reason('fail') - return 'fail' - if g.ExportToWkt() != 'POLYGON EMPTY': - gdaltest.post_reason('fail') - print(g) - return 'fail' + assert not (g.RemoveGeometry(2) == 0 or g.RemoveGeometry(-2) == 0) + + assert g.RemoveGeometry(1) == 0 + assert g.ExportToWkt() == 'POLYGON ((0 0,0 10,10 10,10 0,0 0))' + + assert g.RemoveGeometry(0) == 0 + assert g.ExportToWkt() == 'POLYGON EMPTY' g = ogr.CreateGeometryFromWkt('POLYGON ((0 0,0 10,10 10,10 0,0 0),(1 1,1 9,9 9,1 1))') - if g.RemoveGeometry(-1) != 0: - gdaltest.post_reason('fail') - return 'fail' - if g.ExportToWkt() != 'POLYGON EMPTY': - gdaltest.post_reason('fail') - print(g) - return 'fail' + assert g.RemoveGeometry(-1) == 0 + assert g.ExportToWkt() == 'POLYGON EMPTY' # Unsupported type g = ogr.CreateGeometryFromWkt('POINT (0 0)') - if g.RemoveGeometry(0) == 0: - gdaltest.post_reason('fail') - return 'fail' - - return 'success' + assert g.RemoveGeometry(0) != 0 ############################################################################### -def ogr_geom_sfcgal(): +def test_ogr_geom_sfcgal(): if not ogrtest.have_sfcgal(): - return 'skip' + pytest.skip() g1 = ogr.CreateGeometryFromWkt('TIN EMPTY') @@ -4514,114 +3205,25 @@ def ogr_geom_sfcgal(): g2 = ogr.CreateGeometryFromWkt('CURVEPOLYGON EMPTY') g1.Distance(g2) - return 'success' - ############################################################################### -def ogr_geom_cannot_add_triangle_to_multisurface(): +def test_ogr_geom_cannot_add_triangle_to_multisurface(): g = ogr.Geometry(ogr.wkbMultiSurface) - if g.AddGeometry(ogr.Geometry(ogr.wkbTriangle)) == 0: - return 'fail' - return 'success' + assert g.AddGeometry(ogr.Geometry(ogr.wkbTriangle)) != 0 ############################################################################### -def ogr_geom_force_polygonzm_to_linestring(): +def test_ogr_geom_force_polygonzm_to_linestring(): g = ogr.CreateGeometryFromWkt('POLYGON ZM ((0 0 10 20,0 1 30 40,1 1 50 60,0 0 10 70))') wkt = ogr.ForceToLineString(g).ExportToIsoWkt() - if wkt != 'LINESTRING ZM (0 0 10 20,0 1 30 40,1 1 50 60,0 0 10 70)': - print(wkt) - return 'fail' - return 'success' + assert wkt == 'LINESTRING ZM (0 0 10 20,0 1 30 40,1 1 50 60,0 0 10 70)' ############################################################################### # cleanup -def ogr_geom_cleanup(): - return 'success' - - -gdaltest_list = [ - ogr_geom_area, - ogr_geom_polyhedral_surface, - ogr_geom_tin, - ogr_geom_area_triangle, - ogr_geom_area_linearring, - ogr_geom_area_linearring_big_offset, - ogr_geom_area_geometrycollection, - ogr_geom_is_empty, - ogr_geom_is_empty_triangle, - ogr_geom_pickle, - ogr_geom_boundary_point, - ogr_geom_boundary_multipoint, - ogr_geom_boundary_linestring, - ogr_geom_boundary_polygon, - ogr_geom_build_from_edges_1, - ogr_geom_build_from_edges_2, - ogr_geom_build_from_edges_3, - ogr_geom_build_from_edges_4, - ogr_geom_area_empty_linearring, - ogr_geom_transform_to, - ogr_geom_transform, - ogr_geom_closerings, - ogr_geom_segmentize, - ogr_geom_value, - ogr_geom_flattenTo2D, - ogr_geom_flattenTo2D_triangle, - ogr_geom_linestring_limits, - ogr_geom_coord_round, - ogr_geom_coord_round_2, - ogr_geom_area_point, - ogr_geom_length_point, - ogr_geom_length_multilinestring, - ogr_geom_length_geometrycollection, - ogr_geom_empty_triangle, - ogr_geom_triangle, - ogr_geom_triangle_invalid_wkt, - ogr_geom_triangle_sfcgal, - ogr_geom_empty, - ogr_geom_getpoints, - ogr_geom_mixed_coordinate_dimension, - ogr_geom_getenvelope3d, - ogr_geom_z_empty, - ogr_geom_getlineargeometry, - ogr_geom_getdimension, - ogr_geom_circularstring, - ogr_geom_compoundcurve, - ogr_geom_curvepolygon, - ogr_geom_multicurve, - ogr_geom_multisurface, - ogr_geom_getcurvegeometry, - ogr_geom_gt_functions, - ogr_geom_api_limit_tests, - ogr_geom_equals, - ogr_geom_measured_geometries_to_2D_or_3D, - ogr_geom_postgis_ewkt_xym, - ogr_geom_curve_surface, - ogr_geom_import_corrupted_wkb, - ogr_geom_triangle_ps_tin_conversion, - ogr_geom_multipoint_envelope_bug, - ogr_geom_polygon_empty_ring, - ogr_geom_polygon_intersects_point, - ogr_geom_geometrycollection, - ogr_geom_assignspatialref, - ogr_geom_swapxy, - ogr_geom_remove_geometry, - ogr_geom_sfcgal, - ogr_geom_cannot_add_triangle_to_multisurface, - ogr_geom_force_polygonzm_to_linestring, - ogr_geom_cleanup] - -# gdaltest_list = [ ogr_geom_triangle_ps_tin_conversion ] - -if __name__ == '__main__': - - gdaltest.setup_run('ogr_geom') - - gdaltest.run_tests(gdaltest_list) - - sys.exit(gdaltest.summarize()) +def test_ogr_geom_cleanup(): + pass diff --git a/autotest/ogr/ogr_georss.py b/autotest/ogr/ogr_georss.py index 040196010ad6..39f9164b2d81 100755 --- a/autotest/ogr/ogr_georss.py +++ b/autotest/ogr/ogr_georss.py @@ -30,17 +30,16 @@ ############################################################################### import os -import sys -sys.path.append('../pymod') import gdaltest from osgeo import ogr from osgeo import osr from osgeo import gdal +import pytest -def ogr_georss_init(): +def test_ogr_georss_init(): ds = ogr.Open('data/atom_rfc_sample.xml') if ds is None: @@ -78,8 +77,6 @@ def ogr_georss_init(): ('content_xml_lang', 'en', ogr.OFTString), ('content_xml_base', 'http://diveintomark.org/', ogr.OFTString)] - return 'success' - ############################################################################### # Used by ogr_georss_1 and ogr_georss_1ter @@ -87,33 +84,27 @@ def ogr_georss_init(): def ogr_georss_test_atom(filename): if not gdaltest.georss_read_support: - return 'skip' + pytest.skip() ds = ogr.Open(filename) lyr = ds.GetLayerByName('georss') - if lyr.GetSpatialRef() is not None: - gdaltest.post_reason('No spatial ref expected') - return 'fail' + assert lyr.GetSpatialRef() is None, 'No spatial ref expected' feat = lyr.GetNextFeature() for field_value in gdaltest.atom_field_values: - if feat.GetFieldAsString(field_value[0]) != field_value[1]: - gdaltest.post_reason('For field "%s", got "%s" instead of "%s"' % (field_value[0], feat.GetFieldAsString(field_value[0]), field_value[1])) - return 'fail' - - if feat.GetFieldAsString('content').find('<div xmlns="http://www.w3.org/1999/xhtml">') == -1: - gdaltest.post_reason('For field "%s", got "%s"' % ('content', feat.GetFieldAsString('content'))) - return 'fail' + assert feat.GetFieldAsString(field_value[0]) == field_value[1], \ + ('For field "%s", got "%s" instead of "%s"' % (field_value[0], feat.GetFieldAsString(field_value[0]), field_value[1])) - return 'success' + assert feat.GetFieldAsString('content').find('<div xmlns="http://www.w3.org/1999/xhtml">') != -1, \ + ('For field "%s", got "%s"' % ('content', feat.GetFieldAsString('content'))) ############################################################################### # Test reading an ATOM document without any geometry -def ogr_georss_1(): +def test_ogr_georss_1(): return ogr_georss_test_atom('data/atom_rfc_sample.xml') @@ -121,7 +112,7 @@ def ogr_georss_1(): # Test reading an ATOM document with atom: prefiw -def ogr_georss_1_atom_ns(): +def test_ogr_georss_1_atom_ns(): return ogr_georss_test_atom('data/atom_rfc_sample_atom_ns.xml') @@ -129,7 +120,7 @@ def ogr_georss_1_atom_ns(): # Test writing a Atom 1.0 document (doesn't need read support) -def ogr_georss_1bis(): +def test_ogr_georss_1bis(): try: os.remove('tmp/test_atom.xml') @@ -148,19 +139,15 @@ def ogr_georss_1bis(): dst_feat.SetField(field_value[0], field_value[1]) dst_feat.SetField('content', '<div xmlns="http://www.w3.org/1999/xhtml"><p><i>[Update: The Atom draft is finished.]</i></p></div>') - if lyr.CreateFeature(dst_feat) != 0: - gdaltest.post_reason('CreateFeature failed.') - return 'fail' + assert lyr.CreateFeature(dst_feat) == 0, 'CreateFeature failed.' ds = None - return 'success' - ############################################################################### # Test reading document created at previous step -def ogr_georss_1ter(): +def test_ogr_georss_1ter(): return ogr_georss_test_atom('tmp/test_atom.xml') @@ -171,79 +158,59 @@ def ogr_georss_1ter(): def ogr_georss_test_rss(filename, only_first_feature): if not gdaltest.georss_read_support: - return 'skip' + pytest.skip() ds = ogr.Open(filename) - if ds is None: - return 'fail' + assert ds is not None lyr = ds.GetLayer(0) srs = osr.SpatialReference() srs.SetWellKnownGeogCS('WGS84') - if lyr.GetSpatialRef() is None or not lyr.GetSpatialRef().IsSame(srs): - gdaltest.post_reason('SRS is not the one expected.') - return 'fail' + assert lyr.GetSpatialRef() is not None and lyr.GetSpatialRef().IsSame(srs), \ + 'SRS is not the one expected.' if lyr.GetSpatialRef().ExportToWkt().find('AXIS["Latitude",NORTH],AXIS["Longitude",EAST]') != -1: lyr.GetSpatialRef().ExportToWkt() - gdaltest.post_reason('AXIS definition found with latitude/longitude order!') - return 'fail' + pytest.fail('AXIS definition found with latitude/longitude order!') feat = lyr.GetNextFeature() expected_wkt = 'POINT (2 49)' - if feat.GetGeometryRef().ExportToWkt() != expected_wkt: - print(('%s' % feat.GetGeometryRef().ExportToWkt())) - return 'fail' - if feat.GetFieldAsString('title') != 'A point': - return 'fail' - if feat.GetFieldAsString('author') != 'Author': - return 'fail' - if feat.GetFieldAsString('link') != 'http://gdal.org': - return 'fail' - if feat.GetFieldAsString('pubDate') != '2008/12/07 20:13:00+02': - return 'fail' - if feat.GetFieldAsString('category') != 'First category': - return 'fail' - if feat.GetFieldAsString('category_domain') != 'first_domain': - return 'fail' - if feat.GetFieldAsString('category2') != 'Second category': - return 'fail' - if feat.GetFieldAsString('category2_domain') != 'second_domain': - return 'fail' + assert feat.GetGeometryRef().ExportToWkt() == expected_wkt, \ + ('%s' % feat.GetGeometryRef().ExportToWkt()) + assert feat.GetFieldAsString('title') == 'A point' + assert feat.GetFieldAsString('author') == 'Author' + assert feat.GetFieldAsString('link') == 'http://gdal.org' + assert feat.GetFieldAsString('pubDate') == '2008/12/07 20:13:00+02' + assert feat.GetFieldAsString('category') == 'First category' + assert feat.GetFieldAsString('category_domain') == 'first_domain' + assert feat.GetFieldAsString('category2') == 'Second category' + assert feat.GetFieldAsString('category2_domain') == 'second_domain' feat = lyr.GetNextFeature() expected_wkt = 'LINESTRING (2 48,2.1 48.1,2.2 48.0)' - if only_first_feature is False and feat.GetGeometryRef().ExportToWkt() != expected_wkt: - print(('%s' % feat.GetGeometryRef().ExportToWkt())) - return 'fail' - if feat.GetFieldAsString('title') != 'A line': - return 'fail' + assert only_first_feature is not False or feat.GetGeometryRef().ExportToWkt() == expected_wkt, \ + ('%s' % feat.GetGeometryRef().ExportToWkt()) + assert feat.GetFieldAsString('title') == 'A line' feat = lyr.GetNextFeature() expected_wkt = 'POLYGON ((2 50,2.1 50.1,2.2 48.1,2.1 46.1,2 50))' - if only_first_feature is False and feat.GetGeometryRef().ExportToWkt() != expected_wkt: - print(('%s' % feat.GetGeometryRef().ExportToWkt())) - return 'fail' - if feat.GetFieldAsString('title') != 'A polygon': - return 'fail' + assert only_first_feature is not False or feat.GetGeometryRef().ExportToWkt() == expected_wkt, \ + ('%s' % feat.GetGeometryRef().ExportToWkt()) + assert feat.GetFieldAsString('title') == 'A polygon' feat = lyr.GetNextFeature() expected_wkt = 'POLYGON ((2 49,2.0 49.5,2.2 49.5,2.2 49.0,2 49))' - if only_first_feature is False and feat.GetGeometryRef().ExportToWkt() != expected_wkt: - print(('%s' % feat.GetGeometryRef().ExportToWkt())) - return 'fail' - if feat.GetFieldAsString('title') != 'A box': - return 'fail' - - return 'success' + assert only_first_feature is not False or feat.GetGeometryRef().ExportToWkt() == expected_wkt, \ + ('%s' % feat.GetGeometryRef().ExportToWkt()) + assert feat.GetFieldAsString('title') == 'A box' ############################################################################### # Test reading a RSS 2.0 document with GeoRSS simple geometries -def ogr_georss_2(): +def test_ogr_georss_2(): return ogr_georss_test_rss('data/test_georss_simple.xml', False) @@ -251,10 +218,10 @@ def ogr_georss_2(): # Test reading a RSS 2.0 document with GeoRSS GML geometries -def ogr_georss_3(): +def test_ogr_georss_3(): if not gdaltest.have_gml_reader: - return 'skip' + pytest.skip() return ogr_georss_test_rss('data/test_georss_gml.xml', False) @@ -292,9 +259,7 @@ def ogr_georss_create(filename, options): dst_feat.SetField('category2_domain', 'second_domain') dst_feat.SetGeometry(ogr.CreateGeometryFromWkt('POINT (2 49)')) - if lyr.CreateFeature(dst_feat) != 0: - gdaltest.post_reason('CreateFeature failed.') - return 'fail' + assert lyr.CreateFeature(dst_feat) == 0, 'CreateFeature failed.' dst_feat = ogr.Feature(feature_def=lyr.GetLayerDefn()) dst_feat.SetField('title', 'A line') @@ -303,9 +268,7 @@ def ogr_georss_create(filename, options): dst_feat.SetField('pubDate', '2008/12/07 20:13:00+02') dst_feat.SetGeometry(ogr.CreateGeometryFromWkt('LINESTRING (2 48,2.1 48.1,2.2 48.0)')) - if lyr.CreateFeature(dst_feat) != 0: - gdaltest.post_reason('CreateFeature failed.') - return 'fail' + assert lyr.CreateFeature(dst_feat) == 0, 'CreateFeature failed.' dst_feat = ogr.Feature(feature_def=lyr.GetLayerDefn()) dst_feat.SetField('title', 'A polygon') @@ -314,9 +277,7 @@ def ogr_georss_create(filename, options): dst_feat.SetField('pubDate', '2008/12/07 20:13:00+02') dst_feat.SetGeometry(ogr.CreateGeometryFromWkt('POLYGON ((2 50,2.1 50.1,2.2 48.1,2.1 46.1,2 50))')) - if lyr.CreateFeature(dst_feat) != 0: - gdaltest.post_reason('CreateFeature failed.') - return 'fail' + assert lyr.CreateFeature(dst_feat) == 0, 'CreateFeature failed.' dst_feat = ogr.Feature(feature_def=lyr.GetLayerDefn()) dst_feat.SetField('title', 'A box') @@ -325,35 +286,26 @@ def ogr_georss_create(filename, options): dst_feat.SetField('pubDate', '2008/12/07 20:13:00+02') dst_feat.SetGeometry(ogr.CreateGeometryFromWkt('POLYGON ((2 49,2.0 49.5,2.2 49.5,2.2 49.0,2 49))')) - if lyr.CreateFeature(dst_feat) != 0: - gdaltest.post_reason('CreateFeature failed.') - return 'fail' + assert lyr.CreateFeature(dst_feat) == 0, 'CreateFeature failed.' ds = None - return 'success' - ############################################################################### # Test writing a RSS 2.0 document in Simple dialect (doesn't need read support) -def ogr_georss_4(): +def test_ogr_georss_4(): - if ogr_georss_create('tmp/test_rss2.xml', []) != 'success': - return 'fail' + ogr_georss_create('tmp/test_rss2.xml', []) content = open('tmp/test_rss2.xml').read() - if content.find('<georss:point>49 2') == -1: - print(('%s' % content)) - return 'fail' - - return 'success' + assert content.find('<georss:point>49 2') != -1, ('%s' % content) ############################################################################### # Test reading document created at previous step -def ogr_georss_5(): +def test_ogr_georss_5(): return ogr_georss_test_rss('tmp/test_rss2.xml', False) @@ -361,25 +313,21 @@ def ogr_georss_5(): # Test writing a RSS 2.0 document in GML dialect (doesn't need read support) -def ogr_georss_6(): +def test_ogr_georss_6(): - if ogr_georss_create('tmp/test_rss2.xml', ['GEOM_DIALECT=GML']) != 'success': - return 'fail' + ogr_georss_create('tmp/test_rss2.xml', ['GEOM_DIALECT=GML']) content = open('tmp/test_rss2.xml').read() - if content.find('<georss:where><gml:Point><gml:pos>49 2') == -1: - print(('%s' % content)) - return 'fail' - - return 'success' + assert content.find('<georss:where><gml:Point><gml:pos>49 2') != -1, \ + ('%s' % content) ############################################################################### # Test reading document created at previous step -def ogr_georss_7(): +def test_ogr_georss_7(): if not gdaltest.have_gml_reader: - return 'skip' + pytest.skip() return ogr_georss_test_rss('tmp/test_rss2.xml', False) @@ -387,23 +335,19 @@ def ogr_georss_7(): # Test writing a RSS 2.0 document in W3C Geo dialect (doesn't need read support) -def ogr_georss_8(): +def test_ogr_georss_8(): - if ogr_georss_create('tmp/test_rss2.xml', ['GEOM_DIALECT=W3C_GEO']) != 'success': - return 'fail' + ogr_georss_create('tmp/test_rss2.xml', ['GEOM_DIALECT=W3C_GEO']) content = open('tmp/test_rss2.xml').read() - if content.find('<geo:lat>49') == -1 or content.find('<geo:long>2') == -1: - print(('%s' % content)) - return 'fail' - - return 'success' + assert not (content.find('<geo:lat>49') == -1 or content.find('<geo:long>2') == -1), \ + ('%s' % content) ############################################################################### # Test reading document created at previous step -def ogr_georss_9(): +def test_ogr_georss_9(): return ogr_georss_test_rss('tmp/test_rss2.xml', True) @@ -411,7 +355,7 @@ def ogr_georss_9(): # Test writing a RSS 2.0 document in GML dialect with EPSG:32631 -def ogr_georss_10(): +def test_ogr_georss_10(): try: os.remove('tmp/test32631.rss') except OSError: @@ -427,9 +371,7 @@ def ogr_georss_10(): except: lyr = None gdal.PopErrorHandler() - if lyr is not None: - gdaltest.post_reason('should not have accepted EPSG:32631 with GEOM_DIALECT != GML') - return 'fail' + assert lyr is None, 'should not have accepted EPSG:32631 with GEOM_DIALECT != GML' ds = None @@ -444,29 +386,24 @@ def ogr_georss_10(): dst_feat = ogr.Feature(feature_def=lyr.GetLayerDefn()) dst_feat.SetGeometry(ogr.CreateGeometryFromWkt('POINT (500000 4000000)')) - if lyr.CreateFeature(dst_feat) != 0: - gdaltest.post_reason('CreateFeature failed.') - return 'fail' + assert lyr.CreateFeature(dst_feat) == 0, 'CreateFeature failed.' ds = None content = open('tmp/test32631.rss').read() - if content.find('<georss:where><gml:Point srsName="urn:ogc:def:crs:EPSG::32631"><gml:pos>500000 4000000') == -1: - print(('%s' % content)) - return 'fail' - - return 'success' + assert content.find('<georss:where><gml:Point srsName="urn:ogc:def:crs:EPSG::32631"><gml:pos>500000 4000000') != -1, \ + ('%s' % content) ############################################################################### # Test reading document created at previous step -def ogr_georss_11(): +def test_ogr_georss_11(): if not gdaltest.georss_read_support: - return 'skip' + pytest.skip() if not gdaltest.have_gml_reader: - return 'skip' + pytest.skip() ds = ogr.Open('tmp/test32631.rss') lyr = ds.GetLayer(0) @@ -474,62 +411,52 @@ def ogr_georss_11(): srs = osr.SpatialReference() srs.ImportFromEPSG(32631) - if lyr.GetSpatialRef() is None or not lyr.GetSpatialRef().IsSame(srs): - gdaltest.post_reason('SRS is not the one expected.') - return 'fail' + assert lyr.GetSpatialRef() is not None and lyr.GetSpatialRef().IsSame(srs), \ + 'SRS is not the one expected.' if lyr.GetSpatialRef().ExportToWkt().find('AXIS["Easting",EAST],AXIS["Northing",NORTH]') == -1: print(('%s' % lyr.GetSpatialRef().ExportToWkt())) - gdaltest.post_reason('AXIS definition expected is AXIS["Easting",EAST],AXIS["Northing",NORTH]!') - return 'fail' + pytest.fail('AXIS definition expected is AXIS["Easting",EAST],AXIS["Northing",NORTH]!') feat = lyr.GetNextFeature() expected_wkt = 'POINT (500000 4000000)' - if feat.GetGeometryRef().ExportToWkt() != expected_wkt: - print(('%s' % feat.GetGeometryRef().ExportToWkt())) - return 'fail' - - return 'success' + assert feat.GetGeometryRef().ExportToWkt() == expected_wkt, \ + ('%s' % feat.GetGeometryRef().ExportToWkt()) ############################################################################### # Test various broken documents -def ogr_georss_12(): +def test_ogr_georss_12(): if not gdaltest.georss_read_support: - return 'skip' + pytest.skip() open('tmp/broken.rss', 'wt').write('<?xml version="1.0"?><rss><item><a></item></rss>') gdal.PushErrorHandler('CPLQuietErrorHandler') ds = ogr.Open('tmp/broken.rss') gdal.PopErrorHandler() - if ds is not None: - return 'fail' + assert ds is None open('tmp/broken.rss', 'wt').write('<?xml version="1.0"?><rss><channel><item><georss:box>49 2 49.5</georss:box></item></channel></rss>') ds = ogr.Open('tmp/broken.rss') gdal.PushErrorHandler('CPLQuietErrorHandler') feat = ds.GetLayer(0).GetNextFeature() gdal.PopErrorHandler() - if feat.GetGeometryRef() is not None: - return 'fail' + assert feat.GetGeometryRef() is None open('tmp/broken.rss', 'wt').write('<?xml version="1.0"?><rss><channel><item><georss:where><gml:LineString><gml:posList>48 2 48.1 2.1 48</gml:posList></gml:LineString></georss:where></item></channel></rss>') ds = ogr.Open('tmp/broken.rss') gdal.PushErrorHandler('CPLQuietErrorHandler') feat = ds.GetLayer(0).GetNextFeature() gdal.PopErrorHandler() - if feat.GetGeometryRef() is not None: - return 'fail' - - return 'success' + assert feat.GetGeometryRef() is None ############################################################################### # Test writing non standard fields -def ogr_georss_13(): +def test_ogr_georss_13(): try: os.remove('tmp/nonstandard.rss') except OSError: @@ -546,64 +473,49 @@ def ogr_georss_13(): dst_feat.SetField('field2', 'val2') dst_feat.SetField('ogr_field3', 'val3') - if lyr.CreateFeature(dst_feat) != 0: - gdaltest.post_reason('CreateFeature failed.') - return 'fail' + assert lyr.CreateFeature(dst_feat) == 0, 'CreateFeature failed.' ds = None content = open('tmp/nonstandard.rss').read() - if content.find('<myns:field>val</myns:field>') == -1: - print(('%s' % content)) - return 'fail' - if content.find('<ogr:field2>val2</ogr:field2>') == -1: - print(('%s' % content)) - return 'fail' - if content.find('<ogr:field3>val3</ogr:field3>') == -1: - print(('%s' % content)) - return 'fail' - - return 'success' + assert content.find('<myns:field>val</myns:field>') != -1, ('%s' % content) + assert content.find('<ogr:field2>val2</ogr:field2>') != -1, ('%s' % content) + assert content.find('<ogr:field3>val3</ogr:field3>') != -1, ('%s' % content) ############################################################################### # Test reading document created at previous step -def ogr_georss_14(): +def test_ogr_georss_14(): if not gdaltest.georss_read_support: - return 'skip' + pytest.skip() ds = ogr.Open('tmp/nonstandard.rss') lyr = ds.GetLayer(0) feat = lyr.GetNextFeature() - if feat.GetFieldAsString('myns_field') != 'val': - print(('Expected %s. Got %s' % ('val', feat.GetFieldAsString('myns_field')))) - return 'fail' - if feat.GetFieldAsString('ogr_field2') != 'val2': - print(('Expected %s. Got %s' % ('val2', feat.GetFieldAsString('ogr_field2')))) - return 'fail' - if feat.GetFieldAsString('ogr_field3') != 'val3': - print(('Expected %s. Got %s' % ('val3', feat.GetFieldAsString('ogr_field3')))) - return 'fail' - - return 'success' + assert feat.GetFieldAsString('myns_field') == 'val', \ + ('Expected %s. Got %s' % ('val', feat.GetFieldAsString('myns_field'))) + assert feat.GetFieldAsString('ogr_field2') == 'val2', \ + ('Expected %s. Got %s' % ('val2', feat.GetFieldAsString('ogr_field2'))) + assert feat.GetFieldAsString('ogr_field3') == 'val3', \ + ('Expected %s. Got %s' % ('val3', feat.GetFieldAsString('ogr_field3'))) ############################################################################### # Test reading an in memory file (#2931) -def ogr_georss_15(): +def test_ogr_georss_15(): if not gdaltest.georss_read_support: - return 'skip' + pytest.skip() try: gdal.FileFromMemBuffer except AttributeError: - return 'skip' + pytest.skip() content = """<?xml version="1.0" encoding="UTF-8"?> <rss version="2.0" xmlns:georss="http://www.georss.org/georss" xmlns:gml="http://www.opengis.net/gml"> @@ -627,20 +539,17 @@ def ogr_georss_15(): feat = lyr.GetNextFeature() - if feat.GetFieldAsString('title') != 'item title': - print(('Expected %s. Got %s' % ('item title', feat.GetFieldAsString('title')))) - return 'fail' + assert feat.GetFieldAsString('title') == 'item title', \ + ('Expected %s. Got %s' % ('item title', feat.GetFieldAsString('title'))) # Release memory associated to the in-memory file gdal.Unlink('/vsimem/georssinmem') - return 'success' - ############################################################################### # -def ogr_georss_cleanup(): +def test_ogr_georss_cleanup(): list_files = ['tmp/test_rss2.xml', 'tmp/test_atom.xml', 'tmp/test32631.rss', 'tmp/broken.rss', 'tmp/nonstandard.rss'] for filename in list_files: @@ -654,35 +563,6 @@ def ogr_georss_cleanup(): if len(filename) > 13 and filename[-13:] == '.resolved.gml': os.unlink('data/' + filename) - return 'success' - - -gdaltest_list = [ - ogr_georss_init, - ogr_georss_1, - ogr_georss_1_atom_ns, - ogr_georss_1bis, - ogr_georss_1ter, - ogr_georss_2, - ogr_georss_3, - ogr_georss_4, - ogr_georss_5, - ogr_georss_6, - ogr_georss_7, - ogr_georss_8, - ogr_georss_9, - ogr_georss_10, - ogr_georss_11, - ogr_georss_12, - ogr_georss_13, - ogr_georss_14, - ogr_georss_15, - ogr_georss_cleanup] - -if __name__ == '__main__': - - gdaltest.setup_run('ogr_georss') - - gdaltest.run_tests(gdaltest_list) - - sys.exit(gdaltest.summarize()) + + + diff --git a/autotest/ogr/ogr_geos.py b/autotest/ogr/ogr_geos.py index 460ad2b4e3a4..ee6d2481c348 100755 --- a/autotest/ogr/ogr_geos.py +++ b/autotest/ogr/ogr_geos.py @@ -27,290 +27,238 @@ # Boston, MA 02111-1307, USA. ############################################################################### -import sys -sys.path.append('../pymod') import gdaltest import ogrtest from osgeo import ogr from osgeo import gdal +import pytest ############################################################################### # Establish whether we have GEOS support integrated, testing simple Union. -def ogr_geos_union(): +def test_ogr_geos_union(): if not ogrtest.have_geos(): - return 'skip' + pytest.skip() pnt1 = ogr.CreateGeometryFromWkt('POINT(10 20)') pnt2 = ogr.CreateGeometryFromWkt('POINT(30 20)') result = pnt1.Union(pnt2) - if ogrtest.check_feature_geometry(result, 'MULTIPOINT (10 20,30 20)'): - return 'fail' - - return 'success' + assert not ogrtest.check_feature_geometry(result, 'MULTIPOINT (10 20,30 20)') ############################################################################### # Test polygon intersection. -def ogr_geos_intersection(): +def test_ogr_geos_intersection(): if not ogrtest.have_geos(): - return 'skip' + pytest.skip() g1 = ogr.CreateGeometryFromWkt('POLYGON((0 0, 10 10, 10 0, 0 0))') g2 = ogr.CreateGeometryFromWkt('POLYGON((0 0, 0 10, 10 0, 0 0))') result = g1.Intersection(g2) - if ogrtest.check_feature_geometry(result, 'POLYGON ((0 0,5 5,10 0,0 0))'): - gdaltest.post_reason('Got: %s' % result.ExportToWkt()) - return 'fail' - - return 'success' + assert not ogrtest.check_feature_geometry(result, 'POLYGON ((0 0,5 5,10 0,0 0))'), \ + ('Got: %s' % result.ExportToWkt()) ############################################################################### # Test polygon difference. -def ogr_geos_difference(): +def test_ogr_geos_difference(): if not ogrtest.have_geos(): - return 'skip' + pytest.skip() g1 = ogr.CreateGeometryFromWkt('POLYGON((0 0, 10 10, 10 0, 0 0))') g2 = ogr.CreateGeometryFromWkt('POLYGON((0 0, 0 10, 10 0, 0 0))') result = g1.Difference(g2) - if ogrtest.check_feature_geometry(result, - 'POLYGON ((5 5,10 10,10 0,5 5))'): - gdaltest.post_reason('Got: %s' % result.ExportToWkt()) - return 'fail' - - return 'success' + assert (not ogrtest.check_feature_geometry(result, + 'POLYGON ((5 5,10 10,10 0,5 5))')), \ + ('Got: %s' % result.ExportToWkt()) ############################################################################### # Test polygon symmetric difference. -def ogr_geos_symmetric_difference(): +def test_ogr_geos_symmetric_difference(): if not ogrtest.have_geos(): - return 'skip' + pytest.skip() g1 = ogr.CreateGeometryFromWkt('POLYGON((0 0, 10 10, 10 0, 0 0))') g2 = ogr.CreateGeometryFromWkt('POLYGON((0 0, 0 10, 10 0, 0 0))') result = g1.SymmetricDifference(g2) - if ogrtest.check_feature_geometry(result, - 'MULTIPOLYGON (((5 5,0 0,0 10,5 5)),((5 5,10 10,10 0,5 5)))'): - gdaltest.post_reason('Got: %s' % result.ExportToWkt()) - return 'fail' - - return 'success' + assert (not ogrtest.check_feature_geometry(result, + 'MULTIPOLYGON (((5 5,0 0,0 10,5 5)),((5 5,10 10,10 0,5 5)))')), \ + ('Got: %s' % result.ExportToWkt()) ############################################################################### # Test polygon symmetric difference. -def ogr_geos_sym_difference(): +def test_ogr_geos_sym_difference(): if not ogrtest.have_geos(): - return 'skip' + pytest.skip() g1 = ogr.CreateGeometryFromWkt('POLYGON((0 0, 10 10, 10 0, 0 0))') g2 = ogr.CreateGeometryFromWkt('POLYGON((0 0, 0 10, 10 0, 0 0))') result = g1.SymDifference(g2) - if ogrtest.check_feature_geometry(result, - 'MULTIPOLYGON (((5 5,0 0,0 10,5 5)),((5 5,10 10,10 0,5 5)))'): - gdaltest.post_reason('Got: %s' % result.ExportToWkt()) - return 'fail' - - return 'success' + assert (not ogrtest.check_feature_geometry(result, + 'MULTIPOLYGON (((5 5,0 0,0 10,5 5)),((5 5,10 10,10 0,5 5)))')), \ + ('Got: %s' % result.ExportToWkt()) ############################################################################### # Test Intersect(). -def ogr_geos_intersect(): +def test_ogr_geos_intersect(): if not ogrtest.have_geos(): - return 'skip' + pytest.skip() g1 = ogr.CreateGeometryFromWkt('LINESTRING(0 0, 10 10)') g2 = ogr.CreateGeometryFromWkt('LINESTRING(10 0, 0 10)') result = g1.Intersect(g2) - if result == 0: - gdaltest.post_reason('wrong result (got false)') - return 'fail' + assert result != 0, 'wrong result (got false)' g1 = ogr.CreateGeometryFromWkt('LINESTRING(0 0, 10 10)') g2 = ogr.CreateGeometryFromWkt('POLYGON((20 20, 20 30, 30 20, 20 20))') result = g1.Intersect(g2) - if result != 0: - gdaltest.post_reason('wrong result (got true)') - return 'fail' - - return 'success' + assert result == 0, 'wrong result (got true)' ############################################################################### # Test disjoint(). -def ogr_geos_disjoint(): +def test_ogr_geos_disjoint(): if not ogrtest.have_geos(): - return 'skip' + pytest.skip() g1 = ogr.CreateGeometryFromWkt('LINESTRING(0 0, 10 10)') g2 = ogr.CreateGeometryFromWkt('LINESTRING(10 0, 0 10)') result = g1.Disjoint(g2) - if result != 0: - gdaltest.post_reason('wrong result (got true)') - return 'fail' + assert result == 0, 'wrong result (got true)' g1 = ogr.CreateGeometryFromWkt('LINESTRING(0 0, 10 10)') g2 = ogr.CreateGeometryFromWkt('POLYGON((20 20, 20 30, 30 20, 20 20))') result = g1.Disjoint(g2) - if result == 0: - gdaltest.post_reason('wrong result (got false)') - return 'fail' - - return 'success' + assert result != 0, 'wrong result (got false)' ############################################################################### # Test touches. -def ogr_geos_touches(): +def test_ogr_geos_touches(): if not ogrtest.have_geos(): - return 'skip' + pytest.skip() g1 = ogr.CreateGeometryFromWkt('LINESTRING(0 0, 10 10)') g2 = ogr.CreateGeometryFromWkt('LINESTRING(0 0, 0 10)') result = g1.Touches(g2) - if result == 0: - gdaltest.post_reason('wrong result (got false)') - return 'fail' + assert result != 0, 'wrong result (got false)' g1 = ogr.CreateGeometryFromWkt('LINESTRING(0 0, 10 10)') g2 = ogr.CreateGeometryFromWkt('POLYGON((20 20, 20 30, 30 20, 20 20))') result = g1.Touches(g2) - if result != 0: - gdaltest.post_reason('wrong result (got true)') - return 'fail' - - return 'success' + assert result == 0, 'wrong result (got true)' ############################################################################### # Test crosses. -def ogr_geos_crosses(): +def test_ogr_geos_crosses(): if not ogrtest.have_geos(): - return 'skip' + pytest.skip() g1 = ogr.CreateGeometryFromWkt('LINESTRING(0 0, 10 10)') g2 = ogr.CreateGeometryFromWkt('LINESTRING(10 0, 0 10)') result = g1.Crosses(g2) - if result == 0: - gdaltest.post_reason('wrong result (got false)') - return 'fail' + assert result != 0, 'wrong result (got false)' g1 = ogr.CreateGeometryFromWkt('LINESTRING(0 0, 10 10)') g2 = ogr.CreateGeometryFromWkt('LINESTRING(0 0, 0 10)') result = g1.Crosses(g2) - if result != 0: - gdaltest.post_reason('wrong result (got true)') - return 'fail' - - return 'success' + assert result == 0, 'wrong result (got true)' ############################################################################### -def ogr_geos_within(): +def test_ogr_geos_within(): if not ogrtest.have_geos(): - return 'skip' + pytest.skip() g1 = ogr.CreateGeometryFromWkt('POLYGON((0 0, 10 10, 10 0, 0 0))') g2 = ogr.CreateGeometryFromWkt('POLYGON((-90 -90, -90 90, 190 -90, -90 -90))') result = g1.Within(g2) - if result == 0: - gdaltest.post_reason('wrong result (got false)') - return 'fail' + assert result != 0, 'wrong result (got false)' result = g2.Within(g1) - if result != 0: - gdaltest.post_reason('wrong result (got true)') - return 'fail' - - return 'success' + assert result == 0, 'wrong result (got true)' ############################################################################### -def ogr_geos_contains(): +def test_ogr_geos_contains(): if not ogrtest.have_geos(): - return 'skip' + pytest.skip() g1 = ogr.CreateGeometryFromWkt('POLYGON((0 0, 10 10, 10 0, 0 0))') g2 = ogr.CreateGeometryFromWkt('POLYGON((-90 -90, -90 90, 190 -90, -90 -90))') result = g2.Contains(g1) - if result == 0: - gdaltest.post_reason('wrong result (got false)') - return 'fail' + assert result != 0, 'wrong result (got false)' result = g1.Contains(g2) - if result != 0: - gdaltest.post_reason('wrong result (got true)') - return 'fail' - - return 'success' + assert result == 0, 'wrong result (got true)' ############################################################################### -def ogr_geos_overlaps(): +def test_ogr_geos_overlaps(): if not ogrtest.have_geos(): - return 'skip' + pytest.skip() g1 = ogr.CreateGeometryFromWkt('POLYGON((0 0, 10 10, 10 0, 0 0))') g2 = ogr.CreateGeometryFromWkt('POLYGON((-90 -90, -90 90, 190 -90, -90 -90))') @@ -318,444 +266,330 @@ def ogr_geos_overlaps(): result = g2.Overlaps(g1) # g1 and g2 intersect, but their intersection is equal to g1 - if result != 0: - gdaltest.post_reason('wrong result (got true)') - return 'fail' + assert result == 0, 'wrong result (got true)' g1 = ogr.CreateGeometryFromWkt('POLYGON((0 0, 10 10, 10 0, 0 0))') g2 = ogr.CreateGeometryFromWkt('POLYGON((0 -5,10 5,10 -5,0 -5))') result = g2.Overlaps(g1) - if result == 0: - gdaltest.post_reason('wrong result (got false)') - return 'fail' - - return 'success' + assert result != 0, 'wrong result (got false)' ############################################################################### -def ogr_geos_buffer(): +def test_ogr_geos_buffer(): if not ogrtest.have_geos(): - return 'skip' + pytest.skip() g1 = ogr.CreateGeometryFromWkt('POLYGON((0 0, 10 10, 10 0, 0 0))') result = g1.Buffer(1.0, 3) - if ogrtest.check_feature_geometry(result, - 'POLYGON ((0 -1,-0.555570233019607 -0.831469612302542,-0.923879532511288 -0.382683432365087,-0.98078528040323 0.19509032201613,-0.707106781186547 0.707106781186547,9.292893218813452 10.707106781186548,9.690983005625053 10.951056516295154,10.156434465040231 10.987688340595138,10.587785252292473 10.809016994374947,10.891006524188368 10.453990499739547,11 10,11 0,10.866025403784439 -0.5,10.5 -0.866025403784439,10 -1,0 -1))') != 0: - gdaltest.post_reason('Got: %s' % result.ExportToWkt()) - return 'fail' - - return 'success' + assert (ogrtest.check_feature_geometry(result, + 'POLYGON ((0 -1,-0.555570233019607 -0.831469612302542,-0.923879532511288 -0.382683432365087,-0.98078528040323 0.19509032201613,-0.707106781186547 0.707106781186547,9.292893218813452 10.707106781186548,9.690983005625053 10.951056516295154,10.156434465040231 10.987688340595138,10.587785252292473 10.809016994374947,10.891006524188368 10.453990499739547,11 10,11 0,10.866025403784439 -0.5,10.5 -0.866025403784439,10 -1,0 -1))') == 0), \ + ('Got: %s' % result.ExportToWkt()) ############################################################################### -def ogr_geos_centroid(): +def test_ogr_geos_centroid(): if not ogrtest.have_geos(): - return 'skip' + pytest.skip() g1 = ogr.CreateGeometryFromWkt('POLYGON((0 0, 10 10, 10 0, 0 0))') centroid = g1.Centroid() - if ogrtest.check_feature_geometry(centroid, - 'POINT(6.666666667 3.333333333)') != 0: - gdaltest.post_reason('Got: %s' % centroid.ExportToWkt()) - return 'fail' + assert (ogrtest.check_feature_geometry(centroid, + 'POINT(6.666666667 3.333333333)') == 0), \ + ('Got: %s' % centroid.ExportToWkt()) # Test with a self intersecting polygon too. # This particular polygon has two triangles. The right triangle is larger. g2 = ogr.CreateGeometryFromWkt('POLYGON((0 0, 0 2, 2 -0.1, 2 2.1, 0 0))') centroid2 = g2.Centroid() - if ogrtest.check_feature_geometry(centroid2, 'POINT (8.0 1.0)') != 0: - gdaltest.post_reason('Got: %s' % centroid2.ExportToWkt()) - return 'fail' - - return 'success' + assert ogrtest.check_feature_geometry(centroid2, 'POINT (8.0 1.0)') == 0, \ + ('Got: %s' % centroid2.ExportToWkt()) ############################################################################### -def ogr_geos_centroid_multipolygon(): +def test_ogr_geos_centroid_multipolygon(): if not ogrtest.have_geos(): - return 'skip' + pytest.skip() g1 = ogr.CreateGeometryFromWkt('MULTIPOLYGON(((0 0,0 1,1 1,1 0,0 0)),((2 0,2 1,3 1,3 0,2 0)))') centroid = g1.Centroid() - if ogrtest.check_feature_geometry(centroid, - 'POINT (1.5 0.5)') != 0: - gdaltest.post_reason('Got: %s' % centroid.ExportToWkt()) - return 'fail' - - return 'success' + assert (ogrtest.check_feature_geometry(centroid, + 'POINT (1.5 0.5)') == 0), \ + ('Got: %s' % centroid.ExportToWkt()) ############################################################################### -def ogr_geos_centroid_point_empty(): +def test_ogr_geos_centroid_point_empty(): if not ogrtest.have_geos(): - return 'skip' + pytest.skip() g1 = ogr.CreateGeometryFromWkt('POINT EMPTY') centroid = g1.Centroid() - if centroid.ExportToWkt() != 'POINT EMPTY': - gdaltest.post_reason('Got: %s' % centroid.ExportToWkt()) - return 'fail' - - return 'success' + assert centroid.ExportToWkt() == 'POINT EMPTY', ('Got: %s' % centroid.ExportToWkt()) ############################################################################### -def ogr_geos_simplify_linestring(): +def test_ogr_geos_simplify_linestring(): if not ogrtest.have_geos(): - return 'skip' + pytest.skip() g1 = ogr.CreateGeometryFromWkt('LINESTRING(0 0,1 0,10 0)') gdal.ErrorReset() simplify = g1.Simplify(5) - if simplify.ExportToWkt() != 'LINESTRING (0 0,10 0)': - gdaltest.post_reason('Got: %s' % simplify.ExportToWkt()) - return 'fail' - - return 'success' + assert simplify.ExportToWkt() == 'LINESTRING (0 0,10 0)', \ + ('Got: %s' % simplify.ExportToWkt()) ############################################################################### -def ogr_geos_simplifypreservetopology_linestring(): +def test_ogr_geos_simplifypreservetopology_linestring(): if not ogrtest.have_geos(): - return 'skip' + pytest.skip() g1 = ogr.CreateGeometryFromWkt('LINESTRING(0 0,1 0,10 0)') gdal.ErrorReset() simplify = g1.SimplifyPreserveTopology(5) - if simplify.ExportToWkt() != 'LINESTRING (0 0,10 0)': - gdaltest.post_reason('Got: %s' % simplify.ExportToWkt()) - return 'fail' - - return 'success' + assert simplify.ExportToWkt() == 'LINESTRING (0 0,10 0)', \ + ('Got: %s' % simplify.ExportToWkt()) ############################################################################### -def ogr_geos_unioncascaded(): +def test_ogr_geos_unioncascaded(): if not ogrtest.have_geos(): - return 'skip' + pytest.skip() g1 = ogr.CreateGeometryFromWkt('MULTIPOLYGON(((0 0,0 1,1 1,1 0,0 0)),((0.5 0.5,0.5 1.5,1.5 1.5,1.5 0.5,0.5 0.5)))') gdal.ErrorReset() cascadedunion = g1.UnionCascaded() - if cascadedunion.ExportToWkt() != 'POLYGON ((0 0,0 1,0.5 1.0,0.5 1.5,1.5 1.5,1.5 0.5,1.0 0.5,1 0,0 0))': - gdaltest.post_reason('Got: %s' % cascadedunion.ExportToWkt()) - return 'fail' - - return 'success' + assert cascadedunion.ExportToWkt() == 'POLYGON ((0 0,0 1,0.5 1.0,0.5 1.5,1.5 1.5,1.5 0.5,1.0 0.5,1 0,0 0))', \ + ('Got: %s' % cascadedunion.ExportToWkt()) ############################################################################### -def ogr_geos_convexhull(): +def test_ogr_geos_convexhull(): if not ogrtest.have_geos(): - return 'skip' + pytest.skip() g1 = ogr.CreateGeometryFromWkt('GEOMETRYCOLLECTION(POINT(0 1), POINT(0 0), POINT(1 0), POINT(1 1))') convexhull = g1.ConvexHull() - if convexhull.ExportToWkt() != 'POLYGON ((0 0,0 1,1 1,1 0,0 0))': - gdaltest.post_reason('Got: %s' % convexhull.ExportToWkt()) - return 'fail' - - return 'success' + assert convexhull.ExportToWkt() == 'POLYGON ((0 0,0 1,1 1,1 0,0 0))', \ + ('Got: %s' % convexhull.ExportToWkt()) ############################################################################### -def ogr_geos_distance(): +def test_ogr_geos_distance(): if not ogrtest.have_geos(): - return 'skip' + pytest.skip() g1 = ogr.CreateGeometryFromWkt('POINT(0 0)') g2 = ogr.CreateGeometryFromWkt('POINT(1 0)') distance = g1.Distance(g2) - if abs(distance - 1) > 0.00000000001: - gdaltest.post_reason('Distance() result wrong, got %g.' % distance) - return 'fail' - - return 'success' + assert abs(distance - 1) <= 0.00000000001, \ + ('Distance() result wrong, got %g.' % distance) ############################################################################### -def ogr_geos_isring(): +def test_ogr_geos_isring(): if not ogrtest.have_geos(): - return 'skip' + pytest.skip() g1 = ogr.CreateGeometryFromWkt('LINESTRING(0 0,0 1,1 1,0 0)') isring = g1.IsRing() - if isring != 1: - return 'fail' - - return 'success' + assert isring == 1 ############################################################################### -def ogr_geos_issimple_true(): +def test_ogr_geos_issimple_true(): if not ogrtest.have_geos(): - return 'skip' + pytest.skip() g1 = ogr.CreateGeometryFromWkt('POLYGON ((0 0,0 1,1 1,1 0,0 0))') isring = g1.IsSimple() - if isring != 1: - return 'fail' - - return 'success' + assert isring == 1 ############################################################################### -def ogr_geos_issimple_false(): +def test_ogr_geos_issimple_false(): if not ogrtest.have_geos(): - return 'skip' + pytest.skip() g1 = ogr.CreateGeometryFromWkt('LINESTRING(1 1,2 2,2 3.5,1 3,1 2,2 1)') isring = g1.IsSimple() - if isring != 0: - return 'fail' - - return 'success' + assert isring == 0 ############################################################################### -def ogr_geos_isvalid_true(): +def test_ogr_geos_isvalid_true(): if not ogrtest.have_geos(): - return 'skip' + pytest.skip() g1 = ogr.CreateGeometryFromWkt('LINESTRING(0 0, 1 1)') isring = g1.IsValid() - if isring != 1: - return 'fail' - - return 'success' + assert isring == 1 ############################################################################### -def ogr_geos_isvalid_true_linestringM(): +def test_ogr_geos_isvalid_true_linestringM(): if not ogrtest.have_geos(): - return 'skip' + pytest.skip() g1 = ogr.CreateGeometryFromWkt('LINESTRING M(0 0 10, 1 1 20)') isring = g1.IsValid() - if isring != 1: - return 'fail' - - return 'success' + assert isring == 1 ############################################################################### -def ogr_geos_isvalid_true_circularStringM(): +def test_ogr_geos_isvalid_true_circularStringM(): if not ogrtest.have_geos(): - return 'skip' + pytest.skip() g1 = ogr.CreateGeometryFromWkt('CIRCULARSTRING M(0 0 10, 1 1 20,2 0 30)') isring = g1.IsValid() - if isring != 1: - return 'fail' - - return 'success' + assert isring == 1 ############################################################################### -def ogr_geos_isvalid_true_triangle(): +def test_ogr_geos_isvalid_true_triangle(): if not ogrtest.have_geos(): - return 'skip' + pytest.skip() g1 = ogr.CreateGeometryFromWkt('TRIANGLE ((0 0,0 1,1 1,0 0))') isring = g1.IsValid() - if isring != 1: - return 'fail' - - return 'success' + assert isring == 1 ############################################################################### -def ogr_geos_isvalid_false(): +def test_ogr_geos_isvalid_false(): if not ogrtest.have_geos(): - return 'skip' + pytest.skip() g1 = ogr.CreateGeometryFromWkt('POLYGON((0 0,1 1,1 2,1 1,0 0))') with gdaltest.error_handler(): isring = g1.IsValid() - if isring != 0: - return 'fail' - - return 'success' + assert isring == 0 ############################################################################### -def ogr_geos_pointonsurface(): +def test_ogr_geos_pointonsurface(): if not ogrtest.have_geos(): - return 'skip' + pytest.skip() g1 = ogr.CreateGeometryFromWkt('POLYGON((0 0, 10 10, 10 0, 0 0))') pointonsurface = g1.PointOnSurface() - if pointonsurface.Within(g1) != 1: - return 'fail' - - return 'success' + assert pointonsurface.Within(g1) == 1 ############################################################################### -def ogr_geos_DelaunayTriangulation(): +def test_ogr_geos_DelaunayTriangulation(): if not ogrtest.have_geos(): - return 'skip' + pytest.skip() g1 = ogr.CreateGeometryFromWkt('MULTIPOINT(0 0,0 1,1 1,1 0)') gdal.ErrorReset() triangulation = g1.DelaunayTriangulation() if triangulation is None: - if gdal.GetLastErrorMsg() == '': - return 'fail' - return 'skip' + assert gdal.GetLastErrorMsg() != '' + pytest.skip() - if triangulation.ExportToWkt() != 'GEOMETRYCOLLECTION (POLYGON ((0 1,0 0,1 0,0 1)),POLYGON ((0 1,1 0,1 1,0 1)))': - gdaltest.post_reason('Got: %s' % triangulation.ExportToWkt()) - return 'fail' - - return 'success' + assert triangulation.ExportToWkt() == 'GEOMETRYCOLLECTION (POLYGON ((0 1,0 0,1 0,0 1)),POLYGON ((0 1,1 0,1 1,0 1)))', \ + ('Got: %s' % triangulation.ExportToWkt()) ############################################################################### -def ogr_geos_polygonize(): +def test_ogr_geos_polygonize(): if not ogrtest.have_geos(): - return 'skip' + pytest.skip() g = ogr.CreateGeometryFromWkt('MULTILINESTRING((0 0,0 1,1 1),(1 1,0 0))') got = g.Polygonize() - if got.ExportToWkt() != 'GEOMETRYCOLLECTION (POLYGON ((0 0,0 1,1 1,0 0)))': - gdaltest.post_reason('Got: %s' % got.ExportToWkt()) - return 'fail' + assert got.ExportToWkt() == 'GEOMETRYCOLLECTION (POLYGON ((0 0,0 1,1 1,0 0)))', \ + ('Got: %s' % got.ExportToWkt()) g = ogr.CreateGeometryFromWkt('POINT EMPTY') got = g.Polygonize() - if got is not None: - gdaltest.post_reason('Got: %s' % got.ExportToWkt()) - return 'fail' + assert got is None, ('Got: %s' % got.ExportToWkt()) g = ogr.CreateGeometryFromWkt('GEOMETRYCOLLECTION(POINT EMPTY)') got = g.Polygonize() - if got is not None: - gdaltest.post_reason('Got: %s' % got.ExportToWkt()) - return 'fail' - - return 'success' - - -gdaltest_list = [ - ogr_geos_union, - ogr_geos_intersection, - ogr_geos_difference, - ogr_geos_symmetric_difference, - ogr_geos_sym_difference, - ogr_geos_intersect, - ogr_geos_disjoint, - ogr_geos_touches, - ogr_geos_crosses, - ogr_geos_within, - ogr_geos_contains, - ogr_geos_overlaps, - ogr_geos_buffer, - ogr_geos_centroid, - ogr_geos_centroid_multipolygon, - ogr_geos_centroid_point_empty, - ogr_geos_simplify_linestring, - ogr_geos_simplifypreservetopology_linestring, - ogr_geos_unioncascaded, - ogr_geos_convexhull, - ogr_geos_distance, - ogr_geos_isring, - ogr_geos_issimple_true, - ogr_geos_issimple_false, - ogr_geos_isvalid_true, - ogr_geos_isvalid_true_linestringM, - ogr_geos_isvalid_true_circularStringM, - ogr_geos_isvalid_true_triangle, - ogr_geos_isvalid_false, - ogr_geos_pointonsurface, - ogr_geos_DelaunayTriangulation, - ogr_geos_polygonize, -] - -if __name__ == '__main__': - - gdaltest.setup_run('ogr_geos') - - gdaltest.run_tests(gdaltest_list) - - sys.exit(gdaltest.summarize()) + assert got is None, ('Got: %s' % got.ExportToWkt()) + + + diff --git a/autotest/ogr/ogr_gft.py b/autotest/ogr/ogr_gft.py index e7449b572472..f8a551f7bc8f 100755 --- a/autotest/ogr/ogr_gft.py +++ b/autotest/ogr/ogr_gft.py @@ -30,44 +30,40 @@ ############################################################################### import os -import sys -sys.path.append('../pymod') import gdaltest import ogrtest from osgeo import gdal from osgeo import ogr +import pytest ############################################################################### # Test if driver is available -def ogr_gft_init(): +def test_ogr_gft_init(): ogrtest.gft_drv = None ogrtest.gft_drv = ogr.GetDriverByName('GFT') if ogrtest.gft_drv is None: - return 'skip' + pytest.skip() if gdaltest.gdalurlopen('http://www.google.com') is None: - print('cannot open http://www.google.com') ogrtest.gft_drv = None - return 'skip' + pytest.skip('cannot open http://www.google.com') ogrtest.gft_refresh = '1/woRTxgfN8dLUpRhnOL-BXG-f7VxzXKy_3D5eizH8bS8' - return 'success' - ############################################################################### # Read test on Wikileaks Afgan War Diary 2004-2010 table. -def ogr_gft_read(): +def test_ogr_gft_read(): if ogrtest.gft_drv is None: - return 'skip' + pytest.skip() table_id = '15eIgEVTUNlC649ODphJVHXeb4nsOb49WJUlnhw' @@ -81,54 +77,46 @@ def ogr_gft_read(): gdal.SetConfigOption('GFT_AUTH', old_auth) gdal.SetConfigOption('GFT_ACCESS_TOKEN', old_access) gdal.SetConfigOption('GFT_REFRESH_TOKEN', old_refresh) - if ds is None: - return 'fail' + assert ds is not None lyr = ds.GetLayer(0) - if lyr is None: - return 'fail' + assert lyr is not None lyr.SetSpatialFilterRect(67, 31.5, 67.5, 32) lyr.SetAttributeFilter("'Attack on' = 'ENEMY'") count = lyr.GetFeatureCount() if count == 0: - gdaltest.post_reason('did not get expected feature count') print(count) if gdaltest.skip_on_travis() or gdal.GetConfigOption('APPVEYOR') is not None: ogrtest.gft_drv = None - return 'skip' - return 'fail' + pytest.skip() + pytest.fail('did not get expected feature count') sql_lyr = ds.ExecuteSQL("SELECT Latitude, Longitude FROM " + table_id + " WHERE ST_INTERSECTS('Latitude', RECTANGLE(LATLNG(31.5,67.0), LATLNG(32.0,67.5))) AND 'Attack on' = 'ENEMY'") - if sql_lyr is None: - gdaltest.post_reason('SQL request failed') - return 'fail' + assert sql_lyr is not None, 'SQL request failed' sql_lyr_count = sql_lyr.GetFeatureCount() ds.ReleaseResultSet(sql_lyr) - if sql_lyr_count != count: - gdaltest.post_reason('did not get expected feature count. Got %d, expected %d' % (sql_lyr_count, count)) - return 'fail' - - return 'success' + assert sql_lyr_count == count, \ + ('did not get expected feature count. Got %d, expected %d' % (sql_lyr_count, count)) ############################################################################### # Write test -def ogr_gft_write(): +def test_ogr_gft_write(): if ogrtest.gft_drv is None: - return 'skip' + pytest.skip() if ogrtest.gft_refresh is None: ogrtest.gft_can_write = False - return 'skip' + pytest.skip() ds = ogr.Open('GFT:refresh=%s' % ogrtest.gft_refresh, update=1) if ds is None: ogrtest.gft_can_write = False - return 'skip' + pytest.skip() ogrtest.gft_can_write = True import random @@ -146,62 +134,48 @@ def ogr_gft_write(): expected_wkt = "POLYGON ((0 0,0 1,1 1,1 0),(0.25 0.25,0.25 0.75,0.75 0.75,0.75 0.25))" geom = ogr.CreateGeometryFromWkt(expected_wkt) feat.SetGeometry(geom) - if lyr.CreateFeature(feat) != 0: - gdaltest.post_reason('CreateFeature() failed') - return 'fail' + assert lyr.CreateFeature(feat) == 0, 'CreateFeature() failed' fid = feat.GetFID() feat.SetField('strcol', 'bar') - if lyr.SetFeature(feat) != 0: - gdaltest.post_reason('SetFeature() failed') - return 'fail' + assert lyr.SetFeature(feat) == 0, 'SetFeature() failed' lyr.ResetReading() feat = lyr.GetNextFeature() if feat.GetFieldAsString('strcol') != 'bar': - gdaltest.post_reason('GetNextFeature() did not get expected feature') feat.DumpReadable() - return 'fail' + pytest.fail('GetNextFeature() did not get expected feature') feat = lyr.GetFeature(fid) if feat.GetFieldAsString('strcol') != 'bar': - gdaltest.post_reason('GetFeature() did not get expected feature') feat.DumpReadable() - return 'fail' + pytest.fail('GetFeature() did not get expected feature') got_wkt = feat.GetGeometryRef().ExportToWkt() - if got_wkt != expected_wkt: - gdaltest.post_reason('did not get expected geometry') - print(got_wkt) - return 'fail' + assert got_wkt == expected_wkt, 'did not get expected geometry' - if lyr.GetFeatureCount() != 1: - gdaltest.post_reason('GetFeatureCount() did not returned expected value') - return 'fail' + assert lyr.GetFeatureCount() == 1, \ + 'GetFeatureCount() did not returned expected value' - if lyr.DeleteFeature(feat.GetFID()) != 0: - gdaltest.post_reason('DeleteFeature() failed') - return 'fail' + assert lyr.DeleteFeature(feat.GetFID()) == 0, 'DeleteFeature() failed' ds.ExecuteSQL('DELLAYER:%s' % table_name) ds = None - return 'success' - ############################################################################### # ogr2ogr test to create a non-spatial GFT table -def ogr_gft_ogr2ogr_non_spatial(): +def test_ogr_gft_ogr2ogr_non_spatial(): if ogrtest.gft_drv is None: - return 'skip' + pytest.skip() if not ogrtest.gft_can_write: - return 'skip' + pytest.skip() import test_cli_utilities if test_cli_utilities.get_ogr2ogr_path() is None: - return 'skip' + pytest.skip() layer_name = 'no_geometry_table_%d' % ogrtest.gft_rand_val @@ -218,40 +192,35 @@ def ogr_gft_ogr2ogr_non_spatial(): ds = ogr.Open('GFT:refresh=%s' % ogrtest.gft_refresh, update=1) lyr = ds.GetLayerByName(layer_name) if lyr.GetLayerDefn().GetFieldCount() != 2: - gdaltest.post_reason('did not get expected field count') ds.ExecuteSQL('DELLAYER:' + layer_name) - return 'fail' + pytest.fail('did not get expected field count') if lyr.GetGeomType() != ogr.wkbNone: - gdaltest.post_reason('did not get expected layer geometry type') ds.ExecuteSQL('DELLAYER:' + layer_name) - return 'fail' + pytest.fail('did not get expected layer geometry type') if lyr.GetFeatureCount() != 3: - gdaltest.post_reason('did not get expected feature count') ds.ExecuteSQL('DELLAYER:' + layer_name) - return 'fail' + pytest.fail('did not get expected feature count') ds.ExecuteSQL('DELLAYER:' + layer_name) ds = None - return 'success' - ############################################################################### # ogr2ogr test to create a spatial GFT table -def ogr_gft_ogr2ogr_spatial(): +def test_ogr_gft_ogr2ogr_spatial(): if ogrtest.gft_drv is None: - return 'skip' + pytest.skip() if not ogrtest.gft_can_write: - return 'skip' + pytest.skip() import test_cli_utilities if test_cli_utilities.get_ogr2ogr_path() is None: - return 'skip' + pytest.skip() layer_name = 'geometry_table_%d' % ogrtest.gft_rand_val copied_layer_name = 'copied_geometry_table_%d' % ogrtest.gft_rand_val @@ -281,62 +250,40 @@ def ogr_gft_ogr2ogr_spatial(): lyr = ds.GetLayerByName(name) if lyr.GetGeometryColumn() != 'geometry': - gdaltest.post_reason('layer %s: did not get expected geometry column' % name) ds.ExecuteSQL('DELLAYER:' + layer_name) ds.ExecuteSQL('DELLAYER:' + copied_layer_name) - return 'fail' + pytest.fail('layer %s: did not get expected geometry column' % name) if lyr.GetLayerDefn().GetFieldCount() != 3: - gdaltest.post_reason('layer %s: did not get expected field count' % name) ds.ExecuteSQL('DELLAYER:' + layer_name) ds.ExecuteSQL('DELLAYER:' + copied_layer_name) - return 'fail' + pytest.fail('layer %s: did not get expected field count' % name) if lyr.GetGeomType() != ogr.wkbUnknown: - gdaltest.post_reason('layer %s: did not get expected layer geometry type' % name) ds.ExecuteSQL('DELLAYER:' + layer_name) ds.ExecuteSQL('DELLAYER:' + copied_layer_name) - return 'fail' + pytest.fail('layer %s: did not get expected layer geometry type' % name) if lyr.GetFeatureCount() != 3: - gdaltest.post_reason('layer %s: did not get expected feature count' % name) ds.ExecuteSQL('DELLAYER:' + layer_name) ds.ExecuteSQL('DELLAYER:' + copied_layer_name) - return 'fail' + pytest.fail('layer %s: did not get expected feature count' % name) feat = lyr.GetNextFeature() if feat.GetGeometryRef().ExportToWkt() != "POINT (0 1)": - gdaltest.post_reason('layer %s: did not get expected geometry' % name) ds.ExecuteSQL('DELLAYER:' + layer_name) ds.ExecuteSQL('DELLAYER:' + copied_layer_name) - return 'fail' + pytest.fail('layer %s: did not get expected geometry' % name) if feat.GetFieldAsInteger('bar') != 2: - gdaltest.post_reason('layer %s: did not get expected field value' % name) ds.ExecuteSQL('DELLAYER:' + layer_name) ds.ExecuteSQL('DELLAYER:' + copied_layer_name) - return 'fail' + pytest.fail('layer %s: did not get expected field value' % name) ds.ExecuteSQL('DELLAYER:' + layer_name) ds.ExecuteSQL('DELLAYER:' + copied_layer_name) ds = None - return 'success' - - -gdaltest_list = [ - ogr_gft_init, - ogr_gft_read, - ogr_gft_write, - ogr_gft_ogr2ogr_non_spatial, - ogr_gft_ogr2ogr_spatial, -] - -if __name__ == '__main__': - - gdaltest.setup_run('ogr_gft') - gdaltest.run_tests(gdaltest_list) - sys.exit(gdaltest.summarize()) diff --git a/autotest/ogr/ogr_gml_fgd_read.py b/autotest/ogr/ogr_gml_fgd_read.py index 6badd173e37f..9ac522809205 100755 --- a/autotest/ogr/ogr_gml_fgd_read.py +++ b/autotest/ogr/ogr_gml_fgd_read.py @@ -29,15 +29,14 @@ # DEALINGS IN THE SOFTWARE. ############################################################################### -import sys -sys.path.append('../pymod') import gdaltest import ogrtest from osgeo import gdal from osgeo import ogr from osgeo import osr +import pytest ############################################################################### @@ -50,7 +49,7 @@ ############################################################################### # Test reading Japanese FGD GML (v4) ElevPt file -def ogr_gml_fgd_1(): +def test_ogr_gml_fgd_1(): gdaltest.have_gml_fgd_reader = 0 @@ -59,92 +58,61 @@ def ogr_gml_fgd_1(): if ds is None: if gdal.GetLastErrorMsg().find('Xerces') != -1: - return 'skip' - gdaltest.post_reason('failed to open test file.') - return 'fail' + pytest.skip() + pytest.fail('failed to open test file.') # we have gml reader for fgd gdaltest.have_gml_fgd_reader = 1 # check number of layers - if ds.GetLayerCount() != 1: - gdaltest.post_reason('Wrong layer count') - return 'fail' + assert ds.GetLayerCount() == 1, 'Wrong layer count' lyr = ds.GetLayer(0) # check the SRS sr = osr.SpatialReference() sr.ImportFromEPSG(6668) # JGD2011 - if not sr.IsSame(lyr.GetSpatialRef()): - gdaltest.post_reason('Wrong SRS') - return 'fail' + assert sr.IsSame(lyr.GetSpatialRef()), 'Wrong SRS' # check the first feature feat = lyr.GetNextFeature() - if ogrtest.check_feature_geometry(feat, 'POINT (133.123456789 34.123456789)'): - gdaltest.post_reason('Wrong geometry') - return 'fail' + assert not ogrtest.check_feature_geometry(feat, 'POINT (133.123456789 34.123456789)'), \ + 'Wrong geometry' - if feat.GetField('devDate') != '2015-01-07': - gdaltest.post_reason('Wrong attribute value') - return 'fail' - - return 'success' + assert feat.GetField('devDate') == '2015-01-07', 'Wrong attribute value' ############################################################################### # Test reading Japanese FGD GML (v4) BldA file -def ogr_gml_fgd_2(): +def test_ogr_gml_fgd_2(): if not gdaltest.have_gml_fgd_reader: - return 'skip' + pytest.skip() # open FGD GML file ds = ogr.Open(_fgd_dir + 'BldA.xml') # check number of layers - if ds.GetLayerCount() != 1: - gdaltest.post_reason('Wrong layer count') - return 'fail' + assert ds.GetLayerCount() == 1, 'Wrong layer count' lyr = ds.GetLayer(0) # check the SRS sr = osr.SpatialReference() sr.ImportFromEPSG(6668) # JGD2011 - if not sr.IsSame(lyr.GetSpatialRef()): - gdaltest.post_reason('Wrong SRS') - return 'fail' + assert sr.IsSame(lyr.GetSpatialRef()), 'Wrong SRS' wkt = 'POLYGON ((139.718509733734 35.6952171397133,139.718444177734 35.6953121947133,139.718496754142 35.6953498949667,139.718550483734 35.6952359447133,139.718509733734 35.6952171397133))' # check the first feature feat = lyr.GetNextFeature() - if ogrtest.check_feature_geometry(feat, wkt): - gdaltest.post_reason('Wrong geometry') - return 'fail' - - if feat.GetField('devDate') != '2017-03-07': - gdaltest.post_reason('Wrong attribute value') - return 'fail' + assert not ogrtest.check_feature_geometry(feat, wkt), 'Wrong geometry' - return 'success' + assert feat.GetField('devDate') == '2017-03-07', 'Wrong attribute value' ############################################################################### # List test cases -gdaltest_list = [ - ogr_gml_fgd_1, - ogr_gml_fgd_2 -] - - -if __name__ == '__main__': - - gdaltest.setup_run('ogr_gml_fgd_read') - gdaltest.run_tests(gdaltest_list) - sys.exit(gdaltest.summarize()) diff --git a/autotest/ogr/ogr_gml_geom.py b/autotest/ogr/ogr_gml_geom.py index cc605e73798c..2fb7dd71e473 100755 --- a/autotest/ogr/ogr_gml_geom.py +++ b/autotest/ogr/ogr_gml_geom.py @@ -28,9 +28,8 @@ ############################################################################### import os -import sys -sys.path.append('../pymod') +import pytest import gdaltest import ogrtest @@ -41,73 +40,64 @@ ############################################################################### -class gml_geom_unit(object): - def __init__(self, unit): - self.unit = unit - - def gml_geom(self): - raw_wkt = open('data/wkb_wkt/' + self.unit + '.wkt').read() - - ###################################################################### - # Convert WKT to GML. +@pytest.mark.parametrize( + 'filename', + [ + f for f in os.listdir(os.path.join(os.path.dirname(__file__), 'data/wkb_wkt')) + if f[-4:] == '.wkt' + ] +) +def test_gml_geom(filename): + raw_wkt = open('data/wkb_wkt/' + filename).read() - geom_wkt = ogr.CreateGeometryFromWkt(raw_wkt) + ###################################################################### + # Convert WKT to GML. - gml = geom_wkt.ExportToGML() + geom_wkt = ogr.CreateGeometryFromWkt(raw_wkt) - if gml is None or not gml: - gdaltest.post_reason('Conversion to GML failed.') - return 'fail' + gml = geom_wkt.ExportToGML() - ###################################################################### - # Create geometry from GML. + assert gml is not None and gml, 'Conversion to GML failed.' - geom_gml = ogr.CreateGeometryFromGML(gml) + ###################################################################### + # Create geometry from GML. - if ogrtest.check_feature_geometry(geom_wkt, geom_gml, 0.0000000000001) == 1: - clean_wkt = geom_wkt.ExportToWkt() - gml_wkt = geom_gml.ExportToWkt() - gdaltest.post_reason('WKT from GML (%s) does not match clean WKT (%s).\ngml was (%s)' % (gml_wkt, clean_wkt, gml)) - return 'fail' + geom_gml = ogr.CreateGeometryFromGML(gml) - return 'success' + if ogrtest.check_feature_geometry(geom_wkt, geom_gml, 0.0000000000001) == 1: + clean_wkt = geom_wkt.ExportToWkt() + gml_wkt = geom_gml.ExportToWkt() + pytest.fail('WKT from GML (%s) does not match clean WKT (%s).\ngml was (%s)' % (gml_wkt, clean_wkt, gml)) + ############################################################################### # Test geometries with extra spaces at the end, as sometimes are generated # by ESRI WFS software. -def gml_space_test(): +def test_gml_space_test(): gml = '<gml:LineString xmlns:foo="http://bar"><gml:coordinates xmlns:foo="http://bar" decimal="." cs="," ts=" ">189999.99995605,624999.99998375 200000.00005735,624999.99998375 200000.00005735,612499.99997125 195791.3593843,612499.99997125 193327.3749823,612499.99997125 189999.99995605,612499.99997125 189999.99995605,619462.31247125 189999.99995605,624999.99998375 \n</gml:coordinates></gml:LineString>' geom = ogr.CreateGeometryFromGML(gml) - if geom is None or geom.GetGeometryType() is not ogr.wkbLineString \ - or geom.GetPointCount() != 8: - gdaltest.post_reason('GML not correctly parsed') - return 'fail' - - return 'success' + assert geom is not None and geom.GetGeometryType() is ogr.wkbLineString and geom.GetPointCount() == 8, \ + 'GML not correctly parsed' ############################################################################### # Test GML 3.x "pos" element for a point. -def gml_pos_point(): +def test_gml_pos_point(): gml = '<gml:Point xmlns:foo="http://bar"><gml:pos>31 29 16</gml:pos></gml:Point>' geom = ogr.CreateGeometryFromGML(gml) - if geom.ExportToWkt() != 'POINT (31 29 16)': - gdaltest.post_reason('<gml:pos> not correctly parsed') - return 'fail' - - return 'success' + assert geom.ExportToWkt() == 'POINT (31 29 16)', '<gml:pos> not correctly parsed' ############################################################################### # Test GML 3.1.1 "pos" element for a polygon. (ticket #3244) -def gml_pos_polygon(): +def test_gml_pos_polygon(): gml = '''<gml:Polygon xmlns:foo="http://bar"> <gml:exterior xmlns:foo="http://bar"> @@ -132,75 +122,60 @@ def gml_pos_polygon(): geom = ogr.CreateGeometryFromGML(gml) - if geom.ExportToWkt() != 'POLYGON ((0 0,4 0,4 4,0 4,0 0),(1 1,2 1,2 2,1 2,1 1))': - gdaltest.post_reason('<gml:Polygon> not correctly parsed') - return 'fail' - - return 'success' + assert geom.ExportToWkt() == 'POLYGON ((0 0,4 0,4 4,0 4,0 0),(1 1,2 1,2 2,1 2,1 1))', \ + '<gml:Polygon> not correctly parsed' ############################################################################### # Test GML 3.x "posList" element for a linestring. -def gml_posList_line(): +def test_gml_posList_line(): gml = '<LineString xmlns:foo="http://bar"><posList xmlns:foo="http://bar">31 42 53 64 55 76</posList></LineString>' geom = ogr.CreateGeometryFromGML(gml) - if geom.ExportToWkt() != 'LINESTRING (31 42,53 64,55 76)': - gdaltest.post_reason('<gml:posList> not correctly parsed') - return 'fail' - - return 'success' + assert geom.ExportToWkt() == 'LINESTRING (31 42,53 64,55 76)', \ + '<gml:posList> not correctly parsed' ############################################################################### # Test GML 3.x "posList" element for a 3D linestring. -def gml_posList_line3d(): +def test_gml_posList_line3d(): gml = '<LineString><posList xmlns:foo="http://bar" srsDimension="3">31 42 1 53 64 2 55 76 3</posList></LineString>' geom = ogr.CreateGeometryFromGML(gml) - if geom.ExportToWkt() != 'LINESTRING (31 42 1,53 64 2,55 76 3)': - gdaltest.post_reason('<gml:posList> not correctly parsed') - return 'fail' - - return 'success' + assert geom.ExportToWkt() == 'LINESTRING (31 42 1,53 64 2,55 76 3)', \ + '<gml:posList> not correctly parsed' ############################################################################### # Test GML 3.x "posList" element for a 3D linestring, but with srsDimension # set on LineString, not posList -def gml_posList_line3d_2(): +def test_gml_posList_line3d_2(): gml = '<LineString srsDimension="3"><posList>31 42 1 53 64 2 55 76 3</posList></LineString>' geom = ogr.CreateGeometryFromGML(gml) - if geom.ExportToWkt() != 'LINESTRING (31 42 1,53 64 2,55 76 3)': - gdaltest.post_reason('<gml:posList> not correctly parsed') - return 'fail' - - return 'success' + assert geom.ExportToWkt() == 'LINESTRING (31 42 1,53 64 2,55 76 3)', \ + '<gml:posList> not correctly parsed' ############################################################################### # Test GML 3.x "polygon" element for a point. -def gml_polygon(): +def test_gml_polygon(): gml = '<Polygon><exterior><LinearRing><posList>0 0 4 0 4 4 0 4 0 0</posList></LinearRing></exterior><interior xmlns:foo="http://bar"><LinearRing><posList xmlns:foo="http://bar">1 1 2 1 2 2 1 2 1 1</posList></LinearRing></interior></Polygon>' geom = ogr.CreateGeometryFromGML(gml) - if geom.ExportToWkt() != 'POLYGON ((0 0,4 0,4 4,0 4,0 0),(1 1,2 1,2 2,1 2,1 1))': - gdaltest.post_reason('<gml:Polygon> not correctly parsed') - return 'fail' - - return 'success' + assert geom.ExportToWkt() == 'POLYGON ((0 0,4 0,4 4,0 4,0 0),(1 1,2 1,2 2,1 2,1 1))', \ + '<gml:Polygon> not correctly parsed' ############################################################################### # Private utility function to convert WKT to GML with assigned WGS 84 as SRS. @@ -230,175 +205,131 @@ def _CreateGMLWithSRSFromWkt(wkt, epsg): # Test of Point geometry with SRS assigned -def gml_out_point_srs(): +def test_gml_out_point_srs(): wkt = 'POINT(21.675 53.763)' gml = _CreateGMLWithSRSFromWkt(wkt, 4326) - if gml is None or not gml: - gdaltest.post_reason('Conversion to GML failed.') - return 'fail' + assert gml is not None and gml, 'Conversion to GML failed.' - if gml[0:31] != '<gml:Point srsName="EPSG:4326">': - gdaltest.post_reason('No srsName attribute in GML output') - return 'fail' - - return 'success' + assert gml[0:31] == '<gml:Point srsName="EPSG:4326">', \ + 'No srsName attribute in GML output' ############################################################################### # Test of Point 3D geometry with SRS assigned -def gml_out_point3d_srs(): +def test_gml_out_point3d_srs(): wkt = 'POINT(21.675 53.763 100)' gml = _CreateGMLWithSRSFromWkt(wkt, 4326) - if gml is None or not gml: - gdaltest.post_reason('Conversion to GML failed.') - return 'fail' - - if gml[0:31] != '<gml:Point srsName="EPSG:4326">': - gdaltest.post_reason('No srsName attribute in GML output') - return 'fail' + assert gml is not None and gml, 'Conversion to GML failed.' - return 'success' + assert gml[0:31] == '<gml:Point srsName="EPSG:4326">', \ + 'No srsName attribute in GML output' ############################################################################### # Test of LineString geometry with SRS assigned -def gml_out_linestring_srs(): +def test_gml_out_linestring_srs(): wkt = open('data/wkb_wkt/5.wkt').read() gml = _CreateGMLWithSRSFromWkt(wkt, 4326) - if gml is None or not gml: - gdaltest.post_reason('Conversion to GML failed.') - return 'fail' + assert gml is not None and gml, 'Conversion to GML failed.' - if gml[0:36] != '<gml:LineString srsName="EPSG:4326">': - gdaltest.post_reason('No srsName attribute in GML output') - return 'fail' - - return 'success' + assert gml[0:36] == '<gml:LineString srsName="EPSG:4326">', \ + 'No srsName attribute in GML output' ############################################################################### # Test of Polygon geometry with SRS assigned -def gml_out_polygon_srs(): +def test_gml_out_polygon_srs(): wkt = open('data/wkb_wkt/6.wkt').read() gml = _CreateGMLWithSRSFromWkt(wkt, 4326) - if gml is None or not gml: - gdaltest.post_reason('Conversion to GML failed.') - return 'fail' - - if gml[0:33] != '<gml:Polygon srsName="EPSG:4326">': - gdaltest.post_reason('No srsName attribute in GML output') - return 'fail' + assert gml is not None and gml, 'Conversion to GML failed.' - return 'success' + assert gml[0:33] == '<gml:Polygon srsName="EPSG:4326">', \ + 'No srsName attribute in GML output' ############################################################################### # Test of MultiPoint geometry with SRS assigned -def gml_out_multipoint_srs(): +def test_gml_out_multipoint_srs(): wkt = open('data/wkb_wkt/11.wkt').read() gml = _CreateGMLWithSRSFromWkt(wkt, 4326) - if gml is None or not gml: - gdaltest.post_reason('Conversion to GML failed.') - return 'fail' - - if gml[0:36] != '<gml:MultiPoint srsName="EPSG:4326">': - gdaltest.post_reason('No srsName attribute in GML output') - return 'fail' + assert gml is not None and gml, 'Conversion to GML failed.' - return 'success' + assert gml[0:36] == '<gml:MultiPoint srsName="EPSG:4326">', \ + 'No srsName attribute in GML output' ############################################################################### # Test of MultiLineString geometry with SRS assigned -def gml_out_multilinestring_srs(): +def test_gml_out_multilinestring_srs(): wkt = open('data/wkb_wkt/2.wkt').read() gml = _CreateGMLWithSRSFromWkt(wkt, 4326) - if gml is None or not gml: - gdaltest.post_reason('Conversion to GML failed.') - return 'fail' + assert gml is not None and gml, 'Conversion to GML failed.' - if gml[0:41] != '<gml:MultiLineString srsName="EPSG:4326">': - gdaltest.post_reason('No srsName attribute in GML output') - return 'fail' - - return 'success' + assert gml[0:41] == '<gml:MultiLineString srsName="EPSG:4326">', \ + 'No srsName attribute in GML output' ############################################################################### # Test of MultiPolygon geometry with SRS assigned -def gml_out_multipolygon_srs(): +def test_gml_out_multipolygon_srs(): wkt = open('data/wkb_wkt/4.wkt').read() gml = _CreateGMLWithSRSFromWkt(wkt, 4326) - if gml is None or not gml: - gdaltest.post_reason('Conversion to GML failed.') - return 'fail' + assert gml is not None and gml, 'Conversion to GML failed.' - if gml[0:38] != '<gml:MultiPolygon srsName="EPSG:4326">': - gdaltest.post_reason('No srsName attribute in GML output') - print(gml) - return 'fail' + assert gml[0:38] == '<gml:MultiPolygon srsName="EPSG:4326">', \ + 'No srsName attribute in GML output' # Verify we have no other srsName's on subelements. - if gml[39:].find('srsName') != -1: - gdaltest.post_reason('Got extra srsName attributes on subelements.') - print(gml) - return 'fail' - - return 'success' + assert gml[39:].find('srsName') == -1, \ + 'Got extra srsName attributes on subelements.' ############################################################################### # Test of GeometryCollection with SRS assigned -def gml_out_geometrycollection_srs(): +def test_gml_out_geometrycollection_srs(): wkt = open('data/wkb_wkt/3.wkt').read() gml = _CreateGMLWithSRSFromWkt(wkt, 4326) - if gml is None or not gml: - gdaltest.post_reason('Conversion to GML failed.') - return 'fail' + assert gml is not None and gml, 'Conversion to GML failed.' - if gml[0:39] != '<gml:MultiGeometry srsName="EPSG:4326">': - gdaltest.post_reason('No srsName attribute in GML output') - print(gml) - return 'fail' - - return 'success' + assert gml[0:39] == '<gml:MultiGeometry srsName="EPSG:4326">', \ + 'No srsName attribute in GML output' ############################################################################### # Test GML Box -def gml_Box(): +def test_gml_Box(): gml = """<gml:Box xmlns:gml="http://www.opengis.net/gml" srsName="foo"> <gml:coord> @@ -413,18 +344,14 @@ def gml_Box(): geom = ogr.CreateGeometryFromGML(gml) - if geom.ExportToWkt() != 'POLYGON ((1 2 0,3 2 0,3 4 0,1 4 0,1 2 0))': - gdaltest.post_reason('<gml:Box> not correctly parsed') - print(geom.ExportToWkt()) - return 'fail' - - return 'success' + assert geom.ExportToWkt() == 'POLYGON ((1 2 0,3 2 0,3 4 0,1 4 0,1 2 0))', \ + '<gml:Box> not correctly parsed' ############################################################################### # Test GML Envelope -def gml_Envelope(): +def test_gml_Envelope(): gml = """<gml:Envelope xmlns:gml="http://www.opengis.net/gml" srsName="foo"> <gml:lowerCorner>1 2</gml:lowerCorner> @@ -433,18 +360,14 @@ def gml_Envelope(): geom = ogr.CreateGeometryFromGML(gml) - if geom.ExportToWkt() != 'POLYGON ((1 2,3 2,3 4,1 4,1 2))': - gdaltest.post_reason('<gml:Envelope> not correctly parsed') - print(geom.ExportToWkt()) - return 'fail' - - return 'success' + assert geom.ExportToWkt() == 'POLYGON ((1 2,3 2,3 4,1 4,1 2))', \ + '<gml:Envelope> not correctly parsed' ############################################################################### # Test GML Curve -def gml_Curve(): +def test_gml_Curve(): gml = """<gml:Curve xmlns:gml="http://www.opengis.net/gml" srsName="foo"> <gml:segments xmlns:foo="http://bar"> @@ -456,18 +379,14 @@ def gml_Curve(): geom = ogr.CreateGeometryFromGML(gml) - if geom.ExportToWkt() != 'LINESTRING (1 2,3 4)': - gdaltest.post_reason('<gml:Curve> not correctly parsed') - print(geom.ExportToWkt()) - return 'fail' - - return 'success' + assert geom.ExportToWkt() == 'LINESTRING (1 2,3 4)', \ + '<gml:Curve> not correctly parsed' ############################################################################### # Test GML Curve with pointProperty elements -def gml_Curve_with_pointProperty(): +def test_gml_Curve_with_pointProperty(): gml = """<gml:Curve xmlns:gml="http://www.opengis.net/gml" srsName="foo"> <gml:segments> @@ -484,18 +403,14 @@ def gml_Curve_with_pointProperty(): geom = ogr.CreateGeometryFromGML(gml) - if geom.ExportToWkt() != 'LINESTRING (1 2,3 4)': - gdaltest.post_reason('<gml:Curve> not correctly parsed') - print(geom.ExportToWkt()) - return 'fail' - - return 'success' + assert geom.ExportToWkt() == 'LINESTRING (1 2,3 4)', \ + '<gml:Curve> not correctly parsed' ############################################################################### # Test GML MultiCurve -def gml_MultiCurve(): +def test_gml_MultiCurve(): gml = """<gml:MultiCurve xmlns:foo="http://bar" xmlns:gml="http://www.opengis.net/gml" srsName="foo"> <gml:curveMember xmlns:foo="http://bar"> @@ -512,18 +427,14 @@ def gml_MultiCurve(): geom = ogr.CreateGeometryFromGML(gml) - if geom.ExportToWkt() != 'MULTILINESTRING ((1 2,2 3),(3 4,4 5))': - gdaltest.post_reason('<gml:MultiCurve> not correctly parsed') - print(geom.ExportToWkt()) - return 'fail' - - return 'success' + assert geom.ExportToWkt() == 'MULTILINESTRING ((1 2,2 3),(3 4,4 5))', \ + '<gml:MultiCurve> not correctly parsed' ############################################################################### # Test GML MultiSurface with PolygonPatch -def gml_MultiSurface(): +def test_gml_MultiSurface(): gml = """<gml:MultiSurface xmlns:gml="http://www.opengis.net/gml" srsName="foo"> <gml:surfaceMember xmlns:foo="http://bar" xlink:role="main"> @@ -595,18 +506,14 @@ def gml_MultiSurface(): geom = ogr.CreateGeometryFromGML(gml) - if geom.ExportToWkt() != 'MULTIPOLYGON (((1 2,3 4,5 6,1 2),(2 3,4 5,6 7,2 3),(3 4,5 6,7 8,3 4)),((4 5,6 7,8 9,4 5)))': - gdaltest.post_reason('<gml:MultiSurface> not correctly parsed') - print(geom.ExportToWkt()) - return 'fail' - - return 'success' + assert geom.ExportToWkt() == 'MULTIPOLYGON (((1 2,3 4,5 6,1 2),(2 3,4 5,6 7,2 3),(3 4,5 6,7 8,3 4)),((4 5,6 7,8 9,4 5)))', \ + '<gml:MultiSurface> not correctly parsed' ############################################################################### # Test GML MultiSurface with surfaceMembers -def gml_MultiSurface_surfaceMembers(): +def test_gml_MultiSurface_surfaceMembers(): gml = """<gml:MultiSurface xmlns:foo="http://bar"> <gml:surfaceMembers xmlns:foo="http://bar"> @@ -649,18 +556,14 @@ def gml_MultiSurface_surfaceMembers(): geom = ogr.CreateGeometryFromGML(gml) - if geom.ExportToWkt() != 'MULTIPOLYGON (((1 2,3 4,5 6,1 2),(2 3,4 5,6 7,2 3)),((3 4,5 6,7 8,3 4)),((30 40,50 60,70 80,30 40)))': - gdaltest.post_reason('<gml:MultiSurface> not correctly parsed') - print(geom.ExportToWkt()) - return 'fail' - - return 'success' + assert geom.ExportToWkt() == 'MULTIPOLYGON (((1 2,3 4,5 6,1 2),(2 3,4 5,6 7,2 3)),((3 4,5 6,7 8,3 4)),((30 40,50 60,70 80,30 40)))', \ + '<gml:MultiSurface> not correctly parsed' ############################################################################### # Test GML MultiCurve with curveMembers -def gml_MultiCurve_curveMembers(): +def test_gml_MultiCurve_curveMembers(): gml = """<gml:MultiCurve xmlns:foo="http://bar"> <gml:curveMembers xmlns:foo="http://bar"> @@ -672,17 +575,13 @@ def gml_MultiCurve_curveMembers(): geom = ogr.CreateGeometryFromGML(gml) - if geom.ExportToWkt() != 'MULTILINESTRING ((0 0,1 1))': - gdaltest.post_reason('<gml:MultiCurve> not correctly parsed') - print(geom.ExportToWkt()) - return 'fail' - - return 'success' + assert geom.ExportToWkt() == 'MULTILINESTRING ((0 0,1 1))', \ + '<gml:MultiCurve> not correctly parsed' ############################################################################### # Test GML MultiGeometry with geometryMembers -def gml_MultiGeometry_geometryMembers(): +def test_gml_MultiGeometry_geometryMembers(): gml = """<gml:MultiGeometry xmlns:foo="http://bar"> <gml:geometryMembers xmlns:foo="http://bar"> @@ -694,18 +593,14 @@ def gml_MultiGeometry_geometryMembers(): geom = ogr.CreateGeometryFromGML(gml) - if geom.ExportToWkt() != 'GEOMETRYCOLLECTION (LINESTRING (0 0,1 1))': - gdaltest.post_reason('<gml:MultiGeometry> not correctly parsed') - print(geom.ExportToWkt()) - return 'fail' - - return 'success' + assert geom.ExportToWkt() == 'GEOMETRYCOLLECTION (LINESTRING (0 0,1 1))', \ + '<gml:MultiGeometry> not correctly parsed' ############################################################################### # Test GML CompositeCurve with curveMembers -def gml_CompositeCurve_curveMembers(): +def test_gml_CompositeCurve_curveMembers(): gml = """<gml:CompositeCurve xmlns:foo="http://bar"> <gml:curveMembers xmlns:foo="http://bar"> @@ -720,18 +615,14 @@ def gml_CompositeCurve_curveMembers(): geom = ogr.CreateGeometryFromGML(gml) - if geom.ExportToWkt() != 'LINESTRING (0 0,1 1,2 2)': - gdaltest.post_reason('<gml:CompositeCurve> not correctly parsed') - print(geom.ExportToWkt()) - return 'fail' - - return 'success' + assert geom.ExportToWkt() == 'LINESTRING (0 0,1 1,2 2)', \ + '<gml:CompositeCurve> not correctly parsed' ############################################################################### # Test GML MultiPoint with pointMembers -def gml_MultiCurve_pointMembers(): +def test_gml_MultiCurve_pointMembers(): gml = """<gml:MultiPoint xmlns:foo="http://bar"> <gml:pointMembers xmlns:foo="http://bar"> @@ -746,17 +637,13 @@ def gml_MultiCurve_pointMembers(): geom = ogr.CreateGeometryFromGML(gml) - if geom.ExportToWkt() != 'MULTIPOINT (0 0,1 1)': - gdaltest.post_reason('<gml:MultiPoint> not correctly parsed') - print(geom.ExportToWkt()) - return 'fail' - - return 'success' + assert geom.ExportToWkt() == 'MULTIPOINT (0 0,1 1)', \ + '<gml:MultiPoint> not correctly parsed' ############################################################################### # Test GML Solid -def gml_Solid(): +def test_gml_Solid(): gml = """<gml:Solid xmlns:foo="http://bar" gml:id="UUID_cc5a9513-2d85-4f1a-869a-620400182e1f"> <gml:exterior xmlns:foo="http://bar"> @@ -776,18 +663,14 @@ def gml_Solid(): geom = ogr.CreateGeometryFromGML(gml) - if geom.ExportToWkt() != 'POLYHEDRALSURFACE Z (((1 2 0,3 4 0,5 6 0,1 2 0)))': - gdaltest.post_reason('<gml:Solid> not correctly parsed') - print(geom.ExportToWkt()) - return 'fail' - - return 'success' + assert geom.ExportToWkt() == 'POLYHEDRALSURFACE Z (((1 2 0,3 4 0,5 6 0,1 2 0)))', \ + '<gml:Solid> not correctly parsed' ############################################################################### # Test GML OrientableSurface -def gml_OrientableSurface(): +def test_gml_OrientableSurface(): gml = """<gml:OrientableSurface xmlns:foo="http://bar" orientation="+"> <gml:baseSurface xmlns:foo="http://bar"> @@ -805,18 +688,14 @@ def gml_OrientableSurface(): geom = ogr.CreateGeometryFromGML(gml) - if geom.ExportToWkt() != 'POLYGON ((-213.475 24.989 0,-213.475 24.989 8,-215.704 25.077 8,-215.704 25.077 0,-213.475 24.989 0))': - gdaltest.post_reason('<gml:OrientableSurface> not correctly parsed') - print(geom.ExportToWkt()) - return 'fail' - - return 'success' + assert geom.ExportToWkt() == 'POLYGON ((-213.475 24.989 0,-213.475 24.989 8,-215.704 25.077 8,-215.704 25.077 0,-213.475 24.989 0))', \ + '<gml:OrientableSurface> not correctly parsed' ############################################################################### # Test GML Triangle -def gml_Triangle(): +def test_gml_Triangle(): gml = """<gml:Triangle xmlns:foo="http://bar"> <gml:exterior> @@ -828,10 +707,8 @@ def gml_Triangle(): geom = ogr.CreateGeometryFromGML(gml) - if geom.ExportToWkt() != 'TRIANGLE ((0 0,0 1,1 1,0 0))': - gdaltest.post_reason('<gml:Triangle> not correctly parsed') - print(geom.ExportToWkt()) - return 'fail' + assert geom.ExportToWkt() == 'TRIANGLE ((0 0,0 1,1 1,0 0))', \ + '<gml:Triangle> not correctly parsed' # check the conversion of Triangle from OGR -> GML wkt_original = 'TRIANGLE ((0 0,0 1,0 1,0 0))' @@ -840,17 +717,15 @@ def gml_Triangle(): gml_string = triangle.ExportToGML(opts) if gml_string != '<gml:Triangle><gml:exterior><gml:LinearRing><gml:posList>0 0 0 1 0 1 0 0</gml:posList></gml:LinearRing></gml:exterior></gml:Triangle>': - gdaltest.post_reason('incorrect conversion from OGR -> GML for OGRTriangle') print(geom.ExportToWkt()) - return 'fail' - - return 'success' + pytest.fail('incorrect conversion from OGR -> GML for OGRTriangle') + ############################################################################### # Test GML Rectangle -def gml_Rectangle(): +def test_gml_Rectangle(): gml = """<gml:Rectangle xmlns:foo="http://bar"> <gml:exterior> @@ -862,18 +737,14 @@ def gml_Rectangle(): geom = ogr.CreateGeometryFromGML(gml) - if geom.ExportToWkt() != 'POLYGON ((0 0,0 1,1 1,1 0,0 0))': - gdaltest.post_reason('<gml:Rectangle> not correctly parsed') - print(geom.ExportToWkt()) - return 'fail' - - return 'success' + assert geom.ExportToWkt() == 'POLYGON ((0 0,0 1,1 1,1 0,0 0))', \ + '<gml:Rectangle> not correctly parsed' ############################################################################### # Test GML PolyhedralSurface -def gml_PolyhedralSurface(): +def test_gml_PolyhedralSurface(): # Conversion from GML -> OGR @@ -905,10 +776,8 @@ def gml_PolyhedralSurface(): # NOTE - this is actually an invalid PolyhedralSurface # need to assert geom.IsValid() == True to determine the validity of the geometry - if geom.ExportToWkt() != 'POLYHEDRALSURFACE Z (((1 2 3,4 5 6,7 8 9,1 2 3)),((10 11 12,13 14 15,16 17 18,10 11 12),(19 20 21,22 23 24,25 26 27,19 20 21)))': - gdaltest.post_reason('<gml:PolyhedralSurface> not correctly parsed') - print(geom.ExportToWkt()) - return 'fail' + assert geom.ExportToWkt() == 'POLYHEDRALSURFACE Z (((1 2 3,4 5 6,7 8 9,1 2 3)),((10 11 12,13 14 15,16 17 18,10 11 12),(19 20 21,22 23 24,25 26 27,19 20 21)))', \ + '<gml:PolyhedralSurface> not correctly parsed' # 1 patch and 2 rings gml = """<gml:PolyhedralSurface> @@ -933,10 +802,8 @@ def gml_PolyhedralSurface(): # NOTE - this is actually an invalid PolyhedralSurface # need to assert geom.IsValid() == True to determine the validity of the geometry - if geom.ExportToWkt() != 'POLYHEDRALSURFACE Z (((1 2 3,4 5 6,7 8 9,1 2 3)),((10 11 12,13 14 15,16 17 18,10 11 12)))': - gdaltest.post_reason('<gml:PolyhedralSurface> not correctly parsed') - print(geom.ExportToWkt()) - return 'fail' + assert geom.ExportToWkt() == 'POLYHEDRALSURFACE Z (((1 2 3,4 5 6,7 8 9,1 2 3)),((10 11 12,13 14 15,16 17 18,10 11 12)))', \ + '<gml:PolyhedralSurface> not correctly parsed' # Variations of empty PolyhedralSurface gml_strings = ['<gml:PolyhedralSurface></gml:PolyhedralSurface>', @@ -952,10 +819,8 @@ def gml_PolyhedralSurface(): for string in gml_strings: geom = ogr.CreateGeometryFromGML(string) - if geom.ExportToWkt() != 'POLYHEDRALSURFACE EMPTY': - gdaltest.post_reason('Empty <gml:PolyhedralSurface> not correctly parsed') - print(geom.ExportToWkt()) - return 'fail' + assert geom.ExportToWkt() == 'POLYHEDRALSURFACE EMPTY', \ + 'Empty <gml:PolyhedralSurface> not correctly parsed' # Conversion from OGR -> GML wkt_original = 'POLYHEDRALSURFACE Z (((0 0 0,0 0 1,0 1 1,0 1 0,0 0 0)),\ @@ -968,15 +833,13 @@ def gml_PolyhedralSurface(): opts = ["FORMAT=GML3"] string = ps.ExportToGML(opts) if string != '<gml:PolyhedralSurface><gml:polygonPatches><gml:PolygonPatch><gml:exterior><gml:LinearRing><gml:posList srsDimension="3">0 0 0 0 0 1 0 1 1 0 1 0 0 0 0</gml:posList></gml:LinearRing></gml:exterior></gml:PolygonPatch><gml:PolygonPatch><gml:exterior><gml:LinearRing><gml:posList srsDimension="3">0 0 0 0 1 0 1 1 0 1 0 0 0 0 0</gml:posList></gml:LinearRing></gml:exterior></gml:PolygonPatch><gml:PolygonPatch><gml:exterior><gml:LinearRing><gml:posList srsDimension="3">0 0 0 1 0 0 1 0 1 0 0 1 0 0 0</gml:posList></gml:LinearRing></gml:exterior></gml:PolygonPatch><gml:PolygonPatch><gml:exterior><gml:LinearRing><gml:posList srsDimension="3">1 1 0 1 1 1 1 0 1 1 0 0 1 1 0</gml:posList></gml:LinearRing></gml:exterior></gml:PolygonPatch><gml:PolygonPatch><gml:exterior><gml:LinearRing><gml:posList srsDimension="3">0 1 0 0 1 1 1 1 1 1 1 0 0 1 0</gml:posList></gml:LinearRing></gml:exterior></gml:PolygonPatch><gml:PolygonPatch><gml:exterior><gml:LinearRing><gml:posList srsDimension="3">0 0 1 1 0 1 1 1 1 0 1 1 0 0 1</gml:posList></gml:LinearRing></gml:exterior></gml:PolygonPatch></gml:polygonPatches></gml:PolyhedralSurface>': - gdaltest.post_reason('incorrect parsing of OGR -> GML for PolyhedralSurface') print(geom.ExportToWkt()) - return 'fail' + pytest.fail('incorrect parsing of OGR -> GML for PolyhedralSurface') g2 = ogr.CreateGeometryFromGML(string) if g2.Equals(ps) != 1: - gdaltest.post_reason('incorrect round-tripping') print(geom.ExportToWkt()) - return 'fail' + pytest.fail('incorrect round-tripping') # empty geometry wkt_original = 'POLYHEDRALSURFACE EMPTY' @@ -984,9 +847,8 @@ def gml_PolyhedralSurface(): opts = ["FORMAT=GML3"] string = ps.ExportToGML(opts) if string != '<gml:PolyhedralSurface><gml:polygonPatches></gml:polygonPatches></gml:PolyhedralSurface>': - gdaltest.post_reason('incorrect parsing of OGR -> GML for empty PolyhedralSurface') print(geom.ExportToWkt()) - return 'fail' + pytest.fail('incorrect parsing of OGR -> GML for empty PolyhedralSurface') # several polygon patches (and test that non elements such as comments are parsed OK) gml = """<gml:PolyhedralSurface> @@ -1013,10 +875,8 @@ def gml_PolyhedralSurface(): </gml:PolyhedralSurface>""" geom = ogr.CreateGeometryFromGML(gml) - if geom.ExportToWkt() != 'GEOMETRYCOLLECTION (POLYHEDRALSURFACE (((1 2 3,4 5 6,7 8 9,1 2 3))),POLYHEDRALSURFACE (((1 2 3,4 5 6,7 8 9,1 2 3))))': - gdaltest.post_reason('<gml:PolyhedralSurface> not correctly parsed') - print(geom.ExportToWkt()) - return 'fail' + assert geom.ExportToWkt() == 'GEOMETRYCOLLECTION (POLYHEDRALSURFACE (((1 2 3,4 5 6,7 8 9,1 2 3))),POLYHEDRALSURFACE (((1 2 3,4 5 6,7 8 9,1 2 3))))', \ + '<gml:PolyhedralSurface> not correctly parsed' # Test PolyhedralSurface with curve section (which we linearize since the SF PolyhedralSurface doesn't support curves) gml = """<gml:PolyhedralSurface> @@ -1046,18 +906,14 @@ def gml_PolyhedralSurface(): </gml:PolyhedralSurface>""" geom = ogr.CreateGeometryFromGML(gml) - if geom.ExportToWkt().find('POLYHEDRALSURFACE (((0 -1,0 1,') < 0: - gdaltest.post_reason('<gml:PolyhedralSurface> not correctly parsed') - print(geom.ExportToWkt()) - return 'fail' - - return 'success' + assert geom.ExportToWkt().find('POLYHEDRALSURFACE (((0 -1,0 1,') >= 0, \ + '<gml:PolyhedralSurface> not correctly parsed' ############################################################################### # Test GML Tin -def gml_Tin(): +def test_gml_Tin(): gml = """<gml:Tin xmlns:foo="http://bar"> <gml:patches xmlns:foo="http://bar"> @@ -1075,10 +931,8 @@ def gml_Tin(): # NOTE - this is actually an invalid TIN surface, as the triangle is incorrect # need to assert geom.IsValid() == True to determine the validity of the geometry - if geom.ExportToWkt() != 'TIN Z (((0 0 1,0 1 1,1 1 1,1 0 1,0 0 1)))': - gdaltest.post_reason('<gml:Tin> not correctly parsed') - print(geom.ExportToWkt()) - return 'fail' + assert geom.ExportToWkt() == 'TIN Z (((0 0 1,0 1 1,1 1 1,1 0 1,0 0 1)))', \ + '<gml:Tin> not correctly parsed' # Test for gml:TriangulatedSurface gml = """<gml:TriangulatedSurface> @@ -1102,10 +956,8 @@ def gml_Tin(): geom = ogr.CreateGeometryFromGML(gml) - if geom.ExportToWkt() != 'TIN Z (((0 0 0,0 0 1,0 1 0,0 0 0)),((0 0 0,0 1 0,1 1 0,0 0 0)))': - gdaltest.post_reason('<gml:Tin> not correctly parsed') - print(geom.ExportToWkt()) - return 'fail' + assert geom.ExportToWkt() == 'TIN Z (((0 0 0,0 0 1,0 1 0,0 0 0)),((0 0 0,0 1 0,1 1 0,0 0 0)))', \ + '<gml:Tin> not correctly parsed' # substituting gml:trianglePatches for gml:patches gml = """<gml:TriangulatedSurface> @@ -1129,10 +981,8 @@ def gml_Tin(): geom = ogr.CreateGeometryFromGML(gml) - if geom.ExportToWkt() != 'TIN Z (((0 0 0,0 0 1,0 1 0,0 0 0)),((0 0 0,0 1 0,1 1 0,0 0 0)))': - gdaltest.post_reason('<gml:Tin> not correctly parsed') - print(geom.ExportToWkt()) - return 'fail' + assert geom.ExportToWkt() == 'TIN Z (((0 0 0,0 0 1,0 1 0,0 0 0)),((0 0 0,0 1 0,1 1 0,0 0 0)))', \ + '<gml:Tin> not correctly parsed' # Part 2 - Create GML File from OGR Geometries wkt_original = 'TIN Z (((0 0 0,0 0 1,0 1 0,0 0 0)),((0 0 0,0 1 0,1 1 0,0 0 0)))' @@ -1142,17 +992,15 @@ def gml_Tin(): gml_string = tin.ExportToGML(opts) if gml_string != '<gml:TriangulatedSurface><gml:patches><gml:Triangle><gml:exterior><gml:LinearRing><gml:posList srsDimension="3">0 0 0 0 0 1 0 1 0 0 0 0</gml:posList></gml:LinearRing></gml:exterior></gml:Triangle><gml:Triangle><gml:exterior><gml:LinearRing><gml:posList srsDimension="3">0 0 0 0 1 0 1 1 0 0 0 0</gml:posList></gml:LinearRing></gml:exterior></gml:Triangle></gml:patches></gml:TriangulatedSurface>': - gdaltest.post_reason('OGRGeometry::TriangulatedSurface incorrectly converted') print(geom.ExportToWkt()) - return 'fail' - - return 'success' + pytest.fail('OGRGeometry::TriangulatedSurface incorrectly converted') + ############################################################################### # Test concatenated sections (#4451) -def gml_ConcatenatedDeduplication(): +def test_gml_ConcatenatedDeduplication(): gml = """<gml:Surface> <gml:patches> @@ -1182,15 +1030,9 @@ def gml_ConcatenatedDeduplication(): geom = ogr.CreateGeometryFromGML(gml) expected_wkt = 'CURVEPOLYGON (COMPOUNDCURVE ((0 -1,0 1),CIRCULARSTRING (0 1,1 0,0 -1)))' - if ogrtest.check_feature_geometry(geom, ogr.CreateGeometryFromWkt(expected_wkt)) != 0: - print(geom) - return 'fail' - - if ogrtest.have_geos() and not geom.IsValid(): - gdaltest.post_reason('geometry not valid') - return 'fail' + assert ogrtest.check_feature_geometry(geom, ogr.CreateGeometryFromWkt(expected_wkt)) == 0 - return 'success' + assert not ogrtest.have_geos() or geom.IsValid(), 'geometry not valid' ############################################################################### # Test OGRFormatDouble() to check for rounding errors (would also apply for KML output, or ogrinfo output) @@ -1201,26 +1043,18 @@ def gml_out_precision(): geom = ogr.CreateGeometryFromWkt('POINT(93538.15 1.23456789)') expected_gml = '<gml:Point><gml:coordinates>93538.15,1.23456789</gml:coordinates></gml:Point>' got_gml = geom.ExportToGML() - if got_gml != expected_gml: - gdaltest.post_reason('did not get expected gml') - print(got_gml) - return 'fail' + assert got_gml == expected_gml, 'did not get expected gml' geom = ogr.CreateGeometryFromWkt('POINT(93538.55 1234567.89)') expected_gml = '<gml:Point><gml:coordinates>93538.55,1234567.89</gml:coordinates></gml:Point>' got_gml = geom.ExportToGML() - if got_gml != expected_gml: - gdaltest.post_reason('did not get expected gml') - print(got_gml) - return 'fail' - - return 'success' + assert got_gml == expected_gml, 'did not get expected gml' ############################################################################### # Test various error cases of gml2ogrgeometry.cpp -def gml_invalid_geoms(): +def test_gml_invalid_geoms(): gml_expected_wkt_list = [ ('<?xml version="1.0" encoding="UTF-8"?>', None), @@ -1378,26 +1212,22 @@ def gml_invalid_geoms(): geom = ogr.CreateGeometryFromGML(gml) gdal.PopErrorHandler() if geom is None: - if expected_wkt is not None: - gdaltest.post_reason('did not get expected result for %s. Got None instead of %s' % (gml, expected_wkt)) - return 'fail' + assert expected_wkt is None, \ + ('did not get expected result for %s. Got None instead of %s' % (gml, expected_wkt)) else: wkt = geom.ExportToWkt() if expected_wkt is None: - gdaltest.post_reason('did not get expected result for %s. Got %s instead of None' % (gml, wkt)) - return 'fail' + pytest.fail('did not get expected result for %s. Got %s instead of None' % (gml, wkt)) else: - if wkt != expected_wkt: - gdaltest.post_reason('did not get expected result for %s. Got %s instead of %s' % (gml, wkt, expected_wkt)) - return 'fail' - - return 'success' + assert wkt == expected_wkt, \ + ('did not get expected result for %s. Got %s instead of %s' % (gml, wkt, expected_wkt)) + ############################################################################### # Test write support for GML3 -def gml_write_gml3_geometries(): +def test_gml_write_gml3_geometries(): gml_list = ['<gml:Point><gml:pos>2 3</gml:pos></gml:Point>', '<gml:Point><gml:pos>2 3 4</gml:pos></gml:Point>', @@ -1419,17 +1249,14 @@ def gml_write_gml3_geometries(): gml_out = geom.ExportToGML(['FORMAT=GML3', 'GML3_LINESTRING_ELEMENT=curve']) else: gml_out = geom.ExportToGML(['FORMAT=GML3']) - if gml_out != gml_in: - gdaltest.post_reason('got %s, instead of %s' % (gml_out, gml_in)) - return 'fail' - - return 'success' + assert gml_out == gml_in, ('got %s, instead of %s' % (gml_out, gml_in)) + ############################################################################### # Test write support for GML3 SRS -def gml_write_gml3_srs(): +def test_gml_write_gml3_srs(): sr32631 = osr.SpatialReference() sr32631.SetFromUserInput("EPSG:32631") @@ -1444,80 +1271,62 @@ def gml_write_gml3_srs(): geom.AssignSpatialReference(sr32631) gml3 = geom.ExportToGML(options=['FORMAT=GML3']) expected_gml = '<gml:Point srsName="urn:ogc:def:crs:EPSG::32631"><gml:pos>500000 4500000</gml:pos></gml:Point>' - if gml3 != expected_gml: - gdaltest.post_reason('got %s, instead of %s' % (gml3, expected_gml)) - return 'fail' + assert gml3 == expected_gml, ('got %s, instead of %s' % (gml3, expected_gml)) # Should perform the needed coordinate order swapping geom = ogr.CreateGeometryFromWkt('POINT(2 49)') geom.AssignSpatialReference(srlonglat) gml3 = geom.ExportToGML(options=['FORMAT=GML3']) expected_gml = '<gml:Point srsName="urn:ogc:def:crs:EPSG::4326"><gml:pos>49 2</gml:pos></gml:Point>' - if gml3 != expected_gml: - gdaltest.post_reason('got %s, instead of %s' % (gml3, expected_gml)) - return 'fail' + assert gml3 == expected_gml, ('got %s, instead of %s' % (gml3, expected_gml)) # Should not change the coordinate order. geom = ogr.CreateGeometryFromWkt('POINT(49 2)') geom.AssignSpatialReference(srlatlong) gml3 = geom.ExportToGML(options=['FORMAT=GML3']) expected_gml = '<gml:Point srsName="urn:ogc:def:crs:EPSG::4326"><gml:pos>49 2</gml:pos></gml:Point>' - if gml3 != expected_gml: - gdaltest.post_reason('got %s, instead of %s' % (gml3, expected_gml)) - return 'fail' + assert gml3 == expected_gml, ('got %s, instead of %s' % (gml3, expected_gml)) # Legacy SRS format geom = ogr.CreateGeometryFromWkt('POINT(2 49)') geom.AssignSpatialReference(srlonglat) gml3 = geom.ExportToGML(options=['FORMAT=GML3', 'GML3_LONGSRS=NO']) expected_gml = '<gml:Point srsName="EPSG:4326"><gml:pos>2 49</gml:pos></gml:Point>' - if gml3 != expected_gml: - gdaltest.post_reason('got %s, instead of %s' % (gml3, expected_gml)) - return 'fail' + assert gml3 == expected_gml, ('got %s, instead of %s' % (gml3, expected_gml)) # Test SRSNAME_FORMAT=SHORT geom = ogr.CreateGeometryFromWkt('POINT(2 49)') geom.AssignSpatialReference(srlonglat) gml3 = geom.ExportToGML(options=['FORMAT=GML3', 'SRSNAME_FORMAT=SHORT']) expected_gml = '<gml:Point srsName="EPSG:4326"><gml:pos>2 49</gml:pos></gml:Point>' - if gml3 != expected_gml: - gdaltest.post_reason('got %s, instead of %s' % (gml3, expected_gml)) - return 'fail' + assert gml3 == expected_gml, ('got %s, instead of %s' % (gml3, expected_gml)) # Test SRSNAME_FORMAT=SRSNAME_FORMAT geom = ogr.CreateGeometryFromWkt('POINT(2 49)') geom.AssignSpatialReference(srlonglat) gml3 = geom.ExportToGML(options=['FORMAT=GML3', 'SRSNAME_FORMAT=OGC_URN']) expected_gml = '<gml:Point srsName="urn:ogc:def:crs:EPSG::4326"><gml:pos>49 2</gml:pos></gml:Point>' - if gml3 != expected_gml: - gdaltest.post_reason('got %s, instead of %s' % (gml3, expected_gml)) - return 'fail' + assert gml3 == expected_gml, ('got %s, instead of %s' % (gml3, expected_gml)) # Test SRSNAME_FORMAT=OGC_URL geom = ogr.CreateGeometryFromWkt('POINT(2 49)') geom.AssignSpatialReference(srlonglat) gml3 = geom.ExportToGML(options=['FORMAT=GML3', 'SRSNAME_FORMAT=OGC_URL']) expected_gml = '<gml:Point srsName="http://www.opengis.net/def/crs/EPSG/0/4326"><gml:pos>49 2</gml:pos></gml:Point>' - if gml3 != expected_gml: - gdaltest.post_reason('got %s, instead of %s' % (gml3, expected_gml)) - return 'fail' - - return 'success' + assert gml3 == expected_gml, ('got %s, instead of %s' % (gml3, expected_gml)) ############################################################################### # Test that importing too nested GML doesn't cause stack overflows -def gml_nested(): +def test_gml_nested(): gml = '<gml:MultiGeometry><gml:geometryMember>' * 31 gml += '<gml:MultiPolygon></gml:MultiPolygon>' gml += '</gml:geometryMember></gml:MultiGeometry>' * 31 geom = ogr.CreateGeometryFromGML(gml) - if geom is None: - gdaltest.post_reason('expected a geometry') - return 'fail' + assert geom is not None, 'expected a geometry' gml = '<gml:MultiGeometry><gml:geometryMember>' * 32 gml += '<gml:MultiPolygon></gml:MultiPolygon>' @@ -1526,85 +1335,65 @@ def gml_nested(): gdal.PushErrorHandler('CPLQuietErrorHandler') geom = ogr.CreateGeometryFromGML(gml) gdal.PopErrorHandler() - if geom is not None: - gdaltest.post_reason('expected None') - return 'fail' - - return 'success' + assert geom is None, 'expected None' ############################################################################### # Test GML 3.3 SimplePolygon -def gml_SimplePolygon(): +def test_gml_SimplePolygon(): gml = """<gmlce:SimplePolygon><gml:posList>0 0 1 0 1 1 0 1</gml:posList></gmlce:SimplePolygon>""" geom = ogr.CreateGeometryFromGML(gml) - if geom.ExportToWkt() != 'POLYGON ((0 0,1 0,1 1,0 1,0 0))': - gdaltest.post_reason('<gmlce:SimplePolygon> not correctly parsed') - print(geom.ExportToWkt()) - return 'fail' - - return 'success' + assert geom.ExportToWkt() == 'POLYGON ((0 0,1 0,1 1,0 1,0 0))', \ + '<gmlce:SimplePolygon> not correctly parsed' ############################################################################### # Test GML 3.3 SimpleRectangle -def gml_SimpleRectangle(): +def test_gml_SimpleRectangle(): gml = """<gmlce:SimpleRectangle><gml:posList>0 0 1 0 1 1 0 1</gml:posList></gmlce:SimpleRectangle>""" geom = ogr.CreateGeometryFromGML(gml) - if geom.ExportToWkt() != 'POLYGON ((0 0,1 0,1 1,0 1,0 0))': - gdaltest.post_reason('<gmlce:SimpleRectangle> not correctly parsed') - print(geom.ExportToWkt()) - return 'fail' - - return 'success' + assert geom.ExportToWkt() == 'POLYGON ((0 0,1 0,1 1,0 1,0 0))', \ + '<gmlce:SimpleRectangle> not correctly parsed' ############################################################################### # Test GML 3.3 SimpleTriangle -def gml_SimpleTriangle(): +def test_gml_SimpleTriangle(): gml = """<gmlce:SimpleTriangle><gml:posList>0 0 1 0 1 1</gml:posList></gmlce:SimpleTriangle>""" geom = ogr.CreateGeometryFromGML(gml) - if geom.ExportToWkt() != 'TRIANGLE ((0 0,1 0,1 1,0 0))': - gdaltest.post_reason('<gmlce:SimpleTriangle> not correctly parsed') - print(geom.ExportToWkt()) - return 'fail' - - return 'success' + assert geom.ExportToWkt() == 'TRIANGLE ((0 0,1 0,1 1,0 0))', \ + '<gmlce:SimpleTriangle> not correctly parsed' ############################################################################### # Test GML 3.3 SimpleMultiPoint -def gml_SimpleMultiPoint(): +def test_gml_SimpleMultiPoint(): gml = """<gmlce:SimpleMultiPoint><gml:posList>0 1 2 3</gml:posList></gmlce:SimpleMultiPoint>""" geom = ogr.CreateGeometryFromGML(gml) - if geom.ExportToWkt() != 'MULTIPOINT (0 1,2 3)': - gdaltest.post_reason('<gmlce:SimpleMultiPoint> not correctly parsed') - print(geom.ExportToWkt()) - return 'fail' - - return 'success' + assert geom.ExportToWkt() == 'MULTIPOINT (0 1,2 3)', \ + '<gmlce:SimpleMultiPoint> not correctly parsed' ############################################################################### # Test gml:CompositeCurve> in <gml:Ring> -def gml_CompositeCurveInRing(): +def test_gml_CompositeCurveInRing(): gml = """<gml:Surface> <gml:patches> @@ -1653,17 +1442,13 @@ def gml_CompositeCurveInRing(): geom = ogr.CreateGeometryFromGML(gml) - if geom.ExportToWkt() != 'POLYGON ((0 0,0 1,1 1,0 0))': - print(geom.ExportToWkt()) - return 'fail' - - return 'success' + assert geom.ExportToWkt() == 'POLYGON ((0 0,0 1,1 1,0 0))' ############################################################################### # Test <gml:CompositeSurface> in <gml:surfaceMembers> (#5369) -def gml_CompositeSurface_in_surfaceMembers(): +def test_gml_CompositeSurface_in_surfaceMembers(): gml = """<gml:MultiSurface> <gml:surfaceMembers> @@ -1692,17 +1477,13 @@ def gml_CompositeSurface_in_surfaceMembers(): geom = ogr.CreateGeometryFromGML(gml) - if geom.ExportToWkt() != 'MULTIPOLYGON (((0 0,0 1,1 1,1 0,0 0)),((2 0,2 1,3 1,3 0,2 0)))': - print(geom.ExportToWkt()) - return 'fail' - - return 'success' + assert geom.ExportToWkt() == 'MULTIPOLYGON (((0 0,0 1,1 1,1 0,0 0)),((2 0,2 1,3 1,3 0,2 0)))' ############################################################################### # Test <gml:PolygonPatch> with only Interior ring (#5421) -def gml_MultiSurfaceOfSurfaceOfPolygonPatchWithInteriorRing(): +def test_gml_MultiSurfaceOfSurfaceOfPolygonPatchWithInteriorRing(): gml = """<gml:MultiSurface> <gml:surfaceMember> @@ -1748,17 +1529,13 @@ def gml_MultiSurfaceOfSurfaceOfPolygonPatchWithInteriorRing(): geom = ogr.CreateGeometryFromGML(gml) - if geom.ExportToWkt() != 'MULTIPOLYGON (((0 0,0 1,1 1,1 0,0 0),(0.25 0.25,0.25 0.75,0.75 0.75,0.75 0.25,0.25 0.25)),((0 0,0 -1,-1 -1,-1 0,0 0)))': - print(geom.ExportToWkt()) - return 'fail' - - return 'success' + assert geom.ExportToWkt() == 'MULTIPOLYGON (((0 0,0 1,1 1,1 0,0 0),(0.25 0.25,0.25 0.75,0.75 0.75,0.75 0.25,0.25 0.25)),((0 0,0 -1,-1 -1,-1 0,0 0)))' ############################################################################### # Test ts, cs and decimal attributes of gml:coordinates -def gml_Coordinates_ts_cs_decimal(): +def test_gml_Coordinates_ts_cs_decimal(): gml_expected_wkt_list = [ ('<gml:Point><gml:coordinates>1,2</gml:coordinates></gml:Point>', 'POINT (1 2)'), # default values @@ -1781,20 +1558,17 @@ def gml_Coordinates_ts_cs_decimal(): geom = ogr.CreateGeometryFromGML(gml) wkt = geom.ExportToWkt() if expected_wkt is None: - gdaltest.post_reason('did not get expected result for %s. Got %s instead of None' % (gml, wkt)) - return 'fail' + pytest.fail('did not get expected result for %s. Got %s instead of None' % (gml, wkt)) else: - if wkt != expected_wkt: - gdaltest.post_reason('did not get expected result for %s. Got %s instead of %s' % (gml, wkt, expected_wkt)) - return 'fail' - - return 'success' + assert wkt == expected_wkt, \ + ('did not get expected result for %s. Got %s instead of %s' % (gml, wkt, expected_wkt)) + ############################################################################### # Test gml with XML header and comments -def gml_with_xml_header_and_comments(): +def test_gml_with_xml_header_and_comments(): gml_expected_wkt_list = [ ('<?xml version="1.0" encoding="UTF-8"?><!-- comment --><gml:Point> <!-- comment --> <gml:coordinates>1,2</gml:coordinates></gml:Point>', 'POINT (1 2)'), @@ -1825,20 +1599,17 @@ def gml_with_xml_header_and_comments(): geom = ogr.CreateGeometryFromGML(gml) wkt = geom.ExportToWkt() if expected_wkt is None: - gdaltest.post_reason('did not get expected result for %s. Got %s instead of None' % (gml, wkt)) - return 'fail' + pytest.fail('did not get expected result for %s. Got %s instead of None' % (gml, wkt)) else: - if wkt != expected_wkt: - gdaltest.post_reason('did not get expected result for %s. Got %s instead of %s' % (gml, wkt, expected_wkt)) - return 'fail' - - return 'success' + assert wkt == expected_wkt, \ + ('did not get expected result for %s. Got %s instead of %s' % (gml, wkt, expected_wkt)) + ############################################################################### # Test srsDimension attribute on top-level geometry and not on posList (#5606) -def gml_srsDimension_topgeometry(): +def test_gml_srsDimension_topgeometry(): gml = """<gml:Surface srsName="EPSG:25832" srsDimension="3"> <gml:patches> @@ -1856,80 +1627,54 @@ def gml_srsDimension_topgeometry(): geom = ogr.CreateGeometryFromGML(gml) - if geom.ExportToWkt() != 'POLYGON ((0 0 10,0 1 10,1 1 10,1 0 10,0 0 10))': - gdaltest.post_reason('fail') - print(geom.ExportToWkt()) - return 'fail' - - return 'success' + assert geom.ExportToWkt() == 'POLYGON ((0 0 10,0 1 10,1 1 10,1 0 10,0 0 10))' ############################################################################### # Test GML Arc -def gml_Arc(): +def test_gml_Arc(): gml = "<gml:Arc><gml:posList>1 0 0 1 -1 0</gml:posList></gml:Arc>" geom = ogr.CreateGeometryFromGML(gml) - if ogrtest.check_feature_geometry(geom, ogr.CreateGeometryFromWkt('CIRCULARSTRING (1 0,0 1,-1 0)')) != 0: - gdaltest.post_reason('fail') - print(geom) - return 'fail' + assert ogrtest.check_feature_geometry(geom, ogr.CreateGeometryFromWkt('CIRCULARSTRING (1 0,0 1,-1 0)')) == 0 gml2 = geom.ExportToGML(['FORMAT=GML3']) expected_gml2 = '<gml:Curve><gml:segments><gml:ArcString><gml:posList>1 0 0 1 -1 0</gml:posList></gml:ArcString></gml:segments></gml:Curve>' - if gml2 != expected_gml2: - gdaltest.post_reason('fail') - print(gml2) - return 'fail' + assert gml2 == expected_gml2 geom2 = ogr.CreateGeometryFromGML(gml2) - if not geom.Equals(geom2): - gdaltest.post_reason('fail') - print(geom2) - return 'fail' - - return 'success' + assert geom.Equals(geom2) ############################################################################### # Test GML ArcByBulge -def gml_ArcByBulge(): +def test_gml_ArcByBulge(): gml = "<gml:ArcByBulge><gml:posList>2 0 -2 0</gml:posList><gml:bulge>2</gml:bulge><gml:normal>-1</gml:normal></gml:ArcByBulge>" geom = ogr.CreateGeometryFromGML(gml) - if ogrtest.check_feature_geometry(geom, ogr.CreateGeometryFromWkt('CIRCULARSTRING (2 0,0 2,-2 0)')) != 0: - gdaltest.post_reason('fail') - print(geom) - return 'fail' - - return 'success' + assert ogrtest.check_feature_geometry(geom, ogr.CreateGeometryFromWkt('CIRCULARSTRING (2 0,0 2,-2 0)')) == 0 ############################################################################### # Test GML ArcByCenterPoint -def gml_ArcByCenterPoint(): +def test_gml_ArcByCenterPoint(): gml = "<gml:ArcByCenterPoint><gml:pos>1 2</gml:pos><gml:radius>2</gml:radius><gml:startAngle>90</gml:startAngle><gml:endAngle>270</gml:endAngle></gml:ArcByCenterPoint>" geom = ogr.CreateGeometryFromGML(gml) - if ogrtest.check_feature_geometry(geom, ogr.CreateGeometryFromWkt('CIRCULARSTRING (1 4,-1 2,1 0)')) != 0: - gdaltest.post_reason('fail') - print(geom) - return 'fail' - - return 'success' + assert ogrtest.check_feature_geometry(geom, ogr.CreateGeometryFromWkt('CIRCULARSTRING (1 4,-1 2,1 0)')) == 0 ############################################################################### # Test compound curve of ArcByCenterPoint whose ends don't exactly match # with ends of neighbouring curves, as found in some AIXM files -def gml_CompoundCurve_of_ArcByCenterPoint(): +def test_gml_CompoundCurve_of_ArcByCenterPoint(): gml = """ <Surface gml:id="Surface1" srsDimension="2" srsName="URN:OGC:DEF:CRS:OGC:1.3:CRS84"> @@ -1980,34 +1725,24 @@ def gml_CompoundCurve_of_ArcByCenterPoint(): </Surface>""" geom = ogr.CreateGeometryFromGML(gml) - if ogrtest.check_feature_geometry(geom, ogr.CreateGeometryFromWkt('POLYGON ((-80.4 33.86,-80.27 33.63,-80.305028054229538 33.622017309598967,-80.335422529369936 33.613343178471617,-80.366464292754429 33.606448070493634,-80.398003921948742 33.601365147653873,-80.429889693662162 33.598118851265042,-80.461968286017793 33.596724788982847,-80.494085487001527 33.597189662699385,-80.52608690656875 33.599511237590342,-80.557818688893789 33.603678352435914,-80.589128223167393 33.609670971175497,-80.619864849221443 33.617460275496377,-80.63 33.62,-80.39 33.85))')) != 0: - gdaltest.post_reason('fail') - print(geom) - return 'fail' - - return 'success' + assert ogrtest.check_feature_geometry(geom, ogr.CreateGeometryFromWkt('POLYGON ((-80.4 33.86,-80.27 33.63,-80.305028054229538 33.622017309598967,-80.335422529369936 33.613343178471617,-80.366464292754429 33.606448070493634,-80.398003921948742 33.601365147653873,-80.429889693662162 33.598118851265042,-80.461968286017793 33.596724788982847,-80.494085487001527 33.597189662699385,-80.52608690656875 33.599511237590342,-80.557818688893789 33.603678352435914,-80.589128223167393 33.609670971175497,-80.619864849221443 33.617460275496377,-80.63 33.62,-80.39 33.85))')) == 0 ############################################################################### # Test GML CircleByCenterPoint -def gml_CircleByCenterPoint(): +def test_gml_CircleByCenterPoint(): gml = "<gml:CircleByCenterPoint><gml:pos>1 2</gml:pos><gml:radius>2</gml:radius></gml:CircleByCenterPoint>" geom = ogr.CreateGeometryFromGML(gml) - if ogrtest.check_feature_geometry(geom, ogr.CreateGeometryFromWkt('CIRCULARSTRING (-1 2,3 2,-1 2)')) != 0: - gdaltest.post_reason('fail') - print(geom) - return 'fail' - - return 'success' + assert ogrtest.check_feature_geometry(geom, ogr.CreateGeometryFromWkt('CIRCULARSTRING (-1 2,3 2,-1 2)')) == 0 ############################################################################### # Test GML Circle -def gml_Circle(): +def test_gml_Circle(): gml = """<gml:Curve><gml:segments><gml:Circle> <gml:posList>-1 0 0 1 -0.707106781186547 -0.707106781186548</gml:posList> @@ -2016,31 +1751,20 @@ def gml_Circle(): geom = ogr.CreateGeometryFromGML(gml) expected_wkt = 'CIRCULARSTRING (-1 0,0 1,-0.707106781186547 -0.707106781186548,-0.923879532511287 -0.38268343236509,-1 0)' - if ogrtest.check_feature_geometry(geom, ogr.CreateGeometryFromWkt(expected_wkt)) != 0: - print(geom) - return 'fail' + assert ogrtest.check_feature_geometry(geom, ogr.CreateGeometryFromWkt(expected_wkt)) == 0 geom = ogr.CreateGeometryFromWkt('CIRCULARSTRING (0 0,2 0,0 0)') gml2 = geom.ExportToGML(['FORMAT=GML3']) expected_gml2 = '<gml:Curve><gml:segments><gml:Circle><gml:posList>0 0 1 1 2 0</gml:posList></gml:Circle></gml:segments></gml:Curve>' - if gml2 != expected_gml2: - gdaltest.post_reason('fail') - print(gml2) - return 'fail' + assert gml2 == expected_gml2 geom2 = ogr.CreateGeometryFromGML(gml2) - if geom2.ExportToWkt() != 'CIRCULARSTRING (0 0,1 1,2 0,1 -1,0 0)': - gdaltest.post_reason('fail') - print(geom2) - return 'fail' + assert geom2.ExportToWkt() == 'CIRCULARSTRING (0 0,1 1,2 0,1 -1,0 0)' geom = ogr.CreateGeometryFromWkt('CIRCULARSTRING (0 0 10,2 0 10,0 0 10)') gml2 = geom.ExportToGML(['FORMAT=GML3']) expected_gml2 = '<gml:Curve><gml:segments><gml:Circle><gml:posList srsDimension="3">0 0 10 1 1 10 2 0 10</gml:posList></gml:Circle></gml:segments></gml:Curve>' - if gml2 != expected_gml2: - gdaltest.post_reason('fail') - print(gml2) - return 'fail' + assert gml2 == expected_gml2 gml = """<gml:PolygonPatch> <gml:exterior> @@ -2061,81 +1785,54 @@ def gml_Circle(): geom = ogr.CreateGeometryFromGML(gml) expected_wkt = 'CURVEPOLYGON ( CIRCULARSTRING (-1 0,0 1,-0.707106781186547 -0.707106781186548,-0.923879532511287 -0.38268343236509,-1 0))' - if ogrtest.check_feature_geometry(geom, ogr.CreateGeometryFromWkt(expected_wkt)) != 0: - print(geom) - return 'fail' - - return 'success' + assert ogrtest.check_feature_geometry(geom, ogr.CreateGeometryFromWkt(expected_wkt)) == 0 ############################################################################### # Test ArcString -def gml_ArcString(): +def test_gml_ArcString(): gml = """<gml:ArcString><gml:posList srsDimension="2">-2 0 -1 -1 0 0</gml:posList></gml:ArcString>""" geom = ogr.CreateGeometryFromGML(gml) - if geom.ExportToWkt() != 'CIRCULARSTRING (-2 0,-1 -1,0 0)': - print(geom.ExportToWkt()) - return 'fail' + assert geom.ExportToWkt() == 'CIRCULARSTRING (-2 0,-1 -1,0 0)' gml = """<gml:ArcString><gml:posList srsDimension="2">-2 0 -1 -1 0 0 1 -1 2 0 0 2 -2 0</gml:posList></gml:ArcString>""" geom = ogr.CreateGeometryFromGML(gml) - if geom.ExportToWkt() != 'CIRCULARSTRING (-2 0,-1 -1,0 0,1 -1,2 0,0 2,-2 0)': - print(geom.ExportToWkt()) - return 'fail' + assert geom.ExportToWkt() == 'CIRCULARSTRING (-2 0,-1 -1,0 0,1 -1,2 0,0 2,-2 0)' gml2 = geom.ExportToGML(['FORMAT=GML3']) expected_gml2 = '<gml:Curve><gml:segments><gml:ArcString><gml:posList>-2 0 -1 -1 0 0 1 -1 2 0 0 2 -2 0</gml:posList></gml:ArcString></gml:segments></gml:Curve>' - if gml2 != expected_gml2: - gdaltest.post_reason('fail') - print(gml2) - return 'fail' + assert gml2 == expected_gml2 geom2 = ogr.CreateGeometryFromGML(gml2) - if geom2.ExportToWkt() != 'CIRCULARSTRING (-2 0,-1 -1,0 0,1 -1,2 0,0 2,-2 0)': - gdaltest.post_reason('fail') - print(geom2) - return 'fail' - - return 'success' + assert geom2.ExportToWkt() == 'CIRCULARSTRING (-2 0,-1 -1,0 0,1 -1,2 0,0 2,-2 0)' ############################################################################### # Test OGRCompoundCurve -def gml_OGRCompoundCurve(): +def test_gml_OGRCompoundCurve(): wkt = 'COMPOUNDCURVE ((0 0,1 1,2 0))' geom = ogr.CreateGeometryFromWkt(wkt) gml = geom.ExportToGML(['FORMAT=GML3']) expected_gml = '<gml:CompositeCurve><gml:curveMember><gml:LineString><gml:posList>0 0 1 1 2 0</gml:posList></gml:LineString></gml:curveMember></gml:CompositeCurve>' - if gml != expected_gml: - gdaltest.post_reason('fail') - print(gml) - return 'fail' + assert gml == expected_gml # CompositeCurve of LineStringSegment gml = expected_gml geom = ogr.CreateGeometryFromGML(gml) # We simplify it in LINESTRING - if geom.ExportToWkt() != 'LINESTRING (0 0,1 1,2 0)': - # if geom.ExportToWkt() != wkt - print(geom.ExportToWkt()) - return 'fail' + assert geom.ExportToWkt() == 'LINESTRING (0 0,1 1,2 0)' # CompositeCurve of Arc gml = """<gml:CompositeCurve><gml:curveMember><gml:Curve><gml:segments><gml:ArcString><gml:posList>0 0 1 1 2 0</gml:posList></gml:ArcString></gml:segments></gml:Curve></gml:curveMember></gml:CompositeCurve>""" geom = ogr.CreateGeometryFromGML(gml) - if geom.ExportToWkt() != 'COMPOUNDCURVE (CIRCULARSTRING (0 0,1 1,2 0))': - print(geom.ExportToWkt()) - return 'fail' + assert geom.ExportToWkt() == 'COMPOUNDCURVE (CIRCULARSTRING (0 0,1 1,2 0))' gml2 = geom.ExportToGML(['FORMAT=GML3']) - if gml2 != gml: - gdaltest.post_reason('fail') - print(gml2) - return 'fail' + assert gml2 == gml # CompositeCurve of 3 arcs gml = """<gml:CompositeCurve> @@ -2144,9 +1841,7 @@ def gml_OGRCompoundCurve(): <gml:curveMember><gml:Curve><gml:segments><gml:Arc><gml:posList>4 0 5 1 6 0</gml:posList></gml:Arc></gml:segments></gml:Curve></gml:curveMember> </gml:CompositeCurve>""" geom = ogr.CreateGeometryFromGML(gml) - if geom.ExportToWkt() != 'COMPOUNDCURVE (CIRCULARSTRING (0 0,1 1,2 0),CIRCULARSTRING (2 0,3 1,4 0),CIRCULARSTRING (4 0,5 1,6 0))': - print(geom.ExportToWkt()) - return 'fail' + assert geom.ExportToWkt() == 'COMPOUNDCURVE (CIRCULARSTRING (0 0,1 1,2 0),CIRCULARSTRING (2 0,3 1,4 0),CIRCULARSTRING (4 0,5 1,6 0))' # Alternative syntax : Curve with 3 Arc segments gml = """<gml:Curve><gml:segments> @@ -2155,9 +1850,7 @@ def gml_OGRCompoundCurve(): <gml:Arc><gml:posList>4 0 5 1 6 0</gml:posList></gml:Arc> </gml:segments></gml:Curve>""" geom = ogr.CreateGeometryFromGML(gml) - if geom.ExportToWkt() != 'COMPOUNDCURVE (CIRCULARSTRING (0 0,1 1,2 0),CIRCULARSTRING (2 0,3 1,4 0),CIRCULARSTRING (4 0,5 1,6 0))': - print(geom.ExportToWkt()) - return 'fail' + assert geom.ExportToWkt() == 'COMPOUNDCURVE (CIRCULARSTRING (0 0,1 1,2 0),CIRCULARSTRING (2 0,3 1,4 0),CIRCULARSTRING (4 0,5 1,6 0))' # Curve with LineStringSegment and Arc segments gml = """<gml:Curve><gml:segments> @@ -2165,9 +1858,7 @@ def gml_OGRCompoundCurve(): <gml:LineStringSegment><gml:posList>0 0 -1 0 0 0</gml:posList></gml:LineStringSegment> </gml:segments></gml:Curve>""" geom = ogr.CreateGeometryFromGML(gml) - if geom.ExportToWkt() != 'COMPOUNDCURVE (CIRCULARSTRING (0 0,1 0,0 0),(0 0,-1 0,0 0))': - print(geom.ExportToWkt()) - return 'fail' + assert geom.ExportToWkt() == 'COMPOUNDCURVE (CIRCULARSTRING (0 0,1 0,0 0),(0 0,-1 0,0 0))' # Composite curve of a LineString and a (Composite) Curve with an Arc and a LineString gml = """<gml:CompositeCurve> @@ -2180,68 +1871,50 @@ def gml_OGRCompoundCurve(): </gml:curveMember> </gml:CompositeCurve>""" geom = ogr.CreateGeometryFromGML(gml) - if geom.ExportToWkt() != 'COMPOUNDCURVE ((0 0,1 0,0 0),CIRCULARSTRING (0 0,1 0,0 0),(0 0,-1 0,0 0))': - print(geom.ExportToWkt()) - return 'fail' - - return 'success' + assert geom.ExportToWkt() == 'COMPOUNDCURVE ((0 0,1 0,0 0),CIRCULARSTRING (0 0,1 0,0 0),(0 0,-1 0,0 0))' ############################################################################### # Test OGRCurvePolygon -def gml_OGRCurvePolygon(): +def test_gml_OGRCurvePolygon(): # Test one CircularString gml = """<gml:Polygon><gml:exterior><gml:Ring><gml:curveMember><gml:Arc><gml:posList>0 0 1 0 0 0</gml:posList></gml:Arc></gml:curveMember></gml:Ring></gml:exterior></gml:Polygon>""" geom = ogr.CreateGeometryFromGML(gml) - if geom.ExportToWkt() != 'CURVEPOLYGON (CIRCULARSTRING (0 0,1 0,0 0))': - print(geom.ExportToWkt()) - return 'fail' + assert geom.ExportToWkt() == 'CURVEPOLYGON (CIRCULARSTRING (0 0,1 0,0 0))' gml2 = geom.ExportToGML(['FORMAT=GML3']) expected_gml2 = '<gml:Polygon><gml:exterior><gml:Curve><gml:segments><gml:Circle><gml:posList>0 0 0.5 0.5 1 0</gml:posList></gml:Circle></gml:segments></gml:Curve></gml:exterior></gml:Polygon>' - if gml2 != expected_gml2: - gdaltest.post_reason('fail') - print(gml2) - return 'fail' + assert gml2 == expected_gml2 # Test two CircularString gml = """<gml:Polygon><gml:exterior><gml:Ring><gml:curveMember><gml:Arc><gml:posList>0 0 1 0 0 0</gml:posList></gml:Arc></gml:curveMember></gml:Ring></gml:exterior><gml:interior><gml:Ring><gml:curveMember><gml:Arc><gml:posList>0.25 0 0.75 0 0.25 0</gml:posList></gml:Arc></gml:curveMember></gml:Ring></gml:interior></gml:Polygon>""" geom = ogr.CreateGeometryFromGML(gml) - if geom.ExportToWkt() != 'CURVEPOLYGON (CIRCULARSTRING (0 0,1 0,0 0),CIRCULARSTRING (0.25 0.0,0.75 0.0,0.25 0.0))': - print(geom.ExportToWkt()) - return 'fail' + assert geom.ExportToWkt() == 'CURVEPOLYGON (CIRCULARSTRING (0 0,1 0,0 0),CIRCULARSTRING (0.25 0.0,0.75 0.0,0.25 0.0))' # Test a LinearRing followed by a CircularString gml = """<gml:Polygon><gml:exterior><gml:LinearRing><gml:posList>-2 -2 -2 2 2 2 2 -2 -2 -2</gml:posList></gml:LinearRing></gml:exterior><gml:interior><gml:Ring><gml:curveMember><gml:Arc><gml:posList>0.25 0 0.75 0 0.25 0</gml:posList></gml:Arc></gml:curveMember></gml:Ring></gml:interior></gml:Polygon>""" geom = ogr.CreateGeometryFromGML(gml) - if geom.ExportToWkt() != 'CURVEPOLYGON ((-2 -2,-2 2,2 2,2 -2,-2 -2),CIRCULARSTRING (0.25 0.0,0.75 0.0,0.25 0.0))': - print(geom.ExportToWkt()) - return 'fail' + assert geom.ExportToWkt() == 'CURVEPOLYGON ((-2 -2,-2 2,2 2,2 -2,-2 -2),CIRCULARSTRING (0.25 0.0,0.75 0.0,0.25 0.0))' # Test a CircularString followed by a LinearRing gml = """<gml:Polygon><gml:exterior><gml:Ring><gml:curveMember><gml:Circle><gml:posList>-1 0 1 2 3 0</gml:posList></gml:Circle></gml:curveMember></gml:Ring></gml:exterior><gml:interior><gml:LinearRing><gml:posList>-2 -2 -2 2 2 2 2 -2 -2 -2</gml:posList></gml:LinearRing></gml:interior></gml:Polygon>""" geom = ogr.CreateGeometryFromGML(gml) - if ogrtest.check_feature_geometry(geom, 'CURVEPOLYGON (CIRCULARSTRING (-1 0,1 2,3 0,1.0 -2.0,-1 0),(-2 -2,-2 2,2 2,2 -2,-2 -2))') != 0: - print(geom.ExportToWkt()) - return 'fail' + assert ogrtest.check_feature_geometry(geom, 'CURVEPOLYGON (CIRCULARSTRING (-1 0,1 2,3 0,1.0 -2.0,-1 0),(-2 -2,-2 2,2 2,2 -2,-2 -2))') == 0, \ + geom.ExportToWkt() gml2 = geom.ExportToGML(['FORMAT=GML3']) geom2 = ogr.CreateGeometryFromGML(gml) expected_gml2 = '<gml:Polygon><gml:exterior><gml:Curve><gml:segments><gml:ArcString><gml:posList>-1 0 1 2 3 0 1 -2 -1 0</gml:posList></gml:ArcString></gml:segments></gml:Curve></gml:exterior><gml:interior><gml:LineString><gml:posList>-2 -2 -2 2 2 2 2 -2 -2 -2</gml:posList></gml:LineString></gml:interior></gml:Polygon>' expected_geom2 = ogr.CreateGeometryFromGML(expected_gml2) - if ogrtest.check_feature_geometry(geom2, expected_geom2) != 0: - print(gml2) - return 'fail' - - return 'success' + assert ogrtest.check_feature_geometry(geom2, expected_geom2) == 0, gml2 ############################################################################### # Test OGRMultiSurface -def gml_OGRMultiSurface(): +def test_gml_OGRMultiSurface(): # MultiSurface of CurvePolygon gml = """<gml:MultiSurface> @@ -2259,10 +1932,8 @@ def gml_OGRMultiSurface(): </gml:MultiSurface>""" geom = ogr.CreateGeometryFromGML(gml) - if geom.ExportToWkt() != 'MULTISURFACE (CURVEPOLYGON (CIRCULARSTRING (0 0,1 1,1 -1,0.292893218813453 -0.707106781186548,0 0)))': - gdaltest.post_reason('<gml:MultiSurface> not correctly parsed') - print(geom.ExportToWkt()) - return 'fail' + assert geom.ExportToWkt() == 'MULTISURFACE (CURVEPOLYGON (CIRCULARSTRING (0 0,1 1,1 -1,0.292893218813453 -0.707106781186548,0 0)))', \ + '<gml:MultiSurface> not correctly parsed' # MultiSurface of Polygon and CurvePolygon gml = """<gml:MultiSurface> @@ -2283,10 +1954,8 @@ def gml_OGRMultiSurface(): </gml:MultiSurface>""" geom = ogr.CreateGeometryFromGML(gml) - if geom.ExportToWkt() != 'MULTISURFACE (((0 0,0 1,1 1,0 0)),CURVEPOLYGON (CIRCULARSTRING (0 0,1 1,1 -1,0.292893218813453 -0.707106781186548,0 0)))': - gdaltest.post_reason('<gml:MultiSurface> not correctly parsed') - print(geom.ExportToWkt()) - return 'fail' + assert geom.ExportToWkt() == 'MULTISURFACE (((0 0,0 1,1 1,0 0)),CURVEPOLYGON (CIRCULARSTRING (0 0,1 1,1 -1,0.292893218813453 -0.707106781186548,0 0)))', \ + '<gml:MultiSurface> not correctly parsed' # MultiSurface of CurvePolygon and Polygon gml = """<gml:MultiSurface> @@ -2307,41 +1976,29 @@ def gml_OGRMultiSurface(): </gml:MultiSurface>""" geom = ogr.CreateGeometryFromGML(gml) - if geom.ExportToWkt() != 'MULTISURFACE (CURVEPOLYGON (CIRCULARSTRING (0 0,1 1,1 -1,0.292893218813453 -0.707106781186548,0 0)),((0 0,0 1,1 1,0 0)))': - gdaltest.post_reason('<gml:MultiSurface> not correctly parsed') - print(geom.ExportToWkt()) - return 'fail' + assert geom.ExportToWkt() == 'MULTISURFACE (CURVEPOLYGON (CIRCULARSTRING (0 0,1 1,1 -1,0.292893218813453 -0.707106781186548,0 0)),((0 0,0 1,1 1,0 0)))', \ + '<gml:MultiSurface> not correctly parsed' geom = ogr.CreateGeometryFromWkt('MULTISURFACE (CURVEPOLYGON((0 0,0 1,1 1,1 0,0 0)))') gml2 = geom.ExportToGML(['FORMAT=GML3']) expected_gml2 = '<gml:MultiSurface><gml:surfaceMember><gml:Polygon><gml:exterior><gml:LinearRing><gml:posList>0 0 0 1 1 1 1 0 0 0</gml:posList></gml:LinearRing></gml:exterior></gml:Polygon></gml:surfaceMember></gml:MultiSurface>' - if gml2 != expected_gml2: - gdaltest.post_reason('fail') - print(gml2) - return 'fail' - - return 'success' + assert gml2 == expected_gml2 ############################################################################### # Test OGRMultiCurve -def gml_OGRMultiCurve(): +def test_gml_OGRMultiCurve(): # MultiCurve of Arc gml = """<gml:MultiCurve><gml:curveMember><gml:Curve><gml:segments><gml:ArcString><gml:posList>0 0 1 1 1 -1</gml:posList></gml:ArcString></gml:segments></gml:Curve></gml:curveMember></gml:MultiCurve>""" geom = ogr.CreateGeometryFromGML(gml) - if geom.ExportToWkt() != 'MULTICURVE (CIRCULARSTRING (0 0,1 1,1 -1))': - gdaltest.post_reason('<gml:MultiCurve> not correctly parsed') - print(geom.ExportToWkt()) - return 'fail' + assert geom.ExportToWkt() == 'MULTICURVE (CIRCULARSTRING (0 0,1 1,1 -1))', \ + '<gml:MultiCurve> not correctly parsed' gml2 = geom.ExportToGML(['FORMAT=GML3']) - if gml2 != gml: - gdaltest.post_reason('fail') - print(gml2) - return 'fail' + assert gml2 == gml # MultiCurve of LineString and Arc gml = """<gml:MultiCurve> @@ -2356,10 +2013,8 @@ def gml_OGRMultiCurve(): </gml:MultiCurve>""" geom = ogr.CreateGeometryFromGML(gml) - if geom.ExportToWkt() != 'MULTICURVE ((0 0,1 1,1 -1),CIRCULARSTRING (0 0,1 1,1 -1))': - gdaltest.post_reason('<gml:MultiCurve> not correctly parsed') - print(geom.ExportToWkt()) - return 'fail' + assert geom.ExportToWkt() == 'MULTICURVE ((0 0,1 1,1 -1),CIRCULARSTRING (0 0,1 1,1 -1))', \ + '<gml:MultiCurve> not correctly parsed' # MultiCurve of Arc and LineString gml = """<gml:MultiCurve> @@ -2374,10 +2029,8 @@ def gml_OGRMultiCurve(): </gml:MultiCurve>""" geom = ogr.CreateGeometryFromGML(gml) - if geom.ExportToWkt() != 'MULTICURVE (CIRCULARSTRING (0 0,1 1,1 -1),(0 0,1 1,1 -1))': - gdaltest.post_reason('<gml:MultiCurve> not correctly parsed') - print(geom.ExportToWkt()) - return 'fail' + assert geom.ExportToWkt() == 'MULTICURVE (CIRCULARSTRING (0 0,1 1,1 -1),(0 0,1 1,1 -1))', \ + '<gml:MultiCurve> not correctly parsed' # MultiCurve of CompositeCurve gml = """<gml:MultiCurve> @@ -2396,41 +2049,29 @@ def gml_OGRMultiCurve(): </gml:MultiCurve>""" geom = ogr.CreateGeometryFromGML(gml) - if geom.ExportToWkt() != 'MULTICURVE (COMPOUNDCURVE (CIRCULARSTRING (0 0,1 1,1 -1),(1 -1,1 1,1 -1)))': - gdaltest.post_reason('<gml:MultiCurve> not correctly parsed') - print(geom.ExportToWkt()) - return 'fail' - - return 'success' + assert geom.ExportToWkt() == 'MULTICURVE (COMPOUNDCURVE (CIRCULARSTRING (0 0,1 1,1 -1),(1 -1,1 1,1 -1)))', \ + '<gml:MultiCurve> not correctly parsed' ############################################################################### # Test write support for GML namespace declaration -def gml_write_gml_ns(): +def test_gml_write_gml_ns(): geom = ogr.CreateGeometryFromWkt('POINT(500000 4500000)') gml = geom.ExportToGML(options=['NAMESPACE_DECL=YES']) expected_gml = '<gml:Point xmlns:gml="http://www.opengis.net/gml"><gml:coordinates>500000,4500000</gml:coordinates></gml:Point>' - if gml != expected_gml: - gdaltest.post_reason('got %s, instead of %s' % (gml, expected_gml)) - return 'fail' + assert gml == expected_gml, ('got %s, instead of %s' % (gml, expected_gml)) geom = ogr.CreateGeometryFromWkt('POINT(500000 4500000)') gml = geom.ExportToGML(options=['FORMAT=GML3', 'NAMESPACE_DECL=YES']) expected_gml = '<gml:Point xmlns:gml="http://www.opengis.net/gml"><gml:pos>500000 4500000</gml:pos></gml:Point>' - if gml != expected_gml: - gdaltest.post_reason('got %s, instead of %s' % (gml, expected_gml)) - return 'fail' + assert gml == expected_gml, ('got %s, instead of %s' % (gml, expected_gml)) geom = ogr.CreateGeometryFromWkt('POINT(500000 4500000)') gml = geom.ExportToGML(options=['FORMAT=GML32', 'GMLID=foo', 'NAMESPACE_DECL=YES']) expected_gml = '<gml:Point xmlns:gml="http://www.opengis.net/gml/3.2" gml:id="foo"><gml:pos>500000 4500000</gml:pos></gml:Point>' - if gml != expected_gml: - gdaltest.post_reason('got %s, instead of %s' % (gml, expected_gml)) - return 'fail' - - return 'success' + assert gml == expected_gml, ('got %s, instead of %s' % (gml, expected_gml)) ############################################################################### # When imported build a list of units based on the files available. @@ -2439,79 +2080,5 @@ def gml_write_gml_ns(): # sys.stdin.readline() -gdaltest_list = [] - -files = os.listdir('data/wkb_wkt') -for filename in files: - if filename[-4:] == '.wkt': - ut = gml_geom_unit(filename[:-4]) - gdaltest_list.append((ut.gml_geom, ut.unit)) - -gdaltest_list.append(gml_space_test) -gdaltest_list.append(gml_pos_point) -gdaltest_list.append(gml_pos_polygon) -gdaltest_list.append(gml_posList_line) -gdaltest_list.append(gml_posList_line3d) -gdaltest_list.append(gml_posList_line3d_2) -gdaltest_list.append(gml_polygon) -gdaltest_list.append(gml_out_point_srs) -gdaltest_list.append(gml_out_point3d_srs) -gdaltest_list.append(gml_out_linestring_srs) -gdaltest_list.append(gml_out_polygon_srs) -gdaltest_list.append(gml_out_multipoint_srs) -gdaltest_list.append(gml_out_multilinestring_srs) -gdaltest_list.append(gml_out_multipolygon_srs) -gdaltest_list.append(gml_out_geometrycollection_srs) -gdaltest_list.append(gml_Box) -gdaltest_list.append(gml_Envelope) -gdaltest_list.append(gml_Curve) -gdaltest_list.append(gml_Curve_with_pointProperty) -gdaltest_list.append(gml_MultiCurve) -gdaltest_list.append(gml_MultiSurface) -gdaltest_list.append(gml_MultiSurface_surfaceMembers) -gdaltest_list.append(gml_MultiCurve_curveMembers) -gdaltest_list.append(gml_MultiGeometry_geometryMembers) -gdaltest_list.append(gml_CompositeCurve_curveMembers) -gdaltest_list.append(gml_MultiCurve_pointMembers) -gdaltest_list.append(gml_Solid) -gdaltest_list.append(gml_OrientableSurface) -gdaltest_list.append(gml_Triangle) -gdaltest_list.append(gml_Rectangle) -gdaltest_list.append(gml_Tin) -gdaltest_list.append(gml_PolyhedralSurface) -gdaltest_list.append(gml_ConcatenatedDeduplication) -# gdaltest_list.append( gml_out_precision ) -gdaltest_list.append(gml_invalid_geoms) -gdaltest_list.append(gml_write_gml3_geometries) -gdaltest_list.append(gml_write_gml3_srs) -gdaltest_list.append(gml_nested) -gdaltest_list.append(gml_SimplePolygon) -gdaltest_list.append(gml_SimpleRectangle) -gdaltest_list.append(gml_SimpleTriangle) -gdaltest_list.append(gml_SimpleMultiPoint) -gdaltest_list.append(gml_CompositeCurveInRing) -gdaltest_list.append(gml_CompositeSurface_in_surfaceMembers) -gdaltest_list.append(gml_MultiSurfaceOfSurfaceOfPolygonPatchWithInteriorRing) -gdaltest_list.append(gml_Coordinates_ts_cs_decimal) -gdaltest_list.append(gml_with_xml_header_and_comments) -gdaltest_list.append(gml_srsDimension_topgeometry) -gdaltest_list.append(gml_Arc) -gdaltest_list.append(gml_ArcByBulge) -gdaltest_list.append(gml_ArcByCenterPoint) -gdaltest_list.append(gml_CompoundCurve_of_ArcByCenterPoint) -gdaltest_list.append(gml_CircleByCenterPoint) -gdaltest_list.append(gml_Circle) -gdaltest_list.append(gml_ArcString) -gdaltest_list.append(gml_OGRCompoundCurve) -gdaltest_list.append(gml_OGRCurvePolygon) -gdaltest_list.append(gml_OGRMultiSurface) -gdaltest_list.append(gml_OGRMultiCurve) -gdaltest_list.append(gml_write_gml_ns) - -if __name__ == '__main__': - - gdaltest.setup_run('ogr_gml_geom') - - gdaltest.run_tests(gdaltest_list) - - sys.exit(gdaltest.summarize()) + + diff --git a/autotest/ogr/ogr_gml_read.py b/autotest/ogr/ogr_gml_read.py index 97ae391b1fd0..272b4f6eab69 100755 --- a/autotest/ogr/ogr_gml_read.py +++ b/autotest/ogr/ogr_gml_read.py @@ -33,7 +33,6 @@ import os import sys -sys.path.append('../pymod') import shutil import gdaltest @@ -41,180 +40,137 @@ from osgeo import gdal from osgeo import ogr from osgeo import osr +import pytest ############################################################################### # Test reading geometry and attribute from ionic wfs gml file. # -def ogr_gml_1(): +def test_ogr_gml_1(): gdaltest.have_gml_reader = 0 gml_ds = ogr.Open('data/ionic_wfs.gml') if gml_ds is None: if gdal.GetLastErrorMsg().find('Xerces') != -1: - return 'skip' - gdaltest.post_reason('failed to open test file.') - return 'fail' + pytest.skip() + pytest.fail('failed to open test file.') gdaltest.have_gml_reader = 1 - if gml_ds.GetLayerCount() != 1: - gdaltest.post_reason('wrong number of layers') - return 'fail' + assert gml_ds.GetLayerCount() == 1, 'wrong number of layers' lyr = gml_ds.GetLayerByName('GEM') feat = lyr.GetNextFeature() - if feat.GetField('Name') != 'Aartselaar': - gdaltest.post_reason('Wrong name field value') - return 'fail' + assert feat.GetField('Name') == 'Aartselaar', 'Wrong name field value' wkt = 'POLYGON ((44038 511549,44015 511548,43994 511522,43941 511539,43844 511514,43754 511479,43685 511521,43594 511505,43619 511452,43645 511417,4363 511387,437 511346,43749 511298,43808 511229,43819 511205,4379 511185,43728 511167,43617 511175,43604 511151,43655 511125,43746 511143,43886 511154,43885 511178,43928 511186,43977 511217,4404 511223,44008 511229,44099 51131,44095 511335,44106 51135,44127 511379,44124 511435,44137 511455,44105 511467,44098 511484,44086 511499,4407 511506,44067 511535,44038 511549))' - if ogrtest.check_feature_geometry(feat, wkt): - return 'fail' + assert not ogrtest.check_feature_geometry(feat, wkt) feat = lyr.GetNextFeature() - if feat is not None: - gdaltest.post_reason('got unexpected feature.') - return 'fail' - - return 'success' + assert feat is None, 'got unexpected feature.' ############################################################################### # Do the same test somewhere without a .gfs file. -def ogr_gml_2(): +def test_ogr_gml_2(): if not gdaltest.have_gml_reader: - return 'skip' + pytest.skip() # copy gml file (but not .gfs file) open('tmp/ionic_wfs.gml', 'w').write(open('data/ionic_wfs.gml').read()) gml_ds = ogr.Open('tmp/ionic_wfs.gml') - if gml_ds.GetLayerCount() != 1: - gdaltest.post_reason('wrong number of layers') - return 'fail' + assert gml_ds.GetLayerCount() == 1, 'wrong number of layers' lyr = gml_ds.GetLayerByName('GEM') feat = lyr.GetNextFeature() - if feat.GetField('Name') != 'Aartselaar': - gdaltest.post_reason('Wrong name field value') - return 'fail' + assert feat.GetField('Name') == 'Aartselaar', 'Wrong name field value' wkt = 'POLYGON ((44038 511549,44015 511548,43994 511522,43941 511539,43844 511514,43754 511479,43685 511521,43594 511505,43619 511452,43645 511417,4363 511387,437 511346,43749 511298,43808 511229,43819 511205,4379 511185,43728 511167,43617 511175,43604 511151,43655 511125,43746 511143,43886 511154,43885 511178,43928 511186,43977 511217,4404 511223,44008 511229,44099 51131,44095 511335,44106 51135,44127 511379,44124 511435,44137 511455,44105 511467,44098 511484,44086 511499,4407 511506,44067 511535,44038 511549))' - if ogrtest.check_feature_geometry(feat, wkt): - return 'fail' + assert not ogrtest.check_feature_geometry(feat, wkt) feat = lyr.GetNextFeature() - if feat is not None: - gdaltest.post_reason('got unexpected feature.') - return 'fail' - - return 'success' + assert feat is None, 'got unexpected feature.' ############################################################################### # Similar test for RNF style line data. -def ogr_gml_3(): +def test_ogr_gml_3(): if not gdaltest.have_gml_reader: - return 'skip' + pytest.skip() gml_ds = ogr.Open('data/rnf_eg.gml') - if gml_ds.GetLayerCount() != 1: - gdaltest.post_reason('wrong number of layers') - return 'fail' + assert gml_ds.GetLayerCount() == 1, 'wrong number of layers' lyr = gml_ds.GetLayerByName('RoadSegment') feat = lyr.GetNextFeature() - if feat.GetField('ngd_id') != 817792: - gdaltest.post_reason('Wrong ngd_id field value') - return 'fail' + assert feat.GetField('ngd_id') == 817792, 'Wrong ngd_id field value' - if feat.GetField('type') != 'HWY': - gdaltest.post_reason('Wrong type field value') - return 'fail' + assert feat.GetField('type') == 'HWY', 'Wrong type field value' wkt = 'LINESTRING (-63.500411040289066 46.240122507771368,-63.501009714909742 46.240344881690326,-63.502170462373471 46.241041855639622,-63.505862621395394 46.24195250605576,-63.506719184531178 46.242002742901576,-63.507197272602212 46.241931577811606,-63.508403092799554 46.241752283460158,-63.509946573455622 46.241745397977233)' - if ogrtest.check_feature_geometry(feat, wkt): - return 'fail' + assert not ogrtest.check_feature_geometry(feat, wkt) feat = lyr.GetNextFeature() - if feat is not None: - gdaltest.post_reason('got unexpected feature.') - return 'fail' - - return 'success' + assert feat is None, 'got unexpected feature.' ############################################################################### # Test of read GML file with UTF-8 BOM indicator. # Test also support for nested GML elements (#3680) -def ogr_gml_4(): +def test_ogr_gml_4(): if not gdaltest.have_gml_reader: - return 'skip' + pytest.skip() gml_ds = ogr.Open('data/bom.gml') - if gml_ds.GetLayerCount() != 1: - gdaltest.post_reason('wrong number of layers') - return 'fail' + assert gml_ds.GetLayerCount() == 1, 'wrong number of layers' lyr = gml_ds.GetLayerByName('CartographicText') - if lyr.GetFeatureCount() != 3: - gdaltest.post_reason('wrong number of features') - return 'fail' + assert lyr.GetFeatureCount() == 3, 'wrong number of features' # Test 1st feature feat = lyr.GetNextFeature() - if feat.GetField('featureCode') != 10198: - gdaltest.post_reason('Wrong featureCode field value') - return 'fail' + assert feat.GetField('featureCode') == 10198, 'Wrong featureCode field value' - if feat.GetField('anchorPosition') != 8: - gdaltest.post_reason('Wrong anchorPosition field value') - return 'fail' + assert feat.GetField('anchorPosition') == 8, 'Wrong anchorPosition field value' wkt = 'POINT (347243.85 461299.5)' - if ogrtest.check_feature_geometry(feat, wkt): - return 'fail' + assert not ogrtest.check_feature_geometry(feat, wkt) # Test 2nd feature feat = lyr.GetNextFeature() - if feat.GetField('featureCode') != 10069: - gdaltest.post_reason('Wrong featureCode field value') - return 'fail' + assert feat.GetField('featureCode') == 10069, 'Wrong featureCode field value' wkt = 'POINT (347251.45 461250.85)' - if ogrtest.check_feature_geometry(feat, wkt): - return 'fail' - - return 'success' + assert not ogrtest.check_feature_geometry(feat, wkt) ############################################################################### # Test of read GML file that triggeered bug #2349 -def ogr_gml_5(): +def test_ogr_gml_5(): if not gdaltest.have_gml_reader: - return 'skip' + pytest.skip() gml_ds = ogr.Open('data/ticket_2349_test_1.gml') @@ -224,16 +180,14 @@ def ogr_gml_5(): lyr.GetNextFeature() - return 'success' - ############################################################################### # Test of various FIDs (various prefixes and lengths) (Ticket#1017) -def ogr_gml_6(): +def test_ogr_gml_6(): if not gdaltest.have_gml_reader: - return 'skip' + pytest.skip() files = ['test_point1', 'test_point2', 'test_point3', 'test_point4'] fids = [] @@ -247,23 +201,21 @@ def ogr_gml_6(): if (feat.GetFID() < 0) or (feat.GetFID() in fids): gml_ds = None os.remove('data' + os.sep + filename + '.gfs') - gdaltest.post_reason('Wrong FID value') - return 'fail' + pytest.fail('Wrong FID value') fids.append(feat.GetFID()) feat = lyr.GetNextFeature() gml_ds = None os.remove('data' + os.sep + filename + '.gfs') - return 'success' - + ############################################################################### # Test of colon terminated prefixes for attribute values (Ticket#2493) -def ogr_gml_7(): +def test_ogr_gml_7(): if not gdaltest.have_gml_reader: - return 'skip' + pytest.skip() gdal.SetConfigOption('GML_EXPOSE_FID', 'FALSE') gml_ds = ogr.Open('data/test_point.gml') @@ -272,58 +224,43 @@ def ogr_gml_7(): ldefn = lyr.GetLayerDefn() # Test fix for #2969 - if lyr.GetFeatureCount() != 5: - gdaltest.post_reason('Bad feature count') - return 'fail' + assert lyr.GetFeatureCount() == 5, 'Bad feature count' try: ldefn.GetFieldDefn(0).GetFieldTypeName except: - return 'skip' - - if ldefn.GetFieldDefn(0).GetFieldTypeName(ldefn.GetFieldDefn(0).GetType())\ - != 'Real': - return 'fail' - if ldefn.GetFieldDefn(1).GetFieldTypeName(ldefn.GetFieldDefn(1).GetType())\ - != 'Integer': - return 'fail' - if ldefn.GetFieldDefn(2).GetFieldTypeName(ldefn.GetFieldDefn(2).GetType())\ - != 'String': - return 'fail' + pytest.skip() - return 'success' + assert ldefn.GetFieldDefn(0).GetFieldTypeName(ldefn.GetFieldDefn(0).GetType()) == 'Real' + assert ldefn.GetFieldDefn(1).GetFieldTypeName(ldefn.GetFieldDefn(1).GetType()) == 'Integer' + assert ldefn.GetFieldDefn(2).GetFieldTypeName(ldefn.GetFieldDefn(2).GetType()) == 'String' ############################################################################### # Test a GML file with some non-ASCII UTF-8 content that triggered a bug (Ticket#2948) -def ogr_gml_8(): +def test_ogr_gml_8(): if not gdaltest.have_gml_reader: - return 'skip' + pytest.skip() gml_ds = ogr.Open('data/utf8.gml') lyr = gml_ds.GetLayer() feat = lyr.GetNextFeature() if sys.version_info >= (3, 0, 0): - if feat.GetFieldAsString('name') != '\xc4\x80liamanu'.encode('latin1').decode('utf-8'): - print(feat.GetFieldAsString('name')) - return 'fail' + assert feat.GetFieldAsString('name') == '\xc4\x80liamanu'.encode('latin1').decode('utf-8') else: - if feat.GetFieldAsString('name') != '\xc4\x80liamanu': - print(feat.GetFieldAsString('name')) - return 'fail' - - return 'success' + assert feat.GetFieldAsString('name') == '\xc4\x80liamanu' + ############################################################################### # Test writing invalid UTF-8 content in a GML file (ticket #2971) -def ogr_gml_9(): +def test_ogr_gml_9(): if not gdaltest.have_gml_reader: - return 'skip' + pytest.skip() drv = ogr.GetDriverByName('GML') ds = drv.CreateDataSource('tmp/broken_utf8.gml') @@ -338,35 +275,28 @@ def ogr_gml_9(): ret = lyr.CreateFeature(dst_feat) gdal.PopErrorHandler() - if ret != 0: - gdaltest.post_reason('CreateFeature failed.') - return 'fail' + assert ret == 0, 'CreateFeature failed.' ds = None ds = ogr.Open('tmp/broken_utf8.gml') lyr = ds.GetLayerByName('test') feat = lyr.GetNextFeature() - if feat.GetField('test') != '?bad': - gdaltest.post_reason('Unexpected content.') - print(feat.GetField('test')) - return 'fail' + assert feat.GetField('test') == '?bad', 'Unexpected content.' ds = None os.remove('tmp/broken_utf8.gml') os.remove('tmp/broken_utf8.xsd') - return 'success' - ############################################################################### # Test writing different data types in a GML file (ticket #2857) # TODO: Add test for other data types as they are added to the driver. -def ogr_gml_10(): +def test_ogr_gml_10(): if not gdaltest.have_gml_reader: - return 'skip' + pytest.skip() drv = ogr.GetDriverByName('GML') ds = drv.CreateDataSource('tmp/fields.gml') @@ -393,9 +323,7 @@ def ogr_gml_10(): ret = lyr.CreateFeature(dst_feat) - if ret != 0: - gdaltest.post_reason('CreateFeature failed.') - return 'fail' + assert ret == 0, 'CreateFeature failed.' ds = None @@ -403,65 +331,46 @@ def ogr_gml_10(): lyr = ds.GetLayerByName('test') feat = lyr.GetNextFeature() - if feat.GetFieldDefnRef(feat.GetFieldIndex('string')).GetType() != ogr.OFTString: - gdaltest.post_reason('String type is reported wrong. Got ' + str(feat.GetFieldDefnRef(feat.GetFieldIndex('string')).GetType())) - return 'fail' - if feat.GetFieldDefnRef(feat.GetFieldIndex('date')).GetType() != ogr.OFTString: - gdaltest.post_reason('Date type is not reported as OFTString. Got ' + str(feat.GetFieldDefnRef(feat.GetFieldIndex('date')).GetType())) - return 'fail' - if feat.GetFieldDefnRef(feat.GetFieldIndex('real')).GetType() != ogr.OFTReal: - gdaltest.post_reason('Real type is reported wrong. Got ' + str(feat.GetFieldDefnRef(feat.GetFieldIndex('real')).GetType())) - return 'fail' - if feat.GetFieldDefnRef(feat.GetFieldIndex('float')).GetType() != ogr.OFTReal: - gdaltest.post_reason('Float type is not reported as OFTReal. Got ' + str(feat.GetFieldDefnRef(feat.GetFieldIndex('float')).GetType())) - return 'fail' - if feat.GetFieldDefnRef(feat.GetFieldIndex('integer')).GetType() != ogr.OFTInteger: - gdaltest.post_reason('Integer type is reported wrong. Got ' + str(feat.GetFieldDefnRef(feat.GetFieldIndex('integer')).GetType())) - return 'fail' - - if feat.GetField('string') != 'test string of length 24': - gdaltest.post_reason('Unexpected string content.' + feat.GetField('string')) - return 'fail' - if feat.GetField('date') != '2003/04/22': - gdaltest.post_reason('Unexpected string content.' + feat.GetField('date')) - return 'fail' - if feat.GetFieldAsDouble('real') != 12.34: - gdaltest.post_reason('Unexpected real content.') - return 'fail' - if feat.GetField('float') != 1234.5678: - gdaltest.post_reason('Unexpected float content.') - return 'fail' - if feat.GetField('integer') != 1234: - gdaltest.post_reason('Unexpected integer content.') - return 'fail' - - if lyr.GetLayerDefn().GetFieldDefn(lyr.GetLayerDefn().GetFieldIndex('string')).GetWidth() != 100: - gdaltest.post_reason('Unexpected width of string field.') - return 'fail' - if lyr.GetLayerDefn().GetFieldDefn(lyr.GetLayerDefn().GetFieldIndex('real')).GetWidth() != 4: - gdaltest.post_reason('Unexpected width of real field.') - return 'fail' - if lyr.GetLayerDefn().GetFieldDefn(lyr.GetLayerDefn().GetFieldIndex('real')).GetPrecision() != 2: - gdaltest.post_reason('Unexpected precision of real field.') - return 'fail' - if lyr.GetLayerDefn().GetFieldDefn(lyr.GetLayerDefn().GetFieldIndex('integer')).GetWidth() != 5: - gdaltest.post_reason('Unexpected width of integer field.') - return 'fail' + assert feat.GetFieldDefnRef(feat.GetFieldIndex('string')).GetType() == ogr.OFTString, \ + ('String type is reported wrong. Got ' + str(feat.GetFieldDefnRef(feat.GetFieldIndex('string')).GetType())) + assert feat.GetFieldDefnRef(feat.GetFieldIndex('date')).GetType() == ogr.OFTString, \ + ('Date type is not reported as OFTString. Got ' + str(feat.GetFieldDefnRef(feat.GetFieldIndex('date')).GetType())) + assert feat.GetFieldDefnRef(feat.GetFieldIndex('real')).GetType() == ogr.OFTReal, \ + ('Real type is reported wrong. Got ' + str(feat.GetFieldDefnRef(feat.GetFieldIndex('real')).GetType())) + assert feat.GetFieldDefnRef(feat.GetFieldIndex('float')).GetType() == ogr.OFTReal, \ + ('Float type is not reported as OFTReal. Got ' + str(feat.GetFieldDefnRef(feat.GetFieldIndex('float')).GetType())) + assert feat.GetFieldDefnRef(feat.GetFieldIndex('integer')).GetType() == ogr.OFTInteger, \ + ('Integer type is reported wrong. Got ' + str(feat.GetFieldDefnRef(feat.GetFieldIndex('integer')).GetType())) + + assert feat.GetField('string') == 'test string of length 24', \ + ('Unexpected string content.' + feat.GetField('string')) + assert feat.GetField('date') == '2003/04/22', \ + ('Unexpected string content.' + feat.GetField('date')) + assert feat.GetFieldAsDouble('real') == 12.34, 'Unexpected real content.' + assert feat.GetField('float') == 1234.5678, 'Unexpected float content.' + assert feat.GetField('integer') == 1234, 'Unexpected integer content.' + + assert lyr.GetLayerDefn().GetFieldDefn(lyr.GetLayerDefn().GetFieldIndex('string')).GetWidth() == 100, \ + 'Unexpected width of string field.' + assert lyr.GetLayerDefn().GetFieldDefn(lyr.GetLayerDefn().GetFieldIndex('real')).GetWidth() == 4, \ + 'Unexpected width of real field.' + assert lyr.GetLayerDefn().GetFieldDefn(lyr.GetLayerDefn().GetFieldIndex('real')).GetPrecision() == 2, \ + 'Unexpected precision of real field.' + assert lyr.GetLayerDefn().GetFieldDefn(lyr.GetLayerDefn().GetFieldIndex('integer')).GetWidth() == 5, \ + 'Unexpected width of integer field.' ds = None os.remove('tmp/fields.gml') os.remove('tmp/fields.xsd') - return 'success' - ############################################################################### # Test reading a geometry element specified with <GeometryElementPath> -def ogr_gml_11(): +def test_ogr_gml_11(): if not gdaltest.have_gml_reader: - return 'skip' + pytest.skip() # Make sure the .gfs file is more recent that the .gml one try: @@ -480,106 +389,87 @@ def ogr_gml_11(): ds = ogr.Open('data/testgeometryelementpath.gml') lyr = ds.GetLayer(0) - if lyr.GetGeometryColumn() != 'location1container|location1': - gdaltest.post_reason('did not get expected geometry column name') - return 'fail' + assert lyr.GetGeometryColumn() == 'location1container|location1', \ + 'did not get expected geometry column name' feat = lyr.GetNextFeature() - if feat.GetField('attrib1') != 'attrib1_value': - gdaltest.post_reason('did not get expected value for attrib1') - return 'fail' - if feat.GetField('attrib2') != 'attrib2_value': - gdaltest.post_reason('did not get expected value for attrib2') - return 'fail' + assert feat.GetField('attrib1') == 'attrib1_value', \ + 'did not get expected value for attrib1' + assert feat.GetField('attrib2') == 'attrib2_value', \ + 'did not get expected value for attrib2' geom = feat.GetGeometryRef() - if geom.ExportToWkt() != 'POINT (3 50)': - gdaltest.post_reason('did not get expected geometry') - return 'fail' + assert geom.ExportToWkt() == 'POINT (3 50)', 'did not get expected geometry' ds = None - return 'success' ############################################################################### # Test reading a virtual GML file -def ogr_gml_12(): +def test_ogr_gml_12(): if not gdaltest.have_gml_reader: - return 'skip' + pytest.skip() ds = ogr.Open('/vsizip/data/testgeometryelementpath.zip/testgeometryelementpath.gml') lyr = ds.GetLayer(0) - if lyr.GetGeometryColumn() != 'location1container|location1': - gdaltest.post_reason('did not get expected geometry column name') - return 'fail' + assert lyr.GetGeometryColumn() == 'location1container|location1', \ + 'did not get expected geometry column name' feat = lyr.GetNextFeature() - if feat.GetField('attrib1') != 'attrib1_value': - gdaltest.post_reason('did not get expected value for attrib1') - return 'fail' - if feat.GetField('attrib2') != 'attrib2_value': - gdaltest.post_reason('did not get expected value for attrib2') - return 'fail' + assert feat.GetField('attrib1') == 'attrib1_value', \ + 'did not get expected value for attrib1' + assert feat.GetField('attrib2') == 'attrib2_value', \ + 'did not get expected value for attrib2' geom = feat.GetGeometryRef() - if geom.ExportToWkt() != 'POINT (3 50)': - gdaltest.post_reason('did not get expected geometry') - return 'fail' + assert geom.ExportToWkt() == 'POINT (3 50)', 'did not get expected geometry' ds = None - return 'success' ############################################################################### # Test reading GML with StringList, IntegerList and RealList fields -def ogr_gml_13(): +def test_ogr_gml_13(): if not gdaltest.have_gml_reader: - return 'skip' + pytest.skip() for _ in range(2): ds = ogr.Open('data/testlistfields.gml') lyr = ds.GetLayer(0) feat = lyr.GetNextFeature() - if feat.GetFieldAsStringList(feat.GetFieldIndex('attrib1')) != ['value1', 'value2']: - gdaltest.post_reason('did not get expected value for attrib1') - return 'fail' - if feat.GetField(feat.GetFieldIndex('attrib2')) != 'value3': - gdaltest.post_reason('did not get expected value for attrib2') - return 'fail' - if feat.GetFieldAsIntegerList(feat.GetFieldIndex('attrib3')) != [4, 5]: - gdaltest.post_reason('did not get expected value for attrib3') - return 'fail' - if feat.GetFieldAsDoubleList(feat.GetFieldIndex('attrib4')) != [6.1, 7.1]: - gdaltest.post_reason('did not get expected value for attrib4') - return 'fail' + assert feat.GetFieldAsStringList(feat.GetFieldIndex('attrib1')) == ['value1', 'value2'], \ + 'did not get expected value for attrib1' + assert feat.GetField(feat.GetFieldIndex('attrib2')) == 'value3', \ + 'did not get expected value for attrib2' + assert feat.GetFieldAsIntegerList(feat.GetFieldIndex('attrib3')) == [4, 5], \ + 'did not get expected value for attrib3' + assert feat.GetFieldAsDoubleList(feat.GetFieldIndex('attrib4')) == [6.1, 7.1], \ + 'did not get expected value for attrib4' ds = None gdal.Unlink('data/testlistfields.gfs') - return 'success' - ############################################################################### # Test xlink resolution -def ogr_gml_14(): +def test_ogr_gml_14(): if not gdaltest.have_gml_reader: - return 'skip' + pytest.skip() # We need CURL for xlink resolution, and a sign that Curl is available # is the availability of the WMS driver gdaltest.wms_drv = gdal.GetDriverByName('WMS') if gdaltest.wms_drv is None: - return 'skip' + pytest.skip() if gdaltest.gdalurlopen('http://download.osgeo.org/gdal/data/gml/xlink3.gml') is None: - print('cannot open URL') - return 'skip' + pytest.skip('cannot open URL') files = ['xlink1.gml', 'xlink2.gml', 'expected1.gml', 'expected2.gml'] for f in files: if not gdaltest.download_file('http://download.osgeo.org/gdal/data/gml/' + f, f): - return 'skip' + pytest.skip() gdal.SetConfigOption('GML_SKIP_RESOLVE_ELEMS', 'NONE') gdal.SetConfigOption('GML_SAVE_RESOLVED_TO', 'tmp/cache/xlink1resolved.gml') @@ -602,11 +492,9 @@ def ogr_gml_14(): expectedtext = fp.read() fp.close() except (IOError, OSError): - return 'fail' + pytest.fail() - if text != expectedtext: - print('Problem with file 1') - return 'fail' + assert text == expectedtext, 'Problem with file 1' try: fp = open('tmp/cache/xlink2resolved.gml', 'r') @@ -617,43 +505,35 @@ def ogr_gml_14(): expectedtext = fp.read() fp.close() except (IOError, OSError): - return 'fail' - - if text != expectedtext: - print('Problem with file 2') - return 'fail' + pytest.fail() - return 'success' + assert text == expectedtext, 'Problem with file 2' ############################################################################### # Run test_ogrsf -def ogr_gml_15(): +def test_ogr_gml_15(): if not gdaltest.have_gml_reader: - return 'skip' + pytest.skip() import test_cli_utilities if test_cli_utilities.get_test_ogrsf_path() is None: - return 'skip' + pytest.skip() ret = gdaltest.runexternal(test_cli_utilities.get_test_ogrsf_path() + ' -ro data/test_point.gml') - if ret.find('INFO') == -1 or ret.find('ERROR') != -1: - print(ret) - return 'fail' - - return 'success' + assert ret.find('INFO') != -1 and ret.find('ERROR') == -1 ############################################################################### # Read CityGML generic attributes -def ogr_gml_16(): +def test_ogr_gml_16(): if not gdaltest.have_gml_reader: - return 'skip' + pytest.skip() ds = ogr.Open('data/citygml.gml') lyr = ds.GetLayer(0) @@ -663,76 +543,58 @@ def ogr_gml_16(): feat.GetField('a_int_attr') != 2 or \ feat.GetField('a_double_attr') != 3.45: feat.DumpReadable() - gdaltest.post_reason('did not get expected values') - return 'fail' - - return 'success' + pytest.fail('did not get expected values') + ############################################################################### # Read layer SRS for WFS 1.0.0 return -def ogr_gml_17(): +def test_ogr_gml_17(): if not gdaltest.have_gml_reader: - return 'skip' + pytest.skip() ds = ogr.Open('data/gnis_pop_100.gml') lyr = ds.GetLayer(0) sr = lyr.GetSpatialRef() got_wkt = sr.ExportToWkt() - if got_wkt.find('GEOGCS["WGS 84"') == -1: - gdaltest.post_reason('did not get expected SRS') - print(got_wkt) - return 'fail' + assert got_wkt.find('GEOGCS["WGS 84"') != -1, 'did not get expected SRS' feat = lyr.GetNextFeature() geom = feat.GetGeometryRef() got_wkt = geom.ExportToWkt() - if got_wkt != 'POINT (2.09 34.12)': - gdaltest.post_reason('did not get expected geometry') - print(got_wkt) - return 'fail' - - return 'success' + assert got_wkt == 'POINT (2.09 34.12)', 'did not get expected geometry' ############################################################################### # Read layer SRS for WFS 1.1.0 return -def ogr_gml_18(): +def test_ogr_gml_18(): if not gdaltest.have_gml_reader: - return 'skip' + pytest.skip() ds = ogr.Open('data/gnis_pop_110.gml') lyr = ds.GetLayer(0) sr = lyr.GetSpatialRef() got_wkt = sr.ExportToWkt() - if got_wkt.find('GEOGCS["WGS 84"') == -1: - gdaltest.post_reason('did not get expected SRS') - print(got_wkt) - return 'fail' + assert got_wkt.find('GEOGCS["WGS 84"') != -1, 'did not get expected SRS' feat = lyr.GetNextFeature() geom = feat.GetGeometryRef() got_wkt = geom.ExportToWkt() - if got_wkt != 'POINT (2.09 34.12)': - gdaltest.post_reason('did not get expected geometry') - print(got_wkt) - return 'fail' - - return 'success' + assert got_wkt == 'POINT (2.09 34.12)', 'did not get expected geometry' ############################################################################### # Read layer SRS for WFS 1.1.0 return, but without trying to restore # (long, lat) order. So we should get EPSGA:4326 and (lat, long) order -def ogr_gml_19(): +def test_ogr_gml_19(): if not gdaltest.have_gml_reader: - return 'skip' + pytest.skip() try: os.remove('data/gnis_pop_110.gfs') @@ -746,30 +608,23 @@ def ogr_gml_19(): lyr = ds.GetLayer(0) sr = lyr.GetSpatialRef() got_wkt = sr.ExportToWkt() - if got_wkt.find('GEOGCS["WGS 84"') == -1 or \ - got_wkt.find('AXIS["Latitude",NORTH],AXIS["Longitude",EAST]') == -1: - gdaltest.post_reason('did not get expected SRS') - print(got_wkt) - return 'fail' + assert (not (got_wkt.find('GEOGCS["WGS 84"') == -1 or \ + got_wkt.find('AXIS["Latitude",NORTH],AXIS["Longitude",EAST]') == -1)), \ + 'did not get expected SRS' feat = lyr.GetNextFeature() geom = feat.GetGeometryRef() got_wkt = geom.ExportToWkt() - if got_wkt != 'POINT (34.12 2.09)': - gdaltest.post_reason('did not get expected geometry') - print(got_wkt) - return 'fail' - - return 'success' + assert got_wkt == 'POINT (34.12 2.09)', 'did not get expected geometry' ############################################################################### # Test parsing a .xsd where the type definition is before its reference -def ogr_gml_20(): +def test_ogr_gml_20(): if not gdaltest.have_gml_reader: - return 'skip' + pytest.skip() try: os.remove('data/archsites.gfs') @@ -783,49 +638,41 @@ def ogr_gml_20(): try: ldefn.GetFieldDefn(0).GetFieldTypeName except: - return 'skip' + pytest.skip() idx = ldefn.GetFieldIndex("gml_id") - if idx == -1: - gdaltest.post_reason('did not get expected column "gml_id"') - return 'fail' + assert idx != -1, 'did not get expected column "gml_id"' idx = ldefn.GetFieldIndex("cat") fddefn = ldefn.GetFieldDefn(idx) - if fddefn.GetFieldTypeName(fddefn.GetType()) != 'Integer64': - gdaltest.post_reason('did not get expected column type for col "cat"') - return 'fail' + assert fddefn.GetFieldTypeName(fddefn.GetType()) == 'Integer64', \ + 'did not get expected column type for col "cat"' idx = ldefn.GetFieldIndex("str1") fddefn = ldefn.GetFieldDefn(idx) - if fddefn.GetFieldTypeName(fddefn.GetType()) != 'String': - gdaltest.post_reason('did not get expected column type for col "str1"') - return 'fail' + assert fddefn.GetFieldTypeName(fddefn.GetType()) == 'String', \ + 'did not get expected column type for col "str1"' - if lyr.GetGeometryColumn() != 'the_geom': - gdaltest.post_reason('did not get expected geometry column name') - return 'fail' + assert lyr.GetGeometryColumn() == 'the_geom', \ + 'did not get expected geometry column name' - if ldefn.GetGeomType() != ogr.wkbPoint: - gdaltest.post_reason('did not get expected geometry type') - return 'fail' + assert ldefn.GetGeomType() == ogr.wkbPoint, 'did not get expected geometry type' ds = None try: os.stat('data/archsites.gfs') - gdaltest.post_reason('did not expected .gfs -> XSD parsing failed') - return 'fail' + pytest.fail('did not expected .gfs -> XSD parsing failed') except OSError: - return 'success' + return ############################################################################### # Test writing GML3 -def ogr_gml_21(frmt='GML3'): +def test_ogr_gml_21(frmt='GML3'): if not gdaltest.have_gml_reader: - return 'skip' + pytest.skip() # Create GML3 file sr = osr.SpatialReference() @@ -858,9 +705,8 @@ def ogr_gml_21(frmt='GML3'): ds = ogr.Open('tmp/gml_21.gml') lyr = ds.GetLayer(0) feat = lyr.GetNextFeature() - if feat.GetGeometryRef().ExportToWkt() != 'POINT (2 49)': - gdaltest.post_reason('did not get expected geometry') - return 'fail' + assert feat.GetGeometryRef().ExportToWkt() == 'POINT (2 49)', \ + 'did not get expected geometry' ds = None # Test that .gml and .xsd are identical to what is expected @@ -875,9 +721,8 @@ def ogr_gml_21(frmt='GML3'): line1 = line1.strip() line2 = line2.strip() if line1 != line2: - gdaltest.post_reason('.gml file not identical to expected') print(open('tmp/gml_21.gml', 'rt').read()) - return 'fail' + pytest.fail('.gml file not identical to expected') line1 = f1.readline() line2 = f2.readline() f1.close() @@ -896,60 +741,49 @@ def ogr_gml_21(frmt='GML3'): line1 = line1.strip() line2 = line2.strip() if line1 != line2: - gdaltest.post_reason('.xsd file not identical to expected') print(open('tmp/gml_21.xsd', 'rt').read()) - return 'fail' + pytest.fail('.xsd file not identical to expected') line1 = f1.readline() line2 = f2.readline() f1.close() f2.close() - return 'success' - -def ogr_gml_21_deegree3(): - return ogr_gml_21('GML3Deegree') +def test_ogr_gml_21_deegree3(): + return test_ogr_gml_21('GML3Deegree') -def ogr_gml_21_gml32(): - return ogr_gml_21('GML3.2') +def test_ogr_gml_21_gml32(): + return test_ogr_gml_21('GML3.2') ############################################################################### # Read a OpenLS DetermineRouteResponse document -def ogr_gml_22(): +def test_ogr_gml_22(): if not gdaltest.have_gml_reader: - return 'skip' + pytest.skip() ds = ogr.Open('data/paris_typical_strike_demonstration.xml') lyr = ds.GetLayerByName('RouteGeometry') - if lyr is None: - gdaltest.post_reason('cannot find RouteGeometry') - return 'fail' + assert lyr is not None, 'cannot find RouteGeometry' lyr = ds.GetLayerByName('RouteInstruction') - if lyr is None: - gdaltest.post_reason('cannot find RouteInstruction') - return 'fail' + assert lyr is not None, 'cannot find RouteInstruction' count = lyr.GetFeatureCount() - if count != 9: - gdaltest.post_reason('did not get expected feature count') - print(count) - return 'fail' + assert count == 9, 'did not get expected feature count' ds = None - return 'success' ############################################################################### # Test that use SRS defined in global gml:Envelope if no SRS is set for any # feature geometry -def ogr_gml_23(): +def test_ogr_gml_23(): if not gdaltest.have_gml_reader: - return 'skip' + pytest.skip() try: os.remove('tmp/global_geometry.gfs') @@ -964,37 +798,27 @@ def ogr_gml_23(): lyr = ds.GetLayer(0) sr = lyr.GetSpatialRef() got_wkt = sr.ExportToWkt() - if got_wkt.find('GEOGCS["WGS 84"') == -1 or \ - got_wkt.find('AXIS["Latitude",NORTH],AXIS["Longitude",EAST]') != -1: - gdaltest.post_reason('did not get expected SRS') - print(got_wkt) - return 'fail' + assert (got_wkt.find('GEOGCS["WGS 84"') != -1 and \ + got_wkt.find('AXIS["Latitude",NORTH],AXIS["Longitude",EAST]') == -1), \ + 'did not get expected SRS' feat = lyr.GetNextFeature() geom = feat.GetGeometryRef() got_wkt = geom.ExportToWkt() - if got_wkt != 'POINT (2 49)': - gdaltest.post_reason('did not get expected geometry') - print(got_wkt) - return 'fail' + assert got_wkt == 'POINT (2 49)', 'did not get expected geometry' extent = lyr.GetExtent() - if extent != (2.0, 3.0, 49.0, 50.0): - gdaltest.post_reason('did not get expected layer extent') - print(extent) - return 'fail' - - return 'success' + assert extent == (2.0, 3.0, 49.0, 50.0), 'did not get expected layer extent' ############################################################################### # Test that use SRS defined in global gml:Envelope if no SRS is set for any # feature geometry -def ogr_gml_24(): +def test_ogr_gml_24(): if not gdaltest.have_gml_reader: - return 'skip' + pytest.skip() try: os.remove('data/global_geometry.gfs') @@ -1019,31 +843,22 @@ def ogr_gml_24(): feat = lyr.GetNextFeature() geom = feat.GetGeometryRef() got_wkt = geom.ExportToWkt() - if got_wkt != 'POINT (2 49)': - gdaltest.post_reason('did not get expected geometry') - print(got_wkt) - return 'fail' + assert got_wkt == 'POINT (2 49)', 'did not get expected geometry' extent = lyr.GetExtent() - if extent != (2.0, 3.0, 49.0, 50.0): - gdaltest.post_reason('did not get expected layer extent') - print(extent) - return 'fail' - - return 'success' + assert extent == (2.0, 3.0, 49.0, 50.0), 'did not get expected layer extent' ############################################################################### # Test fixes for #3934 and #3935 -def ogr_gml_25(): +def test_ogr_gml_25(): if not gdaltest.have_gml_reader: - return 'skip' + pytest.skip() if int(gdal.VersionInfo('VERSION_NUM')) < 1900: - gdaltest.post_reason('would crash') - return 'skip' + pytest.skip('would crash') try: os.remove('data/curveProperty.gfs') @@ -1059,129 +874,107 @@ def ogr_gml_25(): feat = lyr.GetNextFeature() geom = feat.GetGeometryRef() got_wkt = geom.ExportToWkt() - if got_wkt != 'POLYGON ((14 21,6 21,6 9,14 9,22 9,22 21,14 21))': - gdaltest.post_reason('did not get expected geometry') - print(got_wkt) - return 'fail' - - return 'success' + assert got_wkt == 'POLYGON ((14 21,6 21,6 9,14 9,22 9,22 21,14 21))', \ + 'did not get expected geometry' ############################################################################### # Test writing and reading 3D geoms (GML2) -def ogr_gml_26(): +def test_ogr_gml_26(): if not gdaltest.have_gml_reader: - return 'skip' + pytest.skip() import test_cli_utilities if test_cli_utilities.get_ogr2ogr_path() is None: - return 'skip' + pytest.skip() gdaltest.runexternal(test_cli_utilities.get_ogr2ogr_path() + ' -f GML tmp/ogr_gml_26.gml data/poly.shp -zfield eas_id') f = open('tmp/ogr_gml_26.gml', 'rt') content = f.read() f.close() - if content.find("<gml:coord><gml:X>478315.53125</gml:X><gml:Y>4762880.5</gml:Y><gml:Z>158</gml:Z></gml:coord>") == -1: - return 'fail' + assert content.find("<gml:coord><gml:X>478315.53125</gml:X><gml:Y>4762880.5</gml:Y><gml:Z>158</gml:Z></gml:coord>") != -1 ds = ogr.Open('tmp/ogr_gml_26.gml') lyr = ds.GetLayer(0) - if lyr.GetGeomType() != ogr.wkbPolygon25D: - return 'fail' + assert lyr.GetGeomType() == ogr.wkbPolygon25D ds = None - return 'success' - ############################################################################### # Test writing and reading 3D geoms (GML3) -def ogr_gml_27(): +def test_ogr_gml_27(): if not gdaltest.have_gml_reader: - return 'skip' + pytest.skip() import test_cli_utilities if test_cli_utilities.get_ogr2ogr_path() is None: - return 'skip' + pytest.skip() gdaltest.runexternal(test_cli_utilities.get_ogr2ogr_path() + ' -f GML tmp/ogr_gml_27.gml data/poly.shp -zfield eas_id -dsco FORMAT=GML3') f = open('tmp/ogr_gml_27.gml', 'rt') content = f.read() f.close() - if content.find("<gml:lowerCorner>478315.53125 4762880.5 158</gml:lowerCorner>") == -1: - return 'fail' + assert content.find("<gml:lowerCorner>478315.53125 4762880.5 158</gml:lowerCorner>") != -1 ds = ogr.Open('tmp/ogr_gml_27.gml') lyr = ds.GetLayer(0) - if lyr.GetGeomType() != ogr.wkbPolygon25D: - gdaltest.post_reason('fail') - print(lyr.GetGeomType()) - return 'fail' + assert lyr.GetGeomType() == ogr.wkbPolygon25D ds = None - return 'success' - ############################################################################### # Test writing and reading layers of type wkbNone (#4154) -def ogr_gml_28(): +def test_ogr_gml_28(): if not gdaltest.have_gml_reader: - return 'skip' + pytest.skip() import test_cli_utilities if test_cli_utilities.get_ogr2ogr_path() is None: - return 'skip' + pytest.skip() gdaltest.runexternal(test_cli_utilities.get_ogr2ogr_path() + ' -f GML tmp/ogr_gml_28.gml data/idlink.dbf') # Try with .xsd ds = ogr.Open('tmp/ogr_gml_28.gml') lyr = ds.GetLayer(0) - if lyr.GetGeomType() != ogr.wkbNone: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.GetGeomType() == ogr.wkbNone ds = None os.unlink('tmp/ogr_gml_28.xsd') ds = ogr.Open('tmp/ogr_gml_28.gml') lyr = ds.GetLayer(0) - if lyr.GetGeomType() != ogr.wkbNone: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.GetGeomType() == ogr.wkbNone ds = None # Try with .gfs ds = ogr.Open('tmp/ogr_gml_28.gml') lyr = ds.GetLayer(0) - if lyr.GetGeomType() != ogr.wkbNone: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.GetGeomType() == ogr.wkbNone ds = None - return 'success' - ############################################################################### # Test reading FME GMLs -def ogr_gml_29(): +def test_ogr_gml_29(): if not gdaltest.have_gml_reader: - return 'skip' + pytest.skip() ds = ogr.Open('data/testfmegml.gml') @@ -1192,30 +985,25 @@ def ogr_gml_29(): for j, expected_result in enumerate(expected_results): lyr = ds.GetLayer(j) - if lyr.GetGeomType() != expected_result[0]: - gdaltest.post_reason('layer %d, did not get expected layer geometry type' % j) - return 'fail' + assert lyr.GetGeomType() == expected_result[0], \ + ('layer %d, did not get expected layer geometry type' % j) for _ in range(2): feat = lyr.GetNextFeature() geom = feat.GetGeometryRef() got_wkt = geom.ExportToWkt() - if got_wkt != expected_result[1]: - gdaltest.post_reason('layer %d, did not get expected geometry' % j) - print(got_wkt) - return 'fail' + assert got_wkt == expected_result[1], \ + ('layer %d, did not get expected geometry' % j) ds = None - return 'success' - ############################################################################### # Test reading a big field and a big geometry -def ogr_gml_30(): +def test_ogr_gml_30(): if not gdaltest.have_gml_reader: - return 'skip' + pytest.skip() field1 = " " for _ in range(11): @@ -1246,36 +1034,23 @@ def ogr_gml_30(): gdal.Unlink("/vsimem/ogr_gml_30.gml") gdal.Unlink("/vsimem/ogr_gml_30.gfs") - if len(field1) != 2050: - gdaltest.post_reason('did not get expected len(field1)') - print(field1) - print(len(field1)) - return 'fail' + assert len(field1) == 2050, 'did not get expected len(field1)' - if len(geom_wkt) != 2060: - gdaltest.post_reason('did not get expected len(geom_wkt)') - print(geom_wkt) - print(len(geom_wkt)) - return 'fail' - - return 'success' + assert len(geom_wkt) == 2060, 'did not get expected len(geom_wkt)' ############################################################################### # Test SEQUENTIAL_LAYERS -def ogr_gml_31(): +def test_ogr_gml_31(): if not gdaltest.have_gml_reader: - return 'skip' + pytest.skip() gdal.SetConfigOption('GML_READ_MODE', 'SEQUENTIAL_LAYERS') - ret = ogr_gml_29() + test_ogr_gml_29() gdal.SetConfigOption('GML_READ_MODE', None) - if ret != 'success': - return ret - # Test reading second layer and then first layer gdal.SetConfigOption('GML_READ_MODE', 'SEQUENTIAL_LAYERS') ds = ogr.Open('data/testfmegml.gml') @@ -1284,27 +1059,21 @@ def ogr_gml_31(): lyr = ds.GetLayer(1) feat = lyr.GetNextFeature() feat = lyr.GetNextFeature() - if feat.GetFID() != 1: - gdaltest.post_reason('did not get feature when reading directly second layer') - return 'fail' + assert feat.GetFID() == 1, 'did not get feature when reading directly second layer' lyr = ds.GetLayer(0) feat = lyr.GetNextFeature() feat = lyr.GetNextFeature() - if feat.GetFID() != 1: - gdaltest.post_reason('did not get feature when reading back first layer') - return 'fail' - - return 'success' + assert feat.GetFID() == 1, 'did not get feature when reading back first layer' ############################################################################### # Test SEQUENTIAL_LAYERS without a .gfs -def ogr_gml_32(): +def test_ogr_gml_32(): if not gdaltest.have_gml_reader: - return 'skip' + pytest.skip() # Test without .xsd or .gfs f = gdal.VSIFOpenL("data/testfmegml.gml", "rb") @@ -1320,9 +1089,7 @@ def ogr_gml_32(): lyr = ds.GetLayer(1) feat = lyr.GetNextFeature() feat = lyr.GetNextFeature() - if feat.GetFID() != 1: - gdaltest.post_reason('did not get feature when reading directly second layer') - return 'fail' + assert feat.GetFID() == 1, 'did not get feature when reading directly second layer' ds = None @@ -1332,23 +1099,20 @@ def ogr_gml_32(): data = str(data) - if data.find("<SequentialLayers>true</SequentialLayers>") == -1: - gdaltest.post_reason('did not find <SequentialLayers>true</SequentialLayers> in .gfs') - return 'fail' + assert data.find("<SequentialLayers>true</SequentialLayers>") != -1, \ + 'did not find <SequentialLayers>true</SequentialLayers> in .gfs' gdal.Unlink("/vsimem/ogr_gml_31.gml") gdal.Unlink("/vsimem/ogr_gml_31.gfs") - return 'success' - ############################################################################### # Test INTERLEAVED_LAYERS -def ogr_gml_33(): +def test_ogr_gml_33(): if not gdaltest.have_gml_reader: - return 'skip' + pytest.skip() # Test reading second layer and then first layer gdal.SetConfigOption('GML_READ_MODE', 'INTERLEAVED_LAYERS') @@ -1377,20 +1141,17 @@ def ogr_gml_33(): else: fid = feat.GetFID() expected_fid = read_seq[1] - if fid != expected_fid: - gdaltest.post_reason('failed at step %d' % i) - return 'fail' - - return 'success' + assert fid == expected_fid, ('failed at step %d' % i) + ############################################################################### # Test writing non-ASCII UTF-8 content (#4117, #4299) -def ogr_gml_34(): +def test_ogr_gml_34(): if not gdaltest.have_gml_reader: - return 'skip' + pytest.skip() drv = ogr.GetDriverByName('GML') ds = drv.CreateDataSource('/vsimem/ogr_gml_34.gml') @@ -1405,30 +1166,26 @@ def ogr_gml_34(): ds = ogr.Open('/vsimem/ogr_gml_34.gml') lyr = ds.GetLayer(0) feat = lyr.GetNextFeature() - if feat.GetFieldAsString('name') != '\xc4\x80liamanu<&': - print(feat.GetFieldAsString('name')) - return 'fail' + assert feat.GetFieldAsString('name') == '\xc4\x80liamanu<&' ds = None gdal.Unlink('/vsimem/ogr_gml_34.gml') gdal.Unlink('/vsimem/ogr_gml_34.xsd') - return 'success' - ############################################################################### # Test GML_SKIP_RESOLVE_ELEMS=HUGE (#4380) -def ogr_gml_35(): +def test_ogr_gml_35(): if not gdaltest.have_gml_reader: - return 'skip' + pytest.skip() if ogr.GetDriverByName('SQLite') is None: - return 'skip' + pytest.skip() if not ogrtest.have_geos(): - return 'skip' + pytest.skip() try: os.remove('tmp/GmlTopo-sample.sqlite') @@ -1449,53 +1206,39 @@ def ogr_gml_35(): ds = ogr.Open('tmp/GmlTopo-sample.xml') gdal.SetConfigOption('GML_SKIP_RESOLVE_ELEMS', None) - try: + with pytest.raises(OSError, message='did not expect tmp/GmlTopo-sample.sqlite'): os.stat('tmp/GmlTopo-sample.sqlite') - gdaltest.post_reason('did not expect tmp/GmlTopo-sample.sqlite') - return 'fail' - except OSError: - pass + - if gdal.GetLastErrorMsg() != '': - gdaltest.post_reason('did not expect error') - return 'fail' - if ds.GetLayerCount() != 3: - # We have an extra layer : ResolvedNodes - gdaltest.post_reason('expected 3 layers, got %d' % ds.GetLayerCount()) - return 'fail' + assert gdal.GetLastErrorMsg() == '', 'did not expect error' + assert ds.GetLayerCount() == 3, ('expected 3 layers, got %d' % ds.GetLayerCount()) lyr = ds.GetLayerByName('Suolo') feat = lyr.GetNextFeature() wkt = 'MULTIPOLYGON (((-0.1 0.6,-0.0 0.7,0.2 0.7,0.3 0.6,0.5 0.6,0.5 0.8,0.7 0.8,0.8 0.6,0.9 0.6,0.9 0.4,0.7 0.3,0.7 0.2,0.9 0.1,0.9 -0.1,0.6 -0.2,0.3 -0.2,0.2 -0.2,-0.1 0.0,-0.1 0.1,-0.1 0.2,0.1 0.3,0.1 0.4,-0.0 0.4,-0.1 0.5,-0.1 0.6)))' - if ogrtest.check_feature_geometry(feat, wkt): - print(feat.GetGeometryRef()) - return 'fail' + assert not ogrtest.check_feature_geometry(feat, wkt), feat.GetGeometryRef() ds = None ds = ogr.Open('tmp/GmlTopo-sample.xml') lyr = ds.GetLayerByName('Suolo') feat = lyr.GetNextFeature() - if ogrtest.check_feature_geometry(feat, wkt): - print(feat.GetGeometryRef()) - return 'fail' + assert not ogrtest.check_feature_geometry(feat, wkt), feat.GetGeometryRef() ds = None - return 'success' - ############################################################################### # Test GML_SKIP_RESOLVE_ELEMS=NONE (and new GMLTopoSurface interpretation) -def ogr_gml_36(GML_FACE_HOLE_NEGATIVE='NO'): +def test_ogr_gml_36(GML_FACE_HOLE_NEGATIVE='NO'): if not gdaltest.have_gml_reader: - return 'skip' + pytest.skip() if GML_FACE_HOLE_NEGATIVE == 'NO': if not ogrtest.have_geos(): - return 'skip' + pytest.skip() try: os.remove('tmp/GmlTopo-sample.gfs') @@ -1513,9 +1256,7 @@ def ogr_gml_36(GML_FACE_HOLE_NEGATIVE='NO'): ds = ogr.Open('tmp/GmlTopo-sample.xml') gdal.SetConfigOption('GML_SKIP_RESOLVE_ELEMS', None) gdal.SetConfigOption('GML_FACE_HOLE_NEGATIVE', None) - if gdal.GetLastErrorMsg() != '': - gdaltest.post_reason('did not expect error') - return 'fail' + assert gdal.GetLastErrorMsg() == '', 'did not expect error' lyr = ds.GetLayerByName('Suolo') feat = lyr.GetNextFeature() @@ -1523,9 +1264,7 @@ def ogr_gml_36(GML_FACE_HOLE_NEGATIVE='NO'): wkt = 'MULTIPOLYGON (((-0.1 0.6,-0.0 0.7,0.2 0.7,0.3 0.6,0.5 0.6,0.5 0.8,0.7 0.8,0.8 0.6,0.9 0.6,0.9 0.4,0.7 0.3,0.7 0.2,0.9 0.1,0.9 -0.1,0.6 -0.2,0.3 -0.2,0.2 -0.2,-0.1 0.0,-0.1 0.1,-0.1 0.2,0.1 0.3,0.1 0.4,-0.0 0.4,-0.1 0.5,-0.1 0.6)))' else: wkt = 'POLYGON ((-0.1 0.6,-0.0 0.7,0.2 0.7,0.3 0.6,0.5 0.6,0.5 0.8,0.7 0.8,0.8 0.6,0.9 0.6,0.9 0.4,0.7 0.3,0.7 0.2,0.9 0.1,0.9 -0.1,0.6 -0.2,0.3 -0.2,0.2 -0.2,-0.1 0.0,-0.1 0.1,-0.1 0.2,0.1 0.3,0.1 0.4,-0.0 0.4,-0.1 0.5,-0.1 0.6),(0.2 0.2,0.2 0.4,0.4 0.4,0.5 0.2,0.5 0.1,0.5 0.0,0.2 0.0,0.2 0.2),(0.6 0.1,0.8 0.1,0.8 -0.1,0.6 -0.1,0.6 0.1))' - if ogrtest.check_feature_geometry(feat, wkt): - print(feat.GetGeometryRef()) - return 'fail' + assert not ogrtest.check_feature_geometry(feat, wkt), feat.GetGeometryRef() ds = None @@ -1534,36 +1273,32 @@ def ogr_gml_36(GML_FACE_HOLE_NEGATIVE='NO'): gdal.SetConfigOption('GML_FACE_HOLE_NEGATIVE', None) lyr = ds.GetLayerByName('Suolo') feat = lyr.GetNextFeature() - if ogrtest.check_feature_geometry(feat, wkt): - print(feat.GetGeometryRef()) - return 'fail' + assert not ogrtest.check_feature_geometry(feat, wkt), feat.GetGeometryRef() ds = None - return 'success' - ############################################################################### # Test GML_SKIP_RESOLVE_ELEMS=NONE with old GMLTopoSurface interpretation -def ogr_gml_37(): - return ogr_gml_36('YES') +def test_ogr_gml_37(): + return test_ogr_gml_36('YES') ############################################################################### # Test new GMLTopoSurface interpretation (#3934) with HUGE xlink resolver -def ogr_gml_38(resolver='HUGE'): +def test_ogr_gml_38(resolver='HUGE'): if not gdaltest.have_gml_reader: - return 'skip' + pytest.skip() if resolver == 'HUGE': if ogr.GetDriverByName('SQLite') is None: - return 'skip' + pytest.skip() if not ogrtest.have_geos(): - return 'skip' + pytest.skip() try: os.remove('tmp/sample_gml_face_hole_negative_no.sqlite') @@ -1586,65 +1321,53 @@ def ogr_gml_38(resolver='HUGE'): gdal.SetConfigOption('GML_FACE_HOLE_NEGATIVE', None) if resolver == 'HUGE': - try: + with pytest.raises(OSError, message='did not expect tmp/sample_gml_face_hole_negative_no.sqlite'): os.stat('tmp/sample_gml_face_hole_negative_no.sqlite') - gdaltest.post_reason('did not expect tmp/sample_gml_face_hole_negative_no.sqlite') - return 'fail' - except OSError: - pass + - if gdal.GetLastErrorMsg() != '': - gdaltest.post_reason('did not expect error') - return 'fail' + assert gdal.GetLastErrorMsg() == '', 'did not expect error' lyr = ds.GetLayerByName('Suolo') feat = lyr.GetNextFeature() wkt = 'MULTIPOLYGON (((0.9 0.6,0.9 0.4,0.7 0.3,0.7 0.2,0.9 0.1,0.9 -0.1,0.6 -0.2,0.3 -0.2,0.2 -0.2,-0.1 0.0,-0.1 0.1,-0.1 0.2,0.1 0.3,0.1 0.4,-0.0 0.4,-0.1 0.5,-0.1 0.6,-0.0 0.7,0.2 0.7,0.3 0.6,0.5 0.6,0.5 0.8,0.7 0.8,0.8 0.6,0.9 0.6),(0.6 0.1,0.6 -0.1,0.8 -0.1,0.8 0.1,0.6 0.1),(0.2 0.4,0.2 0.2,0.2 0.0,0.5 0.0,0.5 0.1,0.5 0.2,0.4 0.4,0.2 0.4)))' - if ogrtest.check_feature_geometry(feat, wkt): - print(feat.GetGeometryRef()) - return 'fail' + assert not ogrtest.check_feature_geometry(feat, wkt), feat.GetGeometryRef() ds = None - return 'success' - ############################################################################### # Test new GMLTopoSurface interpretation (#3934) with standard xlink resolver -def ogr_gml_39(): - return ogr_gml_38('NONE') +def test_ogr_gml_39(): + return test_ogr_gml_38('NONE') ############################################################################### # Test parsing XSD where simpleTypes not inlined, but defined elsewhere in the .xsd (#4328) -def ogr_gml_40(): +def test_ogr_gml_40(): if not gdaltest.have_gml_reader: - return 'skip' + pytest.skip() ds = ogr.Open('data/testLookForSimpleType.xml') lyr = ds.GetLayer(0) fld_defn = lyr.GetLayerDefn().GetFieldDefn(lyr.GetLayerDefn().GetFieldIndex('CITYNAME')) - if fld_defn.GetWidth() != 26: - return 'fail' - - return 'success' + assert fld_defn.GetWidth() == 26 ############################################################################### # Test validating against .xsd -def ogr_gml_41(): +def test_ogr_gml_41(): gdaltest.have_gml_validation = False if not gdaltest.have_gml_reader: - return 'skip' + pytest.skip() if not gdaltest.download_file('http://schemas.opengis.net/SCHEMAS_OPENGIS_NET.zip', 'SCHEMAS_OPENGIS_NET.zip'): - return 'skip' + pytest.skip() ds = ogr.Open('data/expected_gml_21.gml') @@ -1659,22 +1382,19 @@ def ogr_gml_41(): ds.ReleaseResultSet(lyr) if val == 0: - if gdal.GetLastErrorMsg().find('not implemented due to missing libxml2 support') == -1: - return 'fail' - return 'skip' + assert gdal.GetLastErrorMsg().find('not implemented due to missing libxml2 support') != -1 + pytest.skip() gdaltest.have_gml_validation = True - return 'success' - ############################################################################### # Test validating against .xsd -def ogr_gml_42(): +def test_ogr_gml_42(): if not gdaltest.have_gml_validation: - return 'skip' + pytest.skip() try: os.mkdir('tmp/cache/SCHEMAS_OPENGIS_NET') @@ -1698,27 +1418,23 @@ def ogr_gml_42(): ds.ReleaseResultSet(lyr) - if val == 0: - return 'fail' - - return 'success' + assert val != 0 ############################################################################### # Test automated downloading of WFS schema -def ogr_gml_43(): +def test_ogr_gml_43(): # The service times out - return 'skip' + pytest.skip() # pylint: disable=unreachable if not gdaltest.have_gml_reader: - return 'skip' + pytest.skip() ds = ogr.Open('data/wfs_typefeature.gml') - if ds is None: - return 'fail' + assert ds is not None ds = None try: @@ -1733,20 +1449,17 @@ def ogr_gml_43(): else: can_download_schema = gdal.GetDriverByName('HTTP') is not None - if can_download_schema: - gdaltest.post_reason('.gfs found, but schema could be downloaded') - return 'fail' - - return 'success' + assert not can_download_schema, '.gfs found, but schema could be downloaded' + ############################################################################### # Test providing a custom XSD filename -def ogr_gml_44(): +def test_ogr_gml_44(): if not gdaltest.have_gml_reader: - return 'skip' + pytest.skip() xsd_content = """<?xml version="1.0" encoding="UTF-8"?> <xs:schema targetNamespace="http://ogr.maptools.org/" xmlns:ogr="http://ogr.maptools.org/" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:gml="http://www.opengis.net/gml" elementFormDefault="qualified" version="1.0"> @@ -1785,23 +1498,20 @@ def ogr_gml_44(): lyr = ds.GetLayer(0) # fid and dbl - if lyr.GetLayerDefn().GetFieldCount() != 2: - return 'fail' + assert lyr.GetLayerDefn().GetFieldCount() == 2 ds = None gdal.Unlink('/vsimem/ogr_gml_44.xsd') - return 'success' - ############################################################################### # Test PREFIX and TARGET_NAMESPACE creation options -def ogr_gml_45(): +def test_ogr_gml_45(): if not gdaltest.have_gml_reader: - return 'skip' + pytest.skip() drv = ogr.GetDriverByName('GML') ds = drv.CreateDataSource('/vsimem/ogr_gml_45.gml', options=['PREFIX=foo', 'TARGET_NAMESPACE=http://bar/']) @@ -1823,7 +1533,7 @@ def ogr_gml_45(): if not gdaltest.have_gml_validation: gdal.Unlink('/vsimem/ogr_gml_45.gml') gdal.Unlink('/vsimem/ogr_gml_45.xsd') - return 'skip' + pytest.skip() # Validate document @@ -1843,19 +1553,16 @@ def ogr_gml_45(): gdal.Unlink('/vsimem/ogr_gml_45.gml') gdal.Unlink('/vsimem/ogr_gml_45.xsd') - if val == 0: - return 'fail' - - return 'success' + assert val != 0 ############################################################################### # Validate different kinds of GML files -def ogr_gml_46(): +def test_ogr_gml_46(): if not gdaltest.have_gml_validation: - return 'skip' + pytest.skip() wkt_list = ['', 'POINT (0 1)', @@ -1953,23 +1660,21 @@ def ogr_gml_46(): gdal.Unlink('/vsimem/ogr_gml_46.gml') gdal.Unlink('/vsimem/ogr_gml_46.xsd') - if val == 0: - return 'fail' + assert val != 0 # Only minor schema changes if frmt == 'GML3Deegree': break - return 'success' - + ############################################################################### # Test validation of WFS GML documents -def ogr_gml_47(): +def test_ogr_gml_47(): if not gdaltest.have_gml_validation: - return 'skip' + pytest.skip() filenames = ['data/wfs10.xml', 'data/wfs11.xml', 'data/wfs20.xml'] @@ -1990,12 +1695,9 @@ def ogr_gml_47(): ds.ReleaseResultSet(lyr) ds = None - if val == 0: - gdaltest.post_reason('validation failed for file=%s' % filename) - return 'fail' - - return 'success' + assert val != 0, ('validation failed for file=%s' % filename) + ############################################################################### # Test that we can parse some particular .xsd files that have the geometry # field declared as : @@ -2008,36 +1710,30 @@ def ogr_gml_47(): # </xsd:element> -def ogr_gml_48(): +def test_ogr_gml_48(): if not gdaltest.have_gml_reader: - return 'skip' + pytest.skip() gdal.Unlink('data/schema_with_geom_in_complextype.gfs') ds = ogr.Open('data/schema_with_geom_in_complextype.xml') lyr = ds.GetLayer(0) - if lyr.GetGeomType() != ogr.wkbUnknown: - gdaltest.post_reason('failure') - return 'fail' + assert lyr.GetGeomType() == ogr.wkbUnknown - if lyr.GetLayerDefn().GetFieldDefn(0).GetType() != ogr.OFTString: - gdaltest.post_reason('failure') - return 'fail' + assert lyr.GetLayerDefn().GetFieldDefn(0).GetType() == ogr.OFTString ds = None - return 'success' - ############################################################################### # Test a pseudo Inspire GML file -def ogr_gml_49(): +def test_ogr_gml_49(): if not gdaltest.have_gml_reader: - return 'skip' + pytest.skip() xsd_content = """<ogr:FeatureCollection xmlns:gml="http://www.opengis.net/gml" xmlns:ogr="http://ogr.maptools.org/"> <gml:featureMember> @@ -2054,33 +1750,27 @@ def ogr_gml_49(): ds = ogr.Open('/vsimem/ogr_gml_49.gml') lyr = ds.GetLayer(0) feat = lyr.GetNextFeature() - if feat.GetGeometryRef().GetGeometryType() != ogr.wkbPolygon: - gdaltest.post_reason('failure') - return 'fail' + assert feat.GetGeometryRef().GetGeometryType() == ogr.wkbPolygon ds = None # Now with .gfs file present (#6247) ds = ogr.Open('/vsimem/ogr_gml_49.gml') lyr = ds.GetLayer(0) feat = lyr.GetNextFeature() - if feat.GetGeometryRef().GetGeometryType() != ogr.wkbPolygon: - gdaltest.post_reason('failure') - return 'fail' + assert feat.GetGeometryRef().GetGeometryType() == ogr.wkbPolygon ds = None gdal.Unlink('/vsimem/ogr_gml_49.gml') gdal.Unlink('/vsimem/ogr_gml_49.gfs') - return 'success' - ############################################################################### # Test support for StringList, IntegerList, RealList -def ogr_gml_50(): +def test_ogr_gml_50(): if not gdaltest.have_gml_reader: - return 'skip' + pytest.skip() drv = ogr.GetDriverByName('GML') ds = drv.CreateDataSource('/vsimem/ogr_gml_50.gml') @@ -2102,36 +1792,31 @@ def ogr_gml_50(): lyr = ds.GetLayer(0) feat = lyr.GetNextFeature() if feat.GetFieldAsStringList(lyr.GetLayerDefn().GetFieldIndex('stringlist')) != ['a', 'b']: - gdaltest.post_reason('fail') feat.DumpReadable() - return 'fail' + pytest.fail() if feat.GetFieldAsIntegerList(lyr.GetLayerDefn().GetFieldIndex('intlist')) != [2, 3]: - gdaltest.post_reason('fail') feat.DumpReadable() - return 'fail' + pytest.fail() if feat.GetFieldAsDoubleList(lyr.GetLayerDefn().GetFieldIndex('reallist')) != [4.56, 5.67]: - gdaltest.post_reason('fail') feat.DumpReadable() - return 'fail' + pytest.fail() ds = None gdal.Unlink('/vsimem/ogr_gml_50.gml') gdal.Unlink('/vsimem/ogr_gml_50.xsd') - return 'success' - ############################################################################### # Test -dsco WRITE_FEATURE_BOUNDED_BY=no -dsco STRIP_PREFIX=YES -def ogr_gml_51(): +def test_ogr_gml_51(): if not gdaltest.have_gml_reader: - return 'skip' + pytest.skip() import test_cli_utilities if test_cli_utilities.get_ogr2ogr_path() is None: - return 'skip' + pytest.skip() for frmt in ['GML2', 'GML3']: @@ -2140,46 +1825,29 @@ def ogr_gml_51(): f = open('tmp/ogr_gml_51.gml', 'rt') content = f.read() f.close() - if content.find("<FeatureCollection") == -1: - gdaltest.post_reason('fail') - print(content) - return 'fail' + assert content.find("<FeatureCollection") != -1 if frmt == 'GML3': - if content.find("<featureMember>") == -1: - gdaltest.post_reason('fail') - print(content) - return 'fail' - if content.find("""<poly""") == -1: - gdaltest.post_reason('fail') - print(content) - return 'fail' - if content.find("""<AREA>215229.266</AREA>""") == -1: - gdaltest.post_reason('fail') - print(content) - return 'fail' - - if content.find("""<gml:boundedBy><gml:Envelope><gml:lowerCorner>479647""") != -1: - gdaltest.post_reason('fail') - print(content) - return 'fail' + assert content.find("<featureMember>") != -1 + assert content.find("""<poly""") != -1 + assert content.find("""<AREA>215229.266</AREA>""") != -1 + + assert content.find("""<gml:boundedBy><gml:Envelope><gml:lowerCorner>479647""") == -1 ds = ogr.Open('tmp/ogr_gml_51.gml') lyr = ds.GetLayer(0) feat = lyr.GetNextFeature() - if feat is None: - return 'fail' + assert feat is not None ds = None - return 'success' - + ############################################################################### # Test reading MTKGML files -def ogr_gml_52(): +def test_ogr_gml_52(): if not gdaltest.have_gml_reader: - return 'skip' + pytest.skip() try: os.remove('data/fake_mtkgml.gfs') @@ -2191,18 +1859,11 @@ def ogr_gml_52(): ds = ogr.Open('data/fake_mtkgml.xml') lyr = ds.GetLayerByName('A') - if lyr.GetGeomType() != ogr.wkbPoint25D: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.GetGeomType() == ogr.wkbPoint25D srs = lyr.GetSpatialRef() - if srs is None: - gdaltest.post_reason('fail') - return 'fail' + assert srs is not None wkt = srs.ExportToWkt() - if wkt.find('3067') < 0: - gdaltest.post_reason('fail') - print(wkt) - return 'fail' + assert wkt.find('3067') >= 0 feat = lyr.GetNextFeature() if feat.GetField('gid') != '1' or \ @@ -2211,118 +1872,93 @@ def ogr_gml_52(): feat.GetField('teksti') != 'En francais !' or \ feat.GetField('teksti_kieli') != 'fr' or \ ogrtest.check_feature_geometry(feat, 'POINT (280000 7000000 0)') != 0: - gdaltest.post_reason('fail') feat.DumpReadable() - return 'fail' + pytest.fail() lyr = ds.GetLayerByName('B') - if lyr.GetGeomType() != ogr.wkbPolygon25D: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.GetGeomType() == ogr.wkbPolygon25D srs = lyr.GetSpatialRef() - if srs is None: - gdaltest.post_reason('fail') - return 'fail' + assert srs is not None feat = lyr.GetNextFeature() if ogrtest.check_feature_geometry(feat, 'POLYGON ((280000 7000000 0,281000 7000000 0,281000 7001000 0,280000 7001000 0,280000 7000000 0))') != 0: - gdaltest.post_reason('fail') feat.DumpReadable() - return 'fail' + pytest.fail() lyr = ds.GetLayerByName('C') - if lyr.GetGeomType() != ogr.wkbLineString25D: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.GetGeomType() == ogr.wkbLineString25D feat = lyr.GetNextFeature() if ogrtest.check_feature_geometry(feat, 'LINESTRING (280000 7000000 0,281000 7000000 0,281000 7001000 0,280000 7001000 0,280000 7000000 0)') != 0: - gdaltest.post_reason('fail') feat.DumpReadable() - return 'fail' + pytest.fail() ds = None os.remove('data/fake_mtkgml.gfs') - return 'success' - ############################################################################### # Test that we don't recognize .xsd files themselves -def ogr_gml_53(): +def test_ogr_gml_53(): if not gdaltest.have_gml_reader: - return 'skip' + pytest.skip() ds = ogr.Open('data/archsites.xsd') - if ds is not None: - gdaltest.post_reason('fail') - return 'fail' + assert ds is None ds = None - return 'success' - ############################################################################### # Test that we can open an empty GML datasource (#249, #5205) -def ogr_gml_54(): +def test_ogr_gml_54(): if not gdaltest.have_gml_reader: - return 'skip' + pytest.skip() gdal.Unlink('data/empty.gfs') ds = ogr.Open('data/empty.gml') - if ds is None: - gdaltest.post_reason('fail') - return 'fail' + assert ds is not None ds = None # with .gfs now ds = ogr.Open('data/empty.gml') - if ds is None: - gdaltest.post_reason('fail') - return 'fail' + assert ds is not None ds = None gdal.Unlink('data/empty.gfs') - return 'success' - ############################################################################### # Test support for <xs:include> in schemas # Necessary for Finnish NLS data -def ogr_gml_55(): +def test_ogr_gml_55(): if not gdaltest.have_gml_reader: - return 'skip' + pytest.skip() ds = ogr.Open('data/ogr_gml_55.gml') lyr = ds.GetLayer(0) - if lyr.GetLayerDefn().GetFieldDefn(0).GetType() != ogr.OFTString: - return 'fail' + assert lyr.GetLayerDefn().GetFieldDefn(0).GetType() == ogr.OFTString ds = None - try: + with pytest.raises(OSError): os.unlink('data/ogr_gml_55.gfs') - return 'fail' - except OSError: - pass - - return 'success' + + ############################################################################### # Test support for gml:FeaturePropertyType and multiple geometry field # Necessary for Finnish NLS data -def ogr_gml_56(): +def test_ogr_gml_56(): if not gdaltest.have_gml_reader: - return 'skip' + pytest.skip() gdal.Unlink('data/ogr_gml_56.gfs') @@ -2330,82 +1966,51 @@ def ogr_gml_56(): ds = ogr.Open('data/ogr_gml_56.gml') gdal.SetConfigOption('GML_REGISTRY', None) lyr = ds.GetLayerByName('mainFeature') - if lyr.GetSpatialRef() is None: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.GetSpatialRef() is not None feat = lyr.GetNextFeature() - if feat.GetFieldAsString(feat.GetFieldIndex('subFeatureProperty_href')) != '#subFeature.0': - gdaltest.post_reason('fail') - return 'fail' - if feat.GetFieldAsStringList(feat.GetFieldIndex('subFeatureRepeatedProperty_href')) != ['#subFeatureRepeated.0', '#subFeatureRepeated.1']: - gdaltest.post_reason('fail') - return 'fail' - if feat.GetGeomFieldRef(0).ExportToWkt() != 'POLYGON ((0 0,0 1,1 1,1 0,0 0))': - gdaltest.post_reason('fail') - return 'fail' - if feat.GetGeomFieldRef(1).ExportToWkt() != 'POINT (10 10)': - gdaltest.post_reason('fail') - return 'fail' + assert feat.GetFieldAsString(feat.GetFieldIndex('subFeatureProperty_href')) == '#subFeature.0' + assert feat.GetFieldAsStringList(feat.GetFieldIndex('subFeatureRepeatedProperty_href')) == ['#subFeatureRepeated.0', '#subFeatureRepeated.1'] + assert feat.GetGeomFieldRef(0).ExportToWkt() == 'POLYGON ((0 0,0 1,1 1,1 0,0 0))' + assert feat.GetGeomFieldRef(1).ExportToWkt() == 'POINT (10 10)' lyr = ds.GetLayerByName('subFeature') - if lyr.GetLayerDefn().GetGeomFieldCount() != 0: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.GetLayerDefn().GetGeomFieldCount() == 0 feat = lyr.GetNextFeature() - if feat.GetFieldAsStringList(feat.GetFieldIndex('subFeatureRepeatedProperty_href')) != ['#subFeatureRepeated.2']: - gdaltest.post_reason('fail') - return 'fail' - if feat.GetField('foo') != 'bar': - gdaltest.post_reason('fail') - return 'fail' + assert feat.GetFieldAsStringList(feat.GetFieldIndex('subFeatureRepeatedProperty_href')) == ['#subFeatureRepeated.2'] + assert feat.GetField('foo') == 'bar' lyr = ds.GetLayerByName('subFeatureRepeated') feat = lyr.GetNextFeature() - if feat.GetField('gml_id') != 'subFeatureRepeated.2': - gdaltest.post_reason('fail') - return 'fail' - if feat.GetField('bar') != 'baz': - gdaltest.post_reason('fail') - return 'fail' + assert feat.GetField('gml_id') == 'subFeatureRepeated.2' + assert feat.GetField('bar') == 'baz' feat = lyr.GetNextFeature() - if feat.GetField('gml_id') != 'subFeatureRepeated.0': - gdaltest.post_reason('fail') - return 'fail' + assert feat.GetField('gml_id') == 'subFeatureRepeated.0' feat = lyr.GetNextFeature() - if feat.GetField('gml_id') != 'subFeatureRepeated.1': - gdaltest.post_reason('fail') - return 'fail' + assert feat.GetField('gml_id') == 'subFeatureRepeated.1' ds = None - try: + with pytest.raises(OSError): os.unlink('data/ogr_gml_56.gfs') - return 'fail' - except OSError: - pass - - return 'success' + + ############################################################################### # Test write support for multiple geometry field -def ogr_gml_57(): +def test_ogr_gml_57(): if not gdaltest.have_gml_reader: - return 'skip' + pytest.skip() for i in range(4): options = [] if i == 3: options = ['FORMAT=GML3.2'] ds = ogr.GetDriverByName('GML').CreateDataSource('/vsimem/ogr_gml_57.gml', options=options) - if ds.TestCapability(ogr.ODsCCreateGeomFieldAfterCreateLayer) != 1: - gdaltest.post_reason('fail') - return 'fail' + assert ds.TestCapability(ogr.ODsCCreateGeomFieldAfterCreateLayer) == 1 lyr = ds.CreateLayer('myLayer', geom_type=ogr.wkbNone) - if lyr.TestCapability(ogr.OLCCreateGeomField) != 1: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.TestCapability(ogr.OLCCreateGeomField) == 1 geomfielddefn = ogr.GeomFieldDefn('first_geometry', ogr.wkbPoint) if i == 1 or i == 2: sr = osr.SpatialReference() @@ -2437,57 +2042,36 @@ def ogr_gml_57(): ds = ogr.Open('/vsimem/ogr_gml_57.gml') lyr = ds.GetLayer(0) feat = lyr.GetNextFeature() - if i == 1 and feat.GetGeomFieldRef(0).GetSpatialReference().ExportToWkt().find('32630') < 0: - gdaltest.post_reason('fail') - return 'fail' - if i == 1 and feat.GetGeomFieldRef(1).GetSpatialReference().ExportToWkt().find('32630') < 0: - gdaltest.post_reason('fail') - return 'fail' - if i == 2 and feat.GetGeomFieldRef(1).GetSpatialReference().ExportToWkt().find('32631') < 0: - gdaltest.post_reason('fail') - return 'fail' - if feat.GetGeomFieldRef(0).ExportToWkt() != 'POINT (0 1)': - gdaltest.post_reason('fail') - return 'fail' - if feat.GetGeomFieldRef(1).ExportToWkt() != 'LINESTRING (2 3,4 5)': - gdaltest.post_reason('fail') - return 'fail' + assert not (i == 1 and feat.GetGeomFieldRef(0).GetSpatialReference().ExportToWkt().find('32630') < 0) + assert not (i == 1 and feat.GetGeomFieldRef(1).GetSpatialReference().ExportToWkt().find('32630') < 0) + assert not (i == 2 and feat.GetGeomFieldRef(1).GetSpatialReference().ExportToWkt().find('32631') < 0) + assert feat.GetGeomFieldRef(0).ExportToWkt() == 'POINT (0 1)' + assert feat.GetGeomFieldRef(1).ExportToWkt() == 'LINESTRING (2 3,4 5)' ds = None gdal.Unlink('/vsimem/ogr_gml_57.gml') gdal.Unlink('/vsimem/ogr_gml_57.xsd') - return 'success' - + ############################################################################### # Test support for Inspire Cadastral schemas -def ogr_gml_58(): +def test_ogr_gml_58(): if not gdaltest.have_gml_reader: - return 'skip' + pytest.skip() gdal.Unlink('data/inspire_cadastralparcel.gfs') ds = ogr.Open('data/inspire_cadastralparcel.xml') lyr = ds.GetLayer(0) lyr_defn = lyr.GetLayerDefn() - if lyr_defn.GetGeomFieldCount() != 2: - gdaltest.post_reason('fail') - return 'fail' - if lyr_defn.GetGeomFieldDefn(0).GetName() != 'geometry': - gdaltest.post_reason('fail') - return 'fail' - if lyr_defn.GetGeomFieldDefn(0).GetType() != ogr.wkbMultiPolygon: - gdaltest.post_reason('fail') - return 'fail' - if lyr_defn.GetGeomFieldDefn(1).GetName() != 'referencePoint': - gdaltest.post_reason('fail') - return 'fail' - if lyr_defn.GetGeomFieldDefn(1).GetType() != ogr.wkbPoint: - gdaltest.post_reason('fail') - return 'fail' + assert lyr_defn.GetGeomFieldCount() == 2 + assert lyr_defn.GetGeomFieldDefn(0).GetName() == 'geometry' + assert lyr_defn.GetGeomFieldDefn(0).GetType() == ogr.wkbMultiPolygon + assert lyr_defn.GetGeomFieldDefn(1).GetName() == 'referencePoint' + assert lyr_defn.GetGeomFieldDefn(1).GetType() == ogr.wkbPoint feat = lyr.GetNextFeature() expected = [('gml_id', 'CadastralParcel-01'), @@ -2505,18 +2089,9 @@ def ogr_gml_58(): ('administrativeUnit_href', '#AU.1'), ('zoning_href', '#CZ.1')] for (key, val) in expected: - if feat.GetField(key) != val: - print(key) - print(val) - print(feat.GetField(key)) - gdaltest.post_reason('fail') - return 'fail' - if feat.GetGeomFieldRef(0).ExportToWkt() != 'MULTIPOLYGON (((2 49,2 50,3 50,3 49)))': - gdaltest.post_reason('fail') - return 'fail' - if feat.GetGeomFieldRef(1).ExportToWkt() != 'POINT (2.5 49.5)': - gdaltest.post_reason('fail') - return 'fail' + assert feat.GetField(key) == val + assert feat.GetGeomFieldRef(0).ExportToWkt() == 'MULTIPOLYGON (((2 49,2 50,3 50,3 49)))' + assert feat.GetGeomFieldRef(1).ExportToWkt() == 'POINT (2.5 49.5)' feat = lyr.GetNextFeature() expected = [('gml_id', 'CadastralParcel-02'), @@ -2534,18 +2109,9 @@ def ogr_gml_58(): ('administrativeUnit_href', None), ('zoning_href', None)] for (key, val) in expected: - if feat.GetField(key) != val: - print(key) - print(val) - print(feat.GetField(key)) - gdaltest.post_reason('fail') - return 'fail' - if feat.GetGeomFieldRef(0).ExportToWkt() != 'MULTIPOLYGON (((2 49,2 50,3 50,3 49)))': - gdaltest.post_reason('fail') - return 'fail' - if feat.GetGeomFieldRef(1) is not None: - gdaltest.post_reason('fail') - return 'fail' + assert feat.GetField(key) == val + assert feat.GetGeomFieldRef(0).ExportToWkt() == 'MULTIPOLYGON (((2 49,2 50,3 50,3 49)))' + assert feat.GetGeomFieldRef(1) is None feat = None lyr = None ds = None @@ -2553,9 +2119,7 @@ def ogr_gml_58(): ds = ogr.Open('data/inspire_basicpropertyunit.xml') lyr = ds.GetLayer(0) lyr_defn = lyr.GetLayerDefn() - if lyr_defn.GetGeomFieldCount() != 0: - gdaltest.post_reason('fail') - return 'fail' + assert lyr_defn.GetGeomFieldCount() == 0 feat = lyr.GetNextFeature() expected = [('gml_id', 'BasicPropertyUnit-01'), @@ -2570,12 +2134,7 @@ def ogr_gml_58(): ('endLifespanVersion', '2003-01-01T00:00:00.0Z'), ('administrativeUnit_href', '#AU.1')] for (key, val) in expected: - if feat.GetField(key) != val: - print(key) - print(val) - print(feat.GetField(key)) - gdaltest.post_reason('fail') - return 'fail' + assert feat.GetField(key) == val feat = lyr.GetNextFeature() expected = [('gml_id', 'BasicPropertyUnit-02'), @@ -2590,12 +2149,7 @@ def ogr_gml_58(): ('endLifespanVersion', None), ('administrativeUnit_href', None)] for (key, val) in expected: - if feat.GetField(key) != val: - print(key) - print(val) - print(feat.GetField(key)) - gdaltest.post_reason('fail') - return 'fail' + assert feat.GetField(key) == val feat = None lyr = None ds = None @@ -2603,15 +2157,9 @@ def ogr_gml_58(): ds = ogr.Open('data/inspire_cadastralboundary.xml') lyr = ds.GetLayer(0) lyr_defn = lyr.GetLayerDefn() - if lyr_defn.GetGeomFieldCount() != 1: - gdaltest.post_reason('fail') - return 'fail' - if lyr_defn.GetGeomFieldDefn(0).GetName() != 'geometry': - gdaltest.post_reason('fail') - return 'fail' - if lyr_defn.GetGeomFieldDefn(0).GetType() != ogr.wkbLineString: - gdaltest.post_reason('fail') - return 'fail' + assert lyr_defn.GetGeomFieldCount() == 1 + assert lyr_defn.GetGeomFieldDefn(0).GetName() == 'geometry' + assert lyr_defn.GetGeomFieldDefn(0).GetType() == ogr.wkbLineString feat = lyr.GetNextFeature() expected = [('gml_id', 'CadastralBoundary-01'), @@ -2625,15 +2173,8 @@ def ogr_gml_58(): ('validTo', '2003-01-01T00:00:00.0Z'), ('parcel_href', ['#Parcel.1', '#Parcel.2'])] for (key, val) in expected: - if feat.GetField(key) != val: - print(key) - print(val) - print(feat.GetField(key)) - gdaltest.post_reason('fail') - return 'fail' - if feat.GetGeomFieldRef(0).ExportToWkt() != 'LINESTRING (2 49,3 50)': - gdaltest.post_reason('fail') - return 'fail' + assert feat.GetField(key) == val + assert feat.GetGeomFieldRef(0).ExportToWkt() == 'LINESTRING (2 49,3 50)' feat = lyr.GetNextFeature() expected = [('gml_id', 'CadastralBoundary-02'), @@ -2647,15 +2188,8 @@ def ogr_gml_58(): ('validTo', None), ('parcel_href', None)] for (key, val) in expected: - if feat.GetField(key) != val: - print(key) - print(val) - print(feat.GetField(key)) - gdaltest.post_reason('fail') - return 'fail' - if feat.GetGeomFieldRef(0).ExportToWkt() != 'LINESTRING (2 49,3 50)': - gdaltest.post_reason('fail') - return 'fail' + assert feat.GetField(key) == val + assert feat.GetGeomFieldRef(0).ExportToWkt() == 'LINESTRING (2 49,3 50)' feat = None lyr = None ds = None @@ -2663,21 +2197,11 @@ def ogr_gml_58(): ds = ogr.Open('data/inspire_cadastralzoning.xml') lyr = ds.GetLayer(0) lyr_defn = lyr.GetLayerDefn() - if lyr_defn.GetGeomFieldCount() != 2: - gdaltest.post_reason('fail') - return 'fail' - if lyr_defn.GetGeomFieldDefn(0).GetName() != 'geometry': - gdaltest.post_reason('fail') - return 'fail' - if lyr_defn.GetGeomFieldDefn(0).GetType() != ogr.wkbMultiPolygon: - gdaltest.post_reason('fail') - return 'fail' - if lyr_defn.GetGeomFieldDefn(1).GetName() != 'referencePoint': - gdaltest.post_reason('fail') - return 'fail' - if lyr_defn.GetGeomFieldDefn(1).GetType() != ogr.wkbPoint: - gdaltest.post_reason('fail') - return 'fail' + assert lyr_defn.GetGeomFieldCount() == 2 + assert lyr_defn.GetGeomFieldDefn(0).GetName() == 'geometry' + assert lyr_defn.GetGeomFieldDefn(0).GetType() == ogr.wkbMultiPolygon + assert lyr_defn.GetGeomFieldDefn(1).GetName() == 'referencePoint' + assert lyr_defn.GetGeomFieldDefn(1).GetType() == ogr.wkbPoint feat = lyr.GetNextFeature() expected = [('gml_id', 'CadastralZoning-01'), @@ -2702,18 +2226,9 @@ def ogr_gml_58(): ('validTo', '2003-01-01T00:00:00.0Z'), ('upperLevelUnit_href', '#ulu.1')] for (key, val) in expected: - if feat.GetField(key) != val: - print(key) - print(val) - print(feat.GetField(key)) - gdaltest.post_reason('fail') - return 'fail' - if feat.GetGeomFieldRef(0).ExportToWkt() != 'MULTIPOLYGON (((2 49,2 50,3 50,3 49)))': - gdaltest.post_reason('fail') - return 'fail' - if feat.GetGeomFieldRef(1).ExportToWkt() != 'POINT (2.5 49.5)': - gdaltest.post_reason('fail') - return 'fail' + assert feat.GetField(key) == val + assert feat.GetGeomFieldRef(0).ExportToWkt() == 'MULTIPOLYGON (((2 49,2 50,3 50,3 49)))' + assert feat.GetGeomFieldRef(1).ExportToWkt() == 'POINT (2.5 49.5)' feat = lyr.GetNextFeature() expected = [('gml_id', 'CadastralZoning-02'), @@ -2738,32 +2253,21 @@ def ogr_gml_58(): ('validTo', None), ('upperLevelUnit_href', None)] for (key, val) in expected: - if feat.GetField(key) != val: - print(key) - print(val) - print(feat.GetField(key)) - gdaltest.post_reason('fail') - return 'fail' - if feat.GetGeomFieldRef(0).ExportToWkt() != 'MULTIPOLYGON (((2 49,2 50,3 50,3 49)))': - gdaltest.post_reason('fail') - return 'fail' - if feat.GetGeomFieldRef(1) is not None: - gdaltest.post_reason('fail') - return 'fail' + assert feat.GetField(key) == val + assert feat.GetGeomFieldRef(0).ExportToWkt() == 'MULTIPOLYGON (((2 49,2 50,3 50,3 49)))' + assert feat.GetGeomFieldRef(1) is None feat = None lyr = None ds = None - return 'success' - ############################################################################### # Test GFS conditions -def ogr_gml_59(): +def test_ogr_gml_59(): if not gdaltest.have_gml_reader: - return 'skip' + pytest.skip() # Make sure the .gfs file is more recent that the .gml one try: @@ -2788,27 +2292,20 @@ def ogr_gml_59(): ('name_others_lang', ['de']), ('name_others', ['Deutsche name'])] for (key, val) in expected: - if feat.GetField(key) != val: - print(key) - print(val) - print(feat.GetField(key)) - gdaltest.post_reason('fail') - return 'fail' + assert feat.GetField(key) == val feat = None lyr = None ds = None - return 'success' - ######################################################## # Test reading WFS 2.0 GetFeature documents with wfs:FeatureCollection # as a wfs:member of the top wfs:FeatureCollection -def ogr_gml_60(): +def test_ogr_gml_60(): if not gdaltest.have_gml_reader: - return 'skip' + pytest.skip() # Make sure the .gfs file is more recent that the .gml one gdal.Unlink('data/wfs_200_multiplelayers.gfs') @@ -2816,35 +2313,25 @@ def ogr_gml_60(): for _ in range(2): ds = ogr.Open('data/wfs_200_multiplelayers.gml') lyr = ds.GetLayerByName('road') - if lyr.GetFeatureCount() != 1: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.GetFeatureCount() == 1 feat = lyr.GetNextFeature() - if feat.GetField('gml_id') != 'road.21': - gdaltest.post_reason('fail') - return 'fail' + assert feat.GetField('gml_id') == 'road.21' lyr = ds.GetLayerByName('popplace') - if lyr.GetFeatureCount() != 1: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.GetFeatureCount() == 1 feat = lyr.GetNextFeature() - if feat.GetField('gml_id') != 'popplace.BACMK': - gdaltest.post_reason('fail') - return 'fail' + assert feat.GetField('gml_id') == 'popplace.BACMK' ds = None gdal.Unlink('data/wfs_200_multiplelayers.gfs') - return 'success' - ############################################################################### # Test reading a element specified with a full path in <ElementPath> -def ogr_gml_61(): +def test_ogr_gml_61(): if not gdaltest.have_gml_reader: - return 'skip' + pytest.skip() # Make sure the .gfs file is more recent that the .gml one try: @@ -2863,43 +2350,36 @@ def ogr_gml_61(): ds = ogr.Open('data/gmlsubfeature.gml') lyr = ds.GetLayer(0) - if lyr.GetFeatureCount() != 2: - gdaltest.post_reason('did not get expected geometry column name') - return 'fail' + assert lyr.GetFeatureCount() == 2, 'did not get expected geometry column name' feat = lyr.GetNextFeature() if feat.GetField('gml_id') != 'Object.1' or feat.GetField('foo') != 'bar': - gdaltest.post_reason('fail') feat.DumpReadable() - return 'fail' + pytest.fail() geom = feat.GetGeometryRef() if geom.ExportToWkt() != 'POLYGON ((2 48,2 49,3 49,3 48,2 48))': - gdaltest.post_reason('fail') feat.DumpReadable() - return 'fail' + pytest.fail() feat = lyr.GetNextFeature() if feat.GetField('gml_id') != 'Object.2' or feat.GetField('foo') != 'baz': - gdaltest.post_reason('fail') feat.DumpReadable() - return 'fail' + pytest.fail() geom = feat.GetGeometryRef() if geom.ExportToWkt() != 'POLYGON ((2 -48,2 -49,3 -49,3 -48,2 -48))': - gdaltest.post_reason('fail') feat.DumpReadable() - return 'fail' + pytest.fail() ds = None - return 'success' ############################################################################### # Test GML_ATTRIBUTES_TO_OGR_FIELDS option -def ogr_gml_62(): +def test_ogr_gml_62(): if not gdaltest.have_gml_reader: - return 'skip' + pytest.skip() gdal.Unlink('tmp/gmlattributes.gfs') @@ -2908,9 +2388,7 @@ def ogr_gml_62(): # Default behaviour ds = ogr.Open('tmp/gmlattributes.gml') lyr = ds.GetLayer(0) - if lyr.GetLayerDefn().GetFieldCount() != 1: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.GetLayerDefn().GetFieldCount() == 1 ds = None # Test GML_ATTRIBUTES_TO_OGR_FIELDS=YES @@ -2924,67 +2402,54 @@ def ogr_gml_62(): if i == 0: gdal.SetConfigOption('GML_ATTRIBUTES_TO_OGR_FIELDS', None) lyr = ds.GetLayer(0) - if lyr.GetLayerDefn().GetFieldCount() != 4: - gdaltest.post_reason('fail') - print(i) - return 'fail' + assert lyr.GetLayerDefn().GetFieldCount() == 4, i feat = lyr.GetNextFeature() if feat.GetField('element_attr1') != '1' or \ feat.GetField('element2_attr1') != 'a' or \ feat.GetField('element2') != 'foo' or \ feat.IsFieldSet('element3_attr1'): - gdaltest.post_reason('fail') feat.DumpReadable() - print(i) - return 'fail' + pytest.fail(i) feat = lyr.GetNextFeature() if feat.IsFieldSet('element_attr1') or \ feat.IsFieldSet('element2_attr1') or \ feat.IsFieldSet('element2') or \ feat.GetField('element3_attr1') != 1: - gdaltest.post_reason('fail') feat.DumpReadable() - print(i) - return 'fail' + pytest.fail(i) feat = lyr.GetNextFeature() if feat.GetField('element_attr1') != 'a' or \ feat.IsFieldSet('element2_attr1') or \ feat.IsFieldSet('element2') or \ feat.IsFieldSet('element3_attr1'): - gdaltest.post_reason('fail') feat.DumpReadable() - print(i) - return 'fail' + pytest.fail(i) feat = None ds = None - return 'success' - + ############################################################################### # Test reading RUIAN VFR files -def ogr_gml_63(): +def test_ogr_gml_63(): if not gdaltest.have_gml_reader: - return 'skip' + pytest.skip() # test ST file type ds = ogr.Open('data/ruian_st_v1.xml.gz') # check number of layers nlayers = ds.GetLayerCount() - if nlayers != 14: - return 'fail' + assert nlayers == 14 # check name of first layer lyr = ds.GetLayer(0) - if lyr.GetName() != 'Staty': - return 'fail' + assert lyr.GetName() == 'Staty' # check geometry column name - if lyr.GetGeometryColumn() != 'DefinicniBod': - return 'fail' + assert lyr.GetGeometryColumn() == 'DefinicniBod' ds = None @@ -2993,27 +2458,23 @@ def ogr_gml_63(): # check number of layers nlayers = ds.GetLayerCount() - if nlayers != 11: - return 'fail' + assert nlayers == 11 # check number of features nfeatures = 0 for i in range(nlayers): lyr = ds.GetLayer(i) nfeatures += lyr.GetFeatureCount() - if nfeatures != 7: - return 'fail' - - return 'success' + assert nfeatures == 7 ############################################################################### # Test multiple instances of parsers (#5571) -def ogr_gml_64(): +def test_ogr_gml_64(): if not gdaltest.have_gml_reader: - return 'skip' + pytest.skip() for parser in ['XERCES', 'EXPAT']: for _ in range(2): @@ -3022,20 +2483,17 @@ def ogr_gml_64(): gdal.SetConfigOption('GML_PARSER', None) lyr = ds.GetLayer(0) feat = lyr.GetNextFeature() - if feat is None: - print(parser) - return 'fail' - - return 'success' + assert feat is not None, parser + ############################################################################### # Test SRSDIMENSION_LOC=GEOMETRY option (#5606) -def ogr_gml_65(): +def test_ogr_gml_65(): if not gdaltest.have_gml_reader: - return 'skip' + pytest.skip() option_expected_list = [['SRSDIMENSION_LOC=GEOMETRY', '<ogr:geometryProperty><gml:MultiSurface srsDimension="3"><gml:surfaceMember><gml:Polygon><gml:exterior><gml:LinearRing><gml:posList>0 1 2 3 4 5 6 7 8 0 1 2</gml:posList></gml:LinearRing></gml:exterior></gml:Polygon></gml:surfaceMember></gml:MultiSurface></ogr:geometryProperty>'], ['SRSDIMENSION_LOC=POSLIST', '<ogr:geometryProperty><gml:MultiSurface><gml:surfaceMember><gml:Polygon><gml:exterior><gml:LinearRing><gml:posList srsDimension="3">0 1 2 3 4 5 6 7 8 0 1 2</gml:posList></gml:LinearRing></gml:exterior></gml:Polygon></gml:surfaceMember></gml:MultiSurface></ogr:geometryProperty>'], @@ -3055,32 +2513,28 @@ def ogr_gml_65(): data = gdal.VSIFReadL(1, 10000, f).decode('ascii') gdal.VSIFCloseL(f) - if data.find(expected) < 0: - gdaltest.post_reason('fail') - return 'fail' + assert data.find(expected) >= 0 ds = ogr.Open(filename) lyr = ds.GetLayer(0) feat = lyr.GetNextFeature() if feat.GetGeometryRef().ExportToWkt() != "MULTIPOLYGON (((0 1 2,3 4 5,6 7 8,0 1 2)))": - gdaltest.post_reason('fail') feat.DumpReadable() - return 'fail' + pytest.fail() ds = None gdal.Unlink(filename) gdal.Unlink(filename[0:-3] + "xsd") - return 'success' - + ############################################################################### # Test curve geometries -def ogr_gml_66(): +def test_ogr_gml_66(): if not gdaltest.have_gml_reader: - return 'skip' + pytest.skip() filename = '/vsimem/ogr_gml_66.gml' # filename = 'ogr_gml_66.gml' @@ -3217,199 +2671,148 @@ def ogr_gml_66(): ds = ogr.Open(filename) lyr = ds.GetLayerByName('compoundcurve') - if lyr.GetGeomType() != ogr.wkbCompoundCurve: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.GetGeomType() == ogr.wkbCompoundCurve feat = lyr.GetNextFeature() if feat.GetGeometryRef().ExportToWkt() != 'COMPOUNDCURVE (CIRCULARSTRING (0 0,1 1,2 0))': - gdaltest.post_reason('fail') feat.DumpReadable() - return 'fail' + pytest.fail() feat = lyr.GetNextFeature() if feat.GetGeometryRef().ExportToWkt() != 'COMPOUNDCURVE (CIRCULARSTRING (0 0,1 1,2 0))': - gdaltest.post_reason('fail') feat.DumpReadable() - return 'fail' + pytest.fail() feat = lyr.GetNextFeature() if feat.GetGeometryRef().ExportToWkt() != 'COMPOUNDCURVE ((0 0,1 1,2 0))': - gdaltest.post_reason('fail') feat.DumpReadable() - return 'fail' + pytest.fail() lyr = ds.GetLayerByName('curvepolygon') - if lyr.GetGeomType() != ogr.wkbCurvePolygon: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.GetGeomType() == ogr.wkbCurvePolygon feat = lyr.GetNextFeature() if feat.GetGeometryRef().ExportToWkt() != 'CURVEPOLYGON (CIRCULARSTRING (0 0,0.5 0.5,1 0,0.5 -0.5,0 0))': - gdaltest.post_reason('fail') feat.DumpReadable() - return 'fail' + pytest.fail() feat = lyr.GetNextFeature() if feat.GetGeometryRef().ExportToWkt() != 'CURVEPOLYGON ((0 0,0 1,1 1,0 0))': - gdaltest.post_reason('fail') feat.DumpReadable() - return 'fail' + pytest.fail() lyr = ds.GetLayerByName('multisurface') - if lyr.GetGeomType() != ogr.wkbMultiSurface: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.GetGeomType() == ogr.wkbMultiSurface feat = lyr.GetNextFeature() if feat.GetGeometryRef().ExportToWkt() != 'MULTISURFACE (CURVEPOLYGON (CIRCULARSTRING (0 0,0.5 0.5,1 0,0.5 -0.5,0 0)))': - gdaltest.post_reason('fail') feat.DumpReadable() - return 'fail' + pytest.fail() feat = lyr.GetNextFeature() if feat.GetGeometryRef().ExportToWkt() != 'MULTISURFACE (((0 0,0 1,1 1,0 0)))': - gdaltest.post_reason('fail') feat.DumpReadable() - return 'fail' + pytest.fail() lyr = ds.GetLayerByName('multicurve') - if lyr.GetGeomType() != ogr.wkbMultiCurve: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.GetGeomType() == ogr.wkbMultiCurve feat = lyr.GetNextFeature() if feat.GetGeometryRef().ExportToWkt() != 'MULTICURVE (CIRCULARSTRING (0 0,0.5 0.5,1 0,0.5 -0.5,0 0))': - gdaltest.post_reason('fail') feat.DumpReadable() - return 'fail' + pytest.fail() feat = lyr.GetNextFeature() if feat.GetGeometryRef().ExportToWkt() != 'MULTICURVE ((0 0,0 1,1 1,0 0))': - gdaltest.post_reason('fail') feat.DumpReadable() - return 'fail' + pytest.fail() lyr = ds.GetLayerByName('polygon') - if lyr.GetGeomType() != ogr.wkbPolygon: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.GetGeomType() == ogr.wkbPolygon feat = lyr.GetNextFeature() if feat.GetGeometryRef().ExportToWkt() != 'POLYGON ((0 0,0 1,1 1,0 0))': - gdaltest.post_reason('fail') feat.DumpReadable() - return 'fail' + pytest.fail() lyr = ds.GetLayerByName('linestring') - if lyr.GetGeomType() != ogr.wkbLineString: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.GetGeomType() == ogr.wkbLineString feat = lyr.GetNextFeature() if feat.GetGeometryRef().ExportToWkt() != 'LINESTRING (0 0,0 1,1 1,0 0)': - gdaltest.post_reason('fail') feat.DumpReadable() - return 'fail' + pytest.fail() lyr = ds.GetLayerByName('multipolygon') - if lyr.GetGeomType() != ogr.wkbMultiPolygon: - print(lyr.GetGeomType()) - gdaltest.post_reason('fail') - return 'fail' + assert lyr.GetGeomType() == ogr.wkbMultiPolygon feat = lyr.GetNextFeature() if feat.GetGeometryRef().ExportToWkt() != 'MULTIPOLYGON (((0 0,0 1,1 1,0 0)))': - gdaltest.post_reason('fail') feat.DumpReadable() - return 'fail' + pytest.fail() lyr = ds.GetLayerByName('multilinestring') - if lyr.GetGeomType() != ogr.wkbMultiLineString: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.GetGeomType() == ogr.wkbMultiLineString feat = lyr.GetNextFeature() if feat.GetGeometryRef().ExportToWkt() != 'MULTILINESTRING ((0 0,0 1,1 1,0 0))': - gdaltest.post_reason('fail') feat.DumpReadable() - return 'fail' + pytest.fail() lyr = ds.GetLayerByName('compoundcurve_untyped') if i != 0: - if lyr.GetGeomType() != ogr.wkbCompoundCurve: - print(lyr.GetGeomType()) - gdaltest.post_reason('fail') - return 'fail' + assert lyr.GetGeomType() == ogr.wkbCompoundCurve feat = lyr.GetNextFeature() if feat.GetGeometryRef().ExportToWkt() != 'COMPOUNDCURVE ((0 0,1 1,2 0))': - gdaltest.post_reason('fail') feat.DumpReadable() - return 'fail' + pytest.fail() else: feat = lyr.GetNextFeature() if feat.GetGeometryRef().ExportToWkt() != 'LINESTRING (0 0,1 1,2 0)': - gdaltest.post_reason('fail') feat.DumpReadable() - return 'fail' + pytest.fail() feat = lyr.GetNextFeature() if feat.GetGeometryRef().ExportToWkt() != 'COMPOUNDCURVE (CIRCULARSTRING (0 0,1 1,2 0))': - gdaltest.post_reason('fail') feat.DumpReadable() - return 'fail' + pytest.fail() lyr = ds.GetLayerByName('curvepolygon_untyped') if i != 0: - if lyr.GetGeomType() != ogr.wkbCurvePolygon: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.GetGeomType() == ogr.wkbCurvePolygon feat = lyr.GetNextFeature() if feat.GetGeometryRef().ExportToWkt() != 'CURVEPOLYGON ((0 0,0 1,1 1,0 0))': - gdaltest.post_reason('fail') feat.DumpReadable() - return 'fail' + pytest.fail() else: feat = lyr.GetNextFeature() if feat.GetGeometryRef().ExportToWkt() != 'POLYGON ((0 0,0 1,1 1,0 0))': - gdaltest.post_reason('fail') feat.DumpReadable() - return 'fail' + pytest.fail() feat = lyr.GetNextFeature() if feat.GetGeometryRef().ExportToWkt() != 'CURVEPOLYGON (CIRCULARSTRING (0 0,0.5 0.5,1 0,0.5 -0.5,0 0))': - gdaltest.post_reason('fail') feat.DumpReadable() - return 'fail' + pytest.fail() lyr = ds.GetLayerByName('multisurface_untyped') if i != 0: - if lyr.GetGeomType() != ogr.wkbMultiSurface: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.GetGeomType() == ogr.wkbMultiSurface feat = lyr.GetNextFeature() if feat.GetGeometryRef().ExportToWkt() != 'MULTISURFACE (((0 0,0 1,1 1,0 0)))': - gdaltest.post_reason('fail') feat.DumpReadable() - return 'fail' + pytest.fail() else: feat = lyr.GetNextFeature() if feat.GetGeometryRef().ExportToWkt() != 'MULTIPOLYGON (((0 0,0 1,1 1,0 0)))': - gdaltest.post_reason('fail') feat.DumpReadable() - return 'fail' + pytest.fail() feat = lyr.GetNextFeature() if feat.GetGeometryRef().ExportToWkt() != 'MULTISURFACE (CURVEPOLYGON (CIRCULARSTRING (0 0,0.5 0.5,1 0,0.5 -0.5,0 0)))': - gdaltest.post_reason('fail') feat.DumpReadable() - return 'fail' + pytest.fail() lyr = ds.GetLayerByName('multicurve_untyped') if i != 0: - if lyr.GetGeomType() != ogr.wkbMultiCurve: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.GetGeomType() == ogr.wkbMultiCurve feat = lyr.GetNextFeature() if feat.GetGeometryRef().ExportToWkt() != 'MULTICURVE ((0 0,0 1,1 1,0 0))': - gdaltest.post_reason('fail') feat.DumpReadable() - return 'fail' + pytest.fail() else: feat = lyr.GetNextFeature() if feat.GetGeometryRef().ExportToWkt() != 'MULTILINESTRING ((0 0,0 1,1 1,0 0))': - gdaltest.post_reason('fail') feat.DumpReadable() - return 'fail' + pytest.fail() feat = lyr.GetNextFeature() if feat.GetGeometryRef().ExportToWkt() != 'MULTICURVE (CIRCULARSTRING (0 0,1 1,2 0))': - gdaltest.post_reason('fail') feat.DumpReadable() - return 'fail' + pytest.fail() ds = None @@ -3418,16 +2821,14 @@ def ogr_gml_66(): gdal.Unlink(filename) gdal.Unlink(filename[0:-3] + "gfs") - return 'success' - ############################################################################### # Test boolean, int16, integer64 type -def ogr_gml_67(): +def test_ogr_gml_67(): if not gdaltest.have_gml_reader: - return 'skip' + pytest.skip() filename = '/vsimem/ogr_gml_67.gml' ds = ogr.GetDriverByName('GML').CreateDataSource(filename) @@ -3475,48 +2876,32 @@ def ogr_gml_67(): ds = ogr.Open(filename) lyr = ds.GetLayer(0) - if lyr.GetLayerDefn().GetFieldDefn(lyr.GetLayerDefn().GetFieldIndex('b1')).GetType() != ogr.OFTInteger or \ - lyr.GetLayerDefn().GetFieldDefn(lyr.GetLayerDefn().GetFieldIndex('b1')).GetSubType() != ogr.OFSTBoolean: - print(i) - gdaltest.post_reason('fail') - return 'fail' - if lyr.GetLayerDefn().GetFieldDefn(lyr.GetLayerDefn().GetFieldIndex('bool_list')).GetType() != ogr.OFTIntegerList or \ - lyr.GetLayerDefn().GetFieldDefn(lyr.GetLayerDefn().GetFieldIndex('bool_list')).GetSubType() != ogr.OFSTBoolean: - print(i) - gdaltest.post_reason('fail') - return 'fail' + assert (lyr.GetLayerDefn().GetFieldDefn(lyr.GetLayerDefn().GetFieldIndex('b1')).GetType() == ogr.OFTInteger and \ + lyr.GetLayerDefn().GetFieldDefn(lyr.GetLayerDefn().GetFieldIndex('b1')).GetSubType() == ogr.OFSTBoolean), \ + i + assert (lyr.GetLayerDefn().GetFieldDefn(lyr.GetLayerDefn().GetFieldIndex('bool_list')).GetType() == ogr.OFTIntegerList and \ + lyr.GetLayerDefn().GetFieldDefn(lyr.GetLayerDefn().GetFieldIndex('bool_list')).GetSubType() == ogr.OFSTBoolean), \ + i if i == 0: - if lyr.GetLayerDefn().GetFieldDefn(lyr.GetLayerDefn().GetFieldIndex('short')).GetType() != ogr.OFTInteger or \ - lyr.GetLayerDefn().GetFieldDefn(lyr.GetLayerDefn().GetFieldIndex('short')).GetSubType() != ogr.OFSTInt16: - print(i) - gdaltest.post_reason('fail') - return 'fail' + assert (lyr.GetLayerDefn().GetFieldDefn(lyr.GetLayerDefn().GetFieldIndex('short')).GetType() == ogr.OFTInteger and \ + lyr.GetLayerDefn().GetFieldDefn(lyr.GetLayerDefn().GetFieldIndex('short')).GetSubType() == ogr.OFSTInt16), \ + i if i == 0: - if lyr.GetLayerDefn().GetFieldDefn(lyr.GetLayerDefn().GetFieldIndex('float')).GetType() != ogr.OFTReal or \ - lyr.GetLayerDefn().GetFieldDefn(lyr.GetLayerDefn().GetFieldIndex('float')).GetSubType() != ogr.OFSTFloat32: - print(i) - gdaltest.post_reason('fail') - return 'fail' - if lyr.GetLayerDefn().GetFieldDefn(lyr.GetLayerDefn().GetFieldIndex('int64')).GetType() != ogr.OFTInteger64: - print(i) - gdaltest.post_reason('fail') - return 'fail' - if lyr.GetLayerDefn().GetFieldDefn(lyr.GetLayerDefn().GetFieldIndex('int64list')).GetType() != ogr.OFTInteger64List: - print(i) - gdaltest.post_reason('fail') - return 'fail' + assert (lyr.GetLayerDefn().GetFieldDefn(lyr.GetLayerDefn().GetFieldIndex('float')).GetType() == ogr.OFTReal and \ + lyr.GetLayerDefn().GetFieldDefn(lyr.GetLayerDefn().GetFieldIndex('float')).GetSubType() == ogr.OFSTFloat32), \ + i + assert lyr.GetLayerDefn().GetFieldDefn(lyr.GetLayerDefn().GetFieldIndex('int64')).GetType() == ogr.OFTInteger64, \ + i + assert lyr.GetLayerDefn().GetFieldDefn(lyr.GetLayerDefn().GetFieldIndex('int64list')).GetType() == ogr.OFTInteger64List, \ + i f = lyr.GetNextFeature() if f.GetField('b1') != 1 or f.GetField('b2') != 0 or f.GetFieldAsString('bool_list') != '(2:1,0)' or f.GetField('short') != -32768 or f.GetField('float') != 1.23: - print(i) - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' + pytest.fail(i) f = lyr.GetNextFeature() if f.GetFID() != 1234567890123 or f.GetField('int64') != 1234567890123 or f.GetField('int64list') != [1, 1234567890123]: - print(i) - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' + pytest.fail(i) ds = None gdal.Unlink(filename[0:-3] + "xsd") @@ -3524,16 +2909,14 @@ def ogr_gml_67(): gdal.Unlink(filename) gdal.Unlink(filename[0:-3] + "gfs") - return 'success' - ############################################################################### # Test reading GML with xsd with a choice of geometry properites -def ogr_gml_68(): +def test_ogr_gml_68(): if not gdaltest.have_gml_reader: - return 'skip' + pytest.skip() ds = ogr.Open('data/choicepolygonmultipolygon.gml') @@ -3541,30 +2924,24 @@ def ogr_gml_68(): 'MULTIPOLYGON (((0 0,0 1,1 1,1 0,0 0)),((10 0,10 1,11 1,11 0,10 0)))'] lyr = ds.GetLayer(0) - if lyr.GetGeomType() != ogr.wkbMultiPolygon: - gdaltest.post_reason(' did not get expected layer geometry type') - return 'fail' + assert lyr.GetGeomType() == ogr.wkbMultiPolygon, \ + ' did not get expected layer geometry type' for i in range(2): feat = lyr.GetNextFeature() geom = feat.GetGeometryRef() got_wkt = geom.ExportToWkt() - if got_wkt != expected_results[i]: - gdaltest.post_reason('did not get expected geometry') - print(got_wkt) - return 'fail' + assert got_wkt == expected_results[i], 'did not get expected geometry' ds = None - return 'success' - ############################################################################### # Test not nullable fields -def ogr_gml_69(): +def test_ogr_gml_69(): if not gdaltest.have_gml_reader: - return 'skip' + pytest.skip() ds = ogr.GetDriverByName('GML').CreateDataSource('/vsimem/ogr_gml_69.gml') lyr = ds.CreateLayer('test', geom_type=ogr.wkbNone) @@ -3590,9 +2967,7 @@ def ogr_gml_69(): gdal.PushErrorHandler() ret = lyr.CreateFeature(f) gdal.PopErrorHandler() - if ret == 0: - gdaltest.post_reason('fail') - return 'fail' + assert ret != 0 f = None # Error case: missing non-nullable field @@ -3601,43 +2976,31 @@ def ogr_gml_69(): gdal.PushErrorHandler() ret = lyr.CreateFeature(f) gdal.PopErrorHandler() - if ret == 0: - gdaltest.post_reason('fail') - return 'fail' + assert ret != 0 f = None ds = None ds = gdal.OpenEx('/vsimem/ogr_gml_69.gml', open_options=['EMPTY_AS_NULL=NO']) lyr = ds.GetLayerByName('test') - if lyr.GetLayerDefn().GetFieldDefn(lyr.GetLayerDefn().GetFieldIndex('field_not_nullable')).IsNullable() != 0: - gdaltest.post_reason('fail') - return 'fail' - if lyr.GetLayerDefn().GetFieldDefn(lyr.GetLayerDefn().GetFieldIndex('field_nullable')).IsNullable() != 1: - gdaltest.post_reason('fail') - return 'fail' - if lyr.GetLayerDefn().GetGeomFieldDefn(lyr.GetLayerDefn().GetGeomFieldIndex('geomfield_not_nullable')).IsNullable() != 0: - gdaltest.post_reason('fail') - return 'fail' - if lyr.GetLayerDefn().GetGeomFieldDefn(lyr.GetLayerDefn().GetGeomFieldIndex('geomfield_nullable')).IsNullable() != 1: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.GetLayerDefn().GetFieldDefn(lyr.GetLayerDefn().GetFieldIndex('field_not_nullable')).IsNullable() == 0 + assert lyr.GetLayerDefn().GetFieldDefn(lyr.GetLayerDefn().GetFieldIndex('field_nullable')).IsNullable() == 1 + assert lyr.GetLayerDefn().GetGeomFieldDefn(lyr.GetLayerDefn().GetGeomFieldIndex('geomfield_not_nullable')).IsNullable() == 0 + assert lyr.GetLayerDefn().GetGeomFieldDefn(lyr.GetLayerDefn().GetGeomFieldIndex('geomfield_nullable')).IsNullable() == 1 ds = None gdal.Unlink("/vsimem/ogr_gml_69.gml") gdal.Unlink("/vsimem/ogr_gml_69.xsd") - return 'success' - ############################################################################### # Test default fields (not really supported, but we must do something as we # support not nullable fields) -def ogr_gml_70(): +def test_ogr_gml_70(): if not gdaltest.have_gml_reader: - return 'skip' + pytest.skip() ds = ogr.GetDriverByName('GML').CreateDataSource('/vsimem/ogr_gml_70.gml') lyr = ds.CreateLayer('test', geom_type=ogr.wkbNone) @@ -3657,31 +3020,22 @@ def ogr_gml_70(): lyr = ds.GetLayerByName('test') f = lyr.GetNextFeature() if f.GetField('field_string') != 'a': - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' + pytest.fail() ds = None gdal.Unlink("/vsimem/ogr_gml_70.gml") gdal.Unlink("/vsimem/ogr_gml_70.xsd") - return 'success' - ############################################################################### # Test reading WFS 2.0 layer resulting from a join operation def ogr_gml_71_helper(ds): - if ds.GetLayerCount() != 1: - gdaltest.post_reason('fail') - print(ds.GetLayerCount()) - return 'fail' + assert ds.GetLayerCount() == 1 lyr = ds.GetLayer(0) - if lyr.GetName() != 'join_table1_table2': - gdaltest.post_reason('fail') - print(lyr.GetName()) - return 'fail' + assert lyr.GetName() == 'join_table1_table2' fields = [('table1.gml_id', ogr.OFTString), ('table1.foo', ogr.OFTInteger), ('table1.bar', ogr.OFTInteger), @@ -3689,34 +3043,14 @@ def ogr_gml_71_helper(ds): ('table2.bar', ogr.OFTInteger), ('table2.baz', ogr.OFTString)] layer_defn = lyr.GetLayerDefn() - if layer_defn.GetFieldCount() != len(fields): - gdaltest.post_reason('fail') - print(layer_defn.GetFieldCount()) - return 'fail' + assert layer_defn.GetFieldCount() == len(fields) for i, field in enumerate(fields): fld_defn = layer_defn.GetFieldDefn(i) - if fld_defn.GetName() != field[0]: - gdaltest.post_reason('fail') - print(i) - print(fld_defn.GetName()) - return 'fail' - if fld_defn.GetType() != field[1]: - gdaltest.post_reason('fail') - print(i) - print(fld_defn.GetType()) - return 'fail' - if layer_defn.GetGeomFieldCount() != 2: - gdaltest.post_reason('fail') - print(layer_defn.GetGeomFieldCount()) - return 'fail' - if layer_defn.GetGeomFieldDefn(0).GetName() != 'table1.geometry': - gdaltest.post_reason('fail') - print(layer_defn.GetGeomFieldDefn(0).GetName()) - return 'fail' - if layer_defn.GetGeomFieldDefn(1).GetName() != 'table2.geometry': - gdaltest.post_reason('fail') - print(layer_defn.GetGeomFieldDefn(1).GetName()) - return 'fail' + assert fld_defn.GetName() == field[0], i + assert fld_defn.GetType() == field[1], i + assert layer_defn.GetGeomFieldCount() == 2 + assert layer_defn.GetGeomFieldDefn(0).GetName() == 'table1.geometry' + assert layer_defn.GetGeomFieldDefn(1).GetName() == 'table2.geometry' f = lyr.GetNextFeature() if f.GetField('table1.gml_id') != 'table1-1' or \ f.GetField('table1.foo') != 1 or \ @@ -3726,9 +3060,8 @@ def ogr_gml_71_helper(ds): f.GetField('table2.baz') != 'foo' or \ f.GetGeomFieldRef(0) is not None or \ f.GetGeomFieldRef(1).ExportToWkt() != 'POINT (2 49)': - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' + pytest.fail() f = lyr.GetNextFeature() if f.GetField('table1.gml_id') != 'table1-2' or \ f.IsFieldSet('table1.foo') or \ @@ -3738,88 +3071,68 @@ def ogr_gml_71_helper(ds): f.GetField('table2.baz') != 'bar' or \ f.GetGeomFieldRef(0).ExportToWkt() != 'POINT (3 50)' or \ f.GetGeomFieldRef(1).ExportToWkt() != 'POINT (2 50)': - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' + pytest.fail() - return 'success' + - -def ogr_gml_71(): +def test_ogr_gml_71(): if not gdaltest.have_gml_reader: - return 'skip' + pytest.skip() # With .xsd gdal.Unlink('data/wfsjointlayer.gfs') ds = ogr.Open('data/wfsjointlayer.gml') - if ogr_gml_71_helper(ds) != 'success': - gdaltest.post_reason('fail') - return 'fail' + ogr_gml_71_helper(ds) ds = None - try: + with pytest.raises(OSError): os.unlink('data/wfsjointlayer.gfs') - gdaltest.post_reason('fail') - return 'fail' - except OSError: - pass + # With .xsd but that is only partially understood ds = gdal.OpenEx('data/wfsjointlayer.gml', open_options=['XSD=data/wfsjointlayer_not_understood.xsd']) - if ogr_gml_71_helper(ds) != 'success': - gdaltest.post_reason('fail') - return 'fail' + ogr_gml_71_helper(ds) ds = None try: os.unlink('data/wfsjointlayer.gfs') except OSError: - gdaltest.post_reason('fail') - return 'fail' + pytest.fail() # Without .xsd nor .gfs shutil.copy('data/wfsjointlayer.gml', 'tmp/wfsjointlayer.gml') gdal.Unlink('tmp/wfsjointlayer.gfs') ds = ogr.Open('tmp/wfsjointlayer.gml') - if ogr_gml_71_helper(ds) != 'success': - gdaltest.post_reason('fail') - return 'fail' + ogr_gml_71_helper(ds) ds = None try: os.stat('tmp/wfsjointlayer.gfs') except OSError: - gdaltest.post_reason('fail') - return 'fail' + pytest.fail() # With .gfs ds = ogr.Open('tmp/wfsjointlayer.gml') - if ogr_gml_71_helper(ds) != 'success': - gdaltest.post_reason('fail') - return 'fail' + ogr_gml_71_helper(ds) ds = None - return 'success' - ############################################################################### # Test name and description -def ogr_gml_72(): +def test_ogr_gml_72(): if not gdaltest.have_gml_reader: - return 'skip' + pytest.skip() ds = ogr.GetDriverByName('GML').CreateDataSource('/vsimem/ogr_gml_72.gml', options=['NAME=name', 'DESCRIPTION=description']) ds.SetMetadata({'NAME': 'ignored', 'DESCRIPTION': 'ignored'}) ds = None ds = ogr.Open('/vsimem/ogr_gml_72.gml') - if ds.GetMetadata() != {'NAME': 'name', 'DESCRIPTION': 'description'}: - gdaltest.post_reason('fail') - print(ds.GetMetadata()) - return 'fail' + assert ds.GetMetadata() == {'NAME': 'name', 'DESCRIPTION': 'description'} ds = None gdal.Unlink("/vsimem/ogr_gml_72.gml") @@ -3831,26 +3144,21 @@ def ogr_gml_72(): ds = None ds = ogr.Open('/vsimem/ogr_gml_72.gml') - if ds.GetMetadata() != {'NAME': 'name', 'DESCRIPTION': 'description'}: - gdaltest.post_reason('fail') - print(ds.GetMetadata()) - return 'fail' + assert ds.GetMetadata() == {'NAME': 'name', 'DESCRIPTION': 'description'} ds = None gdal.Unlink("/vsimem/ogr_gml_72.gml") gdal.Unlink("/vsimem/ogr_gml_72.xsd") gdal.Unlink("/vsimem/ogr_gml_72.gfs") - return 'success' - ############################################################################### # Read a CSW GetRecordsResponse document -def ogr_gml_73(): +def test_ogr_gml_73(): if not gdaltest.have_gml_reader: - return 'skip' + pytest.skip() try: os.remove('data/cswresults.gfs') @@ -3862,18 +3170,13 @@ def ogr_gml_73(): lyr = ds.GetLayer(i) sr = lyr.GetSpatialRef() got_wkt = sr.ExportToWkt() - if got_wkt.find('4326') < 0: - gdaltest.post_reason('did not get expected SRS') - print(got_wkt) - return 'fail' + assert got_wkt.find('4326') >= 0, 'did not get expected SRS' feat = lyr.GetNextFeature() geom = feat.GetGeometryRef() got_wkt = geom.ExportToWkt() - if got_wkt != 'POLYGON ((-180 -90,-180 90,180 90,180 -90,-180 -90))': - gdaltest.post_reason('did not get expected geometry') - print(got_wkt) - return 'fail' + assert got_wkt == 'POLYGON ((-180 -90,-180 90,180 90,180 -90,-180 -90))', \ + 'did not get expected geometry' ds = None @@ -3882,27 +3185,21 @@ def ogr_gml_73(): except OSError: pass - return 'success' - + ############################################################################### # Test FORCE_SRS_DETECTION open option -def ogr_gml_74(): +def test_ogr_gml_74(): if not gdaltest.have_gml_reader: - return 'skip' + pytest.skip() # With .xsd ds = gdal.OpenEx('data/expected_gml_gml32.gml', open_options=['FORCE_SRS_DETECTION=YES']) lyr = ds.GetLayer(0) - if lyr.GetSpatialRef() is None: - gdaltest.post_reason('did not get expected SRS') - return 'fail' - if lyr.GetFeatureCount() != 2: - gdaltest.post_reason('did not get expected feature count') - print(lyr.GetFeatureCount()) - return 'fail' + assert lyr.GetSpatialRef() is not None, 'did not get expected SRS' + assert lyr.GetFeatureCount() == 2, 'did not get expected feature count' shutil.copy('data/expected_gml_gml32.gml', 'tmp/ogr_gml_74.gml') if os.path.exists('tmp/ogr_gml_74.gfs'): @@ -3911,39 +3208,27 @@ def ogr_gml_74(): # Without .xsd or .gfs ds = gdal.OpenEx('tmp/ogr_gml_74.gml', open_options=['FORCE_SRS_DETECTION=YES']) lyr = ds.GetLayer(0) - if lyr.GetSpatialRef() is None: - gdaltest.post_reason('did not get expected SRS') - return 'fail' - if lyr.GetFeatureCount() != 2: - gdaltest.post_reason('did not get expected feature count') - print(lyr.GetFeatureCount()) - return 'fail' + assert lyr.GetSpatialRef() is not None, 'did not get expected SRS' + assert lyr.GetFeatureCount() == 2, 'did not get expected feature count' # With .gfs ds = gdal.OpenEx('tmp/ogr_gml_74.gml', open_options=['FORCE_SRS_DETECTION=YES']) lyr = ds.GetLayer(0) - if lyr.GetSpatialRef() is None: - gdaltest.post_reason('did not get expected SRS') - return 'fail' - if lyr.GetFeatureCount() != 2: - gdaltest.post_reason('did not get expected feature count') - print(lyr.GetFeatureCount()) - return 'fail' + assert lyr.GetSpatialRef() is not None, 'did not get expected SRS' + assert lyr.GetFeatureCount() == 2, 'did not get expected feature count' ds = None os.unlink('tmp/ogr_gml_74.gml') os.unlink('tmp/ogr_gml_74.gfs') - return 'success' - ############################################################################### # Test we don't open a WMTS Capabilities doc -def ogr_gml_75(): +def test_ogr_gml_75(): if not gdaltest.have_gml_reader: - return 'skip' + pytest.skip() gdal.FileFromMemBuffer("/vsimem/ogr_gml_75.xml", """<?xml version="1.0" encoding="UTF-8"?> @@ -3973,24 +3258,20 @@ def ogr_gml_75(): </Capabilities>""") ds = ogr.Open('/vsimem/ogr_gml_75.xml') - if ds is not None: - gdaltest.post_reason('fail') - return 'fail' + assert ds is None gdal.Unlink('/vsimem/ogr_gml_75.xml') - return 'success' - ############################################################################### # Test we are robust to content of XML elements bigger than 2 GB -def ogr_gml_76(): +def test_ogr_gml_76(): if not gdaltest.have_gml_reader: - return 'skip' + pytest.skip() if not gdaltest.run_slow_tests(): - return 'skip' + pytest.skip() with gdaltest.error_handler(): ds = ogr.Open('/vsisparse/data/huge_attribute_gml_sparse.xml') @@ -4003,16 +3284,15 @@ def ogr_gml_76(): lyr = ds.GetLayer(0) lyr.GetNextFeature() - return 'success' - + ############################################################################### # Test interpretation of http://www.opengis.net/def/crs/EPSG/0/ URLs (#6678) -def ogr_gml_77(): +def test_ogr_gml_77(): if not gdaltest.have_gml_reader: - return 'skip' + pytest.skip() gdal.FileFromMemBuffer("/vsimem/ogr_gml_77.xml", """<?xml version="1.0" encoding="utf-8" ?> @@ -4031,44 +3311,34 @@ def ogr_gml_77(): ds = ogr.Open('/vsimem/ogr_gml_77.xml') lyr = ds.GetLayer(0) - if lyr.GetSpatialRef().ExportToWkt().find('AXIS') >= 0: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.GetSpatialRef().ExportToWkt().find('AXIS') < 0 f = lyr.GetNextFeature() - if f.GetGeometryRef().ExportToWkt() != 'POINT (2 49)': - gdaltest.post_reason('fail') - return 'fail' + assert f.GetGeometryRef().ExportToWkt() == 'POINT (2 49)' ds = None ds = gdal.OpenEx('/vsimem/ogr_gml_77.xml', open_options=['SWAP_COORDINATES=YES']) lyr = ds.GetLayer(0) f = lyr.GetNextFeature() - if f.GetGeometryRef().ExportToWkt() != 'POINT (2 49)': - gdaltest.post_reason('fail') - return 'fail' + assert f.GetGeometryRef().ExportToWkt() == 'POINT (2 49)' ds = None ds = gdal.OpenEx('/vsimem/ogr_gml_77.xml', open_options=['SWAP_COORDINATES=NO']) lyr = ds.GetLayer(0) f = lyr.GetNextFeature() - if f.GetGeometryRef().ExportToWkt() != 'POINT (49 2)': - gdaltest.post_reason('fail') - return 'fail' + assert f.GetGeometryRef().ExportToWkt() == 'POINT (49 2)' ds = None gdal.Unlink('/vsimem/ogr_gml_77.xml') gdal.Unlink('/vsimem/ogr_gml_77.gfs') - return 'success' - ############################################################################### # Test effect of SWAP_COORDINATES (#6678) -def ogr_gml_78(): +def test_ogr_gml_78(): if not gdaltest.have_gml_reader: - return 'skip' + pytest.skip() gdal.FileFromMemBuffer("/vsimem/ogr_gml_78.xml", """<?xml version="1.0" encoding="utf-8" ?> @@ -4087,41 +3357,31 @@ def ogr_gml_78(): ds = ogr.Open('/vsimem/ogr_gml_78.xml') lyr = ds.GetLayer(0) - if lyr.GetSpatialRef().ExportToWkt().find('AXIS') >= 0: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.GetSpatialRef().ExportToWkt().find('AXIS') < 0 f = lyr.GetNextFeature() - if f.GetGeometryRef().ExportToWkt() != 'POINT (2 49)': - gdaltest.post_reason('fail') - return 'fail' + assert f.GetGeometryRef().ExportToWkt() == 'POINT (2 49)' ds = None ds = gdal.OpenEx('/vsimem/ogr_gml_78.xml', open_options=['SWAP_COORDINATES=YES']) lyr = ds.GetLayer(0) f = lyr.GetNextFeature() - if f.GetGeometryRef().ExportToWkt() != 'POINT (49 2)': - gdaltest.post_reason('fail') - return 'fail' + assert f.GetGeometryRef().ExportToWkt() == 'POINT (49 2)' ds = None ds = gdal.OpenEx('/vsimem/ogr_gml_78.xml', open_options=['SWAP_COORDINATES=NO']) lyr = ds.GetLayer(0) f = lyr.GetNextFeature() - if f.GetGeometryRef().ExportToWkt() != 'POINT (2 49)': - gdaltest.post_reason('fail') - return 'fail' + assert f.GetGeometryRef().ExportToWkt() == 'POINT (2 49)' ds = None gdal.Unlink('/vsimem/ogr_gml_78.xml') gdal.Unlink('/vsimem/ogr_gml_78.gfs') - return 'success' - ############################################################################### # Test SRSNAME_FORMAT -def ogr_gml_79(): +def test_ogr_gml_79(): sr = osr.SpatialReference() sr.ImportFromEPSG(4326) @@ -4146,25 +3406,20 @@ def ogr_gml_79(): data = gdal.VSIFReadL(1, 10000, f).decode('utf-8') gdal.VSIFCloseL(f) - if data.find(expected_srsname) < 0 or data.find(expected_coords) < 0: - gdaltest.post_reason('fail') - print(srsname_format) - print(data) - return 'fail' + assert data.find(expected_srsname) >= 0 and data.find(expected_coords) >= 0, \ + srsname_format gdal.Unlink('/vsimem/ogr_gml_79.xml') gdal.Unlink('/vsimem/ogr_gml_79.xsd') - return 'success' - ############################################################################### # Test null / unset -def ogr_gml_80(): +def test_ogr_gml_80(): if not gdaltest.have_gml_reader: - return 'skip' + pytest.skip() ds = ogr.GetDriverByName('GML').CreateDataSource('/vsimem/ogr_gml_80.xml') lyr = ds.CreateLayer('test', geom_type=ogr.wkbNone) @@ -4187,37 +3442,32 @@ def ogr_gml_80(): lyr = ds.GetLayer(0) f = lyr.GetNextFeature() if f['int_field'] != 4: - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' + pytest.fail() f = lyr.GetNextFeature() if f['int_field'] is not None: - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' + pytest.fail() f = lyr.GetNextFeature() if f.IsFieldSet('int_field'): - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' + pytest.fail() f = None ds = None gdal.Unlink('/vsimem/ogr_gml_80.xml') gdal.Unlink('/vsimem/ogr_gml_80.xsd') - return 'success' - ############################################################################### # Test building a .gfs with a field with xsi:nil="true" (#7027) -def ogr_gml_81(): +def test_ogr_gml_81(): if not gdaltest.have_gml_reader: - return 'skip' + pytest.skip() gdal.Unlink('data/test_xsi_nil_gfs.gfs') ds = ogr.Open('data/test_xsi_nil_gfs.gml') @@ -4225,21 +3475,19 @@ def ogr_gml_81(): f = lyr.GetNextFeature() if f.GetField('intval') != 1: f.DumpReadable() - return 'fail' + pytest.fail() ds = None gdal.Unlink('data/test_xsi_nil_gfs.gfs') - return 'success' - ############################################################################### # Test GML_FEATURE_COLLECTION=YES -def ogr_gml_82(): +def test_ogr_gml_82(): if not gdaltest.have_gml_reader: - return 'skip' + pytest.skip() gdal.VectorTranslate('/vsimem/ogr_gml_82.gml', 'data/poly.shp', format='GML', @@ -4248,42 +3496,29 @@ def ogr_gml_82(): ds = ogr.Open('/vsimem/ogr_gml_82.gml') lyr = ds.GetLayer(0) - if lyr.GetFeatureCount() != 10: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.GetFeatureCount() == 10 ds = None f = gdal.VSIFOpenL("/vsimem/ogr_gml_82.gml", "rb") if f is not None: data = gdal.VSIFReadL(1, 10000, f).decode('utf-8') gdal.VSIFCloseL(f) - if data.find('gml:FeatureCollection') < 0: - gdaltest.post_reason('fail') - print(data) - return 'fail' + assert data.find('gml:FeatureCollection') >= 0 f = gdal.VSIFOpenL("/vsimem/ogr_gml_82.xsd", "rb") if f is not None: data = gdal.VSIFReadL(1, 10000, f).decode('utf-8') gdal.VSIFCloseL(f) - if data.find('name = "FeatureCollection"') >= 0: - gdaltest.post_reason('fail') - print(data) - return 'fail' - if data.find('gmlsf') >= 0: - gdaltest.post_reason('fail') - print(data) - return 'fail' + assert data.find('name = "FeatureCollection"') < 0 + assert data.find('gmlsf') < 0 gdal.Unlink('/vsimem/ogr_gml_82.gml') gdal.Unlink('/vsimem/ogr_gml_82.xsd') - return 'success' - ############################################################################### -def ogr_gml_gml2_write_geometry_error(): +def test_ogr_gml_gml2_write_geometry_error(): ds = ogr.GetDriverByName('GML').CreateDataSource('/vsimem/ogr_gml_83.gml') lyr = ds.CreateLayer('test') @@ -4296,15 +3531,13 @@ def ogr_gml_gml2_write_geometry_error(): gdal.Unlink('/vsimem/ogr_gml_83.gml') gdal.Unlink('/vsimem/ogr_gml_83.xsd') - return 'success' - ############################################################################### # Cleanup -def ogr_gml_cleanup(): +def test_ogr_gml_cleanup(): if not gdaltest.have_gml_reader: - return 'skip' + pytest.skip() gdal.SetConfigOption('GML_SKIP_RESOLVE_ELEMS', None) gdal.SetConfigOption('GML_SAVE_RESOLVED_TO', None) @@ -4315,10 +3548,10 @@ def ogr_gml_cleanup(): if fl is not None: print(fl) - return ogr_gml_clean_files() + return test_ogr_gml_clean_files() -def ogr_gml_clean_files(): +def test_ogr_gml_clean_files(): try: os.remove('data/bom.gfs') except OSError: @@ -4429,109 +3662,3 @@ def ogr_gml_clean_files(): if len(filename) > 13 and filename[-13:] == '.resolved.gml': os.unlink('data/' + filename) gdal.Unlink('data/test_xsi_nil_gfs.gfs') - - return 'success' - - -gdaltest_list = [ - ogr_gml_clean_files, - ogr_gml_1, - ogr_gml_2, - ogr_gml_3, - ogr_gml_4, - ogr_gml_5, - ogr_gml_6, - ogr_gml_7, - ogr_gml_8, - ogr_gml_9, - ogr_gml_10, - ogr_gml_11, - ogr_gml_12, - ogr_gml_13, - ogr_gml_14, - ogr_gml_15, - ogr_gml_16, - ogr_gml_17, - ogr_gml_18, - ogr_gml_19, - ogr_gml_20, - ogr_gml_21, - ogr_gml_21_deegree3, - ogr_gml_21_gml32, - ogr_gml_22, - ogr_gml_23, - ogr_gml_24, - ogr_gml_25, - ogr_gml_26, - ogr_gml_27, - ogr_gml_28, - ogr_gml_29, - ogr_gml_30, - ogr_gml_31, - ogr_gml_32, - ogr_gml_33, - ogr_gml_34, - ogr_gml_35, - ogr_gml_36, - ogr_gml_37, - ogr_gml_38, - ogr_gml_39, - ogr_gml_40, - ogr_gml_41, - ogr_gml_42, - ogr_gml_43, - ogr_gml_44, - ogr_gml_45, - ogr_gml_46, - ogr_gml_47, - ogr_gml_48, - ogr_gml_49, - ogr_gml_50, - ogr_gml_51, - ogr_gml_52, - ogr_gml_53, - ogr_gml_54, - ogr_gml_55, - ogr_gml_56, - ogr_gml_57, - ogr_gml_58, - ogr_gml_59, - ogr_gml_60, - ogr_gml_61, - ogr_gml_62, - ogr_gml_63, - ogr_gml_64, - ogr_gml_65, - ogr_gml_66, - ogr_gml_67, - ogr_gml_68, - ogr_gml_69, - ogr_gml_70, - ogr_gml_71, - ogr_gml_72, - ogr_gml_73, - ogr_gml_74, - ogr_gml_75, - ogr_gml_76, - ogr_gml_77, - ogr_gml_78, - ogr_gml_79, - ogr_gml_80, - ogr_gml_81, - ogr_gml_82, - ogr_gml_gml2_write_geometry_error, - ogr_gml_cleanup] - -disabled_gdaltest_list = [ - ogr_gml_clean_files, - ogr_gml_1, - ogr_gml_82, - ogr_gml_cleanup] - -if __name__ == '__main__': - - gdaltest.setup_run('ogr_gml_read') - - gdaltest.run_tests(gdaltest_list) - - sys.exit(gdaltest.summarize()) diff --git a/autotest/ogr/ogr_gmlas.py b/autotest/ogr/ogr_gmlas.py index de19582f2890..98d2b265aebe 100755 --- a/autotest/ogr/ogr_gmlas.py +++ b/autotest/ogr/ogr_gmlas.py @@ -41,7 +41,6 @@ import os.path import sys -sys.path.append('../pymod') import gdaltest import ogrtest @@ -49,6 +48,7 @@ from osgeo import gdal from osgeo import ogr +import pytest ############################################################################### @@ -58,7 +58,7 @@ def compare_ogrinfo_output(gmlfile, reffile, options=''): import test_cli_utilities if test_cli_utilities.get_ogrinfo_path() is None: - return 'skip' + pytest.skip() tmpfilename = 'tmp/' + os.path.basename(gmlfile) + '.txt' ret = gdaltest.runexternal(test_cli_utilities.get_ogrinfo_path() + @@ -73,24 +73,21 @@ def compare_ogrinfo_output(gmlfile, reffile, options=''): expected = open(reffile, 'rb').read().decode('utf-8') expected = expected.replace('\r\n', '\n') if ret != expected: - gdaltest.post_reason('fail') - print('Got:') print(ret.encode('utf-8')) open(tmpfilename, 'wb').write(ret.encode('utf-8')) print('Diff:') os.system('diff -u ' + reffile + ' ' + tmpfilename) # os.unlink(tmpfilename) - return 'fail' - return 'success' - + pytest.fail('Got:') + ############################################################################### # Basic test -def ogr_gmlas_basic(): +def test_ogr_gmlas_basic(): if ogr.GetDriverByName('GMLAS') is None: - return 'skip' + pytest.skip() gdal.SetConfigOption('GMLAS_WARN_UNEXPECTED', 'YES') @@ -100,15 +97,12 @@ def ogr_gmlas_basic(): gdal.SetConfigOption('GDAL_XML_VALIDATION', 'NO') ds = ogr.Open('GMLAS:data/gmlas/gmlas_test1.xml') - if ds is None: - gdaltest.post_reason('fail') - return 'fail' + assert ds is not None ds = None # Skip tests when -fsanitize is used if gdaltest.is_travis_branch('sanitize'): - print('Skipping because of -sanitize') - return 'skip' + pytest.skip('Skipping because of -sanitize') return compare_ogrinfo_output('data/gmlas/gmlas_test1.xml', 'data/gmlas/gmlas_test1.txt') @@ -117,37 +111,32 @@ def ogr_gmlas_basic(): # Run test_ogrsf -def ogr_gmlas_test_ogrsf(): +def test_ogr_gmlas_test_ogrsf(): if ogr.GetDriverByName('GMLAS') is None: - return 'skip' + pytest.skip() # Skip tests when -fsanitize is used if gdaltest.is_travis_branch('sanitize'): - print('Skipping because of -sanitize') - return 'skip' + pytest.skip('Skipping because of -sanitize') import test_cli_utilities if test_cli_utilities.get_test_ogrsf_path() is None: - return 'skip' + pytest.skip() ret = gdaltest.runexternal(test_cli_utilities.get_test_ogrsf_path() + ' -ro GMLAS:data/gmlas/gmlas_test1.xml') - if ret.find('INFO') == -1 or ret.find('ERROR') != -1: - print(ret) - return 'fail' - - return 'success' + assert ret.find('INFO') != -1 and ret.find('ERROR') == -1 ############################################################################### # Test virtual file support -def ogr_gmlas_virtual_file(): +def test_ogr_gmlas_virtual_file(): if ogr.GetDriverByName('GMLAS') is None: - return 'skip' + pytest.skip() gdal.FileFromMemBuffer('/vsimem/ogr_gmlas_8.xml', """<myns:main_elt xmlns:myns="http://myns" @@ -163,215 +152,151 @@ def ogr_gmlas_virtual_file(): </xs:schema>""") ds = gdal.OpenEx('GMLAS:/vsimem/ogr_gmlas_8.xml') - if ds is None: - gdaltest.post_reason('fail') - return 'fail' + assert ds is not None gdal.Unlink('/vsimem/ogr_gmlas_8.xml') gdal.Unlink('/vsimem/ogr_gmlas_8.xsd') - return 'success' - ############################################################################### # Test opening with XSD option -def ogr_gmlas_datafile_with_xsd_option(): +def test_ogr_gmlas_datafile_with_xsd_option(): if ogr.GetDriverByName('GMLAS') is None: - return 'skip' + pytest.skip() ds = gdal.OpenEx('GMLAS:data/gmlas/gmlas_test1.xml', open_options=['XSD=data/gmlas/gmlas_test1.xsd']) - if ds is None: - gdaltest.post_reason('fail') - return 'fail' - - return 'success' + assert ds is not None ############################################################################### # Test opening with just XSD option -def ogr_gmlas_no_datafile_with_xsd_option(): +def test_ogr_gmlas_no_datafile_with_xsd_option(): if ogr.GetDriverByName('GMLAS') is None: - return 'skip' + pytest.skip() ds = gdal.OpenEx('GMLAS:', open_options=['XSD=data/gmlas/gmlas_test1.xsd']) - if ds is None: - gdaltest.post_reason('fail') - return 'fail' - - return 'success' + assert ds is not None ############################################################################### # Test opening with just XSD option but pointing to a non-xsd filename -def ogr_gmlas_no_datafile_xsd_which_is_not_xsd(): +def test_ogr_gmlas_no_datafile_xsd_which_is_not_xsd(): if ogr.GetDriverByName('GMLAS') is None: - return 'skip' + pytest.skip() with gdaltest.error_handler(): ds = gdal.OpenEx('GMLAS:', open_options=['XSD=data/gmlas/gmlas_test1.xml']) - if ds is not None: - gdaltest.post_reason('fail') - return 'fail' - if gdal.GetLastErrorMsg().find("invalid content in 'schema' element") < 0: - gdaltest.post_reason('fail') - print(gdal.GetLastErrorMsg()) - return 'fail' - - return 'success' + assert ds is None + assert gdal.GetLastErrorMsg().find("invalid content in 'schema' element") >= 0 ############################################################################### # Test opening with nothing -def ogr_gmlas_no_datafile_no_xsd(): +def test_ogr_gmlas_no_datafile_no_xsd(): if ogr.GetDriverByName('GMLAS') is None: - return 'skip' + pytest.skip() with gdaltest.error_handler(): ds = gdal.OpenEx('GMLAS:') - if ds is not None: - gdaltest.post_reason('fail') - return 'fail' - if gdal.GetLastErrorMsg().find('XSD open option must be provided when no XML data file is passed') < 0: - gdaltest.post_reason('fail') - print(gdal.GetLastErrorMsg()) - return 'fail' - - return 'success' + assert ds is None + assert gdal.GetLastErrorMsg().find('XSD open option must be provided when no XML data file is passed') >= 0 ############################################################################### # Test opening an inexisting GML file -def ogr_gmlas_non_existing_gml(): +def test_ogr_gmlas_non_existing_gml(): if ogr.GetDriverByName('GMLAS') is None: - return 'skip' + pytest.skip() with gdaltest.error_handler(): ds = gdal.OpenEx('GMLAS:/vsimem/i_do_not_exist.gml') - if ds is not None: - gdaltest.post_reason('fail') - return 'fail' - if gdal.GetLastErrorMsg().find('Cannot open /vsimem/i_do_not_exist.gml') < 0: - gdaltest.post_reason('fail') - print(gdal.GetLastErrorMsg()) - return 'fail' - - return 'success' + assert ds is None + assert gdal.GetLastErrorMsg().find('Cannot open /vsimem/i_do_not_exist.gml') >= 0 ############################################################################### # Test opening with just XSD option but pointing to a non existing file -def ogr_gmlas_non_existing_xsd(): +def test_ogr_gmlas_non_existing_xsd(): if ogr.GetDriverByName('GMLAS') is None: - return 'skip' + pytest.skip() with gdaltest.error_handler(): ds = gdal.OpenEx('GMLAS:', open_options=['XSD=/vsimem/i_do_not_exist.xsd']) - if ds is not None: - gdaltest.post_reason('fail') - return 'fail' - if gdal.GetLastErrorMsg().find('Cannot resolve /vsimem/i_do_not_exist.xsd') < 0: - gdaltest.post_reason('fail') - print(gdal.GetLastErrorMsg()) - return 'fail' - - return 'success' + assert ds is None + assert gdal.GetLastErrorMsg().find('Cannot resolve /vsimem/i_do_not_exist.xsd') >= 0 ############################################################################### # Test opening a GML file without schemaLocation -def ogr_gmlas_gml_without_schema_location(): +def test_ogr_gmlas_gml_without_schema_location(): if ogr.GetDriverByName('GMLAS') is None: - return 'skip' + pytest.skip() gdal.FileFromMemBuffer('/vsimem/ogr_gmlas_gml_without_schema_location.xml', """<MYNS:main_elt xmlns:MYNS="http://myns"/>""") with gdaltest.error_handler(): ds = gdal.OpenEx('GMLAS:/vsimem/ogr_gmlas_gml_without_schema_location.xml') - if ds is not None: - gdaltest.post_reason('fail') - return 'fail' - if gdal.GetLastErrorMsg().find('No schema locations found when analyzing data file: XSD open option must be provided') < 0: - gdaltest.post_reason('fail') - print(gdal.GetLastErrorMsg()) - return 'fail' + assert ds is None + assert gdal.GetLastErrorMsg().find('No schema locations found when analyzing data file: XSD open option must be provided') >= 0 gdal.Unlink('/vsimem/ogr_gmlas_gml_without_schema_location.xml') - return 'success' - ############################################################################### # Test invalid schema -def ogr_gmlas_invalid_schema(): +def test_ogr_gmlas_invalid_schema(): if ogr.GetDriverByName('GMLAS') is None: - return 'skip' + pytest.skip() with gdaltest.error_handler(): ds = gdal.OpenEx('GMLAS:data/gmlas/gmlas_invalid_schema.xml') - if ds is not None: - gdaltest.post_reason('fail') - return 'fail' - if gdal.GetLastErrorMsg().find('invalid content') < 0: - gdaltest.post_reason('fail') - print(gdal.GetLastErrorMsg()) - return 'fail' - - return 'success' + assert ds is None + assert gdal.GetLastErrorMsg().find('invalid content') >= 0 ############################################################################### # Test invalid XML -def ogr_gmlas_invalid_xml(): +def test_ogr_gmlas_invalid_xml(): if ogr.GetDriverByName('GMLAS') is None: - return 'skip' + pytest.skip() ds = gdal.OpenEx('GMLAS:data/gmlas/gmlas_invalid_xml.xml') lyr = ds.GetLayer(0) with gdaltest.error_handler(): f = lyr.GetNextFeature() - if f is not None: - gdaltest.post_reason('fail') - return 'fail' - if gdal.GetLastErrorMsg().find('input ended before all started tags were ended') < 0: - gdaltest.post_reason('fail') - print(gdal.GetLastErrorMsg()) - return 'fail' - - return 'success' + assert f is None + assert gdal.GetLastErrorMsg().find('input ended before all started tags were ended') >= 0 ############################################################################### # Test links with gml:ReferenceType -def ogr_gmlas_gml_Reference(): +def test_ogr_gmlas_gml_Reference(): if ogr.GetDriverByName('GMLAS') is None: - return 'skip' + pytest.skip() ds = ogr.Open('GMLAS:data/gmlas/gmlas_test_targetelement.xml') - if ds.GetLayerCount() != 3: - gdaltest.post_reason('fail') - print(ds.GetLayerCount()) - return 'fail' + assert ds.GetLayerCount() == 3 lyr = ds.GetLayerByName('main_elt') with gdaltest.error_handler(): @@ -383,243 +308,174 @@ def ogr_gmlas_gml_Reference(): f['reference_existing_abstract_target_elt_href'] != '#BAW' or \ f.IsFieldSet('reference_existing_abstract_target_elt_nillable_href') or \ f['reference_existing_abstract_target_elt_nillable_nil'] != 1: - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' - - return 'success' + pytest.fail() + ############################################################################### # Test that we fix ambiguities in class names -def ogr_gmlas_same_element_in_different_ns(): +def test_ogr_gmlas_same_element_in_different_ns(): if ogr.GetDriverByName('GMLAS') is None: - return 'skip' + pytest.skip() ds = gdal.OpenEx('GMLAS:data/gmlas/gmlas_same_element_in_different_ns.xml') - if ds is None: - gdaltest.post_reason('fail') - return 'fail' + assert ds is not None # for i in range(ds.GetLayerCount()): # print(ds.GetLayer(i).GetName()) - if ds.GetLayerCount() != 5: - gdaltest.post_reason('fail') - print(ds.GetLayerCount()) - return 'fail' + assert ds.GetLayerCount() == 5 lyr = ds.GetLayerByName('elt') f = lyr.GetNextFeature() if f.IsFieldSet('abstractElt_other_ns_realizationOfAbstractElt_pkid') == 0: - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' - if ds.GetLayerByName('myns_realizationOfAbstractElt') is None: - gdaltest.post_reason('fail') - return 'fail' - if ds.GetLayerByName('other_ns_realizationOfAbstractElt') is None: - gdaltest.post_reason('fail') - return 'fail' - if ds.GetLayerByName('elt_elt2_abstractElt_myns_realizationOfAbstractElt') is None: - gdaltest.post_reason('fail') - return 'fail' - if ds.GetLayerByName('elt_elt2_abstractElt_other_ns_realizationOfAbstractElt') is None: - gdaltest.post_reason('fail') - return 'fail' - - return 'success' + pytest.fail() + assert ds.GetLayerByName('myns_realizationOfAbstractElt') is not None + assert ds.GetLayerByName('other_ns_realizationOfAbstractElt') is not None + assert ds.GetLayerByName('elt_elt2_abstractElt_myns_realizationOfAbstractElt') is not None + assert ds.GetLayerByName('elt_elt2_abstractElt_other_ns_realizationOfAbstractElt') is not None ############################################################################### # Test a corner case of relative path resolution -def ogr_gmlas_corner_case_relative_path(): +def test_ogr_gmlas_corner_case_relative_path(): if ogr.GetDriverByName('GMLAS') is None: - return 'skip' + pytest.skip() ds = ogr.Open('GMLAS:../ogr/data/gmlas/gmlas_test1.xml') - if ds is None: - gdaltest.post_reason('fail') - return 'fail' - - return 'success' + assert ds is not None ############################################################################### # Test unexpected repeated element -def ogr_gmlas_unexpected_repeated_element(): +def test_ogr_gmlas_unexpected_repeated_element(): if ogr.GetDriverByName('GMLAS') is None: - return 'skip' + pytest.skip() ds = gdal.OpenEx('GMLAS:data/gmlas/gmlas_unexpected_repeated_element.xml') lyr = ds.GetLayer(0) with gdaltest.error_handler(): f = lyr.GetNextFeature() if f is None or f['foo'] != 'foo_again': # somewhat arbitrary to keep the latest one! - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' - if gdal.GetLastErrorMsg().find('Unexpected element myns:main_elt/myns:foo') < 0: - gdaltest.post_reason('fail') - print(gdal.GetLastErrorMsg()) - return 'fail' + pytest.fail() + assert gdal.GetLastErrorMsg().find('Unexpected element myns:main_elt/myns:foo') >= 0 f = lyr.GetNextFeature() - if f is not None: - gdaltest.post_reason('fail') - return 'fail' + assert f is None ds = None - return 'success' - ############################################################################### # Test unexpected repeated element -def ogr_gmlas_unexpected_repeated_element_variant(): +def test_ogr_gmlas_unexpected_repeated_element_variant(): if ogr.GetDriverByName('GMLAS') is None: - return 'skip' + pytest.skip() ds = gdal.OpenEx('GMLAS:data/gmlas/gmlas_unexpected_repeated_element_variant.xml') lyr = ds.GetLayer(0) with gdaltest.error_handler(): f = lyr.GetNextFeature() if f is None or f['foo'] != 'foo_again': # somewhat arbitrary to keep the latest one! - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' - if gdal.GetLastErrorMsg().find('Unexpected element myns:main_elt/myns:foo') < 0: - gdaltest.post_reason('fail') - print(gdal.GetLastErrorMsg()) - return 'fail' + pytest.fail() + assert gdal.GetLastErrorMsg().find('Unexpected element myns:main_elt/myns:foo') >= 0 f = lyr.GetNextFeature() - if f is not None: - gdaltest.post_reason('fail') - return 'fail' + assert f is None ds = None - return 'success' - ############################################################################### # Test reading geometries embedded in a geometry property element -def ogr_gmlas_geometryproperty(): +def test_ogr_gmlas_geometryproperty(): if ogr.GetDriverByName('GMLAS') is None: - return 'skip' + pytest.skip() ds = gdal.OpenEx('GMLAS:data/gmlas/gmlas_geometryproperty_gml32.gml', open_options=[ 'CONFIG_FILE=<Configuration><LayerBuildingRules><GML><IncludeGeometryXML>true</IncludeGeometryXML></GML></LayerBuildingRules></Configuration>']) lyr = ds.GetLayer(0) with gdaltest.error_handler(): geom_field_count = lyr.GetLayerDefn().GetGeomFieldCount() - if geom_field_count != 15: - gdaltest.post_reason('fail') - print(geom_field_count) - return 'fail' + assert geom_field_count == 15 f = lyr.GetNextFeature() if f['geometryProperty_xml'] != ' <gml:Point gml:id="poly.geom.Geometry" srsName="urn:ogc:def:crs:EPSG::4326"> <gml:pos>49 2</gml:pos> </gml:Point> ': - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' + pytest.fail() if not f.IsFieldNull('geometryPropertyEmpty_xml'): - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' + pytest.fail() if f['pointProperty_xml'] != '<gml:Point gml:id="poly.geom.Point"><gml:pos srsName="http://www.opengis.net/def/crs/EPSG/0/4326">50 3</gml:pos></gml:Point>': - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' + pytest.fail() if f['pointPropertyRepeated_xml'] != [ '<gml:Point gml:id="poly.geom.pointPropertyRepeated.1"><gml:pos>0 1</gml:pos></gml:Point>', '<gml:Point gml:id="poly.geom.pointPropertyRepeated.2"><gml:pos>1 2</gml:pos></gml:Point>', '<gml:Point gml:id="poly.geom.pointPropertyRepeated.3"><gml:pos>3 4</gml:pos></gml:Point>']: - gdaltest.post_reason('fail') - print(f['pointPropertyRepeated_xml']) f.DumpReadable() - return 'fail' + pytest.fail(f['pointPropertyRepeated_xml']) geom_idx = lyr.GetLayerDefn().GetGeomFieldIndex('geometryProperty') sr = lyr.GetLayerDefn().GetGeomFieldDefn(geom_idx).GetSpatialRef() - if sr is None or sr.ExportToWkt().find('4326') < 0 or sr.ExportToWkt().find('AXIS') >= 0: - gdaltest.post_reason('fail') - print(sr) - return 'fail' + assert not (sr is None or sr.ExportToWkt().find('4326') < 0 or sr.ExportToWkt().find('AXIS') >= 0) wkt = f.GetGeomFieldRef(geom_idx).ExportToWkt() # Axis swapping if wkt != 'POINT (2 49)': - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' + pytest.fail() geom_idx = lyr.GetLayerDefn().GetGeomFieldIndex('geometryPropertyEmpty') if f.GetGeomFieldRef(geom_idx) is not None: - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' + pytest.fail() geom_idx = lyr.GetLayerDefn().GetGeomFieldIndex('pointProperty') sr = lyr.GetLayerDefn().GetGeomFieldDefn(geom_idx).GetSpatialRef() - if sr is None or sr.ExportToWkt().find('4326') < 0 or sr.ExportToWkt().find('AXIS') >= 0: - gdaltest.post_reason('fail') - print(sr) - return 'fail' + assert not (sr is None or sr.ExportToWkt().find('4326') < 0 or sr.ExportToWkt().find('AXIS') >= 0) wkt = f.GetGeomFieldRef(geom_idx).ExportToWkt() if wkt != 'POINT (3 50)': - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' + pytest.fail() geom_idx = lyr.GetLayerDefn().GetGeomFieldIndex('lineStringProperty') sr = lyr.GetLayerDefn().GetGeomFieldDefn(geom_idx).GetSpatialRef() - if sr is None or sr.ExportToWkt().find('4326') < 0 or sr.ExportToWkt().find('AXIS') >= 0: - gdaltest.post_reason('fail') - print(sr) - return 'fail' - if lyr.GetLayerDefn().GetGeomFieldDefn(geom_idx).GetType() != ogr.wkbLineString: - gdaltest.post_reason('fail') - print(lyr.GetLayerDefn().GetGeomFieldDefn(geom_idx).GetType()) - return 'fail' + assert not (sr is None or sr.ExportToWkt().find('4326') < 0 or sr.ExportToWkt().find('AXIS') >= 0) + assert lyr.GetLayerDefn().GetGeomFieldDefn(geom_idx).GetType() == ogr.wkbLineString wkt = f.GetGeomFieldRef(geom_idx).ExportToWkt() if wkt != 'LINESTRING (2 49)': - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' + pytest.fail() geom_idx = lyr.GetLayerDefn().GetGeomFieldIndex('pointPropertyRepeated') - if lyr.GetLayerDefn().GetGeomFieldDefn(geom_idx).GetType() != ogr.wkbUnknown: - gdaltest.post_reason('fail') - print(lyr.GetLayerDefn().GetGeomFieldDefn(geom_idx).GetType()) - return 'fail' + assert lyr.GetLayerDefn().GetGeomFieldDefn(geom_idx).GetType() == ogr.wkbUnknown wkt = f.GetGeomFieldRef(geom_idx).ExportToWkt() if wkt != 'GEOMETRYCOLLECTION (POINT (0 1),POINT (1 2),POINT (3 4))': - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' + pytest.fail() geom_idx = lyr.GetLayerDefn().GetGeomFieldIndex('mycustompointproperty_point') wkt = f.GetGeomFieldRef(geom_idx).ExportToWkt() if wkt != 'POINT (5 6)': - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' + pytest.fail() # Test that on-the-fly reprojection works f = lyr.GetNextFeature() geom_idx = lyr.GetLayerDefn().GetGeomFieldIndex('geometryProperty') geom = f.GetGeomFieldRef(geom_idx) if ogrtest.check_feature_geometry(geom, 'POINT (3.0 0.0)') != 0: - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' + pytest.fail() # Failed reprojection with gdaltest.error_handler(): f = lyr.GetNextFeature() geom_idx = lyr.GetLayerDefn().GetGeomFieldIndex('geometryProperty') if f.GetGeomFieldRef(geom_idx) is not None: - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' + pytest.fail() # Test SWAP_COORDINATES=NO ds = gdal.OpenEx('GMLAS:data/gmlas/gmlas_geometryproperty_gml32.gml', @@ -631,16 +487,14 @@ def ogr_gmlas_geometryproperty(): wkt = f.GetGeomFieldRef(geom_idx).ExportToWkt() # Axis swapping if wkt != 'POINT (49 2)': - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' + pytest.fail() geom_idx = lyr.GetLayerDefn().GetGeomFieldIndex('lineStringProperty') wkt = f.GetGeomFieldRef(geom_idx).ExportToWkt() # Axis swapping if wkt != 'LINESTRING (2 49)': - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' + pytest.fail() # Test SWAP_COORDINATES=YES ds = gdal.OpenEx('GMLAS:data/gmlas/gmlas_geometryproperty_gml32.gml', @@ -652,60 +506,48 @@ def ogr_gmlas_geometryproperty(): wkt = f.GetGeomFieldRef(geom_idx).ExportToWkt() # Axis swapping if wkt != 'POINT (2 49)': - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' + pytest.fail() geom_idx = lyr.GetLayerDefn().GetGeomFieldIndex('lineStringProperty') wkt = f.GetGeomFieldRef(geom_idx).ExportToWkt() # Axis swapping if wkt != 'LINESTRING (49 2)': - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' - - return 'success' + pytest.fail() + ############################################################################### # Test reading geometries referenced by a AbstractGeometry element -def ogr_gmlas_abstractgeometry(): +def test_ogr_gmlas_abstractgeometry(): if ogr.GetDriverByName('GMLAS') is None: - return 'skip' + pytest.skip() ds = gdal.OpenEx('GMLAS:data/gmlas/gmlas_abstractgeometry_gml32.gml', open_options=[ 'CONFIG_FILE=<Configuration><LayerBuildingRules><GML><IncludeGeometryXML>true</IncludeGeometryXML></GML></LayerBuildingRules></Configuration>']) lyr = ds.GetLayer(0) - if lyr.GetLayerDefn().GetGeomFieldCount() != 2: - gdaltest.post_reason('fail') - print(lyr.GetLayerDefn().GetGeomFieldCount()) - return 'fail' + assert lyr.GetLayerDefn().GetGeomFieldCount() == 2 f = lyr.GetNextFeature() if f['AbstractGeometry_xml'] != '<gml:Point gml:id="test.geom.0"><gml:pos>0 1</gml:pos></gml:Point>': - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' + pytest.fail() if f['repeated_AbstractGeometry_xml'] != [ '<gml:Point gml:id="test.geom.repeated.1"><gml:pos>0 1</gml:pos>', '<gml:Point gml:id="test.geom.repeated.2"><gml:pos>1 2</gml:pos>']: - gdaltest.post_reason('fail') - print(f['repeated_AbstractGeometry_xml']) f.DumpReadable() - return 'fail' + pytest.fail(f['repeated_AbstractGeometry_xml']) wkt = f.GetGeomFieldRef(0).ExportToWkt() if wkt != 'POINT (0 1)': - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' + pytest.fail() wkt = f.GetGeomFieldRef(1).ExportToWkt() if wkt != 'GEOMETRYCOLLECTION (POINT (0 1),POINT (1 2))': - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' - - return 'success' + pytest.fail() + ############################################################################### # Test validation against schema @@ -719,16 +561,14 @@ def error_handler(self, err_type, err_no, err_msg): self.error_list.append((err_type, err_no, err_msg)) -def ogr_gmlas_validate(): +def test_ogr_gmlas_validate(): if ogr.GetDriverByName('GMLAS') is None: - return 'skip' + pytest.skip() # By default check we are silent about validation error ds = gdal.OpenEx('GMLAS:data/gmlas/gmlas_validate.xml') - if ds is None: - gdaltest.post_reason('fail') - return 'fail' + assert ds is not None myhandler = MyHandler() gdal.PushErrorHandler(myhandler.error_handler) gdal.SetConfigOption('GMLAS_WARN_UNEXPECTED', None) @@ -736,39 +576,25 @@ def ogr_gmlas_validate(): lyr.GetFeatureCount() gdal.SetConfigOption('GMLAS_WARN_UNEXPECTED', 'YES') gdal.PopErrorHandler() - if myhandler.error_list: - gdaltest.post_reason('fail') - print(myhandler.error_list) - return 'fail' + assert not myhandler.error_list ds = gdal.OpenEx('GMLAS:data/gmlas/gmlas_validate.xml') - if ds is None: - gdaltest.post_reason('fail') - return 'fail' + assert ds is not None myhandler = MyHandler() gdal.PushErrorHandler(myhandler.error_handler) lyr = ds.GetLayer(0) lyr.GetFeatureCount() gdal.PopErrorHandler() # Unexpected element with xpath=myns:main_elt/myns:bar (subxpath=myns:main_elt/myns:bar) found - if len(myhandler.error_list) < 2: - gdaltest.post_reason('fail') - print(myhandler.error_list) - return 'fail' + assert len(myhandler.error_list) >= 2 # Enable validation on a doc without validation errors myhandler = MyHandler() gdal.PushErrorHandler(myhandler.error_handler) ds = gdal.OpenEx('GMLAS:data/gmlas/gmlas_test1.xml', open_options=['VALIDATE=YES']) gdal.PopErrorHandler() - if ds is None: - gdaltest.post_reason('fail') - print(myhandler.error_list) - return 'fail' - if myhandler.error_list: - gdaltest.post_reason('fail') - print(myhandler.error_list) - return 'fail' + assert ds is not None, myhandler.error_list + assert not myhandler.error_list # Enable validation on a doc without validation error, and with explicit XSD gdal.FileFromMemBuffer('/vsimem/gmlas_test1.xml', @@ -779,67 +605,41 @@ def ogr_gmlas_validate(): 'XSD=' + os.getcwd() + '/data/gmlas/gmlas_test1.xsd', 'VALIDATE=YES']) gdal.PopErrorHandler() gdal.Unlink('/vsimem/gmlas_test1.xml') - if ds is None: - gdaltest.post_reason('fail') - print(myhandler.error_list) - return 'fail' - if myhandler.error_list: - gdaltest.post_reason('fail') - print(myhandler.error_list) - return 'fail' + assert ds is not None, myhandler.error_list + assert not myhandler.error_list # Validation errors, but do not prevent dataset opening myhandler = MyHandler() gdal.PushErrorHandler(myhandler.error_handler) ds = gdal.OpenEx('GMLAS:data/gmlas/gmlas_validate.xml', open_options=['VALIDATE=YES']) gdal.PopErrorHandler() - if ds is None: - gdaltest.post_reason('fail') - return 'fail' - if len(myhandler.error_list) != 5: - gdaltest.post_reason('fail') - print(myhandler.error_list) - print(len(myhandler.error_list)) - return 'fail' + assert ds is not None + assert len(myhandler.error_list) == 5 # Validation errors and do prevent dataset opening myhandler = MyHandler() gdal.PushErrorHandler(myhandler.error_handler) ds = gdal.OpenEx('GMLAS:data/gmlas/gmlas_validate.xml', open_options=['VALIDATE=YES', 'FAIL_IF_VALIDATION_ERROR=YES']) gdal.PopErrorHandler() - if ds is not None: - gdaltest.post_reason('fail') - return 'fail' - if len(myhandler.error_list) != 6: - gdaltest.post_reason('fail') - print(myhandler.error_list) - print(len(myhandler.error_list)) - return 'fail' + assert ds is None + assert len(myhandler.error_list) == 6 # Test that validation without doc doesn't crash myhandler = MyHandler() gdal.PushErrorHandler(myhandler.error_handler) ds = gdal.OpenEx('GMLAS:', open_options=['XSD=data/gmlas/gmlas_test1.xsd', 'VALIDATE=YES']) gdal.PopErrorHandler() - if ds is None: - gdaltest.post_reason('fail') - print(myhandler.error_list) - return 'fail' - if myhandler.error_list: - gdaltest.post_reason('fail') - print(myhandler.error_list) - return 'fail' - - return 'success' + assert ds is not None, myhandler.error_list + assert not myhandler.error_list ############################################################################### # Test correct namespace prefix handling -def ogr_gmlas_test_ns_prefix(): +def test_ogr_gmlas_test_ns_prefix(): if ogr.GetDriverByName('GMLAS') is None: - return 'skip' + pytest.skip() # The schema doesn't directly import xlink, but indirectly references it ds = gdal.OpenEx('GMLAS:', open_options=['XSD=data/gmlas/gmlas_test_targetelement.xsd']) @@ -847,55 +647,47 @@ def ogr_gmlas_test_ns_prefix(): lyr = ds.GetLayerByName('_ogr_fields_metadata') f = lyr.GetNextFeature() if f['field_xpath'] != 'myns:main_elt/myns:reference_missing_target_elt/@xlink:href': - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' - - return 'success' + pytest.fail() + ############################################################################### # Test parsing documents without namespace -def ogr_gmlas_no_namespace(): +def test_ogr_gmlas_no_namespace(): if ogr.GetDriverByName('GMLAS') is None: - return 'skip' + pytest.skip() ds = ogr.Open('GMLAS:data/gmlas/gmlas_no_namespace.xml') lyr = ds.GetLayer(0) f = lyr.GetNextFeature() if f['foo'] != 'bar': - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' - - return 'success' + pytest.fail() + ############################################################################### # Test CONFIG_FILE -def ogr_gmlas_conf(): +def test_ogr_gmlas_conf(): if ogr.GetDriverByName('GMLAS') is None: - return 'skip' + pytest.skip() # Non existing file with gdaltest.error_handler(): ds = gdal.OpenEx('GMLAS:data/gmlas/gmlas_test1.xml', open_options=['CONFIG_FILE=not_existing']) - if ds is not None: - gdaltest.post_reason('fail') - return 'fail' + assert ds is None # Broken conf file gdal.FileFromMemBuffer('/vsimem/my_conf.xml', "<broken>") with gdaltest.error_handler(): ds = gdal.OpenEx('GMLAS:data/gmlas/gmlas_test1.xml', open_options=['CONFIG_FILE=/vsimem/my_conf.xml']) gdal.Unlink('/vsimem/my_conf.xml') - if ds is not None: - gdaltest.post_reason('fail') - return 'fail' + assert ds is None # Valid XML, but not validating gdal.FileFromMemBuffer('/vsimem/my_conf.xml', "<not_validating/>") @@ -906,88 +698,61 @@ def ogr_gmlas_conf(): # Inlined conf file + UseArrays = false ds = gdal.OpenEx('GMLAS:data/gmlas/gmlas_test1.xml', open_options=[ 'CONFIG_FILE=<Configuration><LayerBuildingRules><UseArrays>false</UseArrays></LayerBuildingRules></Configuration>']) - if ds is None: - gdaltest.post_reason('fail') - return 'fail' + assert ds is not None lyr = ds.GetLayerByName('main_elt_string_array') - if lyr.GetFeatureCount() != 2: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.GetFeatureCount() == 2 # AlwaysGenerateOGRId = true ds = gdal.OpenEx('GMLAS:data/gmlas/gmlas_test1.xml', open_options=[ 'CONFIG_FILE=<Configuration><LayerBuildingRules><AlwaysGenerateOGRId>true</AlwaysGenerateOGRId></LayerBuildingRules></Configuration>']) - if ds is None: - gdaltest.post_reason('fail') - return 'fail' + assert ds is not None lyr = ds.GetLayerByName('main_elt') f = lyr.GetNextFeature() if f['ogr_pkid'].find('main_elt_1') < 0 or \ f['otherns_id'] != 'otherns_id': - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' + pytest.fail() # IncludeGeometryXML = false ds = gdal.OpenEx('GMLAS:data/gmlas/gmlas_geometryproperty_gml32.gml', open_options=[ 'CONFIG_FILE=<Configuration><LayerBuildingRules><GML><IncludeGeometryXML>false</IncludeGeometryXML></GML></LayerBuildingRules></Configuration>']) - if ds is None: - gdaltest.post_reason('fail') - return 'fail' + assert ds is not None lyr = ds.GetLayer(0) with gdaltest.error_handler(): - if lyr.GetLayerDefn().GetFieldIndex('geometryProperty_xml') >= 0: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.GetLayerDefn().GetFieldIndex('geometryProperty_xml') < 0 f = lyr.GetNextFeature() geom_idx = lyr.GetLayerDefn().GetGeomFieldIndex('geometryProperty') wkt = f.GetGeomFieldRef(geom_idx).ExportToWkt() if wkt != 'POINT (2 49)': - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' + pytest.fail() # ExposeMetadataLayers = true ds = gdal.OpenEx('GMLAS:data/gmlas/gmlas_abstractgeometry_gml32.gml', open_options=[ 'CONFIG_FILE=<Configuration><ExposeMetadataLayers>true</ExposeMetadataLayers></Configuration>']) - if ds is None: - gdaltest.post_reason('fail') - return 'fail' - if ds.GetLayerCount() != 5: - gdaltest.post_reason('fail') - print(ds.GetLayerCount()) - return 'fail' + assert ds is not None + assert ds.GetLayerCount() == 5 # Test override with open option ds = gdal.OpenEx('GMLAS:data/gmlas/gmlas_abstractgeometry_gml32.gml', open_options=[ 'EXPOSE_METADATA_LAYERS=NO', 'CONFIG_FILE=<Configuration><ExposeMetadataLayers>true</ExposeMetadataLayers></Configuration>']) - if ds is None: - gdaltest.post_reason('fail') - return 'fail' - if ds.GetLayerCount() != 1: - gdaltest.post_reason('fail') - print(ds.GetLayerCount()) - return 'fail' + assert ds is not None + assert ds.GetLayerCount() == 1 # Turn on validation and error on validation with gdaltest.error_handler(): ds = gdal.OpenEx('GMLAS:data/gmlas/gmlas_validate.xml', open_options=[ 'CONFIG_FILE=<Configuration><Validation enabled="true"><FailIfError>true</FailIfError></Validation></Configuration>']) - if ds is not None or gdal.GetLastErrorMsg().find('Validation') < 0: - gdaltest.post_reason('fail') - print(gdal.GetLastErrorMsg()) - return 'fail' - - return 'success' + assert ds is None and gdal.GetLastErrorMsg().find('Validation') >= 0 ############################################################################### # Test IgnoredXPaths aspect of config file -def ogr_gmlas_conf_ignored_xpath(): +def test_ogr_gmlas_conf_ignored_xpath(): if ogr.GetDriverByName('GMLAS') is None: - return 'skip' + pytest.skip() # Test unsupported and invalid XPaths for xpath in ['', @@ -1010,11 +775,7 @@ def ogr_gmlas_conf_ignored_xpath(): <XPath>%s</XPath> </IgnoredXPaths> </Configuration>""" % xpath]) - if gdal.GetLastErrorMsg().find('XPath syntax') < 0: - gdaltest.post_reason('fail') - print(xpath) - print(gdal.GetLastErrorMsg()) - return 'fail' + assert gdal.GetLastErrorMsg().find('XPath syntax') >= 0, xpath # Test duplicating mapping with gdaltest.error_handler(): @@ -1028,10 +789,7 @@ def ogr_gmlas_conf_ignored_xpath(): </Namespaces> </IgnoredXPaths> </Configuration>"""]) - if gdal.GetLastErrorMsg().find('Prefix ns was already mapped') < 0: - gdaltest.post_reason('fail') - print(gdal.GetLastErrorMsg()) - return 'fail' + assert gdal.GetLastErrorMsg().find('Prefix ns was already mapped') >= 0 # Test XPath with implicit namespace, and warning ds = gdal.OpenEx('GMLAS:data/gmlas/gmlas_test1.xml', open_options=[ @@ -1041,19 +799,12 @@ def ogr_gmlas_conf_ignored_xpath(): <XPath>@otherns:id</XPath> </IgnoredXPaths> </Configuration>"""]) - if ds is None: - gdaltest.post_reason('fail') - return 'fail' + assert ds is not None lyr = ds.GetLayerByName('main_elt') - if lyr.GetLayerDefn().GetFieldIndex('otherns_id') >= 0: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.GetLayerDefn().GetFieldIndex('otherns_id') < 0 with gdaltest.error_handler(): lyr.GetNextFeature() - if gdal.GetLastErrorMsg().find('Attribute with xpath=myns:main_elt/@otherns:id found in document but ignored') < 0: - gdaltest.post_reason('fail') - print(gdal.GetLastErrorMsg()) - return 'fail' + assert gdal.GetLastErrorMsg().find('Attribute with xpath=myns:main_elt/@otherns:id found in document but ignored') >= 0 # Test XPath with explicit namespace, and warning suppression ds = gdal.OpenEx('GMLAS:data/gmlas/gmlas_test1.xml', open_options=[ @@ -1065,15 +816,10 @@ def ogr_gmlas_conf_ignored_xpath(): <XPath warnIfIgnoredXPathFoundInDocInstance="false">@other_ns:id</XPath> </IgnoredXPaths> </Configuration>"""]) - if ds is None: - gdaltest.post_reason('fail') - return 'fail' + assert ds is not None lyr = ds.GetLayerByName('main_elt') lyr.GetNextFeature() - if gdal.GetLastErrorMsg() != '': - gdaltest.post_reason('fail') - print(gdal.GetLastErrorMsg()) - return 'fail' + assert gdal.GetLastErrorMsg() == '' # Test various XPath syntaxes ds = gdal.OpenEx('GMLAS:', open_options=[ @@ -1093,37 +839,19 @@ def ogr_gmlas_conf_ignored_xpath(): <XPath>foo/myns:long</XPath> <!-- no match --> </IgnoredXPaths> </Configuration>"""]) - if ds is None: - gdaltest.post_reason('fail') - return 'fail' + assert ds is not None lyr = ds.GetLayerByName('main_elt') # Ignored fields - if lyr.GetLayerDefn().GetFieldIndex('optionalStrAttr') >= 0: - gdaltest.post_reason('fail') - return 'fail' - if lyr.GetLayerDefn().GetFieldIndex('fixedValUnset') >= 0: - gdaltest.post_reason('fail') - return 'fail' - if lyr.GetLayerDefn().GetFieldIndex('base_int') >= 0: - gdaltest.post_reason('fail') - return 'fail' - if lyr.GetLayerDefn().GetFieldIndex('string') >= 0: - gdaltest.post_reason('fail') - return 'fail' - if lyr.GetLayerDefn().GetFieldIndex('string_array') >= 0: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.GetLayerDefn().GetFieldIndex('optionalStrAttr') < 0 + assert lyr.GetLayerDefn().GetFieldIndex('fixedValUnset') < 0 + assert lyr.GetLayerDefn().GetFieldIndex('base_int') < 0 + assert lyr.GetLayerDefn().GetFieldIndex('string') < 0 + assert lyr.GetLayerDefn().GetFieldIndex('string_array') < 0 # Present fields - if lyr.GetLayerDefn().GetFieldIndex('int_array') < 0: - gdaltest.post_reason('fail') - return 'fail' - if lyr.GetLayerDefn().GetFieldIndex('long') < 0: - gdaltest.post_reason('fail') - return 'fail' - - return 'success' + assert lyr.GetLayerDefn().GetFieldIndex('int_array') >= 0 + assert lyr.GetLayerDefn().GetFieldIndex('long') >= 0 ############################################################################### @@ -1171,19 +899,19 @@ def do_GET(self): # Test schema caching -def ogr_gmlas_cache(): +def test_ogr_gmlas_cache(): if ogr.GetDriverByName('GMLAS') is None: - return 'skip' + pytest.skip() drv = gdal.GetDriverByName('HTTP') if drv is None: - return 'skip' + pytest.skip() (webserver_process, webserver_port) = webserver.launch(handler=GMLASHTTPHandler) if webserver_port == 0: - return 'skip' + pytest.skip() gdal.FileFromMemBuffer('/vsimem/ogr_gmlas_cache.xml', """<main_elt xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" @@ -1214,37 +942,28 @@ def ogr_gmlas_cache(): with gdaltest.error_handler(): ds = gdal.OpenEx('GMLAS:/vsimem/ogr_gmlas_cache.xml', open_options=[ 'CONFIG_FILE=<Configuration><AllowRemoteSchemaDownload>false</AllowRemoteSchemaDownload><SchemaCache><Directory>/vsimem/my/gmlas_cache</Directory></SchemaCache></Configuration>']) - if ds is not None or gdal.GetLastErrorMsg().find('Cannot resolve') < 0: - gdaltest.post_reason('fail') - print(gdal.GetLastErrorMsg()) - return 'fail' + assert ds is None and gdal.GetLastErrorMsg().find('Cannot resolve') >= 0 # Test invalid cache directory with gdaltest.error_handler(): ds = gdal.OpenEx('GMLAS:/vsimem/ogr_gmlas_cache.xml', open_options=[ 'CONFIG_FILE=<Configuration><SchemaCache><Directory>/inexisting_directory/not/exist</Directory></SchemaCache></Configuration>']) if ds is None: - gdaltest.post_reason('fail') webserver.server_stop(webserver_process, webserver_port) - return 'fail' + pytest.fail() if ds.GetLayerCount() != 1: - gdaltest.post_reason('fail') - print(ds.GetLayerCount()) webserver.server_stop(webserver_process, webserver_port) - return 'fail' + pytest.fail(ds.GetLayerCount()) # Will create the directory and download and cache ds = gdal.OpenEx('GMLAS:/vsimem/ogr_gmlas_cache.xml', open_options=[ 'CONFIG_FILE=<Configuration><SchemaCache><Directory>/vsimem/my/gmlas_cache</Directory></SchemaCache></Configuration>']) if ds is None: - gdaltest.post_reason('fail') webserver.server_stop(webserver_process, webserver_port) - return 'fail' + pytest.fail() if ds.GetLayerCount() != 1: - gdaltest.post_reason('fail') - print(ds.GetLayerCount()) webserver.server_stop(webserver_process, webserver_port) - return 'fail' + pytest.fail(ds.GetLayerCount()) gdal.Unlink('/vsimem/my/gmlas_cache/' + gdal.ReadDir('/vsimem/my/gmlas_cache')[0]) @@ -1252,38 +971,30 @@ def ogr_gmlas_cache(): ds = gdal.OpenEx('GMLAS:/vsimem/ogr_gmlas_cache.xml', open_options=[ 'CONFIG_FILE=<Configuration><SchemaCache><Directory>/vsimem/my/gmlas_cache</Directory></SchemaCache></Configuration>']) if ds is None: - gdaltest.post_reason('fail') webserver.server_stop(webserver_process, webserver_port) - return 'fail' + pytest.fail() if ds.GetLayerCount() != 1: - gdaltest.post_reason('fail') webserver.server_stop(webserver_process, webserver_port) - return 'fail' + pytest.fail() # With XSD open option ds = gdal.OpenEx('GMLAS:/vsimem/ogr_gmlas_cache.xml', open_options=[ 'XSD=http://localhost:%d/vsimem/ogr_gmlas_cache.xsd' % webserver_port, 'CONFIG_FILE=<Configuration><SchemaCache><Directory>/vsimem/my/gmlas_cache</Directory></SchemaCache></Configuration>']) if ds is None: - gdaltest.post_reason('fail') webserver.server_stop(webserver_process, webserver_port) - return 'fail' + pytest.fail() if ds.GetLayerCount() != 1: - gdaltest.post_reason('fail') webserver.server_stop(webserver_process, webserver_port) - return 'fail' + pytest.fail() webserver.server_stop(webserver_process, webserver_port) # Now re-open with the webserver turned off ds = gdal.OpenEx('GMLAS:/vsimem/ogr_gmlas_cache.xml', open_options=[ 'CONFIG_FILE=<Configuration><SchemaCache><Directory>/vsimem/my/gmlas_cache</Directory></SchemaCache></Configuration>']) - if ds is None: - gdaltest.post_reason('fail') - return 'fail' - if ds.GetLayerCount() != 1: - gdaltest.post_reason('fail') - return 'fail' + assert ds is not None + assert ds.GetLayerCount() == 1 # Re try but ask for refresh with gdaltest.error_handler(): @@ -1291,10 +1002,8 @@ def ogr_gmlas_cache(): 'REFRESH_CACHE=YES', 'CONFIG_FILE=<Configuration><SchemaCache><Directory>/vsimem/my/gmlas_cache</Directory></SchemaCache></Configuration>']) if ds is not None or gdal.GetLastErrorMsg().find('Cannot resolve') < 0: - gdaltest.post_reason('fail') - print(gdal.GetLastErrorMsg()) webserver.server_stop(webserver_process, webserver_port) - return 'fail' + pytest.fail(gdal.GetLastErrorMsg()) # Re try with non existing cached schema gdal.Unlink('/vsimem/my/gmlas_cache/' + gdal.ReadDir('/vsimem/my/gmlas_cache')[0]) @@ -1302,10 +1011,7 @@ def ogr_gmlas_cache(): with gdaltest.error_handler(): ds = gdal.OpenEx('GMLAS:/vsimem/ogr_gmlas_cache.xml', open_options=[ 'CONFIG_FILE=<Configuration><SchemaCache><Directory>/vsimem/my/gmlas_cache</Directory></SchemaCache></Configuration>']) - if ds is not None or gdal.GetLastErrorMsg().find('Cannot resolve') < 0: - gdaltest.post_reason('fail') - print(gdal.GetLastErrorMsg()) - return 'fail' + assert ds is None and gdal.GetLastErrorMsg().find('Cannot resolve') >= 0 # Cleanup gdal.Unlink('/vsimem/ogr_gmlas_cache.xml') @@ -1318,91 +1024,78 @@ def ogr_gmlas_cache(): gdal.Rmdir('/vsimem/my/gmlas_cache') gdal.Rmdir('/vsimem/my') - return 'success' - ############################################################################### # Test good working of linking to a child through its id attribute -def ogr_gmlas_link_nested_independant_child(): +def test_ogr_gmlas_link_nested_independant_child(): if ogr.GetDriverByName('GMLAS') is None: - return 'skip' + pytest.skip() ds = ogr.Open('GMLAS:data/gmlas/gmlas_link_nested_independant_child.xml') lyr = ds.GetLayer(0) f = lyr.GetNextFeature() if f['second_my_id'] != 'second_id': - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' - - return 'success' + pytest.fail() + ############################################################################### # Test some pattern found in geosciml schemas -def ogr_gmlas_composition_compositionPart(): +def test_ogr_gmlas_composition_compositionPart(): if ogr.GetDriverByName('GMLAS') is None: - return 'skip' + pytest.skip() ds = ogr.Open('GMLAS:data/gmlas/gmlas_composition_compositionPart.xml') lyr = ds.GetLayerByName('first_composition') f = lyr.GetNextFeature() if f.IsFieldSet('parent_ogr_pkid') == 0 or f.IsFieldSet('CompositionPart_pkid') == 0: - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' + pytest.fail() f = lyr.GetNextFeature() if f.IsFieldSet('parent_ogr_pkid') == 0 or f.IsFieldSet('CompositionPart_pkid') == 0: - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' + pytest.fail() lyr = ds.GetLayerByName('CompositionPart') f = lyr.GetNextFeature() if f.IsFieldSet('my_id') == 0 or f.IsFieldSet('a') == 0: - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' + pytest.fail() f = lyr.GetNextFeature() if f.IsFieldSet('my_id') == 0 or f.IsFieldSet('a') == 0: - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' - - return 'success' + pytest.fail() + ############################################################################### # Test that when importing GML we expose by default only elements deriving # from _Feature/AbstractFeature -def ogr_gmlas_instantiate_only_gml_feature(): +def test_ogr_gmlas_instantiate_only_gml_feature(): if ogr.GetDriverByName('GMLAS') is None: - return 'skip' + pytest.skip() ds = gdal.OpenEx('GMLAS:', open_options=['XSD=data/gmlas/gmlas_instantiate_only_gml_feature.xsd']) - if ds.GetLayerCount() != 1: - gdaltest.post_reason('fail') - return 'fail' + assert ds.GetLayerCount() == 1 ds = None - return 'success' - ############################################################################### # Test that WFS style timeStamp are ignored for hash generation -def ogr_gmlas_timestamp_ignored_for_hash(): +def test_ogr_gmlas_timestamp_ignored_for_hash(): if ogr.GetDriverByName('GMLAS') is None: - return 'skip' + pytest.skip() ds = ogr.Open('GMLAS:data/gmlas/gmlas_timestamp_ignored_for_hash_foo.xml') lyr = ds.GetLayer(0) @@ -1413,55 +1106,40 @@ def ogr_gmlas_timestamp_ignored_for_hash(): lyr = ds.GetLayer(0) f = lyr.GetNextFeature() if f['ogr_pkid'] != pkid: - gdaltest.post_reason('fail') - print(pkid) f.DumpReadable() - return 'fail' - - return 'success' + pytest.fail(pkid) + ############################################################################### # Test dataset GetNextFeature() -def ogr_gmlas_dataset_getnextfeature(): +def test_ogr_gmlas_dataset_getnextfeature(): if ogr.GetDriverByName('GMLAS') is None: - return 'skip' + pytest.skip() ds = gdal.OpenEx('GMLAS:data/gmlas/gmlas_test1.xml') - if ds.TestCapability(ogr.ODsCRandomLayerRead) != 1: - gdaltest.post_reason('fail') - return 'fail' + assert ds.TestCapability(ogr.ODsCRandomLayerRead) == 1 count = 0 last_l = None while True: f, lyr = ds.GetNextFeature() if f is None: - if lyr is not None: - gdaltest.post_reason('fail') - return 'fail' + assert lyr is None break count += 1 last_l = lyr base_count = 59 - if count != base_count: - gdaltest.post_reason('fail') - print(count) - return 'fail' + assert count == base_count - if last_l.GetName() != 'main_elt': - gdaltest.post_reason('fail') - print(last_l.GetName()) - return 'fail' + assert last_l.GetName() == 'main_elt' f, lyr = ds.GetNextFeature() - if f is not None or lyr is not None: - gdaltest.post_reason('fail') - return 'fail' + assert f is None and lyr is None ds.ResetReading() last_pct = 0 @@ -1469,14 +1147,9 @@ def ogr_gmlas_dataset_getnextfeature(): f, l, pct = ds.GetNextFeature(include_pct=True) last_pct = pct if f is None: - if l is not None: - gdaltest.post_reason('fail') - return 'fail' + assert l is None break - if last_pct != 1.0: - gdaltest.post_reason('fail') - print(last_pct - 1.0) - return 'fail' + assert last_pct == 1.0 ds = gdal.OpenEx('GMLAS:data/gmlas/gmlas_test1.xml', open_options=['EXPOSE_METADATA_LAYERS=YES']) fc_map = {} @@ -1492,9 +1165,7 @@ def ogr_gmlas_dataset_getnextfeature(): while True: f, lyr = ds.GetNextFeature() if f is None: - if lyr is not None: - gdaltest.post_reason('fail') - return 'fail' + assert lyr is None break count += 1 @@ -1503,15 +1174,10 @@ def ogr_gmlas_dataset_getnextfeature(): expected_count += fc_map['_ogr_layers_metadata'] expected_count += fc_map['_ogr_layer_relationships'] expected_count += fc_map['_ogr_other_metadata'] - if count != expected_count: - gdaltest.post_reason('fail') - print(count) - return 'fail' + assert count == expected_count f, lyr = ds.GetNextFeature() - if f is not None or lyr is not None: - gdaltest.post_reason('fail') - return 'fail' + assert f is None and lyr is None ds.ResetReading() @@ -1519,17 +1185,11 @@ def ogr_gmlas_dataset_getnextfeature(): while True: f, lyr = ds.GetNextFeature() if f is None: - if lyr is not None: - gdaltest.post_reason('fail') - return 'fail' + assert lyr is None break count += 1 - if count != expected_count: - gdaltest.post_reason('fail') - print(count) - print(expected_count) - return 'fail' + assert count == expected_count for layers in [['_ogr_fields_metadata'], ['_ogr_layers_metadata'], @@ -1549,22 +1209,14 @@ def ogr_gmlas_dataset_getnextfeature(): while True: f, lyr = ds.GetNextFeature() if f is None: - if lyr is not None: - gdaltest.post_reason('fail') - return 'fail' + assert lyr is None break count += 1 - if count != expected_count: - gdaltest.post_reason('fail') - print(count) - print(expected_count) - return 'fail' + assert count == expected_count f, lyr = ds.GetNextFeature() - if f is not None or lyr is not None: - gdaltest.post_reason('fail') - return 'fail' + assert f is None and lyr is None # Test iterating over metadata layers on XSD-only based dataset ds = gdal.OpenEx('GMLAS:', open_options=['XSD=data/gmlas/gmlas_test1.xsd', 'EXPOSE_METADATA_LAYERS=YES']) @@ -1573,77 +1225,55 @@ def ogr_gmlas_dataset_getnextfeature(): while True: f, lyr = ds.GetNextFeature() if f is None: - if lyr is not None: - gdaltest.post_reason('fail') - return 'fail' + assert lyr is None break count += 1 last_l = lyr - if count == 0: - gdaltest.post_reason('fail') - print(count) - return 'fail' - - return 'success' + assert count != 0 ############################################################################### # Test that with schemas that have a structure like a base:identifier, we # will inline it. -def ogr_gmlas_inline_identifier(): +def test_ogr_gmlas_inline_identifier(): if ogr.GetDriverByName('GMLAS') is None: - return 'skip' + pytest.skip() ds = gdal.OpenEx('GMLAS:', open_options=['XSD=data/gmlas/gmlas_inline_identifier.xsd']) if ds.GetLayerCount() != 2: - gdaltest.post_reason('fail') - print(ds.GetLayerCount()) for i in range(ds.GetLayerCount()): print(ds.GetLayer(i).GetName()) - return 'fail' + pytest.fail(ds.GetLayerCount()) lyr = ds.GetLayer(0) - if lyr.GetLayerDefn().GetFieldIndex('identifier_foo') < 0: - gdaltest.post_reason('fail') - return 'fail' - - return 'success' + assert lyr.GetLayerDefn().GetFieldIndex('identifier_foo') >= 0 ############################################################################### # Test that we can handle things like gml:name and au:name -def ogr_gmlas_avoid_same_name_inlined_classes(): +def test_ogr_gmlas_avoid_same_name_inlined_classes(): if ogr.GetDriverByName('GMLAS') is None: - return 'skip' + pytest.skip() ds = gdal.OpenEx('GMLAS:', open_options=['XSD=data/gmlas/gmlas_avoid_same_name_inlined_classes.xsd']) - if ds.GetLayerCount() != 3: - gdaltest.post_reason('fail') - print(ds.GetLayerCount()) - return 'fail' + assert ds.GetLayerCount() == 3 lyr = ds.GetLayerByName('myFeature_ns1_dt') - if lyr is None: - gdaltest.post_reason('fail') - return 'fail' + assert lyr is not None lyr = ds.GetLayerByName('myFeature_ns2_dt') - if lyr is None: - gdaltest.post_reason('fail') - return 'fail' - - return 'success' + assert lyr is not None ############################################################################### # Test validation with an optional fixed attribute that is ignored -def ogr_gmlas_validate_ignored_fixed_attribute(): +def test_ogr_gmlas_validate_ignored_fixed_attribute(): if ogr.GetDriverByName('GMLAS') is None: - return 'skip' + pytest.skip() myhandler = MyHandler() gdal.PushErrorHandler(myhandler.error_handler) @@ -1651,78 +1281,63 @@ def ogr_gmlas_validate_ignored_fixed_attribute(): open_options=['VALIDATE=YES', 'CONFIG_FILE=<Configuration><IgnoredXPaths><XPath>@bar</XPath></IgnoredXPaths></Configuration>']) gdal.PopErrorHandler() - if myhandler.error_list: - gdaltest.post_reason('fail') - print(myhandler.error_list) - return 'fail' - - return 'success' + assert not myhandler.error_list ############################################################################### # Test REMOVE_UNUSED_LAYERS and REMOVE_UNUSED_FIELDS options -def ogr_gmlas_remove_unused_layers_and_fields(): +def test_ogr_gmlas_remove_unused_layers_and_fields(): if ogr.GetDriverByName('GMLAS') is None: - return 'skip' + pytest.skip() ds = gdal.OpenEx('GMLAS:data/gmlas/gmlas_remove_unused_layers_and_fields.xml', open_options=['REMOVE_UNUSED_LAYERS=YES', 'REMOVE_UNUSED_FIELDS=YES']) - if ds.GetLayerCount() != 1: - gdaltest.post_reason('fail') - return 'fail' + assert ds.GetLayerCount() == 1 lyr = ds.GetLayer(0) f = lyr.GetNextFeature() if lyr.GetLayerDefn().GetFieldCount() != 4: - gdaltest.post_reason('fail') - print(lyr.GetLayerDefn().GetFieldCount()) f.DumpReadable() - return 'fail' - if f['used1'] != 'foo' or f['used2'] != 'bar' or f['nillable_nilReason'] != 'unknown': - gdaltest.post_reason('fail') - return 'fail' + pytest.fail(lyr.GetLayerDefn().GetFieldCount()) + assert f['used1'] == 'foo' and f['used2'] == 'bar' and f['nillable_nilReason'] == 'unknown' lyr = ds.GetLayerByName('_ogr_layers_metadata') if lyr.GetFeatureCount() != 1: - gdaltest.post_reason('fail') for f in lyr: f.DumpReadable() - return 'fail' + pytest.fail() lyr = ds.GetLayerByName('_ogr_fields_metadata') if lyr.GetFeatureCount() != 7: - gdaltest.post_reason('fail') for f in lyr: f.DumpReadable() - return 'fail' + pytest.fail() lyr = ds.GetLayerByName('_ogr_layer_relationships') if lyr.GetFeatureCount() != 0: - gdaltest.post_reason('fail') for f in lyr: f.DumpReadable() - return 'fail' - - return 'success' + pytest.fail() + ############################################################################### # Test xlink resolution -def ogr_gmlas_xlink_resolver(): +def test_ogr_gmlas_xlink_resolver(): if ogr.GetDriverByName('GMLAS') is None: - return 'skip' + pytest.skip() drv = gdal.GetDriverByName('HTTP') if drv is None: - return 'skip' + pytest.skip() (webserver_process, webserver_port) = webserver.launch(handler=GMLASHTTPHandler) if webserver_port == 0: - return 'skip' + pytest.skip() gdal.FileFromMemBuffer('/vsimem/ogr_gmlas_xlink_resolver.xsd', """<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" @@ -1785,9 +1400,8 @@ def ogr_gmlas_xlink_resolver(): ds = gdal.OpenEx('GMLAS:/vsimem/ogr_gmlas_xlink_resolver.xml') lyr = ds.GetLayer(0) if lyr.GetLayerDefn().GetFieldIndex('my_link_rawcontent') >= 0: - gdaltest.post_reason('fail') webserver.server_stop(webserver_process, webserver_port) - return 'fail' + pytest.fail() ds = None # Enable resolution, but only from local cache @@ -1801,14 +1415,12 @@ def ogr_gmlas_xlink_resolver(): </XLinkResolution></Configuration>"""]) lyr = ds.GetLayer(0) if lyr.GetLayerDefn().GetFieldIndex('my_link_rawcontent') < 0: - gdaltest.post_reason('fail') webserver.server_stop(webserver_process, webserver_port) - return 'fail' + pytest.fail() f = lyr.GetNextFeature() if f.IsFieldSet('my_link_rawcontent'): - gdaltest.post_reason('fail') webserver.server_stop(webserver_process, webserver_port) - return 'fail' + pytest.fail() # Try again but this time with the cached file cached_file = '/vsimem/gmlas_xlink_cache/localhost_%d_vsimem_resource.xml' % webserver_port @@ -1816,9 +1428,8 @@ def ogr_gmlas_xlink_resolver(): lyr.ResetReading() f = lyr.GetNextFeature() if f['my_link_rawcontent'] != 'foo': - gdaltest.post_reason('fail') webserver.server_stop(webserver_process, webserver_port) - return 'fail' + pytest.fail() ds = None gdal.Unlink(cached_file) @@ -1838,29 +1449,25 @@ def ogr_gmlas_xlink_resolver(): lyr = ds.GetLayer(0) f = lyr.GetNextFeature() if f['my_link_rawcontent'] != 'bar': - gdaltest.post_reason('fail') webserver.server_stop(webserver_process, webserver_port) - return 'fail' + pytest.fail() # Check that the content is not cached if gdal.VSIStatL(cached_file) is not None: - gdaltest.post_reason('fail') webserver.server_stop(webserver_process, webserver_port) - return 'fail' + pytest.fail() # Delete the remote file and check that we can retrieve it from RAM cache gdal.Unlink('/vsimem/resource.xml') lyr.ResetReading() f = lyr.GetNextFeature() if f['my_link_rawcontent'] != 'bar': - gdaltest.post_reason('fail') webserver.server_stop(webserver_process, webserver_port) - return 'fail' + pytest.fail() f = lyr.GetNextFeature() if f['my_link_rawcontent'] != 'baz': - gdaltest.post_reason('fail') webserver.server_stop(webserver_process, webserver_port) - return 'fail' + pytest.fail() gdal.Unlink('/vsimem/resource2.xml') lyr.ResetReading() @@ -1868,15 +1475,13 @@ def ogr_gmlas_xlink_resolver(): with gdaltest.error_handler(): f = lyr.GetNextFeature() if f['my_link_rawcontent'] is not None: - gdaltest.post_reason('fail') webserver.server_stop(webserver_process, webserver_port) - return 'fail' + pytest.fail() f = lyr.GetNextFeature() if f['my_link_rawcontent'] != 'baz': - gdaltest.post_reason('fail') webserver.server_stop(webserver_process, webserver_port) - return 'fail' + pytest.fail() ds = None @@ -1894,14 +1499,12 @@ def ogr_gmlas_xlink_resolver(): lyr = ds.GetLayer(0) f = lyr.GetNextFeature() if f['my_link_rawcontent'] != 'bar': - gdaltest.post_reason('fail') webserver.server_stop(webserver_process, webserver_port) - return 'fail' + pytest.fail() # Check that the content is cached if gdal.VSIStatL(cached_file) is None: - gdaltest.post_reason('fail') webserver.server_stop(webserver_process, webserver_port) - return 'fail' + pytest.fail() ds = None # Enable remote resolution and caching and REFRESH_CACHE @@ -1918,14 +1521,12 @@ def ogr_gmlas_xlink_resolver(): lyr = ds.GetLayer(0) f = lyr.GetNextFeature() if f['my_link_rawcontent'] != 'baz': - gdaltest.post_reason('fail') webserver.server_stop(webserver_process, webserver_port) - return 'fail' + pytest.fail() # Check that the content is cached if gdal.VSIStatL(cached_file) is None: - gdaltest.post_reason('fail') webserver.server_stop(webserver_process, webserver_port) - return 'fail' + pytest.fail() ds = None # Test absent remote resource @@ -1948,10 +1549,9 @@ def ogr_gmlas_xlink_resolver(): with gdaltest.error_handler(): f = lyr.GetNextFeature() if f.IsFieldSet('my_link_rawcontent'): - gdaltest.post_reason('fail') f.DumpReadable() webserver.server_stop(webserver_process, webserver_port) - return 'fail' + pytest.fail() ds = None # Test file size limit @@ -1970,14 +1570,12 @@ def ogr_gmlas_xlink_resolver(): with gdaltest.error_handler(): f = lyr.GetNextFeature() if gdal.GetLastErrorMsg() == '': - gdaltest.post_reason('fail') webserver.server_stop(webserver_process, webserver_port) - return 'fail' + pytest.fail() # Check that the content is not cached if gdal.VSIStatL(cached_file) is not None: - gdaltest.post_reason('fail') webserver.server_stop(webserver_process, webserver_port) - return 'fail' + pytest.fail() ds = None # Test with URL specific rule with RawContent resolution @@ -1999,15 +1597,13 @@ def ogr_gmlas_xlink_resolver(): f['my_link_href'] != 'http://localhost:%d/vsimem/resource.xml' % webserver_port or \ f['my_link_rawcontent'] != 'bar' or \ f['my_link_attr_after'] != 'b': - gdaltest.post_reason('fail') f.DumpReadable() webserver.server_stop(webserver_process, webserver_port) - return 'fail' + pytest.fail() # Check that the content is cached if gdal.VSIStatL(cached_file) is None: - gdaltest.post_reason('fail') webserver.server_stop(webserver_process, webserver_port) - return 'fail' + pytest.fail() ds = None # Test with URL specific rule with FieldsFromXPath resolution @@ -2130,17 +1726,15 @@ def ogr_gmlas_xlink_resolver(): f['my_link2_datetime'] != '2016/10/07 12:34:56+00' or \ f['my_link2_bar'] is not None or \ f['my_link2_attr_after'] != 'b2': - gdaltest.post_reason('fail') f.DumpReadable() webserver.server_stop(webserver_process, webserver_port) - return 'fail' + pytest.fail() f = lyr.GetNextFeature() if f['my_link2_bar'] != 123: - gdaltest.post_reason('fail') f.DumpReadable() webserver.server_stop(webserver_process, webserver_port) - return 'fail' + pytest.fail() gdal.Unlink('/vsimem/subdir1/resource.xml') gdal.Unlink('/vsimem/subdir2/resource2_super_super_super_super_super_super_super_super_super_super_super_super_super_super_super_super_super_super_super_super_super_super_super_super_super_super_super_super_super_super_super_super_super_super_super_super_super_super_super_super_super_super_super_super_very_long.xml') @@ -2161,10 +1755,9 @@ def ogr_gmlas_xlink_resolver(): f['my_link2_baz'] != 345 or \ f['my_link2_bar'] is not None or \ f['my_link2_attr_after'] != 'b2': - gdaltest.post_reason('fail') f.DumpReadable() webserver.server_stop(webserver_process, webserver_port) - return 'fail' + pytest.fail() ds = None @@ -2185,16 +1778,14 @@ def ogr_gmlas_xlink_resolver(): gdal.Unlink('/vsimem/subdir2/resource2_super_super_super_super_super_super_super_super_super_super_super_super_super_super_super_super_super_super_super_super_super_super_super_super_super_super_super_super_super_super_super_super_super_super_super_super_super_super_super_super_super_super_super_super_very_long.xml') gdal.Unlink('/vsimem/non_matching_resource.xml') - return 'success' - ############################################################################### # Test UTF-8 support -def ogr_gmlas_recoding(): +def test_ogr_gmlas_recoding(): if ogr.GetDriverByName('GMLAS') is None: - return 'skip' + pytest.skip() if sys.version_info >= (3, 0, 0): accent = '\u00e9' @@ -2206,29 +1797,26 @@ def ogr_gmlas_recoding(): lyr = ds.GetLayer(0) f = lyr.GetNextFeature() if f['attr'] != accent: - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' - - return 'success' + pytest.fail() + ############################################################################### # Test schema without namespace prefix -def ogr_gmlas_schema_without_namespace_prefix(): +def test_ogr_gmlas_schema_without_namespace_prefix(): if ogr.GetDriverByName('GMLAS') is None: - return 'skip' + pytest.skip() # Generic http:// namespace URI ds = gdal.OpenEx('GMLAS:', open_options=['XSD=data/gmlas/gmlas_schema_without_namespace_prefix_generic_http_uri.xsd']) lyr = ds.GetLayerByName('_ogr_layers_metadata') f = lyr.GetNextFeature() if f['layer_xpath'] != 'my_ns:main_elt': - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' + pytest.fail() gdal.Unlink('/vsimem/ogr_gmlas_schema_without_namespace_prefix.xsd') @@ -2238,9 +1826,8 @@ def ogr_gmlas_schema_without_namespace_prefix(): lyr = ds.GetLayerByName('_ogr_layers_metadata') f = lyr.GetNextFeature() if f['layer_xpath'] != 'fake_3_0:main_elt': - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' + pytest.fail() gdal.Unlink('/vsimem/ogr_gmlas_schema_without_namespace_prefix.xsd') @@ -2250,150 +1837,97 @@ def ogr_gmlas_schema_without_namespace_prefix(): lyr = ds.GetLayerByName('_ogr_layers_metadata') f = lyr.GetNextFeature() if f['layer_xpath'] != 'my_namespace:main_elt': - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' - - return 'success' + pytest.fail() + ############################################################################### # Test parsing truncated XML -def ogr_gmlas_truncated_xml(): +def test_ogr_gmlas_truncated_xml(): if ogr.GetDriverByName('GMLAS') is None: - return 'skip' + pytest.skip() ds = gdal.OpenEx('GMLAS:data/gmlas/gmlas_truncated_xml.xml') lyr = ds.GetLayer(0) with gdaltest.error_handler(): f = lyr.GetNextFeature() if f is not None: - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' - - return 'success' + pytest.fail() + ############################################################################### # Test identifier truncation -def ogr_gmlas_identifier_truncation(): +def test_ogr_gmlas_identifier_truncation(): if ogr.GetDriverByName('GMLAS') is None: - return 'skip' + pytest.skip() ds = gdal.OpenEx('GMLAS:', open_options=[ 'XSD=data/gmlas/gmlas_identifier_truncation.xsd', 'CONFIG_FILE=<Configuration><LayerBuildingRules><IdentifierMaxLength>10</IdentifierMaxLength><PostgreSQLIdentifierLaundering>false</PostgreSQLIdentifierLaundering></LayerBuildingRules></Configuration>']) lyr = ds.GetLayerByName('v_l_i_clas') - if lyr is None: - gdaltest.post_reason('fail') - print(ds.GetLayer(0).GetName()) - return 'fail' + assert lyr is not None, ds.GetLayer(0).GetName() s = lyr.GetLayerDefn().GetFieldDefn(1).GetName() - if s != 'v_l_idTifi': - gdaltest.post_reason('fail') - print(s) - return 'fail' + assert s == 'v_l_idTifi' s = lyr.GetLayerDefn().GetFieldDefn(2).GetName() - if s != 'an_lo_ide1': - gdaltest.post_reason('fail') - print(s) - return 'fail' + assert s == 'an_lo_ide1' s = lyr.GetLayerDefn().GetFieldDefn(3).GetName() - if s != 'an_lo_ide2': - gdaltest.post_reason('fail') - print(s) - return 'fail' + assert s == 'an_lo_ide2' s = lyr.GetLayerDefn().GetFieldDefn(4).GetName() - if s != 'x': - gdaltest.post_reason('fail') - print(s) - return 'fail' + assert s == 'x' s = lyr.GetLayerDefn().GetFieldDefn(5).GetName() - if s != 'noTCAMELCa': - gdaltest.post_reason('fail') - print(s) - return 'fail' + assert s == 'noTCAMELCa' s = lyr.GetLayerDefn().GetFieldDefn(6).GetName() - if s != 'suuuuuuuuu': - gdaltest.post_reason('fail') - print(s) - return 'fail' + assert s == 'suuuuuuuuu' s = lyr.GetLayerDefn().GetFieldDefn(7).GetName() - if s != '_r_l_o_n_g': - gdaltest.post_reason('fail') - print(s) - return 'fail' + assert s == '_r_l_o_n_g' lyr = ds.GetLayerByName('a_l_i_cla1') - if lyr is None: - gdaltest.post_reason('fail') - print(ds.GetLayer(1).GetName()) - return 'fail' + assert lyr is not None, ds.GetLayer(1).GetName() lyr = ds.GetLayerByName('a_l_i_cla2') - if lyr is None: - gdaltest.post_reason('fail') - print(ds.GetLayer(2).GetName()) - return 'fail' + assert lyr is not None, ds.GetLayer(2).GetName() lyr = ds.GetLayerByName('y') - if lyr is None: - gdaltest.post_reason('fail') - print(ds.GetLayer(3).GetName()) - return 'fail' + assert lyr is not None, ds.GetLayer(3).GetName() ds = None - return 'success' - ############################################################################### # Test behaviour when identifiers have same case -def ogr_gmlas_identifier_case_ambiguity(): +def test_ogr_gmlas_identifier_case_ambiguity(): if ogr.GetDriverByName('GMLAS') is None: - return 'skip' + pytest.skip() ds = gdal.OpenEx('GMLAS:', open_options=[ 'XSD=data/gmlas/gmlas_identifier_case_ambiguity.xsd', 'CONFIG_FILE=<Configuration><LayerBuildingRules><PostgreSQLIdentifierLaundering>false</PostgreSQLIdentifierLaundering></LayerBuildingRules></Configuration>']) lyr = ds.GetLayerByName('differentcase1') - if lyr is None: - gdaltest.post_reason('fail') - print(ds.GetLayer(0).GetName()) - return 'fail' + assert lyr is not None, ds.GetLayer(0).GetName() s = lyr.GetLayerDefn().GetFieldDefn(1).GetName() - if s != 'differentcase1': - gdaltest.post_reason('fail') - print(s) - return 'fail' + assert s == 'differentcase1' s = lyr.GetLayerDefn().GetFieldDefn(2).GetName() - if s != 'DifferentCASE2': - gdaltest.post_reason('fail') - print(s) - return 'fail' + assert s == 'DifferentCASE2' lyr = ds.GetLayerByName('DifferentCASE2') - if lyr is None: - gdaltest.post_reason('fail') - print(ds.GetLayer(0).GetName()) - return 'fail' + assert lyr is not None, ds.GetLayer(0).GetName() ds = None - return 'success' - ############################################################################### # Test writing support -def ogr_gmlas_writer(): +def test_ogr_gmlas_writer(): if ogr.GetDriverByName('GMLAS') is None: - return 'skip' + pytest.skip() if ogr.GetDriverByName('SQLite') is None: - return 'skip' + pytest.skip() src_ds = gdal.OpenEx('GMLAS:data/gmlas/gmlas_test1.xml', open_options=['EXPOSE_METADATA_LAYERS=YES']) tmp_ds = gdal.VectorTranslate('/vsimem/ogr_gmlas_writer.db', src_ds, format='SQLite') @@ -2404,100 +1938,82 @@ def ogr_gmlas_writer(): tmp_ds = None gdal.Unlink('/vsimem/ogr_gmlas_writer.db') - if ret_ds is None: - gdaltest.post_reason('fail') - return 'fail' - - return 'success' + assert ret_ds is not None ############################################################################### # Check the generated .xml and .xsd -def ogr_gmlas_writer_check_xml_xsd(): +def test_ogr_gmlas_writer_check_xml_xsd(): if ogr.GetDriverByName('GMLAS') is None: - return 'skip' + pytest.skip() if ogr.GetDriverByName('SQLite') is None: - return 'skip' + pytest.skip() got = open('tmp/gmlas_test1_generated.xml', 'rt').read() got = got.replace('\r\n', '\n') pos = got.find('http://myns ') + len('http://myns ') pos_end = got.find('"', pos) absolute_xsd = got[pos:pos_end] - if not absolute_xsd.endswith('gmlas_test1.xsd') or not os.path.exists(absolute_xsd): - gdaltest.post_reason('fail') - print(absolute_xsd) - return 'fail' + assert absolute_xsd.endswith('gmlas_test1.xsd') and os.path.exists(absolute_xsd) got = got.replace(absolute_xsd, 'gmlas_test1.xsd') expected = open('data/gmlas/gmlas_test1_generated.xml', 'rt').read() expected = expected.replace('\r\n', '\n') if got != expected: - gdaltest.post_reason('fail') - - print('Got:') print(got) print('') print('Diff:') os.system('diff -u data/gmlas/gmlas_test1_generated.xml tmp/gmlas_test1_generated.xml') - return 'fail' + pytest.fail('Got:') got = open('tmp/gmlas_test1_generated.xsd', 'rt').read() got = got.replace('\r\n', '\n') pos = got.find('schemaLocation="') + len('schemaLocation="') pos_end = got.find('"', pos) absolute_xsd = got[pos:pos_end] - if not absolute_xsd.endswith('gmlas_test1.xsd') or not os.path.exists(absolute_xsd): - gdaltest.post_reason('fail') - print(absolute_xsd) - return 'fail' + assert absolute_xsd.endswith('gmlas_test1.xsd') and os.path.exists(absolute_xsd) got = got.replace(absolute_xsd, 'gmlas_test1.xsd') expected = open('data/gmlas/gmlas_test1_generated.xsd', 'rt').read() expected = expected.replace('\r\n', '\n') if got != expected: - gdaltest.post_reason('fail') - - print('Got:') print(got) print('') print('Diff:') os.system('diff -u data/gmlas/gmlas_test1_generated.xsd tmp/gmlas_test1_generated.xsd') - return 'fail' - - return 'success' + pytest.fail('Got:') + ############################################################################### # Check that the .xml read back by the GMLAS driver has the same content # as the original one. -def ogr_gmlas_writer_check_xml_read_back(): +def test_ogr_gmlas_writer_check_xml_read_back(): if ogr.GetDriverByName('GMLAS') is None: - return 'skip' + pytest.skip() if ogr.GetDriverByName('SQLite') is None: - return 'skip' + pytest.skip() # Skip tests when -fsanitize is used if gdaltest.is_travis_branch('sanitize'): - print('Skipping because of -sanitize') - return 'skip' + pytest.skip('Skipping because of -sanitize') import test_cli_utilities if test_cli_utilities.get_ogrinfo_path() is None: gdal.Unlink('tmp/gmlas_test1_generated.xml') gdal.Unlink('tmp/gmlas_test1_generated.xsd') - return 'skip' + pytest.skip() # Compare the ogrinfo dump of the generated .xml with a reference one ret = gdaltest.runexternal(test_cli_utilities.get_ogrinfo_path() + @@ -2516,9 +2032,6 @@ def ogr_gmlas_writer_check_xml_read_back(): ret_for_comparison = ret_for_comparison.replace('fake_hash', '3CF9893502A592E8CF5EA6EF3D8F8C7B') if ret_for_comparison != expected: - gdaltest.post_reason('fail') - - print('XML:') print(open('tmp/gmlas_test1_generated.xml', 'rt').read()) print('') @@ -2537,21 +2050,19 @@ def ogr_gmlas_writer_check_xml_read_back(): os.unlink('tmp/gmlas_test1_generated_expected.txt') os.unlink('tmp/gmlas_test1_generated_got.txt') - return 'fail' + pytest.fail('XML:') gdal.Unlink('tmp/gmlas_test1_generated.xml') gdal.Unlink('tmp/gmlas_test1_generated.xsd') - return 'success' - ############################################################################### # Test writing support with geometries -def ogr_gmlas_writer_gml(): +def test_ogr_gmlas_writer_gml(): if ogr.GetDriverByName('GMLAS') is None: - return 'skip' + pytest.skip() src_ds = gdal.OpenEx('GMLAS:data/gmlas/gmlas_geometryproperty_gml32_no_error.gml', open_options=['EXPOSE_METADATA_LAYERS=YES', '@HASH=hash']) @@ -2565,55 +2076,34 @@ def ogr_gmlas_writer_gml(): 'LAYERS={SPATIAL_LAYERS}']) tmp_ds = None - if ret_ds is None: - gdaltest.post_reason('fail') - return 'fail' + assert ret_ds is not None f = gdal.VSIFOpenL('/vsimem/ogr_gmlas_writer_gml.xml', 'rb') - if f is None: - gdaltest.post_reason('fail') - return 'fail' + assert f is not None content = gdal.VSIFReadL(1, 10000, f).decode('utf-8') gdal.VSIFCloseL(f) gdal.Unlink('/vsimem/ogr_gmlas_writer_gml.xml') gdal.Unlink('/vsimem/ogr_gmlas_writer_gml.xsd') - if content.find('xmlns:gml="http://fake_gml32"') < 0: - gdaltest.post_reason('fail') - print(content) - return 'fail' - - if content.find('<ogr:geometryProperty><gml:Point srsName="http://www.opengis.net/def/crs/EPSG/0/4326" gml:id="hash_test_1.geom0"><gml:pos>49 2</gml:pos></gml:Point></ogr:geometryProperty>') < 0: - gdaltest.post_reason('fail') - print(content) - return 'fail' + assert content.find('xmlns:gml="http://fake_gml32"') >= 0 - if content.find('<ogr:pointProperty><gml:Point srsName="http://www.opengis.net/def/crs/EPSG/0/4326" gml:id="hash_test_1.geom2"><gml:pos>50 3</gml:pos></gml:Point></ogr:pointProperty>') < 0: - gdaltest.post_reason('fail') - print(content) - return 'fail' + assert content.find('<ogr:geometryProperty><gml:Point srsName="http://www.opengis.net/def/crs/EPSG/0/4326" gml:id="hash_test_1.geom0"><gml:pos>49 2</gml:pos></gml:Point></ogr:geometryProperty>') >= 0 - if content.find(' <ogr:pointPropertyRepeated><gml:Point gml:id="hash_test_1.geom13.0"><gml:pos>0 1</gml:pos></gml:Point></ogr:pointPropertyRepeated>') < 0: - gdaltest.post_reason('fail') - print(content) - return 'fail' + assert content.find('<ogr:pointProperty><gml:Point srsName="http://www.opengis.net/def/crs/EPSG/0/4326" gml:id="hash_test_1.geom2"><gml:pos>50 3</gml:pos></gml:Point></ogr:pointProperty>') >= 0 - if content.find(' <ogr:pointPropertyRepeated><gml:Point gml:id="hash_test_1.geom13.1"><gml:pos>1 2</gml:pos></gml:Point></ogr:pointPropertyRepeated>') < 0: - gdaltest.post_reason('fail') - print(content) - return 'fail' + assert content.find(' <ogr:pointPropertyRepeated><gml:Point gml:id="hash_test_1.geom13.0"><gml:pos>0 1</gml:pos></gml:Point></ogr:pointPropertyRepeated>') >= 0 - return 'success' + assert content.find(' <ogr:pointPropertyRepeated><gml:Point gml:id="hash_test_1.geom13.1"><gml:pos>1 2</gml:pos></gml:Point></ogr:pointPropertyRepeated>') >= 0 ############################################################################### # Test writing support with geometries and -a_srs -def ogr_gmlas_writer_gml_assign_srs(): +def test_ogr_gmlas_writer_gml_assign_srs(): if ogr.GetDriverByName('GMLAS') is None: - return 'skip' + pytest.skip() src_ds = gdal.OpenEx('GMLAS:data/gmlas/gmlas_geometryproperty_gml32_no_error.gml', open_options=['EXPOSE_METADATA_LAYERS=YES', '@HASH=hash']) @@ -2626,24 +2116,17 @@ def ogr_gmlas_writer_gml_assign_srs(): reproject=False) tmp_ds = None - if ret_ds is None: - gdaltest.post_reason('fail') - return 'fail' + assert ret_ds is not None f = gdal.VSIFOpenL('/vsimem/ogr_gmlas_writer_gml.xml', 'rb') - if f is None: - gdaltest.post_reason('fail') - return 'fail' + assert f is not None content = gdal.VSIFReadL(1, 10000, f).decode('utf-8') gdal.VSIFCloseL(f) gdal.Unlink('/vsimem/ogr_gmlas_writer_gml.xml') gdal.Unlink('/vsimem/ogr_gmlas_writer_gml.xsd') - if content.find('http://www.opengis.net/def/crs/EPSG/0/32631') < 0: - gdaltest.post_reason('fail') - print(content) - return 'fail' + assert content.find('http://www.opengis.net/def/crs/EPSG/0/32631') >= 0 # No geometry, but to test that the proxied ExecuteSQL() works @@ -2663,27 +2146,21 @@ def ogr_gmlas_writer_gml_assign_srs(): tmp_ds = None gdal.Unlink('/vsimem/ogr_gmlas_writer.db') - if gdal.VSIStatL('/vsimem/gmlas_test1_generated_ref0.xml').size != gdal.VSIStatL('/vsimem/gmlas_test1_generated_asrs.xml').size: - gdaltest.post_reason('fail') - print(gdal.VSIStatL('/vsimem/gmlas_test1_generated_ref0.xml').size) - print(gdal.VSIStatL('/vsimem/gmlas_test1_generated_asrs.xml').size) - return 'fail' + assert gdal.VSIStatL('/vsimem/gmlas_test1_generated_ref0.xml').size == gdal.VSIStatL('/vsimem/gmlas_test1_generated_asrs.xml').size gdal.Unlink('/vsimem/gmlas_test1_generated_ref0.xml') gdal.Unlink('/vsimem/gmlas_test1_generated_ref0.xsd') gdal.Unlink('/vsimem/gmlas_test1_generated_asrs.xml') gdal.Unlink('/vsimem/gmlas_test1_generated_asrs.xsd') - return 'success' - ############################################################################### # Test writing support with geometries with original XML content preserved -def ogr_gmlas_writer_gml_original_xml(): +def test_ogr_gmlas_writer_gml_original_xml(): if ogr.GetDriverByName('GMLAS') is None: - return 'skip' + pytest.skip() src_ds = gdal.OpenEx('GMLAS:data/gmlas/gmlas_geometryproperty_gml32_no_error.gml', open_options=['EXPOSE_METADATA_LAYERS=YES', @@ -2694,52 +2171,35 @@ def ogr_gmlas_writer_gml_original_xml(): datasetCreationOptions=['WRAPPING=GMLAS_FEATURECOLLECTION']) tmp_ds = None - if ret_ds is None: - gdaltest.post_reason('fail') - return 'fail' + assert ret_ds is not None ret_ds = None ds = gdal.OpenEx('GMLAS:/vsimem/ogr_gmlas_writer_gml.xml', open_options=['VALIDATE=YES']) - if ds is None or gdal.GetLastErrorMsg() != '': - gdaltest.post_reason('fail') - return 'fail' + assert ds is not None and gdal.GetLastErrorMsg() == '' ds = None f = gdal.VSIFOpenL('/vsimem/ogr_gmlas_writer_gml.xml', 'rb') - if f is None: - gdaltest.post_reason('fail') - return 'fail' + assert f is not None content = gdal.VSIFReadL(1, 10000, f).decode('utf-8') gdal.VSIFCloseL(f) gdal.Unlink('/vsimem/ogr_gmlas_writer_gml.xml') gdal.Unlink('/vsimem/ogr_gmlas_writer_gml.xsd') - if content.find('<ogr:geometryProperty> <gml:Point gml:id="poly.geom.Geometry" srsName="urn:ogc:def:crs:EPSG::4326"> <gml:pos>49 2</gml:pos> </gml:Point> </ogr:geometryProperty>') < 0: - gdaltest.post_reason('fail') - print(content) - return 'fail' + assert content.find('<ogr:geometryProperty> <gml:Point gml:id="poly.geom.Geometry" srsName="urn:ogc:def:crs:EPSG::4326"> <gml:pos>49 2</gml:pos> </gml:Point> </ogr:geometryProperty>') >= 0 - if content.find(' <ogr:pointPropertyRepeated><gml:Point gml:id="poly.geom.pointPropertyRepeated.1"><gml:pos>0 1</gml:pos></gml:Point></ogr:pointPropertyRepeated>') < 0: - gdaltest.post_reason('fail') - print(content) - return 'fail' + assert content.find(' <ogr:pointPropertyRepeated><gml:Point gml:id="poly.geom.pointPropertyRepeated.1"><gml:pos>0 1</gml:pos></gml:Point></ogr:pointPropertyRepeated>') >= 0 - if content.find(' <ogr:pointPropertyRepeated><gml:Point gml:id="poly.geom.pointPropertyRepeated.2"><gml:pos>1 2</gml:pos></gml:Point></ogr:pointPropertyRepeated>') < 0: - gdaltest.post_reason('fail') - print(content) - return 'fail' - - return 'success' + assert content.find(' <ogr:pointPropertyRepeated><gml:Point gml:id="poly.geom.pointPropertyRepeated.2"><gml:pos>1 2</gml:pos></gml:Point></ogr:pointPropertyRepeated>') >= 0 ############################################################################### # Test writing support with XSD, INDENT_SIZE, COMMENT, OUTPUT_XSD_FILENAME, TIMESTAMP options -def ogr_gmlas_writer_options(): +def test_ogr_gmlas_writer_options(): if ogr.GetDriverByName('GMLAS') is None: - return 'skip' + pytest.skip() src_ds = gdal.OpenEx('GMLAS:data/gmlas/gmlas_geometryproperty_gml32_no_error.gml', open_options=['@HASH=hash']) tmp_ds = gdal.VectorTranslate('', src_ds, format='Memory') @@ -2754,48 +2214,30 @@ def ogr_gmlas_writer_options(): 'OUTPUT_XSD_FILENAME=/vsimem/my_schema.xsd']) tmp_ds = None - if ret_ds is None: - gdaltest.post_reason('fail') - return 'fail' + assert ret_ds is not None f = gdal.VSIFOpenL('/vsimem/ogr_gmlas_writer_options.xml', 'rb') - if f is None: - gdaltest.post_reason('fail') - return 'fail' + assert f is not None content = gdal.VSIFReadL(1, 10000, f).decode('utf-8') gdal.VSIFCloseL(f) gdal.Unlink('/vsimem/ogr_gmlas_writer_options.xml') - if gdal.VSIStatL('/vsimem/my_schema.xsd') is None: - gdaltest.post_reason('fail') - return 'fail' + assert gdal.VSIStatL('/vsimem/my_schema.xsd') is not None gdal.Unlink('/vsimem/my_schema.xsd') # Test indentation size - if content.find('\n <ogr:test gml:id="poly.0">') < 0: - gdaltest.post_reason('fail') - print(content) - return 'fail' + assert content.find('\n <ogr:test gml:id="poly.0">') >= 0 # Test comment - if content.find('\n<!-- - - -a comment- - - -->') < 0: - gdaltest.post_reason('fail') - print(content) - return 'fail' + assert content.find('\n<!-- - - -a comment- - - -->') >= 0 # Test OUTPUT_XSD_FILENAME - if content.find('/vsimem/my_schema.xsd') < 0: - gdaltest.post_reason('fail') - print(content) - return 'fail' + assert content.find('/vsimem/my_schema.xsd') >= 0 # Test SRSNAME_FORMAT=OGC_URN - if content.find('<ogr:geometryProperty><gml:Point srsName="urn:ogc:def:crs:EPSG::4326" gml:id="hash_test_1.geom0"><gml:pos>49 2</gml:pos></gml:Point></ogr:geometryProperty>') < 0: - gdaltest.post_reason('fail') - print(content) - return 'fail' + assert content.find('<ogr:geometryProperty><gml:Point srsName="urn:ogc:def:crs:EPSG::4326" gml:id="hash_test_1.geom0"><gml:pos>49 2</gml:pos></gml:Point></ogr:geometryProperty>') >= 0 # Test TIMESTAMP option src_ds = gdal.OpenEx('GMLAS:data/gmlas/gmlas_geometryproperty_gml32_no_error.gml', @@ -2806,28 +2248,19 @@ def ogr_gmlas_writer_options(): datasetCreationOptions=['TIMESTAMP=1970-01-01T12:34:56Z', '@REOPEN_DATASET_WITH_GMLAS=NO']) tmp_ds = None - if ret_ds is None: - gdaltest.post_reason('fail') - return 'fail' + assert ret_ds is not None f = gdal.VSIFOpenL('/vsimem/ogr_gmlas_writer_options.xml', 'rb') - if f is None: - gdaltest.post_reason('fail') - return 'fail' + assert f is not None content = gdal.VSIFReadL(1, 10000, f).decode('utf-8') gdal.VSIFCloseL(f) gdal.Unlink('/vsimem/ogr_gmlas_writer_options.xml') - if gdal.VSIStatL('/vsimem/my_schema.xsd') is not None: - gdaltest.post_reason('fail') - return 'fail' + assert gdal.VSIStatL('/vsimem/my_schema.xsd') is None - if content.find('timeStamp="1970-01-01T12:34:56Z"') < 0 or \ - content.find('xsi:schemaLocation="http://www.opengis.net/wfs/2.0 http://schemas.opengis.net/wfs/2.0/wfs.xsd ') < 0: - gdaltest.post_reason('fail') - print(content) - return 'fail' + assert (content.find('timeStamp="1970-01-01T12:34:56Z"') >= 0 and \ + content.find('xsi:schemaLocation="http://www.opengis.net/wfs/2.0 http://schemas.opengis.net/wfs/2.0/wfs.xsd ') >= 0) # Test WFS20_SCHEMALOCATION option src_ds = gdal.OpenEx('GMLAS:data/gmlas/gmlas_geometryproperty_gml32_no_error.gml', @@ -2838,9 +2271,7 @@ def ogr_gmlas_writer_options(): datasetCreationOptions=['WFS20_SCHEMALOCATION=/vsimem/fake_wfs.xsd']) tmp_ds = None - if ret_ds is None: - gdaltest.post_reason('fail') - return 'fail' + assert ret_ds is not None gdal.FileFromMemBuffer('/vsimem/fake_wfs.xsd', """ @@ -2863,47 +2294,33 @@ def ogr_gmlas_writer_options(): ds = gdal.OpenEx('GMLAS:/vsimem/ogr_gmlas_writer_options.xml', open_options=['VALIDATE=YES']) gdal.Unlink('/vsimem/fake_wfs.xsd') - if ds is None or gdal.GetLastErrorMsg() != '': - gdaltest.post_reason('fail') - return 'fail' + assert ds is not None and gdal.GetLastErrorMsg() == '' ds = None f = gdal.VSIFOpenL('/vsimem/ogr_gmlas_writer_options.xml', 'rb') - if f is None: - gdaltest.post_reason('fail') - return 'fail' + assert f is not None content = gdal.VSIFReadL(1, 10000, f).decode('utf-8') gdal.VSIFCloseL(f) gdal.Unlink('/vsimem/ogr_gmlas_writer_options.xml') - if gdal.VSIStatL('/vsimem/my_schema.xsd') is not None: - gdaltest.post_reason('fail') - return 'fail' - - if content.find('xsi:schemaLocation="http://www.opengis.net/wfs/2.0 /vsimem/fake_wfs.xsd ') < 0: - gdaltest.post_reason('fail') - print(content) - return 'fail' + assert gdal.VSIStatL('/vsimem/my_schema.xsd') is None - return 'success' + assert content.find('xsi:schemaLocation="http://www.opengis.net/wfs/2.0 /vsimem/fake_wfs.xsd ') >= 0 ############################################################################### # Test writing support error handle -def ogr_gmlas_writer_errors(): +def test_ogr_gmlas_writer_errors(): if ogr.GetDriverByName('GMLAS') is None: - return 'skip' + pytest.skip() # Source dataset is empty with gdaltest.error_handler(): ret_ds = gdal.VectorTranslate('/vsimem/valid.xml', gdal.GetDriverByName('Memory').Create('', 0, 0, 0, 0), format='GMLAS') - if ret_ds is not None or gdal.GetLastErrorMsg().find('Source dataset has no layers') < 0: - gdaltest.post_reason('fail') - print(gdal.GetLastErrorMsg()) - return 'fail' + assert ret_ds is None and gdal.GetLastErrorMsg().find('Source dataset has no layers') >= 0 # Missing input schemas src_ds = gdal.OpenEx('GMLAS:data/gmlas/gmlas_geometryproperty_gml32_no_error.gml') @@ -2911,19 +2328,13 @@ def ogr_gmlas_writer_errors(): src_ds = None with gdaltest.error_handler(): ret_ds = gdal.VectorTranslate('/vsimem/valid.xml', tmp_ds, format='GMLAS') - if ret_ds is not None or gdal.GetLastErrorMsg().find('Cannot establish schema since no INPUT_XSD creation option specified and no _ogr_other_metadata found in source dataset') < 0: - gdaltest.post_reason('fail') - print(gdal.GetLastErrorMsg()) - return 'fail' + assert ret_ds is None and gdal.GetLastErrorMsg().find('Cannot establish schema since no INPUT_XSD creation option specified and no _ogr_other_metadata found in source dataset') >= 0 # Invalid input schema with gdaltest.error_handler(): ret_ds = gdal.VectorTranslate('/vsimem/valid.xml', tmp_ds, format='GMLAS', datasetCreationOptions=['INPUT_XSD=/i_do_not/exist.xsd']) - if ret_ds is not None or gdal.GetLastErrorMsg().find('Cannot resolve /i_do_not/exist.xsd') < 0: - gdaltest.post_reason('fail') - print(gdal.GetLastErrorMsg()) - return 'fail' + assert ret_ds is None and gdal.GetLastErrorMsg().find('Cannot resolve /i_do_not/exist.xsd') >= 0 # Invalid output .xml name src_ds = gdal.OpenEx('GMLAS:data/gmlas/gmlas_geometryproperty_gml32_no_error.gml', @@ -2933,48 +2344,33 @@ def ogr_gmlas_writer_errors(): with gdaltest.error_handler(): ret_ds = gdal.VectorTranslate('/i_am/not/valid.xml', tmp_ds, format='GMLAS', datasetCreationOptions=['GENERATE_XSD=NO']) - if ret_ds is not None or gdal.GetLastErrorMsg().find('Cannot create /i_am/not/valid.xml') < 0: - gdaltest.post_reason('fail') - print(gdal.GetLastErrorMsg()) - return 'fail' + assert ret_ds is None and gdal.GetLastErrorMsg().find('Cannot create /i_am/not/valid.xml') >= 0 # .xsd extension not allowed with gdaltest.error_handler(): ret_ds = gdal.VectorTranslate('/i_am/not/valid.xsd', tmp_ds, format='GMLAS', datasetCreationOptions=['GENERATE_XSD=NO']) - if ret_ds is not None or gdal.GetLastErrorMsg().find('.xsd extension is not valid') < 0: - gdaltest.post_reason('fail') - print(gdal.GetLastErrorMsg()) - return 'fail' + assert ret_ds is None and gdal.GetLastErrorMsg().find('.xsd extension is not valid') >= 0 # Invalid output .xsd name with gdaltest.error_handler(): ret_ds = gdal.VectorTranslate('/vsimem/valid.xml', tmp_ds, format='GMLAS', datasetCreationOptions=['WRAPPING=GMLAS_FEATURECOLLECTION', 'OUTPUT_XSD_FILENAME=/i_am/not/valid.xsd']) - if ret_ds is not None or gdal.GetLastErrorMsg().find('Cannot create /i_am/not/valid.xsd') < 0: - gdaltest.post_reason('fail') - print(gdal.GetLastErrorMsg()) - return 'fail' + assert ret_ds is None and gdal.GetLastErrorMsg().find('Cannot create /i_am/not/valid.xsd') >= 0 gdal.Unlink('/vsimem/valid.xml') # Invalid CONFIG_FILE with gdaltest.error_handler(): ret_ds = gdal.VectorTranslate('/vsimem/valid.xml', tmp_ds, format='GMLAS', datasetCreationOptions=['CONFIG_FILE=/i/do_not/exist']) - if ret_ds is not None or gdal.GetLastErrorMsg().find('Loading of configuration failed') < 0: - gdaltest.post_reason('fail') - print(gdal.GetLastErrorMsg()) - return 'fail' + assert ret_ds is None and gdal.GetLastErrorMsg().find('Loading of configuration failed') >= 0 # Invalid layer name with gdaltest.error_handler(): ret_ds = gdal.VectorTranslate('/vsimem/valid.xml', tmp_ds, format='GMLAS', datasetCreationOptions=['LAYERS=foo']) - if ret_ds is not None or gdal.GetLastErrorMsg().find('Layer foo specified in LAYERS option does not exist') < 0: - gdaltest.post_reason('fail') - print(gdal.GetLastErrorMsg()) - return 'fail' + assert ret_ds is None and gdal.GetLastErrorMsg().find('Layer foo specified in LAYERS option does not exist') >= 0 gdal.Unlink('/vsimem/valid.xml') # _ogr_layers_metadata not found @@ -2982,10 +2378,7 @@ def ogr_gmlas_writer_errors(): src_ds.CreateLayer('_ogr_other_metadata') with gdaltest.error_handler(): ret_ds = gdal.VectorTranslate('/vsimem/valid.xml', src_ds, format='GMLAS') - if ret_ds is not None or gdal.GetLastErrorMsg().find('_ogr_layers_metadata not found') < 0: - gdaltest.post_reason('fail') - print(gdal.GetLastErrorMsg()) - return 'fail' + assert ret_ds is None and gdal.GetLastErrorMsg().find('_ogr_layers_metadata not found') >= 0 # _ogr_fields_metadata not found src_ds = gdal.GetDriverByName('Memory').Create('', 0, 0, 0, 0) @@ -2993,10 +2386,7 @@ def ogr_gmlas_writer_errors(): src_ds.CreateLayer('_ogr_layers_metadata') with gdaltest.error_handler(): ret_ds = gdal.VectorTranslate('/vsimem/valid.xml', src_ds, format='GMLAS') - if ret_ds is not None or gdal.GetLastErrorMsg().find('_ogr_fields_metadata not found') < 0: - gdaltest.post_reason('fail') - print(gdal.GetLastErrorMsg()) - return 'fail' + assert ret_ds is None and gdal.GetLastErrorMsg().find('_ogr_fields_metadata not found') >= 0 # _ogr_layer_relationships not found src_ds = gdal.GetDriverByName('Memory').Create('', 0, 0, 0, 0) @@ -3005,10 +2395,7 @@ def ogr_gmlas_writer_errors(): src_ds.CreateLayer('_ogr_fields_metadata') with gdaltest.error_handler(): ret_ds = gdal.VectorTranslate('/vsimem/valid.xml', src_ds, format='GMLAS') - if ret_ds is not None or gdal.GetLastErrorMsg().find('_ogr_layer_relationships not found') < 0: - gdaltest.post_reason('fail') - print(gdal.GetLastErrorMsg()) - return 'fail' + assert ret_ds is None and gdal.GetLastErrorMsg().find('_ogr_layer_relationships not found') >= 0 # Cannot find field layer_name in _ogr_layers_metadata layer src_ds = gdal.GetDriverByName('Memory').Create('', 0, 0, 0, 0) @@ -3018,24 +2405,19 @@ def ogr_gmlas_writer_errors(): src_ds.CreateLayer('_ogr_layer_relationships') with gdaltest.error_handler(): ret_ds = gdal.VectorTranslate('/vsimem/valid.xml', src_ds, format='GMLAS') - if ret_ds is not None or gdal.GetLastErrorMsg().find('Cannot find field layer_name in _ogr_layers_metadata layer') < 0: - gdaltest.post_reason('fail') - print(gdal.GetLastErrorMsg()) - return 'fail' + assert ret_ds is None and gdal.GetLastErrorMsg().find('Cannot find field layer_name in _ogr_layers_metadata layer') >= 0 gdal.Unlink('/vsimem/valid.xml') gdal.Unlink('/vsimem/valid.xsd') - return 'success' - ############################################################################### # Test reading a particular construct with group, etc... that could cause # crashes -def ogr_gmlas_read_fake_gmljp2(): +def test_ogr_gmlas_read_fake_gmljp2(): if ogr.GetDriverByName('GMLAS') is None: - return 'skip' + pytest.skip() ds = gdal.OpenEx('GMLAS:data/fake_gmljp2.xml') @@ -3043,27 +2425,20 @@ def ogr_gmlas_read_fake_gmljp2(): while True: f, lyr = ds.GetNextFeature() if f is None: - if lyr is not None: - gdaltest.post_reason('fail') - return 'fail' + assert lyr is None break count += 1 - if count != 5: - gdaltest.post_reason('fail') - print(count) - return 'fail' - - return 'success' + assert count == 5 ############################################################################### # Test TypingConstraints -def ogr_gmlas_typing_constraints(): +def test_ogr_gmlas_typing_constraints(): if ogr.GetDriverByName('GMLAS') is None: - return 'skip' + pytest.skip() # One substitution, no repetition ds = gdal.OpenEx('GMLAS:data/gmlas/gmlas_typing_constraints_one_subst_no_repetition.xml', @@ -3083,15 +2458,13 @@ def ogr_gmlas_typing_constraints(): lyr = ds.GetLayer(0) f = lyr.GetNextFeature() if not f.IsFieldSetAndNotNull('foo_bar_pkid'): - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' + pytest.fail() lyr = ds.GetLayer(1) f = lyr.GetNextFeature() if f.GetField('value') != 'baz': - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' + pytest.fail() ds = None # One substitution, with repetition @@ -3111,20 +2484,16 @@ def ogr_gmlas_typing_constraints(): </TypingConstraints> </Configuration>"""]) lyr = ds.GetLayer('main_elt_foo_bar') - if lyr.GetFeatureCount() != 2: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.GetFeatureCount() == 2 lyr = ds.GetLayer('bar') f = lyr.GetNextFeature() if f.GetField('value') != 'baz': - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' + pytest.fail() f = lyr.GetNextFeature() if f.GetField('value') != 'baz2': - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' + pytest.fail() ds = None # 2 substitutions @@ -3146,31 +2515,26 @@ def ogr_gmlas_typing_constraints(): lyr = ds.GetLayer(0) f = lyr.GetNextFeature() if not f.IsFieldSetAndNotNull('foo_bar_pkid'): - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' + pytest.fail() if f.IsFieldSetAndNotNull('foo_baz_pkid'): - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' + pytest.fail() lyr = ds.GetLayer(1) f = lyr.GetNextFeature() if f.GetField('value') != 'baz': - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' + pytest.fail() ds = None - return 'success' - ############################################################################### # Test swe:DataArray -def ogr_gmlas_swe_dataarray(): +def test_ogr_gmlas_swe_dataarray(): if ogr.GetDriverByName('GMLAS') is None: - return 'skip' + pytest.skip() ds = gdal.OpenEx('GMLAS:data/gmlas/gmlas_swe_dataarray.xml') @@ -3183,90 +2547,74 @@ def ogr_gmlas_swe_dataarray(): f.GetField('myCount') != 3 or \ f.GetField('myText') != 'foo' or \ f.GetField('myBoolean') is False: - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' + pytest.fail() f = lyr.GetNextFeature() if f.GetField('myTime') != '2017/09/01 00:00:00' or \ f.GetField('myCategory') != '2' or \ f.GetField('myQuantity') != 3.45: - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' + pytest.fail() f = lyr.GetNextFeature() if f is not None: - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' + pytest.fail() lyr = ds.GetLayerByName('dataarray_2') f = lyr.GetNextFeature() if f.GetField('myTime') != '2016/09/01 00:00:00+01' or \ f.GetField('myCategory') != '1' or \ f.GetField('myQuantity') != 2.34: - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' + pytest.fail() f = lyr.GetNextFeature() if f.GetField('myTime') != '2017/09/01 00:00:00' or \ f.GetField('myCategory') is not None or \ f.GetField('myQuantity') != 3.45: - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' + pytest.fail() f = lyr.GetNextFeature() if f is not None: - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' + pytest.fail() lyr = ds.GetLayerByName('dataarray_3') f = lyr.GetNextFeature() if f.GetField('myTime') != '2016/09/01 00:00:00+01' or \ f.GetField('myCategory') != '1' or \ f.GetField('myQuantity') != 2.34: - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' + pytest.fail() f = lyr.GetNextFeature() if f.GetField('myTime') != '2017/09/01 00:00:00' or \ f.GetField('myCategory') is not None or \ f.GetField('myQuantity') != 3.45: - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' + pytest.fail() f = lyr.GetNextFeature() if f is not None: - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' + pytest.fail() ds = None - return 'success' - ############################################################################### # Test swe:DataRecord -def ogr_gmlas_swe_datarecord(): +def test_ogr_gmlas_swe_datarecord(): if ogr.GetDriverByName('GMLAS') is None: - return 'skip' + pytest.skip() gdal.ErrorReset() ds = gdal.OpenEx('GMLAS:data/gmlas/gmlas_swe_datarecord.xml', open_options=['VALIDATE=YES']) - if gdal.GetLastErrorMsg() != '': - gdaltest.post_reason('fail') - return 'fail' + assert gdal.GetLastErrorMsg() == '' ds = None ds = gdal.OpenEx('GMLAS:data/gmlas/gmlas_swe_datarecord.xml') lyr = ds.GetLayerByName('main_elt_foo') - if lyr.GetLayerDefn().GetFieldCount() != 12: - gdaltest.post_reason('fail') - print(lyr.GetLayerDefn().GetFieldCount()) - return 'fail' + assert lyr.GetLayerDefn().GetFieldCount() == 12 f = lyr.GetNextFeature() if f.GetField('mytime_value') != '2017/09/01 00:00:00' or \ f.GetField('mycategory_value') != 'myvalue' or \ @@ -3276,21 +2624,18 @@ def ogr_gmlas_swe_datarecord(): f.GetField('mycount_value') != 2 or \ f.GetField('mytext_value') != 'foo' or \ f.GetField('myboolean_value') is False: - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' + pytest.fail() ds = None - return 'success' - ############################################################################### # Test a xs:any field at end of a type declaration -def ogr_gmlas_any_field_at_end_of_declaration(): +def test_ogr_gmlas_any_field_at_end_of_declaration(): if ogr.GetDriverByName('GMLAS') is None: - return 'skip' + pytest.skip() # Simplified test case for # http://schemas.earthresourceml.org/earthresourceml-lite/1.0/erml-lite.xsd @@ -3303,63 +2648,57 @@ def ogr_gmlas_any_field_at_end_of_declaration(): gdal.ErrorReset() with gdaltest.error_handler(): f = lyr.GetNextFeature() - if gdal.GetLastErrorMsg() == '': - gdaltest.post_reason('fail') - return 'fail' + assert gdal.GetLastErrorMsg() != '' if f.GetField('foo') != 'bar': - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' + pytest.fail() if f.GetField('value') != '<something>baz</something>': print('Expected fail: value != <something>baz</something>') - return 'success' - + ############################################################################### # Test auxiliary schema without namespace prefix -def ogr_gmlas_aux_schema_without_namespace_prefix(): +def test_ogr_gmlas_aux_schema_without_namespace_prefix(): if ogr.GetDriverByName('GMLAS') is None: - return 'skip' + pytest.skip() ds = gdal.OpenEx('GMLAS:data/gmlas/gmlas_aux_schema_without_namespace_prefix.xml') lyr = ds.GetLayerByName('main_elt') f = lyr.GetNextFeature() if not f.IsFieldSetAndNotNull('generic_pkid'): f.DumpReadable() - return 'fail' - - return 'success' + pytest.fail() + ############################################################################### # Test importing a GML geometry that is in an element that is a substitutionGroup # of another one (#6990) -def ogr_gmlas_geometry_as_substitutiongroup(): +def test_ogr_gmlas_geometry_as_substitutiongroup(): if ogr.GetDriverByName('GMLAS') is None: - return 'skip' + pytest.skip() ds = gdal.OpenEx('GMLAS:data/gmlas/gmlas_geometry_as_substitutiongroup.xml') lyr = ds.GetLayerByName('foo') f = lyr.GetNextFeature() if f.GetGeometryRef() is None: f.DumpReadable() - return 'fail' + pytest.fail() ds = None - return 'success' - ############################################################################### -def ogr_gmlas_extra_piezometre(): +@pytest.mark.skip() +def test_ogr_gmlas_extra_piezometre(): if ogr.GetDriverByName('GMLAS') is None: - return 'skip' + pytest.skip() return compare_ogrinfo_output('data/gmlas/real_world/Piezometre.06512X0037.STREMY.2.gml', 'data/gmlas/real_world/output/Piezometre.06512X0037.STREMY.2.txt', @@ -3368,10 +2707,11 @@ def ogr_gmlas_extra_piezometre(): ############################################################################### -def ogr_gmlas_extra_eureg(): +@pytest.mark.skip() +def test_ogr_gmlas_extra_eureg(): if ogr.GetDriverByName('GMLAS') is None: - return 'skip' + pytest.skip() return compare_ogrinfo_output('data/gmlas/real_world/EUReg.example.gml', 'data/gmlas/real_world/output/EUReg.example.txt', @@ -3382,29 +2722,27 @@ def ogr_gmlas_extra_eureg(): # Test a schema that has nothing interesting in it but imports another # schema -def ogr_gmlas_no_element_in_first_choice_schema(): +def test_ogr_gmlas_no_element_in_first_choice_schema(): if ogr.GetDriverByName('GMLAS') is None: - return 'skip' + pytest.skip() ds = gdal.OpenEx('GMLAS:', open_options=['XSD=data/gmlas/gmlas_no_element_in_first_choice_schema.xsd']) lyr = ds.GetLayerByName('_ogr_layers_metadata') f = lyr.GetNextFeature() if f['layer_xpath'] != 'my_ns:main_elt': - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' - - return 'success' + pytest.fail() + ############################################################################### # Test cross-layer links with xlink:href="#my_id" -def ogr_gmlas_internal_xlink_href(): +def test_ogr_gmlas_internal_xlink_href(): if ogr.GetDriverByName('GMLAS') is None: - return 'skip' + pytest.skip() with gdaltest.error_handler(): ds = gdal.OpenEx('GMLAS:data/gmlas/gmlas_internal_xlink_href.xml') @@ -3414,53 +2752,47 @@ def ogr_gmlas_internal_xlink_href(): f.IsFieldSet('link_to_second_or_third_elt_second_elt_pkid') or \ f.IsFieldSet('link_to_second_or_third_elt_third_elt_pkid') or \ f.IsFieldSet('link_to_third_elt_third_elt_pkid'): - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' + pytest.fail() f = lyr.GetNextFeature() if f['link_to_second_or_third_elt_href'] != '#id2' or \ f['link_to_second_or_third_elt_second_elt_pkid'] != 'id2' or \ f.IsFieldSet('link_to_second_or_third_elt_third_elt_pkid') or \ f.IsFieldSet('link_to_third_elt_third_elt_pkid'): - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' + pytest.fail() f = lyr.GetNextFeature() if f['link_to_second_or_third_elt_href'] != '#id3' or \ f['link_to_second_or_third_elt_second_elt_pkid'] != 'id3' or \ f.IsFieldSet('link_to_second_or_third_elt_third_elt_pkid') or \ f.IsFieldSet('link_to_third_elt_third_elt_pkid'): - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' + pytest.fail() f = lyr.GetNextFeature() if f['link_to_second_or_third_elt_href'] != '#id4' or \ f.IsFieldSet('link_to_second_or_third_elt_second_elt_pkid') or \ f['link_to_second_or_third_elt_third_elt_pkid'] != 'D1013B7E44F28C976B976A4314FA4A09_third_elt_1' or \ f.IsFieldSet('link_to_third_elt_third_elt_pkid'): - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' + pytest.fail() f = lyr.GetNextFeature() if f['link_to_third_elt_href'] != '#id4' or \ f.IsFieldSet('link_to_second_or_third_elt_second_elt_pkid') or \ f.IsFieldSet('link_to_second_or_third_elt_third_elt_pkid') or \ f['link_to_third_elt_third_elt_pkid'] != 'D1013B7E44F28C976B976A4314FA4A09_third_elt_1': - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' + pytest.fail() lyr = ds.GetLayerByName('_ogr_fields_metadata') f = lyr.GetNextFeature() if f['layer_name'] != 'main_elt' or f['field_index'] != 1 or \ f['field_name'] != 'link_to_second_or_third_elt_href': - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' + pytest.fail() f = lyr.GetNextFeature() if f['layer_name'] != 'main_elt' or f['field_index'] != 2 or \ @@ -3472,9 +2804,8 @@ def ogr_gmlas_internal_xlink_href(): f['field_max_occurs'] != 1 or \ f['field_category'] != 'PATH_TO_CHILD_ELEMENT_WITH_LINK' or \ f['field_related_layer'] != 'second_elt': - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' + pytest.fail() f = lyr.GetNextFeature() if f['layer_name'] != 'main_elt' or f['field_index'] != 3 or \ @@ -3486,37 +2817,32 @@ def ogr_gmlas_internal_xlink_href(): f['field_max_occurs'] != 1 or \ f['field_category'] != 'PATH_TO_CHILD_ELEMENT_WITH_LINK' or \ f['field_related_layer'] != 'third_elt': - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' + pytest.fail() f = lyr.GetNextFeature() if f['layer_name'] != 'main_elt' or f['field_index'] != 4 or \ f['field_name'] != 'link_to_second_or_third_elt': - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' + pytest.fail() f = lyr.GetNextFeature() if f['layer_name'] != 'main_elt' or f['field_index'] != 5 or \ f['field_name'] != 'link_to_third_elt_href': - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' + pytest.fail() f = lyr.GetNextFeature() if f['layer_name'] != 'main_elt' or f['field_index'] != 6 or \ f['field_name'] != 'link_to_third_elt_third_elt_pkid': - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' + pytest.fail() f = lyr.GetNextFeature() if f['layer_name'] != 'third_elt' or f['field_index'] != 1 or \ f['field_name'] != 'id': - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' + pytest.fail() lyr = ds.GetLayerByName('_ogr_layer_relationships') f = lyr.GetNextFeature() @@ -3525,9 +2851,8 @@ def ogr_gmlas_internal_xlink_href(): f['parent_element_name'] != 'link_to_third_elt_third_elt_pkid' or \ f['child_layer'] != 'third_elt' or \ f['child_pkid'] != 'ogr_pkid': - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' + pytest.fail() f = lyr.GetNextFeature() if f['parent_layer'] != 'main_elt' or \ @@ -3535,9 +2860,8 @@ def ogr_gmlas_internal_xlink_href(): f['parent_element_name'] != 'link_to_second_or_third_elt_second_elt_pkid' or \ f['child_layer'] != 'second_elt' or \ f['child_pkid'] != 'id': - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' + pytest.fail() f = lyr.GetNextFeature() if f['parent_layer'] != 'main_elt' or \ @@ -3545,20 +2869,18 @@ def ogr_gmlas_internal_xlink_href(): f['parent_element_name'] != 'link_to_second_or_third_elt_third_elt_pkid' or \ f['child_layer'] != 'third_elt' or \ f['child_pkid'] != 'ogr_pkid': - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' - - return 'success' + pytest.fail() + ############################################################################### # Cleanup -def ogr_gmlas_cleanup(): +def test_ogr_gmlas_cleanup(): if ogr.GetDriverByName('GMLAS') is None: - return 'skip' + pytest.skip() files = gdal.ReadDir('/vsimem/') if files is not None: @@ -3566,82 +2888,3 @@ def ogr_gmlas_cleanup(): gdal.SetConfigOption('GMLAS_WARN_UNEXPECTED', None) gdal.SetConfigOption('GDAL_XML_VALIDATION', ogrtest.old_val_GDAL_XML_VALIDATION) - - return 'success' - - -gdaltest_list = [ - ogr_gmlas_basic, - ogr_gmlas_test_ogrsf, - ogr_gmlas_virtual_file, - ogr_gmlas_datafile_with_xsd_option, - ogr_gmlas_no_datafile_with_xsd_option, - ogr_gmlas_no_datafile_xsd_which_is_not_xsd, - ogr_gmlas_no_datafile_no_xsd, - ogr_gmlas_non_existing_gml, - ogr_gmlas_non_existing_xsd, - ogr_gmlas_gml_without_schema_location, - ogr_gmlas_invalid_schema, - ogr_gmlas_invalid_xml, - ogr_gmlas_gml_Reference, - ogr_gmlas_same_element_in_different_ns, - ogr_gmlas_corner_case_relative_path, - ogr_gmlas_unexpected_repeated_element, - ogr_gmlas_unexpected_repeated_element_variant, - ogr_gmlas_geometryproperty, - ogr_gmlas_abstractgeometry, - ogr_gmlas_validate, - ogr_gmlas_test_ns_prefix, - ogr_gmlas_no_namespace, - ogr_gmlas_conf, - ogr_gmlas_conf_ignored_xpath, - ogr_gmlas_cache, - ogr_gmlas_link_nested_independant_child, - ogr_gmlas_composition_compositionPart, - ogr_gmlas_instantiate_only_gml_feature, - ogr_gmlas_timestamp_ignored_for_hash, - ogr_gmlas_dataset_getnextfeature, - ogr_gmlas_inline_identifier, - ogr_gmlas_avoid_same_name_inlined_classes, - ogr_gmlas_validate_ignored_fixed_attribute, - ogr_gmlas_remove_unused_layers_and_fields, - ogr_gmlas_xlink_resolver, - ogr_gmlas_recoding, - ogr_gmlas_schema_without_namespace_prefix, - ogr_gmlas_truncated_xml, - ogr_gmlas_identifier_truncation, - ogr_gmlas_identifier_case_ambiguity, - ogr_gmlas_writer, - ogr_gmlas_writer_check_xml_xsd, - ogr_gmlas_writer_check_xml_read_back, - ogr_gmlas_writer_gml, - ogr_gmlas_writer_gml_assign_srs, - ogr_gmlas_writer_gml_original_xml, - ogr_gmlas_writer_options, - ogr_gmlas_writer_errors, - ogr_gmlas_read_fake_gmljp2, - ogr_gmlas_typing_constraints, - ogr_gmlas_swe_dataarray, - ogr_gmlas_swe_datarecord, - ogr_gmlas_any_field_at_end_of_declaration, - ogr_gmlas_aux_schema_without_namespace_prefix, - ogr_gmlas_geometry_as_substitutiongroup, - ogr_gmlas_no_element_in_first_choice_schema, - ogr_gmlas_internal_xlink_href, - ogr_gmlas_cleanup] - -# gdaltest_list = [ ogr_gmlas_basic, ogr_gmlas_aux_schema_without_namespace_prefix, ogr_gmlas_cleanup ] - -# Test only work if using "python ogr_gmlas.py" -gdaltest_extra_list = [ - ogr_gmlas_extra_piezometre, - ogr_gmlas_extra_eureg -] - -if __name__ == '__main__': - - gdaltest.setup_run('ogr_gmlas') - - gdaltest.run_tests(gdaltest_list + gdaltest_extra_list) - - sys.exit(gdaltest.summarize()) diff --git a/autotest/ogr/ogr_gmt.py b/autotest/ogr/ogr_gmt.py index 547d46646c11..1cf48546f5a6 100755 --- a/autotest/ogr/ogr_gmt.py +++ b/autotest/ogr/ogr_gmt.py @@ -28,9 +28,7 @@ # DEALINGS IN THE SOFTWARE. ############################################################################### -import sys -sys.path.append('../pymod') import gdaltest import ogrtest @@ -41,21 +39,18 @@ # Open Memory datasource. -def ogr_gmt_1(): +def test_ogr_gmt_1(): gmt_drv = ogr.GetDriverByName('GMT') gdaltest.gmt_ds = gmt_drv.CreateDataSource('tmp/tpoly.gmt') - if gdaltest.gmt_ds is None: - return 'fail' - - return 'success' + assert gdaltest.gmt_ds is not None ############################################################################### # Create table from data/poly.shp -def ogr_gmt_2(): +def test_ogr_gmt_2(): ####################################################### # Create gmtory Layer @@ -92,13 +87,11 @@ def ogr_gmt_2(): gdaltest.gmt_lyr = None gdaltest.gmt_ds = None - return 'success' - ############################################################################### # Verify that stuff we just wrote is still OK. -def ogr_gmt_3(): +def test_ogr_gmt_3(): gdaltest.gmt_ds = ogr.Open('tmp/tpoly.gmt') gdaltest.gmt_lyr = gdaltest.gmt_ds.GetLayer(0) @@ -114,66 +107,53 @@ def ogr_gmt_3(): orig_feat = gdaltest.poly_feat[i] read_feat = gdaltest.gmt_lyr.GetNextFeature() - if ogrtest.check_feature_geometry(read_feat, orig_feat.GetGeometryRef(), - max_error=0.000000001) != 0: - return 'fail' + assert (ogrtest.check_feature_geometry(read_feat, orig_feat.GetGeometryRef(), + max_error=0.000000001) == 0) for fld in range(3): - if orig_feat.GetField(fld) != read_feat.GetField(fld): - gdaltest.post_reason('Attribute %d does not match' % fld) - return 'fail' + assert orig_feat.GetField(fld) == read_feat.GetField(fld), \ + ('Attribute %d does not match' % fld) gdaltest.poly_feat = None gdaltest.shp_ds = None gdaltest.gmt_lyr = None gdaltest.gmt_ds = None - return 'success' if tr else 'fail' + assert tr ############################################################################### # Verify reading of multilinestring file. (#3802) -def ogr_gmt_4(): +def test_ogr_gmt_4(): ds = ogr.Open('data/test_multi.gmt') lyr = ds.GetLayer(0) - if lyr.GetLayerDefn().GetGeomType() != ogr.wkbMultiLineString: - gdaltest.post_reason('did not get expected multilinestring type.') - return 'fail' + assert lyr.GetLayerDefn().GetGeomType() == ogr.wkbMultiLineString, \ + 'did not get expected multilinestring type.' feat = lyr.GetNextFeature() - if ogrtest.check_feature_geometry(feat, 'MULTILINESTRING ((175 -45,176 -45),(180.0 -45.3,179.0 -45.4))'): - return 'fail' + assert not ogrtest.check_feature_geometry(feat, 'MULTILINESTRING ((175 -45,176 -45),(180.0 -45.3,179.0 -45.4))') - if feat.GetField('name') != 'feature 1': - gdaltest.post_reason('got wrong name, feature 1') - return 'fail' + assert feat.GetField('name') == 'feature 1', 'got wrong name, feature 1' feat = lyr.GetNextFeature() - if ogrtest.check_feature_geometry(feat, 'MULTILINESTRING ((175.1 -45.0,175.2 -45.1),(180.1 -45.3,180.0 -45.2))'): - return 'fail' + assert not ogrtest.check_feature_geometry(feat, 'MULTILINESTRING ((175.1 -45.0,175.2 -45.1),(180.1 -45.3,180.0 -45.2))') - if feat.GetField('name') != 'feature 2': - gdaltest.post_reason('got wrong name, feature 2') - return 'fail' + assert feat.GetField('name') == 'feature 2', 'got wrong name, feature 2' feat = lyr.GetNextFeature() - if feat is not None: - gdaltest.post_reason('did not get null feature when expected.') - return 'fail' - - return 'success' + assert feat is None, 'did not get null feature when expected.' ############################################################################### # Write a multipolygon file and verify it. -def ogr_gmt_5(): +def test_ogr_gmt_5(): ####################################################### # Create gmtory Layer @@ -211,41 +191,30 @@ def ogr_gmt_5(): ds = ogr.Open('tmp/mpoly.gmt') lyr = ds.GetLayer(0) - if lyr.GetLayerDefn().GetGeomType() != ogr.wkbMultiPolygon: - gdaltest.post_reason('did not get expected multipolygon type.') - return 'fail' + assert lyr.GetLayerDefn().GetGeomType() == ogr.wkbMultiPolygon, \ + 'did not get expected multipolygon type.' feat = lyr.GetNextFeature() - if ogrtest.check_feature_geometry(feat, 'MULTIPOLYGON(((0 0,0 10,10 10,0 10,0 0),(3 3,4 4, 3 4,3 3)),((12 0,14 0,12 3,12 0)))'): - return 'fail' + assert not ogrtest.check_feature_geometry(feat, 'MULTIPOLYGON(((0 0,0 10,10 10,0 10,0 0),(3 3,4 4, 3 4,3 3)),((12 0,14 0,12 3,12 0)))') - if feat.GetField('ID') != 15: - gdaltest.post_reason('got wrong id, first feature') - return 'fail' + assert feat.GetField('ID') == 15, 'got wrong id, first feature' feat = lyr.GetNextFeature() - if ogrtest.check_feature_geometry(feat, 'MULTIPOLYGON(((30 20,40 20,30 30,30 20)))'): - return 'fail' + assert not ogrtest.check_feature_geometry(feat, 'MULTIPOLYGON(((30 20,40 20,30 30,30 20)))') - if feat.GetField('ID') != 16: - gdaltest.post_reason('got wrong ID, second feature') - return 'fail' + assert feat.GetField('ID') == 16, 'got wrong ID, second feature' feat = lyr.GetNextFeature() - if feat is not None: - gdaltest.post_reason('did not get null feature when expected.') - return 'fail' - - return 'success' + assert feat is None, 'did not get null feature when expected.' ############################################################################### # -def ogr_gmt_cleanup(): +def test_ogr_gmt_cleanup(): if gdaltest.gmt_ds is not None: gdaltest.gmt_lyr = None @@ -253,21 +222,5 @@ def ogr_gmt_cleanup(): gdaltest.clean_tmp() - return 'success' - - -gdaltest_list = [ - ogr_gmt_1, - ogr_gmt_2, - ogr_gmt_3, - ogr_gmt_4, - ogr_gmt_5, - ogr_gmt_cleanup] - -if __name__ == '__main__': - - gdaltest.setup_run('ogr_gmt') - gdaltest.run_tests(gdaltest_list) - sys.exit(gdaltest.summarize()) diff --git a/autotest/ogr/ogr_gpkg.py b/autotest/ogr/ogr_gpkg.py index f1a81379ddb5..1376cd920430 100755 --- a/autotest/ogr/ogr_gpkg.py +++ b/autotest/ogr/ogr_gpkg.py @@ -33,67 +33,64 @@ import os import struct import sys - -# Make sure we run from the directory of the script -if os.path.basename(sys.argv[0]) == os.path.basename(__file__): - if os.path.dirname(sys.argv[0]) != '': - os.chdir(os.path.dirname(sys.argv[0])) - -sys.path.append('../pymod') -sys.path.append('../../gdal/swig/python/samples') +import pytest from osgeo import gdal from osgeo import ogr from osgeo import osr import gdaltest -sys.path.append('../osr') -import osr_proj4 + +from osr import osr_proj4 ############################################################################### # Validate a geopackage -try: - import validate_gpkg - has_validate = True -except ImportError: - has_validate = False + +def _validate_check(filename): + path = '../../gdal/swig/python/samples' + if path not in sys.path: + sys.path.append(path) + try: + import validate_gpkg + except ImportError: + return + validate_gpkg.check(filename) def validate(filename, quiet=False): - if has_validate: - my_filename = filename - if my_filename.startswith('/vsimem/'): - my_filename = 'tmp/validate.gpkg' - f = gdal.VSIFOpenL(filename, 'rb') - if f is None: - print('Cannot open %s' % filename) - return False - content = gdal.VSIFReadL(1, 10000000, f) - gdal.VSIFCloseL(f) - open(my_filename, 'wb').write(content) - try: - validate_gpkg.check(my_filename) - except Exception as e: - if not quiet: - print(e) + my_filename = filename + if my_filename.startswith('/vsimem/'): + my_filename = 'tmp/validate.gpkg' + f = gdal.VSIFOpenL(filename, 'rb') + if f is None: + print('Cannot open %s' % filename) return False - finally: - if my_filename != filename: - os.unlink(my_filename) + content = gdal.VSIFReadL(1, 10000000, f) + gdal.VSIFCloseL(f) + open(my_filename, 'wb').write(content) + try: + _validate_check(my_filename) + except Exception as e: + if not quiet: + print(e) + return False + finally: + if my_filename != filename: + os.unlink(my_filename) return True ############################################################################### # Create a fresh database. -def ogr_gpkg_1(): +def test_ogr_gpkg_1(): gdaltest.gpkg_ds = None gdaltest.gpkg_dr = None gdaltest.gpkg_dr = ogr.GetDriverByName('GPKG') if gdaltest.gpkg_dr is None: - return 'skip' + pytest.skip() try: os.remove('tmp/gpkg_test.gpkg') @@ -107,62 +104,51 @@ def ogr_gpkg_1(): gdaltest.gpkg_ds = gdaltest.gpkg_dr.CreateDataSource('tmp/gpkg_test.gpkg') - if gdaltest.gpkg_ds is None: - return 'fail' + assert gdaltest.gpkg_ds is not None gdaltest.gpkg_ds = None - if not validate('tmp/gpkg_test.gpkg'): - gdaltest.post_reason('validation failed') - return 'fail' - - return 'success' + assert validate('tmp/gpkg_test.gpkg'), 'validation failed' ############################################################################### # Re-open database to test validity -def ogr_gpkg_2(): +def test_ogr_gpkg_2(): if gdaltest.gpkg_dr is None: - return 'skip' + pytest.skip() gdaltest.gpkg_ds = gdaltest.gpkg_dr.Open('tmp/gpkg_test.gpkg', update=1) # Check there a ogr_empty_table sql_lyr = gdaltest.gpkg_ds.ExecuteSQL("SELECT COUNT(*) FROM sqlite_master WHERE name = 'ogr_empty_table'") f = sql_lyr.GetNextFeature() - if f.GetField(0) != 1: - gdaltest.post_reason('fail') - return 'fail' + assert f.GetField(0) == 1 gdaltest.gpkg_ds.ReleaseResultSet(sql_lyr) # Should default to GPKG 1.2 sql_lyr = gdaltest.gpkg_ds.ExecuteSQL('PRAGMA application_id') f = sql_lyr.GetNextFeature() if f['application_id'] != 1196444487: - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' + pytest.fail() gdaltest.gpkg_ds.ReleaseResultSet(sql_lyr) sql_lyr = gdaltest.gpkg_ds.ExecuteSQL('PRAGMA user_version') f = sql_lyr.GetNextFeature() if f['user_version'] != 10200: - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' + pytest.fail() gdaltest.gpkg_ds.ReleaseResultSet(sql_lyr) - return 'success' - ############################################################################### # Create a layer -def ogr_gpkg_3(): +def test_ogr_gpkg_3(): if gdaltest.gpkg_dr is None or gdaltest.gpkg_ds is None: - return 'skip' + pytest.skip() # Test invalid FORMAT # gdal.PushErrorHandler('CPLQuietErrorHandler') @@ -170,68 +156,52 @@ def ogr_gpkg_3(): srs4326.ImportFromEPSG(4326) lyr = gdaltest.gpkg_ds.CreateLayer('first_layer', geom_type=ogr.wkbPoint, srs=srs4326, options=['GEOMETRY_NAME=gpkg_geometry', 'SPATIAL_INDEX=NO']) # gdal.PopErrorHandler() - if lyr is None: - return 'fail' + assert lyr is not None # Test creating a layer with an existing name gdal.PushErrorHandler('CPLQuietErrorHandler') lyr = gdaltest.gpkg_ds.CreateLayer('a_layer', options=['SPATIAL_INDEX=NO']) lyr = gdaltest.gpkg_ds.CreateLayer('a_layer', options=['SPATIAL_INDEX=NO']) gdal.PopErrorHandler() - if lyr is not None: - gdaltest.post_reason('layer creation should have failed') - return 'fail' - - return 'success' + assert lyr is None, 'layer creation should have failed' ############################################################################### # Close and re-open to test the layer registration -def ogr_gpkg_4(): +def test_ogr_gpkg_4(): if gdaltest.gpkg_dr is None or gdaltest.gpkg_ds is None: - return 'skip' + pytest.skip() gdaltest.gpkg_ds = None - if not validate('tmp/gpkg_test.gpkg'): - gdaltest.post_reason('validation failed') - return 'fail' + assert validate('tmp/gpkg_test.gpkg'), 'validation failed' gdal.PushErrorHandler('CPLQuietErrorHandler') gdaltest.gpkg_ds = gdaltest.gpkg_dr.Open('tmp/gpkg_test.gpkg', update=1) gdal.PopErrorHandler() - if gdaltest.gpkg_ds is None: - return 'fail' + assert gdaltest.gpkg_ds is not None # Check there no ogr_empty_table sql_lyr = gdaltest.gpkg_ds.ExecuteSQL("SELECT COUNT(*) FROM sqlite_master WHERE name = 'ogr_empty_table'") f = sql_lyr.GetNextFeature() - if f.GetField(0) != 0: - gdaltest.post_reason('fail') - return 'fail' + assert f.GetField(0) == 0 gdaltest.gpkg_ds.ReleaseResultSet(sql_lyr) - if gdaltest.gpkg_ds.GetLayerCount() != 2: - gdaltest.post_reason('unexpected number of layers') - return 'fail' + assert gdaltest.gpkg_ds.GetLayerCount() == 2, 'unexpected number of layers' lyr0 = gdaltest.gpkg_ds.GetLayer(0) - if lyr0.GetFIDColumn() != 'fid': - gdaltest.post_reason('unexpected FID name for layer 0') - return 'fail' + assert lyr0.GetFIDColumn() == 'fid', 'unexpected FID name for layer 0' gdaltest.gpkg_ds = None gdaltest.gpkg_ds = gdaltest.gpkg_dr.Open('tmp/gpkg_test.gpkg', update=1) lyr0 = gdaltest.gpkg_ds.GetLayer(0) - if lyr0.GetName() != 'first_layer': - gdaltest.post_reason('unexpected layer name for layer 0') - return 'fail' + assert lyr0.GetName() == 'first_layer', 'unexpected layer name for layer 0' gdaltest.gpkg_ds = None gdaltest.gpkg_ds = gdaltest.gpkg_dr.Open('tmp/gpkg_test.gpkg', update=1) @@ -239,122 +209,88 @@ def ogr_gpkg_4(): lyr0 = gdaltest.gpkg_ds.GetLayer(0) lyr1 = gdaltest.gpkg_ds.GetLayer(1) - if lyr0.GetLayerDefn().GetGeomFieldDefn(0).GetName() != 'gpkg_geometry': - gdaltest.post_reason('unexpected geometry field name for layer 0') - return 'fail' + assert lyr0.GetLayerDefn().GetGeomFieldDefn(0).GetName() == 'gpkg_geometry', \ + 'unexpected geometry field name for layer 0' - if lyr1.GetName() != 'a_layer': - gdaltest.post_reason('unexpected layer name for layer 1') - return 'fail' + assert lyr1.GetName() == 'a_layer', 'unexpected layer name for layer 1' sql_lyr = gdaltest.gpkg_ds.ExecuteSQL("SELECT * FROM sqlite_master WHERE name = 'gpkg_extensions'") - if sql_lyr.GetFeatureCount() != 0: - gdaltest.post_reason('fail') - return 'fail' + assert sql_lyr.GetFeatureCount() == 0 gdaltest.gpkg_ds.ReleaseResultSet(sql_lyr) - return 'success' - ############################################################################### # Delete a layer -def ogr_gpkg_5(): +def test_ogr_gpkg_5(): if gdaltest.gpkg_dr is None or gdaltest.gpkg_ds is None: - return 'skip' + pytest.skip() - if gdaltest.gpkg_ds.GetLayerCount() != 2: - gdaltest.post_reason('unexpected number of layers') - return 'fail' + assert gdaltest.gpkg_ds.GetLayerCount() == 2, 'unexpected number of layers' with gdaltest.error_handler(): ret = gdaltest.gpkg_ds.DeleteLayer(-1) - if ret == 0: - gdaltest.post_reason('expected error') - return 'fail' + assert ret != 0, 'expected error' with gdaltest.error_handler(): ret = gdaltest.gpkg_ds.DeleteLayer(gdaltest.gpkg_ds.GetLayerCount()) - if ret == 0: - gdaltest.post_reason('expected error') - return 'fail' + assert ret != 0, 'expected error' - if gdaltest.gpkg_ds.DeleteLayer(1) != 0: - gdaltest.post_reason('got error code from DeleteLayer(1)') - return 'fail' + assert gdaltest.gpkg_ds.DeleteLayer(1) == 0, 'got error code from DeleteLayer(1)' - if gdaltest.gpkg_ds.DeleteLayer(0) != 0: - gdaltest.post_reason('got error code from DeleteLayer(0)') - return 'fail' + assert gdaltest.gpkg_ds.DeleteLayer(0) == 0, 'got error code from DeleteLayer(0)' - if gdaltest.gpkg_ds.GetLayerCount() != 0: - gdaltest.post_reason('unexpected number of layers (not 0)') - return 'fail' - - return 'success' + assert gdaltest.gpkg_ds.GetLayerCount() == 0, 'unexpected number of layers (not 0)' ############################################################################### # Add fields -def ogr_gpkg_6(): +def test_ogr_gpkg_6(): if gdaltest.gpkg_dr is None or gdaltest.gpkg_ds is None: - return 'skip' + pytest.skip() srs4326 = osr.SpatialReference() srs4326.ImportFromEPSG(4326) lyr = gdaltest.gpkg_ds.CreateLayer('field_test_layer', geom_type=ogr.wkbPoint, srs=srs4326) - if lyr is None: - return 'fail' + assert lyr is not None field_defn = ogr.FieldDefn('dummy', ogr.OFTString) lyr.CreateField(field_defn) - if lyr.GetLayerDefn().GetFieldDefn(0).GetType() != ogr.OFTString: - gdaltest.post_reason('wrong field type') - return 'fail' + assert lyr.GetLayerDefn().GetFieldDefn(0).GetType() == ogr.OFTString, \ + 'wrong field type' gdaltest.gpkg_ds = None - if not validate('tmp/gpkg_test.gpkg'): - gdaltest.post_reason('validation failed') - return 'fail' + assert validate('tmp/gpkg_test.gpkg'), 'validation failed' gdal.PushErrorHandler('CPLQuietErrorHandler') gdaltest.gpkg_ds = gdaltest.gpkg_dr.Open('tmp/gpkg_test.gpkg', update=1) gdal.PopErrorHandler() - if gdaltest.gpkg_ds is None: - return 'fail' + assert gdaltest.gpkg_ds is not None - if gdaltest.gpkg_ds.GetLayerCount() != 1: - return 'fail' + assert gdaltest.gpkg_ds.GetLayerCount() == 1 lyr = gdaltest.gpkg_ds.GetLayer(0) - if lyr.GetName() != 'field_test_layer': - return 'fail' + assert lyr.GetName() == 'field_test_layer' field_defn_out = lyr.GetLayerDefn().GetFieldDefn(0) - if field_defn_out.GetType() != ogr.OFTString: - gdaltest.post_reason('wrong field type after reopen') - return 'fail' - - if field_defn_out.GetName() != 'dummy': - gdaltest.post_reason('wrong field name after reopen') - return 'fail' + assert field_defn_out.GetType() == ogr.OFTString, 'wrong field type after reopen' - return 'success' + assert field_defn_out.GetName() == 'dummy', 'wrong field name after reopen' ############################################################################### # Add a feature / read a feature / delete a feature -def ogr_gpkg_7(): +def test_ogr_gpkg_7(): if gdaltest.gpkg_dr is None or gdaltest.gpkg_ds is None: - return 'skip' + pytest.skip() lyr = gdaltest.gpkg_ds.GetLayerByName('field_test_layer') geom = ogr.CreateGeometryFromWkt('POINT(10 10)') @@ -362,90 +298,71 @@ def ogr_gpkg_7(): feat.SetGeometry(geom) feat.SetField('dummy', 'a dummy value') - if lyr.TestCapability(ogr.OLCSequentialWrite) != 1: - gdaltest.post_reason('lyr.TestCapability(ogr.OLCSequentialWrite) != 1') - return 'fail' + assert lyr.TestCapability(ogr.OLCSequentialWrite) == 1, \ + 'lyr.TestCapability(ogr.OLCSequentialWrite) != 1' - if lyr.CreateFeature(feat) != 0: - gdaltest.post_reason('cannot create feature') - return 'fail' + assert lyr.CreateFeature(feat) == 0, 'cannot create feature' # Read back what we just inserted lyr.ResetReading() feat_read = lyr.GetNextFeature() - if feat_read.GetField('dummy') != 'a dummy value': - gdaltest.post_reason('output does not match input') - return 'fail' + assert feat_read.GetField('dummy') == 'a dummy value', 'output does not match input' # Only inserted one thing, so second feature should return NULL feat_read = lyr.GetNextFeature() - if feat_read is not None: - gdaltest.post_reason('last call should return NULL') - return 'fail' + assert feat_read is None, 'last call should return NULL' # Add another feature geom = ogr.CreateGeometryFromWkt('POINT(100 100)') feat = ogr.Feature(lyr.GetLayerDefn()) feat.SetGeometry(geom) feat.SetField('dummy', 'who you calling a dummy?') - if lyr.CreateFeature(feat) != 0: - gdaltest.post_reason('cannot create feature') - return 'fail' + assert lyr.CreateFeature(feat) == 0, 'cannot create feature' - if lyr.TestCapability(ogr.OLCRandomRead) != 1: - gdaltest.post_reason('lyr.TestCapability(ogr.OLCRandomRead) != 1') - return 'fail' + assert lyr.TestCapability(ogr.OLCRandomRead) == 1, \ + 'lyr.TestCapability(ogr.OLCRandomRead) != 1' # Random read a feature feat_read_random = lyr.GetFeature(feat.GetFID()) - if feat_read_random.GetField('dummy') != 'who you calling a dummy?': - gdaltest.post_reason('random read output does not match input') - return 'fail' + assert feat_read_random.GetField('dummy') == 'who you calling a dummy?', \ + 'random read output does not match input' - if lyr.TestCapability(ogr.OLCRandomWrite) != 1: - gdaltest.post_reason('lyr.TestCapability(ogr.OLCRandomWrite) != 1') - return 'fail' + assert lyr.TestCapability(ogr.OLCRandomWrite) == 1, \ + 'lyr.TestCapability(ogr.OLCRandomWrite) != 1' # Random write a feature feat.SetField('dummy', 'i am no dummy') lyr.SetFeature(feat) feat_read_random = lyr.GetFeature(feat.GetFID()) - if feat_read_random.GetField('dummy') != 'i am no dummy': - gdaltest.post_reason('random read output does not match random write input') - return 'fail' + assert feat_read_random.GetField('dummy') == 'i am no dummy', \ + 'random read output does not match random write input' - if lyr.TestCapability(ogr.OLCDeleteFeature) != 1: - gdaltest.post_reason('lyr.TestCapability(ogr.OLCDeleteFeature) != 1') - return 'fail' + assert lyr.TestCapability(ogr.OLCDeleteFeature) == 1, \ + 'lyr.TestCapability(ogr.OLCDeleteFeature) != 1' # Delete a feature lyr.DeleteFeature(feat.GetFID()) - if lyr.GetFeatureCount() != 1: - gdaltest.post_reason('delete feature did not delete') - return 'fail' + assert lyr.GetFeatureCount() == 1, 'delete feature did not delete' # Test updating non-existing feature feat.SetFID(-10) - if lyr.SetFeature(feat) != ogr.OGRERR_NON_EXISTING_FEATURE: - gdaltest.post_reason('Expected failure of SetFeature().') - return 'fail' + assert lyr.SetFeature(feat) == ogr.OGRERR_NON_EXISTING_FEATURE, \ + 'Expected failure of SetFeature().' # Test deleting non-existing feature - if lyr.DeleteFeature(-10) != ogr.OGRERR_NON_EXISTING_FEATURE: - gdaltest.post_reason('Expected failure of DeleteFeature().') - return 'fail' + assert lyr.DeleteFeature(-10) == ogr.OGRERR_NON_EXISTING_FEATURE, \ + 'Expected failure of DeleteFeature().' # Delete the layer if gdaltest.gpkg_ds.DeleteLayer('field_test_layer') != 0: gdaltest.post_reason('got error code from DeleteLayer(field_test_layer)') - return 'success' - + ############################################################################### # Test a variety of geometry feature types and attribute types -def ogr_gpkg_8(): +def test_ogr_gpkg_8(): # try: # os.remove( 'tmp/gpkg_test.gpkg' ) @@ -455,15 +372,14 @@ def ogr_gpkg_8(): # gdaltest.gpkg_ds = gdaltest.gpkg_dr.CreateDataSource( 'tmp/gpkg_test.gpkg' ) if gdaltest.gpkg_dr is None or gdaltest.gpkg_ds is None: - return 'skip' + pytest.skip() srs = osr.SpatialReference() # Test a non-default SRS srs.ImportFromEPSG(32631) lyr = gdaltest.gpkg_ds.CreateLayer('tbl_linestring', geom_type=ogr.wkbLineString, srs=srs) - if lyr is None: - return 'fail' + assert lyr is not None lyr.StartTransaction() lyr.CreateField(ogr.FieldDefn('fld_integer', ogr.OFTInteger)) @@ -500,46 +416,32 @@ def ogr_gpkg_8(): feat.SetField('fld_float', 1.23) feat.SetField('fld_integer64', 1000000000000 + i) - if lyr.CreateFeature(feat) != 0: - gdaltest.post_reason('cannot create feature %d' % i) - return 'fail' + assert lyr.CreateFeature(feat) == 0, ('cannot create feature %d' % i) lyr.CommitTransaction() feat = ogr.Feature(lyr.GetLayerDefn()) - if lyr.CreateFeature(feat) != 0: - gdaltest.post_reason('cannot insert empty') - return 'fail' + assert lyr.CreateFeature(feat) == 0, 'cannot insert empty' feat.SetFID(6) - if lyr.SetFeature(feat) != 0: - gdaltest.post_reason('cannot update with empty') - return 'fail' + assert lyr.SetFeature(feat) == 0, 'cannot update with empty' gdaltest.gpkg_ds = None gdaltest.gpkg_ds = gdaltest.gpkg_dr.Open('tmp/gpkg_test.gpkg', update=1) lyr = gdaltest.gpkg_ds.GetLayerByName('tbl_linestring') - if lyr.GetLayerDefn().GetFieldDefn(6).GetSubType() != ogr.OFSTBoolean: - gdaltest.post_reason('fail') - return 'fail' - if lyr.GetLayerDefn().GetFieldDefn(7).GetSubType() != ogr.OFSTInt16: - gdaltest.post_reason('fail') - return 'fail' - if lyr.GetLayerDefn().GetFieldDefn(8).GetSubType() != ogr.OFSTFloat32: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.GetLayerDefn().GetFieldDefn(6).GetSubType() == ogr.OFSTBoolean + assert lyr.GetLayerDefn().GetFieldDefn(7).GetSubType() == ogr.OFSTInt16 + assert lyr.GetLayerDefn().GetFieldDefn(8).GetSubType() == ogr.OFSTFloat32 feat = lyr.GetNextFeature() if feat.GetField(0) != 10 or feat.GetField(1) != 'test string 0 test' or \ feat.GetField(2) != 3.14159 or feat.GetField(3) != '2014/05/17' or \ feat.GetField(4) != '2014/05/17 12:34:56+00' or feat.GetField(5) != 'FFFE' or \ feat.GetField(6) != 1 or feat.GetField(7) != -32768 or feat.GetField(8) != 1.23 or \ feat.GetField(9) != 1000000000000: - gdaltest.post_reason('fail') feat.DumpReadable() - return 'fail' + pytest.fail() lyr = gdaltest.gpkg_ds.CreateLayer('tbl_polygon', geom_type=ogr.wkbPolygon, srs=srs) - if lyr is None: - return 'fail' + assert lyr is not None lyr.StartTransaction() lyr.CreateField(ogr.FieldDefn('fld_datetime', ogr.OFTDateTime)) @@ -554,21 +456,17 @@ def ogr_gpkg_8(): feat.SetField('fld_string', 'my super string %d' % i) feat.SetField('fld_datetime', '2010-01-01') - if lyr.CreateFeature(feat) != 0: - gdaltest.post_reason('cannot create polygon feature %d' % i) - return 'fail' + assert lyr.CreateFeature(feat) == 0, ('cannot create polygon feature %d' % i) lyr.CommitTransaction() feat = lyr.GetFeature(3) geom_read = feat.GetGeometryRef() - if geom.ExportToWkt() != geom_read.ExportToWkt(): - gdaltest.post_reason('geom output not equal to geom input') - return 'fail' + assert geom.ExportToWkt() == geom_read.ExportToWkt(), \ + 'geom output not equal to geom input' # Test out the 3D support... lyr = gdaltest.gpkg_ds.CreateLayer('tbl_polygon25d', geom_type=ogr.wkbPolygon25D, srs=srs) - if lyr is None: - return 'fail' + assert lyr is not None lyr.CreateField(ogr.FieldDefn('fld_string', ogr.OFTString)) geom = ogr.CreateGeometryFromWkt('POLYGON((5 5 1, 10 5 2, 10 10 3, 5 104 , 5 5 1),(6 6 4, 6 7 5, 7 7 6, 7 6 7, 6 6 4))') @@ -579,44 +477,33 @@ def ogr_gpkg_8(): lyr.ResetReading() feat = lyr.GetNextFeature() geom_read = feat.GetGeometryRef() - if geom.ExportToWkt() != geom_read.ExportToWkt(): - gdaltest.post_reason('3d geom output not equal to geom input') - return 'fail' - - return 'success' + assert geom.ExportToWkt() == geom_read.ExportToWkt(), \ + '3d geom output not equal to geom input' ############################################################################### # Test support for extents and counts -def ogr_gpkg_9(): +def test_ogr_gpkg_9(): if gdaltest.gpkg_dr is None or gdaltest.gpkg_ds is None: - return 'skip' + pytest.skip() lyr = gdaltest.gpkg_ds.GetLayerByName('tbl_linestring') extent = lyr.GetExtent() - if extent != (5.0, 10.0, 5.0, 10.0): - gdaltest.post_reason('got bad extent') - print(extent) - return 'fail' + assert extent == (5.0, 10.0, 5.0, 10.0), 'got bad extent' fcount = lyr.GetFeatureCount() - if fcount != 11: - gdaltest.post_reason('got bad featurecount') - print(fcount) - return 'fail' - - return 'success' + assert fcount == 11, 'got bad featurecount' ############################################################################### # Test non-SELECT SQL commands -def ogr_gpkg_11(): +def test_ogr_gpkg_11(): if gdaltest.gpkg_dr is None: - return 'skip' + pytest.skip() gdaltest.gpkg_ds = None gdaltest.gpkg_ds = ogr.Open('tmp/gpkg_test.gpkg', update=1) @@ -627,55 +514,31 @@ def ogr_gpkg_11(): gdaltest.gpkg_ds = ogr.Open('tmp/gpkg_test.gpkg', update=1) lyr = gdaltest.gpkg_ds.GetLayerByName('tbl_linestring_renamed') - if lyr is None: - return 'fail' + assert lyr is not None lyr.SetAttributeFilter('fld_integer = 10') - if lyr.GetFeatureCount() != 1: - return 'fail' - - return 'success' + assert lyr.GetFeatureCount() == 1 ############################################################################### # Test SELECT SQL commands -def ogr_gpkg_12(): +def test_ogr_gpkg_12(): if gdaltest.gpkg_dr is None: - return 'skip' + pytest.skip() sql_lyr = gdaltest.gpkg_ds.ExecuteSQL('SELECT * FROM tbl_linestring_renamed') - if sql_lyr.GetFIDColumn() != 'fid': - gdaltest.post_reason('fail') - return 'fail' - if sql_lyr.GetGeomType() != ogr.wkbLineString: - gdaltest.post_reason('fail') - return 'fail' - if sql_lyr.GetGeometryColumn() != 'geom': - gdaltest.post_reason('fail') - return 'fail' - if sql_lyr.GetSpatialRef().ExportToWkt().find('32631') < 0: - gdaltest.post_reason('fail') - return 'fail' + assert sql_lyr.GetFIDColumn() == 'fid' + assert sql_lyr.GetGeomType() == ogr.wkbLineString + assert sql_lyr.GetGeometryColumn() == 'geom' + assert sql_lyr.GetSpatialRef().ExportToWkt().find('32631') >= 0 feat = sql_lyr.GetNextFeature() - if feat.GetFID() != 1: - gdaltest.post_reason('fail') - return 'fail' - if sql_lyr.GetFeatureCount() != 11: - gdaltest.post_reason('fail') - return 'fail' - if sql_lyr.GetLayerDefn().GetFieldCount() != 10: - gdaltest.post_reason('fail') - return 'fail' - if sql_lyr.GetLayerDefn().GetFieldDefn(6).GetSubType() != ogr.OFSTBoolean: - gdaltest.post_reason('fail') - return 'fail' - if sql_lyr.GetLayerDefn().GetFieldDefn(7).GetSubType() != ogr.OFSTInt16: - gdaltest.post_reason('fail') - return 'fail' - if sql_lyr.GetLayerDefn().GetFieldDefn(8).GetSubType() != ogr.OFSTFloat32: - gdaltest.post_reason('fail') - return 'fail' + assert feat.GetFID() == 1 + assert sql_lyr.GetFeatureCount() == 11 + assert sql_lyr.GetLayerDefn().GetFieldCount() == 10 + assert sql_lyr.GetLayerDefn().GetFieldDefn(6).GetSubType() == ogr.OFSTBoolean + assert sql_lyr.GetLayerDefn().GetFieldDefn(7).GetSubType() == ogr.OFSTInt16 + assert sql_lyr.GetLayerDefn().GetFieldDefn(8).GetSubType() == ogr.OFSTFloat32 gdaltest.gpkg_ds.ReleaseResultSet(sql_lyr) sql_lyr = gdaltest.gpkg_ds.ExecuteSQL( @@ -692,55 +555,24 @@ def ogr_gpkg_12(): 'CAST(fld_binary as BLOB) as FLD_BINARY, ' 'CAST(fld_integer64 AS INTEGER) AS FLD_INTEGER64 ' 'FROM tbl_linestring_renamed') - if sql_lyr.GetFIDColumn() != 'FID': - gdaltest.post_reason('fail') - print(sql_lyr.GetFIDColumn()) - return 'fail' - if sql_lyr.GetGeometryColumn() != 'GEOM': - gdaltest.post_reason('fail') - print(sql_lyr.GetGeometryColumn()) - return 'fail' - if sql_lyr.GetLayerDefn().GetFieldCount() != 5: - gdaltest.post_reason('fail') - print(sql_lyr.GetLayerDefn().GetFieldCount()) - return 'fail' - if sql_lyr.GetLayerDefn().GetFieldDefn(0).GetName() != 'FLD_INTEGER': - gdaltest.post_reason('fail') - return 'fail' - if sql_lyr.GetLayerDefn().GetFieldDefn(0).GetType() != ogr.OFTInteger: - gdaltest.post_reason('fail') - return 'fail' - if sql_lyr.GetLayerDefn().GetFieldDefn(1).GetName() != 'FLD_STRING': - gdaltest.post_reason('fail') - return 'fail' - if sql_lyr.GetLayerDefn().GetFieldDefn(1).GetType() != ogr.OFTString: - gdaltest.post_reason('fail') - return 'fail' - if sql_lyr.GetLayerDefn().GetFieldDefn(2).GetName() != 'FLD_REAL': - gdaltest.post_reason('fail') - return 'fail' - if sql_lyr.GetLayerDefn().GetFieldDefn(2).GetType() != ogr.OFTReal: - gdaltest.post_reason('fail') - return 'fail' - if sql_lyr.GetLayerDefn().GetFieldDefn(3).GetName() != 'FLD_BINARY': - gdaltest.post_reason('fail') - return 'fail' - if sql_lyr.GetLayerDefn().GetFieldDefn(3).GetType() != ogr.OFTBinary: - gdaltest.post_reason('fail') - return 'fail' - if sql_lyr.GetLayerDefn().GetFieldDefn(4).GetName() != 'FLD_INTEGER64': - gdaltest.post_reason('fail') - return 'fail' - if sql_lyr.GetLayerDefn().GetFieldDefn(4).GetType() != ogr.OFTInteger64: - gdaltest.post_reason('fail') - return 'fail' + assert sql_lyr.GetFIDColumn() == 'FID' + assert sql_lyr.GetGeometryColumn() == 'GEOM' + assert sql_lyr.GetLayerDefn().GetFieldCount() == 5 + assert sql_lyr.GetLayerDefn().GetFieldDefn(0).GetName() == 'FLD_INTEGER' + assert sql_lyr.GetLayerDefn().GetFieldDefn(0).GetType() == ogr.OFTInteger + assert sql_lyr.GetLayerDefn().GetFieldDefn(1).GetName() == 'FLD_STRING' + assert sql_lyr.GetLayerDefn().GetFieldDefn(1).GetType() == ogr.OFTString + assert sql_lyr.GetLayerDefn().GetFieldDefn(2).GetName() == 'FLD_REAL' + assert sql_lyr.GetLayerDefn().GetFieldDefn(2).GetType() == ogr.OFTReal + assert sql_lyr.GetLayerDefn().GetFieldDefn(3).GetName() == 'FLD_BINARY' + assert sql_lyr.GetLayerDefn().GetFieldDefn(3).GetType() == ogr.OFTBinary + assert sql_lyr.GetLayerDefn().GetFieldDefn(4).GetName() == 'FLD_INTEGER64' + assert sql_lyr.GetLayerDefn().GetFieldDefn(4).GetType() == ogr.OFTInteger64 gdaltest.gpkg_ds.ReleaseResultSet(sql_lyr) sql_lyr = gdaltest.gpkg_ds.ExecuteSQL('SELECT * FROM tbl_linestring_renamed WHERE 0=1') feat = sql_lyr.GetNextFeature() - if feat is not None: - gdaltest.post_reason('fail') - return 'fail' + assert feat is None gdaltest.gpkg_ds.ReleaseResultSet(sql_lyr) for sql in ['SELECT * FROM tbl_linestring_renamed LIMIT 1', @@ -748,41 +580,27 @@ def ogr_gpkg_12(): 'SELECT * FROM tbl_linestring_renamed UNION ALL SELECT * FROM tbl_linestring_renamed ORDER BY fld_integer LIMIT 1']: sql_lyr = gdaltest.gpkg_ds.ExecuteSQL(sql) feat = sql_lyr.GetNextFeature() - if feat is None: - gdaltest.post_reason('fail') - return 'fail' + assert feat is not None feat = sql_lyr.GetNextFeature() - if feat is not None: - gdaltest.post_reason('fail') - return 'fail' - if sql_lyr.GetFeatureCount() != 1: - gdaltest.post_reason('fail') - return 'fail' + assert feat is None + assert sql_lyr.GetFeatureCount() == 1 gdaltest.gpkg_ds.ReleaseResultSet(sql_lyr) sql_lyr = gdaltest.gpkg_ds.ExecuteSQL('SELECT sqlite_version()') feat = sql_lyr.GetNextFeature() - if feat is None: - gdaltest.post_reason('fail') - return 'fail' - if sql_lyr.GetLayerDefn().GetFieldCount() != 1: - gdaltest.post_reason('fail') - return 'fail' - if sql_lyr.GetLayerDefn().GetGeomFieldCount() != 0: - gdaltest.post_reason('fail') - return 'fail' + assert feat is not None + assert sql_lyr.GetLayerDefn().GetFieldCount() == 1 + assert sql_lyr.GetLayerDefn().GetGeomFieldCount() == 0 gdaltest.gpkg_ds.ReleaseResultSet(sql_lyr) - return 'success' - ############################################################################### # Test non-spatial tables -def ogr_gpkg_13(): +def test_ogr_gpkg_13(): if gdaltest.gpkg_dr is None: - return 'skip' + pytest.skip() lyr = gdaltest.gpkg_ds.CreateLayer('non_spatial', geom_type=ogr.wkbNone, options=['ASPATIAL_VARIANT=OGR_ASPATIAL']) feat = ogr.Feature(lyr.GetLayerDefn()) @@ -797,63 +615,46 @@ def ogr_gpkg_13(): feat = lyr.GetNextFeature() if not feat.IsFieldNull('fld_integer'): feat.DumpReadable() - gdaltest.post_reason('fail') - return 'fail' + pytest.fail() feat = lyr.GetNextFeature() if feat.GetField('fld_integer') != 1: feat.DumpReadable() - gdaltest.post_reason('fail') - return 'fail' + pytest.fail() # Test second aspatial layer lyr = gdaltest.gpkg_ds.CreateLayer('non_spatial2', geom_type=ogr.wkbNone, options=['ASPATIAL_VARIANT=OGR_ASPATIAL']) gdaltest.gpkg_ds = None gdaltest.gpkg_ds = ogr.Open('tmp/gpkg_test.gpkg', update=1) - if gdal.GetLastErrorMsg() != '': - gdaltest.post_reason('fail : warning NOT expected') - return 'fail' - if gdaltest.gpkg_ds.GetLayerCount() != 5: - gdaltest.post_reason('fail') - return 'fail' + assert gdal.GetLastErrorMsg() == '', 'fail : warning NOT expected' + assert gdaltest.gpkg_ds.GetLayerCount() == 5 lyr = gdaltest.gpkg_ds.GetLayer('non_spatial') - if lyr.GetGeomType() != ogr.wkbNone: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.GetGeomType() == ogr.wkbNone feat = lyr.GetNextFeature() - if not feat.IsFieldNull('fld_integer'): - gdaltest.post_reason('fail') - return 'fail' + assert feat.IsFieldNull('fld_integer') feat = lyr.GetNextFeature() if feat.GetField('fld_integer') != 1: feat.DumpReadable() - gdaltest.post_reason('fail') - return 'fail' + pytest.fail() sql_lyr = gdaltest.gpkg_ds.ExecuteSQL("SELECT * FROM gpkg_extensions WHERE table_name IS NULL AND extension_name = 'gdal_aspatial'") - if sql_lyr.GetFeatureCount() != 1: - gdaltest.post_reason('fail') - return 'fail' + assert sql_lyr.GetFeatureCount() == 1 gdaltest.gpkg_ds.ReleaseResultSet(sql_lyr) - return 'success' - ############################################################################### # Add various geometries to test spatial filtering -def ogr_gpkg_14(): +def test_ogr_gpkg_14(): if gdaltest.gpkg_dr is None: - return 'skip' + pytest.skip() sr = osr.SpatialReference() sr.ImportFromEPSG(32631) lyr = gdaltest.gpkg_ds.CreateLayer('point_no_spi-but-with-dashes', geom_type=ogr.wkbPoint, options=['SPATIAL_INDEX=NO'], srs=sr) - if lyr.TestCapability(ogr.OLCFastSpatialFilter) != 0: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.TestCapability(ogr.OLCFastSpatialFilter) == 0 feat = ogr.Feature(lyr.GetLayerDefn()) feat.SetGeometry(ogr.CreateGeometryFromWkt('POINT(1000 30000000)')) lyr.CreateFeature(feat) @@ -876,27 +677,21 @@ def ogr_gpkg_14(): f = lyr.GetFeature(5) if f.GetGeometryRef() is not None: - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' + pytest.fail() f = lyr.GetFeature(6) if f.GetGeometryRef().ExportToWkt() != 'POINT EMPTY': - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' + pytest.fail() f = None sql_lyr = gdaltest.gpkg_ds.ExecuteSQL('SELECT * FROM "point_no_spi-but-with-dashes"') res = sql_lyr.TestCapability(ogr.OLCFastSpatialFilter) gdaltest.gpkg_ds.ReleaseResultSet(sql_lyr) - if res != 0: - gdaltest.post_reason('fail') - return 'fail' + assert res == 0 lyr = gdaltest.gpkg_ds.CreateLayer('point-with-spi-and-dashes', geom_type=ogr.wkbPoint) - if lyr.TestCapability(ogr.OLCFastSpatialFilter) != 1: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.TestCapability(ogr.OLCFastSpatialFilter) == 1 feat = ogr.Feature(lyr.GetLayerDefn()) feat.SetGeometry(ogr.CreateGeometryFromWkt('POINT(1000 30000000)')) lyr.CreateFeature(feat) @@ -920,32 +715,24 @@ def ogr_gpkg_14(): sql_lyr = gdaltest.gpkg_ds.ExecuteSQL('SELECT * FROM "point-with-spi-and-dashes"') res = sql_lyr.TestCapability(ogr.OLCFastSpatialFilter) gdaltest.gpkg_ds.ReleaseResultSet(sql_lyr) - if res != 1: - gdaltest.post_reason('fail') - return 'fail' + assert res == 1 # Test spatial filer right away lyr.SetSpatialFilterRect(1000, 30000000, 1000, 30000000) lyr.ResetReading() f = lyr.GetNextFeature() - if f is None: - gdaltest.post_reason('fail') - return 'fail' + assert f is not None f = lyr.GetNextFeature() - if f is not None: - gdaltest.post_reason('fail') - return 'fail' - - return 'success' + assert f is None ############################################################################### # Test SQL functions -def ogr_gpkg_15(): +def test_ogr_gpkg_15(): if gdaltest.gpkg_dr is None: - return 'skip' + pytest.skip() sql_lyr = gdaltest.gpkg_ds.ExecuteSQL( 'SELECT ST_IsEmpty(geom), ST_SRID(geom), ST_GeometryType(geom), ' + @@ -956,8 +743,7 @@ def ogr_gpkg_15(): feat.GetField(3) != 1000 or feat.GetField(4) != 30000000 or \ feat.GetField(5) != 1000 or feat.GetField(6) != 30000000: feat.DumpReadable() - gdaltest.post_reason('fail') - return 'fail' + pytest.fail() gdaltest.gpkg_ds.ReleaseResultSet(sql_lyr) sql_lyr = gdaltest.gpkg_ds.ExecuteSQL( @@ -967,8 +753,7 @@ def ogr_gpkg_15(): if not feat.IsFieldNull(0) or not feat.IsFieldNull(1) or not feat.IsFieldNull(2) or \ not feat.IsFieldNull(3) or not feat.IsFieldNull(4) or not feat.IsFieldNull(5) or not feat.IsFieldNull(6): feat.DumpReadable() - gdaltest.post_reason('fail') - return 'fail' + pytest.fail() gdaltest.gpkg_ds.ReleaseResultSet(sql_lyr) for (expected_type, actual_type, expected_result) in [ @@ -982,10 +767,8 @@ def ogr_gpkg_15(): feat = sql_lyr.GetNextFeature() got_result = feat.GetField(0) gdaltest.gpkg_ds.ReleaseResultSet(sql_lyr) - if got_result != expected_result: - print("expected_type=%s actual_type=%s expected_result=%d got_result=%d" % (expected_type, actual_type, expected_result, got_result)) - gdaltest.post_reason('fail') - return 'fail' + assert got_result == expected_result, \ + ("expected_type=%s actual_type=%s expected_result=%d got_result=%d" % (expected_type, actual_type, expected_result, got_result)) for (sql, expected_result) in [ ("SELECT HasSpatialIndex('point-with-spi-and-dashes', 'geom')", 1), @@ -1020,72 +803,62 @@ def ogr_gpkg_15(): feat = sql_lyr.GetNextFeature() got_result = feat.GetField(0) gdaltest.gpkg_ds.ReleaseResultSet(sql_lyr) - if got_result != expected_result: - print(sql) - gdaltest.post_reason('fail') - return 'fail' + assert got_result == expected_result, sql # NULL argument sql_lyr = gdaltest.gpkg_ds.ExecuteSQL("SELECT SridFromAuthCRS(NULL, 4326)") feat = sql_lyr.GetNextFeature() if feat.GetField(0) != -1: - gdaltest.post_reason('fail') feat.DumpReadable() - return 'fail' + pytest.fail() gdaltest.gpkg_ds.ReleaseResultSet(sql_lyr) # NULL argument sql_lyr = gdaltest.gpkg_ds.ExecuteSQL("SELECT SridFromAuthCRS('epsg', NULL)") feat = sql_lyr.GetNextFeature() if feat.GetField(0) != -1: - gdaltest.post_reason('fail') feat.DumpReadable() - return 'fail' + pytest.fail() gdaltest.gpkg_ds.ReleaseResultSet(sql_lyr) # Existing entry sql_lyr = gdaltest.gpkg_ds.ExecuteSQL("SELECT SridFromAuthCRS('epsg', 4326)") feat = sql_lyr.GetNextFeature() if feat.GetField(0) != 4326: - gdaltest.post_reason('fail') feat.DumpReadable() - return 'fail' + pytest.fail() gdaltest.gpkg_ds.ReleaseResultSet(sql_lyr) # Non existing entry sql_lyr = gdaltest.gpkg_ds.ExecuteSQL("SELECT SridFromAuthCRS('epsg', 1234)") feat = sql_lyr.GetNextFeature() if feat.GetField(0) != -1: - gdaltest.post_reason('fail') feat.DumpReadable() - return 'fail' + pytest.fail() gdaltest.gpkg_ds.ReleaseResultSet(sql_lyr) # NULL argument sql_lyr = gdaltest.gpkg_ds.ExecuteSQL("SELECT ImportFromEPSG(NULL)") feat = sql_lyr.GetNextFeature() if feat.GetField(0) != -1: - gdaltest.post_reason('fail') feat.DumpReadable() - return 'fail' + pytest.fail() gdaltest.gpkg_ds.ReleaseResultSet(sql_lyr) # Existing entry in gpkg_spatial_ref_sys sql_lyr = gdaltest.gpkg_ds.ExecuteSQL("SELECT ImportFromEPSG(4326)") feat = sql_lyr.GetNextFeature() if feat.GetField(0) != 4326: - gdaltest.post_reason('fail') feat.DumpReadable() - return 'fail' + pytest.fail() gdaltest.gpkg_ds.ReleaseResultSet(sql_lyr) # New entry in gpkg_spatial_ref_sys sql_lyr = gdaltest.gpkg_ds.ExecuteSQL("SELECT ImportFromEPSG(32633)") feat = sql_lyr.GetNextFeature() if feat.GetField(0) != 32633: - gdaltest.post_reason('fail') feat.DumpReadable() - return 'fail' + pytest.fail() gdaltest.gpkg_ds.ReleaseResultSet(sql_lyr) # Invalid code @@ -1093,18 +866,16 @@ def ogr_gpkg_15(): sql_lyr = gdaltest.gpkg_ds.ExecuteSQL("SELECT ImportFromEPSG(0)") feat = sql_lyr.GetNextFeature() if feat.GetField(0) != -1: - gdaltest.post_reason('fail') feat.DumpReadable() - return 'fail' + pytest.fail() gdaltest.gpkg_ds.ReleaseResultSet(sql_lyr) # NULL argument sql_lyr = gdaltest.gpkg_ds.ExecuteSQL("SELECT ST_Transform(NULL, 4326)") feat = sql_lyr.GetNextFeature() if feat.GetGeometryRef() is not None: - gdaltest.post_reason('fail') feat.DumpReadable() - return 'fail' + pytest.fail() gdaltest.gpkg_ds.ReleaseResultSet(sql_lyr) # Invalid geometry @@ -1112,18 +883,16 @@ def ogr_gpkg_15(): sql_lyr = gdaltest.gpkg_ds.ExecuteSQL("SELECT ST_Transform(x'00', 4326)") feat = sql_lyr.GetNextFeature() if feat.GetGeometryRef() is not None: - gdaltest.post_reason('fail') feat.DumpReadable() - return 'fail' + pytest.fail() gdaltest.gpkg_ds.ReleaseResultSet(sql_lyr) # NULL argument sql_lyr = gdaltest.gpkg_ds.ExecuteSQL("SELECT ST_Transform(geom, NULL) FROM tbl_linestring_renamed") feat = sql_lyr.GetNextFeature() if feat.GetGeometryRef() is not None: - gdaltest.post_reason('fail') feat.DumpReadable() - return 'fail' + pytest.fail() gdaltest.gpkg_ds.ReleaseResultSet(sql_lyr) # Invalid target SRID @@ -1131,9 +900,8 @@ def ogr_gpkg_15(): sql_lyr = gdaltest.gpkg_ds.ExecuteSQL("SELECT ST_Transform(geom, 0) FROM tbl_linestring_renamed") feat = sql_lyr.GetNextFeature() if feat.GetGeometryRef() is not None: - gdaltest.post_reason('fail') feat.DumpReadable() - return 'fail' + pytest.fail() gdaltest.gpkg_ds.ReleaseResultSet(sql_lyr) # Invalid source SRID @@ -1141,9 +909,8 @@ def ogr_gpkg_15(): sql_lyr = gdaltest.gpkg_ds.ExecuteSQL("SELECT ST_Transform(geom, 4326) FROM \"point-with-spi-and-dashes\"") feat = sql_lyr.GetNextFeature() if feat.GetGeometryRef() is not None: - gdaltest.post_reason('fail') feat.DumpReadable() - return 'fail' + pytest.fail() gdaltest.gpkg_ds.ReleaseResultSet(sql_lyr) # Invalid spatialite geometry: SRID=4326,MULTIPOINT EMPTY truncated @@ -1151,44 +918,39 @@ def ogr_gpkg_15(): sql_lyr = gdaltest.gpkg_ds.ExecuteSQL("SELECT ST_Transform(x'0001E610000000000000000000000000000000000000000000000000000000000000000000007C04000000000000FE', 4326) FROM tbl_linestring_renamed") feat = sql_lyr.GetNextFeature() if feat.GetGeometryRef() is not None: - gdaltest.post_reason('fail') feat.DumpReadable() - return 'fail' + pytest.fail() gdaltest.gpkg_ds.ReleaseResultSet(sql_lyr) if osr_proj4.have_proj480(): sql_lyr = gdaltest.gpkg_ds.ExecuteSQL("SELECT ST_Transform(geom, ST_SRID(geom)) FROM tbl_linestring_renamed") feat = sql_lyr.GetNextFeature() if feat.GetGeometryRef().ExportToWkt() != 'LINESTRING (5 5,10 5,10 10,5 10)': - gdaltest.post_reason('fail') feat.DumpReadable() - return 'fail' + pytest.fail() gdaltest.gpkg_ds.ReleaseResultSet(sql_lyr) sql_lyr = gdaltest.gpkg_ds.ExecuteSQL("SELECT ST_SRID(ST_Transform(geom, 4326)) FROM tbl_linestring_renamed") feat = sql_lyr.GetNextFeature() if feat.GetField(0) != 4326: - gdaltest.post_reason('fail') feat.DumpReadable() - return 'fail' + pytest.fail() gdaltest.gpkg_ds.ReleaseResultSet(sql_lyr) # Spatialite geometry: SRID=4326,MULTIPOINT EMPTY sql_lyr = gdaltest.gpkg_ds.ExecuteSQL("SELECT ST_SRID(ST_Transform(x'0001E610000000000000000000000000000000000000000000000000000000000000000000007C0400000000000000FE', 4326)) FROM tbl_linestring_renamed") feat = sql_lyr.GetNextFeature() if feat.GetField(0) != 4326: - gdaltest.post_reason('fail') feat.DumpReadable() - return 'fail' + pytest.fail() gdaltest.gpkg_ds.ReleaseResultSet(sql_lyr) # Error case: less than 8 bytes sql_lyr = gdaltest.gpkg_ds.ExecuteSQL("SELECT ST_MinX(x'00')") feat = sql_lyr.GetNextFeature() if feat.IsFieldSetAndNotNull(0): - gdaltest.post_reason('fail') feat.DumpReadable() - return 'fail' + pytest.fail() feat = None gdaltest.gpkg_ds.ReleaseResultSet(sql_lyr) @@ -1196,9 +958,8 @@ def ogr_gpkg_15(): sql_lyr = gdaltest.gpkg_ds.ExecuteSQL("SELECT ST_MinX(x'0001020304050607')") feat = sql_lyr.GetNextFeature() if feat.IsFieldSetAndNotNull(0): - gdaltest.post_reason('fail') feat.DumpReadable() - return 'fail' + pytest.fail() feat = None gdaltest.gpkg_ds.ReleaseResultSet(sql_lyr) @@ -1206,9 +967,8 @@ def ogr_gpkg_15(): sql_lyr = gdaltest.gpkg_ds.ExecuteSQL("SELECT ST_GeometryType(x'4750001100000000')") feat = sql_lyr.GetNextFeature() if feat.IsFieldSetAndNotNull(0): - gdaltest.post_reason('fail') feat.DumpReadable() - return 'fail' + pytest.fail() feat = None gdaltest.gpkg_ds.ReleaseResultSet(sql_lyr) @@ -1216,9 +976,8 @@ def ogr_gpkg_15(): sql_lyr = gdaltest.gpkg_ds.ExecuteSQL("SELECT ST_GeometryType(x'475000110000000001040000')") feat = sql_lyr.GetNextFeature() if feat.IsFieldSetAndNotNull(0): - gdaltest.post_reason('fail') feat.DumpReadable() - return 'fail' + pytest.fail() feat = None gdaltest.gpkg_ds.ReleaseResultSet(sql_lyr) @@ -1226,9 +985,8 @@ def ogr_gpkg_15(): sql_lyr = gdaltest.gpkg_ds.ExecuteSQL("SELECT ST_GeometryType(x'47500011000000000104000000')") feat = sql_lyr.GetNextFeature() if feat.GetField(0) != 'MULTIPOINT': - gdaltest.post_reason('fail') feat.DumpReadable() - return 'fail' + pytest.fail() feat = None gdaltest.gpkg_ds.ReleaseResultSet(sql_lyr) @@ -1236,9 +994,8 @@ def ogr_gpkg_15(): sql_lyr = gdaltest.gpkg_ds.ExecuteSQL("SELECT ST_GeometryType(x'00010000000000000000000000000000000000000000000000000000000000000000000000007C0400000000000000FE')") feat = sql_lyr.GetNextFeature() if feat.GetField(0) != 'MULTIPOINT': - gdaltest.post_reason('fail') feat.DumpReadable() - return 'fail' + pytest.fail() feat = None gdaltest.gpkg_ds.ReleaseResultSet(sql_lyr) @@ -1246,9 +1003,8 @@ def ogr_gpkg_15(): sql_lyr = gdaltest.gpkg_ds.ExecuteSQL("SELECT ST_IsEmpty(x'00010000000000000000000000000000000000000000000000000000000000000000000000007C0400000000000000FE')") feat = sql_lyr.GetNextFeature() if feat.GetField(0) != 1: - gdaltest.post_reason('fail') feat.DumpReadable() - return 'fail' + pytest.fail() feat = None gdaltest.gpkg_ds.ReleaseResultSet(sql_lyr) @@ -1257,9 +1013,8 @@ def ogr_gpkg_15(): sql_lyr = gdaltest.gpkg_ds.ExecuteSQL("SELECT ST_GeometryType(x'475000030000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000')") feat = sql_lyr.GetNextFeature() if feat.IsFieldSetAndNotNull(0): - gdaltest.post_reason('fail') feat.DumpReadable() - return 'fail' + pytest.fail() feat = None gdaltest.gpkg_ds.ReleaseResultSet(sql_lyr) @@ -1279,9 +1034,8 @@ def ogr_gpkg_15(): sql_lyr = gdaltest.gpkg_ds.ExecuteSQL("SELECT hstore_get_value('a=>b', 'a')") feat = sql_lyr.GetNextFeature() if feat.GetField(0) != 'b': - gdaltest.post_reason('fail') feat.DumpReadable() - return 'fail' + pytest.fail() feat = None gdaltest.gpkg_ds.ReleaseResultSet(sql_lyr) @@ -1289,9 +1043,8 @@ def ogr_gpkg_15(): sql_lyr = gdaltest.gpkg_ds.ExecuteSQL("SELECT hstore_get_value('a=>b', 'x')") feat = sql_lyr.GetNextFeature() if feat.GetField(0) is not None: - gdaltest.post_reason('fail') feat.DumpReadable() - return 'fail' + pytest.fail() feat = None gdaltest.gpkg_ds.ReleaseResultSet(sql_lyr) @@ -1299,9 +1052,8 @@ def ogr_gpkg_15(): sql_lyr = gdaltest.gpkg_ds.ExecuteSQL("SELECT hstore_get_value('a=>b', NULL)") feat = sql_lyr.GetNextFeature() if feat.GetField(0) is not None: - gdaltest.post_reason('fail') feat.DumpReadable() - return 'fail' + pytest.fail() feat = None gdaltest.gpkg_ds.ReleaseResultSet(sql_lyr) @@ -1309,9 +1061,8 @@ def ogr_gpkg_15(): sql_lyr = gdaltest.gpkg_ds.ExecuteSQL("SELECT hstore_get_value(NULL, 'a')") feat = sql_lyr.GetNextFeature() if feat.GetField(0) is not None: - gdaltest.post_reason('fail') feat.DumpReadable() - return 'fail' + pytest.fail() feat = None gdaltest.gpkg_ds.ReleaseResultSet(sql_lyr) @@ -1330,29 +1081,21 @@ def ogr_gpkg_15(): if has_spatialite_4_3_or_later: sql_lyr = gdaltest.gpkg_ds.ExecuteSQL( "SELECT ST_Buffer(geom, 0) FROM tbl_linestring_renamed") - if sql_lyr.GetGeomType() != ogr.wkbPolygon: - gdaltest.post_reason('fail') - print(sql_lyr.GetGeomType()) - return 'fail' - if sql_lyr.GetSpatialRef().ExportToWkt().find('32631') < 0: - gdaltest.post_reason('fail') - print(sql_lyr.GetSpatialRef()) - return 'fail' + assert sql_lyr.GetGeomType() == ogr.wkbPolygon + assert sql_lyr.GetSpatialRef().ExportToWkt().find('32631') >= 0 gdaltest.gpkg_ds.ReleaseResultSet(sql_lyr) gdaltest.gpkg_ds = None gdaltest.gpkg_ds = gdaltest.gpkg_dr.Open('tmp/gpkg_test.gpkg', update=1) - return 'success' - ############################################################################### # Test unknown extensions -def ogr_gpkg_16(): +def test_ogr_gpkg_16(): if gdaltest.gpkg_dr is None: - return 'skip' + pytest.skip() ds = gdaltest.gpkg_dr.CreateDataSource('/vsimem/ogr_gpk_16.gpkg') ds.CreateLayer('foo') @@ -1365,9 +1108,7 @@ def ogr_gpkg_16(): lyr = ds.GetLayer(0) lyr.GetLayerDefn() ds = None - if gdal.GetLastErrorMsg() != '': - gdaltest.post_reason('fail : warning NOT expected') - return 'fail' + assert gdal.GetLastErrorMsg() == '', 'fail : warning NOT expected' # Warning since we open as read-write ds = ogr.Open('/vsimem/ogr_gpk_16.gpkg', update=1) @@ -1375,9 +1116,7 @@ def ogr_gpkg_16(): gdal.PushErrorHandler('CPLQuietErrorHandler') lyr.GetLayerDefn() gdal.PopErrorHandler() - if gdal.GetLastErrorMsg() == '': - gdaltest.post_reason('fail : warning expected') - return 'fail' + assert gdal.GetLastErrorMsg() != '', 'fail : warning expected' ds.ExecuteSQL("UPDATE gpkg_extensions SET scope = 'read-write' WHERE extension_name = 'myext'") ds = None @@ -1388,9 +1127,7 @@ def ogr_gpkg_16(): gdal.PushErrorHandler('CPLQuietErrorHandler') lyr.GetLayerDefn() gdal.PopErrorHandler() - if gdal.GetLastErrorMsg() == '': - gdaltest.post_reason('fail : warning expected') - return 'fail' + assert gdal.GetLastErrorMsg() != '', 'fail : warning expected' # and also as read-write ds = ogr.Open('/vsimem/ogr_gpk_16.gpkg', update=1) @@ -1398,9 +1135,7 @@ def ogr_gpkg_16(): gdal.PushErrorHandler('CPLQuietErrorHandler') lyr.GetLayerDefn() gdal.PopErrorHandler() - if gdal.GetLastErrorMsg() == '': - gdaltest.post_reason('fail : warning expected') - return 'fail' + assert gdal.GetLastErrorMsg() != '', 'fail : warning expected' ds = None gdal.Unlink('/vsimem/ogr_gpk_16.gpkg') @@ -1417,9 +1152,7 @@ def ogr_gpkg_16(): gdal.PushErrorHandler('CPLQuietErrorHandler') lyr.GetLayerDefn() gdal.PopErrorHandler() - if gdal.GetLastErrorMsg() == '': - gdaltest.post_reason('fail : warning expected') - return 'fail' + assert gdal.GetLastErrorMsg() != '', 'fail : warning expected' gdal.Unlink('/vsimem/ogr_gpk_16.gpkg') @@ -1434,17 +1167,13 @@ def ogr_gpkg_16(): ds = ogr.Open('/vsimem/ogr_gpk_16.gpkg') lyr = ds.GetLayer(0) lyr.GetLayerDefn() - if gdal.GetLastErrorMsg() != '': - gdaltest.post_reason('fail : warning NOT expected') - return 'fail' + assert gdal.GetLastErrorMsg() == '', 'fail : warning NOT expected' # Warning since we open as read-write gdal.PushErrorHandler('CPLQuietErrorHandler') ds = ogr.Open('/vsimem/ogr_gpk_16.gpkg', update=1) gdal.PopErrorHandler() - if gdal.GetLastErrorMsg() == '': - gdaltest.post_reason('fail : warning expected') - return 'fail' + assert gdal.GetLastErrorMsg() != '', 'fail : warning expected' ds.ExecuteSQL("UPDATE gpkg_extensions SET scope = 'read-write' WHERE extension_name = 'myext'") ds = None @@ -1453,51 +1182,43 @@ def ogr_gpkg_16(): gdal.PushErrorHandler('CPLQuietErrorHandler') ds = ogr.Open('/vsimem/ogr_gpk_16.gpkg') gdal.PopErrorHandler() - if gdal.GetLastErrorMsg() == '': - gdaltest.post_reason('fail : warning expected') - return 'fail' + assert gdal.GetLastErrorMsg() != '', 'fail : warning expected' # and also as read-write gdal.PushErrorHandler('CPLQuietErrorHandler') ds = ogr.Open('/vsimem/ogr_gpk_16.gpkg', update=1) gdal.PopErrorHandler() - if gdal.GetLastErrorMsg() == '': - gdaltest.post_reason('fail : warning expected') - return 'fail' + assert gdal.GetLastErrorMsg() != '', 'fail : warning expected' ds = None gdal.Unlink('/vsimem/ogr_gpk_16.gpkg') - return 'success' - ############################################################################### # Run INDIRECT_SQLITE dialect -def ogr_gpkg_17(): +def test_ogr_gpkg_17(): if gdaltest.gpkg_dr is None: - return 'skip' + pytest.skip() ds = gdaltest.gpkg_dr.CreateDataSource('/vsimem/ogr_gpkg_17.gpkg') sql_lyr = ds.ExecuteSQL("SELECT ogr_version()", dialect='INDIRECT_SQLITE') f = sql_lyr.GetNextFeature() - if f is None: - return 'fail' + assert f is not None ds.ReleaseResultSet(sql_lyr) ds = None gdal.Unlink('/vsimem/ogr_gpkg_17.gpkg') - return 'success' ############################################################################### # Test geometry type extension -def ogr_gpkg_18(): +def test_ogr_gpkg_18(): if gdaltest.gpkg_dr is None: - return 'skip' + pytest.skip() ds = gdaltest.gpkg_dr.CreateDataSource('/vsimem/ogr_gpkg_18.gpkg') lyr = ds.CreateLayer('wkbCircularString', geom_type=ogr.wkbCircularString) @@ -1507,29 +1228,19 @@ def ogr_gpkg_18(): f = None ds = None - if not validate('/vsimem/ogr_gpkg_18.gpkg'): - gdaltest.post_reason('validation failed') - return 'fail' + assert validate('/vsimem/ogr_gpkg_18.gpkg'), 'validation failed' ds = ogr.Open('/vsimem/ogr_gpkg_18.gpkg') - if gdal.GetLastErrorMsg() != '': - gdaltest.post_reason('fail : warning NOT expected') - return 'fail' + assert gdal.GetLastErrorMsg() == '', 'fail : warning NOT expected' lyr = ds.GetLayer(0) - if lyr.GetGeomType() != ogr.wkbCircularString: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.GetGeomType() == ogr.wkbCircularString f = lyr.GetNextFeature() g = f.GetGeometryRef() - if g.GetGeometryType() != ogr.wkbCircularString: - gdaltest.post_reason('fail') - return 'fail' + assert g.GetGeometryType() == ogr.wkbCircularString sql_lyr = ds.ExecuteSQL("SELECT * FROM gpkg_extensions WHERE table_name = 'wkbCircularString' AND extension_name = 'gpkg_geom_CIRCULARSTRING'") - if sql_lyr.GetFeatureCount() != 1: - gdaltest.post_reason('fail') - return 'fail' + assert sql_lyr.GetFeatureCount() == 1 ds.ReleaseResultSet(sql_lyr) ds = None @@ -1544,24 +1255,18 @@ def ogr_gpkg_18(): f = None sql_lyr = ds.ExecuteSQL("SELECT * FROM gpkg_extensions WHERE table_name = 'test' AND extension_name = 'gpkg_geom_CIRCULARSTRING'") - if sql_lyr.GetFeatureCount() != 1: - gdaltest.post_reason('fail') - return 'fail' + assert sql_lyr.GetFeatureCount() == 1 ds.ReleaseResultSet(sql_lyr) ds = None ds = ogr.Open('/vsimem/ogr_gpkg_18.gpkg') - if gdal.GetLastErrorMsg() != '': - gdaltest.post_reason('fail : warning NOT expected') - return 'fail' + assert gdal.GetLastErrorMsg() == '', 'fail : warning NOT expected' lyr = ds.GetLayer(0) f = lyr.GetNextFeature() g = f.GetGeometryRef() - if g.GetGeometryType() != ogr.wkbCircularString: - gdaltest.post_reason('fail') - return 'fail' + assert g.GetGeometryType() == ogr.wkbCircularString ds = None @@ -1570,9 +1275,7 @@ def ogr_gpkg_18(): f = ogr.Feature(lyr.GetLayerDefn()) f.SetGeometry(ogr.CreateGeometryFromWkt('CIRCULARSTRING(0 0,1 0,0 0)')) ret = lyr.CreateFeature(f) - if ret != 0 or gdal.GetLastErrorMsg() != '': - gdaltest.post_reason('fail') - return 'fail' + assert ret == 0 and gdal.GetLastErrorMsg() == '' f = None ds = None @@ -1582,16 +1285,12 @@ def ogr_gpkg_18(): # Warning 1: Registering non-standard gpkg_geom_TRIANGLE extension ds.FlushCache() sql_lyr = ds.ExecuteSQL("SELECT * FROM gpkg_extensions WHERE table_name = 'test' AND extension_name = 'gpkg_geom_TRIANGLE'") - if sql_lyr.GetFeatureCount() != 1: - gdaltest.post_reason('fail') - return 'fail' + assert sql_lyr.GetFeatureCount() == 1 ds.ReleaseResultSet(sql_lyr) ds = None ret = validate('/vsimem/ogr_gpkg_18.gpkg', quiet=True) - if ret: - gdaltest.post_reason('validation unexpectedly succeeded') - return 'fail' + assert not ret, 'validation unexpectedly succeeded' # Test non-linear geometry in GeometryCollection ds = gdaltest.gpkg_dr.CreateDataSource('/vsimem/ogr_gpkg_18.gpkg') @@ -1601,33 +1300,25 @@ def ogr_gpkg_18(): lyr.CreateFeature(f) f = None sql_lyr = ds.ExecuteSQL("SELECT * FROM gpkg_extensions WHERE table_name = 'test' AND extension_name LIKE 'gpkg_geom_%'") - if sql_lyr.GetFeatureCount() != 1: - gdaltest.post_reason('fail') - return 'fail' + assert sql_lyr.GetFeatureCount() == 1 ds.ReleaseResultSet(sql_lyr) ds = None gdal.Unlink('/vsimem/ogr_gpkg_18.gpkg') - return 'success' - ############################################################################### # Test metadata -def ogr_gpkg_19(): +def test_ogr_gpkg_19(): if gdaltest.gpkg_dr is None: - return 'skip' + pytest.skip() ds = gdaltest.gpkg_dr.CreateDataSource('/vsimem/ogr_gpkg_19.gpkg') - if ds.GetMetadata(): - gdaltest.post_reason('fail') - return 'fail' + assert not ds.GetMetadata() lyr = ds.CreateLayer('test_without_md') - if lyr.GetMetadata(): - gdaltest.post_reason('fail') - return 'fail' + assert not lyr.GetMetadata() ds.SetMetadataItem('foo', 'bar') @@ -1640,22 +1331,13 @@ def ogr_gpkg_19(): ds = None ds = ogr.Open('/vsimem/ogr_gpkg_19.gpkg') - if ds.GetMetadataDomainList() != ['']: - print(ds.GetMetadataDomainList()) - gdaltest.post_reason('fail') - return 'fail' + assert ds.GetMetadataDomainList() == [''] ds = ogr.Open('/vsimem/ogr_gpkg_19.gpkg') - if len(ds.GetMetadata()) != 1: - print(ds.GetMetadata()) - gdaltest.post_reason('fail') - return 'fail' + assert len(ds.GetMetadata()) == 1 ds = ogr.Open('/vsimem/ogr_gpkg_19.gpkg') - if ds.GetMetadataItem('foo') != 'bar': - gdaltest.post_reason('fail') - print(ds.GetMetadata()) - return 'fail' + assert ds.GetMetadataItem('foo') == 'bar', ds.GetMetadata() ds = None ds = ogr.Open('/vsimem/ogr_gpkg_19.gpkg', update=1) @@ -1667,21 +1349,12 @@ def ogr_gpkg_19(): ds = ogr.Open('/vsimem/ogr_gpkg_19.gpkg') lyr = ds.GetLayer('test_with_md') - if lyr.GetMetadataItem('IDENTIFIER') != 'ident': - gdaltest.post_reason('fail') - print(lyr.GetMetadataItem('IDENTIFIER')) - return 'fail' - if lyr.GetMetadataItem('DESCRIPTION') != 'desc': - gdaltest.post_reason('fail') - print(lyr.GetMetadataItem('DESCRIPTION')) - return 'fail' + assert lyr.GetMetadataItem('IDENTIFIER') == 'ident' + assert lyr.GetMetadataItem('DESCRIPTION') == 'desc' ds = ogr.Open('/vsimem/ogr_gpkg_19.gpkg', update=1) lyr = ds.GetLayer('test_with_md') - if lyr.GetMetadata() != {'IDENTIFIER': 'ident', 'DESCRIPTION': 'desc'}: - gdaltest.post_reason('fail') - print(lyr.GetMetadata()) - return 'fail' + assert lyr.GetMetadata() == {'IDENTIFIER': 'ident', 'DESCRIPTION': 'desc'} lyr.SetMetadataItem('IDENTIFIER', 'another_ident') lyr.SetMetadataItem('DESCRIPTION', 'another_desc') ds = None @@ -1691,65 +1364,43 @@ def ogr_gpkg_19(): ds = ogr.Open('/vsimem/ogr_gpkg_19.gpkg', update=1) lyr = ds.GetLayer('test_with_md') - if lyr.GetMetadata() != {'IDENTIFIER': 'another_ident', 'DESCRIPTION': 'another_desc'}: - gdaltest.post_reason('fail') - print(lyr.GetMetadata()) - return 'fail' + assert lyr.GetMetadata() == {'IDENTIFIER': 'another_ident', 'DESCRIPTION': 'another_desc'} lyr.SetMetadataItem('foo', 'bar') lyr.SetMetadataItem('bar', 'baz', 'another_domain') ds = None ds = ogr.Open('/vsimem/ogr_gpkg_19.gpkg', update=1) lyr = ds.GetLayer('test_with_md') - if lyr.GetMetadataDomainList() != ['', 'another_domain']: - gdaltest.post_reason('fail') - print(lyr.GetMetadataDomainList()) - return 'fail' + assert lyr.GetMetadataDomainList() == ['', 'another_domain'] ds = None ds = ogr.Open('/vsimem/ogr_gpkg_19.gpkg', update=1) lyr = ds.GetLayer('test_with_md') - if lyr.GetMetadata() != {'IDENTIFIER': 'another_ident', 'foo': 'bar', 'DESCRIPTION': 'another_desc'}: - gdaltest.post_reason('fail') - print(lyr.GetMetadata()) - return 'fail' - if lyr.GetMetadata('another_domain') != {'bar': 'baz'}: - gdaltest.post_reason('fail') - print(lyr.GetMetadata('another_domain')) - return 'fail' + assert lyr.GetMetadata() == {'IDENTIFIER': 'another_ident', 'foo': 'bar', 'DESCRIPTION': 'another_desc'} + assert lyr.GetMetadata('another_domain') == {'bar': 'baz'} lyr.SetMetadata(None) lyr.SetMetadata(None, 'another_domain') ds = None ds = ogr.Open('/vsimem/ogr_gpkg_19.gpkg', update=1) lyr = ds.GetLayer('test_with_md') - if lyr.GetMetadata() != {'IDENTIFIER': 'another_ident', 'DESCRIPTION': 'another_desc'}: - gdaltest.post_reason('fail') - print(lyr.GetMetadata()) - return 'fail' - if lyr.GetMetadataDomainList() != ['']: - gdaltest.post_reason('fail') - print(lyr.GetMetadataDomainList()) - return 'fail' + assert lyr.GetMetadata() == {'IDENTIFIER': 'another_ident', 'DESCRIPTION': 'another_desc'} + assert lyr.GetMetadataDomainList() == [''] ds = None - if not validate('/vsimem/ogr_gpkg_19.gpkg'): - gdaltest.post_reason('validation failed') - return 'fail' + assert validate('/vsimem/ogr_gpkg_19.gpkg'), 'validation failed' gdal.Unlink('/vsimem/ogr_gpkg_19.gpkg') gdal.Unlink('/vsimem/ogr_gpkg_19.gpkg.aux.xml') - return 'success' - ############################################################################### # Test spatial reference system -def ogr_gpkg_20(): +def test_ogr_gpkg_20(): if gdaltest.gpkg_dr is None: - return 'skip' + pytest.skip() ds = gdaltest.gpkg_dr.CreateDataSource('/vsimem/ogr_gpkg_20.gpkg') @@ -1775,34 +1426,20 @@ def ogr_gpkg_20(): sql_lyr = ds.ExecuteSQL("SELECT * FROM gpkg_spatial_ref_sys WHERE srs_name='my geogcs' AND srs_id = 100000 AND organization='MY_ORG' AND organization_coordsys_id=4326 AND description is NULL") fc = sql_lyr.GetFeatureCount() ds.ReleaseResultSet(sql_lyr) - if fc != 1: - gdaltest.post_reason('fail') - print(fc) - return 'fail' + assert fc == 1 sql_lyr = ds.ExecuteSQL("SELECT * FROM gpkg_spatial_ref_sys WHERE srs_name='another geogcs' AND srs_id = 100001 AND organization='NONE' AND organization_coordsys_id=100001 AND description is NULL") fc = sql_lyr.GetFeatureCount() ds.ReleaseResultSet(sql_lyr) - if fc != 1: - gdaltest.post_reason('fail') - print(fc) - return 'fail' + assert fc == 1 lyr = ds.GetLayer('my_org_4326') - if lyr.GetSpatialRef().ExportToWkt().find('my geogcs') < 0: - gdaltest.post_reason('fail') - print(lyr.GetSpatialRef().ExportToWkt()) - return 'fail' + assert lyr.GetSpatialRef().ExportToWkt().find('my geogcs') >= 0 lyr = ds.GetLayer('without_org') - if lyr.GetSpatialRef().ExportToWkt().find('another geogcs') < 0: - gdaltest.post_reason('fail') - print(lyr.GetSpatialRef().ExportToWkt()) - return 'fail' + assert lyr.GetSpatialRef().ExportToWkt().find('another geogcs') >= 0 ds = None - if not validate('/vsimem/ogr_gpkg_20.gpkg'): - gdaltest.post_reason('validation failed') - return 'fail' + assert validate('/vsimem/ogr_gpkg_20.gpkg'), 'validation failed' gdal.Unlink('/vsimem/ogr_gpkg_20.gpkg') @@ -1852,16 +1489,14 @@ def ogr_gpkg_20(): gdal.Unlink('/vsimem/ogr_gpkg_20.gpkg') - return 'success' - ############################################################################### # Test maximum width of text fields -def ogr_gpkg_21(): +def test_ogr_gpkg_21(): if gdaltest.gpkg_dr is None: - return 'skip' + pytest.skip() ds = gdaltest.gpkg_dr.CreateDataSource('/vsimem/ogr_gpkg_21.gpkg') lyr = ds.CreateLayer('test') @@ -1872,16 +1507,12 @@ def ogr_gpkg_21(): ds = ogr.Open('/vsimem/ogr_gpkg_21.gpkg', update=1) lyr = ds.GetLayer(0) - if lyr.GetLayerDefn().GetFieldDefn(0).GetWidth() != 2: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.GetLayerDefn().GetFieldDefn(0).GetWidth() == 2 f = ogr.Feature(lyr.GetLayerDefn()) f.SetField(0, 'ab') gdal.ErrorReset() lyr.CreateFeature(f) - if gdal.GetLastErrorMsg() != '': - gdaltest.post_reason('fail') - return 'fail' + assert gdal.GetLastErrorMsg() == '' f = ogr.Feature(lyr.GetLayerDefn()) f.SetFieldBinaryFromHexString(0, '41E9') @@ -1889,9 +1520,7 @@ def ogr_gpkg_21(): gdal.PushErrorHandler() lyr.CreateFeature(f) gdal.PopErrorHandler() - if gdal.GetLastErrorMsg() == '': - gdaltest.post_reason('fail') - return 'fail' + assert gdal.GetLastErrorMsg() != '' f = ogr.Feature(lyr.GetLayerDefn()) f.SetField(0, 'abc') @@ -1899,14 +1528,10 @@ def ogr_gpkg_21(): gdal.PushErrorHandler() lyr.CreateFeature(f) gdal.PopErrorHandler() - if gdal.GetLastErrorMsg() == '': - gdaltest.post_reason('fail') - return 'fail' + assert gdal.GetLastErrorMsg() != '' f = lyr.GetFeature(f.GetFID()) - if f.GetField(0) != 'abc': - gdaltest.post_reason('fail') - return 'fail' + assert f.GetField(0) == 'abc' gdal.Unlink('/vsimem/ogr_gpkg_21.gpkg') @@ -1922,14 +1547,10 @@ def ogr_gpkg_21(): gdal.PushErrorHandler() lyr.CreateFeature(f) gdal.PopErrorHandler() - if gdal.GetLastErrorMsg() == '': - gdaltest.post_reason('fail') - return 'fail' + assert gdal.GetLastErrorMsg() != '' f = lyr.GetFeature(f.GetFID()) - if f.GetField(0) != 'A_': - gdaltest.post_reason('fail') - return 'fail' + assert f.GetField(0) == 'A_' f = ogr.Feature(lyr.GetLayerDefn()) f.SetField(0, 'abc') @@ -1937,26 +1558,21 @@ def ogr_gpkg_21(): gdal.PushErrorHandler() lyr.CreateFeature(f) gdal.PopErrorHandler() - if gdal.GetLastErrorMsg() == '': - gdaltest.post_reason('fail') - return 'fail' + assert gdal.GetLastErrorMsg() != '' f = lyr.GetFeature(f.GetFID()) if f.GetField(0) != 'ab': - gdaltest.post_reason('fail') - - gdal.Unlink('/vsimem/ogr_gpkg_21.gpkg') - - return 'success' + gdal.Unlink('/vsimem/ogr_gpkg_21.gpkg') + ############################################################################### # Test FID64 support -def ogr_gpkg_22(): +def test_ogr_gpkg_22(): if gdaltest.gpkg_dr is None: - return 'skip' + pytest.skip() ds = gdaltest.gpkg_dr.CreateDataSource('/vsimem/ogr_gpkg_22.gpkg') lyr = ds.CreateLayer('test') @@ -1973,26 +1589,20 @@ def ogr_gpkg_22(): ds = ogr.Open('/vsimem/ogr_gpkg_22.gpkg') lyr = ds.GetLayerByName('test') - if lyr.GetMetadataItem(ogr.OLMD_FID64) is None: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.GetMetadataItem(ogr.OLMD_FID64) is not None f = lyr.GetNextFeature() - if f.GetFID() != 1234567890123: - gdaltest.post_reason('failure') - return 'fail' + assert f.GetFID() == 1234567890123 gdal.Unlink('/vsimem/ogr_gpkg_22.gpkg') - return 'success' - ############################################################################### # Test not nullable fields -def ogr_gpkg_23(): +def test_ogr_gpkg_23(): if gdaltest.gpkg_dr is None: - return 'skip' + pytest.skip() ds = gdaltest.gpkg_dr.CreateDataSource('/vsimem/ogr_gpkg_23.gpkg') lyr = ds.CreateLayer('test', geom_type=ogr.wkbNone) @@ -2017,9 +1627,7 @@ def ogr_gpkg_23(): gdal.PushErrorHandler() ret = lyr.CreateFeature(f) gdal.PopErrorHandler() - if ret == 0: - gdaltest.post_reason('fail') - return 'fail' + assert ret != 0 f = None # Error case: missing non-nullable field @@ -2028,9 +1636,7 @@ def ogr_gpkg_23(): gdal.PushErrorHandler() ret = lyr.CreateFeature(f) gdal.PopErrorHandler() - if ret == 0: - gdaltest.post_reason('fail') - return 'fail' + assert ret != 0 f = None # Nullable geometry field @@ -2040,9 +1646,7 @@ def ogr_gpkg_23(): gdal.PushErrorHandler() ret = lyr.CreateGeomField(ogr.GeomFieldDefn('foo', ogr.wkbPoint)) gdal.PopErrorHandler() - if ret == 0: - gdaltest.post_reason('fail') - return 'fail' + assert ret != 0 f = ogr.Feature(lyr.GetLayerDefn()) lyr.CreateFeature(f) @@ -2065,25 +1669,18 @@ def ogr_gpkg_23(): sql_lyr = ds.ExecuteSQL("SELECT * FROM gpkg_contents WHERE data_type = 'features'") fc = sql_lyr.GetFeatureCount() ds.ReleaseResultSet(sql_lyr) - if fc != 2: - gdaltest.post_reason('fail') - return 'fail' + assert fc == 2 sql_lyr = ds.ExecuteSQL("SELECT * FROM gpkg_extensions") fc = sql_lyr.GetFeatureCount() f = sql_lyr.GetNextFeature() ds.ReleaseResultSet(sql_lyr) - if fc != 2: # r-tree and aspatial - print(fc) - gdaltest.post_reason('fail') - return 'fail' + assert fc == 2 sql_lyr = ds.ExecuteSQL("SELECT * FROM gpkg_geometry_columns") fc = sql_lyr.GetFeatureCount() ds.ReleaseResultSet(sql_lyr) - if fc != 2: - gdaltest.post_reason('fail') - return 'fail' + assert fc == 2 field_defn = ogr.GeomFieldDefn('geomfield_not_nullable', ogr.wkbPoint) field_defn.SetNullable(0) @@ -2092,25 +1689,18 @@ def ogr_gpkg_23(): sql_lyr = ds.ExecuteSQL("SELECT * FROM gpkg_contents WHERE data_type = 'features'") fc = sql_lyr.GetFeatureCount() ds.ReleaseResultSet(sql_lyr) - if fc != 3: - gdaltest.post_reason('fail') - return 'fail' + assert fc == 3 sql_lyr = ds.ExecuteSQL("SELECT * FROM gpkg_extensions") fc = sql_lyr.GetFeatureCount() f = sql_lyr.GetNextFeature() ds.ReleaseResultSet(sql_lyr) - if fc != 1: # r-tree - print(fc) - gdaltest.post_reason('fail') - return 'fail' + assert fc == 1 sql_lyr = ds.ExecuteSQL("SELECT * FROM gpkg_geometry_columns") fc = sql_lyr.GetFeatureCount() ds.ReleaseResultSet(sql_lyr) - if fc != 3: - gdaltest.post_reason('fail') - return 'fail' + assert fc == 3 f = ogr.Feature(lyr.GetLayerDefn()) f.SetField('field_not_nullable', 'not_null') @@ -2120,9 +1710,7 @@ def ogr_gpkg_23(): # Not Nullable geometry field lyr = ds.CreateLayer('test4', geom_type=ogr.wkbPoint, options=['GEOMETRY_NULLABLE=NO']) - if lyr.GetLayerDefn().GetGeomFieldDefn(0).IsNullable() != 0: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.GetLayerDefn().GetGeomFieldDefn(0).IsNullable() == 0 f = ogr.Feature(lyr.GetLayerDefn()) f.SetGeometryDirectly(ogr.CreateGeometryFromWkt('POINT(0 0)')) lyr.CreateFeature(f) @@ -2137,56 +1725,36 @@ def ogr_gpkg_23(): lyr = ds.GetLayerByName('test5') field_defn = ogr.GeomFieldDefn('', ogr.wkbPoint) with gdaltest.error_handler(): - if lyr.CreateGeomField(field_defn) == 0: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.CreateGeomField(field_defn) != 0 lyr = ds.GetLayerByName('test') - if lyr.GetLayerDefn().GetFieldDefn(lyr.GetLayerDefn().GetFieldIndex('field_not_nullable')).IsNullable() != 0: - gdaltest.post_reason('fail') - return 'fail' - if lyr.GetLayerDefn().GetFieldDefn(lyr.GetLayerDefn().GetFieldIndex('field_nullable')).IsNullable() != 1: - gdaltest.post_reason('fail') - return 'fail' - if lyr.GetLayerDefn().GetGeomFieldDefn(lyr.GetLayerDefn().GetGeomFieldIndex('geomfield_not_nullable')).IsNullable() != 0: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.GetLayerDefn().GetFieldDefn(lyr.GetLayerDefn().GetFieldIndex('field_not_nullable')).IsNullable() == 0 + assert lyr.GetLayerDefn().GetFieldDefn(lyr.GetLayerDefn().GetFieldIndex('field_nullable')).IsNullable() == 1 + assert lyr.GetLayerDefn().GetGeomFieldDefn(lyr.GetLayerDefn().GetGeomFieldIndex('geomfield_not_nullable')).IsNullable() == 0 lyr = ds.GetLayerByName('test2') - if lyr.GetLayerDefn().GetGeomFieldDefn(0).IsNullable() != 1: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.GetLayerDefn().GetGeomFieldDefn(0).IsNullable() == 1 lyr = ds.GetLayerByName('test3') - if lyr.GetLayerDefn().GetFieldDefn(lyr.GetLayerDefn().GetFieldIndex('field_not_nullable')).IsNullable() != 0: - gdaltest.post_reason('fail') - return 'fail' - if lyr.GetLayerDefn().GetFieldDefn(lyr.GetLayerDefn().GetFieldIndex('field_nullable')).IsNullable() != 1: - gdaltest.post_reason('fail') - return 'fail' - if lyr.GetLayerDefn().GetGeomFieldDefn(lyr.GetLayerDefn().GetGeomFieldIndex('geomfield_not_nullable')).IsNullable() != 0: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.GetLayerDefn().GetFieldDefn(lyr.GetLayerDefn().GetFieldIndex('field_not_nullable')).IsNullable() == 0 + assert lyr.GetLayerDefn().GetFieldDefn(lyr.GetLayerDefn().GetFieldIndex('field_nullable')).IsNullable() == 1 + assert lyr.GetLayerDefn().GetGeomFieldDefn(lyr.GetLayerDefn().GetGeomFieldIndex('geomfield_not_nullable')).IsNullable() == 0 lyr = ds.GetLayerByName('test4') - if lyr.GetLayerDefn().GetGeomFieldDefn(0).IsNullable() != 0: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.GetLayerDefn().GetGeomFieldDefn(0).IsNullable() == 0 ds = None gdal.Unlink('/vsimem/ogr_gpkg_23.gpkg') - return 'success' - ############################################################################### # Test default values -def ogr_gpkg_24(): +def test_ogr_gpkg_24(): if gdaltest.gpkg_dr is None: - return 'skip' + pytest.skip() ds = gdaltest.gpkg_dr.CreateDataSource('/vsimem/ogr_gpkg_24.gpkg') lyr = ds.CreateLayer('test', geom_type=ogr.wkbNone) @@ -2257,37 +1825,16 @@ def ogr_gpkg_24(): ds = ogr.Open('/vsimem/ogr_gpkg_24.gpkg', update=1) lyr = ds.GetLayerByName('test') - if lyr.GetLayerDefn().GetFieldDefn(lyr.GetLayerDefn().GetFieldIndex('field_string')).GetDefault() != "'a''b'": - gdaltest.post_reason('fail') - return 'fail' - if lyr.GetLayerDefn().GetFieldDefn(lyr.GetLayerDefn().GetFieldIndex('field_int')).GetDefault() != '123': - gdaltest.post_reason('fail') - return 'fail' - if lyr.GetLayerDefn().GetFieldDefn(lyr.GetLayerDefn().GetFieldIndex('field_real')).GetDefault() != '1.23': - gdaltest.post_reason('fail') - return 'fail' - if lyr.GetLayerDefn().GetFieldDefn(lyr.GetLayerDefn().GetFieldIndex('field_nodefault')).GetDefault() is not None: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.GetLayerDefn().GetFieldDefn(lyr.GetLayerDefn().GetFieldIndex('field_string')).GetDefault() == "'a''b'" + assert lyr.GetLayerDefn().GetFieldDefn(lyr.GetLayerDefn().GetFieldIndex('field_int')).GetDefault() == '123' + assert lyr.GetLayerDefn().GetFieldDefn(lyr.GetLayerDefn().GetFieldIndex('field_real')).GetDefault() == '1.23' + assert lyr.GetLayerDefn().GetFieldDefn(lyr.GetLayerDefn().GetFieldIndex('field_nodefault')).GetDefault() is None # Translated from "(strftime('%Y-%m-%dT%H:%M:%fZ','now'))" to CURRENT_TIMESTAMP - if lyr.GetLayerDefn().GetFieldDefn(lyr.GetLayerDefn().GetFieldIndex('field_datetime')).GetDefault() != 'CURRENT_TIMESTAMP': - gdaltest.post_reason('fail') - return 'fail' - if lyr.GetLayerDefn().GetFieldDefn(lyr.GetLayerDefn().GetFieldIndex('field_datetime2')).GetDefault() != "'2015/06/30 12:34:56'": - gdaltest.post_reason('fail') - print(lyr.GetLayerDefn().GetFieldDefn(lyr.GetLayerDefn().GetFieldIndex('field_datetime2')).GetDefault()) - return 'fail' - if lyr.GetLayerDefn().GetFieldDefn(lyr.GetLayerDefn().GetFieldIndex('field_datetime3')).GetDefault() != "CURRENT_TIMESTAMP": - gdaltest.post_reason('fail') - print(lyr.GetLayerDefn().GetFieldDefn(lyr.GetLayerDefn().GetFieldIndex('field_datetime3')).GetDefault()) - return 'fail' - if lyr.GetLayerDefn().GetFieldDefn(lyr.GetLayerDefn().GetFieldIndex('field_datetime4')).GetDefault() != "'2015/06/30 12:34:56.123'": - gdaltest.post_reason('fail') - print(lyr.GetLayerDefn().GetFieldDefn(lyr.GetLayerDefn().GetFieldIndex('field_datetime4')).GetDefault()) - return 'fail' - if lyr.GetLayerDefn().GetFieldDefn(lyr.GetLayerDefn().GetFieldIndex('field_date')).GetDefault() != "CURRENT_DATE": - gdaltest.post_reason('fail') - return 'fail' + assert lyr.GetLayerDefn().GetFieldDefn(lyr.GetLayerDefn().GetFieldIndex('field_datetime')).GetDefault() == 'CURRENT_TIMESTAMP' + assert lyr.GetLayerDefn().GetFieldDefn(lyr.GetLayerDefn().GetFieldIndex('field_datetime2')).GetDefault() == "'2015/06/30 12:34:56'" + assert lyr.GetLayerDefn().GetFieldDefn(lyr.GetLayerDefn().GetFieldIndex('field_datetime3')).GetDefault() == "CURRENT_TIMESTAMP" + assert lyr.GetLayerDefn().GetFieldDefn(lyr.GetLayerDefn().GetFieldIndex('field_datetime4')).GetDefault() == "'2015/06/30 12:34:56.123'" + assert lyr.GetLayerDefn().GetFieldDefn(lyr.GetLayerDefn().GetFieldIndex('field_date')).GetDefault() == "CURRENT_DATE" # if lyr.GetLayerDefn().GetFieldDefn(lyr.GetLayerDefn().GetFieldIndex('field_time')).GetDefault() != "CURRENT_TIME": # gdaltest.post_reason('fail') # return 'fail' @@ -2302,24 +1849,21 @@ def ogr_gpkg_24(): f.GetField('field_datetime5') != '2016/06/30 12:34:56.123+00' or \ f.GetField('field_datetime6') != '2016/06/30 12:34:56+00' or \ f.GetField('field_string2') != 'X': - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' + pytest.fail() ds = None gdal.Unlink('/vsimem/ogr_gpkg_24.gpkg') - return 'success' - ############################################################################### # Test creating a field with the fid name -def ogr_gpkg_25(): +def test_ogr_gpkg_25(): if gdaltest.gpkg_dr is None: - return 'skip' + pytest.skip() ds = gdaltest.gpkg_dr.CreateDataSource('/vsimem/ogr_gpkg_25.gpkg') lyr = ds.CreateLayer('test', geom_type=ogr.wkbNone, options=['FID=myfid']) @@ -2328,14 +1872,10 @@ def ogr_gpkg_25(): gdal.PushErrorHandler() ret = lyr.CreateField(ogr.FieldDefn('myfid', ogr.OFTString)) gdal.PopErrorHandler() - if ret == 0: - gdaltest.post_reason('fail') - return 'fail' + assert ret != 0 ret = lyr.CreateField(ogr.FieldDefn('myfid', ogr.OFTInteger)) - if ret != 0: - gdaltest.post_reason('fail') - return 'fail' + assert ret == 0 lyr.CreateField(ogr.FieldDefn('str2', ogr.OFTString)) feat = ogr.Feature(lyr.GetLayerDefn()) @@ -2343,33 +1883,23 @@ def ogr_gpkg_25(): feat.SetField('myfid', 10) feat.SetField('str2', 'second string') ret = lyr.CreateFeature(feat) - if ret != 0: - gdaltest.post_reason('fail') - return 'fail' - if feat.GetFID() != 10: - gdaltest.post_reason('fail') - return 'fail' + assert ret == 0 + assert feat.GetFID() == 10 feat = ogr.Feature(lyr.GetLayerDefn()) feat.SetField('str2', 'second string') ret = lyr.CreateFeature(feat) - if ret != 0: - gdaltest.post_reason('fail') - return 'fail' + assert ret == 0 if feat.GetFID() < 0: - gdaltest.post_reason('fail') feat.DumpReadable() - return 'fail' + pytest.fail() if feat.GetField('myfid') != feat.GetFID(): - gdaltest.post_reason('fail') feat.DumpReadable() - return 'fail' + pytest.fail() feat.SetField('str', 'foo') ret = lyr.SetFeature(feat) - if ret != 0: - gdaltest.post_reason('fail') - return 'fail' + assert ret == 0 feat = ogr.Feature(lyr.GetLayerDefn()) feat.SetFID(1) @@ -2377,151 +1907,107 @@ def ogr_gpkg_25(): gdal.PushErrorHandler() ret = lyr.CreateFeature(feat) gdal.PopErrorHandler() - if ret == 0: - gdaltest.post_reason('fail') - return 'fail' + assert ret != 0 gdal.PushErrorHandler() ret = lyr.SetFeature(feat) gdal.PopErrorHandler() - if ret == 0: - gdaltest.post_reason('fail') - return 'fail' + assert ret != 0 feat.UnsetField('myfid') gdal.PushErrorHandler() ret = lyr.SetFeature(feat) gdal.PopErrorHandler() - if ret == 0: - gdaltest.post_reason('fail') - return 'fail' + assert ret != 0 lyr.ResetReading() f = lyr.GetNextFeature() if f.GetFID() != 10 or f.GetField('str') != 'first string' or f.GetField('str2') != 'second string' or f.GetField('myfid') != 10: - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' + pytest.fail() f = lyr.GetFeature(f.GetFID()) if f.GetFID() != 10 or f.GetField('str') != 'first string' or f.GetField('str2') != 'second string' or f.GetField('myfid') != 10: - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' + pytest.fail() f = None ds = None gdaltest.gpkg_dr.DeleteDataSource('/vsimem/ogr_gpkg_25.gpkg') - return 'success' - ############################################################################### # Test dataset transactions -def ogr_gpkg_26(): +def test_ogr_gpkg_26(): if gdaltest.gpkg_dr is None: - return 'skip' + pytest.skip() ds = gdaltest.gpkg_dr.CreateDataSource('/vsimem/ogr_gpkg_26.gpkg') - if ds.TestCapability(ogr.ODsCTransactions) != 1: - gdaltest.post_reason('fail') - return 'fail' + assert ds.TestCapability(ogr.ODsCTransactions) == 1 ret = ds.StartTransaction() - if ret != 0: - gdaltest.post_reason('fail') - return 'fail' + assert ret == 0 gdal.PushErrorHandler() ret = ds.StartTransaction() gdal.PopErrorHandler() - if ret == 0: - gdaltest.post_reason('fail') - return 'fail' + assert ret != 0 lyr = ds.CreateLayer('test') lyr.CreateField(ogr.FieldDefn('foo', ogr.OFTString)) ret = ds.RollbackTransaction() - if ret != 0: - gdaltest.post_reason('fail') - return 'fail' + assert ret == 0 gdal.PushErrorHandler() ret = ds.RollbackTransaction() gdal.PopErrorHandler() - if ret == 0: - gdaltest.post_reason('fail') - return 'fail' + assert ret != 0 ds = None ds = ogr.Open('/vsimem/ogr_gpkg_26.gpkg', update=1) - if ds.GetLayerCount() != 0: - gdaltest.post_reason('fail') - return 'fail' + assert ds.GetLayerCount() == 0 ret = ds.StartTransaction() - if ret != 0: - gdaltest.post_reason('fail') - return 'fail' + assert ret == 0 gdal.PushErrorHandler() ret = ds.StartTransaction() gdal.PopErrorHandler() - if ret == 0: - gdaltest.post_reason('fail') - return 'fail' + assert ret != 0 lyr = ds.CreateLayer('test') lyr.CreateField(ogr.FieldDefn('foo', ogr.OFTString)) ret = ds.CommitTransaction() - if ret != 0: - gdaltest.post_reason('fail') - return 'fail' + assert ret == 0 gdal.PushErrorHandler() ret = ds.CommitTransaction() gdal.PopErrorHandler() - if ret == 0: - gdaltest.post_reason('fail') - return 'fail' + assert ret != 0 ds = None ds = ogr.Open('/vsimem/ogr_gpkg_26.gpkg', update=1) - if ds.GetLayerCount() != 1: - gdaltest.post_reason('fail') - return 'fail' + assert ds.GetLayerCount() == 1 lyr = ds.GetLayerByName('test') ds.StartTransaction() lyr.CreateFeature(ogr.Feature(lyr.GetLayerDefn())) lyr.ResetReading() f = lyr.GetNextFeature() - if f is None: - gdaltest.post_reason('fail') - return 'fail' - if lyr.GetFeatureCount() != 1: - gdaltest.post_reason('fail') - return 'fail' + assert f is not None + assert lyr.GetFeatureCount() == 1 ds.RollbackTransaction() - if lyr.GetFeatureCount() != 0: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.GetFeatureCount() == 0 ds.StartTransaction() lyr.CreateFeature(ogr.Feature(lyr.GetLayerDefn())) lyr.CreateFeature(ogr.Feature(lyr.GetLayerDefn())) lyr.ResetReading() f = lyr.GetNextFeature() - if f is None or f.GetFID() != 1: - gdaltest.post_reason('fail') - return 'fail' + assert f is not None and f.GetFID() == 1 ds.CommitTransaction() # the cursor is still valid after CommitTransaction(), which isn't the case for other backends such as PG ! f = lyr.GetNextFeature() - if f is None or f.GetFID() != 2: - gdaltest.post_reason('fail') - return 'fail' - if lyr.GetFeatureCount() != 2: - gdaltest.post_reason('fail') - return 'fail' + assert f is not None and f.GetFID() == 2 + assert lyr.GetFeatureCount() == 2 ds.StartTransaction() lyr = ds.CreateLayer('test2', geom_type=ogr.wkbPoint) @@ -2531,18 +2017,14 @@ def ogr_gpkg_26(): f.SetGeometryDirectly(ogr.CreateGeometryFromWkt('POINT(0 0)')) ret = lyr.CreateFeature(f) ds.CommitTransaction() - if ret != 0: - gdaltest.post_reason('fail') - return 'fail' + assert ret == 0 ds.StartTransaction() f = ogr.Feature(lyr.GetLayerDefn()) f.SetGeometryDirectly(ogr.CreateGeometryFromWkt('POINT(0 0)')) ret = lyr.CreateFeature(f) ds.CommitTransaction() - if ret != 0: - gdaltest.post_reason('fail') - return 'fail' + assert ret == 0 if False: # pylint: disable=using-constant-test ds.StartTransaction() @@ -2566,24 +2048,20 @@ def ogr_gpkg_26(): ds.CommitTransaction() # For some reason fails with SQLite 3.6.X with 'failed to execute insert : callback requested query abort' # but not with later versions... - if ret != 0: - gdaltest.post_reason('fail') - return 'fail' + assert ret == 0 ds = None gdaltest.gpkg_dr.DeleteDataSource('/vsimem/ogr_gpkg_26.gpkg') - return 'success' - ############################################################################### # Test interface with Spatialite -def ogr_gpkg_27(): +def test_ogr_gpkg_27(): if gdaltest.gpkg_dr is None: - return 'skip' + pytest.skip() ds = gdaltest.gpkg_dr.CreateDataSource('/vsimem/ogr_gpkg_27.gpkg') gdal.PushErrorHandler() @@ -2592,7 +2070,7 @@ def ogr_gpkg_27(): if sql_lyr is None: ds = None gdaltest.gpkg_dr.DeleteDataSource('/vsimem/ogr_gpkg_27.gpkg') - return 'skip' + pytest.skip() ds.ReleaseResultSet(sql_lyr) lyr = ds.CreateLayer('test') @@ -2602,92 +2080,72 @@ def ogr_gpkg_27(): sql_lyr = ds.ExecuteSQL('SELECT GeomFromGPB(geom) FROM test') f = sql_lyr.GetNextFeature() if f.GetGeometryRef().ExportToWkt() != 'POINT (2 49)': - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' + pytest.fail() ds.ReleaseResultSet(sql_lyr) ds = None gdaltest.gpkg_dr.DeleteDataSource('/vsimem/ogr_gpkg_27.gpkg') - return 'success' - ############################################################################### # Test ogr2ogr -a_srs (as the geopackage driver doesn't clone the passed SRS # but inc/dec its ref count, which can exhibit issues in GDALVectorTanslate()) -def ogr_gpkg_28(): +def test_ogr_gpkg_28(): if gdaltest.gpkg_dr is None: - return 'skip' + pytest.skip() srcDS = gdal.OpenEx('../ogr/data/poly.shp') ds = gdal.VectorTranslate('/vsimem/ogr_gpkg_28.gpkg', srcDS, format='GPKG', dstSRS='EPSG:4326') - if str(ds.GetLayer(0).GetSpatialRef()).find('1984') == -1: - return 'fail' + assert str(ds.GetLayer(0).GetSpatialRef()).find('1984') != -1 ds = None gdaltest.gpkg_dr.DeleteDataSource('/vsimem/ogr_gpkg_28.gpkg') - return 'success' - ############################################################################### # Test XYM / XYZM support -def ogr_gpkg_29(): +def test_ogr_gpkg_29(): if gdaltest.gpkg_dr is None: - return 'skip' + pytest.skip() ds = gdaltest.gpkg_dr.CreateDataSource('/vsimem/ogr_gpkg_29.gpkg') - if ds.TestCapability(ogr.ODsCMeasuredGeometries) != 1: - gdaltest.post_reason('fail') - return 'fail' + assert ds.TestCapability(ogr.ODsCMeasuredGeometries) == 1 lyr = ds.CreateLayer('pointm', geom_type=ogr.wkbPointM) - if lyr.TestCapability(ogr.OLCMeasuredGeometries) != 1: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.TestCapability(ogr.OLCMeasuredGeometries) == 1 f = ogr.Feature(lyr.GetLayerDefn()) f.SetGeometryDirectly(ogr.CreateGeometryFromWkt('POINT M (1 2 3)')) lyr.CreateFeature(f) lyr = ds.CreateLayer('pointzm', geom_type=ogr.wkbPointZM) - if lyr.TestCapability(ogr.OLCMeasuredGeometries) != 1: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.TestCapability(ogr.OLCMeasuredGeometries) == 1 f = ogr.Feature(lyr.GetLayerDefn()) f.SetGeometryDirectly(ogr.CreateGeometryFromWkt('POINT ZM (1 2 3 4)')) lyr.CreateFeature(f) ds = None - if not validate('/vsimem/ogr_gpkg_29.gpkg'): - gdaltest.post_reason('validation failed') - return 'fail' + assert validate('/vsimem/ogr_gpkg_29.gpkg'), 'validation failed' ds = ogr.Open('/vsimem/ogr_gpkg_29.gpkg', update=1) lyr = ds.GetLayerByName('pointm') - if lyr.GetGeomType() != ogr.wkbPointM: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.GetGeomType() == ogr.wkbPointM f = lyr.GetNextFeature() if f.GetGeometryRef().ExportToIsoWkt() != 'POINT M (1 2 3)': - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' + pytest.fail() # Generate a XYM envelope ds.ExecuteSQL("UPDATE pointm SET geom = x'4750000700000000000000000000F03F000000000000F03F000000000000004000000000000000400000000000000840000000000000084001D1070000000000000000F03F00000000000000400000000000000840'") lyr = ds.GetLayerByName('pointzm') - if lyr.GetGeomType() != ogr.wkbPointZM: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.GetGeomType() == ogr.wkbPointZM f = lyr.GetNextFeature() if f.GetGeometryRef().ExportToIsoWkt() != 'POINT ZM (1 2 3 4)': - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' + pytest.fail() # Generate a XYZM envelope ds.ExecuteSQL("UPDATE pointzm SET geom = x'4750000900000000000000000000F03F000000000000F03F00000000000000400000000000000040000000000000084000000000000008400000000000001040000000000000104001B90B0000000000000000F03F000000000000004000000000000008400000000000001040'") @@ -2697,71 +2155,54 @@ def ogr_gpkg_29(): # Check again ds = ogr.Open('/vsimem/ogr_gpkg_29.gpkg') lyr = ds.GetLayerByName('pointm') - if lyr.GetGeomType() != ogr.wkbPointM: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.GetGeomType() == ogr.wkbPointM f = lyr.GetNextFeature() if f.GetGeometryRef().ExportToIsoWkt() != 'POINT M (1 2 3)': - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' + pytest.fail() lyr = ds.GetLayerByName('pointzm') - if lyr.GetGeomType() != ogr.wkbPointZM: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.GetGeomType() == ogr.wkbPointZM f = lyr.GetNextFeature() if f.GetGeometryRef().ExportToIsoWkt() != 'POINT ZM (1 2 3 4)': - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' + pytest.fail() ds = None gdaltest.gpkg_dr.DeleteDataSource('/vsimem/ogr_gpkg_29.gpkg') - return 'success' - ############################################################################### # Test non standard file extension (#6396) -def ogr_gpkg_30(): +def test_ogr_gpkg_30(): if gdaltest.gpkg_dr is None: - return 'skip' + pytest.skip() with gdaltest.error_handler(): ds = gdaltest.gpkg_dr.CreateDataSource('/vsimem/ogr_gpkg_30.geopkg') - if ds is None: - gdaltest.post_reason('fail') - return 'fail' - if gdal.GetLastErrorMsg() == '': - gdaltest.post_reason('fail') - return 'fail' + assert ds is not None + assert gdal.GetLastErrorMsg() != '' ds = None with gdaltest.error_handler(): ds = ogr.Open('/vsimem/ogr_gpkg_30.geopkg', update=1) - if ds is None: - gdaltest.post_reason('fail') - return 'fail' - if gdal.GetLastErrorMsg() == '': - gdaltest.post_reason('fail') - return 'fail' + assert ds is not None + assert gdal.GetLastErrorMsg() != '' ds = None with gdaltest.error_handler(): gdaltest.gpkg_dr.DeleteDataSource('/vsimem/ogr_gpkg_30.geopkg') - return 'success' - + ############################################################################### # Test CURVE and SURFACE types -def ogr_gpkg_31(): +def test_ogr_gpkg_31(): if gdaltest.gpkg_dr is None: - return 'skip' + pytest.skip() ds = gdaltest.gpkg_dr.CreateDataSource('/vsimem/ogr_gpkg_31.gpkg') lyr = ds.CreateLayer('curve', geom_type=ogr.wkbCurve) @@ -2782,74 +2223,54 @@ def ogr_gpkg_31(): ds = ogr.Open('/vsimem/ogr_gpkg_31.gpkg') lyr = ds.GetLayerByName('curve') - if lyr.GetGeomType() != ogr.wkbCurve: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.GetGeomType() == ogr.wkbCurve lyr = ds.GetLayerByName('surface') - if lyr.GetGeomType() != ogr.wkbSurface: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.GetGeomType() == ogr.wkbSurface ds = None - if not validate('/vsimem/ogr_gpkg_31.gpkg'): - gdaltest.post_reason('validation failed') - return 'fail' + assert validate('/vsimem/ogr_gpkg_31.gpkg'), 'validation failed' gdaltest.gpkg_dr.DeleteDataSource('/vsimem/ogr_gpkg_31.gpkg') - return 'success' - ############################################################################### # Run creating a non-spatial layer that isn't registered as 'aspatial' and # read it back -def ogr_gpkg_32(): +def test_ogr_gpkg_32(): if gdaltest.gpkg_dr is None: - return 'skip' + pytest.skip() ds = gdaltest.gpkg_dr.CreateDataSource('/vsimem/ogr_gpkg_32.gpkg') ds.CreateLayer('aspatial', geom_type=ogr.wkbNone, options=['ASPATIAL_VARIANT=NOT_REGISTERED']) ds = None ds = ogr.Open('/vsimem/ogr_gpkg_32.gpkg') - if ds.GetLayerCount() != 1: - gdaltest.post_reason('fail') - return 'fail' + assert ds.GetLayerCount() == 1 sql_lyr = ds.ExecuteSQL("SELECT * FROM gpkg_contents WHERE table_name != 'ogr_empty_table'") - if sql_lyr.GetFeatureCount() != 0: - gdaltest.post_reason('fail') - return 'fail' + assert sql_lyr.GetFeatureCount() == 0 ds.ReleaseResultSet(sql_lyr) sql_lyr = ds.ExecuteSQL("SELECT * FROM gpkg_geometry_columns WHERE table_name != 'ogr_empty_table'") - if sql_lyr.GetFeatureCount() != 0: - gdaltest.post_reason('fail') - return 'fail' + assert sql_lyr.GetFeatureCount() == 0 ds.ReleaseResultSet(sql_lyr) sql_lyr = ds.ExecuteSQL("SELECT * FROM sqlite_master WHERE name = 'gpkg_extensions'") - if sql_lyr.GetFeatureCount() != 0: - gdaltest.post_reason('fail') - return 'fail' + assert sql_lyr.GetFeatureCount() == 0 ds.ReleaseResultSet(sql_lyr) ds = None - if not validate('/vsimem/ogr_gpkg_32.gpkg'): - gdaltest.post_reason('validation failed') - return 'fail' + assert validate('/vsimem/ogr_gpkg_32.gpkg'), 'validation failed' gdaltest.gpkg_dr.DeleteDataSource('/vsimem/ogr_gpkg_32.gpkg') - return 'success' - ############################################################################### # Test OGR_CURRENT_DATE -def ogr_gpkg_33(): +def test_ogr_gpkg_33(): if gdaltest.gpkg_dr is None: - return 'skip' + pytest.skip() gdal.SetConfigOption('OGR_CURRENT_DATE', '2000-01-01T:00:00:00.000Z') ds = gdaltest.gpkg_dr.CreateDataSource('/vsimem/ogr_gpkg_33.gpkg') @@ -2859,63 +2280,20 @@ def ogr_gpkg_33(): ds = ogr.Open('/vsimem/ogr_gpkg_33.gpkg') sql_lyr = ds.ExecuteSQL("SELECT * FROM gpkg_contents WHERE last_change = '2000-01-01T:00:00:00.000Z' AND table_name != 'ogr_empty_table'") - if sql_lyr.GetFeatureCount() != 1: - gdaltest.post_reason('fail') - return 'fail' + assert sql_lyr.GetFeatureCount() == 1 ds.ReleaseResultSet(sql_lyr) ds = None gdaltest.gpkg_dr.DeleteDataSource('/vsimem/ogr_gpkg_33.gpkg') - return 'success' - -############################################################################### -# Run test_ogrsf - - -def ogr_gpkg_test_ogrsf(): - - if gdaltest.gpkg_dr is None: - return 'skip' - - # Do integrity check first - sql_lyr = gdaltest.gpkg_ds.ExecuteSQL("PRAGMA integrity_check") - feat = sql_lyr.GetNextFeature() - if feat.GetField(0) != 'ok': - gdaltest.post_reason('integrity check failed') - return 'fail' - gdaltest.gpkg_ds.ReleaseResultSet(sql_lyr) - - import test_cli_utilities - if test_cli_utilities.get_test_ogrsf_path() is None: - return 'skip' - - gdaltest.gpkg_ds = None - # sys.exit(0) - ret = gdaltest.runexternal(test_cli_utilities.get_test_ogrsf_path() + ' tmp/gpkg_test.gpkg --config OGR_SQLITE_SYNCHRONOUS OFF') - - if ret.find('INFO') == -1 or ret.find('ERROR') != -1: - gdaltest.post_reason('fail') - print(ret) - return 'fail' - - ret = gdaltest.runexternal(test_cli_utilities.get_test_ogrsf_path() + ' tmp/gpkg_test.gpkg -sql "select * from tbl_linestring_renamed" --config OGR_SQLITE_SYNCHRONOUS OFF') - - if ret.find('INFO') == -1 or ret.find('ERROR') != -1: - gdaltest.post_reason('fail') - print(ret) - return 'fail' - - return 'success' - ############################################################################### # Test rename and delete a layer registered in extensions, metadata, spatial index etc -def ogr_gpkg_34(): +def test_ogr_gpkg_34(): if gdaltest.gpkg_dr is None: - return 'skip' + pytest.skip() layer_name = """weird'layer"name""" @@ -2946,17 +2324,13 @@ def ogr_gpkg_34(): content = gdal.VSIFReadL(1, 1000000, f).decode('latin1') gdal.VSIFCloseL(f) - if content.find(layer_name) < 0: - gdaltest.post_reason('fail') - return 'fail' + assert content.find(layer_name) >= 0 ds = ogr.Open(dbname, update=1) new_layer_name = """weird2'layer"name""" with gdaltest.error_handler(): ds.ExecuteSQL('ALTER TABLE "weird\'layer""name" RENAME TO gpkg_contents') - if gdal.GetLastErrorMsg() == '': - gdaltest.post_reason('fail') - return 'fail' + assert gdal.GetLastErrorMsg() != '' gdal.ErrorReset() ds.ExecuteSQL('ALTER TABLE "weird\'layer""name" RENAME TO "weird2\'layer""name"') ds.ExecuteSQL('VACUUM') @@ -2967,22 +2341,16 @@ def ogr_gpkg_34(): content = gdal.VSIFReadL(1, 1000000, f).decode('latin1') gdal.VSIFCloseL(f) - if content.find(layer_name) >= 0: - gdaltest.post_reason('fail') - return 'fail' + assert content.find(layer_name) < 0 layer_name = new_layer_name ds = ogr.Open(dbname, update=1) with gdaltest.error_handler(): ds.ExecuteSQL('DELLAYER:does_not_exist') - if gdal.GetLastErrorMsg() == '': - gdaltest.post_reason('fail') - return 'fail' + assert gdal.GetLastErrorMsg() != '' gdal.ErrorReset() ds.ExecuteSQL('DELLAYER:' + layer_name) - if gdal.GetLastErrorMsg() != '': - gdaltest.post_reason('fail') - return 'fail' + assert gdal.GetLastErrorMsg() == '' ds.ExecuteSQL('VACUUM') ds = None @@ -2991,9 +2359,7 @@ def ogr_gpkg_34(): content = gdal.VSIFReadL(1, 1000000, f).decode('latin1') gdal.VSIFCloseL(f) - if content.find(layer_name) >= 0: - gdaltest.post_reason('fail') - return 'fail' + assert content.find(layer_name) < 0 gdaltest.gpkg_dr.DeleteDataSource(dbname) @@ -3009,18 +2375,12 @@ def ogr_gpkg_34(): ds = ogr.Open(dbname, update=1) ds.ExecuteSQL('DROP TABLE "weird2\'layer""name"') - if gdal.GetLastErrorMsg() != '': - gdaltest.post_reason('fail') - return 'fail' + assert gdal.GetLastErrorMsg() == '' ds.ExecuteSQL('DROP TABLE another_layer_name') - if gdal.GetLastErrorMsg() != '': - gdaltest.post_reason('fail') - return 'fail' + assert gdal.GetLastErrorMsg() == '' with gdaltest.error_handler(): ds.ExecuteSQL('DROP TABLE "foobar"') - if gdal.GetLastErrorMsg() == '': - gdaltest.post_reason('fail') - return 'fail' + assert gdal.GetLastErrorMsg() != '' gdal.ErrorReset() ds.ExecuteSQL('VACUUM') ds = None @@ -3030,26 +2390,20 @@ def ogr_gpkg_34(): content = gdal.VSIFReadL(1, 1000000, f).decode('latin1') gdal.VSIFCloseL(f) - if content.find(layer_name) >= 0: - gdaltest.post_reason('fail') - return 'fail' + assert content.find(layer_name) < 0 - if content.find('another_layer_name') >= 0: - gdaltest.post_reason('fail') - return 'fail' + assert content.find('another_layer_name') < 0 gdaltest.gpkg_dr.DeleteDataSource(dbname) - return 'success' - ############################################################################### # Test DeleteField() -def ogr_gpkg_35(): +def test_ogr_gpkg_35(): if gdaltest.gpkg_dr is None: - return 'skip' + pytest.skip() dbname = '/vsimem/ogr_gpkg_35.gpkg' ds = gdaltest.gpkg_dr.CreateDataSource(dbname) @@ -3090,49 +2444,35 @@ def ogr_gpkg_35(): ds.ExecuteSQL("INSERT INTO gpkg_data_columns VALUES('test', 'bar_i_will_disappear', 'bar_constraints', NULL, NULL, NULL, NULL)") ds.ExecuteSQL("INSERT INTO gpkg_extensions VALUES('test', 'bar_i_will_disappear', 'extension_name', 'definition', 'scope')") - if lyr.TestCapability(ogr.OLCDeleteField) != 1: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.TestCapability(ogr.OLCDeleteField) == 1 with gdaltest.error_handler(): ret = lyr.DeleteField(-1) - if ret == 0: - gdaltest.post_reason('fail') - return 'fail' + assert ret != 0 with gdaltest.error_handler(): ret = lyr.DeleteField(lyr.GetLayerDefn().GetFieldCount()) - if ret == 0: - gdaltest.post_reason('fail') - return 'fail' + assert ret != 0 - if lyr.DeleteField(1) != 0: - gdaltest.post_reason('fail') - return 'fail' - if lyr.GetLayerDefn().GetFieldCount() != 2: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.DeleteField(1) == 0 + assert lyr.GetLayerDefn().GetFieldCount() == 2 lyr.ResetReading() f = lyr.GetNextFeature() if f.GetFID() != 10 or f['foo'] != 'fooval' or f['baz'] != 'bazval' or \ f.GetGeometryRef().ExportToWkt() != 'POLYGON ((0 0,0 1,1 1,0 0))': - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' + pytest.fail() lyr.StartTransaction() ret = lyr_nonspatial.DeleteField(1) lyr.CommitTransaction() - if ret != 0: - gdaltest.post_reason('fail') - return 'fail' + assert ret == 0 lyr_nonspatial.ResetReading() f = lyr_nonspatial.GetNextFeature() if f.GetFID() != 10 or f['foo'] != 'fooval' or f['baz'] != 'bazval': - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' + pytest.fail() ds.ExecuteSQL('VACUUM') @@ -3143,9 +2483,7 @@ def ogr_gpkg_35(): lyr = ds.GetLayer(0) with gdaltest.error_handler(): ret = lyr.DeleteField(0) - if ret == 0: - gdaltest.post_reason('fail') - return 'fail' + assert ret != 0 ds = None # Check that there is no more any reference to the layer @@ -3153,22 +2491,18 @@ def ogr_gpkg_35(): content = gdal.VSIFReadL(1, 1000000, f).decode('latin1') gdal.VSIFCloseL(f) - if content.find('bar_i_will_disappear') >= 0: - gdaltest.post_reason('fail') - return 'fail' + assert content.find('bar_i_will_disappear') < 0 gdaltest.gpkg_dr.DeleteDataSource(dbname) - return 'success' - ############################################################################### # Test AlterFieldDefn() -def ogr_gpkg_36(): +def test_ogr_gpkg_36(): if gdaltest.gpkg_dr is None: - return 'skip' + pytest.skip() dbname = '/vsimem/ogr_gpkg_36.gpkg' ds = gdaltest.gpkg_dr.CreateDataSource(dbname) @@ -3197,77 +2531,57 @@ def ogr_gpkg_36(): ds.ExecuteSQL("INSERT INTO gpkg_extensions VALUES('test', 'foo', 'extension_name', 'definition', 'scope')") ds.ExecuteSQL("CREATE INDEX my_idx ON test(foo)") - if lyr.TestCapability(ogr.OLCAlterFieldDefn) != 1: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.TestCapability(ogr.OLCAlterFieldDefn) == 1 with gdaltest.error_handler(): ret = lyr.AlterFieldDefn(-1, ogr.FieldDefn('foo'), ogr.ALTER_ALL_FLAG) - if ret == 0: - gdaltest.post_reason('fail') - return 'fail' + assert ret != 0 with gdaltest.error_handler(): ret = lyr.AlterFieldDefn(1, ogr.FieldDefn('foo'), ogr.ALTER_ALL_FLAG) - if ret == 0: - gdaltest.post_reason('fail') - return 'fail' + assert ret != 0 with gdaltest.error_handler(): ret = lyr.AlterFieldDefn(0, ogr.FieldDefn(lyr.GetGeometryColumn()), ogr.ALTER_ALL_FLAG) - if ret == 0: - gdaltest.post_reason('fail') - return 'fail' + assert ret != 0 with gdaltest.error_handler(): ret = lyr.AlterFieldDefn(0, ogr.FieldDefn(lyr.GetFIDColumn()), ogr.ALTER_ALL_FLAG) - if ret == 0: - gdaltest.post_reason('fail') - return 'fail' + assert ret != 0 with gdaltest.error_handler(): ret = lyr.AlterFieldDefn(0, ogr.FieldDefn('baz'), ogr.ALTER_ALL_FLAG) - if ret == 0: - gdaltest.post_reason('fail') - return 'fail' + assert ret != 0 new_field_defn = ogr.FieldDefn('bar', ogr.OFTReal) new_field_defn.SetSubType(ogr.OFSTFloat32) - if lyr.AlterFieldDefn(0, new_field_defn, ogr.ALTER_ALL_FLAG) != 0: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.AlterFieldDefn(0, new_field_defn, ogr.ALTER_ALL_FLAG) == 0 lyr.ResetReading() f = lyr.GetNextFeature() if f.GetFID() != 10 or f['bar'] != 10.5 or \ f.GetGeometryRef().ExportToWkt() != 'POLYGON ((0 0,0 1,1 1,0 0))': - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' + pytest.fail() f = None lyr.StartTransaction() new_field_defn = ogr.FieldDefn('baw', ogr.OFTString) - if lyr.AlterFieldDefn(0, new_field_defn, ogr.ALTER_ALL_FLAG) != 0: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.AlterFieldDefn(0, new_field_defn, ogr.ALTER_ALL_FLAG) == 0 lyr.CommitTransaction() lyr.ResetReading() f = lyr.GetNextFeature() if f.GetFID() != 10 or f['baw'] != '10.5' or \ f.GetGeometryRef().ExportToWkt() != 'POLYGON ((0 0,0 1,1 1,0 0))': - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' + pytest.fail() f = None # Check that index has been recreated sql_lyr = ds.ExecuteSQL("SELECT * FROM sqlite_master WHERE name = 'my_idx'") f = sql_lyr.GetNextFeature() - if f is None: - gdaltest.post_reason('fail') - return 'fail' + assert f is not None f = None ds.ReleaseResultSet(sql_lyr) @@ -3280,9 +2594,7 @@ def ogr_gpkg_36(): lyr = ds.GetLayer(0) with gdaltest.error_handler(): ret = lyr.AlterFieldDefn(0, ogr.FieldDefn('foo'), ogr.ALTER_ALL_FLAG) - if ret == 0: - gdaltest.post_reason('fail') - return 'fail' + assert ret != 0 ds = None # Check that there is no more any reference to the layer @@ -3290,9 +2602,7 @@ def ogr_gpkg_36(): content = gdal.VSIFReadL(1, 1000000, f).decode('latin1') gdal.VSIFCloseL(f) - if content.find('foo') >= 0: - gdaltest.post_reason('fail') - return 'fail' + assert content.find('foo') < 0 gdaltest.gpkg_dr.DeleteDataSource(dbname) @@ -3305,24 +2615,20 @@ def ogr_gpkg_36(): gdal.Unlink(dbname) with gdaltest.error_handler(): ret = lyr.AlterFieldDefn(0, ogr.FieldDefn('bar'), ogr.ALTER_ALL_FLAG) - if ret == 0: - gdaltest.post_reason('fail') - return 'fail' + assert ret != 0 with gdaltest.error_handler(): ds = None gdaltest.gpkg_dr.DeleteDataSource(dbname) - return 'success' - ############################################################################### # Test ReorderFields() -def ogr_gpkg_37(): +def test_ogr_gpkg_37(): if gdaltest.gpkg_dr is None: - return 'skip' + pytest.skip() dbname = '/vsimem/ogr_gpkg_37.gpkg' ds = gdaltest.gpkg_dr.CreateDataSource(dbname) @@ -3352,36 +2658,25 @@ def ogr_gpkg_37(): ds.ExecuteSQL("CREATE INDEX my_idx_foo ON test(foo)") ds.ExecuteSQL("CREATE INDEX my_idx_bar ON test(bar)") - if lyr.TestCapability(ogr.OLCReorderFields) != 1: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.TestCapability(ogr.OLCReorderFields) == 1 with gdaltest.error_handler(): ret = lyr.ReorderFields([-1, -1]) - if ret == 0: - gdaltest.post_reason('fail') - return 'fail' + assert ret != 0 - if lyr.ReorderFields([1, 0]) != 0: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.ReorderFields([1, 0]) == 0 lyr.ResetReading() - if lyr.GetLayerDefn().GetFieldIndex('foo') != 1 or lyr.GetLayerDefn().GetFieldIndex('bar') != 0: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.GetLayerDefn().GetFieldIndex('foo') == 1 and lyr.GetLayerDefn().GetFieldIndex('bar') == 0 f = lyr.GetNextFeature() if f.GetFID() != 10 or f['foo'] != 'fooval' or f['bar'] != 'barval' or \ f.GetGeometryRef().ExportToWkt() != 'POLYGON ((0 0,0 1,1 1,0 0))': - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' + pytest.fail() # Check that index has been recreated sql_lyr = ds.ExecuteSQL("SELECT * FROM sqlite_master WHERE name = 'my_idx_foo' OR name = 'my_idx_bar'") - if sql_lyr.GetFeatureCount() != 2: - gdaltest.post_reason('fail') - return 'fail' + assert sql_lyr.GetFeatureCount() == 2 ds.ReleaseResultSet(sql_lyr) ds = None @@ -3391,23 +2686,19 @@ def ogr_gpkg_37(): lyr = ds.GetLayer(0) with gdaltest.error_handler(): ret = lyr.ReorderFields([1, 0]) - if ret == 0: - gdaltest.post_reason('fail') - return 'fail' + assert ret != 0 ds = None gdaltest.gpkg_dr.DeleteDataSource(dbname) - return 'success' - ############################################################################### # Test GetExtent() and RECOMPUTE EXTENT ON -def ogr_gpkg_38(options=['SPATIAL_INDEX=YES']): +def test_ogr_gpkg_38(options=['SPATIAL_INDEX=YES']): if gdaltest.gpkg_dr is None: - return 'skip' + pytest.skip() dbname = '/vsimem/ogr_gpkg_38.gpkg' ds = gdaltest.gpkg_dr.CreateDataSource(dbname) @@ -3425,28 +2716,18 @@ def ogr_gpkg_38(options=['SPATIAL_INDEX=YES']): ds = ogr.Open(dbname, update=1) lyr = ds.GetLayer(0) extent = lyr.GetExtent(force=0, can_return_null=True) - if extent is not None: - gdaltest.post_reason('fail') - print(extent) - return 'fail' + assert extent is None # Test that we can compute the extent of a layer that has none registered in gpkg_contents extent = lyr.GetExtent(force=1) - if extent != (1, 3, 2, 4): - gdaltest.post_reason('fail') - print(extent) - return 'fail' + assert extent == (1, 3, 2, 4) sql_lyr = ds.ExecuteSQL('SELECT min_x, min_y, max_x, max_y FROM gpkg_contents') f = sql_lyr.GetNextFeature() if f['min_x'] != 1 or f['min_y'] != 2 or f['max_x'] != 3 or f['max_y'] != 4: - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' + pytest.fail() ds.ReleaseResultSet(sql_lyr) extent = lyr.GetExtent(force=0) - if extent != (1, 3, 2, 4): - gdaltest.post_reason('fail') - print(extent) - return 'fail' + assert extent == (1, 3, 2, 4) # Modify feature f = lyr.GetFeature(1) @@ -3455,26 +2736,17 @@ def ogr_gpkg_38(options=['SPATIAL_INDEX=YES']): # The extent has grown extent = lyr.GetExtent(force=0) - if extent != (-3.0, 3.0, -4.0, 4.0): - gdaltest.post_reason('fail') - print(extent) - return 'fail' + assert extent == (-3.0, 3.0, -4.0, 4.0) ds.ExecuteSQL('RECOMPUTE EXTENT ON test') extent = lyr.GetExtent(force=0) - if extent != (-3.0, -1.0, -4.0, -2.0): - gdaltest.post_reason('fail') - print(extent) - return 'fail' + assert extent == (-3.0, -1.0, -4.0, -2.0) ds = None ds = ogr.Open(dbname) lyr = ds.GetLayer(0) extent = lyr.GetExtent(force=0) - if extent != (-3.0, -1.0, -4.0, -2.0): - gdaltest.post_reason('fail') - print(extent) - return 'fail' + assert extent == (-3.0, -1.0, -4.0, -2.0) ds = None ds = ogr.Open(dbname, update=1) @@ -3485,38 +2757,30 @@ def ogr_gpkg_38(options=['SPATIAL_INDEX=YES']): # This should cancel NULLify the extent in gpkg_contents ds.ExecuteSQL('RECOMPUTE EXTENT ON test') extent = lyr.GetExtent(force=0, can_return_null=True) - if extent is not None: - gdaltest.post_reason('fail') - print(extent) - return 'fail' + assert extent is None ds = None ds = ogr.Open(dbname) lyr = ds.GetLayer(0) extent = lyr.GetExtent(force=0, can_return_null=True) - if extent is not None: - gdaltest.post_reason('fail') - print(extent) - return 'fail' + assert extent is None ds = None gdaltest.gpkg_dr.DeleteDataSource(dbname) - return 'success' - -def ogr_gpkg_38_nospi(): - return ogr_gpkg_38(options=['SPATIAL_INDEX=NO']) +def test_ogr_gpkg_38_nospi(): + return test_ogr_gpkg_38(options=['SPATIAL_INDEX=NO']) ############################################################################### # Test checking of IDENTIFIER unicity -def ogr_gpkg_39(): +def test_ogr_gpkg_39(): if gdaltest.gpkg_dr is None: - return 'skip' + pytest.skip() dbname = '/vsimem/ogr_gpkg_39.gpkg' ds = gdaltest.gpkg_dr.CreateDataSource(dbname) @@ -3524,91 +2788,67 @@ def ogr_gpkg_39(): ds.CreateLayer('test') lyr = ds.CreateLayer('test_with_explicit_identifier', options=['IDENTIFIER=explicit_identifier']) - if lyr is None: - gdaltest.post_reason('fail') - return 'fail' + assert lyr is not None # Allow overwriting lyr = ds.CreateLayer('test_with_explicit_identifier', options=['IDENTIFIER=explicit_identifier', 'OVERWRITE=YES']) - if lyr is None: - gdaltest.post_reason('fail') - return 'fail' + assert lyr is not None with gdaltest.error_handler(): lyr = ds.CreateLayer('test2', options=['IDENTIFIER=test']) - if lyr is not None: - gdaltest.post_reason('fail') - return 'fail' + assert lyr is None with gdaltest.error_handler(): lyr = ds.CreateLayer('test2', options=['IDENTIFIER=explicit_identifier']) - if lyr is not None: - gdaltest.post_reason('fail') - return 'fail' + assert lyr is None ds.ExecuteSQL("INSERT INTO gpkg_contents ( table_name, identifier, data_type ) VALUES ( 'some_table', 'another_identifier', 'some_data_type' )") with gdaltest.error_handler(): lyr = ds.CreateLayer('test2', options=['IDENTIFIER=another_identifier']) - if lyr is not None: - gdaltest.post_reason('fail') - return 'fail' + assert lyr is None ds = None gdaltest.gpkg_dr.DeleteDataSource(dbname) - return 'success' - ############################################################################### # Run creating a non-spatial layer that is registered as 'attributes' and # read it back -def ogr_gpkg_40(): +def test_ogr_gpkg_40(): if gdaltest.gpkg_dr is None: - return 'skip' + pytest.skip() ds = gdaltest.gpkg_dr.CreateDataSource('/vsimem/ogr_gpkg_40.gpkg') ds.CreateLayer('aspatial', geom_type=ogr.wkbNone, options=['ASPATIAL_VARIANT=GPKG_ATTRIBUTES']) ds = None ds = ogr.Open('/vsimem/ogr_gpkg_40.gpkg') - if ds.GetLayerCount() != 1: - gdaltest.post_reason('fail') - return 'fail' + assert ds.GetLayerCount() == 1 sql_lyr = ds.ExecuteSQL("SELECT * FROM gpkg_contents WHERE table_name != 'ogr_empty_table'") - if sql_lyr.GetFeatureCount() != 1: - gdaltest.post_reason('fail') - return 'fail' + assert sql_lyr.GetFeatureCount() == 1 ds.ReleaseResultSet(sql_lyr) sql_lyr = ds.ExecuteSQL("SELECT * FROM gpkg_geometry_columns WHERE table_name != 'ogr_empty_table'") - if sql_lyr.GetFeatureCount() != 0: - gdaltest.post_reason('fail') - return 'fail' + assert sql_lyr.GetFeatureCount() == 0 ds.ReleaseResultSet(sql_lyr) sql_lyr = ds.ExecuteSQL("SELECT * FROM sqlite_master WHERE name = 'gpkg_extensions'") - if sql_lyr.GetFeatureCount() != 0: - gdaltest.post_reason('fail') - return 'fail' + assert sql_lyr.GetFeatureCount() == 0 ds.ReleaseResultSet(sql_lyr) ds = None - if not validate('/vsimem/ogr_gpkg_40.gpkg'): - gdaltest.post_reason('validation failed') - return 'fail' + assert validate('/vsimem/ogr_gpkg_40.gpkg'), 'validation failed' gdaltest.gpkg_dr.DeleteDataSource('/vsimem/ogr_gpkg_40.gpkg') - return 'success' - ############################################################################### # Test tables without integer primary key (#6799), and unrecognized column type -def ogr_gpkg_41(): +def test_ogr_gpkg_41(): if gdaltest.gpkg_dr is None: - return 'skip' + pytest.skip() ds = gdaltest.gpkg_dr.CreateDataSource('/vsimem/ogr_gpkg_41.gpkg') ds.ExecuteSQL('CREATE TABLE foo (mycol VARCHAR_ILLEGAL)') @@ -3621,9 +2861,8 @@ def ogr_gpkg_41(): with gdaltest.error_handler(): f = lyr.GetNextFeature() if f['mycol'] != 'myval' or f.GetFID() != 1: - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' + pytest.fail() ds = None ds = ogr.Open('/vsimem/ogr_gpkg_41.gpkg') @@ -3631,15 +2870,12 @@ def ogr_gpkg_41(): with gdaltest.error_handler(): f = lyr.GetFeature(1) if f['mycol'] != 'myval' or f.GetFID() != 1: - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' + pytest.fail() ds = None gdaltest.gpkg_dr.DeleteDataSource('/vsimem/ogr_gpkg_41.gpkg') - return 'success' - ############################################################################### # Test feature_count @@ -3663,10 +2899,10 @@ def get_feature_count_from_gpkg_contents(ds): return val -def ogr_gpkg_42(): +def test_ogr_gpkg_42(): if gdaltest.gpkg_dr is None: - return 'skip' + pytest.skip() ds = gdaltest.gpkg_dr.CreateDataSource('/vsimem/ogr_gpkg_42.gpkg') lyr = ds.CreateLayer('foo', geom_type=ogr.wkbNone) @@ -3679,15 +2915,9 @@ def ogr_gpkg_42(): ds = ogr.Open('/vsimem/ogr_gpkg_42.gpkg') lyr = ds.GetLayer(0) - if get_feature_count_from_gpkg_contents(ds) != 5: - gdaltest.post_reason('fail') - return 'fail' - if not foo_has_trigger(ds): - gdaltest.post_reason('fail') - return 'fail' - if lyr.TestCapability(ogr.OLCFastFeatureCount) == 0: - gdaltest.post_reason('fail') - return 'fail' + assert get_feature_count_from_gpkg_contents(ds) == 5 + assert foo_has_trigger(ds) + assert lyr.TestCapability(ogr.OLCFastFeatureCount) != 0 ds = None ds = ogr.Open('/vsimem/ogr_gpkg_42.gpkg', update=1) @@ -3697,68 +2927,42 @@ def ogr_gpkg_42(): lyr.CreateFeature(f) # Has been invalidated for now - if get_feature_count_from_gpkg_contents(ds) is not None: - gdaltest.post_reason('fail') - return 'fail' + assert get_feature_count_from_gpkg_contents(ds) is None - if foo_has_trigger(ds): - gdaltest.post_reason('fail') - return 'fail' + assert not foo_has_trigger(ds) fc = lyr.GetFeatureCount() - if fc != 6: - gdaltest.post_reason('fail') - print(fc) - return 'fail' + assert fc == 6 ds.ExecuteSQL('DELETE FROM foo WHERE i = 1') - if not foo_has_trigger(ds): - gdaltest.post_reason('fail') - return 'fail' + assert foo_has_trigger(ds) - if get_feature_count_from_gpkg_contents(ds) is not None: - gdaltest.post_reason('fail') - return 'fail' + assert get_feature_count_from_gpkg_contents(ds) is None fc = lyr.GetFeatureCount() - if fc != 5: - gdaltest.post_reason('fail') - print(fc) - return 'fail' + assert fc == 5 - if get_feature_count_from_gpkg_contents(ds) != 5: - gdaltest.post_reason('fail') - return 'fail' + assert get_feature_count_from_gpkg_contents(ds) == 5 ds = None ds = ogr.Open('/vsimem/ogr_gpkg_42.gpkg', update=1) lyr = ds.GetLayer(0) fc = lyr.GetFeatureCount() - if fc != 5: - gdaltest.post_reason('fail') - print(fc) - return 'fail' + assert fc == 5 ds.ExecuteSQL('UPDATE gpkg_ogr_contents SET feature_count = NULL') ds = None ds = ogr.Open('/vsimem/ogr_gpkg_42.gpkg', update=1) lyr = ds.GetLayer(0) - if get_feature_count_from_gpkg_contents(ds) is not None: - gdaltest.post_reason('fail') - return 'fail' + assert get_feature_count_from_gpkg_contents(ds) is None fc = lyr.GetFeatureCount() - if fc != 5: - gdaltest.post_reason('fail') - print(fc) - return 'fail' + assert fc == 5 ds = None ds = ogr.Open('/vsimem/ogr_gpkg_42.gpkg', update=1) - if get_feature_count_from_gpkg_contents(ds) != 5: - gdaltest.post_reason('fail') - return 'fail' + assert get_feature_count_from_gpkg_contents(ds) == 5 # So as to test that we really read from gpkg_ogr_contents ds.ExecuteSQL('UPDATE gpkg_ogr_contents SET feature_count = 5000') @@ -3766,10 +2970,7 @@ def ogr_gpkg_42(): ds = ogr.Open('/vsimem/ogr_gpkg_42.gpkg', update=1) lyr = ds.GetLayer(0) fc = lyr.GetFeatureCount() - if fc != 5000: - gdaltest.post_reason('fail') - print(fc) - return 'fail' + assert fc == 5000 # Test renaming ds.ExecuteSQL('ALTER TABLE foo RENAME TO bar') @@ -3780,17 +2981,13 @@ def ogr_gpkg_42(): val = f.GetField(0) f = None ds.ReleaseResultSet(sql_lyr) - if val != 5000: - gdaltest.post_reason('fail') - return 'fail' + assert val == 5000 # Test layer deletion ds.DeleteLayer(0) sql_lyr = ds.ExecuteSQL("SELECT feature_count FROM gpkg_ogr_contents WHERE table_name != 'ogr_empty_table'", dialect='DEBUG') f = sql_lyr.GetNextFeature() - if f is not None: - gdaltest.post_reason('fail') - return 'fail' + assert f is None ds.ReleaseResultSet(sql_lyr) ds = None @@ -3811,52 +3008,35 @@ def ogr_gpkg_42(): sql_lyr = ds.ExecuteSQL('PRAGMA table_info(gpkg_contents)') fc = sql_lyr.GetFeatureCount() ds.ReleaseResultSet(sql_lyr) - if fc != 10: - gdaltest.post_reason('fail') - return 'fail' + assert fc == 10 - if foo_has_trigger(ds): - gdaltest.post_reason('fail') - return 'fail' + assert not foo_has_trigger(ds) lyr = ds.GetLayer(0) - if lyr.TestCapability(ogr.OLCFastFeatureCount) != 0: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.TestCapability(ogr.OLCFastFeatureCount) == 0 fc = lyr.GetFeatureCount() - if fc != 5: - gdaltest.post_reason('fail') - print(fc) - return 'fail' + assert fc == 5 f = ogr.Feature(lyr.GetLayerDefn()) f.SetField(0, 10) lyr.CreateFeature(f) lyr = ds.GetLayer(0) fc = lyr.GetFeatureCount() - if fc != 6: - gdaltest.post_reason('fail') - print(fc) - return 'fail' + assert fc == 6 ds.ExecuteSQL('DELETE FROM foo WHERE i = 1') fc = lyr.GetFeatureCount() - if fc != 5: - gdaltest.post_reason('fail') - print(fc) - return 'fail' + assert fc == 5 ds = None gdaltest.gpkg_dr.DeleteDataSource('/vsimem/ogr_gpkg_42.gpkg') - return 'success' - ############################################################################### # Test limitations on number of tables -def ogr_gpkg_43(): +def test_ogr_gpkg_43(): if gdaltest.gpkg_dr is None: - return 'skip' + pytest.skip() ds = gdaltest.gpkg_dr.CreateDataSource('/vsimem/ogr_gpkg_43.gpkg') ds.StartTransaction() @@ -3874,33 +3054,25 @@ def ogr_gpkg_43(): with gdaltest.error_handler(): ds = gdal.Open('/vsimem/ogr_gpkg_43.gpkg') - if len(ds.GetMetadata_List('SUBDATASETS')) != 2 * 1000: - gdaltest.post_reason('fail') - print(len(ds.GetMetadata_List('SUBDATASETS'))) - return 'fail' + assert len(ds.GetMetadata_List('SUBDATASETS')) == 2 * 1000 ds = None gdal.SetConfigOption('OGR_TABLE_LIMIT', '1000') with gdaltest.error_handler(): ds = ogr.Open('/vsimem/ogr_gpkg_43.gpkg') gdal.SetConfigOption('OGR_TABLE_LIMIT', None) - if ds.GetLayerCount() != 1000: - gdaltest.post_reason('fail') - print(ds.GetLayerCount()) - return 'fail' + assert ds.GetLayerCount() == 1000 ds = None gdaltest.gpkg_dr.DeleteDataSource('/vsimem/ogr_gpkg_43.gpkg') - return 'success' - ############################################################################### # Test GeoPackage without metadata table -def ogr_gpkg_44(): +def test_ogr_gpkg_44(): if gdaltest.gpkg_dr is None: - return 'skip' + pytest.skip() gdal.SetConfigOption('CREATE_METADATA_TABLES', 'NO') ds = gdaltest.gpkg_dr.CreateDataSource('/vsimem/ogr_gpkg_44.gpkg') @@ -3908,27 +3080,17 @@ def ogr_gpkg_44(): ds = None gdal.SetConfigOption('CREATE_METADATA_TABLES', None) - if not validate('/vsimem/ogr_gpkg_44.gpkg'): - gdaltest.post_reason('validation failed') - return 'fail' + assert validate('/vsimem/ogr_gpkg_44.gpkg'), 'validation failed' ds = ogr.Open('/vsimem/ogr_gpkg_44.gpkg') md = ds.GetMetadata() - if md != {}: - gdaltest.post_reason('fail') - print(md) - return 'fail' + assert md == {} md = ds.GetLayer(0).GetMetadata() - if md != {}: - gdaltest.post_reason('fail') - print(md) - return 'fail' + assert md == {} sql_lyr = ds.ExecuteSQL("SELECT * FROM sqlite_master WHERE name = 'gpkg_metadata'") fc = sql_lyr.GetFeatureCount() ds.ReleaseResultSet(sql_lyr) - if fc != 0: - gdaltest.post_reason('fail') - return 'fail' + assert fc == 0 ds = None ds = ogr.Open('/vsimem/ogr_gpkg_44.gpkg', update=1) @@ -3937,24 +3099,19 @@ def ogr_gpkg_44(): ds = ogr.Open('/vsimem/ogr_gpkg_44.gpkg') md = ds.GetMetadata() - if md != {'FOO': 'BAR'}: - gdaltest.post_reason('fail') - print(md) - return 'fail' + assert md == {'FOO': 'BAR'} ds = None gdaltest.gpkg_dr.DeleteDataSource('/vsimem/ogr_gpkg_44.gpkg') - return 'success' - ############################################################################### # Test non conformant GeoPackage: table with non INTEGER PRIMARY KEY -def ogr_gpkg_45(): +def test_ogr_gpkg_45(): if gdaltest.gpkg_dr is None: - return 'skip' + pytest.skip() ds = gdaltest.gpkg_dr.CreateDataSource('/vsimem/ogr_gpkg_45.gpkg') ds.ExecuteSQL('CREATE TABLE test (a INTEGER, b INTEGER, CONSTRAINT pkid_constraint PRIMARY KEY (a, b))') @@ -3962,26 +3119,20 @@ def ogr_gpkg_45(): ds = None ds = ogr.Open('/vsimem/ogr_gpkg_45.gpkg') lyr = ds.GetLayer(0) - if lyr.GetFIDColumn() != '': - gdaltest.post_reason('fail') - return 'fail' - if lyr.GetLayerDefn().GetFieldCount() != 2: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.GetFIDColumn() == '' + assert lyr.GetLayerDefn().GetFieldCount() == 2 ds = None gdaltest.gpkg_dr.DeleteDataSource('/vsimem/ogr_gpkg_45.gpkg') - return 'success' - ############################################################################### # Test spatial view and spatial index -def ogr_gpkg_46(): +def test_ogr_gpkg_46(): if gdaltest.gpkg_dr is None: - return 'skip' + pytest.skip() ds = gdaltest.gpkg_dr.CreateDataSource('/vsimem/ogr_gpkg_46.gpkg') lyr = ds.CreateLayer('foo') @@ -4007,14 +3158,8 @@ def ogr_gpkg_46(): ds = ogr.Open('/vsimem/ogr_gpkg_46.gpkg', update=1) lyr = ds.GetLayerByName('my_view') - if lyr.GetLayerDefn().GetFieldCount() != 1: - gdaltest.post_reason('fail') - print(lyr.GetLayerDefn().GetFieldCount()) - return 'fail' - if lyr.GetGeometryColumn() != 'my_geom': - gdaltest.post_reason('fail') - print(lyr.GetGeometryColumn()) - return 'fail' + assert lyr.GetLayerDefn().GetFieldCount() == 1 + assert lyr.GetGeometryColumn() == 'my_geom' # Operations not valid on a view with gdaltest.error_handler(): @@ -4033,75 +3178,54 @@ def ogr_gpkg_46(): if not has_spatial_index: ds = None gdaltest.gpkg_dr.DeleteDataSource('/vsimem/ogr_gpkg_46.gpkg') - print('SQLite likely built without SQLITE_HAS_COLUMN_METADATA') - return 'skip' + pytest.skip('SQLite likely built without SQLITE_HAS_COLUMN_METADATA') # Effectively test spatial index lyr.SetSpatialFilterRect(-0.5, -0.5, 0.5, 0.5) - if lyr.GetFeatureCount() != 1: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.GetFeatureCount() == 1 f = lyr.GetNextFeature() - if f is None: - gdaltest.post_reason('fail') - return 'fail' + assert f is not None f = lyr.GetNextFeature() - if f is not None: - gdaltest.post_reason('fail') - return 'fail' + assert f is None # View with FID lyr = ds.GetLayerByName('my_view2') - if lyr.GetLayerDefn().GetFieldCount() != 1: - gdaltest.post_reason('fail') - print(lyr.GetLayerDefn().GetFieldCount()) - return 'fail' - if lyr.GetFIDColumn() != 'OGC_FID': - gdaltest.post_reason('fail') - return 'fail' + assert lyr.GetLayerDefn().GetFieldCount() == 1 + assert lyr.GetFIDColumn() == 'OGC_FID' f = lyr.GetNextFeature() if f.GetFID() != 1 or f.GetField(0) != 'bla': - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' + pytest.fail() # View without valid rowid lyr = ds.GetLayerByName('my_view3') - if lyr.GetLayerDefn().GetFieldCount() != 2: - gdaltest.post_reason('fail') - print(lyr.GetLayerDefn().GetFieldCount()) - return 'fail' + assert lyr.GetLayerDefn().GetFieldCount() == 2 f = lyr.GetNextFeature() if f.GetFID() != 0: - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' + pytest.fail() f = lyr.GetNextFeature() if f.GetFID() != 1: - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' + pytest.fail() f2 = lyr.GetFeature(1) if not f.Equal(f2): - gdaltest.post_reason('fail') f.DumpReadable() f2.DumpReadable() - return 'fail' + pytest.fail() ds = None gdaltest.gpkg_dr.DeleteDataSource('/vsimem/ogr_gpkg_46.gpkg') - return 'success' - ############################################################################### # Test corner case of Identify() -def ogr_gpkg_47(): +def test_ogr_gpkg_47(): if gdaltest.gpkg_dr is None: - return 'skip' + pytest.skip() gdaltest.gpkg_dr.CreateDataSource('/vsimem/ogr_gpkg_47.gpkg') # Set wrong application_id @@ -4112,20 +3236,13 @@ def ogr_gpkg_47(): with gdaltest.error_handler(): ds = ogr.Open('/vsimem/ogr_gpkg_47.gpkg', update=1) - if ds is None: - gdaltest.post_reason('fail') - return 'fail' - if gdal.GetLastErrorMsg() == '': - gdaltest.post_reason('fail') - return 'fail' + assert ds is not None + assert gdal.GetLastErrorMsg() != '' gdal.SetConfigOption('GPKG_WARN_UNRECOGNIZED_APPLICATION_ID', 'NO') ogr.Open('/vsimem/ogr_gpkg_47.gpkg') gdal.SetConfigOption('GPKG_WARN_UNRECOGNIZED_APPLICATION_ID', None) - if gdal.GetLastErrorMsg() != '': - gdaltest.post_reason('fail') - print(gdal.GetLastErrorMsg()) - return 'fail' + assert gdal.GetLastErrorMsg() == '' gdaltest.gpkg_dr.CreateDataSource('/vsimem/ogr_gpkg_47.gpkg', options=['VERSION=1.2']) # Set wrong user_version @@ -4136,20 +3253,14 @@ def ogr_gpkg_47(): with gdaltest.error_handler(): ds = ogr.Open('/vsimem/ogr_gpkg_47.gpkg', update=1) - if ds is None: - gdaltest.post_reason('fail') - return 'fail' - if gdal.GetLastErrorMsg() == '': - gdaltest.post_reason('fail') - return 'fail' + assert ds is not None + assert gdal.GetLastErrorMsg() != '' ds = None gdal.SetConfigOption('GPKG_WARN_UNRECOGNIZED_APPLICATION_ID', 'NO') ogr.Open('/vsimem/ogr_gpkg_47.gpkg') gdal.SetConfigOption('GPKG_WARN_UNRECOGNIZED_APPLICATION_ID', None) - if gdal.GetLastErrorMsg() != '': - gdaltest.post_reason('fail') - return 'fail' + assert gdal.GetLastErrorMsg() == '' # Set GPKG 1.2.1 gdaltest.gpkg_dr.CreateDataSource('/vsimem/ogr_gpkg_47.gpkg', options=['VERSION=1.2']) @@ -4160,20 +3271,14 @@ def ogr_gpkg_47(): gdal.VSIFCloseL(fp) ds = ogr.Open('/vsimem/ogr_gpkg_47.gpkg', update=1) - if ds is None: - gdaltest.post_reason('fail') - return 'fail' - if gdal.GetLastErrorMsg() != '': - gdaltest.post_reason('fail') - return 'fail' + assert ds is not None + assert gdal.GetLastErrorMsg() == '' ds = None gdal.SetConfigOption('GPKG_WARN_UNRECOGNIZED_APPLICATION_ID', 'NO') ogr.Open('/vsimem/ogr_gpkg_47.gpkg') gdal.SetConfigOption('GPKG_WARN_UNRECOGNIZED_APPLICATION_ID', None) - if gdal.GetLastErrorMsg() != '': - gdaltest.post_reason('fail') - return 'fail' + assert gdal.GetLastErrorMsg() == '' # Set GPKG 1.3.0 gdaltest.gpkg_dr.CreateDataSource('/vsimem/ogr_gpkg_47.gpkg', options=['VERSION=1.2']) @@ -4185,19 +3290,13 @@ def ogr_gpkg_47(): with gdaltest.error_handler(): ds = ogr.Open('/vsimem/ogr_gpkg_47.gpkg', update=1) - if ds is None: - gdaltest.post_reason('fail') - return 'fail' - if gdal.GetLastErrorMsg() == '': - gdaltest.post_reason('fail') - return 'fail' + assert ds is not None + assert gdal.GetLastErrorMsg() != '' gdal.SetConfigOption('GPKG_WARN_UNRECOGNIZED_APPLICATION_ID', 'NO') ogr.Open('/vsimem/ogr_gpkg_47.gpkg') gdal.SetConfigOption('GPKG_WARN_UNRECOGNIZED_APPLICATION_ID', None) - if gdal.GetLastErrorMsg() != '': - gdaltest.post_reason('fail') - return 'fail' + assert gdal.GetLastErrorMsg() == '' # Just for the sake of coverage testing in DEBUG mode with gdaltest.error_handler(): @@ -4233,24 +3332,20 @@ def ogr_gpkg_47(): gdal.VSIFCloseL(fp) gdal.VSIFCloseL(fzip) ds = ogr.Open('/vsizip//vsimem/ogr_gpkg_47.zip') - if ds.GetDriver().GetName() != 'GPKG': - gdaltest.post_reason('fail') - return 'fail' + assert ds.GetDriver().GetName() == 'GPKG' ds = None gdal.Unlink('/vsimem/ogr_gpkg_47.zip') gdaltest.gpkg_dr.DeleteDataSource('/vsimem/ogr_gpkg_47.gpkg') - return 'success' - ############################################################################### # Test insertion of features with unset fields -def ogr_gpkg_48(): +def test_ogr_gpkg_48(): if gdaltest.gpkg_dr is None: - return 'skip' + pytest.skip() ds = gdaltest.gpkg_dr.CreateDataSource('/vsimem/ogr_gpkg_48.gpkg') lyr = ds.CreateLayer('foo') @@ -4267,14 +3362,12 @@ def ogr_gpkg_48(): lyr.ResetReading() f = lyr.GetNextFeature() if f.GetField('a') != 'a' or f.GetField('b') is not None: - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' + pytest.fail() f = lyr.GetNextFeature() if f.GetField('b') != 'b' or f.GetField('c') != 'c' or f.GetField('a') is not None: - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' + pytest.fail() # No geom field, one single field with default value lyr = ds.CreateLayer('default_field_no_geom', geom_type=ogr.wkbNone) @@ -4282,40 +3375,32 @@ def ogr_gpkg_48(): fld_defn.SetDefault('x') lyr.CreateField(fld_defn) f = ogr.Feature(lyr.GetLayerDefn()) - if lyr.CreateFeature(f) != 0: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.CreateFeature(f) == 0 lyr.ResetReading() f = lyr.GetNextFeature() if f.GetField('foo') != 'x': - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' + pytest.fail() f = ogr.Feature(lyr.GetLayerDefn()) f.SetFID(1) - if lyr.SetFeature(f) != 0: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.SetFeature(f) == 0 lyr.ResetReading() f = lyr.GetNextFeature() if f.GetField('foo') != 'x': - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' + pytest.fail() ds = None gdaltest.gpkg_dr.DeleteDataSource('/vsimem/ogr_gpkg_48.gpkg') - return 'success' - ############################################################################### # Test CreateGeomField() on a attributes layer -def ogr_gpkg_49(): +def test_ogr_gpkg_49(): if gdaltest.gpkg_dr is None: - return 'skip' + pytest.skip() ds = gdaltest.gpkg_dr.CreateDataSource('/vsimem/ogr_gpkg_49.gpkg') @@ -4327,23 +3412,19 @@ def ogr_gpkg_49(): f = None field_defn = ogr.GeomFieldDefn('', ogr.wkbPoint) - if lyr.CreateGeomField(field_defn) != 0: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.CreateGeomField(field_defn) == 0 ds = None gdaltest.gpkg_dr.DeleteDataSource('/vsimem/ogr_gpkg_49.gpkg') - return 'success' - ############################################################################### # Test minimalistic support of definition_12_063 -def ogr_gpkg_50(): +def test_ogr_gpkg_50(): if gdaltest.gpkg_dr is None: - return 'skip' + pytest.skip() gdal.SetConfigOption('GPKG_ADD_DEFINITION_12_063', 'YES') gdaltest.gpkg_dr.CreateDataSource('/vsimem/ogr_gpkg_50.gpkg') @@ -4363,109 +3444,86 @@ def ogr_gpkg_50(): ds = None - if not validate('/vsimem/ogr_gpkg_50.gpkg'): - gdaltest.post_reason('validation failed') - return 'fail' + assert validate('/vsimem/ogr_gpkg_50.gpkg'), 'validation failed' ds = ogr.Open('/vsimem/ogr_gpkg_50.gpkg') lyr = ds.GetLayer('test') - if not lyr.GetSpatialRef().IsSame(srs32631): - gdaltest.post_reason('fail') - return 'fail' + assert lyr.GetSpatialRef().IsSame(srs32631) lyr = ds.GetLayer('without_org') - if not lyr.GetSpatialRef().IsSame(srs_without_org): - gdaltest.post_reason('fail') - return 'fail' + assert lyr.GetSpatialRef().IsSame(srs_without_org) sql_lyr = ds.ExecuteSQL('SELECT definition_12_063 FROM gpkg_spatial_ref_sys WHERE srs_id = 32631') f = sql_lyr.GetNextFeature() - if f.GetField(0) != 'undefined': - gdaltest.post_reason('fail') - return 'fail' + assert f.GetField(0) == 'undefined' ds.ReleaseResultSet(sql_lyr) ds = None gdaltest.gpkg_dr.DeleteDataSource('/vsimem/ogr_gpkg_50.gpkg') - return 'success' - ############################################################################### # Test opening a .gpkg.sql file -def ogr_gpkg_51(): +def test_ogr_gpkg_51(): if gdaltest.gpkg_dr is None: - return 'skip' + pytest.skip() if gdaltest.gpkg_dr.GetMetadataItem("ENABLE_SQL_GPKG_FORMAT") != 'YES': - return 'skip' + pytest.skip() ds = ogr.Open('data/poly.gpkg.sql') lyr = ds.GetLayer(0) f = lyr.GetNextFeature() - if f is None: - return 'fail' - - return 'success' + assert f is not None ############################################################################### # Test opening a .gpkg file -def ogr_gpkg_52(): +def test_ogr_gpkg_52(): if gdaltest.gpkg_dr is None: - return 'skip' + pytest.skip() ds = ogr.Open('data/poly_non_conformant.gpkg') lyr = ds.GetLayer(0) with gdaltest.error_handler(): f = lyr.GetNextFeature() - if f is None: - return 'fail' - - return 'success' + assert f is not None ############################################################################### # Test opening a .gpkg file with inconsistency regarding table case (#6916) -def ogr_gpkg_53(): +def test_ogr_gpkg_53(): if gdaltest.gpkg_dr is None: - return 'skip' + pytest.skip() if gdaltest.gpkg_dr.GetMetadataItem("ENABLE_SQL_GPKG_FORMAT") != 'YES': - return 'skip' + pytest.skip() ds = ogr.Open('data/poly_inconsistent_case.gpkg.sql') - if ds.GetLayerCount() != 1: - gdaltest.post_reason('fail') - return 'fail' + assert ds.GetLayerCount() == 1 lyr = ds.GetLayer(0) f = lyr.GetNextFeature() - if f is None: - return 'fail' + assert f is not None import test_cli_utilities if test_cli_utilities.get_test_ogrsf_path() is not None: ret = gdaltest.runexternal(test_cli_utilities.get_test_ogrsf_path() + ' data/poly_inconsistent_case.gpkg.sql') - if ret.find('INFO') == -1 or ret.find('ERROR') != -1: - gdaltest.post_reason('fail') - print(ret) - return 'fail' - - return 'success' + assert ret.find('INFO') != -1 and ret.find('ERROR') == -1 + ############################################################################### # Test editing of a database with 2 layers (https://issues.qgis.org/issues/17034) -def ogr_gpkg_54(): +def test_ogr_gpkg_54(): if gdaltest.gpkg_dr is None: - return 'skip' + pytest.skip() # Must be on a real file system to demonstrate potential locking # issue @@ -4512,29 +3570,25 @@ def ogr_gpkg_54(): lyr1 = ds.GetLayer(0) f = lyr1.GetNextFeature() if f.GetGeometryRef().ExportToWkt() != 'POINT (5 6)': - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' + pytest.fail() lyr2 = ds.GetLayer(1) f = lyr2.GetNextFeature() if f.GetGeometryRef().ExportToWkt() != 'POINT (7 8)': - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' + pytest.fail() ds = None gdal.Unlink(tmpfile) - return 'success' - ############################################################################### # Test inserting geometries incompatible with declared layer geometry type -def ogr_gpkg_55(): +def test_ogr_gpkg_55(): if gdaltest.gpkg_dr is None: - return 'skip' + pytest.skip() tmpfile = '/vsimem/ogr_gpkg_55.gpkg' ds = ogr.GetDriverByName('GPKG').CreateDataSource(tmpfile) @@ -4544,32 +3598,26 @@ def ogr_gpkg_55(): gdal.ErrorReset() with gdaltest.error_handler(): lyr.CreateFeature(f) - if gdal.GetLastErrorMsg() == '': - gdaltest.post_reason('should have warned') - return 'fail' + assert gdal.GetLastErrorMsg() != '', 'should have warned' f = None f = ogr.Feature(lyr.GetLayerDefn()) f.SetGeometry(ogr.CreateGeometryFromWkt('POINT(1 1)')) gdal.ErrorReset() lyr.CreateFeature(f) - if gdal.GetLastErrorMsg() != '': - gdaltest.post_reason('should NOT have warned') - return 'fail' + assert gdal.GetLastErrorMsg() == '', 'should NOT have warned' f = None ds = None gdal.Unlink(tmpfile) - return 'success' - ############################################################################### # Test FID identification on SQL result layer -def ogr_gpkg_56(): +def test_ogr_gpkg_56(): if gdaltest.gpkg_dr is None: - return 'skip' + pytest.skip() ds = gdal.VectorTranslate('/vsimem/ogr_gpkg_56.gpkg', 'data/poly.shp', format='GPKG') lyr = ds.ExecuteSQL('select a.fid as fid1, b.fid as fid2 from poly a, poly b order by fid1, fid2') @@ -4577,24 +3625,22 @@ def ogr_gpkg_56(): f = lyr.GetNextFeature() if f.GetField('fid1') != 1 or f.GetField('fid2') != 2: f.DumpReadable() - return 'fail' + pytest.fail() ds.ReleaseResultSet(lyr) ds = None gdal.Unlink('/vsimem/ogr_gpkg_56.gpkg') - return 'success' - ############################################################################### # Test opening a corrupted gpkg with duplicated layer names -def ogr_gpkg_57(): +def test_ogr_gpkg_57(): if gdaltest.gpkg_dr is None: - return 'skip' + pytest.skip() if gdaltest.gpkg_dr.GetMetadataItem("ENABLE_SQL_GPKG_FORMAT") != 'YES': - return 'skip' + pytest.skip() tmpfile = '/vsimem/tmp.gpkg.txt' gdal.FileFromMemBuffer(tmpfile, @@ -4611,26 +3657,21 @@ def ogr_gpkg_57(): with gdaltest.error_handler(): ds = ogr.Open(tmpfile) - if ds.GetLayerCount() != 1: - gdaltest.post_reason('bad layer count') - return 'fail' - if gdal.GetLastErrorMsg().find('Table poly appearing several times') < 0: - gdaltest.post_reason('should NOT have warned') - return 'fail' + assert ds.GetLayerCount() == 1, 'bad layer count' + assert gdal.GetLastErrorMsg().find('Table poly appearing several times') >= 0, \ + 'should NOT have warned' ds = None gdal.Unlink(tmpfile) - return 'success' - ############################################################################### # Test overwriting a layer -def ogr_gpkg_58(): +def test_ogr_gpkg_58(): if gdaltest.gpkg_dr is None: - return 'skip' + pytest.skip() out_filename = '/vsimem/ogr_gpkg_58.gpkg' gdal.VectorTranslate(out_filename, 'data/poly.shp', format='GPKG') @@ -4640,23 +3681,20 @@ def ogr_gpkg_58(): ds = ogr.Open(out_filename) sql_lyr = ds.ExecuteSQL("SELECT HasSpatialIndex('poly', 'geom')") f = sql_lyr.GetNextFeature() - if f.GetField(0) != 1: - return 'fail' + assert f.GetField(0) == 1 ds.ReleaseResultSet(sql_lyr) ds = None gdal.Unlink(out_filename) - return 'success' - ############################################################################### # Test CreateSpatialIndex() -def ogr_gpkg_59(): +def test_ogr_gpkg_59(): if gdaltest.gpkg_dr is None: - return 'skip' + pytest.skip() out_filename = '/vsimem/ogr_gpkg_59.gpkg' gdal.VectorTranslate(out_filename, 'data/poly.shp', format='GPKG', @@ -4665,23 +3703,20 @@ def ogr_gpkg_59(): ds = ogr.Open(out_filename, update=1) sql_lyr = ds.ExecuteSQL("SELECT CreateSpatialIndex('poly', 'geom')") f = sql_lyr.GetNextFeature() - if f.GetField(0) != 1: - return 'fail' + assert f.GetField(0) == 1 ds.ReleaseResultSet(sql_lyr) ds = None gdal.Unlink(out_filename) - return 'success' - ############################################################################### # Test savepoints -def ogr_gpkg_savepoint(): +def test_ogr_gpkg_savepoint(): if gdaltest.gpkg_dr is None: - return 'skip' + pytest.skip() filename = '/vsimem/ogr_gpkg_savepoint.gpkg' ds = gdaltest.gpkg_dr.CreateDataSource(filename) @@ -4706,27 +3741,23 @@ def ogr_gpkg_savepoint(): ds = ogr.Open(filename) lyr = ds.GetLayer(0) - if lyr.GetFeatureCount() != 2: - print(lyr.GetFeatureCount()) - return 'fail' + assert lyr.GetFeatureCount() == 2 ds = None gdal.Unlink(filename) - return 'success' - ############################################################################### # Test that we don't open file handles behind the back of sqlite3 -def ogr_gpkg_wal(): +def test_ogr_gpkg_wal(): if gdaltest.gpkg_dr is None: - return 'skip' + pytest.skip() import test_cli_utilities if test_cli_utilities.get_ogrinfo_path() is None: - return 'skip' + pytest.skip() # needs to be a real file filename = 'tmp/ogr_gpkg_wal.gpkg' @@ -4757,16 +3788,45 @@ def ogr_gpkg_wal(): gdal.Unlink(filename + '-wal') gdal.Unlink(filename + '-shm') - return 'success' + +############################################################################### +# Run test_ogrsf + + +def test_ogr_gpkg_test_ogrsf(): + + if gdaltest.gpkg_dr is None: + pytest.skip() + + # Do integrity check first + sql_lyr = gdaltest.gpkg_ds.ExecuteSQL("PRAGMA integrity_check") + feat = sql_lyr.GetNextFeature() + assert feat.GetField(0) == 'ok', 'integrity check failed' + gdaltest.gpkg_ds.ReleaseResultSet(sql_lyr) + + import test_cli_utilities + if test_cli_utilities.get_test_ogrsf_path() is None: + pytest.skip() + + gdaltest.gpkg_ds = None + # sys.exit(0) + ret = gdaltest.runexternal(test_cli_utilities.get_test_ogrsf_path() + ' tmp/gpkg_test.gpkg --config OGR_SQLITE_SYNCHRONOUS OFF') + + assert ret.find('INFO') != -1 and ret.find('ERROR') == -1 + + ret = gdaltest.runexternal(test_cli_utilities.get_test_ogrsf_path() + ' tmp/gpkg_test.gpkg -sql "select * from tbl_linestring_renamed" --config OGR_SQLITE_SYNCHRONOUS OFF') + + assert ret.find('INFO') != -1 and ret.find('ERROR') == -1 + ############################################################################### # Test JSon subtype support -def ogr_gpkg_json(): +def test_ogr_gpkg_json(): if gdaltest.gpkg_dr is None: - return 'skip' + pytest.skip() filename = '/vsimem/ogr_gpkg_json.gpkg' ds = gdaltest.gpkg_dr.CreateDataSource(filename) @@ -4775,18 +3835,14 @@ def ogr_gpkg_json(): fld_defn = ogr.FieldDefn('test_json', ogr.OFTString) fld_defn.SetSubType(ogr.OFSTJSON) lyr.CreateField(fld_defn) - if lyr.GetLayerDefn().GetFieldDefn(0).GetSubType() != ogr.OFSTJSON: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.GetLayerDefn().GetFieldDefn(0).GetSubType() == ogr.OFSTJSON ds.ReleaseResultSet(ds.ExecuteSQL('SELECT 1 FROM test')) # will crystalize fld_defn = ogr.FieldDefn('test2_json', ogr.OFTString) fld_defn.SetSubType(ogr.OFSTJSON) lyr.CreateField(fld_defn) - if lyr.GetLayerDefn().GetFieldDefn(1).GetSubType() != ogr.OFSTJSON: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.GetLayerDefn().GetFieldDefn(1).GetSubType() == ogr.OFSTJSON fld_defn = ogr.FieldDefn('test_string', ogr.OFTString) lyr.CreateField(fld_defn) @@ -4795,69 +3851,49 @@ def ogr_gpkg_json(): ds = ogr.Open(filename, update = 1) lyr = ds.GetLayer(0) - if lyr.GetLayerDefn().GetFieldDefn(0).GetSubType() != ogr.OFSTJSON: - gdaltest.post_reason('fail') - return 'fail' - if lyr.GetLayerDefn().GetFieldDefn(1).GetSubType() != ogr.OFSTJSON: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.GetLayerDefn().GetFieldDefn(0).GetSubType() == ogr.OFSTJSON + assert lyr.GetLayerDefn().GetFieldDefn(1).GetSubType() == ogr.OFSTJSON # Demote field from JSON new_defn = ogr.FieldDefn('test_was_json_now_string', ogr.OFTString) - if lyr.AlterFieldDefn(lyr.GetLayerDefn().GetFieldIndex('test2_json'), new_defn, ogr.ALTER_ALL_FLAG) != 0: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.AlterFieldDefn(lyr.GetLayerDefn().GetFieldIndex('test2_json'), new_defn, ogr.ALTER_ALL_FLAG) == 0 # Alter field to JSON new_defn = ogr.FieldDefn('test_was_string_now_json', ogr.OFTString) new_defn.SetSubType(ogr.OFSTJSON) - if lyr.AlterFieldDefn(lyr.GetLayerDefn().GetFieldIndex('test_string'), new_defn, ogr.ALTER_ALL_FLAG) != 0: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.AlterFieldDefn(lyr.GetLayerDefn().GetFieldIndex('test_string'), new_defn, ogr.ALTER_ALL_FLAG) == 0 # Delete JSON field - if lyr.DeleteField(lyr.GetLayerDefn().GetFieldIndex('test_json')) != 0: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.DeleteField(lyr.GetLayerDefn().GetFieldIndex('test_json')) == 0 ds = None - if not validate(filename): - gdaltest.post_reason('validation failed') - return 'fail' + assert validate(filename), 'validation failed' ds = ogr.Open(filename) lyr = ds.GetLayer(0) - if lyr.GetLayerDefn().GetFieldDefn( - lyr.GetLayerDefn().GetFieldIndex('test_was_json_now_string')).GetSubType() != ogr.OFSTNone: - gdaltest.post_reason('fail') - return 'fail' - if lyr.GetLayerDefn().GetFieldDefn( - lyr.GetLayerDefn().GetFieldIndex('test_was_string_now_json')).GetSubType() != ogr.OFSTJSON: - gdaltest.post_reason('fail') - return 'fail' + assert (lyr.GetLayerDefn().GetFieldDefn( + lyr.GetLayerDefn().GetFieldIndex('test_was_json_now_string')).GetSubType() == ogr.OFSTNone) + assert (lyr.GetLayerDefn().GetFieldDefn( + lyr.GetLayerDefn().GetFieldIndex('test_was_string_now_json')).GetSubType() == ogr.OFSTJSON) sql_lyr = ds.ExecuteSQL("SELECT 1 FROM gpkg_data_columns WHERE table_name = 'test'") fc = sql_lyr.GetFeatureCount() ds.ReleaseResultSet(sql_lyr) - if fc != 1: # only test_was_string_now_json remaining - gdaltest.post_reason('fail') - return 'fail' + assert fc == 1 ds = None gdal.Unlink(filename) - return 'success' - ############################################################################### # Remove the test db from the tmp directory -def ogr_gpkg_cleanup(): +def test_ogr_gpkg_cleanup(): if gdaltest.gpkg_dr is None: - return 'skip' + pytest.skip() gdaltest.gpkg_ds = None @@ -4871,84 +3907,5 @@ def ogr_gpkg_cleanup(): except OSError: pass - return 'success' - + ############################################################################### - - -gdaltest_list = [ - ogr_gpkg_1, - ogr_gpkg_2, - ogr_gpkg_3, - ogr_gpkg_4, - ogr_gpkg_5, - ogr_gpkg_6, - ogr_gpkg_7, - ogr_gpkg_8, - ogr_gpkg_9, - ogr_gpkg_11, - ogr_gpkg_12, - ogr_gpkg_13, - ogr_gpkg_14, - ogr_gpkg_15, - ogr_gpkg_16, - ogr_gpkg_17, - ogr_gpkg_18, - ogr_gpkg_19, - ogr_gpkg_20, - ogr_gpkg_21, - ogr_gpkg_22, - ogr_gpkg_23, - ogr_gpkg_24, - ogr_gpkg_25, - ogr_gpkg_26, - ogr_gpkg_27, - ogr_gpkg_28, - ogr_gpkg_29, - ogr_gpkg_30, - ogr_gpkg_31, - ogr_gpkg_32, - ogr_gpkg_33, - ogr_gpkg_34, - ogr_gpkg_35, - ogr_gpkg_36, - ogr_gpkg_37, - ogr_gpkg_38, - ogr_gpkg_38_nospi, - ogr_gpkg_39, - ogr_gpkg_40, - ogr_gpkg_41, - ogr_gpkg_42, - ogr_gpkg_43, - ogr_gpkg_44, - ogr_gpkg_45, - ogr_gpkg_46, - ogr_gpkg_47, - ogr_gpkg_48, - ogr_gpkg_49, - ogr_gpkg_50, - ogr_gpkg_51, - ogr_gpkg_52, - ogr_gpkg_53, - ogr_gpkg_54, - ogr_gpkg_55, - ogr_gpkg_56, - ogr_gpkg_57, - ogr_gpkg_58, - ogr_gpkg_59, - ogr_gpkg_savepoint, - ogr_gpkg_wal, - ogr_gpkg_json, - ogr_gpkg_test_ogrsf, - ogr_gpkg_cleanup, -] - -# gdaltest_list = [ ogr_gpkg_1, ogr_gpkg_47, ogr_gpkg_cleanup ] - -if __name__ == '__main__': - - gdaltest.setup_run('ogr_gpkg') - - gdaltest.run_tests(gdaltest_list) - - sys.exit(gdaltest.summarize()) diff --git a/autotest/ogr/ogr_gpsbabel.py b/autotest/ogr/ogr_gpsbabel.py index d21c0ed8eb35..a6a516a444e3 100755 --- a/autotest/ogr/ogr_gpsbabel.py +++ b/autotest/ogr/ogr_gpsbabel.py @@ -28,20 +28,19 @@ # DEALINGS IN THE SOFTWARE. ############################################################################### -import sys -sys.path.append('../pymod') import gdaltest import ogrtest from osgeo import ogr from osgeo import gdal +import pytest ############################################################################### # Check that dependencies are met -def ogr_gpsbabel_init(): +def test_ogr_gpsbabel_init(): # Test if the gpsbabel is accessible ogrtest.have_gpsbabel = False @@ -51,8 +50,7 @@ def ogr_gpsbabel_init(): except OSError: ret = '' if ret.find('GPSBabel') == -1: - print('Cannot access GPSBabel utility') - return 'skip' + pytest.skip('Cannot access GPSBabel utility') ds = ogr.Open('data/test.gpx') @@ -63,52 +61,42 @@ def ogr_gpsbabel_init(): ogrtest.have_gpsbabel = True - return 'success' - ############################################################################### # Test reading with explicit subdriver -def ogr_gpsbabel_1(): +def test_ogr_gpsbabel_1(): if not ogrtest.have_read_gpsbabel: - return 'skip' + pytest.skip() ds = ogr.Open('GPSBabel:nmea:data/nmea.txt') - if ds is None: - return 'fail' - - if ds.GetLayerCount() != 2: - return 'fail' + assert ds is not None - return 'success' + assert ds.GetLayerCount() == 2 ############################################################################### # Test reading with implicit subdriver -def ogr_gpsbabel_2(): +def test_ogr_gpsbabel_2(): if not ogrtest.have_read_gpsbabel: - return 'skip' + pytest.skip() ds = ogr.Open('data/nmea.txt') - if ds is None: - return 'fail' - - if ds.GetLayerCount() != 2: - return 'fail' + assert ds is not None - return 'success' + assert ds.GetLayerCount() == 2 ############################################################################### # Test writing -def ogr_gpsbabel_3(): +def test_ogr_gpsbabel_3(): if not ogrtest.have_gpsbabel: - return 'skip' + pytest.skip() ds = ogr.GetDriverByName('GPSBabel').CreateDataSource('GPSBabel:nmea:tmp/nmea.txt') lyr = ds.CreateLayer('track_points', geom_type=ogr.wkbPoint) @@ -138,27 +126,10 @@ def ogr_gpsbabel_3(): gdal.Unlink('tmp/nmea.txt') - if res.find('$GPRMC') == -1 or \ + assert (not (res.find('$GPRMC') == -1 or \ res.find('$GPGGA') == -1 or \ - res.find('$GPGSA') == -1: - gdaltest.post_reason('did not get expected result') - print(res) - return 'fail' - - return 'success' - - -gdaltest_list = [ - ogr_gpsbabel_init, - ogr_gpsbabel_1, - ogr_gpsbabel_2, - ogr_gpsbabel_3] - + res.find('$GPGSA') == -1)), 'did not get expected result' -if __name__ == '__main__': - gdaltest.setup_run('ogr_gpsbabel') - gdaltest.run_tests(gdaltest_list) - sys.exit(gdaltest.summarize()) diff --git a/autotest/ogr/ogr_gpx.py b/autotest/ogr/ogr_gpx.py index d04f0a5ebfaf..1815245aef03 100755 --- a/autotest/ogr/ogr_gpx.py +++ b/autotest/ogr/ogr_gpx.py @@ -29,17 +29,16 @@ ############################################################################### import os -import sys -sys.path.append('../pymod') import gdaltest import ogrtest from osgeo import ogr from osgeo import gdal +import pytest -def ogr_gpx_init(): +def test_ogr_gpx_init(): gdaltest.gpx_ds = None gdaltest.gpx_ds = ogr.Open('data/test.gpx') @@ -49,24 +48,19 @@ def ogr_gpx_init(): gdaltest.have_gpx = 1 if not gdaltest.have_gpx: - return 'skip' + pytest.skip() - if gdaltest.gpx_ds.GetLayerCount() != 5: - gdaltest.post_reason('wrong number of layers') - return 'fail' - - return 'success' + assert gdaltest.gpx_ds.GetLayerCount() == 5, 'wrong number of layers' ############################################################################### # Test waypoints gpx layer. -def ogr_gpx_1(): +def test_ogr_gpx_1(): if not gdaltest.have_gpx: - return 'skip' + pytest.skip() - if gdaltest.gpx_ds is None: - return 'fail' + assert gdaltest.gpx_ds is not None lyr = gdaltest.gpx_ds.GetLayerByName('waypoints') @@ -74,201 +68,167 @@ def ogr_gpx_1(): with gdaltest.error_handler(): tr = ogrtest.check_features_against_list(lyr, 'ele', expect) - if not tr: - return 'fail' + assert tr lyr.ResetReading() expect = ['waypoint name', None] tr = ogrtest.check_features_against_list(lyr, 'name', expect) - if not tr: - return 'fail' + assert tr lyr.ResetReading() expect = ['href', None] tr = ogrtest.check_features_against_list(lyr, 'link1_href', expect) - if not tr: - return 'fail' + assert tr lyr.ResetReading() expect = ['text', None] tr = ogrtest.check_features_against_list(lyr, 'link1_text', expect) - if not tr: - return 'fail' + assert tr lyr.ResetReading() expect = ['type', None] tr = ogrtest.check_features_against_list(lyr, 'link1_type', expect) - if not tr: - return 'fail' + assert tr lyr.ResetReading() expect = ['href2', None] tr = ogrtest.check_features_against_list(lyr, 'link2_href', expect) - if not tr: - return 'fail' + assert tr lyr.ResetReading() expect = ['text2', None] tr = ogrtest.check_features_against_list(lyr, 'link2_text', expect) - if not tr: - return 'fail' + assert tr lyr.ResetReading() expect = ['type2', None] tr = ogrtest.check_features_against_list(lyr, 'link2_type', expect) - if not tr: - return 'fail' + assert tr lyr.ResetReading() expect = ['2007/11/25 17:58:00+01', None] tr = ogrtest.check_features_against_list(lyr, 'time', expect) - if not tr: - return 'fail' + assert tr lyr.ResetReading() feat = lyr.GetNextFeature() - if ogrtest.check_feature_geometry(feat, 'POINT (1 0)', - max_error=0.0001) != 0: - return 'fail' + assert (ogrtest.check_feature_geometry(feat, 'POINT (1 0)', + max_error=0.0001) == 0) feat = lyr.GetNextFeature() - if ogrtest.check_feature_geometry(feat, 'POINT (4 3)', - max_error=0.0001) != 0: - return 'fail' - - return 'success' + assert (ogrtest.check_feature_geometry(feat, 'POINT (4 3)', + max_error=0.0001) == 0) ############################################################################### # Test routes gpx layer. -def ogr_gpx_2(): +def test_ogr_gpx_2(): if not gdaltest.have_gpx: - return 'skip' + pytest.skip() - if gdaltest.gpx_ds is None: - return 'fail' + assert gdaltest.gpx_ds is not None lyr = gdaltest.gpx_ds.GetLayerByName('routes') lyr.ResetReading() feat = lyr.GetNextFeature() - if ogrtest.check_feature_geometry(feat, 'LINESTRING (6 5,9 8,12 11)', max_error=0.0001) != 0: - return 'fail' + assert ogrtest.check_feature_geometry(feat, 'LINESTRING (6 5,9 8,12 11)', max_error=0.0001) == 0 feat = lyr.GetNextFeature() - if ogrtest.check_feature_geometry(feat, 'LINESTRING EMPTY', max_error=0.0001) != 0: - return 'fail' - - return 'success' + assert ogrtest.check_feature_geometry(feat, 'LINESTRING EMPTY', max_error=0.0001) == 0 ############################################################################### # Test route_points gpx layer. -def ogr_gpx_3(): +def test_ogr_gpx_3(): if not gdaltest.have_gpx: - return 'skip' + pytest.skip() - if gdaltest.gpx_ds is None: - return 'fail' + assert gdaltest.gpx_ds is not None lyr = gdaltest.gpx_ds.GetLayerByName('route_points') expect = ['route point name', None, None] tr = ogrtest.check_features_against_list(lyr, 'name', expect) - if not tr: - return 'fail' + assert tr lyr.ResetReading() feat = lyr.GetNextFeature() - if ogrtest.check_feature_geometry(feat, 'POINT (6 5)', max_error=0.0001) != 0: - return 'fail' - - return 'success' + assert ogrtest.check_feature_geometry(feat, 'POINT (6 5)', max_error=0.0001) == 0 ############################################################################### # Test tracks gpx layer. -def ogr_gpx_4(): +def test_ogr_gpx_4(): if not gdaltest.have_gpx: - return 'skip' + pytest.skip() - if gdaltest.gpx_ds is None: - return 'fail' + assert gdaltest.gpx_ds is not None lyr = gdaltest.gpx_ds.GetLayerByName('tracks') lyr.ResetReading() feat = lyr.GetNextFeature() - if ogrtest.check_feature_geometry(feat, 'MULTILINESTRING ((15 14,18 17),(21 20,24 23))', max_error=0.0001) != 0: - return 'fail' + assert ogrtest.check_feature_geometry(feat, 'MULTILINESTRING ((15 14,18 17),(21 20,24 23))', max_error=0.0001) == 0 feat = lyr.GetNextFeature() - if ogrtest.check_feature_geometry(feat, 'MULTILINESTRING EMPTY', max_error=0.0001) != 0: - return 'fail' + assert ogrtest.check_feature_geometry(feat, 'MULTILINESTRING EMPTY', max_error=0.0001) == 0 feat = lyr.GetNextFeature() f_geom = feat.GetGeometryRef() - if f_geom.ExportToWkt() != 'MULTILINESTRING EMPTY': - return 'fail' - - return 'success' + assert f_geom.ExportToWkt() == 'MULTILINESTRING EMPTY' ############################################################################### # Test route_points gpx layer. -def ogr_gpx_5(): +def test_ogr_gpx_5(): if not gdaltest.have_gpx: - return 'skip' + pytest.skip() - if gdaltest.gpx_ds is None: - return 'fail' + assert gdaltest.gpx_ds is not None lyr = gdaltest.gpx_ds.GetLayerByName('track_points') expect = ['track point name', None, None, None] tr = ogrtest.check_features_against_list(lyr, 'name', expect) - if not tr: - return 'fail' + assert tr lyr.ResetReading() feat = lyr.GetNextFeature() - if ogrtest.check_feature_geometry(feat, 'POINT (15 14)', max_error=0.0001) != 0: - return 'fail' - - return 'success' + assert ogrtest.check_feature_geometry(feat, 'POINT (15 14)', max_error=0.0001) == 0 ############################################################################### # Copy our small gpx file to a new gpx file. -def ogr_gpx_6(): +def test_ogr_gpx_6(): if not gdaltest.have_gpx: - return 'skip' + pytest.skip() if gdaltest.gpx_ds is None: - return 'skip' + pytest.skip() try: gdal.PushErrorHandler('CPLQuietErrorHandler') @@ -294,9 +254,7 @@ def ogr_gpx_6(): feat = gpx_lyr.GetNextFeature() while feat is not None: dst_feat.SetFrom(feat) - if gpx2_lyr.CreateFeature(dst_feat) != 0: - gdaltest.post_reason('CreateFeature failed.') - return 'fail' + assert gpx2_lyr.CreateFeature(dst_feat) == 0, 'CreateFeature failed.' feat = gpx_lyr.GetNextFeature() @@ -312,9 +270,7 @@ def ogr_gpx_6(): feat = gpx_lyr.GetNextFeature() while feat is not None: dst_feat.SetFrom(feat) - if gpx2_lyr.CreateFeature(dst_feat) != 0: - gdaltest.post_reason('CreateFeature failed.') - return 'fail' + assert gpx2_lyr.CreateFeature(dst_feat) == 0, 'CreateFeature failed.' feat = gpx_lyr.GetNextFeature() @@ -330,9 +286,7 @@ def ogr_gpx_6(): feat = gpx_lyr.GetNextFeature() while feat is not None: dst_feat.SetFrom(feat) - if gpx2_lyr.CreateFeature(dst_feat) != 0: - gdaltest.post_reason('CreateFeature failed.') - return 'fail' + assert gpx2_lyr.CreateFeature(dst_feat) == 0, 'CreateFeature failed.' feat = gpx_lyr.GetNextFeature() @@ -344,15 +298,13 @@ def ogr_gpx_6(): gdaltest.gpx_ds = ogr.Open('tmp/gpx.gpx') - return 'success' - ############################################################################### # Output extra fields as <extensions>. -def ogr_gpx_7(): +def test_ogr_gpx_7(): if not gdaltest.have_gpx: - return 'skip' + pytest.skip() gdaltest.gpx_ds = None @@ -384,9 +336,7 @@ def ogr_gpx_7(): feat = bna_lyr.GetNextFeature() while feat is not None: dst_feat.SetFrom(feat) - if gpx_lyr.CreateFeature(dst_feat) != 0: - gdaltest.post_reason('CreateFeature failed.') - return 'fail' + assert gpx_lyr.CreateFeature(dst_feat) == 0, 'CreateFeature failed.' feat = bna_lyr.GetNextFeature() @@ -399,34 +349,29 @@ def ogr_gpx_7(): expect = ['PID1', 'PID2'] tr = ogrtest.check_features_against_list(gpx_lyr, 'ogr_Primary_ID', expect) - if not tr: - return 'fail' + assert tr gpx_lyr.ResetReading() expect = ['SID1', 'SID2'] tr = ogrtest.check_features_against_list(gpx_lyr, 'ogr_Secondary_ID', expect) - if not tr: - return 'fail' + assert tr gpx_lyr.ResetReading() expect = ['TID1', None] tr = ogrtest.check_features_against_list(gpx_lyr, 'ogr_Third_ID', expect) - if not tr: - return 'fail' - - return 'success' + assert tr ############################################################################### # Output extra fields as <extensions>. -def ogr_gpx_8(): +def test_ogr_gpx_8(): if not gdaltest.have_gpx: - return 'skip' + pytest.skip() gdaltest.gpx_ds = None @@ -508,66 +453,35 @@ def ogr_gpx_8(): f.close() f_ref.close() - if f_content.find(f_ref_content) == -1: - gdaltest.post_reason('did not get expected result') - print(f_content) - return 'fail' - - return 'success' + assert f_content.find(f_ref_content) != -1, 'did not get expected result' ############################################################################### # Parse file with a <time> extension at track level (#6237) -def ogr_gpx_9(): +def test_ogr_gpx_9(): if not gdaltest.have_gpx: - return 'skip' + pytest.skip() ds = ogr.Open('data/track_with_time_extension.gpx') lyr = ds.GetLayerByName('tracks') f = lyr.GetNextFeature() if f['time'] != '2015-10-11T15:06:33Z': - gdaltest.post_reason('did not get expected result') f.DumpReadable() - return 'fail' - - return 'success' + pytest.fail('did not get expected result') + ############################################################################### # -def ogr_gpx_cleanup(): +def test_ogr_gpx_cleanup(): gdaltest.gpx_ds = None try: os.remove('tmp/gpx.gpx') except OSError: pass - return 'success' - - -gdaltest_list = [ - ogr_gpx_init, - ogr_gpx_1, - ogr_gpx_2, - ogr_gpx_3, - ogr_gpx_4, - ogr_gpx_5, - ogr_gpx_6, - # Rerun test 1, 2 and 4 with generated tmp/tmp.gpx - ogr_gpx_1, - ogr_gpx_2, - ogr_gpx_4, - ogr_gpx_7, - ogr_gpx_8, - ogr_gpx_9, - ogr_gpx_cleanup] - -if __name__ == '__main__': - - gdaltest.setup_run('ogr_gpx') + - gdaltest.run_tests(gdaltest_list) - sys.exit(gdaltest.summarize()) diff --git a/autotest/ogr/ogr_grass.py b/autotest/ogr/ogr_grass.py index 96f999d24169..ac1aacf349d9 100755 --- a/autotest/ogr/ogr_grass.py +++ b/autotest/ogr/ogr_grass.py @@ -28,68 +28,45 @@ # DEALINGS IN THE SOFTWARE. ############################################################################### -import sys from osgeo import ogr -sys.path.append('../pymod') import gdaltest +import pytest ############################################################################### # Test if GRASS driver is present -def ogr_grass_1(): +def test_ogr_grass_1(): gdaltest.ogr_grass_drv = ogr.GetDriverByName('GRASS') if gdaltest.ogr_grass_drv is None: - return 'skip' - - return 'success' + pytest.skip() + ############################################################################### # Read 'point' datasource -def ogr_grass_2(): +def test_ogr_grass_2(): if gdaltest.ogr_grass_drv is None: - return 'skip' + pytest.skip() ds = ogr.Open('./data/PERMANENT/vector/point/head') - if ds is None: - gdaltest.post_reason('Cannot open datasource') - return 'fail' + assert ds is not None, 'Cannot open datasource' lyr = ds.GetLayerByName('1') - if lyr is None: - gdaltest.post_reason('Cannot find layer') - return 'fail' + assert lyr is not None, 'Cannot find layer' feat = lyr.GetNextFeature() - if feat.GetGeometryRef().ExportToWkt() != 'POINT (0 0)': - print(feat.GetGeometryRef().ExportToWkt()) - return 'fail' + assert feat.GetGeometryRef().ExportToWkt() == 'POINT (0 0)' - if feat.GetFieldAsString('name') != 'my point': - print(feat.GetFieldAsString('name')) - return 'fail' + assert feat.GetFieldAsString('name') == 'my point' ds = None - return 'success' - - -gdaltest_list = [ - ogr_grass_1, - ogr_grass_2 -] - - -if __name__ == '__main__': - gdaltest.setup_run('GRASS') - gdaltest.run_tests(gdaltest_list) - sys.exit(gdaltest.summarize()) diff --git a/autotest/ogr/ogr_gtm.py b/autotest/ogr/ogr_gtm.py index 8fabfd14051b..a26e69005cbd 100755 --- a/autotest/ogr/ogr_gtm.py +++ b/autotest/ogr/ogr_gtm.py @@ -30,16 +30,15 @@ ############################################################################### import os -import sys -sys.path.append('../pymod') import gdaltest import ogrtest from osgeo import ogr +import pytest -def ogr_gtm_init(): +def test_ogr_gtm_init(): gdaltest.gtm_ds = None gdaltest.gtm_ds = ogr.Open('data/samplemap.gtm') @@ -50,136 +49,89 @@ def ogr_gtm_init(): gdaltest.have_gtm = 1 if not gdaltest.have_gtm: - return 'skip' + pytest.skip() - if gdaltest.gtm_ds.GetLayerCount() != 2: - gdaltest.post_reason('wrong number of layers') - return 'fail' - - return 'success' + assert gdaltest.gtm_ds.GetLayerCount() == 2, 'wrong number of layers' ############################################################################### # Test waypoints gtm layer. -def ogr_gtm_read_1(): +def test_ogr_gtm_read_1(): if not gdaltest.have_gtm: - return 'skip' + pytest.skip() - if gdaltest.gtm_ds is None: - return 'fail' + assert gdaltest.gtm_ds is not None lyr = gdaltest.gtm_ds.GetLayerByName('samplemap_waypoints') - if lyr.GetFeatureCount() != 3: - gdaltest.post_reason('wrong number of features') - return 'fail' + assert lyr.GetFeatureCount() == 3, 'wrong number of features' # Test 1st feature feat = lyr.GetNextFeature() - if feat.GetField('name') != 'WAY6': - gdaltest.post_reason('Wrong name field value') - return 'fail' + assert feat.GetField('name') == 'WAY6', 'Wrong name field value' - if feat.GetField('comment') != 'Santa Cruz Stadium': - gdaltest.post_reason('Wrong comment field value') - return 'fail' + assert feat.GetField('comment') == 'Santa Cruz Stadium', 'Wrong comment field value' - if feat.GetField('icon') != 92: - gdaltest.post_reason('Wrong icon field value') - return 'fail' + assert feat.GetField('icon') == 92, 'Wrong icon field value' - if feat.GetField('time') != '2009/12/18 17:32:41': - gdaltest.post_reason('Wrong time field value') - return 'fail' + assert feat.GetField('time') == '2009/12/18 17:32:41', 'Wrong time field value' wkt = 'POINT (-47.789974212646484 -21.201919555664062)' - if ogrtest.check_feature_geometry(feat, wkt): - gdaltest.post_reason('Unexpected geometry') - return 'fail' + assert not ogrtest.check_feature_geometry(feat, wkt), 'Unexpected geometry' # Test 2nd feature feat = lyr.GetNextFeature() - if feat.GetField('name') != 'WAY6': - gdaltest.post_reason('Wrong name field value') - return 'fail' + assert feat.GetField('name') == 'WAY6', 'Wrong name field value' - if feat.GetField('comment') != 'Joe\'s Goalkeeper Pub': - gdaltest.post_reason('Wrong comment field value') - return 'fail' + assert feat.GetField('comment') == 'Joe\'s Goalkeeper Pub', \ + 'Wrong comment field value' - if feat.GetField('icon') != 4: - gdaltest.post_reason('Wrong icon field value') - return 'fail' + assert feat.GetField('icon') == 4, 'Wrong icon field value' - if feat.GetField('time') != '2009/12/18 17:34:46': - gdaltest.post_reason('Wrong time field value') - return 'fail' + assert feat.GetField('time') == '2009/12/18 17:34:46', 'Wrong time field value' wkt = 'POINT (-47.909481048583984 -21.294229507446289)' - if ogrtest.check_feature_geometry(feat, wkt): - gdaltest.post_reason('Unexpected geometry') - return 'fail' + assert not ogrtest.check_feature_geometry(feat, wkt), 'Unexpected geometry' # Test 3rd feature feat = lyr.GetNextFeature() - if feat.GetField('name') != '33543400': - gdaltest.post_reason('Wrong name field value') - return 'fail' + assert feat.GetField('name') == '33543400', 'Wrong name field value' - if feat.GetField('comment') != 'City Hall': - gdaltest.post_reason('Wrong comment field value') - return 'fail' + assert feat.GetField('comment') == 'City Hall', 'Wrong comment field value' - if feat.GetField('icon') != 61: - gdaltest.post_reason('Wrong icon field value') - return 'fail' + assert feat.GetField('icon') == 61, 'Wrong icon field value' - if feat.GetField('time') is not None: - gdaltest.post_reason('Wrong time field value') - return 'fail' + assert feat.GetField('time') is None, 'Wrong time field value' wkt = 'POINT (-47.806097491943362 -21.176849600708007)' - if ogrtest.check_feature_geometry(feat, wkt): - gdaltest.post_reason('Unexpected geometry') - return 'fail' - - return 'success' + assert not ogrtest.check_feature_geometry(feat, wkt), 'Unexpected geometry' ############################################################################### # Test tracks gtm layer. -def ogr_gtm_read_2(): +def test_ogr_gtm_read_2(): if not gdaltest.have_gtm: - return 'skip' + pytest.skip() - if gdaltest.gtm_ds is None: - return 'fail' + assert gdaltest.gtm_ds is not None lyr = gdaltest.gtm_ds.GetLayerByName('samplemap_tracks') - if lyr.GetFeatureCount() != 3: - gdaltest.post_reason('wrong number of features') - return 'fail' + assert lyr.GetFeatureCount() == 3, 'wrong number of features' # Test 1st feature feat = lyr.GetNextFeature() - if feat.GetField('name') != 'San Sebastian Street': - gdaltest.post_reason('Wrong name field value') - return 'fail' + assert feat.GetField('name') == 'San Sebastian Street', 'Wrong name field value' - if feat.GetField('type') != 2: - gdaltest.post_reason('Wrong type field value') - return 'fail' + assert feat.GetField('type') == 2, 'Wrong type field value' - if feat.GetField('color') != 0: - gdaltest.post_reason('Wrong color field value') - return 'fail' + assert feat.GetField('color') == 0, 'Wrong color field value' # if feat.GetField('time') is not None: # gdaltest.post_reason( 'Wrong time field value' ) @@ -189,24 +141,16 @@ def ogr_gtm_read_2(): '-47.808151245117188 -21.177299499511719,' + \ '-47.809136624130645 -21.176562836150087,' + \ '-47.809931418108405 -21.175971104366582)' - if ogrtest.check_feature_geometry(feat, wkt): - gdaltest.post_reason('Unexpected geometry') - return 'fail' + assert not ogrtest.check_feature_geometry(feat, wkt), 'Unexpected geometry' # Test 2nd feature feat = lyr.GetNextFeature() - if feat.GetField('name') != 'Barao do Amazonas Street': - gdaltest.post_reason('Wrong name field value') - return 'fail' + assert feat.GetField('name') == 'Barao do Amazonas Street', 'Wrong name field value' - if feat.GetField('type') != 1: - gdaltest.post_reason('Wrong type field value') - return 'fail' + assert feat.GetField('type') == 1, 'Wrong type field value' - if feat.GetField('color') != 0: - gdaltest.post_reason('Wrong color field value') - return 'fail' + assert feat.GetField('color') == 0, 'Wrong color field value' # if feat.GetField('time') is not None: # gdaltest.post_reason( 'Wrong time field value' ) @@ -216,23 +160,16 @@ def ogr_gtm_read_2(): '-47.808151245117188 -21.177299499511719,' + \ '-47.807561550927701 -21.176617693474089,' + \ '-47.806959118447779 -21.175900153727685)' - if ogrtest.check_feature_geometry(feat, wkt): - return 'fail' + assert not ogrtest.check_feature_geometry(feat, wkt) # Test 3rd feature feat = lyr.GetNextFeature() - if feat.GetField('name') != 'Curupira Park': - gdaltest.post_reason('Wrong name field value') - return 'fail' + assert feat.GetField('name') == 'Curupira Park', 'Wrong name field value' - if feat.GetField('type') != 17: - gdaltest.post_reason('Wrong type field value') - return 'fail' + assert feat.GetField('type') == 17, 'Wrong type field value' - if feat.GetField('color') != 46848: - gdaltest.post_reason('Wrong color field value') - return 'fail' + assert feat.GetField('color') == 46848, 'Wrong color field value' # if feat.GetField('time') is not None: # gdaltest.post_reason( 'Wrong time field value' ) @@ -246,11 +183,7 @@ def ogr_gtm_read_2(): '-47.792263031005859 -21.194267272949219,' + \ '-47.7894287109375 -21.194473266601562)' - if ogrtest.check_feature_geometry(feat, wkt): - gdaltest.post_reason('Unexpected geometry') - return 'fail' - - return 'success' + assert not ogrtest.check_feature_geometry(feat, wkt), 'Unexpected geometry' ############################################################################### @@ -258,7 +191,7 @@ def ogr_gtm_read_2(): ############################################################################### # Waypoint write -def ogr_gtm_write_1(): +def test_ogr_gtm_write_1(): ds = ogr.GetDriverByName('GPSTrackMaker').CreateDataSource('tmp/gtm.gtm') lyr = ds.CreateLayer('gtm_waypoints', geom_type=ogr.wkbPoint) @@ -269,18 +202,14 @@ def ogr_gtm_write_1(): dst_feat.SetField('icon', 10) dst_feat.SetField('time', '2009/12/23 14:25:46') dst_feat.SetGeometry(ogr.CreateGeometryFromWkt('POINT (-21 -47)')) - if lyr.CreateFeature(dst_feat) != 0: - gdaltest.post_reason('CreateFeature failed.') - return 'fail' + assert lyr.CreateFeature(dst_feat) == 0, 'CreateFeature failed.' dst_feat = ogr.Feature(lyr.GetLayerDefn()) dst_feat.SetField('name', 'WAY0000001') dst_feat.SetField('comment', 'Waypoint 1') dst_feat.SetField('icon', 31) dst_feat.SetGeometry(ogr.CreateGeometryFromWkt('POINT (-21.123 -47.231 800)')) - if lyr.CreateFeature(dst_feat) != 0: - gdaltest.post_reason('CreateFeature failed.') - return 'fail' + assert lyr.CreateFeature(dst_feat) == 0, 'CreateFeature failed.' lyr = ds.CreateLayer('gtm_tracks', geom_type=ogr.wkbLineString) @@ -289,18 +218,14 @@ def ogr_gtm_write_1(): dst_feat.SetField('type', 2) dst_feat.SetField('color', 0x0000FF) dst_feat.SetGeometry(ogr.CreateGeometryFromWkt('LINESTRING (-21.1 -47.1, -21.2 -47.2, -21.3 -47.3, -21.4 -47.4)')) - if lyr.CreateFeature(dst_feat) != 0: - gdaltest.post_reason('CreateFeature failed.') - return 'fail' + assert lyr.CreateFeature(dst_feat) == 0, 'CreateFeature failed.' dst_feat = ogr.Feature(lyr.GetLayerDefn()) dst_feat.SetField('name', '2nd Street') dst_feat.SetField('type', 1) dst_feat.SetField('color', 0x000000) dst_feat.SetGeometry(ogr.CreateGeometryFromWkt('LINESTRING (-21.11 -47.1, -21.21 -47.2, -21.31 -47.3, -21.41 -47.4)')) - if lyr.CreateFeature(dst_feat) != 0: - gdaltest.post_reason('CreateFeature failed.') - return 'fail' + assert lyr.CreateFeature(dst_feat) == 0, 'CreateFeature failed.' dst_feat = ogr.Feature(lyr.GetLayerDefn()) dst_feat.SetField('name', '3rd Street') @@ -308,189 +233,110 @@ def ogr_gtm_write_1(): dst_feat.SetField('color', 0x000000) dst_feat.SetGeometry(ogr.CreateGeometryFromWkt('MULTILINESTRING ((-21.12 -47.1, -21.22 -47.2, -21.32 -47.3, -21.42 -47.4),' + '(-21.12 -47.1, -21.02 -47.0, -20.92 -46.9))')) - if lyr.CreateFeature(dst_feat) != 0: - gdaltest.post_reason('CreateFeature failed.') - return 'fail' + assert lyr.CreateFeature(dst_feat) == 0, 'CreateFeature failed.' ds = None - return 'success' - ############################################################################### # Check previous test -def ogr_gtm_check_write_1(): +def test_ogr_gtm_check_write_1(): if not gdaltest.have_gtm: - return 'skip' + pytest.skip() ds = ogr.Open('tmp/gtm.gtm') lyr = ds.GetLayerByName('gtm_waypoints') - if lyr.GetFeatureCount() != 2: - gdaltest.post_reason('Bad feature count.') - return 'fail' + assert lyr.GetFeatureCount() == 2, 'Bad feature count.' # Test 1st waypoint feat = lyr.GetNextFeature() - if feat.GetField('name') != 'WAY0000000': - gdaltest.post_reason('Wrong name field value') - return 'fail' + assert feat.GetField('name') == 'WAY0000000', 'Wrong name field value' - if feat.GetField('comment') != 'Waypoint 0': - gdaltest.post_reason('Wrong comment field value') - return 'fail' + assert feat.GetField('comment') == 'Waypoint 0', 'Wrong comment field value' - if feat.GetField('icon') != 10: - gdaltest.post_reason('Wrong icon field value') - return 'fail' + assert feat.GetField('icon') == 10, 'Wrong icon field value' - if feat.GetField('time') != '2009/12/23 14:25:46': - gdaltest.post_reason('Wrong time field value') - return 'fail' + assert feat.GetField('time') == '2009/12/23 14:25:46', 'Wrong time field value' wkt = 'POINT (-21 -47)' - if ogrtest.check_feature_geometry(feat, wkt): - gdaltest.post_reason('Unexpected geometry') - return 'fail' + assert not ogrtest.check_feature_geometry(feat, wkt), 'Unexpected geometry' # Test 2nd waypoint feat = lyr.GetNextFeature() - if feat.GetField('name') != 'WAY0000001': - gdaltest.post_reason('Wrong name field value') - return 'fail' + assert feat.GetField('name') == 'WAY0000001', 'Wrong name field value' - if feat.GetField('comment') != 'Waypoint 1': - gdaltest.post_reason('Wrong comment field value') - return 'fail' + assert feat.GetField('comment') == 'Waypoint 1', 'Wrong comment field value' - if feat.GetField('icon') != 31: - gdaltest.post_reason('Wrong icon field value') - return 'fail' + assert feat.GetField('icon') == 31, 'Wrong icon field value' - if feat.GetField('time') is not None: - gdaltest.post_reason('Wrong time field value') - return 'fail' + assert feat.GetField('time') is None, 'Wrong time field value' wkt = 'POINT (-21.123 -47.231 800)' - if ogrtest.check_feature_geometry(feat, wkt): - gdaltest.post_reason('Unexpected geometry') - return 'fail' + assert not ogrtest.check_feature_geometry(feat, wkt), 'Unexpected geometry' # Test tracks lyr = ds.GetLayerByName('gtm_tracks') - if lyr.GetFeatureCount() != 4: # The driver converts multiline - # into one line for each tuple - # element - gdaltest.post_reason('Bad feature count.') - return 'fail' + assert lyr.GetFeatureCount() == 4, 'Bad feature count.' # Test 1st track feat = lyr.GetNextFeature() - if feat.GetField('name') != '1st Street': - gdaltest.post_reason('Wrong name field value') - return 'fail' + assert feat.GetField('name') == '1st Street', 'Wrong name field value' - if feat.GetField('type') != 2: - gdaltest.post_reason('Wrong type field value') - return 'fail' + assert feat.GetField('type') == 2, 'Wrong type field value' - if feat.GetField('color') != 0x0000FF: - gdaltest.post_reason('Wrong color field value') - return 'fail' + assert feat.GetField('color') == 0x0000FF, 'Wrong color field value' wkt = 'LINESTRING (-21.1 -47.1, -21.2 -47.2, -21.3 -47.3, -21.4 -47.4)' - if ogrtest.check_feature_geometry(feat, wkt): - gdaltest.post_reason('Unexpected geometry') - return 'fail' + assert not ogrtest.check_feature_geometry(feat, wkt), 'Unexpected geometry' # Test 2nd track feat = lyr.GetNextFeature() - if feat.GetField('name') != '2nd Street': - gdaltest.post_reason('Wrong name field value') - return 'fail' + assert feat.GetField('name') == '2nd Street', 'Wrong name field value' - if feat.GetField('type') != 1: - gdaltest.post_reason('Wrong type field value') - return 'fail' + assert feat.GetField('type') == 1, 'Wrong type field value' - if feat.GetField('color') != 0x000000: - gdaltest.post_reason('Wrong color field value') - return 'fail' + assert feat.GetField('color') == 0x000000, 'Wrong color field value' wkt = 'LINESTRING (-21.11 -47.1, -21.21 -47.2, -21.31 -47.3, -21.41 -47.4)' - if ogrtest.check_feature_geometry(feat, wkt): - gdaltest.post_reason('Unexpected geometry') - return 'fail' + assert not ogrtest.check_feature_geometry(feat, wkt), 'Unexpected geometry' # Test 3rd track feat = lyr.GetNextFeature() - if feat.GetField('name') != '3rd Street': - gdaltest.post_reason('Wrong name field value') - return 'fail' + assert feat.GetField('name') == '3rd Street', 'Wrong name field value' - if feat.GetField('type') != 2: - gdaltest.post_reason('Wrong type field value') - return 'fail' + assert feat.GetField('type') == 2, 'Wrong type field value' - if feat.GetField('color') != 0x000000: - gdaltest.post_reason('Wrong color field value') - return 'fail' + assert feat.GetField('color') == 0x000000, 'Wrong color field value' wkt = 'LINESTRING (-21.12 -47.1, -21.22 -47.2, -21.32 -47.3, -21.42 -47.4)' - if ogrtest.check_feature_geometry(feat, wkt): - gdaltest.post_reason('Unexpected geometry') - return 'fail' + assert not ogrtest.check_feature_geometry(feat, wkt), 'Unexpected geometry' # Test 4th track feat = lyr.GetNextFeature() - if feat.GetField('name') != '3rd Street': - gdaltest.post_reason('Wrong name field value') - return 'fail' + assert feat.GetField('name') == '3rd Street', 'Wrong name field value' - if feat.GetField('type') != 2: - gdaltest.post_reason('Wrong type field value') - return 'fail' + assert feat.GetField('type') == 2, 'Wrong type field value' - if feat.GetField('color') != 0x000000: - gdaltest.post_reason('Wrong color field value') - return 'fail' + assert feat.GetField('color') == 0x000000, 'Wrong color field value' wkt = 'LINESTRING (-21.12 -47.1, -21.02 -47.0, -20.92 -46.9)' - if ogrtest.check_feature_geometry(feat, wkt): - gdaltest.post_reason('Unexpected geometry') - return 'fail' - - return 'success' + assert not ogrtest.check_feature_geometry(feat, wkt), 'Unexpected geometry' ############################################################################### # -def ogr_gtm_cleanup(): +def test_ogr_gtm_cleanup(): gdaltest.gtm_ds = None os.remove('tmp/gtm.gtm') - return 'success' - - -gdaltest_list = [ - ogr_gtm_init, - ogr_gtm_read_1, - ogr_gtm_read_2, - ogr_gtm_write_1, - ogr_gtm_check_write_1, - ogr_gtm_cleanup] - -if __name__ == '__main__': - gdaltest.setup_run('ogr_gtm') - gdaltest.run_tests(gdaltest_list) - sys.exit(gdaltest.summarize()) diff --git a/autotest/ogr/ogr_htf.py b/autotest/ogr/ogr_htf.py index a364f1de5044..6436d016855d 100755 --- a/autotest/ogr/ogr_htf.py +++ b/autotest/ogr/ogr_htf.py @@ -28,114 +28,76 @@ # DEALINGS IN THE SOFTWARE. ############################################################################### -import sys -sys.path.append('../pymod') import gdaltest import ogrtest from osgeo import ogr +import pytest ############################################################################### # Basic test -def ogr_htf_1(): +def test_ogr_htf_1(): ds = ogr.Open('data/test.htf') - if ds is None: - gdaltest.post_reason('cannot open dataset') - return 'fail' + assert ds is not None, 'cannot open dataset' lyr = ds.GetLayer(0) - if lyr.GetName() != 'polygon': - gdaltest.post_reason('layer 0 is not polygon') - return 'fail' + assert lyr.GetName() == 'polygon', 'layer 0 is not polygon' lyr = ds.GetLayerByName('polygon') - if lyr is None: - gdaltest.post_reason('cannot find layer polygon') - return 'fail' + assert lyr is not None, 'cannot find layer polygon' feat = lyr.GetNextFeature() geom = feat.GetGeometryRef() if ogrtest.check_feature_geometry(feat, 'POLYGON ((320830 7678810,350840 7658030,308130 7595560,278310 7616820,320830 7678810))', max_error=0.0000001) != 0: - gdaltest.post_reason('did not get expected first geom') print(geom.ExportToWkt()) - return 'fail' + pytest.fail('did not get expected first geom') feat = lyr.GetNextFeature() geom = feat.GetGeometryRef() if ogrtest.check_feature_geometry(feat, 'POLYGON ((320830 7678810,350840 7658030,308130 7595560,278310 7616820,320830 7678810),(0 0,0 1,1 1,0 0))', max_error=0.0000001) != 0: - gdaltest.post_reason('did not get expected first geom') print(geom.ExportToWkt()) - return 'fail' + pytest.fail('did not get expected first geom') - if feat.GetField('IDENTIFIER') != 2: - gdaltest.post_reason('did not get expected identifier') - print(feat.GetField('IDENTIFIER')) - return 'fail' + assert feat.GetField('IDENTIFIER') == 2, 'did not get expected identifier' lyr = ds.GetLayerByName('sounding') - if lyr is None: - gdaltest.post_reason('cannot find layer sounding') - return 'fail' + assert lyr is not None, 'cannot find layer sounding' - if lyr.GetFeatureCount() != 2: - gdaltest.post_reason('did not get expected feature count') - return 'fail' + assert lyr.GetFeatureCount() == 2, 'did not get expected feature count' feat = lyr.GetNextFeature() geom = feat.GetGeometryRef() if ogrtest.check_feature_geometry(feat, 'POINT (278670 7616330)', max_error=0.0000001) != 0: - gdaltest.post_reason('did not get expected first geom') print(geom.ExportToWkt()) - return 'fail' + pytest.fail('did not get expected first geom') - if feat.GetField('other3') != 'other3': - gdaltest.post_reason('did not get expected other3 val') - print(feat.GetField('other3')) - return 'fail' - - return 'success' + assert feat.GetField('other3') == 'other3', 'did not get expected other3 val' ############################################################################### # Run test_ogrsf -def ogr_htf_2(): +def test_ogr_htf_2(): import test_cli_utilities if test_cli_utilities.get_test_ogrsf_path() is None: - return 'skip' + pytest.skip() ret = gdaltest.runexternal(test_cli_utilities.get_test_ogrsf_path() + ' -ro data/test.htf') - if ret.find('INFO') == -1 or ret.find('ERROR') != -1: - print(ret) - return 'fail' + assert ret.find('INFO') != -1 and ret.find('ERROR') == -1 ret = gdaltest.runexternal(test_cli_utilities.get_test_ogrsf_path() + ' -ro data/test.htf metadata') - if ret.find('INFO') == -1 or ret.find('ERROR') != -1: - print(ret) - return 'fail' - - return 'success' - - -gdaltest_list = [ - ogr_htf_1, - ogr_htf_2] - + assert ret.find('INFO') != -1 and ret.find('ERROR') == -1 -if __name__ == '__main__': - gdaltest.setup_run('ogr_htf') - gdaltest.run_tests(gdaltest_list) - sys.exit(gdaltest.summarize()) diff --git a/autotest/ogr/ogr_idrisi.py b/autotest/ogr/ogr_idrisi.py index 28b3014a211b..e823342154d6 100755 --- a/autotest/ogr/ogr_idrisi.py +++ b/autotest/ogr/ogr_idrisi.py @@ -28,260 +28,172 @@ # DEALINGS IN THE SOFTWARE. ############################################################################### -import sys from osgeo import ogr -sys.path.append('../pymod') -import gdaltest import ogrtest +import pytest ############################################################################### # Test point layer -def ogr_idrisi_1(): +def test_ogr_idrisi_1(): ds = ogr.Open('data/points.vct') - if ds is None: - gdaltest.post_reason('fail') - return 'fail' + assert ds is not None lyr = ds.GetLayer(0) - if lyr.GetGeomType() != ogr.wkbPoint: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.GetGeomType() == ogr.wkbPoint - if lyr.GetLayerDefn().GetFieldDefn(1).GetName() != 'IntegerField': - gdaltest.post_reason('fail') - return 'fail' + assert lyr.GetLayerDefn().GetFieldDefn(1).GetName() == 'IntegerField' - if lyr.GetLayerDefn().GetFieldDefn(1).GetType() != ogr.OFTInteger: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.GetLayerDefn().GetFieldDefn(1).GetType() == ogr.OFTInteger sr = lyr.GetSpatialRef() - if sr.ExportToWkt().find('PROJCS["UTM Zone 31, Northern Hemisphere"') != 0: - gdaltest.post_reason('fail') - print(sr.ExportToWkt()) - return 'fail' + assert sr.ExportToWkt().find('PROJCS["UTM Zone 31, Northern Hemisphere"') == 0 - if lyr.GetFeatureCount() != 2: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.GetFeatureCount() == 2 - if lyr.TestCapability(ogr.OLCFastFeatureCount) != 1: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.TestCapability(ogr.OLCFastFeatureCount) == 1 - if lyr.TestCapability(ogr.OLCFastGetExtent) != 1: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.TestCapability(ogr.OLCFastGetExtent) == 1 - if lyr.GetExtent() != (400000.0, 600000.0, 4000000.0, 5000000.0): - gdaltest.post_reason('fail') - print(lyr.GetExtent()) - return 'fail' + assert lyr.GetExtent() == (400000.0, 600000.0, 4000000.0, 5000000.0) feat = lyr.GetNextFeature() if feat.GetFieldAsDouble(0) != 1.0: - gdaltest.post_reason('fail') feat.DumpReadable() - return 'fail' + pytest.fail() if feat.GetFieldAsInteger(1) != 2: - gdaltest.post_reason('fail') feat.DumpReadable() - return 'fail' + pytest.fail() if feat.GetFieldAsDouble(2) != 3.45: - gdaltest.post_reason('fail') feat.DumpReadable() - return 'fail' + pytest.fail() if feat.GetFieldAsString(3) != 'foo': - gdaltest.post_reason('fail') feat.DumpReadable() - return 'fail' + pytest.fail() if ogrtest.check_feature_geometry(feat, ogr.CreateGeometryFromWkt('POINT(400000 5000000)')) != 0: - gdaltest.post_reason('fail') feat.DumpReadable() - return 'fail' + pytest.fail() feat = lyr.GetNextFeature() if feat.GetFieldAsDouble(0) != 2.0: - gdaltest.post_reason('fail') feat.DumpReadable() - return 'fail' + pytest.fail() if ogrtest.check_feature_geometry(feat, ogr.CreateGeometryFromWkt('POINT (600000 4000000)')) != 0: - gdaltest.post_reason('fail') feat.DumpReadable() - return 'fail' + pytest.fail() lyr.SetSpatialFilterRect(600000 - 1, 4000000 - 1, 600000 + 1, 4000000 + 1) lyr.ResetReading() feat = lyr.GetNextFeature() if feat.GetFieldAsDouble(0) != 2.0: - gdaltest.post_reason('fail') feat.DumpReadable() - return 'fail' + pytest.fail() lyr.SetSpatialFilterRect(0, 0, 1, 1) lyr.ResetReading() feat = lyr.GetNextFeature() - if feat is not None: - gdaltest.post_reason('fail') - return 'fail' + assert feat is None ds = None - return 'success' - ############################################################################### # Test linestring layer -def ogr_idrisi_2(): +def test_ogr_idrisi_2(): ds = ogr.Open('data/lines.vct') - if ds is None: - gdaltest.post_reason('fail') - return 'fail' + assert ds is not None lyr = ds.GetLayer(0) - if lyr.GetGeomType() != ogr.wkbLineString: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.GetGeomType() == ogr.wkbLineString - if lyr.GetFeatureCount() != 2: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.GetFeatureCount() == 2 - if lyr.TestCapability(ogr.OLCFastFeatureCount) != 1: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.TestCapability(ogr.OLCFastFeatureCount) == 1 - if lyr.TestCapability(ogr.OLCFastGetExtent) != 1: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.TestCapability(ogr.OLCFastGetExtent) == 1 - if lyr.GetExtent() != (400000.0, 600000.0, 4000000.0, 5000000.0): - gdaltest.post_reason('fail') - print(lyr.GetExtent()) - return 'fail' + assert lyr.GetExtent() == (400000.0, 600000.0, 4000000.0, 5000000.0) feat = lyr.GetNextFeature() if feat.GetFieldAsDouble(0) != 10.0: - gdaltest.post_reason('fail') feat.DumpReadable() - return 'fail' + pytest.fail() if ogrtest.check_feature_geometry(feat, ogr.CreateGeometryFromWkt('LINESTRING (400000 5000000,600000 4500000)')) != 0: - gdaltest.post_reason('fail') feat.DumpReadable() - return 'fail' + pytest.fail() feat = lyr.GetNextFeature() if feat.GetFieldAsDouble(0) != 20.0: - gdaltest.post_reason('fail') feat.DumpReadable() - return 'fail' + pytest.fail() if ogrtest.check_feature_geometry(feat, ogr.CreateGeometryFromWkt('LINESTRING (450000 4000000,550000 4500000)')) != 0: - gdaltest.post_reason('fail') feat.DumpReadable() - return 'fail' + pytest.fail() lyr.SetSpatialFilterRect(0, 0, 1, 1) lyr.ResetReading() feat = lyr.GetNextFeature() - if feat is not None: - gdaltest.post_reason('fail') - return 'fail' + assert feat is None ds = None - return 'success' - ############################################################################### # Test polygon layer -def ogr_idrisi_3(): +def test_ogr_idrisi_3(): ds = ogr.Open('data/polygons.vct') - if ds is None: - gdaltest.post_reason('fail') - return 'fail' + assert ds is not None lyr = ds.GetLayer(0) - if lyr.GetGeomType() != ogr.wkbPolygon: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.GetGeomType() == ogr.wkbPolygon - if lyr.GetFeatureCount() != 2: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.GetFeatureCount() == 2 - if lyr.TestCapability(ogr.OLCFastFeatureCount) != 1: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.TestCapability(ogr.OLCFastFeatureCount) == 1 - if lyr.TestCapability(ogr.OLCFastGetExtent) != 1: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.TestCapability(ogr.OLCFastGetExtent) == 1 - if lyr.GetExtent() != (400000.0, 600000.0, 4000000.0, 5000000.0): - gdaltest.post_reason('fail') - print(lyr.GetExtent()) - return 'fail' + assert lyr.GetExtent() == (400000.0, 600000.0, 4000000.0, 5000000.0) feat = lyr.GetNextFeature() if feat.GetFieldAsDouble(0) != 1.0: - gdaltest.post_reason('fail') feat.DumpReadable() - return 'fail' + pytest.fail() if ogrtest.check_feature_geometry(feat, ogr.CreateGeometryFromWkt('POLYGON ((400000 4000000,400000 5000000,600000 5000000,600000 4000000,400000 4000000),(450000 4250000,450000 4750000,550000 4750000,550000 4250000,450000 4250000))')) != 0: - gdaltest.post_reason('fail') feat.DumpReadable() - return 'fail' + pytest.fail() feat = lyr.GetNextFeature() if feat.GetFieldAsDouble(0) != 2.0: - gdaltest.post_reason('fail') feat.DumpReadable() - return 'fail' + pytest.fail() if ogrtest.check_feature_geometry(feat, ogr.CreateGeometryFromWkt('POLYGON ((400000 4000000,400000 5000000,600000 5000000,600000 4000000,400000 4000000))')) != 0: - gdaltest.post_reason('fail') feat.DumpReadable() - return 'fail' + pytest.fail() lyr.SetSpatialFilterRect(0, 0, 1, 1) lyr.ResetReading() feat = lyr.GetNextFeature() - if feat is not None: - gdaltest.post_reason('fail') - return 'fail' + assert feat is None ds = None - return 'success' - - -gdaltest_list = [ - ogr_idrisi_1, - ogr_idrisi_2, - ogr_idrisi_3, -] - -if __name__ == '__main__': - - gdaltest.setup_run('ogr_idrisi') - gdaltest.run_tests(gdaltest_list) - sys.exit(gdaltest.summarize()) diff --git a/autotest/ogr/ogr_ili.py b/autotest/ogr/ogr_ili.py index 37e109da3224..af3ac896b56e 100755 --- a/autotest/ogr/ogr_ili.py +++ b/autotest/ogr/ogr_ili.py @@ -26,14 +26,13 @@ # Boston, MA 02111-1307, USA. ############################################################################### -import sys -sys.path.append('../pymod') import gdaltest import ogrtest from osgeo import gdal from osgeo import ogr +import pytest def cpl_debug_on(): @@ -48,48 +47,40 @@ def cpl_debug_reset(): # Open Driver -def ogr_interlis1_1(): +def test_ogr_interlis1_1(): gdaltest.have_ili_reader = 0 driver = ogr.GetDriverByName('Interlis 1') if driver is None: - return 'skip' + pytest.skip() gdaltest.have_ili_reader = 1 - return 'success' - ############################################################################### # Check that Ili1 point layer is properly read. -def ogr_interlis1_2(): +def test_ogr_interlis1_2(): if not gdaltest.have_ili_reader: - return 'skip' + pytest.skip() if not ogrtest.have_geos(): - return 'skip' + pytest.skip() ds = ogr.Open('data/ili/Beispiel.itf,data/ili/Beispiel.imd') layers = ['Bodenbedeckung__BoFlaechen', 'Bodenbedeckung__BoFlaechen_Form', 'Bodenbedeckung__Strasse', 'Bodenbedeckung__Gebaeude'] - if ds.GetLayerCount() != len(layers): - gdaltest.post_reason('layer count wrong.') - return 'fail' + assert ds.GetLayerCount() == len(layers), 'layer count wrong.' for i in range(ds.GetLayerCount()): - if not ds.GetLayer(i).GetName() in layers: - gdaltest.post_reason('Did not get right layers') - return 'fail' + assert ds.GetLayer(i).GetName() in layers, 'Did not get right layers' lyr = ds.GetLayerByName('Bodenbedeckung__BoFlaechen') - if lyr.GetFeatureCount() != 3: - gdaltest.post_reason('feature count wrong.') - return 'fail' + assert lyr.GetFeatureCount() == 3, 'feature count wrong.' # Get 2nd feature feat = lyr.GetNextFeature() @@ -97,129 +88,98 @@ def ogr_interlis1_2(): field_values = [20, 1, 168.27, 170.85] - if feat.GetFieldCount() != len(field_values): - gdaltest.post_reason('field count wrong.') - return 'fail' + assert feat.GetFieldCount() == len(field_values), 'field count wrong.' for i in range(feat.GetFieldCount()): if feat.GetFieldAsString(i) != str(field_values[i]): feat.DumpReadable() print(feat.GetFieldAsString(i)) - gdaltest.post_reason('field value wrong.') - return 'fail' + pytest.fail('field value wrong.') geom = feat.GetGeomFieldRef(0) - if geom.GetCoordinateDimension() != 2: - gdaltest.post_reason('dimension wrong.') - return 'fail' + assert geom.GetCoordinateDimension() == 2, 'dimension wrong.' geom = feat.GetGeomFieldRef(1) - if geom.GetCoordinateDimension() != 2: - gdaltest.post_reason('dimension wrong.') - return 'fail' + assert geom.GetCoordinateDimension() == 2, 'dimension wrong.' geom = feat.GetGeometryRef() - if geom.GetGeometryName() != 'POLYGON': - gdaltest.post_reason('Geometry of wrong type.') - return 'fail' - - return 'success' + assert geom.GetGeometryName() == 'POLYGON', 'Geometry of wrong type.' ############################################################################### # Ili1 FORMAT DEFAULT test. -def ogr_interlis1_3(): +def test_ogr_interlis1_3(): if not gdaltest.have_ili_reader: - return 'skip' + pytest.skip() ds = ogr.Open('data/ili/format-default.itf,data/ili/format-default.imd') layers = ['FormatTests__FormatTable'] - if ds.GetLayerCount() != len(layers): - gdaltest.post_reason('layer count wrong.') - return 'fail' + assert ds.GetLayerCount() == len(layers), 'layer count wrong.' for i in range(ds.GetLayerCount()): - if not ds.GetLayer(i).GetName() in layers: - gdaltest.post_reason('Did not get right layers') - return 'fail' + assert ds.GetLayer(i).GetName() in layers, 'Did not get right layers' lyr = ds.GetLayerByName('FormatTests__FormatTable') - if lyr.GetFeatureCount() != 1: - gdaltest.post_reason('feature count wrong.') - return 'fail' + assert lyr.GetFeatureCount() == 1, 'feature count wrong.' feat = lyr.GetNextFeature() field_values = [0, 'aa bb', 'cc^dd', '', 1] - if feat.GetFieldCount() != len(field_values): - gdaltest.post_reason('field count wrong.') - return 'fail' + assert feat.GetFieldCount() == len(field_values), 'field count wrong.' for i in range(feat.GetFieldCount()): if feat.GetFieldAsString(i) != str(field_values[i]): feat.DumpReadable() print(feat.GetFieldAsString(i)) - gdaltest.post_reason('field value wrong.') - return 'fail' - - return 'success' + pytest.fail('field value wrong.') + ############################################################################### # Ili1 FORMAT test. -def ogr_interlis1_4(): +def test_ogr_interlis1_4(): if not gdaltest.have_ili_reader: - return 'skip' + pytest.skip() ds = ogr.Open('data/ili/format-test.itf,data/ili/format-test.imd') layers = ['FormatTests__FormatTable'] - if ds.GetLayerCount() != len(layers): - gdaltest.post_reason('layer count wrong.') - return 'fail' + assert ds.GetLayerCount() == len(layers), 'layer count wrong.' for i in range(ds.GetLayerCount()): - if not ds.GetLayer(i).GetName() in layers: - gdaltest.post_reason('Did not get right layers') - return 'fail' + assert ds.GetLayer(i).GetName() in layers, 'Did not get right layers' lyr = ds.GetLayerByName('FormatTests__FormatTable') - if lyr.GetFeatureCount() != 1: - gdaltest.post_reason('feature count wrong.') - return 'fail' + assert lyr.GetFeatureCount() == 1, 'feature count wrong.' feat = lyr.GetNextFeature() field_values = [0, 'aa_bb', 'cc dd', '', 1] - if feat.GetFieldCount() != len(field_values): - gdaltest.post_reason('field count wrong.') - return 'fail' + assert feat.GetFieldCount() == len(field_values), 'field count wrong.' for i in range(feat.GetFieldCount()): if feat.GetFieldAsString(i) != str(field_values[i]): feat.DumpReadable() print(feat.GetFieldAsString(i)) - gdaltest.post_reason('field value wrong.') - return 'fail' - - return 'success' + pytest.fail('field value wrong.') + ############################################################################### # Write Ili1 transfer file without model. -def ogr_interlis1_5(): +def test_ogr_interlis1_5(): if not gdaltest.have_ili_reader: - return 'skip' + pytest.skip() ds = ogr.Open('data/ili/format-default.itf,data/ili/format-default.imd') @@ -255,20 +215,17 @@ def ogr_interlis1_5(): ETOP EMOD ENDE""" - if expected not in itf: - gdaltest.post_reason("Interlis output doesn't match.") - return 'fail' - - return 'success' + assert expected in itf, "Interlis output doesn't match." + ############################################################################### # Write Ili1 transfer file. -def ogr_interlis1_6(): +def test_ogr_interlis1_6(): if not gdaltest.have_ili_reader: - return 'skip' + pytest.skip() ds = ogr.Open('data/ili/format-default.itf,data/ili/format-default.imd') lyr = ds.GetLayerByName('FormatTests__FormatTable') @@ -300,39 +257,29 @@ def ogr_interlis1_6(): ETOP EMOD ENDE""" - if expected not in itf: - gdaltest.post_reason("Interlis output doesn't match.") - print(itf) - return 'fail' - - return 'success' + assert expected in itf, "Interlis output doesn't match." + ############################################################################### # Ili1 character encoding test. -def ogr_interlis1_7(): +def test_ogr_interlis1_7(): if not gdaltest.have_ili_reader: - return 'skip' + pytest.skip() ds = ogr.Open('data/ili/encoding-test.itf,data/ili/format-default.imd') layers = ['FormatTests__FormatTable'] - if ds.GetLayerCount() != len(layers): - gdaltest.post_reason('layer count wrong.') - return 'fail' + assert ds.GetLayerCount() == len(layers), 'layer count wrong.' for i in range(ds.GetLayerCount()): - if not ds.GetLayer(i).GetName() in layers: - gdaltest.post_reason('Did not get right layers') - return 'fail' + assert ds.GetLayer(i).GetName() in layers, 'Did not get right layers' lyr = ds.GetLayerByName('FormatTests__FormatTable') - if lyr.GetFeatureCount() != 1: - gdaltest.post_reason('feature count wrong.') - return 'fail' + assert lyr.GetFeatureCount() == 1, 'feature count wrong.' feat = lyr.GetNextFeature() @@ -340,16 +287,13 @@ def ogr_interlis1_7(): # Python source code is UTF-8 encoded field_values = [0, 'äöü', 'ÄÖÜ', '', 1] - if feat.GetFieldCount() != len(field_values): - gdaltest.post_reason('field count wrong.') - return 'fail' + assert feat.GetFieldCount() == len(field_values), 'field count wrong.' for i in range(feat.GetFieldCount()): if feat.GetFieldAsString(i) != str(field_values[i]): feat.DumpReadable() print(feat.GetFieldAsString(i)) - gdaltest.post_reason('field value wrong.') - return 'fail' + pytest.fail('field value wrong.') # Write back driver = ogr.GetDriverByName('Interlis 1') @@ -386,122 +330,94 @@ def ogr_interlis1_7(): expected = expected.decode('utf8').encode('iso-8859-1') except: pass - if expected not in itf: - gdaltest.post_reason("Interlis output doesn't match.") - print(itf) - return 'fail' - - return 'success' + assert expected in itf, "Interlis output doesn't match." ############################################################################### # Ili1 VRT rename -def ogr_interlis1_9(): +def test_ogr_interlis1_9(): if not gdaltest.have_ili_reader: - return 'skip' + pytest.skip() ds = ogr.Open('data/ili/Beispiel-rename.vrt') layers = ['BoGebaeude'] - if ds.GetLayerCount() != len(layers): - gdaltest.post_reason('layer count wrong.') - return 'fail' + assert ds.GetLayerCount() == len(layers), 'layer count wrong.' for i in range(ds.GetLayerCount()): - if not ds.GetLayer(i).GetName() in layers: - gdaltest.post_reason('Did not get right layers') - return 'fail' + assert ds.GetLayer(i).GetName() in layers, 'Did not get right layers' lyr = ds.GetLayerByName('BoGebaeude') - if lyr.GetLayerDefn().GetFieldDefn(0).GetNameRef() != 'AssekuranzNr': - gdaltest.post_reason('Wrong field name: ' + lyr.GetLayerDefn().GetFieldDefn(0).GetNameRef()) - return 'fail' + assert lyr.GetLayerDefn().GetFieldDefn(0).GetNameRef() == 'AssekuranzNr', \ + ('Wrong field name: ' + lyr.GetLayerDefn().GetFieldDefn(0).GetNameRef()) - if lyr.GetFeatureCount() != 1: - gdaltest.post_reason('feature count wrong.') - return 'fail' + assert lyr.GetFeatureCount() == 1, 'feature count wrong.' feat = lyr.GetNextFeature() field_values = ['958', 10, 'POINT (148.41 175.96)'] - if feat.GetFieldCount() != len(field_values) - 1: - gdaltest.post_reason('field count wrong.') - return 'fail' + assert feat.GetFieldCount() == len(field_values) - 1, 'field count wrong.' for i in range(feat.GetFieldCount()): if feat.GetFieldAsString(i) != str(field_values[i]): feat.DumpReadable() print(feat.GetFieldAsString(i)) - gdaltest.post_reason('field value wrong.') - return 'fail' - - return 'success' + pytest.fail('field value wrong.') + ############################################################################### # Ili1 Area with polygonizing -def ogr_interlis1_10(): +def test_ogr_interlis1_10(): if not gdaltest.have_ili_reader: - return 'skip' + pytest.skip() if not ogrtest.have_geos(): - return 'skip' + pytest.skip() ds = ogr.Open('data/ili/Beispiel.itf,data/ili/Beispiel.imd') lyr = ds.GetLayerByName('Bodenbedeckung__BoFlaechen') - if lyr.GetFeatureCount() != 3: - gdaltest.post_reason('feature count wrong.') - return 'fail' + assert lyr.GetFeatureCount() == 3, 'feature count wrong.' feat = lyr.GetNextFeature() geom_field_values = ['POLYGON ((146.92 174.98,138.68 187.51,147.04 193.0,149.79 188.82,158.15 194.31,163.64 185.96,146.92 174.98))', 'POINT (148.2 183.48)'] - if feat.GetGeomFieldCount() != len(geom_field_values): - gdaltest.post_reason('geom field count wrong.') - print(feat.GetGeomFieldCount()) - return 'fail' + assert feat.GetGeomFieldCount() == len(geom_field_values), 'geom field count wrong.' for i in range(feat.GetGeomFieldCount()): geom = feat.GetGeomFieldRef(i) if ogrtest.check_feature_geometry(geom, geom_field_values[i]) != 0: feat.DumpReadable() - return 'fail' - - return 'success' + pytest.fail() + ############################################################################### # Ili1 multi-geom test (RFC41) -def ogr_interlis1_11(): +def test_ogr_interlis1_11(): if not gdaltest.have_ili_reader: - return 'skip' + pytest.skip() ds = ogr.Open('data/ili/multigeom.itf,data/ili/multigeom.imd') layers = ['MultigeomTests__MultigeomTable'] - if ds.GetLayerCount() != len(layers): - gdaltest.post_reason('layer count wrong.') - return 'fail' + assert ds.GetLayerCount() == len(layers), 'layer count wrong.' for i in range(ds.GetLayerCount()): - if not ds.GetLayer(i).GetName() in layers: - gdaltest.post_reason('Did not get right layers') - return 'fail' + assert ds.GetLayer(i).GetName() in layers, 'Did not get right layers' lyr = ds.GetLayerByName('MultigeomTests__MultigeomTable') - if lyr.GetFeatureCount() != 1: - gdaltest.post_reason('feature count wrong.') - return 'fail' + assert lyr.GetFeatureCount() == 1, 'feature count wrong.' feat = lyr.GetNextFeature() @@ -513,83 +429,61 @@ def ogr_interlis1_11(): # GeomPoint_0 (Real) = 148.41 # GeomPoint_1 (Real) = 175.96 - if feat.GetFieldCount() != 5: - gdaltest.post_reason('field count wrong.') - print(feat.GetFieldCount()) - return 'fail' + assert feat.GetFieldCount() == 5, 'field count wrong.' geom_columns = ['GeomLine', 'GeomPoint'] - if feat.GetGeomFieldCount() != len(geom_columns): - gdaltest.post_reason('geom field count wrong.') - print(feat.GetGeomFieldCount()) - return 'fail' + assert feat.GetGeomFieldCount() == len(geom_columns), 'geom field count wrong.' for i in range(feat.GetGeomFieldCount()): defn = lyr.GetLayerDefn().GetGeomFieldDefn(i) - if defn.GetName() != str(geom_columns[i]): - print("Geom field: " + defn.GetName()) - return 'fail' - - return 'success' + assert defn.GetName() == str(geom_columns[i]), ("Geom field: " + defn.GetName()) + ############################################################################### # Ili1 multi-geom test (RFC41) -def ogr_interlis1_12(): +def test_ogr_interlis1_12(): if not gdaltest.have_ili_reader: - return 'skip' + pytest.skip() ds = ogr.Open('data/ili/multicoord.itf,data/ili/multicoord.imd') layers = ['MulticoordTests__MulticoordTable'] - if ds.GetLayerCount() != len(layers): - gdaltest.post_reason('layer count wrong.') - return 'fail' + assert ds.GetLayerCount() == len(layers), 'layer count wrong.' for i in range(ds.GetLayerCount()): - if not ds.GetLayer(i).GetName() in layers: - gdaltest.post_reason('Did not get right layers') - return 'fail' + assert ds.GetLayer(i).GetName() in layers, 'Did not get right layers' lyr = ds.GetLayerByName('MulticoordTests__MulticoordTable') - if lyr.GetFeatureCount() != 1: - gdaltest.post_reason('feature count wrong.') - return 'fail' + assert lyr.GetFeatureCount() == 1, 'feature count wrong.' feat = lyr.GetNextFeature() if feat.GetFieldCount() != 6: feat.DumpReadable() - gdaltest.post_reason('field count wrong.') - return 'fail' + pytest.fail('field count wrong.') geom_columns = ['coordPoint1', 'coordPoint2'] - if feat.GetGeomFieldCount() != len(geom_columns): - gdaltest.post_reason('geom field count wrong.') - print(feat.GetGeomFieldCount()) - return 'fail' + assert feat.GetGeomFieldCount() == len(geom_columns), 'geom field count wrong.' for i in range(feat.GetGeomFieldCount()): defn = lyr.GetLayerDefn().GetGeomFieldDefn(i) - if defn.GetName() != str(geom_columns[i]): - print("Geom field: " + defn.GetName()) - return 'fail' - - return 'success' + assert defn.GetName() == str(geom_columns[i]), ("Geom field: " + defn.GetName()) + ############################################################################### # Ili1 Surface test. -def ogr_interlis1_13(): +def test_ogr_interlis1_13(): if not gdaltest.have_ili_reader: - return 'skip' + pytest.skip() ds = ogr.Open('data/ili/surface.itf,data/ili/surface.imd') @@ -602,70 +496,53 @@ def ogr_interlis1_13(): 'SURFC_TOP__Flaechenelement_Geometrie' ] - if ds.GetLayerCount() != len(layers): - gdaltest.post_reason('layer count wrong.') - return 'fail' + assert ds.GetLayerCount() == len(layers), 'layer count wrong.' for i in range(ds.GetLayerCount()): - if not ds.GetLayer(i).GetName() in layers: - gdaltest.post_reason('Did not get right layers') - return 'fail' + assert ds.GetLayer(i).GetName() in layers, 'Did not get right layers' lyr = ds.GetLayerByName('SURFC_TOP__SURFC_TBL_SHAPE') - if lyr.GetFeatureCount() != 5: - gdaltest.post_reason('feature count wrong.') - return 'fail' + assert lyr.GetFeatureCount() == 5, 'feature count wrong.' lyr = ds.GetLayerByName('SURFC_TOP__SURFC_TBL') - if lyr.GetFeatureCount() != 4: - gdaltest.post_reason('feature count wrong.') - return 'fail' + assert lyr.GetFeatureCount() == 4, 'feature count wrong.' feat = lyr.GetNextFeature() field_values = ['103', 1, 3, 1, 23, 25000, 20060111] - if feat.GetFieldCount() != len(field_values): - gdaltest.post_reason('field count wrong.') - return 'fail' + assert feat.GetFieldCount() == len(field_values), 'field count wrong.' for i in range(feat.GetFieldCount()): if feat.GetFieldAsString(i) != str(field_values[i]): feat.DumpReadable() print(feat.GetFieldAsString(i)) - gdaltest.post_reason('field value wrong.') - return 'fail' + pytest.fail('field value wrong.') geom_field_values = ['CURVEPOLYGON (COMPOUNDCURVE ((598600.961 249487.174,598608.899 249538.768,598624.774 249594.331,598648.586 249630.05,598684.305 249661.8,598763.68 249685.612,598850.993 249685.612,598854.962 249618.143,598843.055 249550.675,598819.243 249514.956,598763.68 249479.237,598692.243 249447.487,598612.868 249427.643,598600.961 249487.174)))'] - if feat.GetGeomFieldCount() != len(geom_field_values): - gdaltest.post_reason('geom field count wrong.') - print(feat.GetGeomFieldCount()) - return 'fail' + assert feat.GetGeomFieldCount() == len(geom_field_values), 'geom field count wrong.' for i in range(feat.GetGeomFieldCount()): geom = feat.GetGeomFieldRef(i) if ogrtest.check_feature_geometry(geom, geom_field_values[i]) != 0: feat.DumpReadable() - return 'fail' + pytest.fail() # --- test curved polygon feat = lyr.GetNextFeature() geom_field_values = ['CURVEPOLYGON (COMPOUNDCURVE ((598131.445 249100.621,598170.131 249095.094,598200.448 249085.393),CIRCULARSTRING (598200.448 249085.393,598239.253 249062.352,598246.529 249044.162),(598246.529 249044.162,598245.316 249025.972,598229.552 249017.483,598165.28 249035.673,598134.963 249049.013,598130.273 249052.095,598131.445 249100.621)))'] - if feat.GetGeomFieldCount() != len(geom_field_values): - gdaltest.post_reason('geom field count wrong.') - print(feat.GetGeomFieldCount()) - return 'fail' + assert feat.GetGeomFieldCount() == len(geom_field_values), 'geom field count wrong.' for i in range(feat.GetGeomFieldCount()): geom = feat.GetGeomFieldRef(i) if ogrtest.check_feature_geometry(geom, geom_field_values[i]) != 0: feat.DumpReadable() - return 'fail' + pytest.fail() # --- test multi-ring polygon @@ -673,30 +550,24 @@ def ogr_interlis1_13(): feat = lyr.GetNextFeature() field_values = ['106', 3, 3, 1, 23, 25000, 20060111] - if feat.GetFieldCount() != len(field_values): - gdaltest.post_reason('field count wrong.') - return 'fail' + assert feat.GetFieldCount() == len(field_values), 'field count wrong.' for i in range(feat.GetFieldCount()): if feat.GetFieldAsString(i) != str(field_values[i]): feat.DumpReadable() print(feat.GetFieldAsString(i)) - gdaltest.post_reason('field value wrong.') - return 'fail' + pytest.fail('field value wrong.') # FIXME: note this is an invalid curve polygon. The two rings are completely disjoint, so this should be a multisurface instead. geom_field_values = ['CURVEPOLYGON (COMPOUNDCURVE ((747951.24 265833.326,747955.101 265828.716,747954.975 265827.862,747951.166 265828.348,747951.24 265833.326)),COMPOUNDCURVE ((747925.762 265857.606,747927.618 265861.533,747928.237 265860.794,747930.956 265857.547,747925.762 265857.606)))'] - if feat.GetGeomFieldCount() != len(geom_field_values): - gdaltest.post_reason('geom field count wrong.') - print(feat.GetGeomFieldCount()) - return 'fail' + assert feat.GetGeomFieldCount() == len(geom_field_values), 'geom field count wrong.' for i in range(feat.GetGeomFieldCount()): geom = feat.GetGeomFieldRef(i) if ogrtest.check_feature_geometry(geom, geom_field_values[i]) != 0: feat.DumpReadable() - return 'fail' + pytest.fail() # --- same with text IDENT field # TODO: Surface with text IDENT field not supported yet @@ -774,9 +645,7 @@ def ogr_interlis1_13(): # return 'fail' lyr = ds.GetLayerByName('SURFC_TOP__Flaechenelement_Geometrie') - if lyr.GetFeatureCount() != 3: - gdaltest.post_reason('feature count wrong.') - return 'fail' + assert lyr.GetFeatureCount() == 3, 'feature count wrong.' feat = lyr.GetNextFeature() @@ -786,7 +655,7 @@ def ogr_interlis1_13(): geom = feat.GetGeomFieldRef(i) if ogrtest.check_feature_geometry(geom, geom_field_values[i]) != 0: feat.DumpReadable() - return 'fail' + pytest.fail() feat = lyr.GetNextFeature() @@ -796,12 +665,10 @@ def ogr_interlis1_13(): geom = feat.GetGeomFieldRef(i) if ogrtest.check_feature_geometry(geom, geom_field_values[i]) != 0: feat.DumpReadable() - return 'fail' + pytest.fail() lyr = ds.GetLayerByName('SURFC_TOP__Flaechenelement') - if lyr.GetFeatureCount() != 2: - gdaltest.post_reason('feature count wrong.') - return 'fail' + assert lyr.GetFeatureCount() == 2, 'feature count wrong.' feat = lyr.GetNextFeature() @@ -811,7 +678,7 @@ def ogr_interlis1_13(): geom = feat.GetGeomFieldRef(i) if ogrtest.check_feature_geometry(geom, geom_field_values[i]) != 0: feat.DumpReadable() - return 'fail' + pytest.fail() feat = lyr.GetNextFeature() @@ -821,7 +688,7 @@ def ogr_interlis1_13(): geom = feat.GetGeomFieldRef(i) if ogrtest.check_feature_geometry(geom, geom_field_values[i]) != 0: feat.DumpReadable() - return 'fail' + pytest.fail() # Test assembling curves not in "right" order ds = ogr.Open('data/ili/surface_complex.itf,data/ili/surface.imd') @@ -834,18 +701,17 @@ def ogr_interlis1_13(): geom = feat.GetGeomFieldRef(i) if ogrtest.check_feature_geometry(geom, geom_field_values[i]) != 0: feat.DumpReadable() - return 'fail' - - return 'success' + pytest.fail() + ############################################################################### # Ili1 Surface test with linear conversion. -def ogr_interlis1_13_linear(): +def test_ogr_interlis1_13_linear(): if not gdaltest.have_ili_reader: - return 'skip' + pytest.skip() gdal.SetConfigOption('OGR_STROKE_CURVE', 'YES') @@ -860,69 +726,52 @@ def ogr_interlis1_13_linear(): 'SURFC_TOP__Flaechenelement_Geometrie' ] - if ds.GetLayerCount() != len(layers): - gdaltest.post_reason('layer count wrong.') - return 'fail' + assert ds.GetLayerCount() == len(layers), 'layer count wrong.' for i in range(ds.GetLayerCount()): - if not ds.GetLayer(i).GetName() in layers: - gdaltest.post_reason('Did not get right layers') - return 'fail' + assert ds.GetLayer(i).GetName() in layers, 'Did not get right layers' lyr = ds.GetLayerByName('SURFC_TOP__SURFC_TBL_SHAPE') - if lyr.GetFeatureCount() != 5: - gdaltest.post_reason('feature count wrong.') - return 'fail' + assert lyr.GetFeatureCount() == 5, 'feature count wrong.' lyr = ds.GetLayerByName('SURFC_TOP__SURFC_TBL') - if lyr.GetFeatureCount() != 4: - gdaltest.post_reason('feature count wrong.') - return 'fail' + assert lyr.GetFeatureCount() == 4, 'feature count wrong.' feat = lyr.GetNextFeature() field_values = ['103', 1, 3, 1, 23, 25000, 20060111] - if feat.GetFieldCount() != len(field_values): - gdaltest.post_reason('field count wrong.') - return 'fail' + assert feat.GetFieldCount() == len(field_values), 'field count wrong.' for i in range(feat.GetFieldCount()): if feat.GetFieldAsString(i) != str(field_values[i]): feat.DumpReadable() print(feat.GetFieldAsString(i)) - gdaltest.post_reason('field value wrong.') - return 'fail' + pytest.fail('field value wrong.') geom_field_values = ['POLYGON ((598600.961 249487.174,598608.899 249538.768,598624.774 249594.331,598648.586 249630.05,598684.305 249661.8,598763.68 249685.612,598850.993 249685.612,598854.962 249618.143,598843.055 249550.675,598819.243 249514.956,598763.68 249479.237,598692.243 249447.487,598612.868 249427.643,598600.961 249487.174))'] - if feat.GetGeomFieldCount() != len(geom_field_values): - gdaltest.post_reason('geom field count wrong.') - print(feat.GetGeomFieldCount()) - return 'fail' + assert feat.GetGeomFieldCount() == len(geom_field_values), 'geom field count wrong.' for i in range(feat.GetGeomFieldCount()): geom = feat.GetGeomFieldRef(i) if ogrtest.check_feature_geometry(geom, geom_field_values[i]) != 0: feat.DumpReadable() - return 'fail' + pytest.fail() # --- test curved polygon geom_field_values = ['POLYGON ((598600.961 249487.174,598608.899 249538.768,598624.774 249594.331,598648.586 249630.05,598684.305 249661.8,598763.68 249685.612,598850.993 249685.612,598854.962 249618.143,598843.055 249550.675,598819.243 249514.956,598763.68 249479.237,598692.243 249447.487,598612.868 249427.643,598600.961 249487.174))'] - if feat.GetGeomFieldCount() != len(geom_field_values): - gdaltest.post_reason('geom field count wrong.') - print(feat.GetGeomFieldCount()) - return 'fail' + assert feat.GetGeomFieldCount() == len(geom_field_values), 'geom field count wrong.' for i in range(feat.GetGeomFieldCount()): geom = feat.GetGeomFieldRef(i) if ogrtest.check_feature_geometry(geom, geom_field_values[i]) != 0: feat.DumpReadable() - return 'fail' + pytest.fail() # --- test multi-ring polygon @@ -931,34 +780,26 @@ def ogr_interlis1_13_linear(): # field_values = ['106', 3, 3, 1, 23, 25000, 20060111] field_values = ['105', 3, 3, 1, 23, 25000, 20060111] - if feat.GetFieldCount() != len(field_values): - gdaltest.post_reason('field count wrong.') - return 'fail' + assert feat.GetFieldCount() == len(field_values), 'field count wrong.' for i in range(feat.GetFieldCount()): if feat.GetFieldAsString(i) != str(field_values[i]): feat.DumpReadable() print(feat.GetFieldAsString(i)) - gdaltest.post_reason('field value wrong.') - return 'fail' + pytest.fail('field value wrong.') geom_field_values = ['POLYGON ((598330.204 249028.397,598344.756 249057.501,598390.838 249074.479,598422.367 249081.755,598459.96 249093.882,598493.915 249101.158,598523.019 249106.008,598563.038 249084.18,598589.716 249042.949,598603.056 249011.42,598607.907 248966.551,598577.59 248960.487,598493.915 248983.528,598424.793 248996.868,598359.308 249010.207,598330.204 249028.397))'] - if feat.GetGeomFieldCount() != len(geom_field_values): - gdaltest.post_reason('geom field count wrong.') - print(feat.GetGeomFieldCount()) - return 'fail' + assert feat.GetGeomFieldCount() == len(geom_field_values), 'geom field count wrong.' for i in range(feat.GetGeomFieldCount()): geom = feat.GetGeomFieldRef(i) if ogrtest.check_feature_geometry(geom, geom_field_values[i]) != 0: feat.DumpReadable() - return 'fail' + pytest.fail() lyr = ds.GetLayerByName('SURFC_TOP__Flaechenelement_Geometrie') - if lyr.GetFeatureCount() != 3: - gdaltest.post_reason('feature count wrong.') - return 'fail' + assert lyr.GetFeatureCount() == 3, 'feature count wrong.' feat = lyr.GetNextFeature() @@ -968,7 +809,7 @@ def ogr_interlis1_13_linear(): geom = feat.GetGeomFieldRef(i) if ogrtest.check_feature_geometry(geom, geom_field_values[i]) != 0: feat.DumpReadable() - return 'fail' + pytest.fail() feat = lyr.GetNextFeature() @@ -978,12 +819,10 @@ def ogr_interlis1_13_linear(): geom = feat.GetGeomFieldRef(i) if ogrtest.check_feature_geometry(geom, geom_field_values[i]) != 0: feat.DumpReadable() - return 'fail' + pytest.fail() lyr = ds.GetLayerByName('SURFC_TOP__Flaechenelement') - if lyr.GetFeatureCount() != 2: - gdaltest.post_reason('feature count wrong.') - return 'fail' + assert lyr.GetFeatureCount() == 2, 'feature count wrong.' feat = lyr.GetNextFeature() @@ -993,7 +832,7 @@ def ogr_interlis1_13_linear(): geom = feat.GetGeomFieldRef(i) if ogrtest.check_feature_geometry(geom, geom_field_values[i]) != 0: feat.DumpReadable() - return 'fail' + pytest.fail() feat = lyr.GetNextFeature() @@ -1003,20 +842,18 @@ def ogr_interlis1_13_linear(): geom = feat.GetGeomFieldRef(i) if ogrtest.check_feature_geometry(geom, geom_field_values[i]) != 0: feat.DumpReadable() - return 'fail' + pytest.fail() gdal.SetConfigOption('OGR_STROKE_CURVE', None) - return 'success' - ############################################################################### # Write Ili1 Arcs. -def ogr_interlis1_14(): +def test_ogr_interlis1_14(): if not gdaltest.have_ili_reader: - return 'skip' + pytest.skip() ds = ogr.Open('data/ili/Beispiel.itf,data/ili/Beispiel.imd') lyr = ds.GetLayerByName('Bodenbedeckung__Strasse') @@ -1054,25 +891,20 @@ def ogr_interlis1_14(): EMOD ENDE """ - if expected not in itf: - gdaltest.post_reason("Interlis output doesn't match.") - print(itf) - return 'fail' - - return 'success' + assert expected in itf, "Interlis output doesn't match." + ############################################################################### # Reading Ili2 without model -def ogr_interlis2_1(): +def test_ogr_interlis2_1(): if not gdaltest.have_ili_reader: - return 'skip' + pytest.skip() ds = ogr.Open('data/ili/RoadsExdm2ien.xml') - if ds is None: - return 'fail' + assert ds is not None layers = ['RoadsExdm2ben.Roads.LandCover', 'RoadsExdm2ben.Roads.Street', @@ -1080,29 +912,23 @@ def ogr_interlis2_1(): 'RoadsExdm2ben.Roads.StreetNamePosition', 'RoadsExdm2ien.RoadsExtended.RoadSign'] - if ds.GetLayerCount() != len(layers): - gdaltest.post_reason('layer count wrong.') - return 'fail' + assert ds.GetLayerCount() == len(layers), 'layer count wrong.' for i in range(ds.GetLayerCount()): - if not ds.GetLayer(i).GetName() in layers: - gdaltest.post_reason('Did not get right layers') - return 'fail' - - return 'success' + assert ds.GetLayer(i).GetName() in layers, 'Did not get right layers' + ############################################################################### # Reading Ili2 -def ogr_interlis2_2(): +def test_ogr_interlis2_2(): if not gdaltest.have_ili_reader: - return 'skip' + pytest.skip() ds = ogr.Open('data/ili/RoadsExdm2ien.xml,data/ili/RoadsExdm2ien.imd') - if ds is None: - return 'fail' + assert ds is not None layers = ['RoadsExdm2ben.Roads.LAttrs', 'RoadsExdm2ben.Roads.LandCover', @@ -1111,19 +937,13 @@ def ogr_interlis2_2(): 'RoadsExdm2ien.RoadsExtended.StreetAxis', 'RoadsExdm2ien.RoadsExtended.RoadSign'] - if ds.GetLayerCount() != len(layers): - gdaltest.post_reason('layer count wrong.') - return 'fail' + assert ds.GetLayerCount() == len(layers), 'layer count wrong.' for i in range(ds.GetLayerCount()): - if not ds.GetLayer(i).GetName() in layers: - gdaltest.post_reason('Did not get right layers') - return 'fail' + assert ds.GetLayer(i).GetName() in layers, 'Did not get right layers' lyr = ds.GetLayerByName('RoadsExdm2ien.RoadsExtended.RoadSign') - if lyr.GetFeatureCount() != 4: - gdaltest.post_reason('feature count wrong.') - return 'fail' + assert lyr.GetFeatureCount() == 4, 'feature count wrong.' feat = lyr.GetNextFeature() @@ -1131,84 +951,66 @@ def ogr_interlis2_2(): if feat.GetFieldCount() != len(field_values): feat.DumpReadable() - gdaltest.post_reason('field count wrong.') - return 'fail' + pytest.fail('field count wrong.') for i in range(feat.GetFieldCount()): if feat.GetFieldAsString(i) != str(field_values[i]): feat.DumpReadable() print(feat.GetFieldAsString(i)) - gdaltest.post_reason('field value wrong.') - return 'fail' + pytest.fail('field value wrong.') geom = feat.GetGeometryRef() - if geom.GetCoordinateDimension() != 2: - gdaltest.post_reason('dimension wrong.') - return 'fail' + assert geom.GetCoordinateDimension() == 2, 'dimension wrong.' geom_field_values = ['POINT (69.389 92.056)'] - if feat.GetGeomFieldCount() != len(geom_field_values): - gdaltest.post_reason('geom field count wrong.') - print(feat.GetGeomFieldCount()) - return 'fail' + assert feat.GetGeomFieldCount() == len(geom_field_values), 'geom field count wrong.' for i in range(feat.GetGeomFieldCount()): geom = feat.GetGeomFieldRef(i) if ogrtest.check_feature_geometry(geom, geom_field_values[i]) != 0: feat.DumpReadable() - return 'fail' + pytest.fail() lyr = ds.GetLayerByName('RoadsExdm2ien.RoadsExtended.StreetAxis') - if lyr.GetFeatureCount() != 7: - gdaltest.post_reason('feature count wrong.') - return 'fail' + assert lyr.GetFeatureCount() == 7, 'feature count wrong.' feat = lyr.GetNextFeature() geom_field_values = ['LINESTRING (55.6 37.649,15.573 25.785)'] - if feat.GetGeomFieldCount() != len(geom_field_values): - gdaltest.post_reason('geom field count wrong.') - print(feat.GetGeomFieldCount()) - return 'fail' + assert feat.GetGeomFieldCount() == len(geom_field_values), 'geom field count wrong.' for i in range(feat.GetGeomFieldCount()): geom = feat.GetGeomFieldRef(i) if ogrtest.check_feature_geometry(geom, geom_field_values[i]) != 0: feat.DumpReadable() - return 'fail' + pytest.fail() lyr = ds.GetLayerByName('RoadsExdm2ben.Roads.LandCover') - if lyr.GetFeatureCount() != 12: - gdaltest.post_reason('feature count wrong.') - return 'fail' + assert lyr.GetFeatureCount() == 12, 'feature count wrong.' feat = lyr.GetNextFeature() geom_field_values = ['POLYGON ((39.038 60.315,41.2 59.302,43.362 60.315,44.713 66.268,45.794 67.662,48.766 67.408,53.36 64.115,56.197 62.595,57.818 63.862,58.899 68.928,55.927 72.348,47.955 75.515,42.281 75.388,39.308 73.235,36.741 69.688,35.525 66.268,35.661 63.735,37.957 61.455,39.038 60.315))'] - if feat.GetGeomFieldCount() != len(geom_field_values): - gdaltest.post_reason('geom field count wrong.') - print(feat.GetGeomFieldCount()) - return 'fail' + assert feat.GetGeomFieldCount() == len(geom_field_values), 'geom field count wrong.' for i in range(feat.GetGeomFieldCount()): geom = feat.GetGeomFieldRef(i) if ogrtest.check_feature_geometry(geom, geom_field_values[i]) != 0: feat.DumpReadable() - return 'fail' - - return 'success' + pytest.fail() + ############################################################################### # Write Ili2 transfer file. -def ogr_interlis2_3(): +def test_ogr_interlis2_3(): if not gdaltest.have_ili_reader: - return 'skip' + pytest.skip() ds = ogr.Open('data/ili/RoadsExdm2ien.xml,data/ili/RoadsExdm2ien.imd') @@ -1241,9 +1043,7 @@ def ogr_interlis2_3(): expected = """<?xml version="1.0" encoding="utf-8" ?> <TRANSFER xmlns="http://www.interlis.ch/INTERLIS2.3"> <HEADERSECTION SENDER="OGR/GDAL""" - if expected not in xtf: - gdaltest.post_reason("Interlis output doesn't match.") - return 'fail' + assert expected in xtf, "Interlis output doesn't match." expected = """<MODELS> <MODEL NAME="RoadsExdm2ben" URI="http://www.interlis.ch/models" VERSION="2005-06-16"/> <MODEL NAME="RoadsExdm2ien" URI="http://www.interlis.ch/models" VERSION="2005-06-16"/> @@ -1292,24 +1092,19 @@ def ogr_interlis2_3(): </TRANSFER>""" expected = expected.replace('.11499999999999', '.115') xtf = xtf.replace('.11499999999999', '.115') - if expected not in xtf: - gdaltest.post_reason("Interlis output doesn't match.") - print(xtf) - return 'fail' - return 'success' - + assert expected in xtf, "Interlis output doesn't match." + ############################################################################### # Ili2 Oereb model -def ogr_interlis2_4(): +def test_ogr_interlis2_4(): if not gdaltest.have_ili_reader: - return 'skip' + pytest.skip() ds = ogr.Open('data/ili/ch.bazl.sicherheitszonenplan.oereb_20131118.xtf,data/ili/ch.bazl.sicherheitszonenplan.oereb_20131118.imd') - if ds is None: - return 'fail' + assert ds is not None layers = ['chGeoId10.BFSNr_', 'chGeoId10.Kanton_', @@ -1339,19 +1134,13 @@ def ogr_interlis2_4(): 'OeREBKRM09trsfr.Transferstruktur.HinweisVorschrift', 'OeREBKRM09vs.Vorschriften.Dokument'] - if ds.GetLayerCount() != len(layers): - gdaltest.post_reason('layer count wrong.') - return 'fail' + assert ds.GetLayerCount() == len(layers), 'layer count wrong.' for i in range(ds.GetLayerCount()): - if not ds.GetLayer(i).GetName() in layers: - gdaltest.post_reason('Did not get right layers') - return 'fail' + assert ds.GetLayer(i).GetName() in layers, 'Did not get right layers' lyr = ds.GetLayerByName('OeREBKRM09trsfr.Transferstruktur.Geometrie') - if lyr.GetFeatureCount() != 36: - gdaltest.post_reason('feature count wrong.') - return 'fail' + assert lyr.GetFeatureCount() == 36, 'feature count wrong.' feat = lyr.GetNextFeature() @@ -1361,21 +1150,16 @@ def ogr_interlis2_4(): if feat.GetFieldCount() != len(field_values): feat.DumpReadable() - gdaltest.post_reason('field count wrong.') - return 'fail' + pytest.fail('field count wrong.') for i in range(feat.GetFieldCount()): if feat.GetFieldAsString(i) != str(field_values[i]): feat.DumpReadable() print(feat.GetFieldAsString(i)) - gdaltest.post_reason('field value wrong.') - return 'fail' + pytest.fail('field value wrong.') geom_field_values = [None, None, 'CURVEPOLYGON (COMPOUNDCURVE ((658593.928 254957.714,658511.628 254948.614,658418.028 254938.516,658106.426 254913.918,658192.222 254445.914,658771.228 254619.412,659667.232 254699.606,660369.238 254827.202,661016.442 255010.1,661279.644 255090.198,661866.648 255138.094,661784.45 255601.798,661211.146 255432.8,660320.54 255352.806,659523.436 255206.71,658703.528 254966.814,658624.228 254961.014,658593.928 254957.714)))'] - if feat.GetGeomFieldCount() != len(geom_field_values): - gdaltest.post_reason('geom field count wrong.') - print(feat.GetGeomFieldCount()) - return 'fail' + assert feat.GetGeomFieldCount() == len(geom_field_values), 'geom field count wrong.' for i in range(feat.GetGeomFieldCount()): geom = feat.GetGeomFieldRef(i) @@ -1385,20 +1169,18 @@ def ogr_interlis2_4(): else: ok = ogrtest.check_feature_geometry(geom, val) == 0 if not ok: - gdaltest.post_reason('geom check failed.') print(geom) - return 'fail' - - return 'success' + pytest.fail('geom check failed.') + ############################################################################### # Check arc segmentation -def ogr_interlis_arc1(): +def test_ogr_interlis_arc1(): if not gdaltest.have_ili_reader: - return 'skip' + pytest.skip() gdal.SetConfigOption('OGR_STROKE_CURVE', 'TRUE') # gdal.SetConfigOption('OGR_ARC_STEPSIZE', '0.96') @@ -1410,9 +1192,7 @@ def ogr_interlis_arc1(): # Read Area lines lyr = ds.GetLayerByName('Bodenbedeckung__BoFlaechen_Form') - if lyr.GetFeatureCount() != 4: - gdaltest.post_reason('feature count wrong.') - return 'fail' + assert lyr.GetFeatureCount() == 4, 'feature count wrong.' # Get 3rd feature feat = lyr.GetNextFeature() @@ -1421,114 +1201,67 @@ def ogr_interlis_arc1(): geom = feat.GetGeometryRef() length = geom.Length() - if abs(length - length_0_1_deg) > 0.001: - gdaltest.post_reason('Length() result wrong, got %g.' % length) - return 'fail' + assert abs(length - length_0_1_deg) <= 0.001, \ + ('Length() result wrong, got %g.' % length) if ogrtest.check_feature_geometry(geom, 'MULTILINESTRING ((186.38 206.82,186.456637039593772 206.352374385077951,186.525513501820711 205.883542875348297,186.586610467027612 205.413634254015022,186.639911152487883 204.942777600139351,186.685400917071064 204.471102253228281,186.72306726518579 203.998737777656032,186.752899850289367 203.525813927088137,186.774890477674461 203.05246060886563,186.789033106731921 202.578807848280093,186.795323852631526 202.104985752892361,186.793760987376999 201.631124476756639,186.784344940257114 201.157354184717377,186.76707829777294 200.683805016597006,186.741965802895692 200.210607051507367,186.709014353764331 199.737890272066551,186.668233001808375 199.265784528717603,186.619632949244959 198.79441950407633,186.563227546008392 198.323924677271833,186.499032286083064 197.854429288403452,186.427064803254297 197.386062303034095,186.347344866240718 196.918952376778151,186.259894373302785 196.453227819933062,186.164737346189185 195.989016562249134,186.06189992355209 195.52644611780849,185.951410353787622 195.065643549954956,185.83329898723602 194.606735436434946,185.70759826788705 194.149847834589281,185.574342724430579 193.695106246756012,185.433568960797828 193.242635585782381,185.285315646106 192.792560140718678,185.129623504006275 192.345003542672174,184.966535301544326 191.900088730850229,184.796095837373258 191.457937918770739,184.618351929457248 191.018672560741805,184.433352402229474 190.582413318443258,184.241148073160701 190.149280027813774,184.04179173881127 189.71939166611989,183.835338160315558 189.292866319286958,183.621844048349857 188.869821149441094,183.401368047569093 188.450372362771276,183.173970720454207 188.03463517752968,182.939714530730242 187.622723792475853,182.698663826158707 187.214751355422749,182.450884820893378 186.810829932226596,182.196445577297681 186.411070475951391,181.935415987201822 186.015582796419011,181.667867752774299 185.624475530035824,181.3938743667604 185.237856109953981,181.113511092327798 184.855830736560137,180.826854942395556 184.478504348306132,180.53398465846837 184.105980592874374,180.234980689005141 183.73836179872157,179.929925167336449 183.375748946964421,179.618901889065427 183.018241643621849,179.301996289112111 182.665938092286495,178.979295418190276 182.318935067130923,178.650887918905909 181.977327886313986,178.316864001440962 181.64121038583832,177.97731541873506 181.310674893720687,177.632335441296135 180.985812204678922,177.282018831589056 180.666711555153569,176.9264618179877 180.353460598817009,176.565762068363227 180.046145382490039,176.200018663221243 179.744850322516839,175.829332068533375 179.449658181561944,175.453804108095909 179.160650045865594,175.073537935597386 178.877905303001143,174.688638006242371 178.601501620054449,174.299210048091453 178.331514922276227,173.905361033015623 178.068019372236421,173.507199147294131 177.811087349466078,173.104833761914023 177.560789430557605,172.698375402513165 177.317194369767066,172.28793571903222 177.080369080176723,171.873627455046488 176.850378615250492,171.455564416777605 176.627286151007837,171.033861441848018 176.411152968667096,170.60863436775486 176.202038437793476,170.18 176.0,140.69 156.63))') != 0: - gdaltest.post_reason('Ili curve not correctly read') print(geom.ExportToWkt()) - return 'fail' + pytest.fail('Ili curve not correctly read') line = geom.GetGeometryRef(0) points = line.GetPoints() - if len(points) != 81: - gdaltest.post_reason('line point count wrong.') - return 'fail' + assert len(points) == 81, 'line point count wrong.' # Get 4th feature feat = lyr.GetNextFeature() geom = feat.GetGeometryRef() length = geom.Length() - if abs(length - 98.0243498288) > 0.001: - gdaltest.post_reason('Length() result wrong, got %g.' % length) - return 'fail' + assert abs(length - 98.0243498288) <= 0.001, \ + ('Length() result wrong, got %g.' % length) if ogrtest.check_feature_geometry(geom, 'MULTILINESTRING ((186.38 206.82,194.26 208.19,194.360118941290381 207.583863387608318,194.450034548441351 206.976129417129414,194.52972141151983 206.366969832830335,194.599157011165488 205.756556781867374,194.658321725044487 205.145062765608571,194.707198833340925 204.532660590913991,194.745774523486006 203.919523321273999,194.774037894087058 203.305824227936654,194.791980957968889 202.691736740889581,194.799598644465704 202.077434399900056,194.796888800832647 201.463090805460496,194.783852192864259 200.848879569690297,194.760492504683469 200.234974267339538,194.72681633767931 199.621548386683543,194.682833208673372 199.00877528050475,194.628555547191326 198.396828117140075,194.56399869197773 197.785879831499159,194.489180886659568 197.176103076206317,194.40412327458759 196.567670172822517,194.308849892848201 195.960753063147394,194.203387665489544 195.355523260601302,194.087766395903571 194.752151801789267,193.962018758407766 194.150809198152245,193.826180289004668 193.55166538777118,193.680289375348337 192.954889687360236,193.524387245874067 192.360650744412823,193.358517958193232 191.769116489536799,193.182728386585921 191.180454089007952,192.997068208809623 190.594829897498101,192.80158989201297 190.012409411123343,192.596348677929171 189.433357220623265,192.381402567276353 188.857836964845745,192.156812303357555 188.28601128455918,191.922641354867636 187.718041776424769,191.678955898001703 187.15408894736899,191.425824797734066 186.594312169210724,191.163319588355051 186.038869633623079,190.891514453251119 185.48791830744446,190.610486203950103 184.941613888295223,190.320314258417028 184.400110760594515,190.021080618593231 183.863561951926357,189.71286984725154 183.332119089784072,189.395769044065645 182.805932358758554,189.069867821024644 182.285150458053948,188.735258277090878 181.769920559469,188.392034972181108 181.260388265836781,188.040294900434645 180.756697569857323,187.680137462819374 180.258990813403187,187.311664439032 179.767408647305245,186.934979958736193 179.282089991582296,186.550190472116782 178.803171996223654,186.157404719844607 178.330790002393741,185.756733702299215 177.865077504182381,185.348290648216761 177.406166110929888,184.932190982704896 176.954185509959615,184.508552294610098 176.50926343000171,184.077494303273824 176.071525605046162,183.639138824742957 175.641095738836128,183.193609737303603 175.218095469892404,182.741032946476452 174.802644337149076,182.281536349473726 174.394859746185801,181.815249799001293 173.994856936020341,181.34230506662422 173.60274894655592,180.86283580545566 173.21864658665433,180.376977512460115 172.84265840277655,179.884867490109144 172.47489064835824,179.38664480760778 172.115447253752762,178.882450261575258 171.764429796865414,178.372426336281904 171.421937474442501,177.856717163354887 171.08806707407345,177.335468481061952 170.762912946782279,176.808827593129507 170.446566980404867,176.276943327102316 170.13911857360651,175.739965992295737 169.840654610641622,175.198047337304331 169.551259436742839,174.651340507162928 169.271014834364934,174.1 169.0,145.08 149.94,140.69 156.63))') != 0: - gdaltest.post_reason('Ili curve not correctly read') print(geom.ExportToWkt()) - return 'fail' + pytest.fail('Ili curve not correctly read') line = geom.GetGeometryRef(0) points = line.GetPoints() - if len(points) != 81: - gdaltest.post_reason('line point count wrong.') - return 'fail' - - return 'success' + assert len(points) == 81, 'line point count wrong.' ############################################################################### # Check polyline with arc -def ogr_interlis_arc2(): +def test_ogr_interlis_arc2(): if not gdaltest.have_ili_reader: - return 'skip' + pytest.skip() ds = ogr.Open('data/ili/Beispiel.itf,data/ili/Beispiel.imd') lyr = ds.GetLayerByName('Bodenbedeckung__Strasse') - if lyr.GetFeatureCount() != 1: - gdaltest.post_reason('feature count wrong.') - return 'fail' + assert lyr.GetFeatureCount() == 1, 'feature count wrong.' feat = lyr.GetNextFeature() geom_field_values = ['MULTICURVE (COMPOUNDCURVE (CIRCULARSTRING (190.26 208.0,187 186,173.1 171.0),(173.1 171.0,141.08 152.94)))'] - if feat.GetGeomFieldCount() != len(geom_field_values): - gdaltest.post_reason('geom field count wrong.') - print(feat.GetGeomFieldCount()) - return 'fail' + assert feat.GetGeomFieldCount() == len(geom_field_values), 'geom field count wrong.' for i in range(feat.GetGeomFieldCount()): geom = feat.GetGeomFieldRef(i) if ogrtest.check_feature_geometry(geom, geom_field_values[i]) != 0: feat.DumpReadable() - return 'fail' - - return 'success' + pytest.fail() + ############################################################################### # -def ogr_interlis_cleanup(): +def test_ogr_interlis_cleanup(): if not gdaltest.have_ili_reader: - return 'skip' + pytest.skip() gdal.SetConfigOption('OGR_STROKE_CURVE', None) gdaltest.clean_tmp() - return 'success' - - -gdaltest_list = [ - ogr_interlis1_1, - ogr_interlis1_2, - ogr_interlis1_3, - ogr_interlis1_4, - ogr_interlis1_5, - ogr_interlis1_6, - ogr_interlis1_7, - ogr_interlis1_9, - ogr_interlis1_10, - ogr_interlis1_11, - ogr_interlis1_12, - ogr_interlis1_13, - ogr_interlis1_13_linear, - ogr_interlis1_14, - ogr_interlis2_1, - ogr_interlis2_2, - ogr_interlis2_3, - ogr_interlis2_4, - ogr_interlis_arc1, - ogr_interlis_arc2, - ogr_interlis_cleanup] - -if __name__ == '__main__': - - gdaltest.setup_run('ogr_ili') - - gdaltest.run_tests(gdaltest_list) - - sys.exit(gdaltest.summarize()) + + diff --git a/autotest/ogr/ogr_index_test.py b/autotest/ogr/ogr_index_test.py index c39233c47685..3bf99c179efa 100755 --- a/autotest/ogr/ogr_index_test.py +++ b/autotest/ogr/ogr_index_test.py @@ -27,19 +27,18 @@ ############################################################################### import os -import sys -sys.path.append('../pymod') import gdaltest from osgeo import ogr import ogrtest +import pytest ############################################################################### # Create a MIF file to be our primary table. -def ogr_index_1(): +def test_ogr_index_1(): from osgeo import gdal gdal.PushErrorHandler('CPLQuietErrorHandler') @@ -79,13 +78,11 @@ def ogr_index_1(): gdaltest.p_ds = ogr.OpenShared('index_p.mif', update=0) gdaltest.p_lyr = gdaltest.p_ds.GetLayerByName('index_p') - return 'success' - ############################################################################### # Create a dbf file to be our secondary table. Close it, and reopen shared. -def ogr_index_2(): +def test_ogr_index_2(): drv = ogr.GetDriverByName('ESRI Shapefile') gdaltest.s_ds = drv.CreateDataSource('join_t.dbf') @@ -99,9 +96,7 @@ def ogr_index_2(): for i in range(20): ogrtest.quick_create_feature(gdaltest.s_lyr, [i, 'Value ' + str(i)], None) - if gdaltest.s_lyr.GetFeatureCount() != 20: - gdaltest.post_reason('FeatureCount wrong') - return 'fail' + assert gdaltest.s_lyr.GetFeatureCount() == 20, 'FeatureCount wrong' gdaltest.s_ds.Release() gdaltest.s_lyr = None @@ -110,13 +105,11 @@ def ogr_index_2(): gdaltest.s_ds = ogr.OpenShared('join_t.dbf', update=1) gdaltest.s_lyr = gdaltest.s_ds.GetLayerByName('join_t') - return 'success' - ############################################################################### # Verify a simple join without indexing. -def ogr_index_3(): +def test_ogr_index_3(): expect = ['Value 5', 'Value 10', 'Value 9', 'Value 4', 'Value 3', 'Value 1'] @@ -129,31 +122,29 @@ def ogr_index_3(): gdaltest.p_ds.ReleaseResultSet(sql_lyr) - return 'success' if tr else 'fail' + assert tr ############################################################################### # Create an INDEX on the SKEY and VALUE field in the join table. -def ogr_index_4(): +def test_ogr_index_4(): gdaltest.s_ds.ExecuteSQL('CREATE INDEX ON join_t USING value') gdaltest.s_ds.ExecuteSQL('CREATE INDEX ON join_t USING skey') - return 'success' - ############################################################################### # Check that indexable single int lookup works. -def ogr_index_5(): +def test_ogr_index_5(): gdaltest.s_lyr.SetAttributeFilter('SKEY = 5') expect = ['Value 5'] tr = ogrtest.check_features_against_list(gdaltest.s_lyr, 'VALUE', expect) - return 'success' if tr else 'fail' + assert tr ############################################################################### # Check that indexable single string lookup works. @@ -162,7 +153,7 @@ def ogr_index_5(): # work OK too. -def ogr_index_6(): +def test_ogr_index_6(): gdaltest.s_ds.Release() gdaltest.s_ds = ogr.OpenShared('join_t.dbf', update=1) @@ -173,14 +164,14 @@ def ogr_index_6(): expect = [5] tr = ogrtest.check_features_against_list(gdaltest.s_lyr, 'SKEY', expect) - return 'success' if tr else 'fail' + assert tr ############################################################################### # Check that range query that isn't currently implemented using index works. -def ogr_index_7(): +def test_ogr_index_7(): gdaltest.s_lyr.SetAttributeFilter('SKEY < 3') @@ -188,13 +179,13 @@ def ogr_index_7(): tr = ogrtest.check_features_against_list(gdaltest.s_lyr, 'SKEY', expect) - return 'success' if tr else 'fail' + assert tr ############################################################################### # Try join again. -def ogr_index_8(): +def test_ogr_index_8(): expect = ['Value 5', 'Value 10', 'Value 9', 'Value 4', 'Value 3', 'Value 1'] @@ -207,14 +198,14 @@ def ogr_index_8(): gdaltest.p_ds.ReleaseResultSet(sql_lyr) - return 'success' if tr else 'fail' + assert tr ############################################################################### # Verify that dropping both indexes gets rid of them, and that results still # work. -def ogr_index_9(): +def test_ogr_index_9(): gdaltest.s_ds.ExecuteSQL('DROP INDEX ON join_t USING value') gdaltest.s_ds.ExecuteSQL('DROP INDEX ON join_t USING skey') @@ -224,20 +215,16 @@ def ogr_index_9(): expect = ['Value 5'] tr = ogrtest.check_features_against_list(gdaltest.s_lyr, 'VALUE', expect) - if not tr: - return 'fail' + assert tr gdaltest.s_ds.Release() # After dataset closing, check that the index files do not exist after # dropping the index for filename in ['join_t.idm', 'join_t.ind']: - try: + with pytest.raises(OSError, message="%s should not exist" % filename): os.stat(filename) - gdaltest.post_reason("%s should not exist" % filename) - return 'fail' - except OSError: - pass + # Re-create an index gdaltest.s_ds = ogr.OpenShared('join_t.dbf', update=1) @@ -248,16 +235,12 @@ def ogr_index_9(): try: os.stat(filename) except OSError: - gdaltest.post_reason("%s should exist" % filename) - return 'fail' + pytest.fail("%s should exist" % filename) f = open('join_t.idm', 'rt') xml = f.read() f.close() - if xml.find('VALUE') == -1: - gdaltest.post_reason('VALUE column is not indexed (1)') - print(xml) - return 'fail' + assert xml.find('VALUE') != -1, 'VALUE column is not indexed (1)' # Close the dataset and re-open gdaltest.s_ds = ogr.OpenShared('join_t.dbf', update=1) @@ -270,22 +253,14 @@ def ogr_index_9(): f = open('join_t.idm', 'rt') xml = f.read() f.close() - if xml.find('VALUE') == -1: - gdaltest.post_reason('VALUE column is not indexed (2)') - print(xml) - return 'fail' - if xml.find('SKEY') == -1: - gdaltest.post_reason('SKEY column is not indexed (2)') - print(xml) - return 'fail' - - return 'success' + assert xml.find('VALUE') != -1, 'VALUE column is not indexed (2)' + assert xml.find('SKEY') != -1, 'SKEY column is not indexed (2)' ############################################################################### # Test fix for #4326 -def ogr_index_10(): +def test_ogr_index_10(): ds = ogr.GetDriverByName('ESRI Shapefile').CreateDataSource('tmp/ogr_index_10.shp') lyr = ds.CreateLayer('ogr_index_10') @@ -304,126 +279,90 @@ def ogr_index_10(): lyr.SetAttributeFilter('intfield IN (1)') lyr.ResetReading() feat = lyr.GetNextFeature() - if feat is None: - gdaltest.post_reason('failed') - return 'fail' + assert feat is not None lyr.SetAttributeFilter('intfield = 1') lyr.ResetReading() feat = lyr.GetNextFeature() - if feat is None: - gdaltest.post_reason('failed') - return 'fail' + assert feat is not None lyr.SetAttributeFilter('intfield IN (2)') lyr.ResetReading() feat = lyr.GetNextFeature() - if feat is not None: - gdaltest.post_reason('failed') - return 'fail' + assert feat is None lyr.SetAttributeFilter('intfield IN (1.0)') lyr.ResetReading() feat = lyr.GetNextFeature() - if feat is None: - gdaltest.post_reason('failed') - return 'fail' + assert feat is not None lyr.SetAttributeFilter('intfield = 1.0') lyr.ResetReading() feat = lyr.GetNextFeature() - if feat is None: - gdaltest.post_reason('failed') - return 'fail' + assert feat is not None lyr.SetAttributeFilter('intfield IN (1.1)') lyr.ResetReading() feat = lyr.GetNextFeature() - if feat is not None: - gdaltest.post_reason('failed') - return 'fail' + assert feat is None lyr.SetAttributeFilter("intfield IN ('1')") lyr.ResetReading() feat = lyr.GetNextFeature() - if feat is None: - gdaltest.post_reason('failed') - return 'fail' + assert feat is not None lyr.SetAttributeFilter('realfield IN (1.0)') lyr.ResetReading() feat = lyr.GetNextFeature() - if feat is None: - gdaltest.post_reason('failed') - return 'fail' + assert feat is not None lyr.SetAttributeFilter('realfield = 1.0') lyr.ResetReading() feat = lyr.GetNextFeature() - if feat is None: - gdaltest.post_reason('failed') - return 'fail' + assert feat is not None lyr.SetAttributeFilter('realfield IN (1.1)') lyr.ResetReading() feat = lyr.GetNextFeature() - if feat is not None: - gdaltest.post_reason('failed') - return 'fail' + assert feat is None lyr.SetAttributeFilter('realfield IN (1)') lyr.ResetReading() feat = lyr.GetNextFeature() - if feat is None: - gdaltest.post_reason('failed') - return 'fail' + assert feat is not None lyr.SetAttributeFilter('realfield = 1') lyr.ResetReading() feat = lyr.GetNextFeature() - if feat is None: - gdaltest.post_reason('failed') - return 'fail' + assert feat is not None lyr.SetAttributeFilter('realfield IN (2)') lyr.ResetReading() feat = lyr.GetNextFeature() - if feat is not None: - gdaltest.post_reason('failed') - return 'fail' + assert feat is None lyr.SetAttributeFilter("realfield IN ('1')") lyr.ResetReading() feat = lyr.GetNextFeature() - if feat is None: - gdaltest.post_reason('failed') - return 'fail' + assert feat is not None lyr.SetAttributeFilter("strfield IN ('foo')") lyr.ResetReading() feat = lyr.GetNextFeature() - if feat is None: - gdaltest.post_reason('failed') - return 'fail' + assert feat is not None lyr.SetAttributeFilter("strfield = 'foo'") lyr.ResetReading() feat = lyr.GetNextFeature() - if feat is None: - gdaltest.post_reason('failed') - return 'fail' + assert feat is not None lyr.SetAttributeFilter("strfield IN ('bar')") lyr.ResetReading() feat = lyr.GetNextFeature() - if feat is not None: - gdaltest.post_reason('failed') - return 'fail' + assert feat is None ds = None - return 'success' - ############################################################################### # Test support for OR and AND expression @@ -433,17 +372,12 @@ def ogr_index_11_check(lyr, expected_fids): lyr.ResetReading() for expected_fid in expected_fids: feat = lyr.GetNextFeature() - if feat is None: - gdaltest.post_reason('failed') - return 'fail' - if feat.GetFID() != expected_fid: - gdaltest.post_reason('failed') - return 'fail' - - return 'success' + assert feat is not None + assert feat.GetFID() == expected_fid + -def ogr_index_11(): +def test_ogr_index_11(): ds = ogr.GetDriverByName('ESRI Shapefile').CreateDataSource('tmp/ogr_index_11.dbf') lyr = ds.CreateLayer('ogr_index_11', geom_type=ogr.wkbNone) @@ -460,38 +394,26 @@ def ogr_index_11(): ds.ExecuteSQL('CREATE INDEX ON ogr_index_11 USING strfield') lyr.SetAttributeFilter("intfield = 1 OR strfield = 'bar'") - ret = ogr_index_11_check(lyr, [0, 1, 3]) - if ret != 'success': - return ret + ogr_index_11_check(lyr, [0, 1, 3]) lyr.SetAttributeFilter("intfield = 1 AND strfield = 'bar'") - ret = ogr_index_11_check(lyr, [1]) - if ret != 'success': - return ret + ogr_index_11_check(lyr, [1]) lyr.SetAttributeFilter("intfield = 1 AND strfield = 'foo'") - ret = ogr_index_11_check(lyr, [0]) - if ret != 'success': - return ret + ogr_index_11_check(lyr, [0]) lyr.SetAttributeFilter("intfield = 3 AND strfield = 'foo'") - ret = ogr_index_11_check(lyr, []) - if ret != 'success': - return ret + ogr_index_11_check(lyr, []) lyr.SetAttributeFilter("intfield IN (1, 2, 3)") - ret = ogr_index_11_check(lyr, [0, 1, 2, 3, 4]) - if ret != 'success': - return ret + ogr_index_11_check(lyr, [0, 1, 2, 3, 4]) ds = None - return 'success' - ############################################################################### -def ogr_index_cleanup(): +def test_ogr_index_cleanup(): try: gdaltest.p_ds.Release() except: @@ -507,39 +429,14 @@ def ogr_index_cleanup(): ogr.GetDriverByName('ESRI Shapefile').DeleteDataSource('join_t.dbf') for filename in ['join_t.idm', 'join_t.ind']: - try: + with pytest.raises(OSError, message="%s should not exist" % filename): os.stat(filename) - gdaltest.post_reason("%s should not exist" % filename) - return 'fail' - except OSError: - pass + ogr.GetDriverByName('ESRI Shapefile').DeleteDataSource( 'tmp/ogr_index_10.shp') ogr.GetDriverByName('ESRI Shapefile').DeleteDataSource( 'tmp/ogr_index_11.dbf') - return 'success' - - -gdaltest_list = [ - ogr_index_1, - ogr_index_2, - ogr_index_3, - ogr_index_4, - ogr_index_5, - ogr_index_6, - ogr_index_7, - ogr_index_8, - ogr_index_9, - ogr_index_10, - ogr_index_11, - ogr_index_cleanup] - -if __name__ == '__main__': - - gdaltest.setup_run('ogr_index_test') - gdaltest.run_tests(gdaltest_list) - sys.exit(gdaltest.summarize()) diff --git a/autotest/ogr/ogr_ingres.py b/autotest/ogr/ogr_ingres.py index c11fee5db32c..d997e19195c5 100755 --- a/autotest/ogr/ogr_ingres.py +++ b/autotest/ogr/ogr_ingres.py @@ -28,40 +28,38 @@ # DEALINGS IN THE SOFTWARE. ############################################################################### -import sys -sys.path.append('../pymod') import gdaltest import ogrtest from osgeo import ogr +import pytest ############################################################################### # Open INGRES test datasource. -def ogr_ingres_1(): +def test_ogr_ingres_1(): gdaltest.ingres_ds = None drv = ogr.GetDriverByName('Ingres') if drv is None: - return 'skip' + pytest.skip() gdaltest.ingres_ds = ogr.Open('@driver=ingres,dbname=test', update=1) if gdaltest.ingres_ds is None: - return 'skip' - - return 'success' + pytest.skip() + ############################################################################### # Create table from data/poly.shp -def ogr_ingres_2(): +def test_ogr_ingres_2(): if gdaltest.ingres_ds is None: - return 'skip' + pytest.skip() ####################################################### # Create Layer @@ -97,15 +95,14 @@ def ogr_ingres_2(): feat = shp_lyr.GetNextFeature() - return 'success' - + ############################################################################### # Verify that stuff we just wrote is still OK. -def ogr_ingres_3(): +def test_ogr_ingres_3(): if gdaltest.ingres_ds is None: - return 'skip' + pytest.skip() expect = [168, 169, 166, 158, 165] @@ -118,14 +115,12 @@ def ogr_ingres_3(): orig_feat = gdaltest.poly_feat[i] read_feat = gdaltest.ingres_lyr.GetNextFeature() - if ogrtest.check_feature_geometry(read_feat, orig_feat.GetGeometryRef(), - max_error=0.000000001) != 0: - return 'fail' + assert (ogrtest.check_feature_geometry(read_feat, orig_feat.GetGeometryRef(), + max_error=0.000000001) == 0) for fld in range(3): - if orig_feat.GetField(fld) != read_feat.GetField(fld): - gdaltest.post_reason('Attribute %d does not match' % fld) - return 'fail' + assert orig_feat.GetField(fld) == read_feat.GetField(fld), \ + ('Attribute %d does not match' % fld) gdaltest.poly_feat = None gdaltest.shp_ds.Destroy() @@ -134,16 +129,16 @@ def ogr_ingres_3(): # automating this in the driver. read_feat = gdaltest.ingres_lyr.GetNextFeature() - return 'success' if tr else 'fail' + assert tr ############################################################################### # Test ExecuteSQL() results layers without geometry. -def ogr_ingres_4(): +def test_ogr_ingres_4(): if gdaltest.ingres_ds is None: - return 'skip' + pytest.skip() expect = [179, 173, 172, 171, 170, 169, 168, 166, 165, 158] @@ -153,7 +148,7 @@ def ogr_ingres_4(): gdaltest.ingres_ds.ReleaseResultSet(sql_lyr) - return 'success' if tr else 'fail' + assert tr ############################################################################### # Test ExecuteSQL() results layers with geometry. @@ -163,12 +158,12 @@ def ogr_ingres_4(): # so we disable this test. -def ogr_ingres_5(): +def test_ogr_ingres_5(): if gdaltest.ingres_ds is None: - return 'skip' + pytest.skip() - return 'skip' + pytest.skip() # pylint: disable=unreachable sql_lyr = gdaltest.ingres_ds.ExecuteSQL( @@ -185,16 +180,16 @@ def ogr_ingres_5(): gdaltest.ingres_ds.ReleaseResultSet(sql_lyr) - return 'success' if tr else 'fail' + assert tr ############################################################################### # Test spatial filtering. -def ogr_ingres_6(): +def test_ogr_ingres_6(): if gdaltest.ingres_ds is None: - return 'skip' + pytest.skip() gdaltest.ingres_lyr.SetAttributeFilter(None) @@ -208,16 +203,16 @@ def ogr_ingres_6(): gdaltest.ingres_lyr.SetSpatialFilter(None) - return 'success' if tr else 'fail' + assert tr ############################################################################### # Test adding a new field. -def ogr_ingres_7(): +def test_ogr_ingres_7(): if gdaltest.ingres_ds is None: - return 'skip' + pytest.skip() #################################################################### # Add new string field. @@ -225,18 +220,14 @@ def ogr_ingres_7(): result = gdaltest.ingres_lyr.CreateField(field_defn) field_defn.Destroy() - if result is not 0: - gdaltest.post_reason('CreateField failed!') - return 'fail' + assert result is 0, 'CreateField failed!' #################################################################### # Apply a value to this field in one feature. gdaltest.ingres_lyr.SetAttributeFilter("prfedea = '35043423'") feat_read = gdaltest.ingres_lyr.GetNextFeature() - if feat_read is None: - gdaltest.post_reason('failed to read target feature!') - return 'fail' + assert feat_read is not None, 'failed to read target feature!' gdaltest.ingres_fid = feat_read.GetFID() @@ -255,20 +246,19 @@ def ogr_ingres_7(): gdaltest.ingres_lyr.SetAttributeFilter(None) - return 'success' if tr else 'fail' + assert tr ############################################################################### # Test deleting a feature. -def ogr_ingres_8(): +def test_ogr_ingres_8(): if gdaltest.ingres_ds is None: - return 'skip' + pytest.skip() - if not gdaltest.ingres_lyr.TestCapability('DeleteFeature'): - gdaltest.post_reason('DeleteFeature capability test failed.') - return 'fail' + assert gdaltest.ingres_lyr.TestCapability('DeleteFeature'), \ + 'DeleteFeature capability test failed.' old_count = gdaltest.ingres_lyr.GetFeatureCount() @@ -276,9 +266,8 @@ def ogr_ingres_8(): # Delete target feature. target_fid = gdaltest.ingres_fid - if gdaltest.ingres_lyr.DeleteFeature(target_fid) != 0: - gdaltest.post_reason('DeleteFeature returned error code.') - return 'fail' + assert gdaltest.ingres_lyr.DeleteFeature(target_fid) == 0, \ + 'DeleteFeature returned error code.' #################################################################### # Verify that count has dropped by one, and that the feature in question @@ -288,42 +277,19 @@ def ogr_ingres_8(): gdaltest.post_reason('got feature count of %d, not expected %d.' % (new_count, old_count - 1)) - if gdaltest.ingres_lyr.GetFeature(target_fid) is not None: - gdaltest.post_reason('Got deleted feature!') - return 'fail' - - return 'success' + assert gdaltest.ingres_lyr.GetFeature(target_fid) is None, 'Got deleted feature!' ############################################################################### # -def ogr_ingres_cleanup(): +def test_ogr_ingres_cleanup(): if gdaltest.ingres_ds is None: - return 'skip' + pytest.skip() gdaltest.ingres_ds.Destroy() gdaltest.ingres_ds = None - return 'success' - - -gdaltest_list = [ - ogr_ingres_1, - ogr_ingres_2, - ogr_ingres_3, - ogr_ingres_4, - ogr_ingres_5, - ogr_ingres_6, - ogr_ingres_7, - ogr_ingres_8, - ogr_ingres_cleanup] - -if __name__ == '__main__': - - gdaltest.setup_run('ogr_ingres') - gdaltest.run_tests(gdaltest_list) - sys.exit(gdaltest.summarize()) diff --git a/autotest/ogr/ogr_jml.py b/autotest/ogr/ogr_jml.py index 0abab1c5de10..7745b6f0b392 100755 --- a/autotest/ogr/ogr_jml.py +++ b/autotest/ogr/ogr_jml.py @@ -29,17 +29,16 @@ # DEALINGS IN THE SOFTWARE. ############################################################################### -import sys -sys.path.append('../pymod') import gdaltest from osgeo import ogr from osgeo import osr from osgeo import gdal +import pytest -def ogr_jml_init(): +def test_ogr_jml_init(): ds = ogr.Open('data/test.jml') @@ -49,30 +48,21 @@ def ogr_jml_init(): gdaltest.jml_read_support = 1 ds = None - return 'success' - + ############################################################################### # Test reading -def ogr_jml_1(): +def test_ogr_jml_1(): if not gdaltest.jml_read_support: - return 'skip' + pytest.skip() ds = ogr.Open('data/test.jml') - if ds.GetLayerCount() != 1: - gdaltest.post_reason('fail') - return 'fail' - if ds.GetLayer(1) is not None: - gdaltest.post_reason('fail') - return 'fail' - if ds.TestCapability(ogr.ODsCCreateLayer) != 0: - gdaltest.post_reason('fail') - return 'fail' - if ds.TestCapability(ogr.ODsCDeleteLayer) != 0: - gdaltest.post_reason('fail') - return 'fail' + assert ds.GetLayerCount() == 1 + assert ds.GetLayer(1) is None + assert ds.TestCapability(ogr.ODsCCreateLayer) == 0 + assert ds.TestCapability(ogr.ODsCDeleteLayer) == 0 lyr = ds.GetLayer(0) fields = [('first_property', ogr.OFTString), ('another_property', ogr.OFTString), @@ -85,15 +75,10 @@ def ogr_jml_1(): ('datetime', ogr.OFTDateTime), ('R_G_B', ogr.OFTString), ('not_ignored', ogr.OFTString)] - if lyr.GetLayerDefn().GetFieldCount() != len(fields): - gdaltest.post_reason('fail') - return 'fail' + assert lyr.GetLayerDefn().GetFieldCount() == len(fields) for i, field in enumerate(fields): field_defn = lyr.GetLayerDefn().GetFieldDefn(i) - if field_defn.GetName() != field[0] or field_defn.GetType() != field[1]: - print(i) - gdaltest.post_reason('fail') - return 'fail' + assert field_defn.GetName() == field[0] and field_defn.GetType() == field[1], i feat = lyr.GetNextFeature() if feat.GetField('first_property') != 'even' or \ feat.GetField('another_property') != 'rouault' or \ @@ -109,8 +94,7 @@ def ogr_jml_1(): feat.GetStyleString() != 'BRUSH(fc:#0000FF)' or \ feat.GetGeometryRef().ExportToWkt() != 'POLYGON ((0 0,0 10,10 10,10 0,0 0))': feat.DumpReadable() - gdaltest.post_reason('fail') - return 'fail' + pytest.fail() feat = lyr.GetNextFeature() if feat.GetFieldAsString('datetime') != '2014/10/18 21:36:45+02' or \ @@ -118,22 +102,19 @@ def ogr_jml_1(): feat.GetStyleString() != 'PEN(c:#FF00FF)' or \ feat.GetGeometryRef().ExportToWkt() != 'POINT (-1 -1)': feat.DumpReadable() - gdaltest.post_reason('fail') - return 'fail' + pytest.fail() feat = lyr.GetNextFeature() if feat.GetGeometryRef() is not None: feat.DumpReadable() - gdaltest.post_reason('fail') - return 'fail' - - return 'success' + pytest.fail() + ############################################################################### # Test creating a file -def ogr_jml_2(): +def test_ogr_jml_2(): # Invalid filename gdal.PushErrorHandler('CPLQuietErrorHandler') @@ -152,7 +133,7 @@ def ogr_jml_2(): data = gdal.VSIFReadL(1, 1000, f).decode('ascii') gdal.VSIFCloseL(f) - if data != """<?xml version='1.0' encoding='UTF-8'?> + assert data == """<?xml version='1.0' encoding='UTF-8'?> <JCSDataFile xmlns:gml="http://www.opengis.net/gml" xmlns:xsi="http://www.w3.org/2000/10/XMLSchema-instance" > <JCSGMLInputTemplate> <CollectionElement>featureCollection</CollectionElement> @@ -170,10 +151,7 @@ def ogr_jml_2(): </gml:boundedBy> </featureCollection> </JCSDataFile> -""": - gdaltest.post_reason('fail') - print(data) - return 'fail' +""" gdal.Unlink('/vsimem/ogr_jml.jml') @@ -192,29 +170,17 @@ def ogr_jml_2(): with gdaltest.error_handler(): lyr.CreateField(ogr.FieldDefn('time_as_str', ogr.OFTTime)) - if lyr.TestCapability(ogr.OLCCreateField) != 1: - gdaltest.post_reason('fail') - return 'fail' - if lyr.TestCapability(ogr.OLCSequentialWrite) != 1: - gdaltest.post_reason('fail') - return 'fail' - if lyr.TestCapability(ogr.OLCRandomWrite) != 0: - gdaltest.post_reason('fail') - return 'fail' - if lyr.TestCapability(ogr.OLCStringsAsUTF8) != 1: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.TestCapability(ogr.OLCCreateField) == 1 + assert lyr.TestCapability(ogr.OLCSequentialWrite) == 1 + assert lyr.TestCapability(ogr.OLCRandomWrite) == 0 + assert lyr.TestCapability(ogr.OLCStringsAsUTF8) == 1 # empty feature f = ogr.Feature(lyr.GetLayerDefn()) lyr.CreateFeature(f) - if lyr.TestCapability(ogr.OLCCreateField) != 0: - gdaltest.post_reason('fail') - return 'fail' - if lyr.CreateField(ogr.FieldDefn('that_wont_work')) == 0: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.TestCapability(ogr.OLCCreateField) == 0 + assert lyr.CreateField(ogr.FieldDefn('that_wont_work')) != 0 f = ogr.Feature(lyr.GetLayerDefn()) f.SetField('str', 'fo<o') @@ -239,7 +205,7 @@ def ogr_jml_2(): data = gdal.VSIFReadL(1, 10000, f).decode('ascii') gdal.VSIFCloseL(f) - if data != """<?xml version='1.0' encoding='UTF-8'?> + assert data == """<?xml version='1.0' encoding='UTF-8'?> <JCSDataFile xmlns:gml="http://www.opengis.net/gml" xmlns:xsi="http://www.w3.org/2000/10/XMLSchema-instance" > <JCSGMLInputTemplate> <CollectionElement>featureCollection</CollectionElement> @@ -344,10 +310,7 @@ def ogr_jml_2(): </feature> </featureCollection> </JCSDataFile> -""": - gdaltest.post_reason('fail') - print(data) - return 'fail' +""" gdal.Unlink('/vsimem/ogr_jml.jml') @@ -372,10 +335,7 @@ def ogr_jml_2(): data = gdal.VSIFReadL(1, 10000, f).decode('ascii') gdal.VSIFCloseL(f) - if data.find('112233') < 0 or data.find('445566') < 0: - gdaltest.post_reason('fail') - print(data) - return 'fail' + assert data.find('112233') >= 0 and data.find('445566') >= 0 gdal.Unlink('/vsimem/ogr_jml.jml') @@ -391,10 +351,7 @@ def ogr_jml_2(): data = gdal.VSIFReadL(1, 10000, f).decode('ascii') gdal.VSIFCloseL(f) - if data.find('R_G_B') >= 0: - gdaltest.post_reason('fail') - print(data) - return 'fail' + assert data.find('R_G_B') < 0 gdal.Unlink('/vsimem/ogr_jml.jml') @@ -411,10 +368,7 @@ def ogr_jml_2(): data = gdal.VSIFReadL(1, 10000, f).decode('ascii') gdal.VSIFCloseL(f) - if data.find('OGR_STYLE') < 0 or data.find('PEN(c:#445566)') < 0: - gdaltest.post_reason('fail') - print(data) - return 'fail' + assert data.find('OGR_STYLE') >= 0 and data.find('PEN(c:#445566)') >= 0 gdal.Unlink('/vsimem/ogr_jml.jml') @@ -433,44 +387,35 @@ def ogr_jml_2(): data = gdal.VSIFReadL(1, 10000, f).decode('ascii') gdal.VSIFCloseL(f) - if data.find('OGR_STYLE') < 0 or data.find('PEN(c:#445566)') < 0 or data.find('112233') < 0: - gdaltest.post_reason('fail') - print(data) - return 'fail' + assert data.find('OGR_STYLE') >= 0 and data.find('PEN(c:#445566)') >= 0 and data.find('112233') >= 0 gdal.Unlink('/vsimem/ogr_jml.jml') - return 'success' - ############################################################################### # Run test_ogrsf -def ogr_jml_3(): +def test_ogr_jml_3(): if not gdaltest.jml_read_support: - return 'skip' + pytest.skip() import test_cli_utilities if test_cli_utilities.get_test_ogrsf_path() is None: - return 'skip' + pytest.skip() ret = gdaltest.runexternal(test_cli_utilities.get_test_ogrsf_path() + ' -ro data/test.jml') - if ret.find('INFO') == -1 or ret.find('ERROR') != -1: - print(ret) - return 'fail' - - return 'success' + assert ret.find('INFO') != -1 and ret.find('ERROR') == -1 ############################################################################### # Test a few error cases -def ogr_jml_4(): +def test_ogr_jml_4(): if not gdaltest.jml_read_support: - return 'skip' + pytest.skip() # Missing CollectionElement, FeatureElement or GeometryElement gdal.FileFromMemBuffer('/vsimem/ogr_jml.jml', """<?xml version='1.0' encoding='UTF-8'?> @@ -491,9 +436,7 @@ def ogr_jml_4(): gdal.PushErrorHandler('CPLQuietErrorHandler') lyr.GetLayerDefn() gdal.PopErrorHandler() - if gdal.GetLastErrorType() == 0: - gdaltest.post_reason('fail') - return 'fail' + assert gdal.GetLastErrorType() != 0 ds = None # XML malformed in JCSGMLInputTemplate @@ -515,9 +458,7 @@ def ogr_jml_4(): gdal.PushErrorHandler('CPLQuietErrorHandler') lyr.GetLayerDefn() gdal.PopErrorHandler() - if gdal.GetLastErrorType() == 0: - gdaltest.post_reason('fail') - return 'fail' + assert gdal.GetLastErrorType() != 0 ds = None # XML malformed in featureCollection @@ -545,9 +486,7 @@ def ogr_jml_4(): gdal.PushErrorHandler('CPLQuietErrorHandler') lyr.GetLayerDefn().GetFieldCount() gdal.PopErrorHandler() - if gdal.GetLastErrorType() == 0: - gdaltest.post_reason('fail') - return 'fail' + assert gdal.GetLastErrorType() != 0 ds = None # XML malformed in featureCollection @@ -576,9 +515,7 @@ def ogr_jml_4(): gdal.PushErrorHandler('CPLQuietErrorHandler') lyr.GetLayerDefn().GetFieldCount() gdal.PopErrorHandler() - if gdal.GetLastErrorType() == 0: - gdaltest.post_reason('fail') - return 'fail' + assert gdal.GetLastErrorType() != 0 del ds # Invalid column definitions @@ -646,59 +583,32 @@ def ogr_jml_4(): ds = ogr.Open('/vsimem/ogr_jml.jml') lyr = ds.GetLayer(0) - if lyr.GetLayerDefn().GetFieldCount() != 0: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.GetLayerDefn().GetFieldCount() == 0 lyr.GetNextFeature() ds = None - return 'success' - ############################################################################### # Test reading SRS -def ogr_jml_read_srs(): +def test_ogr_jml_read_srs(): if not gdaltest.jml_read_support: - return 'skip' + pytest.skip() ds = ogr.Open('data/one_point_srid_4326.jml') lyr = ds.GetLayer(0) - if lyr.GetSpatialRef().ExportToWkt().find('4326') < 0: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.GetSpatialRef().ExportToWkt().find('4326') >= 0 f = lyr.GetNextFeature() - if f.GetGeometryRef() is None: - gdaltest.post_reason('fail') - return 'fail' - - return 'success' + assert f.GetGeometryRef() is not None ############################################################################### # -def ogr_jml_cleanup(): +def test_ogr_jml_cleanup(): gdal.Unlink('/vsimem/ogr_jml.jml') - return 'success' - - -gdaltest_list = [ - ogr_jml_init, - ogr_jml_1, - ogr_jml_2, - ogr_jml_3, - ogr_jml_4, - ogr_jml_read_srs, - ogr_jml_cleanup] - -if __name__ == '__main__': - - gdaltest.setup_run('ogr_jml') - gdaltest.run_tests(gdaltest_list) - sys.exit(gdaltest.summarize()) diff --git a/autotest/ogr/ogr_join_test.py b/autotest/ogr/ogr_join_test.py index 6cd6afaee548..dee0031407c7 100755 --- a/autotest/ogr/ogr_join_test.py +++ b/autotest/ogr/ogr_join_test.py @@ -27,39 +27,35 @@ # Boston, MA 02111-1307, USA. ############################################################################### -import sys -sys.path.append('../pymod') import gdaltest from osgeo import gdal from osgeo import ogr import ogrtest +import pytest ############################################################################### # Test a join. -def ogr_join_1(): +def test_ogr_join_1(): gdaltest.ds = ogr.Open('data') sql_lyr = gdaltest.ds.ExecuteSQL( 'SELECT * FROM poly LEFT JOIN idlink ON poly.eas_id = idlink.eas_id') count = sql_lyr.GetFeatureCount() - if count != 10: - gdaltest.post_reason('Got wrong count with GetFeatureCount() - %d, expecting 10' % count) - return 'fail' + assert count == 10, \ + ('Got wrong count with GetFeatureCount() - %d, expecting 10' % count) gdaltest.ds.ReleaseResultSet(sql_lyr) - return 'success' - ############################################################################### # Check the values we are actually getting back (restricting the search a bit) -def ogr_join_2(): +def test_ogr_join_2(): expect = ['_166_', '_158_', '_165_'] @@ -72,13 +68,13 @@ def ogr_join_2(): gdaltest.ds.ReleaseResultSet(sql_lyr) - return 'success' if tr else 'fail' + assert tr ############################################################################### # Try various naming conversions for the selected fields. -def ogr_join_3(): +def test_ogr_join_3(): expect = ['_166_', '_158_', '_165_'] @@ -91,13 +87,13 @@ def ogr_join_3(): gdaltest.ds.ReleaseResultSet(sql_lyr) - return 'success' if tr else 'fail' + assert tr ############################################################################### # Verify that records for which a join can't be found work ok. -def ogr_join_4(): +def test_ogr_join_4(): expect = ['_179_', '_171_', None, None] @@ -110,13 +106,13 @@ def ogr_join_4(): gdaltest.ds.ReleaseResultSet(sql_lyr) - return 'success' if tr else 'fail' + assert tr ############################################################################### # Verify that table aliases work -def ogr_join_5(): +def test_ogr_join_5(): expect = [179, 171, 173, 172] @@ -129,13 +125,13 @@ def ogr_join_5(): gdaltest.ds.ReleaseResultSet(sql_lyr) - return 'success' if tr else 'fail' + assert tr ############################################################################### # Again, ordering by a primary field. -def ogr_join_6(): +def test_ogr_join_6(): expect = [171, 172, 173, 179] @@ -148,13 +144,13 @@ def ogr_join_6(): gdaltest.ds.ReleaseResultSet(sql_lyr) - return 'success' if tr else 'fail' + assert tr ############################################################################### # Test joining to an external datasource. -def ogr_join_7(): +def test_ogr_join_7(): expect = [171, 172, 173, 179] @@ -167,13 +163,13 @@ def ogr_join_7(): gdaltest.ds.ReleaseResultSet(sql_lyr) - return 'success' if tr else 'fail' + assert tr ############################################################################### # Test doing two joins at once. -def ogr_join_8(): +def test_ogr_join_8(): expect = [171, None, None, 179] @@ -187,14 +183,14 @@ def ogr_join_8(): gdaltest.ds.ReleaseResultSet(sql_lyr) - return 'success' if tr else 'fail' + assert tr ############################################################################### # Verify fix for #2788 (memory corruption on wildcard expansion in SQL request # with join clauses) -def ogr_join_9(): +def test_ogr_join_9(): expect = [179, 171, 173, 172] @@ -207,12 +203,12 @@ def ogr_join_9(): gdaltest.ds.ReleaseResultSet(sql_lyr) - return 'success' if tr else 'fail' + assert tr ############################################################################### -def ogr_join_10(): +def test_ogr_join_10(): expect = [None, None, None, None, None, None, None, None, None, None] @@ -224,13 +220,13 @@ def ogr_join_10(): gdaltest.ds.ReleaseResultSet(sql_lyr) - return 'success' if tr else 'fail' + assert tr ############################################################################### # Test join on string field -def ogr_join_11(): +def test_ogr_join_11(): expect = ['_168_', '_179_', '_171_', '_170_', '_165_', '_158_', '_166_'] @@ -241,32 +237,29 @@ def ogr_join_11(): gdaltest.ds.ReleaseResultSet(sql_lyr) - return 'success' if tr else 'fail' + assert tr ############################################################################### # Test fix for #4112 (join between 2 datasources) -def ogr_join_12(): +def test_ogr_join_12(): ds = ogr.Open('data/poly.shp') sql_lyr = ds.ExecuteSQL( "SELECT * FROM poly LEFT JOIN 'data/idlink.dbf'.idlink ON poly.eas_id = idlink.eas_id") count = sql_lyr.GetFeatureCount() - if count != 10: - gdaltest.post_reason('Got wrong count with GetFeatureCount() - %d, expecting 10' % count) - return 'fail' + assert count == 10, \ + ('Got wrong count with GetFeatureCount() - %d, expecting 10' % count) ds.ReleaseResultSet(sql_lyr) - return 'success' - ############################################################################### # Test joining a float column with a string column (#4321) -def ogr_join_13(): +def test_ogr_join_13(): expect = ['_168_', '_179_', '_171_', None, None, None, '_166_', '_158_', '_165_', '_170_'] @@ -278,13 +271,13 @@ def ogr_join_13(): gdaltest.ds.ReleaseResultSet(sql_lyr) - return 'success' if tr else 'fail' + assert tr ############################################################################### # Test joining a string column with a float column (#4321, actually addressed by #4259) -def ogr_join_14(): +def test_ogr_join_14(): expect = [168, 179, 171, 170, 165, 158, 166] @@ -296,13 +289,13 @@ def ogr_join_14(): gdaltest.ds.ReleaseResultSet(sql_lyr) - return 'success' if tr else 'fail' + assert tr ############################################################################### # Test multiple joins with expressions (#4521) -def ogr_join_15(): +def test_ogr_join_15(): ds = ogr.GetDriverByName('CSV').CreateDataSource('/vsimem/ogr_join_14') lyr = ds.CreateLayer('first') @@ -330,23 +323,15 @@ def ogr_join_15(): gdal.Unlink('/vsimem/ogr_join_14/third.csv') gdal.Unlink('/vsimem/ogr_join_14') - if val1 != 'c2': - gdaltest.post_reason('fail') - print(val1) - return 'fail' + assert val1 == 'c2' - if val2 != 'c2': - gdaltest.post_reason('fail') - print(val2) - return 'fail' - - return 'success' + assert val2 == 'c2' ############################################################################### # Test non-support of a secondarytable.fieldname in a where clause -def ogr_join_16(): +def test_ogr_join_16(): gdal.ErrorReset() gdal.PushErrorHandler('CPLQuietErrorHandler') @@ -356,18 +341,17 @@ def ogr_join_16(): 'WHERE idlink.name = \'_165\'') gdal.PopErrorHandler() - if gdal.GetLastErrorMsg().find('Cannot use field') != 0: - return 'fail' + assert gdal.GetLastErrorMsg().find('Cannot use field') == 0 if sql_lyr is None: - return 'success' - return 'fail' + return + pytest.fail() ############################################################################### # Test non-support of a secondarytable.fieldname in a order by clause -def ogr_join_17(): +def test_ogr_join_17(): gdal.ErrorReset() gdal.PushErrorHandler('CPLQuietErrorHandler') @@ -377,37 +361,32 @@ def ogr_join_17(): 'ORDER BY name') gdal.PopErrorHandler() - if gdal.GetLastErrorMsg().find('Cannot use field') != 0: - print(gdal.GetLastErrorMsg()) - return 'fail' + assert gdal.GetLastErrorMsg().find('Cannot use field') == 0 if sql_lyr is None: - return 'success' - return 'fail' + return + pytest.fail() ############################################################################### # Test inverted order of fields in ON -def ogr_join_18(): +def test_ogr_join_18(): sql_lyr = gdaltest.ds.ExecuteSQL( 'SELECT * FROM poly LEFT JOIN idlink ON idlink.eas_id = poly.eas_id') count = sql_lyr.GetFeatureCount() - if count != 10: - gdaltest.post_reason('Got wrong count with GetFeatureCount() - %d, expecting 10' % count) - return 'fail' + assert count == 10, \ + ('Got wrong count with GetFeatureCount() - %d, expecting 10' % count) gdaltest.ds.ReleaseResultSet(sql_lyr) - return 'success' - ############################################################################### # Test unrecognized primary field -def ogr_join_19(): +def test_ogr_join_19(): gdal.ErrorReset() gdal.PushErrorHandler('CPLQuietErrorHandler') @@ -415,19 +394,17 @@ def ogr_join_19(): 'SELECT * FROM poly LEFT JOIN idlink ON poly.foo = idlink.eas_id') gdal.PopErrorHandler() - if gdal.GetLastErrorMsg().find('"poly"."foo" not recognised as an available field') != 0: - print(gdal.GetLastErrorMsg()) - return 'fail' + assert gdal.GetLastErrorMsg().find('"poly"."foo" not recognised as an available field') == 0 if sql_lyr is None: - return 'success' - return 'fail' + return + pytest.fail() ############################################################################### # Test unrecognized secondary field -def ogr_join_20(): +def test_ogr_join_20(): gdal.ErrorReset() gdal.PushErrorHandler('CPLQuietErrorHandler') @@ -435,19 +412,17 @@ def ogr_join_20(): 'SELECT * FROM poly LEFT JOIN idlink ON poly.eas_id = idlink.foo') gdal.PopErrorHandler() - if gdal.GetLastErrorMsg().find('"idlink"."foo" not recognised as an available field') != 0: - print(gdal.GetLastErrorMsg()) - return 'fail' + assert gdal.GetLastErrorMsg().find('"idlink"."foo" not recognised as an available field') == 0 if sql_lyr is None: - return 'success' - return 'fail' + return + pytest.fail() ############################################################################### # Test unexpected secondary table -def ogr_join_21(): +def test_ogr_join_21(): gdal.ErrorReset() gdal.PushErrorHandler('CPLQuietErrorHandler') @@ -457,19 +432,17 @@ def ogr_join_21(): 'LEFT JOIN idlink il2 ON p.eas_id = il2.eas_id') gdal.PopErrorHandler() - if gdal.GetLastErrorMsg().find('Field il2.eas_id in JOIN clause does not correspond to the primary table nor the joint (secondary) table') != 0: - print(gdal.GetLastErrorMsg()) - return 'fail' + assert gdal.GetLastErrorMsg().find('Field il2.eas_id in JOIN clause does not correspond to the primary table nor the joint (secondary) table') == 0 if sql_lyr is None: - return 'success' - return 'fail' + return + pytest.fail() ############################################################################### # Test join with a complex expression as ON -def ogr_join_22(): +def test_ogr_join_22(): ds = ogr.GetDriverByName('Memory').CreateDataSource('') lyr = ds.CreateLayer('first') @@ -489,18 +462,13 @@ def ogr_join_22(): ds = None - if val != '2': - gdaltest.post_reason('fail') - print(val) - return 'fail' - - return 'success' + assert val == '2' ############################################################################### # Test join with NULL keys -def ogr_join_23(): +def test_ogr_join_23(): ds = ogr.GetDriverByName('Memory').CreateDataSource('') lyr = ds.CreateLayer('first') @@ -516,60 +484,22 @@ def ogr_join_23(): sql_lyr = ds.ExecuteSQL("SELECT * FROM first JOIN second ON first.f = second.f") feat = sql_lyr.GetNextFeature() if feat.IsFieldSetAndNotNull('second.f'): - gdaltest.post_reason('fail') feat.DumpReadable() - return 'fail' + pytest.fail() feat = sql_lyr.GetNextFeature() if feat['f'] != 'key1' or feat['second.f'] != 'key1': - gdaltest.post_reason('fail') feat.DumpReadable() - return 'fail' + pytest.fail() ds.ReleaseResultSet(sql_lyr) ds = None - return 'success' - ############################################################################### -def ogr_join_cleanup(): +def test_ogr_join_cleanup(): gdaltest.lyr = None gdaltest.ds = None - return 'success' - - -gdaltest_list = [ - ogr_join_1, - ogr_join_2, - ogr_join_3, - ogr_join_4, - ogr_join_5, - ogr_join_6, - ogr_join_7, - ogr_join_8, - ogr_join_9, - ogr_join_10, - ogr_join_11, - ogr_join_12, - ogr_join_13, - ogr_join_14, - ogr_join_15, - ogr_join_16, - ogr_join_17, - ogr_join_18, - ogr_join_19, - ogr_join_20, - ogr_join_21, - ogr_join_22, - ogr_join_23, - ogr_join_cleanup] - -if __name__ == '__main__': - - gdaltest.setup_run('ogr_join_test') - - gdaltest.run_tests(gdaltest_list) - - sys.exit(gdaltest.summarize()) + + diff --git a/autotest/ogr/ogr_kml.py b/autotest/ogr/ogr_kml.py index ca3f859bcbab..b686280c2e27 100755 --- a/autotest/ogr/ogr_kml.py +++ b/autotest/ogr/ogr_kml.py @@ -31,22 +31,21 @@ ############################################################################### import os -import sys -sys.path.append('../pymod') import gdaltest import ogrtest from osgeo import ogr from osgeo import osr from osgeo import gdal +import pytest ############################################################################### # Test basic open operation for KML datastore. # -def ogr_kml_datastore(): +def test_ogr_kml_datastore(): ogrtest.kml_ds = None ogrtest.have_read_kml = 0 @@ -55,7 +54,7 @@ def ogr_kml_datastore(): ogrtest.kml_drv = ogr.GetDriverByName('KML') if ogrtest.kml_drv is None: - return 'skip' + pytest.skip() ogrtest.libkml_drv = ogr.GetDriverByName('LIBKML') # Unregister LIBKML driver if present as it's behaviour is not identical @@ -69,160 +68,114 @@ def ogr_kml_datastore(): ogrtest.have_read_kml = 1 if not ogrtest.have_read_kml: - return 'skip' + pytest.skip() - if ogrtest.kml_ds.GetLayerCount() != 6: - gdaltest.post_reason('wrong number of layers') - return 'fail' - - return 'success' + assert ogrtest.kml_ds.GetLayerCount() == 6, 'wrong number of layers' ############################################################################### # Test reading attributes for first layer (point). # -def ogr_kml_attributes_1(): +def test_ogr_kml_attributes_1(): if not ogrtest.have_read_kml: - return 'skip' + pytest.skip() - if ogrtest.kml_ds is None: - gdaltest.post_reason('kml_ds is none') - return 'fail' + assert ogrtest.kml_ds is not None, 'kml_ds is none' lyr = ogrtest.kml_ds.GetLayerByName('Placemarks') feat = lyr.GetNextFeature() - if feat.GetField('Name') != 'Simple placemark': - gdaltest.post_reason('Wrong name field value') - return 'fail' + assert feat.GetField('Name') == 'Simple placemark', 'Wrong name field value' if feat.GetField('description')[:23] != 'Attached to the ground.': - gdaltest.post_reason('Wrong description field value') print('got: ', feat.GetField('description')[:23]) - return 'fail' + pytest.fail('Wrong description field value') feat = lyr.GetNextFeature() - if feat is None: - gdaltest.post_reason('expected feature not found.') - return 'fail' + assert feat is not None, 'expected feature not found.' - if feat.GetField('Name') != 'Floating placemark': - gdaltest.post_reason('Wrong name field value') - return 'fail' + assert feat.GetField('Name') == 'Floating placemark', 'Wrong name field value' if feat.GetField('description')[:25] != 'Floats a defined distance': - gdaltest.post_reason('Wrong description field value') print('got: ', feat.GetField('description')[:25]) - return 'fail' + pytest.fail('Wrong description field value') feat = lyr.GetNextFeature() - if feat is None: - gdaltest.post_reason('expected feature not found.') - return 'fail' + assert feat is not None, 'expected feature not found.' - if feat.GetField('Name') != 'Extruded placemark': - gdaltest.post_reason('Wrong name field value') - return 'fail' + assert feat.GetField('Name') == 'Extruded placemark', 'Wrong name field value' if feat.GetField('description') != 'Tethered to the ground by a customizable \"tail\"': - gdaltest.post_reason('Wrong description field value') print('got: ', feat.GetField('description')) - return 'fail' - - return 'success' + pytest.fail('Wrong description field value') + ############################################################################### # Test reading attributes for another layer (point). # -def ogr_kml_attributes_2(): +def test_ogr_kml_attributes_2(): if not ogrtest.have_read_kml: - return 'skip' + pytest.skip() - if ogrtest.kml_ds is None: - gdaltest.post_reason('kml_ds is none') - return 'fail' + assert ogrtest.kml_ds is not None, 'kml_ds is none' lyr = ogrtest.kml_ds.GetLayerByName('Highlighted Icon') feat = lyr.GetNextFeature() - if feat.GetField('Name') != 'Roll over this icon': - gdaltest.post_reason('Wrong name field value') - return 'fail' + assert feat.GetField('Name') == 'Roll over this icon', 'Wrong name field value' - if feat.GetField('description') != '': - gdaltest.post_reason('Wrong description field value') - return 'fail' + assert feat.GetField('description') == '', 'Wrong description field value' feat = lyr.GetNextFeature() - if feat is not None: - gdaltest.post_reason('unexpected feature found.') - return 'fail' - - return 'success' + assert feat is None, 'unexpected feature found.' ############################################################################### # Test reading attributes for another layer (linestring). # -def ogr_kml_attributes_3(): +def test_ogr_kml_attributes_3(): if not ogrtest.have_read_kml: - return 'skip' + pytest.skip() - if ogrtest.kml_ds is None: - gdaltest.post_reason('kml_ds is none') - return 'fail' + assert ogrtest.kml_ds is not None, 'kml_ds is none' lyr = ogrtest.kml_ds.GetLayerByName('Paths') feat = lyr.GetNextFeature() - if feat.GetField('Name') != 'Tessellated': - gdaltest.post_reason('Wrong name field value') - return 'fail' + assert feat.GetField('Name') == 'Tessellated', 'Wrong name field value' - if feat.GetField('description') != 'If the <tessellate> tag has a value of 1, the line will contour to the underlying terrain': - gdaltest.post_reason('Wrong description field value') - return 'fail' + assert feat.GetField('description') == 'If the <tessellate> tag has a value of 1, the line will contour to the underlying terrain', \ + 'Wrong description field value' feat = lyr.GetNextFeature() - if feat is None: - gdaltest.post_reason('expected feature not found.') - return 'fail' + assert feat is not None, 'expected feature not found.' - if feat.GetField('Name') != 'Untessellated': - gdaltest.post_reason('Wrong name field value') - return 'fail' + assert feat.GetField('Name') == 'Untessellated', 'Wrong name field value' - if feat.GetField('description') != 'If the <tessellate> tag has a value of 0, the line follow a simple straight-line path from point to point': - gdaltest.post_reason('Wrong description field value') - return 'fail' + assert feat.GetField('description') == 'If the <tessellate> tag has a value of 0, the line follow a simple straight-line path from point to point', \ + 'Wrong description field value' feat = lyr.GetNextFeature() - if feat is None: - gdaltest.post_reason('expected feature not found.') - return 'fail' - - return 'success' + assert feat is not None, 'expected feature not found.' ############################################################################### # Test reading attributes for another layer (polygon). # -def ogr_kml_attributes_4(): +def test_ogr_kml_attributes_4(): if not ogrtest.have_read_kml: - return 'skip' + pytest.skip() - if ogrtest.kml_ds is None: - gdaltest.post_reason('kml_ds is none') - return 'fail' + assert ogrtest.kml_ds is not None, 'kml_ds is none' lyr = ogrtest.kml_ds.GetLayerByName('Google Campus') feat = lyr.GetNextFeature() @@ -231,32 +184,26 @@ def ogr_kml_attributes_4(): while feat is not None: name = 'Building %d' % i if feat.GetField('Name') != name: - gdaltest.post_reason('Wrong name field value') print('Got: "%s"' % feat.GetField('name')) - return 'fail' + pytest.fail('Wrong name field value') - if feat.GetField('description') != '': - gdaltest.post_reason('Wrong description field value') - return 'fail' + assert feat.GetField('description') == '', 'Wrong description field value' i = i + 1 feat = lyr.GetNextFeature() - return 'success' - + ############################################################################### # Test reading of KML point geometry # -def ogr_kml_point_read(): +def test_ogr_kml_point_read(): if not ogrtest.have_read_kml: - return 'skip' + pytest.skip() - if ogrtest.kml_ds is None: - gdaltest.post_reason('kml_ds is none') - return 'fail' + assert ogrtest.kml_ds is not None, 'kml_ds is none' lyr = ogrtest.kml_ds.GetLayerByName('Placemarks') lyr.ResetReading() @@ -264,132 +211,98 @@ def ogr_kml_point_read(): wkt = 'POINT(-122.0822035425683 37.42228990140251)' - if ogrtest.check_feature_geometry(feat, wkt): - return 'fail' + assert not ogrtest.check_feature_geometry(feat, wkt) feat = lyr.GetNextFeature() - if feat is None: - gdaltest.post_reason('expected feature not found.') - return 'fail' + assert feat is not None, 'expected feature not found.' wkt = 'POINT(-122.084075 37.4220033612141 50)' - if ogrtest.check_feature_geometry(feat, wkt): - return 'fail' + assert not ogrtest.check_feature_geometry(feat, wkt) feat = lyr.GetNextFeature() - if feat is None: - gdaltest.post_reason('expected feature not found.') - return 'fail' + assert feat is not None, 'expected feature not found.' wkt = 'POINT(-122.0857667006183 37.42156927867553 50)' - if ogrtest.check_feature_geometry(feat, wkt): - return 'fail' - - return 'success' + assert not ogrtest.check_feature_geometry(feat, wkt) ############################################################################### # Test reading of KML linestring geometry # -def ogr_kml_linestring_read(): +def test_ogr_kml_linestring_read(): if not ogrtest.have_read_kml: - return 'skip' + pytest.skip() - if ogrtest.kml_ds is None: - gdaltest.post_reason('kml_ds is none') - return 'fail' + assert ogrtest.kml_ds is not None, 'kml_ds is none' lyr = ogrtest.kml_ds.GetLayerByName('Paths') lyr.ResetReading() feat = lyr.GetNextFeature() wkt = 'LINESTRING (-112.081423783034495 36.106778704771372 0, -112.087026775269294 36.0905099328766 0)' - if ogrtest.check_feature_geometry(feat, wkt): - return 'fail' + assert not ogrtest.check_feature_geometry(feat, wkt) feat = lyr.GetNextFeature() - if feat is None: - gdaltest.post_reason('expected feature not found.') - return 'fail' + assert feat is not None, 'expected feature not found.' wkt = 'LINESTRING (-112.080622229594994 36.106734600079953 0,-112.085242575314993 36.090495986124218 0)' - if ogrtest.check_feature_geometry(feat, wkt): - return 'fail' + assert not ogrtest.check_feature_geometry(feat, wkt) feat = lyr.GetNextFeature() - if feat is None: - gdaltest.post_reason('expected feature not found.') - return 'fail' + assert feat is not None, 'expected feature not found.' wkt = 'LINESTRING (-112.265654928602004 36.094476726025462 2357,-112.266038452823807 36.093426088386707 2357,-112.266813901345301 36.092510587768807 2357,-112.267782683444494 36.091898273579957 2357,-112.268855751095202 36.091313794118697 2357,-112.269481071721899 36.090367720752099 2357,-112.269526855561097 36.089321714872852 2357,-112.269014456727604 36.088509160604723 2357,-112.268152881533894 36.087538135979557 2357,-112.2670588176031 36.086826852625677 2357,-112.265737458732104 36.086463123013033 2357)' - if ogrtest.check_feature_geometry(feat, wkt): - return 'fail' - - return 'success' + assert not ogrtest.check_feature_geometry(feat, wkt) ############################################################################### # Test reading of KML polygon geometry # -def ogr_kml_polygon_read(): +def test_ogr_kml_polygon_read(): if not ogrtest.have_read_kml: - return 'skip' + pytest.skip() - if ogrtest.kml_ds is None: - gdaltest.post_reason('kml_ds is none') - return 'fail' + assert ogrtest.kml_ds is not None, 'kml_ds is none' lyr = ogrtest.kml_ds.GetLayerByName('Google Campus') lyr.ResetReading() feat = lyr.GetNextFeature() wkt = 'POLYGON ((-122.084893845961204 37.422571240447859 17,-122.084958097919795 37.422119226268563 17,-122.084746957304702 37.42207183952619 17,-122.084572538096197 37.422090067296757 17,-122.084595488672306 37.422159327008949 17,-122.0838521118269 37.422272785643713 17,-122.083792243334997 37.422035391120843 17,-122.0835076656616 37.422090069571063 17,-122.083470946415204 37.422009873951609 17,-122.083122108574798 37.422104649494599 17,-122.082924737457205 37.422265039903863 17,-122.082933916938501 37.422312428430942 17,-122.083383735973698 37.422250460876178 17,-122.083360785424802 37.422341592287452 17,-122.083420455164202 37.42237075460644 17,-122.083659133885007 37.422512920110009 17,-122.083975843895203 37.422658730937812 17,-122.084237474333094 37.422651439725207 17,-122.0845036949503 37.422651438643499 17,-122.0848020460801 37.422611339163147 17,-122.084788275051494 37.422563950551208 17,-122.084893845961204 37.422571240447859 17))' - if ogrtest.check_feature_geometry(feat, wkt): - return 'fail' + assert not ogrtest.check_feature_geometry(feat, wkt) feat = lyr.GetNextFeature() - if feat is None: - gdaltest.post_reason('expected feature not found.') - return 'fail' + assert feat is not None, 'expected feature not found.' wkt = 'POLYGON ((-122.085741277148301 37.422270331552568 17,-122.085816976848093 37.422314088323461 17,-122.085852582875006 37.422303374697442 17,-122.085879994563896 37.422256861387893 17,-122.085886010140896 37.422231107613797 17,-122.085806915728796 37.422202501738553 17,-122.085837954265301 37.42214027058678 17,-122.085673264051906 37.422086902144081 17,-122.085602292640701 37.42214885429042 17,-122.085590277843593 37.422128290487002 17,-122.085584167223701 37.422081719672462 17,-122.085485206574106 37.42210455874995 17,-122.085506726435199 37.422142679498243 17,-122.085443071291493 37.422127838461719 17,-122.085099071490404 37.42251282407603 17,-122.085676981863202 37.422818153236513 17,-122.086016227378295 37.422449188587223 17,-122.085726032700407 37.422292396042529 17,-122.085741277148301 37.422270331552568 17))' - if ogrtest.check_feature_geometry(feat, wkt): - return 'fail' + assert not ogrtest.check_feature_geometry(feat, wkt) feat = lyr.GetNextFeature() - if feat is None: - gdaltest.post_reason('expected feature not found.') - return 'fail' + assert feat is not None, 'expected feature not found.' wkt = 'POLYGON ((-122.085786228724203 37.421362088869692 25,-122.085731299060299 37.421369359894811 25,-122.085731299291794 37.421409349109027 25,-122.085607707367899 37.421383901665649 25,-122.085580242651602 37.42137299550869 25,-122.085218622197104 37.421372995043157 25,-122.085227776563897 37.421616565082651 25,-122.085259818934702 37.421605658944031 25,-122.085259818549901 37.421682001560001 25,-122.085236931147804 37.421700178603459 25,-122.085264395782801 37.421761979825753 25,-122.085323903274599 37.421761980139067 25,-122.085355945432397 37.421852864451999 25,-122.085410875246296 37.421889218237339 25,-122.085479537935697 37.42189285337048 25,-122.085543622981902 37.421889217975462 25,-122.085626017804202 37.421860134999257 25,-122.085937287963006 37.421860134536047 25,-122.085942871866607 37.42160898590042 25,-122.085965546986102 37.421579927591438 25,-122.085864046234093 37.421471150029568 25,-122.0858548911215 37.421405713261841 25,-122.085809116276806 37.4214057134039 25,-122.085786228724203 37.421362088869692 25))' - if ogrtest.check_feature_geometry(feat, wkt): - return 'fail' + assert not ogrtest.check_feature_geometry(feat, wkt) feat = lyr.GetNextFeature() - if feat is None: - gdaltest.post_reason('expected feature not found.') - return 'fail' + assert feat is not None, 'expected feature not found.' wkt = 'POLYGON ((-122.084437112828397 37.421772530030907 19,-122.084511885574599 37.421911115428962 19,-122.0850470999805 37.421787551215353 19,-122.085071991339106 37.421436630231611 19,-122.084916406231997 37.421372378221157 19,-122.084219386816699 37.421372378016258 19,-122.084219386589993 37.421476171614962 19,-122.083808641999099 37.4214613409357 19,-122.083789972856394 37.421313064107963 19,-122.083279653469802 37.421293288405927 19,-122.083260981920702 37.421392139442979 19,-122.082937362173695 37.421372363998763 19,-122.082906242566693 37.421515697788713 19,-122.082850226966499 37.421762825764652 19,-122.082943578863507 37.421767769696352 19,-122.083217411188002 37.421792485526858 19,-122.0835970430103 37.421748007445601 19,-122.083945555677104 37.421693642376027 19,-122.084007789463698 37.421762838158529 19,-122.084113587521003 37.421748011043917 19,-122.084076247378405 37.421713412923751 19,-122.084144704773905 37.421678815345693 19,-122.084144704222993 37.421817206601972 19,-122.084250333307395 37.421817070044597 19,-122.084437112828397 37.421772530030907 19))' - if ogrtest.check_feature_geometry(feat, wkt): - return 'fail' - - return 'success' + assert not ogrtest.check_feature_geometry(feat, wkt) ############################################################################### # Write test -def ogr_kml_write_1(): +def test_ogr_kml_write_1(): if ogrtest.kml_drv is None: - return 'skip' + pytest.skip() srs = osr.SpatialReference() srs.SetWellKnownGeogCS('WGS72') @@ -398,13 +311,9 @@ def ogr_kml_write_1(): dst_feat = ogr.Feature(lyr.GetLayerDefn()) dst_feat.SetGeometry(ogr.CreateGeometryFromWkt('POINT (2 49)')) - if lyr.CreateFeature(dst_feat) != 0: - gdaltest.post_reason('CreateFeature failed.') - return 'fail' - if dst_feat.GetGeometryRef().ExportToWkt() != 'POINT (2 49)': - print(dst_feat.GetGeometryRef().ExportToWkt()) - gdaltest.post_reason('CreateFeature changed the geometry.') - return 'fail' + assert lyr.CreateFeature(dst_feat) == 0, 'CreateFeature failed.' + assert dst_feat.GetGeometryRef().ExportToWkt() == 'POINT (2 49)', \ + 'CreateFeature changed the geometry.' lyr = ds.CreateLayer('test_wgs84') @@ -412,142 +321,95 @@ def ogr_kml_write_1(): dst_feat.SetField('name', 'my_name') dst_feat.SetField('description', 'my_description') dst_feat.SetGeometry(ogr.CreateGeometryFromWkt('POINT (2 49)')) - if lyr.CreateFeature(dst_feat) != 0: - gdaltest.post_reason('CreateFeature failed.') - return 'fail' + assert lyr.CreateFeature(dst_feat) == 0, 'CreateFeature failed.' dst_feat = ogr.Feature(lyr.GetLayerDefn()) dst_feat.SetGeometry(ogr.CreateGeometryFromWkt('POINT (2 49 1)')) - if lyr.CreateFeature(dst_feat) != 0: - gdaltest.post_reason('CreateFeature failed.') - return 'fail' + assert lyr.CreateFeature(dst_feat) == 0, 'CreateFeature failed.' dst_feat = ogr.Feature(lyr.GetLayerDefn()) dst_feat.SetGeometry(ogr.CreateGeometryFromWkt('LINESTRING (0 1,2 3)')) - if lyr.CreateFeature(dst_feat) != 0: - gdaltest.post_reason('CreateFeature failed.') - return 'fail' + assert lyr.CreateFeature(dst_feat) == 0, 'CreateFeature failed.' dst_feat = ogr.Feature(lyr.GetLayerDefn()) dst_feat.SetGeometry(ogr.CreateGeometryFromWkt('POLYGON ((0 1,2 3,4 5,0 1),(0 1,2 3,4 5,0 1))')) - if lyr.CreateFeature(dst_feat) != 0: - gdaltest.post_reason('CreateFeature failed.') - return 'fail' + assert lyr.CreateFeature(dst_feat) == 0, 'CreateFeature failed.' dst_feat = ogr.Feature(lyr.GetLayerDefn()) dst_feat.SetGeometry(ogr.CreateGeometryFromWkt('MULTIPOINT (2 49,2 49)')) - if lyr.CreateFeature(dst_feat) != 0: - gdaltest.post_reason('CreateFeature failed.') - return 'fail' + assert lyr.CreateFeature(dst_feat) == 0, 'CreateFeature failed.' dst_feat = ogr.Feature(lyr.GetLayerDefn()) dst_feat.SetGeometry(ogr.CreateGeometryFromWkt('MULTILINESTRING ((0 1,2 3),(0 1,2 3))')) - if lyr.CreateFeature(dst_feat) != 0: - gdaltest.post_reason('CreateFeature failed.') - return 'fail' + assert lyr.CreateFeature(dst_feat) == 0, 'CreateFeature failed.' dst_feat = ogr.Feature(lyr.GetLayerDefn()) dst_feat.SetGeometry(ogr.CreateGeometryFromWkt('MULTIPOLYGON (((0 1,2 3,4 5,0 1),(0 1,2 3,4 5,0 1)),((0 1,2 3,4 5,0 1),(0 1,2 3,4 5,0 1)))')) - if lyr.CreateFeature(dst_feat) != 0: - gdaltest.post_reason('CreateFeature failed.') - return 'fail' + assert lyr.CreateFeature(dst_feat) == 0, 'CreateFeature failed.' dst_feat = ogr.Feature(lyr.GetLayerDefn()) dst_feat.SetGeometry(ogr.CreateGeometryFromWkt('GEOMETRYCOLLECTION (POINT (2 49 1),LINESTRING (0 1 0,2 3 0))')) - if lyr.CreateFeature(dst_feat) != 0: - gdaltest.post_reason('CreateFeature failed.') - return 'fail' + assert lyr.CreateFeature(dst_feat) == 0, 'CreateFeature failed.' ds = None - return 'success' - ############################################################################### # Check previous test -def ogr_kml_check_write_1(): +def test_ogr_kml_check_write_1(): if not ogrtest.have_read_kml: - return 'skip' + pytest.skip() content = open('tmp/kml.kml').read() - if content.find('Schema') >= 0: - gdaltest.post_reason('Did not expect Schema tags.') - return 'fail' + assert content.find('Schema') < 0, 'Did not expect Schema tags.' ds = ogr.Open('tmp/kml.kml') lyr = ds.GetLayerByName('test_wgs84') - if lyr.GetFeatureCount() != 8: - gdaltest.post_reason('Bad feature count.') - return 'fail' + assert lyr.GetFeatureCount() == 8, 'Bad feature count.' feat = lyr.GetNextFeature() - if feat.GetField('name') != 'my_name': - print(feat.GetField('name')) - gdaltest.post_reason('Unexpected name.') - return 'fail' - if feat.GetField('description') != 'my_description': - print(feat.GetField('description')) - gdaltest.post_reason('Unexpected description.') - return 'fail' - if feat.GetGeometryRef().ExportToWkt() != 'POINT (2 49)': - print(feat.GetGeometryRef().ExportToWkt()) - gdaltest.post_reason('Unexpected geometry.') - return 'fail' + assert feat.GetField('name') == 'my_name', 'Unexpected name.' + assert feat.GetField('description') == 'my_description', 'Unexpected description.' + assert feat.GetGeometryRef().ExportToWkt() == 'POINT (2 49)', 'Unexpected geometry.' feat = lyr.GetNextFeature() - if feat.GetGeometryRef().ExportToWkt() != 'POINT (2 49 1)': - print(feat.GetGeometryRef().ExportToWkt()) - gdaltest.post_reason('Unexpected geometry.') - return 'fail' + assert feat.GetGeometryRef().ExportToWkt() == 'POINT (2 49 1)', \ + 'Unexpected geometry.' feat = lyr.GetNextFeature() - if feat.GetGeometryRef().ExportToWkt() != 'LINESTRING (0 1,2 3)': - print(feat.GetGeometryRef().ExportToWkt()) - gdaltest.post_reason('Unexpected geometry.') - return 'fail' + assert feat.GetGeometryRef().ExportToWkt() == 'LINESTRING (0 1,2 3)', \ + 'Unexpected geometry.' feat = lyr.GetNextFeature() - if feat.GetGeometryRef().ExportToWkt() != 'POLYGON ((0 1,2 3,4 5,0 1),(0 1,2 3,4 5,0 1))': - print(feat.GetGeometryRef().ExportToWkt()) - gdaltest.post_reason('Unexpected geometry.') - return 'fail' + assert feat.GetGeometryRef().ExportToWkt() == 'POLYGON ((0 1,2 3,4 5,0 1),(0 1,2 3,4 5,0 1))', \ + 'Unexpected geometry.' feat = lyr.GetNextFeature() - if feat.GetGeometryRef().ExportToWkt() != 'MULTIPOINT (2 49,2 49)': - print(feat.GetGeometryRef().ExportToWkt()) - gdaltest.post_reason('Unexpected geometry.') - return 'fail' + assert feat.GetGeometryRef().ExportToWkt() == 'MULTIPOINT (2 49,2 49)', \ + 'Unexpected geometry.' feat = lyr.GetNextFeature() - if feat.GetGeometryRef().ExportToWkt() != 'MULTILINESTRING ((0 1,2 3),(0 1,2 3))': - print(feat.GetGeometryRef().ExportToWkt()) - gdaltest.post_reason('Unexpected geometry.') - return 'fail' + assert feat.GetGeometryRef().ExportToWkt() == 'MULTILINESTRING ((0 1,2 3),(0 1,2 3))', \ + 'Unexpected geometry.' feat = lyr.GetNextFeature() - if feat.GetGeometryRef().ExportToWkt() != 'MULTIPOLYGON (((0 1,2 3,4 5,0 1),(0 1,2 3,4 5,0 1)),((0 1,2 3,4 5,0 1),(0 1,2 3,4 5,0 1)))': - print(feat.GetGeometryRef().ExportToWkt()) - gdaltest.post_reason('Unexpected geometry.') - return 'fail' + assert feat.GetGeometryRef().ExportToWkt() == 'MULTIPOLYGON (((0 1,2 3,4 5,0 1),(0 1,2 3,4 5,0 1)),((0 1,2 3,4 5,0 1),(0 1,2 3,4 5,0 1)))', \ + 'Unexpected geometry.' feat = lyr.GetNextFeature() - if feat.GetGeometryRef().ExportToWkt() != 'GEOMETRYCOLLECTION (POINT (2 49 1),LINESTRING (0 1 0,2 3 0))': - print(feat.GetGeometryRef().ExportToWkt()) - gdaltest.post_reason('Unexpected geometry.') - return 'fail' - - return 'success' + assert feat.GetGeometryRef().ExportToWkt() == 'GEOMETRYCOLLECTION (POINT (2 49 1),LINESTRING (0 1 0,2 3 0))', \ + 'Unexpected geometry.' ############################################################################### # Test reading attributes with XML content in them # -def ogr_kml_xml_attributes(): +def test_ogr_kml_xml_attributes(): if not ogrtest.have_read_kml: - return 'skip' + pytest.skip() ds = ogr.Open('data/description_with_xml.kml') @@ -555,20 +417,18 @@ def ogr_kml_xml_attributes(): feat = lyr.GetNextFeature() if feat.GetField('description') != 'Description<br></br><i attr="val">Interesting</i><br></br>': - gdaltest.post_reason('Wrong description field value') print('got: ', feat.GetField('description')) - return 'fail' - - return 'success' + pytest.fail('Wrong description field value') + ############################################################################### # Test reading all geometry types (#3558) -def ogr_kml_read_geometries(): +def test_ogr_kml_read_geometries(): if not ogrtest.have_read_kml: - return 'skip' + pytest.skip() ds = ogr.Open('data/geometries.kml') @@ -577,34 +437,29 @@ def ogr_kml_read_geometries(): while feat is not None: feat = lyr.GetNextFeature() - return 'success' - + ############################################################################### # Run test_ogrsf -def ogr_kml_test_ogrsf(): +def test_ogr_kml_test_ogrsf(): if not ogrtest.have_read_kml: - return 'skip' + pytest.skip() import test_cli_utilities if test_cli_utilities.get_test_ogrsf_path() is None: - return 'skip' + pytest.skip() ret = gdaltest.runexternal(test_cli_utilities.get_test_ogrsf_path() + ' --config OGR_SKIP LIBKML -ro data/samples.kml') - if ret.find("using driver `KML'") == -1 or ret.find('INFO') == -1 or ret.find('ERROR') != -1: - print(ret) - return 'fail' - - return 'success' + assert not (ret.find("using driver `KML'") == -1 or ret.find('INFO') == -1 or ret.find('ERROR') != -1) ############################################################################### # Test fix for #2772 -def ogr_kml_interleaved_writing(): +def test_ogr_kml_interleaved_writing(): ds = ogr.GetDriverByName('KML').CreateDataSource('/vsimem/ogr_kml_interleaved_writing.kml') lyr1 = ds.CreateLayer("lyr1") @@ -617,71 +472,49 @@ def ogr_kml_interleaved_writing(): gdal.Unlink('/vsimem/ogr_kml_interleaved_writing.kml') # CreateFeature() should fail - if ret == 0: - return 'fail' - - return 'success' + assert ret != 0 ############################################################################### # Test reading KML with only Placemark -def ogr_kml_read_placemark(): +def test_ogr_kml_read_placemark(): if not ogrtest.have_read_kml: - return 'skip' + pytest.skip() ds = ogr.Open('data/placemark.kml') lyr = ds.GetLayer(0) feat = lyr.GetNextFeature() - if feat is None: - return 'fail' - - return 'success' + assert feat is not None ############################################################################### # Test reading KML without any layer -def ogr_kml_read_empty(): +def test_ogr_kml_read_empty(): if not ogrtest.have_read_kml: - return 'skip' + pytest.skip() ds = ogr.Open('data/empty.kml') - if ds.GetLayerCount() != 0: - gdaltest.post_reason('failed') - print(ds.GetLayerCount()) - return 'fail' - - return 'success' + assert ds.GetLayerCount() == 0 ############################################################################### # Test reading KML with empty layers -def ogr_kml_read_emptylayers(): +def test_ogr_kml_read_emptylayers(): if not ogrtest.have_read_kml: - return 'skip' + pytest.skip() ds = ogr.Open('data/emptylayers.kml') - if ds.GetLayerCount() != 2: - gdaltest.post_reason('failed') - print(ds.GetLayerCount()) - return 'fail' + assert ds.GetLayerCount() == 2 - if ds.GetLayer(0).GetFeatureCount() != 0: - gdaltest.post_reason('failed') - print(ds.GetLayer(0).GetFeatureCount()) - return 'fail' + assert ds.GetLayer(0).GetFeatureCount() == 0 - if ds.GetLayer(1).GetFeatureCount() != 0: - gdaltest.post_reason('failed') - print(ds.GetLayer(1).GetFeatureCount()) - return 'fail' - - return 'success' + assert ds.GetLayer(1).GetFeatureCount() == 0 ############################################################################### @@ -690,23 +523,16 @@ def compare_output(content, expected_content): content_lines = content.strip().split('\n') expected_lines = expected_content.strip().split('\n') - if len(content_lines) != len(expected_lines): - gdaltest.post_reason('fail') - print(content) - return 'fail' + assert len(content_lines) == len(expected_lines), content for i, content_line in enumerate(content_lines): - if content_line.strip() != expected_lines[i].strip(): - gdaltest.post_reason('fail') - print(content) - return 'fail' - - return 'success' + assert content_line.strip() == expected_lines[i].strip(), content + ############################################################################### # Test that we can write a schema -def ogr_kml_write_schema(): +def test_ogr_kml_write_schema(): ds = ogr.GetDriverByName('KML').CreateDataSource('/vsimem/ogr_kml_write_schema.kml') lyr = ds.CreateLayer("lyr") @@ -751,7 +577,7 @@ def ogr_kml_write_schema(): # -def ogr_kml_empty_layer(): +def test_ogr_kml_empty_layer(): ds = ogr.GetDriverByName('KML').CreateDataSource('/vsimem/ogr_kml_empty_layer.kml') ds.CreateLayer("empty") @@ -776,7 +602,7 @@ def ogr_kml_empty_layer(): # Empty layer followed by regular layer -def ogr_kml_two_layers(): +def test_ogr_kml_two_layers(): ds = ogr.GetDriverByName('KML').CreateDataSource('/vsimem/ogr_kml_two_layers.kml') ds.CreateLayer("empty") @@ -817,12 +643,12 @@ def ogr_kml_two_layers(): # Cleanup -def ogr_kml_cleanup(): +def test_ogr_kml_cleanup(): os.remove('tmp/kml.kml') if not ogrtest.have_read_kml: - return 'skip' + pytest.skip() if ogrtest.kml_ds is not None: ogrtest.kml_ds = None @@ -832,190 +658,110 @@ def ogr_kml_cleanup(): print('Re-register LIBKML driver') ogrtest.libkml_drv.Register() - return 'success' - + ############################################################################### # Test reading KML with folder with empty subfolder and placemark -def ogr_kml_read_folder_with_subfolder_placemark(): +def test_ogr_kml_read_folder_with_subfolder_placemark(): if not ogrtest.have_read_kml: - return 'skip' + pytest.skip() ds = ogr.Open('data/folder_with_subfolder_placemark.kml') - if ds.GetLayerCount() != 1: - gdaltest.post_reason('failed') - print(ds.GetLayerCount()) - return 'fail' - - if ds.GetLayer(0).GetFeatureCount() != 0: - gdaltest.post_reason('failed') - print(ds.GetLayer(0).GetFeatureCount()) - return 'fail' + assert ds.GetLayerCount() == 1 - return 'success' + assert ds.GetLayer(0).GetFeatureCount() == 0 ############################################################################### # Test reading invalid KML (#6878) -def ogr_kml_read_truncated(): +def test_ogr_kml_read_truncated(): if not ogrtest.have_read_kml: - return 'skip' + pytest.skip() with gdaltest.error_handler(): ds = ogr.Open('data/truncated.kml') - if ds is not None: - return 'fail' - - return 'success' + assert ds is None ############################################################################### # Test fix for https://bugs.chromium.org/p/oss-fuzz/issues/detail?id=1591 -def ogr_kml_read_weird_empty_folders(): +def test_ogr_kml_read_weird_empty_folders(): if not ogrtest.have_read_kml: - return 'skip' + pytest.skip() ds = ogr.Open('data/weird_empty_folders.kml') - if ds.GetLayerCount() != 1: - gdaltest.post_reason('failed') - print(ds.GetLayerCount()) - return 'fail' + assert ds.GetLayerCount() == 1 - if ds.GetLayer(0).GetFeatureCount() != 0: - gdaltest.post_reason('failed') - print(ds.GetLayer(0).GetFeatureCount()) - return 'fail' - - return 'success' + assert ds.GetLayer(0).GetFeatureCount() == 0 ############################################################################### # Test fix for https://bugs.chromium.org/p/oss-fuzz/issues/detail?id=1683 -def ogr_kml_read_junk_content_after_valid_doc(): +def test_ogr_kml_read_junk_content_after_valid_doc(): if not ogrtest.have_read_kml: - return 'skip' + pytest.skip() with gdaltest.error_handler(): ds = ogr.Open('data/junk_content_after_valid_doc.kml') - if ds is not None: - return 'fail' - - return 'success' + assert ds is None ############################################################################### # Test reading KML with kml: prefix -def ogr_kml_read_placemark_with_kml_prefix(): +def test_ogr_kml_read_placemark_with_kml_prefix(): if not ogrtest.have_read_kml: - return 'skip' + pytest.skip() ds = ogr.Open('data/placemark_with_kml_prefix.kml') lyr = ds.GetLayer(0) feat = lyr.GetNextFeature() - if feat is None: - return 'fail' - - return 'success' + assert feat is not None ############################################################################### # Test reading KML with duplicated folder name -def ogr_kml_read_duplicate_folder_name(): +def test_ogr_kml_read_duplicate_folder_name(): if not ogrtest.have_read_kml: - return 'skip' + pytest.skip() ds = ogr.Open('data/duplicate_folder_name.kml') lyr = ds.GetLayer(0) - if lyr.GetName() != 'layer': - gdaltest.post_reason('failure') - print(lyr.GetName()) - return 'fail' + assert lyr.GetName() == 'layer' lyr = ds.GetLayer(1) - if lyr.GetName() != 'layer (#2)': - gdaltest.post_reason('failure') - print(lyr.GetName()) - return 'fail' - - return 'success' + assert lyr.GetName() == 'layer (#2)' ############################################################################### # Test reading KML with a placemark in root document, and a subfolder (#7221) -def ogr_kml_read_placemark_in_root_and_subfolder(): +def test_ogr_kml_read_placemark_in_root_and_subfolder(): if not ogrtest.have_read_kml: - return 'skip' + pytest.skip() ds = ogr.Open('data/placemark_in_root_and_subfolder.kml') lyr = ds.GetLayerByName('TopLevel') - if lyr is None: - gdaltest.post_reason('failure') - return 'fail' - if lyr.GetFeatureCount() != 1: - gdaltest.post_reason('failure') - return 'fail' + assert lyr is not None + assert lyr.GetFeatureCount() == 1 lyr = ds.GetLayerByName('SubFolder1') - if lyr is None: - gdaltest.post_reason('failure') - return 'fail' - if lyr.GetFeatureCount() != 1: - gdaltest.post_reason('failure') - return 'fail' - - return 'success' + assert lyr is not None + assert lyr.GetFeatureCount() == 1 ############################################################################### # Build tests runner -gdaltest_list = [ - ogr_kml_datastore, - ogr_kml_attributes_1, - ogr_kml_attributes_2, - ogr_kml_attributes_3, - ogr_kml_attributes_4, - ogr_kml_point_read, - ogr_kml_linestring_read, - ogr_kml_polygon_read, - ogr_kml_write_1, - ogr_kml_check_write_1, - ogr_kml_xml_attributes, - ogr_kml_read_geometries, - ogr_kml_test_ogrsf, - ogr_kml_interleaved_writing, - ogr_kml_read_placemark, - ogr_kml_read_empty, - ogr_kml_read_emptylayers, - ogr_kml_write_schema, - ogr_kml_empty_layer, - ogr_kml_two_layers, - ogr_kml_read_folder_with_subfolder_placemark, - ogr_kml_read_truncated, - ogr_kml_read_weird_empty_folders, - ogr_kml_read_junk_content_after_valid_doc, - ogr_kml_read_placemark_with_kml_prefix, - ogr_kml_read_duplicate_folder_name, - ogr_kml_read_placemark_in_root_and_subfolder, - ogr_kml_cleanup] - -if __name__ == '__main__': - - gdaltest.setup_run('ogr_kml') - - gdaltest.run_tests(gdaltest_list) - - sys.exit(gdaltest.summarize()) + diff --git a/autotest/ogr/ogr_layer_algebra.py b/autotest/ogr/ogr_layer_algebra.py index 5bd338259694..637c2fe0ae42 100755 --- a/autotest/ogr/ogr_layer_algebra.py +++ b/autotest/ogr/ogr_layer_algebra.py @@ -29,14 +29,12 @@ # DEALINGS IN THE SOFTWARE. ############################################################################### -import sys -sys.path.append('../pymod') -import gdaltest import ogrtest from osgeo import ogr +import pytest ############################################################################### # Common usage tests. @@ -85,12 +83,12 @@ def is_same(A, B): return False -def algebra_setup(): +def test_algebra_setup(): global ds, A, B, C, pointInB, D1, D2, empty if not ogrtest.have_geos(): - return 'skip' + pytest.skip() # Create three memory layers for intersection. @@ -157,12 +155,10 @@ def algebra_setup(): empty = ds.CreateLayer('empty') - return 'success' - -def algebra_intersection(): +def test_algebra_intersection(): if not ogrtest.have_geos(): - return 'skip' + pytest.skip() recreate_layer_C() @@ -170,22 +166,15 @@ def algebra_intersection(): err = A.Intersection(B, C) - if err != 0: - gdaltest.post_reason('got non-zero result code ' + str(err) + ' from Layer.Intersection') - return 'fail' + assert err == 0, \ + ('got non-zero result code ' + str(err) + ' from Layer.Intersection') C_defn = C.GetLayerDefn() - if C_defn.GetFieldCount() != 2 \ - or C_defn.GetFieldDefn(0).GetName() != 'A' \ - or C_defn.GetFieldDefn(0).GetType() != ogr.OFTInteger \ - or C_defn.GetFieldDefn(1).GetName() != 'B' \ - or C_defn.GetFieldDefn(1).GetType() != ogr.OFTString: - gdaltest.post_reason('Did not get expected output schema.') - return 'fail' - - if C.GetFeatureCount() != 2: - gdaltest.post_reason('Layer.Intersection returned ' + str(C.GetFeatureCount()) + ' features') - return 'fail' + assert C_defn.GetFieldCount() == 2 and C_defn.GetFieldDefn(0).GetName() == 'A' and C_defn.GetFieldDefn(0).GetType() == ogr.OFTInteger and C_defn.GetFieldDefn(1).GetName() == 'B' and C_defn.GetFieldDefn(1).GetType() == ogr.OFTString, \ + 'Did not get expected output schema.' + + assert C.GetFeatureCount() == 2, \ + ('Layer.Intersection returned ' + str(C.GetFeatureCount()) + ' features') f1 = (ogr.Geometry(wkt='POLYGON ((2 3,3 3,3 2,2 2,2 3))'), 1, 'first') f2 = (ogr.Geometry(wkt='POLYGON ((5 2,5 3,6 3,6 2,5 2))'), 2, 'first') @@ -198,16 +187,13 @@ def algebra_intersection(): g = feat.GetGeometryRef() if g.Equals(f1[0]): - if feat.GetField('A') != f1[1] or feat.GetField('B') != f1[2]: - gdaltest.post_reason('Did not get expected field values.') - return 'fail' + assert feat.GetField('A') == f1[1] and feat.GetField('B') == f1[2], \ + 'Did not get expected field values.' elif g.Equals(f2[0]): - if feat.GetField('A') != f2[1] or feat.GetField('B') != f2[2]: - gdaltest.post_reason('Did not get expected field values.') - return 'fail' + assert feat.GetField('A') == f2[1] and feat.GetField('B') == f2[2], \ + 'Did not get expected field values.' else: - gdaltest.post_reason('Layer.Intersection returned wrong geometry: ' + g.ExportToWkt()) - return 'fail' + pytest.fail('Layer.Intersection returned wrong geometry: ' + g.ExportToWkt()) # This time we test with PROMOTE_TO_MULTI and pre-created output fields. recreate_layer_C() @@ -216,13 +202,11 @@ def algebra_intersection(): err = A.Intersection(B, C, options=['PROMOTE_TO_MULTI=YES']) - if err != 0: - gdaltest.post_reason('got non-zero result code ' + str(err) + ' from Layer.Intersection') - return 'fail' + assert err == 0, \ + ('got non-zero result code ' + str(err) + ' from Layer.Intersection') - if C.GetFeatureCount() != 2: - gdaltest.post_reason('Layer.Intersection returned ' + str(C.GetFeatureCount()) + ' features') - return 'fail' + assert C.GetFeatureCount() == 2, \ + ('Layer.Intersection returned ' + str(C.GetFeatureCount()) + ' features') f1 = (ogr.Geometry(wkt='MULTIPOLYGON (((2 3,3 3,3 2,2 2,2 3)))'), 1, 'first') f2 = (ogr.Geometry(wkt='MULTIPOLYGON (((5 2,5 3,6 3,6 2,5 2)))'), 2, 'first') @@ -235,21 +219,13 @@ def algebra_intersection(): g = feat.GetGeometryRef() if g.Equals(f1[0]): - if feat.GetField('A') != f1[1] or feat.GetField('B') != f1[2]: - gdaltest.post_reason('Did not get expected field values. (1)') - print(feat.GetField('A')) - print(feat.GetField('B')) - return 'fail' + assert feat.GetField('A') == f1[1] and feat.GetField('B') == f1[2], \ + 'Did not get expected field values. (1)' elif g.Equals(f2[0]): - if feat.GetField('A') != f2[1] or feat.GetField('B') != f2[2]: - gdaltest.post_reason('Did not get expected field values. (2)') - print(feat.GetField('A')) - print(feat.GetField('B')) - print(feat.GetField('B')) - return 'fail' + assert feat.GetField('A') == f2[1] and feat.GetField('B') == f2[2], \ + 'Did not get expected field values. (2)' else: - gdaltest.post_reason('Layer.Intersection returned wrong geometry: ' + g.ExportToWkt()) - return 'fail' + pytest.fail('Layer.Intersection returned wrong geometry: ' + g.ExportToWkt()) recreate_layer_C() @@ -257,20 +233,15 @@ def algebra_intersection(): err = D1.Intersection(D2, C, ['KEEP_LOWER_DIMENSION_GEOMETRIES=NO']) - if err != 0: - gdaltest.post_reason('got non-zero result code ' + str(err) + ' from Layer.Intersection') - return 'fail' + assert err == 0, \ + ('got non-zero result code ' + str(err) + ' from Layer.Intersection') - if not is_same(D1, C): - gdaltest.post_reason('D1 != C') - return 'fail' + assert is_same(D1, C), 'D1 != C' - return 'success' - -def algebra_KEEP_LOWER_DIMENSION_GEOMETRIES(): +def test_algebra_KEEP_LOWER_DIMENSION_GEOMETRIES(): if not ogrtest.have_geos(): - return 'skip' + pytest.skip() driver = ogr.GetDriverByName('MEMORY') ds = driver.CreateDataSource('ds') @@ -303,46 +274,37 @@ def algebra_KEEP_LOWER_DIMENSION_GEOMETRIES(): layer3 = ds.CreateLayer('layer3a') layer1.Intersection(layer2, layer3, ['KEEP_LOWER_DIMENSION_GEOMETRIES=NO']) - if layer3.GetFeatureCount() != 0: - gdaltest.post_reason('Lower dimension geometries not removed in intersection') - return 'fail' + assert layer3.GetFeatureCount() == 0, \ + 'Lower dimension geometries not removed in intersection' layer3 = ds.CreateLayer('layer3b') layer1.Intersection(layer2, layer3, ['KEEP_LOWER_DIMENSION_GEOMETRIES=YES']) - if layer3.GetFeatureCount() != 2: - gdaltest.post_reason('Lower dimension geometries not kept in intersection') - return 'fail' + assert layer3.GetFeatureCount() == 2, \ + 'Lower dimension geometries not kept in intersection' layer3 = ds.CreateLayer('layer3c') layer1.Union(layer2, layer3, ['KEEP_LOWER_DIMENSION_GEOMETRIES=NO']) - if layer3.GetFeatureCount() != 4: - gdaltest.post_reason('Lower dimension geometries not removed in union') - return 'fail' + assert layer3.GetFeatureCount() == 4, \ + 'Lower dimension geometries not removed in union' layer3 = ds.CreateLayer('layer3d') layer1.Union(layer2, layer3, ['KEEP_LOWER_DIMENSION_GEOMETRIES=YES']) - if layer3.GetFeatureCount() != 6: - gdaltest.post_reason('Lower dimension geometries not kept in union') - return 'fail' + assert layer3.GetFeatureCount() == 6, 'Lower dimension geometries not kept in union' layer3 = ds.CreateLayer('layer3e') layer1.Identity(layer2, layer3, ['KEEP_LOWER_DIMENSION_GEOMETRIES=NO']) - if layer3.GetFeatureCount() != 2: - gdaltest.post_reason('Lower dimension geometries not removed in identity') - return 'fail' + assert layer3.GetFeatureCount() == 2, \ + 'Lower dimension geometries not removed in identity' layer3 = ds.CreateLayer('layer3f') layer1.Identity(layer2, layer3, ['KEEP_LOWER_DIMENSION_GEOMETRIES=YES']) - if layer3.GetFeatureCount() != 4: - gdaltest.post_reason('Lower dimension geometries not kept in identity') - return 'fail' - - return 'success' + assert layer3.GetFeatureCount() == 4, \ + 'Lower dimension geometries not kept in identity' -def algebra_union(): +def test_algebra_union(): if not ogrtest.have_geos(): - return 'skip' + pytest.skip() recreate_layer_C() @@ -351,26 +313,20 @@ def algebra_union(): err = A.Union(B, C) if ogrtest.have_geos(): - if err != 0: - gdaltest.post_reason('got non-zero result code ' + str(err) + ' from Layer.Union') - return 'fail' + assert err == 0, ('got non-zero result code ' + str(err) + ' from Layer.Union') - if C.GetFeatureCount() != 5: - gdaltest.post_reason('Layer.Union returned ' + str(C.GetFeatureCount()) + ' features') - return 'fail' + assert C.GetFeatureCount() == 5, \ + ('Layer.Union returned ' + str(C.GetFeatureCount()) + ' features') recreate_layer_C() err = A.Union(B, C, options=['PROMOTE_TO_MULTI=YES']) if ogrtest.have_geos(): - if err != 0: - gdaltest.post_reason('got non-zero result code ' + str(err) + ' from Layer.Union') - return 'fail' + assert err == 0, ('got non-zero result code ' + str(err) + ' from Layer.Union') - if C.GetFeatureCount() != 5: - gdaltest.post_reason('Layer.Union returned ' + str(C.GetFeatureCount()) + ' features') - return 'fail' + assert C.GetFeatureCount() == 5, \ + ('Layer.Union returned ' + str(C.GetFeatureCount()) + ' features') recreate_layer_C() @@ -379,13 +335,9 @@ def algebra_union(): err = D1.Union(D2, C, ['KEEP_LOWER_DIMENSION_GEOMETRIES=NO']) if ogrtest.have_geos(): - if err != 0: - gdaltest.post_reason('got non-zero result code ' + str(err) + ' from Layer.Union') - return 'fail' + assert err == 0, ('got non-zero result code ' + str(err) + ' from Layer.Union') - if not is_same(D1, C): - gdaltest.post_reason('D1 != C') - return 'fail' + assert is_same(D1, C), 'D1 != C' recreate_layer_C() @@ -394,20 +346,16 @@ def algebra_union(): err = B.Union(pointInB, C) if ogrtest.have_geos(): - if err != 0: - gdaltest.post_reason('got non-zero result code ' + str(err) + ' from Layer.Union') - return 'fail' + assert err == 0, ('got non-zero result code ' + str(err) + ' from Layer.Union') - if C.GetFeatureCount() != 2: - gdaltest.post_reason('Layer.Union returned ' + str(C.GetFeatureCount()) + ' features') - return 'fail' + assert C.GetFeatureCount() == 2, \ + ('Layer.Union returned ' + str(C.GetFeatureCount()) + ' features') - return 'success' + - -def algebra_symdifference(): +def test_algebra_symdifference(): if not ogrtest.have_geos(): - return 'skip' + pytest.skip() recreate_layer_C() @@ -416,26 +364,20 @@ def algebra_symdifference(): err = A.SymDifference(B, C) if ogrtest.have_geos(): - if err != 0: - gdaltest.post_reason('got non-zero result code ' + str(err) + ' from Layer.SymDifference') - return 'fail' + assert err == 0, ('got non-zero result code ' + str(err) + ' from Layer.SymDifference') - if C.GetFeatureCount() != 3: - gdaltest.post_reason('Layer.SymDifference returned ' + str(C.GetFeatureCount()) + ' features') - return 'fail' + assert C.GetFeatureCount() == 3, \ + ('Layer.SymDifference returned ' + str(C.GetFeatureCount()) + ' features') recreate_layer_C() err = A.SymDifference(B, C, options=['PROMOTE_TO_MULTI=YES']) if ogrtest.have_geos(): - if err != 0: - gdaltest.post_reason('got non-zero result code ' + str(err) + ' from Layer.SymDifference') - return 'fail' + assert err == 0, ('got non-zero result code ' + str(err) + ' from Layer.SymDifference') - if C.GetFeatureCount() != 3: - gdaltest.post_reason('Layer.SymDifference returned ' + str(C.GetFeatureCount()) + ' features') - return 'fail' + assert C.GetFeatureCount() == 3, \ + ('Layer.SymDifference returned ' + str(C.GetFeatureCount()) + ' features') recreate_layer_C() @@ -444,20 +386,15 @@ def algebra_symdifference(): err = D1.SymDifference(D2, C) if ogrtest.have_geos(): - if err != 0: - gdaltest.post_reason('got non-zero result code ' + str(err) + ' from Layer.SymDifference') - return 'fail' - - if C.GetFeatureCount() != 0: - gdaltest.post_reason('Layer.SymDifference returned ' + str(C.GetFeatureCount()) + ' features') - return 'fail' + assert err == 0, ('got non-zero result code ' + str(err) + ' from Layer.SymDifference') - return 'success' + assert C.GetFeatureCount() == 0, \ + ('Layer.SymDifference returned ' + str(C.GetFeatureCount()) + ' features') -def algebra_identify(): +def test_algebra_identify(): if not ogrtest.have_geos(): - return 'skip' + pytest.skip() recreate_layer_C() @@ -466,26 +403,20 @@ def algebra_identify(): err = A.Identity(B, C) if ogrtest.have_geos(): - if err != 0: - gdaltest.post_reason('got non-zero result code ' + str(err) + ' from Layer.Identity') - return 'fail' + assert err == 0, ('got non-zero result code ' + str(err) + ' from Layer.Identity') - if C.GetFeatureCount() != 4: - gdaltest.post_reason('Layer.Identity returned ' + str(C.GetFeatureCount()) + ' features') - return 'fail' + assert C.GetFeatureCount() == 4, \ + ('Layer.Identity returned ' + str(C.GetFeatureCount()) + ' features') recreate_layer_C() err = A.Identity(B, C, options=['PROMOTE_TO_MULTI=YES']) if ogrtest.have_geos(): - if err != 0: - gdaltest.post_reason('got non-zero result code ' + str(err) + ' from Layer.Identity') - return 'fail' + assert err == 0, ('got non-zero result code ' + str(err) + ' from Layer.Identity') - if C.GetFeatureCount() != 4: - gdaltest.post_reason('Layer.Identity returned ' + str(C.GetFeatureCount()) + ' features') - return 'fail' + assert C.GetFeatureCount() == 4, \ + ('Layer.Identity returned ' + str(C.GetFeatureCount()) + ' features') recreate_layer_C() @@ -494,20 +425,15 @@ def algebra_identify(): err = D1.Identity(D2, C, ['KEEP_LOWER_DIMENSION_GEOMETRIES=NO']) if ogrtest.have_geos(): - if err != 0: - gdaltest.post_reason('got non-zero result code ' + str(err) + ' from Layer.Identity') - return 'fail' - - if not is_same(D1, C): - gdaltest.post_reason('D1 != C') - return 'fail' + assert err == 0, ('got non-zero result code ' + str(err) + ' from Layer.Identity') - return 'success' + assert is_same(D1, C), 'D1 != C' + -def algebra_update(): +def test_algebra_update(): if not ogrtest.have_geos(): - return 'skip' + pytest.skip() recreate_layer_C() @@ -516,26 +442,20 @@ def algebra_update(): err = A.Update(B, C) if ogrtest.have_geos(): - if err != 0: - gdaltest.post_reason('got non-zero result code ' + str(err) + ' from Layer.Update') - return 'fail' + assert err == 0, ('got non-zero result code ' + str(err) + ' from Layer.Update') - if C.GetFeatureCount() != 3: - gdaltest.post_reason('Layer.Update returned ' + str(C.GetFeatureCount()) + ' features') - return 'fail' + assert C.GetFeatureCount() == 3, \ + ('Layer.Update returned ' + str(C.GetFeatureCount()) + ' features') recreate_layer_C() err = A.Update(B, C, options=['PROMOTE_TO_MULTI=YES']) if ogrtest.have_geos(): - if err != 0: - gdaltest.post_reason('got non-zero result code ' + str(err) + ' from Layer.Update') - return 'fail' + assert err == 0, ('got non-zero result code ' + str(err) + ' from Layer.Update') - if C.GetFeatureCount() != 3: - gdaltest.post_reason('Layer.Update returned ' + str(C.GetFeatureCount()) + ' features') - return 'fail' + assert C.GetFeatureCount() == 3, \ + ('Layer.Update returned ' + str(C.GetFeatureCount()) + ' features') recreate_layer_C() @@ -544,20 +464,15 @@ def algebra_update(): err = D1.Update(D2, C) if ogrtest.have_geos(): - if err != 0: - gdaltest.post_reason('got non-zero result code ' + str(err) + ' from Layer.Update') - return 'fail' + assert err == 0, ('got non-zero result code ' + str(err) + ' from Layer.Update') - if not is_same(D1, C): - gdaltest.post_reason('D1 != C') - return 'fail' + assert is_same(D1, C), 'D1 != C' - return 'success' + - -def algebra_clip(): +def test_algebra_clip(): if not ogrtest.have_geos(): - return 'skip' + pytest.skip() recreate_layer_C() @@ -566,26 +481,20 @@ def algebra_clip(): err = A.Clip(B, C) if ogrtest.have_geos(): - if err != 0: - gdaltest.post_reason('got non-zero result code ' + str(err) + ' from Layer.Clip') - return 'fail' + assert err == 0, ('got non-zero result code ' + str(err) + ' from Layer.Clip') - if C.GetFeatureCount() != 2: - gdaltest.post_reason('Layer.Clip returned ' + str(C.GetFeatureCount()) + ' features') - return 'fail' + assert C.GetFeatureCount() == 2, \ + ('Layer.Clip returned ' + str(C.GetFeatureCount()) + ' features') recreate_layer_C() err = A.Clip(B, C, options=['PROMOTE_TO_MULTI=YES']) if ogrtest.have_geos(): - if err != 0: - gdaltest.post_reason('got non-zero result code ' + str(err) + ' from Layer.Clip') - return 'fail' + assert err == 0, ('got non-zero result code ' + str(err) + ' from Layer.Clip') - if C.GetFeatureCount() != 2: - gdaltest.post_reason('Layer.Clip returned ' + str(C.GetFeatureCount()) + ' features') - return 'fail' + assert C.GetFeatureCount() == 2, \ + ('Layer.Clip returned ' + str(C.GetFeatureCount()) + ' features') recreate_layer_C() @@ -594,20 +503,15 @@ def algebra_clip(): err = D1.Update(D2, C) if ogrtest.have_geos(): - if err != 0: - gdaltest.post_reason('got non-zero result code ' + str(err) + ' from Layer.Clip') - return 'fail' - - if not is_same(D1, C): - gdaltest.post_reason('D1 != C') - return 'fail' + assert err == 0, ('got non-zero result code ' + str(err) + ' from Layer.Clip') - return 'success' + assert is_same(D1, C), 'D1 != C' + -def algebra_erase(): +def test_algebra_erase(): if not ogrtest.have_geos(): - return 'skip' + pytest.skip() recreate_layer_C() @@ -616,26 +520,20 @@ def algebra_erase(): err = A.Erase(B, C) if ogrtest.have_geos(): - if err != 0: - gdaltest.post_reason('got non-zero result code ' + str(err) + ' from Layer.Erase') - return 'fail' + assert err == 0, ('got non-zero result code ' + str(err) + ' from Layer.Erase') - if C.GetFeatureCount() != 2: - gdaltest.post_reason('Layer.Erase returned ' + str(C.GetFeatureCount()) + ' features') - return 'fail' + assert C.GetFeatureCount() == 2, \ + ('Layer.Erase returned ' + str(C.GetFeatureCount()) + ' features') recreate_layer_C() err = A.Erase(B, C, options=['PROMOTE_TO_MULTI=YES']) if ogrtest.have_geos(): - if err != 0: - gdaltest.post_reason('got non-zero result code ' + str(err) + ' from Layer.Erase') - return 'fail' + assert err == 0, ('got non-zero result code ' + str(err) + ' from Layer.Erase') - if C.GetFeatureCount() != 2: - gdaltest.post_reason('Layer.Erase returned ' + str(C.GetFeatureCount()) + ' features') - return 'fail' + assert C.GetFeatureCount() == 2, \ + ('Layer.Erase returned ' + str(C.GetFeatureCount()) + ' features') recreate_layer_C() @@ -644,13 +542,10 @@ def algebra_erase(): err = D1.Erase(D2, C) if ogrtest.have_geos(): - if err != 0: - gdaltest.post_reason('got non-zero result code ' + str(err) + ' from Layer.Erase') - return 'fail' + assert err == 0, ('got non-zero result code ' + str(err) + ' from Layer.Erase') - if C.GetFeatureCount() != 0: - gdaltest.post_reason('Layer.Erase returned ' + str(C.GetFeatureCount()) + ' features') - return 'fail' + assert C.GetFeatureCount() == 0, \ + ('Layer.Erase returned ' + str(C.GetFeatureCount()) + ' features') recreate_layer_C() @@ -658,35 +553,30 @@ def algebra_erase(): A.Erase(empty, C) - if C.GetFeatureCount() != A.GetFeatureCount(): - gdaltest.post_reason('Layer.Erase returned ' + str(C.GetFeatureCount()) + ' features') - return 'fail' + assert C.GetFeatureCount() == A.GetFeatureCount(), \ + ('Layer.Erase returned ' + str(C.GetFeatureCount()) + ' features') A.ResetReading() feat_a = A.GetNextFeature() feat_c = C.GetNextFeature() if feat_a.Equal(feat_c) != 0: - gdaltest.post_reason('features not identical') feat_a.DumpReadable() feat_c.DumpReadable() - return 'fail' + pytest.fail('features not identical') recreate_layer_C() A.Erase(empty, C, options=['PROMOTE_TO_MULTI=YES']) - if C.GetFeatureCount() != A.GetFeatureCount(): - gdaltest.post_reason('Layer.Erase returned ' + str(C.GetFeatureCount()) + ' features') - return 'fail' + assert C.GetFeatureCount() == A.GetFeatureCount(), \ + ('Layer.Erase returned ' + str(C.GetFeatureCount()) + ' features') recreate_layer_C() - return 'success' - -def algebra_cleanup(): +def test_algebra_cleanup(): if not ogrtest.have_geos(): - return 'skip' + pytest.skip() global ds, A, B, C, pointInB, D1, D2, empty @@ -699,26 +589,5 @@ def algebra_cleanup(): empty = None ds = None - return 'success' - - -gdaltest_list = [ - algebra_setup, - algebra_intersection, - algebra_KEEP_LOWER_DIMENSION_GEOMETRIES, - algebra_union, - algebra_symdifference, - algebra_identify, - algebra_update, - algebra_clip, - algebra_erase, - algebra_cleanup, -] - -if __name__ == '__main__': - - gdaltest.setup_run('algebra') - gdaltest.run_tests(gdaltest_list) - sys.exit(gdaltest.summarize()) diff --git a/autotest/ogr/ogr_libkml.py b/autotest/ogr/ogr_libkml.py index 64b830803e90..bfca09c9a46c 100755 --- a/autotest/ogr/ogr_libkml.py +++ b/autotest/ogr/ogr_libkml.py @@ -29,22 +29,21 @@ # DEALINGS IN THE SOFTWARE. ############################################################################### -import sys -sys.path.append('../pymod') import gdaltest import ogrtest from osgeo import ogr from osgeo import osr from osgeo import gdal +import pytest ############################################################################### # Test basic open operation for KML datastore. # -def ogr_libkml_datastore(): +def test_ogr_libkml_datastore(): ogrtest.kml_ds = None ogrtest.have_read_libkml = 0 @@ -53,7 +52,7 @@ def ogr_libkml_datastore(): ogrtest.kml_drv = ogr.GetDriverByName('LIBKML') if ogrtest.kml_drv is None: - return 'skip' + pytest.skip() ogrtest.kml_drv = ogr.GetDriverByName('KML') # Unregister KML driver if present as its behaviour is not identical @@ -67,162 +66,116 @@ def ogr_libkml_datastore(): ogrtest.have_read_libkml = 1 if not ogrtest.have_read_libkml: - return 'skip' + pytest.skip() - if ogrtest.kml_ds.GetLayerCount() != 10: - gdaltest.post_reason('wrong number of layers') - print(ogrtest.kml_ds.GetLayerCount()) - return 'fail' - - return 'success' + assert ogrtest.kml_ds.GetLayerCount() == 10, 'wrong number of layers' ############################################################################### # Test reading attributes for first layer (point). # -def ogr_libkml_attributes_1(): +def test_ogr_libkml_attributes_1(): if not ogrtest.have_read_libkml: - return 'skip' + pytest.skip() - if ogrtest.kml_ds is None: - gdaltest.post_reason('libkml_ds is none') - return 'fail' + assert ogrtest.kml_ds is not None, 'libkml_ds is none' lyr = ogrtest.kml_ds.GetLayerByName('Placemarks') feat = lyr.GetNextFeature() - if feat.GetField('Name') != 'Simple placemark': - gdaltest.post_reason('Wrong name field value') - return 'fail' + assert feat.GetField('Name') == 'Simple placemark', 'Wrong name field value' if feat.GetField('description')[:23] != 'Attached to the ground.': - gdaltest.post_reason('Wrong description field value') print('got: ', feat.GetField('description')[:23]) - return 'fail' + pytest.fail('Wrong description field value') feat = lyr.GetNextFeature() - if feat is None: - gdaltest.post_reason('expected feature not found.') - return 'fail' + assert feat is not None, 'expected feature not found.' - if feat.GetField('Name') != 'Floating placemark': - gdaltest.post_reason('Wrong name field value') - return 'fail' + assert feat.GetField('Name') == 'Floating placemark', 'Wrong name field value' if feat.GetField('description')[:25] != 'Floats a defined distance': - gdaltest.post_reason('Wrong description field value') print('got: ', feat.GetField('description')[:25]) - return 'fail' + pytest.fail('Wrong description field value') feat = lyr.GetNextFeature() - if feat is None: - gdaltest.post_reason('expected feature not found.') - return 'fail' + assert feat is not None, 'expected feature not found.' - if feat.GetField('Name') != 'Extruded placemark': - gdaltest.post_reason('Wrong name field value') - return 'fail' + assert feat.GetField('Name') == 'Extruded placemark', 'Wrong name field value' if feat.GetField('description') != 'Tethered to the ground by a customizable\n \"tail\"': - gdaltest.post_reason('Wrong description field value') print('got: ', feat.GetField('description')) - return 'fail' - - return 'success' + pytest.fail('Wrong description field value') + ############################################################################### # Test reading attributes for another layer (point). # -def ogr_libkml_attributes_2(): +def test_ogr_libkml_attributes_2(): if not ogrtest.have_read_libkml: - return 'skip' + pytest.skip() - if ogrtest.kml_ds is None: - gdaltest.post_reason('libkml_ds is none') - return 'fail' + assert ogrtest.kml_ds is not None, 'libkml_ds is none' lyr = ogrtest.kml_ds.GetLayerByName('Highlighted Icon') feat = lyr.GetNextFeature() - if feat.GetField('Name') != 'Roll over this icon': - gdaltest.post_reason('Wrong name field value') - return 'fail' + assert feat.GetField('Name') == 'Roll over this icon', 'Wrong name field value' if feat.GetField('description') is not None: - gdaltest.post_reason('Wrong description field value') print("'%s'" % feat.GetField('description')) - return 'fail' + pytest.fail('Wrong description field value') feat = lyr.GetNextFeature() - if feat is not None: - gdaltest.post_reason('unexpected feature found.') - return 'fail' - - return 'success' + assert feat is None, 'unexpected feature found.' ############################################################################### # Test reading attributes for another layer (linestring). # -def ogr_libkml_attributes_3(): +def test_ogr_libkml_attributes_3(): if not ogrtest.have_read_libkml: - return 'skip' + pytest.skip() - if ogrtest.kml_ds is None: - gdaltest.post_reason('libkml_ds is none') - return 'fail' + assert ogrtest.kml_ds is not None, 'libkml_ds is none' lyr = ogrtest.kml_ds.GetLayerByName('Paths') feat = lyr.GetNextFeature() - if feat.GetField('Name') != 'Tessellated': - gdaltest.post_reason('Wrong name field value') - return 'fail' + assert feat.GetField('Name') == 'Tessellated', 'Wrong name field value' - if feat.GetField('description') != 'If the <tessellate> tag has a value of 1, the line will contour to the underlying terrain': - gdaltest.post_reason('Wrong description field value') - return 'fail' + assert feat.GetField('description') == 'If the <tessellate> tag has a value of 1, the line will contour to the underlying terrain', \ + 'Wrong description field value' feat = lyr.GetNextFeature() - if feat is None: - gdaltest.post_reason('expected feature not found.') - return 'fail' + assert feat is not None, 'expected feature not found.' - if feat.GetField('Name') != 'Untessellated': - gdaltest.post_reason('Wrong name field value') - return 'fail' + assert feat.GetField('Name') == 'Untessellated', 'Wrong name field value' - if feat.GetField('description') != 'If the <tessellate> tag has a value of 0, the line follow a simple straight-line path from point to point': - gdaltest.post_reason('Wrong description field value') - return 'fail' + assert feat.GetField('description') == 'If the <tessellate> tag has a value of 0, the line follow a simple straight-line path from point to point', \ + 'Wrong description field value' feat = lyr.GetNextFeature() - if feat is None: - gdaltest.post_reason('expected feature not found.') - return 'fail' - - return 'success' + assert feat is not None, 'expected feature not found.' ############################################################################### # Test reading attributes for another layer (polygon). # -def ogr_libkml_attributes_4(): +def test_ogr_libkml_attributes_4(): if not ogrtest.have_read_libkml: - return 'skip' + pytest.skip() - if ogrtest.kml_ds is None: - gdaltest.post_reason('libkml_ds is none') - return 'fail' + assert ogrtest.kml_ds is not None, 'libkml_ds is none' lyr = ogrtest.kml_ds.GetLayerByName('Google Campus') feat = lyr.GetNextFeature() @@ -231,32 +184,26 @@ def ogr_libkml_attributes_4(): while feat is not None: name = 'Building %d' % i if feat.GetField('Name') != name: - gdaltest.post_reason('Wrong name field value') print('Got: "%s"' % feat.GetField('name')) - return 'fail' + pytest.fail('Wrong name field value') - if feat.GetField('description') is not None: - gdaltest.post_reason('Wrong description field value') - return 'fail' + assert feat.GetField('description') is None, 'Wrong description field value' i = i + 1 feat = lyr.GetNextFeature() - return 'success' - + ############################################################################### # Test reading of KML point geometry # -def ogr_libkml_point_read(): +def test_ogr_libkml_point_read(): if not ogrtest.have_read_libkml: - return 'skip' + pytest.skip() - if ogrtest.kml_ds is None: - gdaltest.post_reason('libkml_ds is none') - return 'fail' + assert ogrtest.kml_ds is not None, 'libkml_ds is none' lyr = ogrtest.kml_ds.GetLayerByName('Placemarks') lyr.ResetReading() @@ -264,123 +211,89 @@ def ogr_libkml_point_read(): wkt = 'POINT(-122.0822035425683 37.42228990140251)' - if ogrtest.check_feature_geometry(feat, wkt): - return 'fail' + assert not ogrtest.check_feature_geometry(feat, wkt) feat = lyr.GetNextFeature() - if feat is None: - gdaltest.post_reason('expected feature not found.') - return 'fail' + assert feat is not None, 'expected feature not found.' wkt = 'POINT(-122.084075 37.4220033612141 50)' - if ogrtest.check_feature_geometry(feat, wkt): - return 'fail' + assert not ogrtest.check_feature_geometry(feat, wkt) feat = lyr.GetNextFeature() - if feat is None: - gdaltest.post_reason('expected feature not found.') - return 'fail' + assert feat is not None, 'expected feature not found.' wkt = 'POINT(-122.0857667006183 37.42156927867553 50)' - if ogrtest.check_feature_geometry(feat, wkt): - return 'fail' - - return 'success' + assert not ogrtest.check_feature_geometry(feat, wkt) ############################################################################### # Test reading of KML linestring geometry # -def ogr_libkml_linestring_read(): +def test_ogr_libkml_linestring_read(): if not ogrtest.have_read_libkml: - return 'skip' + pytest.skip() - if ogrtest.kml_ds is None: - gdaltest.post_reason('libkml_ds is none') - return 'fail' + assert ogrtest.kml_ds is not None, 'libkml_ds is none' lyr = ogrtest.kml_ds.GetLayerByName('Paths') lyr.ResetReading() feat = lyr.GetNextFeature() wkt = 'LINESTRING (-112.081423783034495 36.106778704771372 0, -112.087026775269294 36.0905099328766 0)' - if ogrtest.check_feature_geometry(feat, wkt): - return 'fail' + assert not ogrtest.check_feature_geometry(feat, wkt) feat = lyr.GetNextFeature() - if feat is None: - gdaltest.post_reason('expected feature not found.') - return 'fail' + assert feat is not None, 'expected feature not found.' wkt = 'LINESTRING (-112.080622229594994 36.106734600079953 0,-112.085242575314993 36.090495986124218 0)' - if ogrtest.check_feature_geometry(feat, wkt): - return 'fail' + assert not ogrtest.check_feature_geometry(feat, wkt) feat = lyr.GetNextFeature() - if feat is None: - gdaltest.post_reason('expected feature not found.') - return 'fail' + assert feat is not None, 'expected feature not found.' wkt = 'LINESTRING (-112.265654928602004 36.094476726025462 2357,-112.266038452823807 36.093426088386707 2357,-112.266813901345301 36.092510587768807 2357,-112.267782683444494 36.091898273579957 2357,-112.268855751095202 36.091313794118697 2357,-112.269481071721899 36.090367720752099 2357,-112.269526855561097 36.089321714872852 2357,-112.269014456727604 36.088509160604723 2357,-112.268152881533894 36.087538135979557 2357,-112.2670588176031 36.086826852625677 2357,-112.265737458732104 36.086463123013033 2357)' - if ogrtest.check_feature_geometry(feat, wkt): - return 'fail' - - return 'success' + assert not ogrtest.check_feature_geometry(feat, wkt) ############################################################################### # Test reading of KML polygon geometry # -def ogr_libkml_polygon_read(): +def test_ogr_libkml_polygon_read(): if not ogrtest.have_read_libkml: - return 'skip' + pytest.skip() - if ogrtest.kml_ds is None: - gdaltest.post_reason('libkml_ds is none') - return 'fail' + assert ogrtest.kml_ds is not None, 'libkml_ds is none' lyr = ogrtest.kml_ds.GetLayerByName('Google Campus') lyr.ResetReading() feat = lyr.GetNextFeature() wkt = 'POLYGON ((-122.084893845961204 37.422571240447859 17,-122.084958097919795 37.422119226268563 17,-122.084746957304702 37.42207183952619 17,-122.084572538096197 37.422090067296757 17,-122.084595488672306 37.422159327008949 17,-122.0838521118269 37.422272785643713 17,-122.083792243334997 37.422035391120843 17,-122.0835076656616 37.422090069571063 17,-122.083470946415204 37.422009873951609 17,-122.083122108574798 37.422104649494599 17,-122.082924737457205 37.422265039903863 17,-122.082933916938501 37.422312428430942 17,-122.083383735973698 37.422250460876178 17,-122.083360785424802 37.422341592287452 17,-122.083420455164202 37.42237075460644 17,-122.083659133885007 37.422512920110009 17,-122.083975843895203 37.422658730937812 17,-122.084237474333094 37.422651439725207 17,-122.0845036949503 37.422651438643499 17,-122.0848020460801 37.422611339163147 17,-122.084788275051494 37.422563950551208 17,-122.084893845961204 37.422571240447859 17))' - if ogrtest.check_feature_geometry(feat, wkt): - return 'fail' + assert not ogrtest.check_feature_geometry(feat, wkt) feat = lyr.GetNextFeature() - if feat is None: - gdaltest.post_reason('expected feature not found.') - return 'fail' + assert feat is not None, 'expected feature not found.' wkt = 'POLYGON ((-122.085741277148301 37.422270331552568 17,-122.085816976848093 37.422314088323461 17,-122.085852582875006 37.422303374697442 17,-122.085879994563896 37.422256861387893 17,-122.085886010140896 37.422231107613797 17,-122.085806915728796 37.422202501738553 17,-122.085837954265301 37.42214027058678 17,-122.085673264051906 37.422086902144081 17,-122.085602292640701 37.42214885429042 17,-122.085590277843593 37.422128290487002 17,-122.085584167223701 37.422081719672462 17,-122.085485206574106 37.42210455874995 17,-122.085506726435199 37.422142679498243 17,-122.085443071291493 37.422127838461719 17,-122.085099071490404 37.42251282407603 17,-122.085676981863202 37.422818153236513 17,-122.086016227378295 37.422449188587223 17,-122.085726032700407 37.422292396042529 17,-122.085741277148301 37.422270331552568 17))' - if ogrtest.check_feature_geometry(feat, wkt): - return 'fail' + assert not ogrtest.check_feature_geometry(feat, wkt) feat = lyr.GetNextFeature() - if feat is None: - gdaltest.post_reason('expected feature not found.') - return 'fail' + assert feat is not None, 'expected feature not found.' wkt = 'POLYGON ((-122.085786228724203 37.421362088869692 25,-122.085731299060299 37.421369359894811 25,-122.085731299291794 37.421409349109027 25,-122.085607707367899 37.421383901665649 25,-122.085580242651602 37.42137299550869 25,-122.085218622197104 37.421372995043157 25,-122.085227776563897 37.421616565082651 25,-122.085259818934702 37.421605658944031 25,-122.085259818549901 37.421682001560001 25,-122.085236931147804 37.421700178603459 25,-122.085264395782801 37.421761979825753 25,-122.085323903274599 37.421761980139067 25,-122.085355945432397 37.421852864451999 25,-122.085410875246296 37.421889218237339 25,-122.085479537935697 37.42189285337048 25,-122.085543622981902 37.421889217975462 25,-122.085626017804202 37.421860134999257 25,-122.085937287963006 37.421860134536047 25,-122.085942871866607 37.42160898590042 25,-122.085965546986102 37.421579927591438 25,-122.085864046234093 37.421471150029568 25,-122.0858548911215 37.421405713261841 25,-122.085809116276806 37.4214057134039 25,-122.085786228724203 37.421362088869692 25))' - if ogrtest.check_feature_geometry(feat, wkt): - return 'fail' + assert not ogrtest.check_feature_geometry(feat, wkt) feat = lyr.GetNextFeature() - if feat is None: - gdaltest.post_reason('expected feature not found.') - return 'fail' + assert feat is not None, 'expected feature not found.' wkt = 'POLYGON ((-122.084437112828397 37.421772530030907 19,-122.084511885574599 37.421911115428962 19,-122.0850470999805 37.421787551215353 19,-122.085071991339106 37.421436630231611 19,-122.084916406231997 37.421372378221157 19,-122.084219386816699 37.421372378016258 19,-122.084219386589993 37.421476171614962 19,-122.083808641999099 37.4214613409357 19,-122.083789972856394 37.421313064107963 19,-122.083279653469802 37.421293288405927 19,-122.083260981920702 37.421392139442979 19,-122.082937362173695 37.421372363998763 19,-122.082906242566693 37.421515697788713 19,-122.082850226966499 37.421762825764652 19,-122.082943578863507 37.421767769696352 19,-122.083217411188002 37.421792485526858 19,-122.0835970430103 37.421748007445601 19,-122.083945555677104 37.421693642376027 19,-122.084007789463698 37.421762838158529 19,-122.084113587521003 37.421748011043917 19,-122.084076247378405 37.421713412923751 19,-122.084144704773905 37.421678815345693 19,-122.084144704222993 37.421817206601972 19,-122.084250333307395 37.421817070044597 19,-122.084437112828397 37.421772530030907 19))' - if ogrtest.check_feature_geometry(feat, wkt): - return 'fail' - - return 'success' + assert not ogrtest.check_feature_geometry(feat, wkt) ############################################################################### # Write test @@ -389,7 +302,7 @@ def ogr_libkml_polygon_read(): def ogr_libkml_write(filename): if ogrtest.kml_drv is None: - return 'skip' + pytest.skip() ds = ogr.GetDriverByName('LIBKML').CreateDataSource(filename) @@ -400,13 +313,9 @@ def ogr_libkml_write(filename): dst_feat = ogr.Feature(lyr.GetLayerDefn()) dst_feat.SetGeometry(ogr.CreateGeometryFromWkt('POINT (2 49)')) - if lyr.CreateFeature(dst_feat) != 0: - gdaltest.post_reason('CreateFeature failed.') - return 'fail' - if dst_feat.GetGeometryRef().ExportToWkt() != 'POINT (2 49)': - print(dst_feat.GetGeometryRef().ExportToWkt()) - gdaltest.post_reason('CreateFeature changed the geometry.') - return 'fail' + assert lyr.CreateFeature(dst_feat) == 0, 'CreateFeature failed.' + assert dst_feat.GetGeometryRef().ExportToWkt() == 'POINT (2 49)', \ + 'CreateFeature changed the geometry.' lyr = ds.CreateLayer('test_wgs84') @@ -422,56 +331,38 @@ def ogr_libkml_write(filename): dst_feat.SetField('description', 'my_description') dst_feat.SetField('foo', 'bar') dst_feat.SetGeometry(ogr.CreateGeometryFromWkt('POINT (2 49)')) - if lyr.CreateFeature(dst_feat) != 0: - gdaltest.post_reason('CreateFeature failed.') - return 'fail' + assert lyr.CreateFeature(dst_feat) == 0, 'CreateFeature failed.' dst_feat = ogr.Feature(lyr.GetLayerDefn()) dst_feat.SetGeometry(ogr.CreateGeometryFromWkt('POINT (2 49 1)')) - if lyr.CreateFeature(dst_feat) != 0: - gdaltest.post_reason('CreateFeature failed.') - return 'fail' + assert lyr.CreateFeature(dst_feat) == 0, 'CreateFeature failed.' dst_feat = ogr.Feature(lyr.GetLayerDefn()) dst_feat.SetGeometry(ogr.CreateGeometryFromWkt('LINESTRING (0 1,2 3)')) - if lyr.CreateFeature(dst_feat) != 0: - gdaltest.post_reason('CreateFeature failed.') - return 'fail' + assert lyr.CreateFeature(dst_feat) == 0, 'CreateFeature failed.' dst_feat = ogr.Feature(lyr.GetLayerDefn()) dst_feat.SetGeometry(ogr.CreateGeometryFromWkt('POLYGON ((0 0 0,0 1 0,1 1 0,1 0 0,0 0 0),(0.25 0.25 0,0.25 0.75 0,0.75 0.75 0,0.75 0.25 0,0.25 0.25 0))')) - if lyr.CreateFeature(dst_feat) != 0: - gdaltest.post_reason('CreateFeature failed.') - return 'fail' + assert lyr.CreateFeature(dst_feat) == 0, 'CreateFeature failed.' dst_feat = ogr.Feature(lyr.GetLayerDefn()) dst_feat.SetGeometry(ogr.CreateGeometryFromWkt('MULTIPOINT (2 49,2 49)')) - if lyr.CreateFeature(dst_feat) != 0: - gdaltest.post_reason('CreateFeature failed.') - return 'fail' + assert lyr.CreateFeature(dst_feat) == 0, 'CreateFeature failed.' dst_feat = ogr.Feature(lyr.GetLayerDefn()) dst_feat.SetGeometry(ogr.CreateGeometryFromWkt('MULTILINESTRING ((0 1,2 3),(0 1,2 3))')) - if lyr.CreateFeature(dst_feat) != 0: - gdaltest.post_reason('CreateFeature failed.') - return 'fail' + assert lyr.CreateFeature(dst_feat) == 0, 'CreateFeature failed.' dst_feat = ogr.Feature(lyr.GetLayerDefn()) dst_feat.SetGeometry(ogr.CreateGeometryFromWkt('MULTIPOLYGON (((0 0 0,0 1 0,1 1 0,1 0 0,0 0 0),(0.25 0.25 0,0.25 0.75 0,0.75 0.75 0,0.75 0.25 0,0.25 0.25 0)),((-0.25 0.25 0,-0.25 0.75 0,-0.75 0.75 0,-0.75 0.25 0,-0.25 0.25 0)))')) - if lyr.CreateFeature(dst_feat) != 0: - gdaltest.post_reason('CreateFeature failed.') - return 'fail' + assert lyr.CreateFeature(dst_feat) == 0, 'CreateFeature failed.' dst_feat = ogr.Feature(lyr.GetLayerDefn()) dst_feat.SetGeometry(ogr.CreateGeometryFromWkt('GEOMETRYCOLLECTION (POINT (2 49 1),LINESTRING (0 1,2 3))')) - if lyr.CreateFeature(dst_feat) != 0: - gdaltest.post_reason('CreateFeature failed.') - return 'fail' + assert lyr.CreateFeature(dst_feat) == 0, 'CreateFeature failed.' ds = None - return 'success' - ############################################################################### # Check previous test @@ -479,118 +370,89 @@ def ogr_libkml_write(filename): def ogr_libkml_check_write(filename): if not ogrtest.have_read_libkml: - return 'skip' + pytest.skip() ds = ogr.Open(filename) if filename != '/vsimem/libkml_use_doc_off.kmz': lyr = ds.GetLayerByName('test_wgs84') else: lyr = ds.GetLayer(0) - if lyr.GetFeatureCount() != 8: - gdaltest.post_reason('Bad feature count.') - return 'fail' + assert lyr.GetFeatureCount() == 8, 'Bad feature count.' feat = lyr.GetNextFeature() - if feat.GetField('name') != 'my_name': - print(feat.GetField('name')) - gdaltest.post_reason('Unexpected name.') - return 'fail' - if feat.GetField('description') != 'my_description': - print(feat.GetField('description')) - gdaltest.post_reason('Unexpected description.') - return 'fail' - if feat.GetField('foo') != 'bar': - print(feat.GetField('foo')) - gdaltest.post_reason('Unexpected foo.') - return 'fail' - if feat.GetGeometryRef().ExportToWkt() != 'POINT (2 49 0)': - print(feat.GetGeometryRef().ExportToWkt()) - gdaltest.post_reason('Unexpected geometry.') - return 'fail' + assert feat.GetField('name') == 'my_name', 'Unexpected name.' + assert feat.GetField('description') == 'my_description', 'Unexpected description.' + assert feat.GetField('foo') == 'bar', 'Unexpected foo.' + assert feat.GetGeometryRef().ExportToWkt() == 'POINT (2 49 0)', \ + 'Unexpected geometry.' feat = lyr.GetNextFeature() - if feat.GetGeometryRef().ExportToWkt() != 'POINT (2 49 1)': - print(feat.GetGeometryRef().ExportToWkt()) - gdaltest.post_reason('Unexpected geometry.') - return 'fail' + assert feat.GetGeometryRef().ExportToWkt() == 'POINT (2 49 1)', \ + 'Unexpected geometry.' feat = lyr.GetNextFeature() - if feat.GetGeometryRef().ExportToWkt() != 'LINESTRING (0 1 0,2 3 0)': - print(feat.GetGeometryRef().ExportToWkt()) - gdaltest.post_reason('Unexpected geometry.') - return 'fail' + assert feat.GetGeometryRef().ExportToWkt() == 'LINESTRING (0 1 0,2 3 0)', \ + 'Unexpected geometry.' feat = lyr.GetNextFeature() - if feat.GetGeometryRef().ExportToWkt() != 'POLYGON ((0 0 0,0 1 0,1 1 0,1 0 0,0 0 0),(0.25 0.25 0,0.25 0.75 0,0.75 0.75 0,0.75 0.25 0,0.25 0.25 0))': - print(feat.GetGeometryRef().ExportToWkt()) - gdaltest.post_reason('Unexpected geometry.') - return 'fail' + assert feat.GetGeometryRef().ExportToWkt() == 'POLYGON ((0 0 0,0 1 0,1 1 0,1 0 0,0 0 0),(0.25 0.25 0,0.25 0.75 0,0.75 0.75 0,0.75 0.25 0,0.25 0.25 0))', \ + 'Unexpected geometry.' feat = lyr.GetNextFeature() - if feat.GetGeometryRef().ExportToWkt() != 'MULTIPOINT (2 49 0,2 49 0)': - print(feat.GetGeometryRef().ExportToWkt()) - gdaltest.post_reason('Unexpected geometry.') - return 'fail' + assert feat.GetGeometryRef().ExportToWkt() == 'MULTIPOINT (2 49 0,2 49 0)', \ + 'Unexpected geometry.' feat = lyr.GetNextFeature() - if feat.GetGeometryRef().ExportToWkt() != 'MULTILINESTRING ((0 1 0,2 3 0),(0 1 0,2 3 0))': - print(feat.GetGeometryRef().ExportToWkt()) - gdaltest.post_reason('Unexpected geometry.') - return 'fail' + assert feat.GetGeometryRef().ExportToWkt() == 'MULTILINESTRING ((0 1 0,2 3 0),(0 1 0,2 3 0))', \ + 'Unexpected geometry.' feat = lyr.GetNextFeature() - if feat.GetGeometryRef().ExportToWkt() != 'MULTIPOLYGON (((0 0 0,0 1 0,1 1 0,1 0 0,0 0 0),(0.25 0.25 0,0.25 0.75 0,0.75 0.75 0,0.75 0.25 0,0.25 0.25 0)),((-0.25 0.25 0,-0.25 0.75 0,-0.75 0.75 0,-0.75 0.25 0,-0.25 0.25 0)))': - print(feat.GetGeometryRef().ExportToWkt()) - gdaltest.post_reason('Unexpected geometry.') - return 'fail' + assert feat.GetGeometryRef().ExportToWkt() == 'MULTIPOLYGON (((0 0 0,0 1 0,1 1 0,1 0 0,0 0 0),(0.25 0.25 0,0.25 0.75 0,0.75 0.75 0,0.75 0.25 0,0.25 0.25 0)),((-0.25 0.25 0,-0.25 0.75 0,-0.75 0.75 0,-0.75 0.25 0,-0.25 0.25 0)))', \ + 'Unexpected geometry.' feat = lyr.GetNextFeature() - if feat.GetGeometryRef().ExportToWkt() != 'GEOMETRYCOLLECTION (POINT (2 49 1),LINESTRING (0 1 0,2 3 0))': - print(feat.GetGeometryRef().ExportToWkt()) - gdaltest.post_reason('Unexpected geometry.') - return 'fail' + assert feat.GetGeometryRef().ExportToWkt() == 'GEOMETRYCOLLECTION (POINT (2 49 1),LINESTRING (0 1 0,2 3 0))', \ + 'Unexpected geometry.' ds = None - return 'success' - ############################################################################### -def ogr_libkml_write_kml(): +def test_ogr_libkml_write_kml(): return ogr_libkml_write('/vsimem/libkml.kml') -def ogr_libkml_check_write_kml(): +def test_ogr_libkml_check_write_kml(): return ogr_libkml_check_write('/vsimem/libkml.kml') -def ogr_libkml_write_kmz(): +def test_ogr_libkml_write_kmz(): return ogr_libkml_write('/vsimem/libkml.kmz') -def ogr_libkml_check_write_kmz(): +def test_ogr_libkml_check_write_kmz(): return ogr_libkml_check_write('/vsimem/libkml.kmz') -def ogr_libkml_write_kmz_use_doc_off(): +def test_ogr_libkml_write_kmz_use_doc_off(): gdal.SetConfigOption("LIBKML_USE_DOC.KML", "NO") ret = ogr_libkml_write('/vsimem/libkml_use_doc_off.kmz') gdal.SetConfigOption("LIBKML_USE_DOC.KML", None) return ret -def ogr_libkml_check_write_kmz_use_doc_off(): +def test_ogr_libkml_check_write_kmz_use_doc_off(): return ogr_libkml_check_write('/vsimem/libkml_use_doc_off.kmz') -def ogr_libkml_write_dir(): +def test_ogr_libkml_write_dir(): return ogr_libkml_write('/vsimem/libkmldir') -def ogr_libkml_check_write_dir(): +def test_ogr_libkml_check_write_dir(): if not ogrtest.have_read_libkml: - return 'skip' + pytest.skip() ret = ogr_libkml_check_write('/vsimem/libkmldir') files = gdal.ReadDir('/vsimem/libkmldir') @@ -604,10 +466,10 @@ def ogr_libkml_check_write_dir(): # -def ogr_libkml_xml_attributes(): +def test_ogr_libkml_xml_attributes(): if not ogrtest.have_read_libkml: - return 'skip' + pytest.skip() ds = ogr.Open('data/description_with_xml.kml') @@ -615,23 +477,20 @@ def ogr_libkml_xml_attributes(): feat = lyr.GetNextFeature() if feat.GetField('description').find('Description<br></br><i attr="val">Interesting</i><br></br>') != 0: - gdaltest.post_reason('Wrong description field value') print('got: %s ' % feat.GetField('description')) - return 'fail' + pytest.fail('Wrong description field value') ds = None - return 'success' - ############################################################################### # Test reading all geometry types (#3558) # -def ogr_libkml_read_geometries(): +def test_ogr_libkml_read_geometries(): if not ogrtest.have_read_libkml: - return 'skip' + pytest.skip() ds = ogr.Open('data/geometries.kml') @@ -642,97 +501,72 @@ def ogr_libkml_read_geometries(): ds = None - return 'success' - ############################################################################### # Run test_ogrsf -def ogr_libkml_test_ogrsf(): +def test_ogr_libkml_test_ogrsf(): if not ogrtest.have_read_libkml: - return 'skip' + pytest.skip() import test_cli_utilities if test_cli_utilities.get_test_ogrsf_path() is None: - return 'skip' + pytest.skip() ret = gdaltest.runexternal(test_cli_utilities.get_test_ogrsf_path() + ' --config OGR_SKIP KML -ro data/samples.kml') - if ret.find("using driver `LIBKML'") == -1 or ret.find('INFO') == -1 or ret.find('ERROR') != -1: - print(ret) - return 'fail' - - return 'success' + assert not (ret.find("using driver `LIBKML'") == -1 or ret.find('INFO') == -1 or ret.find('ERROR') != -1) ############################################################################### # Test reading KML with only Placemark -def ogr_libkml_read_placemark(): +def test_ogr_libkml_read_placemark(): if not ogrtest.have_read_libkml: - return 'skip' + pytest.skip() ds = ogr.Open('data/placemark.kml') lyr = ds.GetLayer(0) feat = lyr.GetNextFeature() - if feat is None: - return 'fail' + assert feat is not None ds = None - return 'success' - ############################################################################### # Test reading KML without any layer -def ogr_libkml_read_empty(): +def test_ogr_libkml_read_empty(): if not ogrtest.have_read_libkml: - return 'skip' + pytest.skip() ds = ogr.Open('data/empty.kml') - if ds.GetLayerCount() != 0: - gdaltest.post_reason('failed') - print(ds.GetLayerCount()) - return 'fail' + assert ds.GetLayerCount() == 0 ds = None - return 'success' - ############################################################################### # Test reading KML with empty layers -def ogr_libkml_read_emptylayers(): +def test_ogr_libkml_read_emptylayers(): if not ogrtest.have_read_libkml: - return 'skip' + pytest.skip() ds = ogr.Open('data/emptylayers.kml') - if ds.GetLayerCount() != 2: - gdaltest.post_reason('failed') - print(ds.GetLayerCount()) - return 'fail' + assert ds.GetLayerCount() == 2 # --> One difference with the old KML driver - if ds.GetLayer(0).GetFeatureCount() != 1: - gdaltest.post_reason('failed') - print(ds.GetLayer(0).GetFeatureCount()) - return 'fail' + assert ds.GetLayer(0).GetFeatureCount() == 1 - if ds.GetLayer(1).GetFeatureCount() != 0: - gdaltest.post_reason('failed') - print(ds.GetLayer(1).GetFeatureCount()) - return 'fail' + assert ds.GetLayer(1).GetFeatureCount() == 0 ds = None - return 'success' - ############################################################################### # Test reading KML with empty layers @@ -740,114 +574,90 @@ def ogr_libkml_read_emptylayers(): # Test reading KML with empty layers without folder -def ogr_libkml_read_emptylayers_without_folder(): +def test_ogr_libkml_read_emptylayers_without_folder(): if not ogrtest.have_read_libkml: - return 'skip' + pytest.skip() ds = ogr.Open('data/emptylayers_without_folder.kml') - if ds.GetLayerCount() != 1: - gdaltest.post_reason('failed') - print(ds.GetLayerCount()) - return 'fail' + assert ds.GetLayerCount() == 1 # --> One difference with the old KML driver - if ds.GetLayer(0).GetName() != 'Test': - gdaltest.post_reason('failed') - print("Layer name must be '" + ds.GetLayer(0).GetName() + "'.") - return 'fail' + assert ds.GetLayer(0).GetName() == 'Test', \ + ("Layer name must be '" + ds.GetLayer(0).GetName() + "'.") ds = None - return 'success' - ############################################################################### # Test reading KML with empty layers without_folder -def ogr_libkml_read_schema(): +def test_ogr_libkml_read_schema(): if not ogrtest.have_read_libkml: - return 'skip' + pytest.skip() ds = ogr.Open('data/test_schema.kml') - if ds.GetLayerCount() != 4: - gdaltest.post_reason('failed') - print(ds.GetLayerCount()) - return 'fail' + assert ds.GetLayerCount() == 4 lyr = ds.GetLayer(0) feat = lyr.GetNextFeature() if feat.GetField('foo') != 'bar': - gdaltest.post_reason('failed') feat.DumpReadable() - return 'fail' + pytest.fail() lyr = ds.GetLayer(1) feat = lyr.GetNextFeature() if feat.GetField('foo') != 'baz': - gdaltest.post_reason('failed') feat.DumpReadable() - return 'fail' + pytest.fail() lyr = ds.GetLayer(2) - if lyr.GetLayerDefn().GetFieldIndex('foo') != -1: - gdaltest.post_reason('failed') - return 'fail' + assert lyr.GetLayerDefn().GetFieldIndex('foo') == -1 lyr = ds.GetLayer(3) - if lyr.GetLayerDefn().GetFieldIndex('foo') != -1: - gdaltest.post_reason('failed') - return 'fail' + assert lyr.GetLayerDefn().GetFieldIndex('foo') == -1 ds = None - return 'success' - ############################################################################### # Test reading KML with <Data> elements of <ExtendedData> in case # <ExtendedData> doesn't use a <SchemaData> (test changeset r22127) -def ogr_libkml_extended_data_without_schema_data(): +def test_ogr_libkml_extended_data_without_schema_data(): if not ogrtest.have_read_libkml: - return 'skip' + pytest.skip() ds = ogr.Open('data/extended_data_without_schema_data.kml') lyr = ds.GetLayer(0) feat = lyr.GetNextFeature() if feat.GetField('field1') != '1_1': - gdaltest.post_reason('failed') feat.DumpReadable() - return 'fail' + pytest.fail() if feat.GetField('field2') != '1_2': - gdaltest.post_reason('failed') feat.DumpReadable() - return 'fail' + pytest.fail() feat = lyr.GetNextFeature() if feat.GetField('field1') != '2_1': - gdaltest.post_reason('failed') feat.DumpReadable() - return 'fail' + pytest.fail() if feat.IsFieldSet('field2'): - gdaltest.post_reason('failed') feat.DumpReadable() - return 'fail' + pytest.fail() ds = None - return 'success' - ############################################################################### # Test reading KML with <gx:Track> element (#5095) -def ogr_libkml_gxtrack(): +def test_ogr_libkml_gxtrack(): if not ogrtest.have_read_libkml: - return 'skip' + pytest.skip() ds = ogr.Open('data/gxtrack.kml') lyr = ds.GetLayer(0) @@ -857,20 +667,17 @@ def ogr_libkml_gxtrack(): feat.GetField('end') != '2013/05/28 13:00:00' or \ feat.GetGeometryRef().ExportToWkt() != 'LINESTRING (2 49,3 50)': feat.DumpReadable() - gdaltest.post_reason('failure') - return 'fail' + pytest.fail() ds = None - return 'success' - ############################################################################### # Test reading KML with <gx:MultiTrack> element -def ogr_libkml_gxmultitrack(): +def test_ogr_libkml_gxmultitrack(): if not ogrtest.have_read_libkml: - return 'skip' + pytest.skip() ds = ogr.Open('data/gxmultitrack.kml') lyr = ds.GetLayer(0) @@ -880,20 +687,17 @@ def ogr_libkml_gxmultitrack(): feat.GetField('end') != '2013/05/28 13:00:00' or \ feat.GetGeometryRef().ExportToWkt() != 'MULTILINESTRING ((2 49,3 50))': feat.DumpReadable() - gdaltest.post_reason('failure') - return 'fail' + pytest.fail() ds = None - return 'success' - ############################################################################### # Test generating and reading KML with <Camera> element -def ogr_libkml_camera(): +def test_ogr_libkml_camera(): if not ogrtest.have_read_libkml: - return 'skip' + pytest.skip() ds = ogr.GetDriverByName('LIBKML').CreateDataSource("/vsimem/ogr_libkml_camera.kml") lyr = ds.CreateLayer('test') @@ -922,16 +726,13 @@ def ogr_libkml_camera(): data = data.decode('ascii') gdal.VSIFCloseL(f) - if data.find('<Camera>') == -1 or \ + assert (not (data.find('<Camera>') == -1 or \ data.find('<longitude>2</longitude>') == -1 or \ data.find('<latitude>49</latitude>') == -1 or \ data.find('<heading>70</heading>') == -1 or \ data.find('<tilt>75</tilt>') == -1 or \ data.find('<roll>10</roll>') == -1 or \ - data.find('<altitudeMode>relativeToGround</altitudeMode>') == -1: - print(data) - gdaltest.post_reason('failure') - return 'fail' + data.find('<altitudeMode>relativeToGround</altitudeMode>') == -1)) ds = ogr.Open('/vsimem/ogr_libkml_camera.kml') lyr = ds.GetLayer(0) @@ -942,8 +743,7 @@ def ogr_libkml_camera(): feat.GetField("tilt") != 75.0 or feat.GetField("roll") != 10.0): feat.DumpReadable() - gdaltest.post_reason('failure') - return 'fail' + pytest.fail() feat = lyr.GetNextFeature() if (feat.GetGeometryRef().ExportToWkt() != 'POINT (3 50 1)' or @@ -952,20 +752,17 @@ def ogr_libkml_camera(): feat.IsFieldSet("roll") or feat.GetField("altitudeMode") != 'relativeToGround'): feat.DumpReadable() - gdaltest.post_reason('failure') - return 'fail' + pytest.fail() ds = None - return 'success' - ############################################################################### # Test generating a LookAt element at Document level -def ogr_libkml_write_layer_lookat(): +def test_ogr_libkml_write_layer_lookat(): if not ogrtest.have_read_libkml: - return 'skip' + pytest.skip() ds = ogr.GetDriverByName('LIBKML').CreateDataSource("/vsimem/ogr_libkml_write_layer_lookat.kml") options = ['LOOKAT_LONGITUDE=2', 'LOOKAT_LATITUDE=49', 'LOOKAT_RANGE=150'] @@ -980,36 +777,28 @@ def ogr_libkml_write_layer_lookat(): data = data.decode('ascii') gdal.VSIFCloseL(f) - if data.find('<LookAt>') == -1 or \ + assert (not (data.find('<LookAt>') == -1 or \ data.find('<longitude>2</longitude>') == -1 or \ data.find('<latitude>49</latitude>') == -1 or \ - data.find('<range>150</range>') == -1: - print(data) - gdaltest.post_reason('failure') - return 'fail' + data.find('<range>150</range>') == -1)) - if data.find('<LookAt>') == -1 or \ + assert (not (data.find('<LookAt>') == -1 or \ data.find('<longitude>3</longitude>') == -1 or \ data.find('<latitude>50</latitude>') == -1 or \ data.find('<altitude>100</altitude>') == -1 or \ data.find('<heading>70</heading>') == -1 or \ data.find('<tilt>50</tilt>') == -1 or \ data.find('<range>150</range>') == -1 or \ - data.find('<altitudeMode>relativeToGround</altitudeMode>') == -1: - print(data) - gdaltest.post_reason('failure') - return 'fail' - - return 'success' + data.find('<altitudeMode>relativeToGround</altitudeMode>') == -1)) ############################################################################### # Test generating a Camera element at Document level -def ogr_libkml_write_layer_camera(): +def test_ogr_libkml_write_layer_camera(): if not ogrtest.have_read_libkml: - return 'skip' + pytest.skip() ds = ogr.GetDriverByName('LIBKML').CreateDataSource("/vsimem/ogr_libkml_write_layer_camera.kml") options = ['CAMERA_LONGITUDE=3', 'CAMERA_LATITUDE=50', 'CAMERA_ALTITUDE=100', @@ -1022,28 +811,23 @@ def ogr_libkml_write_layer_camera(): data = data.decode('ascii') gdal.VSIFCloseL(f) - if data.find('<Camera>') == -1 or \ + assert (not (data.find('<Camera>') == -1 or \ data.find('<longitude>3</longitude>') == -1 or \ data.find('<latitude>50</latitude>') == -1 or \ data.find('<altitude>100</altitude>') == -1 or \ data.find('<heading>70</heading>') == -1 or \ data.find('<tilt>50</tilt>') == -1 or \ data.find('<roll>10</roll>') == -1 or \ - data.find('<altitudeMode>relativeToGround</altitudeMode>') == -1: - print(data) - gdaltest.post_reason('failure') - return 'fail' - - return 'success' + data.find('<altitudeMode>relativeToGround</altitudeMode>') == -1)) ############################################################################### # Test writing MultiGeometry -def ogr_libkml_write_multigeometry(): +def test_ogr_libkml_write_multigeometry(): if not ogrtest.have_read_libkml: - return 'skip' + pytest.skip() ds = ogr.GetDriverByName('LIBKML').CreateDataSource("/vsimem/ogr_libkml_write_multigeometry.kml") lyr = ds.CreateLayer('test') @@ -1064,24 +848,21 @@ def ogr_libkml_write_multigeometry(): feat = lyr.GetNextFeature() if feat.GetGeometryRef().ExportToWkt() != 'POINT (0 1 0)': feat.DumpReadable() - gdaltest.post_reason('failure') - return 'fail' + pytest.fail() feat = lyr.GetNextFeature() if feat.GetGeometryRef().ExportToWkt() != 'GEOMETRYCOLLECTION EMPTY': feat.DumpReadable() - gdaltest.post_reason('failure') - return 'fail' - - return 'success' + pytest.fail() + ############################################################################### # Test writing <snippet> -def ogr_libkml_write_snippet(): +def test_ogr_libkml_write_snippet(): if not ogrtest.have_read_libkml: - return 'skip' + pytest.skip() ds = ogr.GetDriverByName('LIBKML').CreateDataSource("/vsimem/ogr_libkml_write_snippet.kml") lyr = ds.CreateLayer('test') @@ -1097,40 +878,32 @@ def ogr_libkml_write_snippet(): data = data.decode('ascii') gdal.VSIFCloseL(f) - if data.find('<snippet>test_snippet</snippet>') == -1: - print(data) - gdaltest.post_reason('failure') - return 'fail' + assert data.find('<snippet>test_snippet</snippet>') != -1 ds = ogr.Open("/vsimem/ogr_libkml_write_snippet.kml") lyr = ds.GetLayer(0) feat = lyr.GetNextFeature() if feat.GetField('snippet') != 'test_snippet': feat.DumpReadable() - gdaltest.post_reason('failure') - return 'fail' + pytest.fail() if feat.GetGeometryRef().ExportToWkt() != 'POINT (0 1 0)': feat.DumpReadable() - gdaltest.post_reason('failure') - return 'fail' - - return 'success' + pytest.fail() + ############################################################################### # Test writing <atom:author> -def ogr_libkml_write_atom_author(): +def test_ogr_libkml_write_atom_author(): if not ogrtest.have_read_libkml: - return 'skip' + pytest.skip() filepath = '/vsimem/ogr_libkml_write_atom_author.kml' ds = ogr.GetDriverByName('LIBKML').CreateDataSource(filepath, options=['author_name=name', 'author_uri=http://foo', 'author_email=foo@bar.com']) - if ds is None: - gdaltest.post_reason('Unable to create %s.' % filepath) - return 'fail' + assert ds is not None, ('Unable to create %s.' % filepath) ds = None f = gdal.VSIFOpenL(filepath, 'rb') @@ -1138,31 +911,25 @@ def ogr_libkml_write_atom_author(): data = data.decode('ascii') gdal.VSIFCloseL(f) - if data.find('<kml xmlns="http://www.opengis.net/kml/2.2" xmlns:atom="http://www.w3.org/2005/Atom">') == -1 or \ + assert (not (data.find('<kml xmlns="http://www.opengis.net/kml/2.2" xmlns:atom="http://www.w3.org/2005/Atom">') == -1 or \ data.find('<atom:name>name</atom:name>') == -1 or \ data.find('<atom:uri>http://foo</atom:uri>') == -1 or \ - data.find('<atom:email>foo@bar.com</atom:email>') == -1: - print(data) - gdaltest.post_reason('failure to find an atom string') - return 'fail' - - return 'success' + data.find('<atom:email>foo@bar.com</atom:email>') == -1)), \ + 'failure to find an atom string' ############################################################################### # Test writing <atom:link> -def ogr_libkml_write_atom_link(): +def test_ogr_libkml_write_atom_link(): if not ogrtest.have_read_libkml: - return 'skip' + pytest.skip() filepath = '/vsimem/ogr_libkml_write_atom_link.kml' ds = ogr.GetDriverByName('LIBKML').CreateDataSource(filepath, options=['link=http://foo']) - if ds is None: - gdaltest.post_reason('Unable to create %s.' % filepath) - return 'fail' + assert ds is not None, ('Unable to create %s.' % filepath) ds = None f = gdal.VSIFOpenL(filepath, 'rb') @@ -1170,29 +937,22 @@ def ogr_libkml_write_atom_link(): data = data.decode('ascii') gdal.VSIFCloseL(f) - if data.find('<kml xmlns="http://www.opengis.net/kml/2.2" xmlns:atom="http://www.w3.org/2005/Atom">') == -1 or \ - data.find('<atom:link href="http://foo" rel="related"/>') == -1: - print(data) - gdaltest.post_reason('failure') - return 'fail' - - return 'success' + assert (not (data.find('<kml xmlns="http://www.opengis.net/kml/2.2" xmlns:atom="http://www.w3.org/2005/Atom">') == -1 or \ + data.find('<atom:link href="http://foo" rel="related"/>') == -1)) ############################################################################### # Test writing <phoneNumber> -def ogr_libkml_write_phonenumber(): +def test_ogr_libkml_write_phonenumber(): if not ogrtest.have_read_libkml: - return 'skip' + pytest.skip() filepath = '/vsimem/ogr_libkml_write_phonenumber.kml' ds = ogr.GetDriverByName('LIBKML').CreateDataSource(filepath, options=['phonenumber=tel:911']) - if ds is None: - gdaltest.post_reason('Unable to create %s.' % filepath) - return 'fail' + assert ds is not None, ('Unable to create %s.' % filepath) ds = None f = gdal.VSIFOpenL(filepath, 'rb') @@ -1200,21 +960,16 @@ def ogr_libkml_write_phonenumber(): data = data.decode('ascii') gdal.VSIFCloseL(f) - if data.find('<phoneNumber>tel:911</phoneNumber>') == -1: - print(data) - gdaltest.post_reason('failure') - return 'fail' - - return 'success' + assert data.find('<phoneNumber>tel:911</phoneNumber>') != -1 ############################################################################### # Test writing Region -def ogr_libkml_write_region(): +def test_ogr_libkml_write_region(): if not ogrtest.have_read_libkml: - return 'skip' + pytest.skip() ds = ogr.GetDriverByName('LIBKML').CreateDataSource("/vsimem/ogr_libkml_write_region.kml") lyr = ds.CreateLayer('auto', options=['ADD_REGION=YES']) @@ -1232,38 +987,30 @@ def ogr_libkml_write_region(): data = data.decode('ascii') gdal.VSIFCloseL(f) - if data.find('<north>49</north>') == -1 or \ + assert (not (data.find('<north>49</north>') == -1 or \ data.find('<south>48</south>') == -1 or \ data.find('<east>3</east>') == -1 or \ data.find('<west>2</west>') == -1 or \ data.find('<minLodPixels>256</minLodPixels>') == -1 or \ - data.find('<maxLodPixels>-1</maxLodPixels>') == -1: - print(data) - gdaltest.post_reason('failure') - return 'fail' + data.find('<maxLodPixels>-1</maxLodPixels>') == -1)) - if data.find('<north>90</north>') == -1 or \ + assert (not (data.find('<north>90</north>') == -1 or \ data.find('<south>-90</south>') == -1 or \ data.find('<east>180</east>') == -1 or \ data.find('<west>-180</west>') == -1 or \ data.find('<minLodPixels>128</minLodPixels>') == -1 or \ data.find('<maxLodPixels>10000000</maxLodPixels>') == -1 or \ data.find('<minFadeExtent>1</minFadeExtent>') == -1 or \ - data.find('<maxFadeExtent>2</maxFadeExtent>') == -1: - print(data) - gdaltest.post_reason('failure') - return 'fail' - - return 'success' + data.find('<maxFadeExtent>2</maxFadeExtent>') == -1)) ############################################################################### # Test writing ScreenOverlay -def ogr_libkml_write_screenoverlay(): +def test_ogr_libkml_write_screenoverlay(): if not ogrtest.have_read_libkml: - return 'skip' + pytest.skip() ds = ogr.GetDriverByName('LIBKML').CreateDataSource("/vsimem/ogr_libkml_write_screenoverlay.kml") ds.CreateLayer('auto', options=['SO_HREF=http://foo']) @@ -1289,31 +1036,23 @@ def ogr_libkml_write_screenoverlay(): data = data.decode('ascii') gdal.VSIFCloseL(f) - if data.find('<href>http://foo</href>') == -1 or \ - data.find('<screenXY x="0.05" xunits="fraction" y="0.05" yunits="fraction"/>') == -1: - print(data) - gdaltest.post_reason('failure') - return 'fail' + assert (not (data.find('<href>http://foo</href>') == -1 or \ + data.find('<screenXY x="0.05" xunits="fraction" y="0.05" yunits="fraction"/>') == -1)) - if data.find('<overlayXY x="10" xunits="pixels" y="20" yunits="pixels"/>') == -1 or \ + assert (not (data.find('<overlayXY x="10" xunits="pixels" y="20" yunits="pixels"/>') == -1 or \ data.find('<screenXY x="0.4" xunits="fraction" y="0.5" yunits="fraction"/>') == -1 or \ data.find('<size x="1.1" xunits="fraction" y="1.2" yunits="fraction"/>') == -1 or \ data.find('<name>name</name>') == -1 or \ - data.find('<description>description</description>') == -1: - print(data) - gdaltest.post_reason('failure') - return 'fail' - - return 'success' + data.find('<description>description</description>') == -1)) ############################################################################### # Test writing Model -def ogr_libkml_write_model(): +def test_ogr_libkml_write_model(): if not ogrtest.have_read_libkml: - return 'skip' + pytest.skip() ds = ogr.GetDriverByName('LIBKML').CreateDataSource("/vsimem/ogr_libkml_write_model.kml") lyr = ds.CreateLayer('test') @@ -1350,7 +1089,7 @@ def ogr_libkml_write_model(): data = data.decode('ascii') gdal.VSIFCloseL(f) - if data.find('<longitude>2</longitude>') == -1 or \ + assert (not (data.find('<longitude>2</longitude>') == -1 or \ data.find('<latitude>49</latitude>') == -1 or \ data.find('<altitude>10</altitude>') == -1 or \ data.find('<altitudeMode>relativeToGround</altitudeMode>') == -1 or \ @@ -1364,31 +1103,25 @@ def ogr_libkml_write_model(): data.find('<y>1</y>') == -1 or \ data.find('<z>1</z>') == -1 or \ data.find('<href>http://makc.googlecode.com/svn/trunk/flash/sandy_flar2/cube.dae</href>') == -1 or \ - data.find('<href>http://foo</href>') == -1: - print(data) - gdaltest.post_reason('failure') - return 'fail' + data.find('<href>http://foo</href>') == -1)) # This can only appear if HTTP resource is available and GDAL is built with curl/http support if gdal.GetDriverByName('HTTP') is not None and \ (data.find('<targetHref>http://makc.googlecode.com/svn/trunk/flash/sandy_flar2/cube.gif</targetHref>') == -1 or data.find('<sourceHref>cube.gif</sourceHref>') == -1): - if gdaltest.gdalurlopen('http://makc.googlecode.com/svn/trunk/flash/sandy_flar2/cube.dae') is not None: - print(data) - gdaltest.post_reason('failure') - return 'fail' - - return 'success' + assert gdaltest.gdalurlopen('http://makc.googlecode.com/svn/trunk/flash/sandy_flar2/cube.dae') is None, \ + data + ############################################################################### # Test read / write of style -def ogr_libkml_read_write_style(): +def test_ogr_libkml_read_write_style(): if not ogrtest.have_read_libkml: - return 'skip' + pytest.skip() f = gdal.VSIFOpenL('/vsimem/ogr_libkml_read_write_style_read.kml', 'wb') @@ -1483,17 +1216,13 @@ def ogr_libkml_read_write_style(): lines_ref = [l.strip() for l in styles.split('\n')] if lines_got != lines_ref: print(data) - print(styles) - gdaltest.post_reason('failure') - return 'fail' + pytest.fail(styles) lines_got = lines[lines.index('<Style id="styleMapExample">'):lines.index('</Document>')] lines_ref = [l.strip() for l in resolved_stylemap.split('\n')] if lines_got != lines_ref: print(data) - print(resolved_stylemap) - gdaltest.post_reason('failure') - return 'fail' + pytest.fail(resolved_stylemap) # Test reading highlight style in StyleMap gdal.SetConfigOption('LIBKML_STYLEMAP_KEY', 'HIGHLIGHT') @@ -1516,9 +1245,7 @@ def ogr_libkml_read_write_style(): lines_ref = [l.strip() for l in resolved_stylemap_highlight.split('\n')] if lines_got != lines_ref: print(data) - print(resolved_stylemap_highlight) - gdaltest.post_reason('failure') - return 'fail' + pytest.fail(resolved_stylemap_highlight) # Test writing feature style ds = ogr.GetDriverByName('LIBKML').CreateDataSource('/vsimem/ogr_libkml_read_write_style_write.kml') @@ -1537,15 +1264,9 @@ def ogr_libkml_read_write_style(): ds = ogr.Open('/vsimem/ogr_libkml_read_write_style_write.kml') lyr = ds.GetLayer(0) feat = lyr.GetNextFeature() - if feat.GetStyleString() != '@unknown_style': - print(feat.GetStyleString()) - gdaltest.post_reason('failure') - return 'fail' + assert feat.GetStyleString() == '@unknown_style' feat = lyr.GetNextFeature() - if feat.GetStyleString() != style_string: - print(feat.GetStyleString()) - gdaltest.post_reason('failure') - return 'fail' + assert feat.GetStyleString() == style_string ds = None f = gdal.VSIFOpenL('/vsimem/ogr_libkml_read_write_style_write.kml', 'rb') @@ -1580,9 +1301,7 @@ def ogr_libkml_read_write_style(): lines_ref = [l.strip() for l in expected_style.split('\n')] if lines_got != lines_ref: print(data) - print(resolved_stylemap_highlight) - gdaltest.post_reason('failure') - return 'fail' + pytest.fail(resolved_stylemap_highlight) # Automatic StyleMap creation testing ds = ogr.GetDriverByName('LIBKML').CreateDataSource('/vsimem/ogr_libkml_read_write_style_write.kml') @@ -1629,20 +1348,17 @@ def ogr_libkml_read_write_style(): lines_ref = [l.strip() for l in expected_styles.split('\n')] if lines_got != lines_ref: print(data) - print(styles) - gdaltest.post_reason('failure') - return 'fail' - - return 'success' + pytest.fail(styles) + ############################################################################### # Test writing Update -def ogr_libkml_write_update(): +def test_ogr_libkml_write_update(): if not ogrtest.have_read_libkml: - return 'skip' + pytest.skip() for i in range(3): @@ -1672,14 +1388,12 @@ def ogr_libkml_write_update(): f = gdal.VSIFOpenL('/vsizip//vsimem/ogr_libkml_write_update.kmz', 'rb') else: f = gdal.VSIFOpenL('/vsimem/ogr_libkml_write_update_dir/doc.kml', 'rb') - if f is None: - gdaltest.post_reason('Unable to open the write_update file.') - return 'fail' + assert f is not None, 'Unable to open the write_update file.' data = gdal.VSIFReadL(1, 2048, f) data = data.decode('ascii') gdal.VSIFCloseL(f) - if data.find('<NetworkLinkControl>') == -1 or \ + assert (not (data.find('<NetworkLinkControl>') == -1 or \ data.find('<Update>') == -1 or \ data.find('<targetHref>http://foo</targetHref>') == -1 or \ data.find('<Placemark/>') == -1 or \ @@ -1689,21 +1403,17 @@ def ogr_libkml_write_update(): data.find('<Change>') == -1 or \ data.find('<Placemark targetId="layer_to_edit.2"/>') == -1 or \ data.find('<Delete>') == -1 or \ - data.find('<Placemark targetId="layer_to_edit.3"/>') == -1: - print(data) - gdaltest.post_reason('failure') - return 'fail' - - return 'success' + data.find('<Placemark targetId="layer_to_edit.3"/>') == -1)) + ############################################################################### # Test writing NetworkLinkControl -def ogr_libkml_write_networklinkcontrol(): +def test_ogr_libkml_write_networklinkcontrol(): if not ogrtest.have_read_libkml: - return 'skip' + pytest.skip() options = ['NLC_MINREFRESHPERIOD=3600', 'NLC_MAXSESSIONLENGTH=-1', @@ -1724,9 +1434,7 @@ def ogr_libkml_write_networklinkcontrol(): name = "/vsimem/ogr_libkml_write_networklinkcontrol_dir" ds = ogr.GetDriverByName('LIBKML').CreateDataSource(name, options=options) - if ds is None: - gdaltest.post_reason('Unable to create %s.' % name) - return 'fail' + assert ds is not None, ('Unable to create %s.' % name) ds = None if i == 0: @@ -1735,35 +1443,29 @@ def ogr_libkml_write_networklinkcontrol(): f = gdal.VSIFOpenL('/vsizip//vsimem/ogr_libkml_write_networklinkcontrol.kmz', 'rb') else: f = gdal.VSIFOpenL('/vsimem/ogr_libkml_write_networklinkcontrol_dir/doc.kml', 'rb') - if f is None: - gdaltest.post_reason('failure') - return 'fail' + assert f is not None data = gdal.VSIFReadL(1, 2048, f) data = data.decode('ascii') gdal.VSIFCloseL(f) - if data.find('<minRefreshPeriod>3600</minRefreshPeriod>') == -1 or \ + assert (not (data.find('<minRefreshPeriod>3600</minRefreshPeriod>') == -1 or \ data.find('<maxSessionLength>-1</maxSessionLength>') == -1 or \ data.find('<cookie>cookie</cookie>') == -1 or \ data.find('<message>message</message>') == -1 or \ data.find('<linkName>linkname</linkName>') == -1 or \ data.find('<linkDescription>linkdescription</linkDescription>') == -1 or \ data.find('<linkSnippet>linksnippet</linkSnippet>') == -1 or \ - data.find('<expires>2014-12-31T23:59:59Z</expires>') == -1: - print(data) - gdaltest.post_reason('failure') - return 'fail' - - return 'success' + data.find('<expires>2014-12-31T23:59:59Z</expires>') == -1)) + ############################################################################### # Test writing ListStyle -def ogr_libkml_write_liststyle(): +def test_ogr_libkml_write_liststyle(): if not ogrtest.have_read_libkml: - return 'skip' + pytest.skip() options = ['LISTSTYLE_ICON_HREF=http://www.gdal.org/gdalicon.png'] ds = ogr.GetDriverByName('LIBKML').CreateDataSource("/vsimem/ogr_libkml_write_liststyle.kml", options=options) @@ -1781,7 +1483,7 @@ def ogr_libkml_write_liststyle(): data = data.decode('ascii') gdal.VSIFCloseL(f) - if data.find('<styleUrl>#root_doc_liststyle</styleUrl>') == -1 or \ + assert (not (data.find('<styleUrl>#root_doc_liststyle</styleUrl>') == -1 or \ data.find('<Style id="root_doc_liststyle">') == -1 or \ data.find('<href>http://www.gdal.org/gdalicon.png</href>') == -1 or \ data.find('<styleUrl>#test_liststyle</styleUrl>') == -1 or \ @@ -1790,21 +1492,16 @@ def ogr_libkml_write_liststyle(): data.find('<listItemType>check</listItemType>') == -1 or \ data.find('<listItemType>radioFolder</listItemType>') == -1 or \ data.find('<listItemType>checkOffOnly</listItemType>') == -1 or \ - data.find('<listItemType>checkHideChildren</listItemType>') == -1: - print(data) - gdaltest.post_reason('failure') - return 'fail' - - return 'success' + data.find('<listItemType>checkHideChildren</listItemType>') == -1)) ############################################################################### # Test writing NetworkLink -def ogr_libkml_write_networklink(): +def test_ogr_libkml_write_networklink(): if not ogrtest.have_read_libkml: - return 'skip' + pytest.skip() ds = ogr.GetDriverByName('LIBKML').CreateDataSource("/vsimem/ogr_libkml_write_networklink.kml") lyr = ds.CreateLayer('test') @@ -1849,7 +1546,7 @@ def ogr_libkml_write_networklink(): data = data.decode('ascii') gdal.VSIFCloseL(f) - if data.find('<name>a network link</name>') == -1 or \ + assert (not (data.find('<name>a network link</name>') == -1 or \ data.find('<refreshVisibility>1</refreshVisibility>') == -1 or \ data.find('<flyToView>1</flyToView>') == -1 or \ data.find('<href>http://developers.google.com/kml/documentation/Point.kml</href>') == -1 or \ @@ -1861,21 +1558,16 @@ def ogr_libkml_write_networklink(): data.find('<refreshMode>onExpire</refreshMode>') == -1 or \ data.find('<viewRefreshMode>onRegion</viewRefreshMode>') == -1 or \ data.find('<viewBoundScale>0.5</viewBoundScale>') == -1 or \ - data.find('<viewFormat>BBOX=[bboxWest],[bboxSouth],[bboxEast],[bboxNorth]</viewFormat>') == -1: - print(data) - gdaltest.post_reason('failure') - return 'fail' - - return 'success' + data.find('<viewFormat>BBOX=[bboxWest],[bboxSouth],[bboxEast],[bboxNorth]</viewFormat>') == -1)) ############################################################################### # Test writing PhotoOverlay -def ogr_libkml_write_photooverlay(): +def test_ogr_libkml_write_photooverlay(): if not ogrtest.have_read_libkml: - return 'skip' + pytest.skip() ds = ogr.GetDriverByName('LIBKML').CreateDataSource("/vsimem/ogr_libkml_write_photooverlay.kml") lyr = ds.CreateLayer('test') @@ -1930,7 +1622,7 @@ def ogr_libkml_write_photooverlay(): data = data.decode('ascii') gdal.VSIFCloseL(f) - if data.find('<Camera>') == -1 or \ + assert (not (data.find('<Camera>') == -1 or \ data.find('<longitude>2.2946</longitude>') == -1 or \ data.find('<latitude>48.8583</latitude>') == -1 or \ data.find('<altitude>20</altitude>') == -1 or \ @@ -1950,21 +1642,16 @@ def ogr_libkml_write_photooverlay(): data.find('<tileSize>256</tileSize>') == -1 or \ data.find('<maxWidth>512</maxWidth>') == -1 or \ data.find('<maxHeight>512</maxHeight>') == -1 or \ - data.find('<gridOrigin>upperLeft</gridOrigin>') == -1: - print(data) - gdaltest.post_reason('failure') - return 'fail' - - return 'success' + data.find('<gridOrigin>upperLeft</gridOrigin>') == -1)) ############################################################################### # Test writing and reading Data element -def ogr_libkml_read_write_data(): +def test_ogr_libkml_read_write_data(): if not ogrtest.have_read_libkml: - return 'skip' + pytest.skip() ds = ogr.GetDriverByName('LIBKML').CreateDataSource("/vsimem/ogr_libkml_read_write_data.kml") gdal.SetConfigOption('LIBKML_USE_SIMPLEFIELD', 'NO') @@ -1982,29 +1669,22 @@ def ogr_libkml_read_write_data(): data = data.decode('ascii') gdal.VSIFCloseL(f) - if data.find('<Data name="foo">') == -1 or \ - data.find('<value>bar</value>') == -1: - print(data) - gdaltest.post_reason('failure') - return 'fail' + assert (not (data.find('<Data name="foo">') == -1 or \ + data.find('<value>bar</value>') == -1)) ds = ogr.Open("/vsimem/ogr_libkml_read_write_data.kml") lyr = ds.GetLayer(0) feat = lyr.GetNextFeature() - if feat.GetField('foo') != 'bar': - gdaltest.post_reason('failure') - return 'fail' - - return 'success' + assert feat.GetField('foo') == 'bar' ############################################################################### # Test writing layer as Folder -def ogr_libkml_write_folder(): +def test_ogr_libkml_write_folder(): if not ogrtest.have_read_libkml: - return 'skip' + pytest.skip() ds = ogr.GetDriverByName('LIBKML').CreateDataSource("/vsimem/ogr_libkml_write_folder.kml") ds.CreateLayer('test', options=['LISTSTYLE_ICON_HREF=http://foo', 'FOLDER=YES']) @@ -2016,25 +1696,20 @@ def ogr_libkml_write_folder(): data = data.decode('ascii') gdal.VSIFCloseL(f) - if data.find('<Style id="test_liststyle">') == -1 or \ + assert (not (data.find('<Style id="test_liststyle">') == -1 or \ data.find('<href>http://foo</href>') == -1 or \ data.find('<Folder id="test">') == -1 or \ data.find('<styleUrl>#test_liststyle</styleUrl>') == -1 or \ - data.find('<Folder id="test2">') == -1: - print(data) - gdaltest.post_reason('failure') - return 'fail' - - return 'success' + data.find('<Folder id="test2">') == -1)) ############################################################################### # Test writing datasource and layer container propreties -def ogr_libkml_write_container_properties(): +def test_ogr_libkml_write_container_properties(): if not ogrtest.have_read_libkml: - return 'skip' + pytest.skip() ds = ogr.GetDriverByName('LIBKML').CreateDataSource("/vsimem/ogr_libkml_write_container_properties.kml", options=['NAME=ds_name', 'DESCRIPTION=ds_description', 'OPEN=1', 'VISIBILITY=1', 'SNIPPET=ds_snippet']) @@ -2046,7 +1721,7 @@ def ogr_libkml_write_container_properties(): data = data.decode('ascii') gdal.VSIFCloseL(f) - if data.find('<name>ds_name</name>') == -1 or \ + assert (not (data.find('<name>ds_name</name>') == -1 or \ data.find('<visibility>1</visibility>') == -1 or \ data.find('<open>1</open>') == -1 or \ data.find('<snippet>ds_snippet</snippet>') == -1 or \ @@ -2055,113 +1730,84 @@ def ogr_libkml_write_container_properties(): data.find('<visibility>0</visibility>') == -1 or \ data.find('<open>0</open>') == -1 or \ data.find('<snippet>lyr_snippet</snippet>') == -1 or \ - data.find('<description>lyr_description</description>') == -1: - print(data) - gdaltest.post_reason('failure') - return 'fail' - - return 'success' + data.find('<description>lyr_description</description>') == -1)) ############################################################################### # Test reading gx:TimeStamp and gx:TimeSpan -def ogr_libkml_read_gx_timestamp(): +def test_ogr_libkml_read_gx_timestamp(): if not ogrtest.have_read_libkml: - return 'skip' + pytest.skip() ds = ogr.Open('data/gxtimestamp.kml') lyr = ds.GetLayer(0) f = lyr.GetNextFeature() if f['timestamp'] != '2016/02/13 12:34:56+00': - gdaltest.post_reason('failure') f.DumpReadable() - return 'fail' + pytest.fail() f = lyr.GetNextFeature() if f['begin'] != '2016/02/13 00:00:00+00' or f['end'] != '2016/02/14 00:00:00+00': - gdaltest.post_reason('failure') f.DumpReadable() - return 'fail' - - return 'success' + pytest.fail() + ############################################################################### # Test reading KML with kml: prefix -def ogr_libkml_read_placemark_with_kml_prefix(): +def test_ogr_libkml_read_placemark_with_kml_prefix(): if not ogrtest.have_read_libkml: - return 'skip' + pytest.skip() ds = ogr.Open('data/placemark_with_kml_prefix.kml') lyr = ds.GetLayer(0) feat = lyr.GetNextFeature() - if feat is None: - return 'fail' - - return 'success' + assert feat is not None ############################################################################### # Test reading KML with duplicated folder name -def ogr_libkml_read_duplicate_folder_name(): +def test_ogr_libkml_read_duplicate_folder_name(): if not ogrtest.have_read_libkml: - return 'skip' + pytest.skip() ds = ogr.Open('data/duplicate_folder_name.kml') lyr = ds.GetLayer(0) - if lyr.GetName() != 'layer': - gdaltest.post_reason('failure') - print(lyr.GetName()) - return 'fail' + assert lyr.GetName() == 'layer' lyr = ds.GetLayer(1) - if lyr.GetName() != 'layer (#2)': - gdaltest.post_reason('failure') - print(lyr.GetName()) - return 'fail' - - return 'success' + assert lyr.GetName() == 'layer (#2)' ############################################################################### # Test reading KML with a placemark in root document, and a subfolder (#7221) -def ogr_libkml_read_placemark_in_root_and_subfolder(): +def test_ogr_libkml_read_placemark_in_root_and_subfolder(): if not ogrtest.have_read_libkml: - return 'skip' + pytest.skip() ds = ogr.Open('data/placemark_in_root_and_subfolder.kml') lyr = ds.GetLayerByName('TopLevel') - if lyr is None: - gdaltest.post_reason('failure') - return 'fail' - if lyr.GetFeatureCount() != 1: - gdaltest.post_reason('failure') - return 'fail' + assert lyr is not None + assert lyr.GetFeatureCount() == 1 lyr = ds.GetLayerByName('SubFolder1') - if lyr is None: - gdaltest.post_reason('failure') - return 'fail' - if lyr.GetFeatureCount() != 1: - gdaltest.post_reason('failure') - return 'fail' - - return 'success' + assert lyr is not None + assert lyr.GetFeatureCount() == 1 ############################################################################### # Test reading KML with coordinate tuples separated by tabulations (#7231) -def ogr_libkml_read_tab_separated_coord_triplet(): +def test_ogr_libkml_read_tab_separated_coord_triplet(): if not ogrtest.have_read_libkml: - return 'skip' + pytest.skip() ds = ogr.Open('data/tab_separated_coord_triplet.kml') lyr = ds.GetLayer(0) @@ -2169,19 +1815,16 @@ def ogr_libkml_read_tab_separated_coord_triplet(): wkt = 'LINESTRING Z (1 2 3,4 5 6)' - if ogrtest.check_feature_geometry(feat, wkt): - return 'fail' - - return 'success' + assert not ogrtest.check_feature_geometry(feat, wkt) ############################################################################### # Test reading KML with coordinate with space only content (#7232) -def ogr_libkml_read_kml_with_space_content_in_coordinates(): +def test_ogr_libkml_read_kml_with_space_content_in_coordinates(): if not ogrtest.have_read_libkml: - return 'skip' + pytest.skip() ds = ogr.Open('data/kml_with_space_content_in_coordinates.kml') lyr = ds.GetLayer(0) @@ -2189,57 +1832,49 @@ def ogr_libkml_read_kml_with_space_content_in_coordinates(): wkt = 'LINESTRING EMPTY' - if ogrtest.check_feature_geometry(feat, wkt): - return 'fail' - - return 'success' + assert not ogrtest.check_feature_geometry(feat, wkt) ############################################################################### # Test reading a layer referring several schema (github #826) -def ogr_libkml_read_several_schema(): +def test_ogr_libkml_read_several_schema(): if not ogrtest.have_read_libkml: - return 'skip' + pytest.skip() ds = ogr.Open('data/several_schema_in_layer.kml') lyr = ds.GetLayer(0) feat = lyr.GetNextFeature() if feat['fieldA'] != 'fieldAValue' or feat['common'] != 'commonAValue': - gdaltest.post_reason('fail') feat.DumpReadable() - return 'fail' + pytest.fail() feat = lyr.GetNextFeature() if feat['fieldB'] != 'fieldBValue' or feat['common'] != 'commonBValue': - gdaltest.post_reason('fail') feat.DumpReadable() - return 'fail' + pytest.fail() ds = ogr.Open('data/several_schema_outside_layer.kml') lyr = ds.GetLayer(0) feat = lyr.GetNextFeature() if feat['fieldA'] != 'fieldAValue' or feat['common'] != 'commonAValue': - gdaltest.post_reason('fail') feat.DumpReadable() - return 'fail' + pytest.fail() feat = lyr.GetNextFeature() if feat['fieldB'] != 'fieldBValue' or feat['common'] != 'commonBValue': - gdaltest.post_reason('fail') feat.DumpReadable() - return 'fail' - - return 'success' + pytest.fail() + ############################################################################### -def ogr_libkml_update_existing_kml(): +def test_ogr_libkml_update_existing_kml(): if not ogrtest.have_read_libkml: - return 'skip' + pytest.skip() filename = '/vsimem/ogr_libkml_update_existing_kml.kml' gdal.FileFromMemBuffer(filename, open('data/several_schema_in_layer.kml', 'rb').read()) @@ -2253,19 +1888,17 @@ def ogr_libkml_update_existing_kml(): ds = ogr.Open(filename) lyr = ds.GetLayer(0) fc_after = lyr.GetFeatureCount() - if fc_after != fc_before + 1: - return 'fail' + assert fc_after == fc_before + 1 gdal.Unlink(filename) - return 'success' ############################################################################### # Cleanup -def ogr_libkml_cleanup(): +def test_ogr_libkml_cleanup(): if not ogrtest.have_read_libkml: - return 'skip' + pytest.skip() if ogrtest.kml_ds is not None: ogrtest.kml_ds = None @@ -2306,74 +1939,9 @@ def ogr_libkml_cleanup(): print('Re-register KML driver') ogrtest.kml_drv.Register() - return 'success' - + ############################################################################### # Build tests runner -gdaltest_list = [ - ogr_libkml_datastore, - ogr_libkml_attributes_1, - ogr_libkml_attributes_2, - ogr_libkml_attributes_3, - ogr_libkml_attributes_4, - ogr_libkml_point_read, - ogr_libkml_linestring_read, - ogr_libkml_polygon_read, - ogr_libkml_write_kml, - ogr_libkml_check_write_kml, - ogr_libkml_write_kmz, - ogr_libkml_check_write_kmz, - ogr_libkml_write_kmz_use_doc_off, - ogr_libkml_check_write_kmz_use_doc_off, - ogr_libkml_write_dir, - ogr_libkml_check_write_dir, - ogr_libkml_xml_attributes, - ogr_libkml_read_geometries, - ogr_libkml_test_ogrsf, - ogr_libkml_read_placemark, - ogr_libkml_read_empty, - ogr_libkml_read_emptylayers, - ogr_libkml_read_emptylayers_without_folder, - ogr_libkml_read_schema, - ogr_libkml_extended_data_without_schema_data, - ogr_libkml_gxtrack, - ogr_libkml_gxmultitrack, - ogr_libkml_camera, - ogr_libkml_write_layer_lookat, - ogr_libkml_write_layer_camera, - ogr_libkml_write_multigeometry, - ogr_libkml_write_snippet, - ogr_libkml_write_atom_author, - ogr_libkml_write_atom_link, - ogr_libkml_write_phonenumber, - ogr_libkml_write_region, - ogr_libkml_write_screenoverlay, - ogr_libkml_write_model, - ogr_libkml_read_write_style, - ogr_libkml_write_update, - ogr_libkml_write_networklinkcontrol, - ogr_libkml_write_liststyle, - ogr_libkml_write_networklink, - ogr_libkml_write_photooverlay, - ogr_libkml_read_write_data, - ogr_libkml_write_folder, - ogr_libkml_write_container_properties, - ogr_libkml_read_gx_timestamp, - ogr_libkml_read_placemark_with_kml_prefix, - ogr_libkml_read_duplicate_folder_name, - ogr_libkml_read_placemark_in_root_and_subfolder, - ogr_libkml_read_tab_separated_coord_triplet, - ogr_libkml_read_kml_with_space_content_in_coordinates, - ogr_libkml_read_several_schema, - ogr_libkml_update_existing_kml, - ogr_libkml_cleanup] - -if __name__ == '__main__': - - gdaltest.setup_run('ogr_libkml') - - gdaltest.run_tests(gdaltest_list) - - sys.exit(gdaltest.summarize()) + diff --git a/autotest/ogr/ogr_mem.py b/autotest/ogr/ogr_mem.py index bfffe994df66..ed0de9de324c 100755 --- a/autotest/ogr/ogr_mem.py +++ b/autotest/ogr/ogr_mem.py @@ -29,41 +29,36 @@ # DEALINGS IN THE SOFTWARE. ############################################################################### -import sys -sys.path.append('../pymod') import gdaltest import ogrtest from osgeo import ogr from osgeo import gdal +import pytest ############################################################################### # Open Memory datasource. -def ogr_mem_1(): +def test_ogr_mem_1(): mem_drv = ogr.GetDriverByName('Memory') gdaltest.mem_ds = mem_drv.CreateDataSource('wrk_in_memory') - if gdaltest.mem_ds is None: - return 'fail' - - return 'success' + assert gdaltest.mem_ds is not None ############################################################################### # Create table from data/poly.shp -def ogr_mem_2(): +def test_ogr_mem_2(): if gdaltest.mem_ds is None: - return 'skip' + pytest.skip() - if gdaltest.mem_ds.TestCapability(ogr.ODsCCreateLayer) == 0: - gdaltest.post_reason('ODsCCreateLayer TestCapability failed.') - return 'fail' + assert gdaltest.mem_ds.TestCapability(ogr.ODsCCreateLayer) != 0, \ + 'ODsCCreateLayer TestCapability failed.' ####################################################### # Create memory Layer @@ -95,21 +90,18 @@ def ogr_mem_2(): dst_feat.SetFrom(feat) ret = gdaltest.mem_lyr.CreateFeature(dst_feat) - if ret != 0: - gdaltest.post_reason('CreateFeature() failed.') - return 'fail' + assert ret == 0, 'CreateFeature() failed.' feat = shp_lyr.GetNextFeature() - return 'success' - + ############################################################################### # Verify that stuff we just wrote is still OK. -def ogr_mem_3(): +def test_ogr_mem_3(): if gdaltest.mem_ds is None: - return 'skip' + pytest.skip() expect = [168, 169, 166, 158, 165] @@ -122,29 +114,27 @@ def ogr_mem_3(): orig_feat = gdaltest.poly_feat[i] read_feat = gdaltest.mem_lyr.GetNextFeature() - if ogrtest.check_feature_geometry(read_feat, orig_feat.GetGeometryRef(), - max_error=0.000000001) != 0: - return 'fail' + assert (ogrtest.check_feature_geometry(read_feat, orig_feat.GetGeometryRef(), + max_error=0.000000001) == 0) for fld in range(3): - if orig_feat.GetField(fld) != read_feat.GetField(fld): - gdaltest.post_reason('Attribute %d does not match' % fld) - return 'fail' + assert orig_feat.GetField(fld) == read_feat.GetField(fld), \ + ('Attribute %d does not match' % fld) gdaltest.poly_feat = None gdaltest.shp_ds = None - return 'success' if tr else 'fail' + assert tr ############################################################################### # Write more features with a bunch of different geometries, and verify the # geometries are still OK. -def ogr_mem_4(): +def test_ogr_mem_4(): if gdaltest.mem_ds is None: - return 'skip' + pytest.skip() dst_feat = ogr.Feature(feature_def=gdaltest.mem_lyr.GetLayerDefn()) wkt_list = ['10', '2', '1', '3d_1', '4', '5', '6'] @@ -167,19 +157,17 @@ def ogr_mem_4(): gdaltest.mem_lyr.SetAttributeFilter("PRFEDEA = '%s'" % item) feat_read = gdaltest.mem_lyr.GetNextFeature() - if ogrtest.check_feature_geometry(feat_read, geom) != 0: - return 'fail' - - return 'success' + assert ogrtest.check_feature_geometry(feat_read, geom) == 0 + ############################################################################### # Test ExecuteSQL() results layers without geometry. -def ogr_mem_5(): +def test_ogr_mem_5(): if gdaltest.mem_ds is None: - return 'skip' + pytest.skip() expect = [179, 173, 172, 171, 170, 169, 168, 166, 165, 158, None] @@ -189,16 +177,16 @@ def ogr_mem_5(): gdaltest.mem_ds.ReleaseResultSet(sql_lyr) - return 'success' if tr else 'fail' + assert tr ############################################################################### # Test ExecuteSQL() results layers with geometry. -def ogr_mem_6(): +def test_ogr_mem_6(): if gdaltest.mem_ds is None: - return 'skip' + pytest.skip() sql_lyr = gdaltest.mem_ds.ExecuteSQL( "select * from tpoly where prfedea = '2'") @@ -212,16 +200,16 @@ def ogr_mem_6(): gdaltest.mem_ds.ReleaseResultSet(sql_lyr) - return 'success' if tr else 'fail' + assert tr ############################################################################### # Test spatial filtering. -def ogr_mem_7(): +def test_ogr_mem_7(): if gdaltest.mem_ds is None: - return 'skip' + pytest.skip() gdaltest.mem_lyr.SetAttributeFilter(None) @@ -230,22 +218,21 @@ def ogr_mem_7(): gdaltest.mem_lyr.SetSpatialFilter(geom) geom.Destroy() - if gdaltest.mem_lyr.TestCapability(ogr.OLCFastSpatialFilter): - gdaltest.post_reason('OLCFastSpatialFilter capability test should have failed.') - return 'fail' + assert not gdaltest.mem_lyr.TestCapability(ogr.OLCFastSpatialFilter), \ + 'OLCFastSpatialFilter capability test should have failed.' tr = ogrtest.check_features_against_list(gdaltest.mem_lyr, 'eas_id', [158]) gdaltest.mem_lyr.SetSpatialFilter(None) - return 'success' if tr else 'fail' + assert tr ############################################################################### # Test adding a new field. -def ogr_mem_8(): +def test_ogr_mem_8(): #################################################################### # Add new string field. @@ -266,8 +253,7 @@ def ogr_mem_8(): gdal.PushErrorHandler('CPLQuietErrorHandler') ret = gdaltest.mem_lyr.SetFeature(new_feat) gdal.PopErrorHandler() - if ret == 0: - return 'fail' + assert ret != 0 new_feat = None #################################################################### @@ -280,21 +266,19 @@ def ogr_mem_8(): gdaltest.mem_lyr.SetAttributeFilter(None) - return 'success' if tr else 'fail' + assert tr ############################################################################### # Test deleting a feature. -def ogr_mem_9(): +def test_ogr_mem_9(): - if not gdaltest.mem_lyr.TestCapability(ogr.OLCDeleteFeature): - gdaltest.post_reason('OLCDeleteFeature capability test failed.') - return 'fail' + assert gdaltest.mem_lyr.TestCapability(ogr.OLCDeleteFeature), \ + 'OLCDeleteFeature capability test failed.' - if not gdaltest.mem_lyr.TestCapability(ogr.OLCFastFeatureCount): - gdaltest.post_reason('OLCFastFeatureCount capability test failed.') - return 'fail' + assert gdaltest.mem_lyr.TestCapability(ogr.OLCFastFeatureCount), \ + 'OLCFastFeatureCount capability test failed.' old_count = gdaltest.mem_lyr.GetFeatureCount() @@ -302,13 +286,11 @@ def ogr_mem_9(): # Delete target feature. target_fid = 2 - if gdaltest.mem_lyr.DeleteFeature(target_fid) != 0: - gdaltest.post_reason('DeleteFeature returned error code.') - return 'fail' + assert gdaltest.mem_lyr.DeleteFeature(target_fid) == 0, \ + 'DeleteFeature returned error code.' - if gdaltest.mem_lyr.DeleteFeature(target_fid) == 0: - gdaltest.post_reason('DeleteFeature should have returned error code.') - return 'fail' + assert gdaltest.mem_lyr.DeleteFeature(target_fid) != 0, \ + 'DeleteFeature should have returned error code.' #################################################################### # Verify that count has dropped by one, and that the feature in question @@ -318,23 +300,14 @@ def ogr_mem_9(): gdaltest.post_reason('got feature count of %d, not expected %d.' % (new_count, old_count - 1)) - if not gdaltest.mem_lyr.TestCapability(ogr.OLCRandomRead): - gdaltest.post_reason('OLCRandomRead capability test failed.') - return 'fail' - - if gdaltest.mem_lyr.GetFeature(target_fid) is not None: - gdaltest.post_reason('Got deleted feature!') - return 'fail' + assert gdaltest.mem_lyr.TestCapability(ogr.OLCRandomRead), \ + 'OLCRandomRead capability test failed.' - if gdaltest.mem_lyr.GetFeature(-1) is not None: - gdaltest.post_reason('GetFeature() should have failed') - return 'fail' + assert gdaltest.mem_lyr.GetFeature(target_fid) is None, 'Got deleted feature!' - if gdaltest.mem_lyr.GetFeature(1000) is not None: - gdaltest.post_reason('GetFeature() should have failed') - return 'fail' + assert gdaltest.mem_lyr.GetFeature(-1) is None, 'GetFeature() should have failed' - return 'success' + assert gdaltest.mem_lyr.GetFeature(1000) is None, 'GetFeature() should have failed' ############################################################################### # Test GetDriver() / name bug (#1674) @@ -342,27 +315,23 @@ def ogr_mem_9(): # Mostly we are verifying that this doesn't still cause a crash. -def ogr_mem_10(): +def test_ogr_mem_10(): d = ogr.GetDriverByName('Memory') ds = d.CreateDataSource('xxxxxx') d2 = ds.GetDriver() - if d2 is None or d2.GetName() != 'Memory': - gdaltest.post_reason('Did not get expected driver name.') - return 'fail' - - return 'success' + assert d2 is not None and d2.GetName() == 'Memory', \ + 'Did not get expected driver name.' ############################################################################### # Verify that we can delete layers properly -def ogr_mem_11(): +def test_ogr_mem_11(): - if gdaltest.mem_ds.TestCapability('DeleteLayer') == 0: - gdaltest.post_reason('Deletelayer TestCapability failed.') - return 'fail' + assert gdaltest.mem_ds.TestCapability('DeleteLayer') != 0, \ + 'Deletelayer TestCapability failed.' gdaltest.mem_ds.CreateLayer('extra') gdaltest.mem_ds.CreateLayer('extra2') @@ -370,48 +339,35 @@ def ogr_mem_11(): gdaltest.mem_lyr = None # Delete extra layer - if gdaltest.mem_ds.DeleteLayer(layer_count - 2) != 0: - gdaltest.post_reason('DeleteLayer() failed') - return 'fail' + assert gdaltest.mem_ds.DeleteLayer(layer_count - 2) == 0, 'DeleteLayer() failed' - if gdaltest.mem_ds.DeleteLayer(-1) == 0: - gdaltest.post_reason('DeleteLayer() should have failed') - return 'fail' + assert gdaltest.mem_ds.DeleteLayer(-1) != 0, 'DeleteLayer() should have failed' - if gdaltest.mem_ds.DeleteLayer(gdaltest.mem_ds.GetLayerCount()) == 0: - gdaltest.post_reason('DeleteLayer() should have failed') - return 'fail' + assert gdaltest.mem_ds.DeleteLayer(gdaltest.mem_ds.GetLayerCount()) != 0, \ + 'DeleteLayer() should have failed' - if gdaltest.mem_ds.GetLayer(-1) is not None: - gdaltest.post_reason('GetLayer() should have failed') - return 'fail' + assert gdaltest.mem_ds.GetLayer(-1) is None, 'GetLayer() should have failed' - if gdaltest.mem_ds.GetLayer(gdaltest.mem_ds.GetLayerCount()) is not None: - gdaltest.post_reason('GetLayer() should have failed') - return 'fail' + assert gdaltest.mem_ds.GetLayer(gdaltest.mem_ds.GetLayerCount()) is None, \ + 'GetLayer() should have failed' lyr = gdaltest.mem_ds.GetLayer(gdaltest.mem_ds.GetLayerCount() - 1) - if lyr.GetName() != 'extra2': - gdaltest.post_reason('delete layer seems iffy') - return 'fail' - - return 'success' + assert lyr.GetName() == 'extra2', 'delete layer seems iffy' ############################################################################### # Test some date handling -def ogr_mem_12(): +def test_ogr_mem_12(): if gdaltest.mem_ds is None: - return 'skip' + pytest.skip() ####################################################### # Create memory Layer lyr = gdaltest.mem_ds.GetLayerByName('tpoly') - if lyr is None: - return 'fail' + assert lyr is not None # Set the date of the first feature f = lyr.GetFeature(1) @@ -422,19 +378,16 @@ def ogr_mem_12(): expected = [2008, 3, 19, 16, 15, 0.0, 0] result = f.GetFieldAsDateTime(idx) for i, value in enumerate(result): - if value != expected[i]: - gdaltest.post_reason('%s != %s' % (result, expected)) - return 'fail' - return 'success' - + assert value == expected[i], ('%s != %s' % (result, expected)) + ############################################################################### # Test Get/Set on StringList, IntegerList, RealList -def ogr_mem_13(): +def test_ogr_mem_13(): if gdaltest.mem_ds is None: - return 'skip' + pytest.skip() lyr = gdaltest.mem_ds.CreateLayer('listlayer') field_defn = ogr.FieldDefn('stringlist', ogr.OFTStringList) @@ -449,33 +402,25 @@ def ogr_mem_13(): feat.SetFieldStringList except AttributeError: # OG python bindings - return 'skip' + pytest.skip() feat.SetFieldStringList(0, ['a', 'b']) - if feat.GetFieldAsStringList(0) != ['a', 'b']: - print(feat.GetFieldAsStringList(0)) - return 'fail' + assert feat.GetFieldAsStringList(0) == ['a', 'b'] feat.SetFieldIntegerList(1, [2, 3]) - if feat.GetFieldAsIntegerList(1) != [2, 3]: - print(feat.GetFieldAsIntegerList(1)) - return 'fail' + assert feat.GetFieldAsIntegerList(1) == [2, 3] feat.SetFieldDoubleList(2, [4., 5.]) - if feat.GetFieldAsDoubleList(2) != [4., 5.]: - print(feat.GetFieldAsDoubleList(2)) - return 'fail' - - return 'success' + assert feat.GetFieldAsDoubleList(2) == [4., 5.] ############################################################################### # Test SetNextByIndex -def ogr_mem_14(): +def test_ogr_mem_14(): if gdaltest.mem_ds is None: - return 'skip' + pytest.skip() lyr = gdaltest.mem_ds.CreateLayer('SetNextByIndex') field_defn = ogr.FieldDefn('foo', ogr.OFTString) @@ -490,47 +435,31 @@ def ogr_mem_14(): feat.SetField(0, 'third feature') lyr.CreateFeature(feat) - if not lyr.TestCapability(ogr.OLCFastSetNextByIndex): - gdaltest.post_reason('OLCFastSetNextByIndex capability test failed.') - return 'fail' + assert lyr.TestCapability(ogr.OLCFastSetNextByIndex), \ + 'OLCFastSetNextByIndex capability test failed.' - if lyr.SetNextByIndex(1) != 0: - gdaltest.post_reason('SetNextByIndex() failed') - return 'fail' + assert lyr.SetNextByIndex(1) == 0, 'SetNextByIndex() failed' feat = lyr.GetNextFeature() - if feat.GetFieldAsString(0) != 'second feature': - gdaltest.post_reason('did not get expected feature') - return 'fail' + assert feat.GetFieldAsString(0) == 'second feature', 'did not get expected feature' - if lyr.SetNextByIndex(-1) == 0: - gdaltest.post_reason('SetNextByIndex() should have failed') - return 'fail' + assert lyr.SetNextByIndex(-1) != 0, 'SetNextByIndex() should have failed' - if lyr.SetNextByIndex(100) == 0: - gdaltest.post_reason('SetNextByIndex() should have failed') - return 'fail' + assert lyr.SetNextByIndex(100) != 0, 'SetNextByIndex() should have failed' lyr.SetAttributeFilter("foo != 'second feature'") - if lyr.TestCapability(ogr.OLCFastSetNextByIndex): - gdaltest.post_reason('OLCFastSetNextByIndex capability test should have failed.') - return 'fail' + assert not lyr.TestCapability(ogr.OLCFastSetNextByIndex), \ + 'OLCFastSetNextByIndex capability test should have failed.' - if lyr.SetNextByIndex(1) != 0: - gdaltest.post_reason('SetNextByIndex() failed') - return 'fail' + assert lyr.SetNextByIndex(1) == 0, 'SetNextByIndex() failed' feat = lyr.GetNextFeature() - if feat.GetFieldAsString(0) != 'third feature': - gdaltest.post_reason('did not get expected feature') - return 'fail' - - return 'success' + assert feat.GetFieldAsString(0) == 'third feature', 'did not get expected feature' ############################################################################### # Test non-linear geometries -def ogr_mem_15(): +def test_ogr_mem_15(): lyr = gdaltest.mem_ds.CreateLayer('wkbCircularString', geom_type=ogr.wkbCircularString) f = ogr.Feature(lyr.GetLayerDefn()) @@ -538,184 +467,109 @@ def ogr_mem_15(): lyr.CreateFeature(f) f = None - if lyr.GetGeomType() != ogr.wkbCircularString: - gdaltest.post_reason('fail') - return 'fail' - if lyr.GetLayerDefn().GetGeomType() != ogr.wkbCircularString: - gdaltest.post_reason('fail') - return 'fail' - if lyr.GetLayerDefn().GetGeomFieldDefn(0).GetType() != ogr.wkbCircularString: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.GetGeomType() == ogr.wkbCircularString + assert lyr.GetLayerDefn().GetGeomType() == ogr.wkbCircularString + assert lyr.GetLayerDefn().GetGeomFieldDefn(0).GetType() == ogr.wkbCircularString f = lyr.GetNextFeature() g = f.GetGeometryRef() - if g.GetGeometryType() != ogr.wkbCircularString: - gdaltest.post_reason('fail') - return 'fail' + assert g.GetGeometryType() == ogr.wkbCircularString # Test SetNonLinearGeometriesEnabledFlag(False) old_val = ogr.GetNonLinearGeometriesEnabledFlag() ogr.SetNonLinearGeometriesEnabledFlag(False) - if lyr.GetGeomType() != ogr.wkbLineString: - gdaltest.post_reason('fail') - return 'fail' - if lyr.GetLayerDefn().GetGeomType() != ogr.wkbLineString: - gdaltest.post_reason('fail') - return 'fail' - if lyr.GetLayerDefn().GetGeomFieldDefn(0).GetType() != ogr.wkbLineString: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.GetGeomType() == ogr.wkbLineString + assert lyr.GetLayerDefn().GetGeomType() == ogr.wkbLineString + assert lyr.GetLayerDefn().GetGeomFieldDefn(0).GetType() == ogr.wkbLineString lyr.ResetReading() f = lyr.GetNextFeature() g = f.GetGeometryRef() - if g.GetGeometryType() != ogr.wkbLineString: - gdaltest.post_reason('fail') - return 'fail' + assert g.GetGeometryType() == ogr.wkbLineString lyr.ResetReading() f = lyr.GetNextFeature() g = f.GetGeomFieldRef(0) - if g.GetGeometryType() != ogr.wkbLineString: - gdaltest.post_reason('fail') - return 'fail' + assert g.GetGeometryType() == ogr.wkbLineString ogr.SetNonLinearGeometriesEnabledFlag(old_val) - return 'success' - ############################################################################### # Test map implementation -def ogr_mem_16(): +def test_ogr_mem_16(): lyr = gdaltest.mem_ds.CreateLayer('ogr_mem_16') f = ogr.Feature(lyr.GetLayerDefn()) ret = lyr.CreateFeature(f) - if ret != 0: - gdaltest.post_reason('fail') - return 'fail' - if f.GetFID() != 0: - gdaltest.post_reason('fail') - return 'fail' + assert ret == 0 + assert f.GetFID() == 0 f = ogr.Feature(lyr.GetLayerDefn()) ret = lyr.CreateFeature(f) - if ret != 0: - gdaltest.post_reason('fail') - return 'fail' - if f.GetFID() != 1: - gdaltest.post_reason('fail') - return 'fail' + assert ret == 0 + assert f.GetFID() == 1 f = ogr.Feature(lyr.GetLayerDefn()) f.SetFID(100000000) ret = lyr.CreateFeature(f) - if ret != 0: - gdaltest.post_reason('fail') - return 'fail' + assert ret == 0 f = ogr.Feature(lyr.GetLayerDefn()) f.SetFID(100000000) ret = lyr.SetFeature(f) - if ret != 0: - gdaltest.post_reason('fail') - return 'fail' - - if lyr.GetFeatureCount() != 3: - gdaltest.post_reason('fail') - print(lyr.GetFeatureCount()) - return 'fail' - - if lyr.GetFeature(0) is None: - gdaltest.post_reason('fail') - return 'fail' - if lyr.GetFeature(1) is None: - gdaltest.post_reason('fail') - return 'fail' - if lyr.GetFeature(2) is not None: - gdaltest.post_reason('fail') - return 'fail' - if lyr.GetFeature(100000000) is None: - gdaltest.post_reason('fail') - return 'fail' + assert ret == 0 + + assert lyr.GetFeatureCount() == 3 + + assert lyr.GetFeature(0) is not None + assert lyr.GetFeature(1) is not None + assert lyr.GetFeature(2) is None + assert lyr.GetFeature(100000000) is not None lyr.ResetReading() f = lyr.GetNextFeature() - if f.GetFID() != 0: - gdaltest.post_reason('fail') - return 'fail' + assert f.GetFID() == 0 f = lyr.GetNextFeature() - if f.GetFID() != 1: - gdaltest.post_reason('fail') - return 'fail' + assert f.GetFID() == 1 f = lyr.GetNextFeature() - if f.GetFID() != 100000000: - gdaltest.post_reason('fail') - return 'fail' + assert f.GetFID() == 100000000 f = lyr.GetNextFeature() - if f is not None: - gdaltest.post_reason('fail') - return 'fail' + assert f is None f = ogr.Feature(lyr.GetLayerDefn()) f.SetFID(100000000) ret = lyr.CreateFeature(f) - if ret != 0: - gdaltest.post_reason('fail') - return 'fail' - if f.GetFID() != 2: - gdaltest.post_reason('fail') - print(f.GetFID()) - return 'fail' - - if lyr.GetFeatureCount() != 4: - gdaltest.post_reason('fail') - print(lyr.GetFeatureCount()) - return 'fail' + assert ret == 0 + assert f.GetFID() == 2 + + assert lyr.GetFeatureCount() == 4 ret = lyr.DeleteFeature(1) - if ret != 0: - gdaltest.post_reason('fail') - return 'fail' + assert ret == 0 - if lyr.GetFeatureCount() != 3: - gdaltest.post_reason('fail') - print(lyr.GetFeatureCount()) - return 'fail' + assert lyr.GetFeatureCount() == 3 ret = lyr.DeleteFeature(1) - if ret == 0: - gdaltest.post_reason('fail') - return 'fail' + assert ret != 0 - if lyr.GetFeatureCount() != 3: - gdaltest.post_reason('fail') - print(lyr.GetFeatureCount()) - return 'fail' + assert lyr.GetFeatureCount() == 3 # Test first feature with huge ID lyr = gdaltest.mem_ds.CreateLayer('ogr_mem_16_bis') f = ogr.Feature(lyr.GetLayerDefn()) f.SetFID(1234567890123) ret = lyr.CreateFeature(f) - if ret != 0: - gdaltest.post_reason('fail') - return 'fail' - if f.GetFID() != 1234567890123: - gdaltest.post_reason('fail') - return 'fail' + assert ret == 0 + assert f.GetFID() == 1234567890123 f = None # Important we must not have dangling references before modifying the schema ! # Create a field so as to test OGRMemLayerIteratorMap lyr.CreateField(ogr.FieldDefn('foo')) - return 'success' - ############################################################################### # Test Dataset.GetNextFeature() implementation -def ogr_mem_17(): +def test_ogr_mem_17(): ds = gdal.GetDriverByName('Memory').Create('', 0, 0, 0, gdal.GDT_Unknown) lyr = ds.CreateLayer('ogr_mem_1') @@ -736,143 +590,61 @@ def ogr_mem_17(): lyr.CreateFeature(f) f, lyr = ds.GetNextFeature() - if f is None or lyr.GetName() != 'ogr_mem_1': - gdaltest.post_reason('fail') - print(f) - print(lyr.GetName()) - return 'fail' + assert f is not None and lyr.GetName() == 'ogr_mem_1' f, lyr = ds.GetNextFeature() - if f is None or lyr.GetName() != 'ogr_mem_1': - gdaltest.post_reason('fail') - print(f) - print(lyr.GetName()) - return 'fail' + assert f is not None and lyr.GetName() == 'ogr_mem_1' f, lyr = ds.GetNextFeature() - if f is None or lyr.GetName() != 'ogr_mem_2': - gdaltest.post_reason('fail') - print(f) - print(lyr.GetName()) - return 'fail' + assert f is not None and lyr.GetName() == 'ogr_mem_2' f, lyr = ds.GetNextFeature() - if f is None or lyr.GetName() != 'ogr_mem_4': - gdaltest.post_reason('fail') - print(f) - print(lyr.GetName()) - return 'fail' + assert f is not None and lyr.GetName() == 'ogr_mem_4' f, lyr = ds.GetNextFeature() - if f is not None or lyr is not None: - gdaltest.post_reason('fail') - return 'fail' + assert f is None and lyr is None f, lyr = ds.GetNextFeature() - if f is not None or lyr is not None: - gdaltest.post_reason('fail') - return 'fail' + assert f is None and lyr is None ds.ResetReading() f, lyr = ds.GetNextFeature() - if f is None or lyr.GetName() != 'ogr_mem_1': - gdaltest.post_reason('fail') - print(f) - print(lyr.GetName()) - return 'fail' + assert f is not None and lyr.GetName() == 'ogr_mem_1' ds.ResetReading() f, lyr, pct = ds.GetNextFeature(include_pct=True) - if f is None or lyr.GetName() != 'ogr_mem_1' or pct != 0.25: - gdaltest.post_reason('fail') - print(f) - print(lyr.GetName()) - print(pct) - return 'fail' + assert f is not None and lyr.GetName() == 'ogr_mem_1' and pct == 0.25 f, pct = ds.GetNextFeature(include_layer=False, include_pct=True) - if f is None or pct != 0.50: - gdaltest.post_reason('fail') - print(f) - print(pct) - return 'fail' + assert f is not None and pct == 0.50 f, pct = ds.GetNextFeature(include_layer=False, include_pct=True) - if f is None or pct != 0.75: - gdaltest.post_reason('fail') - print(f) - print(pct) - return 'fail' + assert f is not None and pct == 0.75 f, pct = ds.GetNextFeature(include_layer=False, include_pct=True) - if f is None or pct != 1.0: - gdaltest.post_reason('fail') - print(f) - print(pct) - return 'fail' + assert f is not None and pct == 1.0 f, pct = ds.GetNextFeature(include_layer=False, include_pct=True) - if f is not None or pct != 1.0: - gdaltest.post_reason('fail') - print(f) - print(pct) - return 'fail' + assert f is None and pct == 1.0 f, pct = ds.GetNextFeature(include_layer=False, include_pct=True) - if f is not None or pct != 1.0: - gdaltest.post_reason('fail') - print(f) - print(pct) - return 'fail' + assert f is None and pct == 1.0 ds.ResetReading() f = ds.GetNextFeature(include_layer=False) - if f is None: - gdaltest.post_reason('fail') - print(f) - return 'fail' + assert f is not None - return 'success' - -def ogr_mem_cleanup(): +def test_ogr_mem_cleanup(): if gdaltest.mem_ds is None: - return 'skip' + pytest.skip() ogr.SetNonLinearGeometriesEnabledFlag(True) gdaltest.mem_ds = None - return 'success' - - -gdaltest_list = [ - ogr_mem_1, - ogr_mem_2, - ogr_mem_3, - ogr_mem_4, - ogr_mem_5, - ogr_mem_6, - ogr_mem_7, - ogr_mem_8, - ogr_mem_9, - ogr_mem_10, - ogr_mem_11, - ogr_mem_12, - ogr_mem_13, - ogr_mem_14, - ogr_mem_15, - ogr_mem_16, - ogr_mem_17, - ogr_mem_cleanup] - -if __name__ == '__main__': - - gdaltest.setup_run('ogr_mem') - gdaltest.run_tests(gdaltest_list) - sys.exit(gdaltest.summarize()) diff --git a/autotest/ogr/ogr_mitab.py b/autotest/ogr/ogr_mitab.py index 4c45461c23ad..ef81e18b5b7a 100755 --- a/autotest/ogr/ogr_mitab.py +++ b/autotest/ogr/ogr_mitab.py @@ -33,7 +33,6 @@ import shutil import time -sys.path.append('../pymod') import gdaltest import ogrtest @@ -41,28 +40,29 @@ from osgeo import osr from osgeo import gdal import test_cli_utilities +import pytest ############################################################################### # Create TAB file. -def ogr_mitab_1(): +def test_ogr_mitab_1(): gdaltest.mapinfo_drv = ogr.GetDriverByName('MapInfo File') gdaltest.mapinfo_ds = gdaltest.mapinfo_drv.CreateDataSource('tmp') if gdaltest.mapinfo_ds is not None: - return 'success' - return 'fail' + return + pytest.fail() ############################################################################### # Create table from data/poly.shp -def ogr_mitab_2(): +def test_ogr_mitab_2(): if gdaltest.mapinfo_ds is None: - return 'skip' + pytest.skip() # This should convert to MapInfo datum name 'New_Zealand_GD49' WEIRD_SRS = 'PROJCS["NZGD49 / UTM zone 59S",GEOGCS["NZGD49",DATUM["NZGD49",SPHEROID["International 1924",6378388,297,AUTHORITY["EPSG","7022"]],TOWGS84[59.47,-5.04,187.44,0.47,-0.1,1.024,-4.5993],AUTHORITY["EPSG","6272"]],PRIMEM["Greenwich",0,AUTHORITY["EPSG","8901"]],UNIT["degree",0.0174532925199433,AUTHORITY["EPSG","9122"]],AUTHORITY["EPSG","4272"]],PROJECTION["Transverse_Mercator"],PARAMETER["latitude_of_origin",0],PARAMETER["central_meridian",171],PARAMETER["scale_factor",0.9996],PARAMETER["false_easting",500000],PARAMETER["false_northing",10000000],UNIT["metre",1,AUTHORITY["EPSG","9001"]],AXIS["Easting",EAST],AXIS["Northing",NORTH],AUTHORITY["EPSG","27259"]]' @@ -106,8 +106,6 @@ def ogr_mitab_2(): gdaltest.mapinfo_ds = None - return 'success' - ############################################################################### # Verify that stuff we just wrote is still OK. # @@ -115,9 +113,9 @@ def ogr_mitab_2(): # coordinates are not stored with much precision in Mapinfo format. -def ogr_mitab_3(): +def test_ogr_mitab_3(): if gdaltest.mapinfo_drv is None: - return 'skip' + pytest.skip() gdaltest.mapinfo_ds = ogr.Open('tmp') gdaltest.mapinfo_lyr = gdaltest.mapinfo_ds.GetLayer(0) @@ -133,30 +131,28 @@ def ogr_mitab_3(): orig_feat = gdaltest.poly_feat[i] read_feat = gdaltest.mapinfo_lyr.GetNextFeature() - if ogrtest.check_feature_geometry(read_feat, + assert (ogrtest.check_feature_geometry(read_feat, orig_feat.GetGeometryRef(), - max_error=0.02) != 0: - gdaltest.post_reason('Geometry check fail. i=%d' % i) - return 'fail' + max_error=0.02) == 0), \ + ('Geometry check fail. i=%d' % i) for fld in range(3): - if orig_feat.GetField(fld) != read_feat.GetField(fld): - gdaltest.post_reason('Attribute %d does not match' % fld) - return 'fail' + assert orig_feat.GetField(fld) == read_feat.GetField(fld), \ + ('Attribute %d does not match' % fld) gdaltest.poly_feat = None gdaltest.shp_ds = None - return 'success' if tr else 'fail' + assert tr ############################################################################### # Test ExecuteSQL() results layers with geometry. -def ogr_mitab_4(): +def test_ogr_mitab_4(): if gdaltest.mapinfo_ds is None: - return 'skip' + pytest.skip() sql_lyr = gdaltest.mapinfo_ds.ExecuteSQL( "select * from tpoly where prfedea = '35043413'") @@ -170,16 +166,16 @@ def ogr_mitab_4(): gdaltest.mapinfo_ds.ReleaseResultSet(sql_lyr) - return 'success' if tr else 'fail' + assert tr ############################################################################### # Test spatial filtering. -def ogr_mitab_5(): +def test_ogr_mitab_5(): if gdaltest.mapinfo_ds is None: - return 'skip' + pytest.skip() gdaltest.mapinfo_lyr.SetAttributeFilter(None) @@ -191,31 +187,28 @@ def ogr_mitab_5(): gdaltest.mapinfo_lyr.SetSpatialFilter(None) - return 'success' if tr else 'fail' + assert tr ############################################################################### # Verify that Non-WGS84 datums are populated correctly -def ogr_mitab_6(): +def test_ogr_mitab_6(): if gdaltest.mapinfo_drv is None: - return 'skip' + pytest.skip() srs = gdaltest.mapinfo_lyr.GetSpatialRef() datum_name = srs.GetAttrValue('PROJCS|GEOGCS|DATUM') - if datum_name != "New_Zealand_GD49": - gdaltest.post_reason("Datum name does not match (expected 'New_Zealand_GD49', got '%s')" % datum_name) - return 'fail' - - return 'success' + assert datum_name == "New_Zealand_GD49", \ + ("Datum name does not match (expected 'New_Zealand_GD49', got '%s')" % datum_name) ############################################################################### # Create MIF file. -def ogr_mitab_7(): +def test_ogr_mitab_7(): gdaltest.mapinfo_ds = None gdaltest.mapinfo_drv.DeleteDataSource('tmp') @@ -223,17 +216,17 @@ def ogr_mitab_7(): gdaltest.mapinfo_ds = gdaltest.mapinfo_drv.CreateDataSource('tmp/wrk.mif') if gdaltest.mapinfo_ds is not None: - return 'success' - return 'fail' + return + pytest.fail() ############################################################################### # Create table from data/poly.shp -def ogr_mitab_8(): +def test_ogr_mitab_8(): if gdaltest.mapinfo_ds is None: - return 'skip' + pytest.skip() ####################################################### # Create memory Layer @@ -272,15 +265,13 @@ def ogr_mitab_8(): gdaltest.mapinfo_ds = None - return 'success' - ############################################################################### # Verify that stuff we just wrote is still OK. -def ogr_mitab_9(): +def test_ogr_mitab_9(): if gdaltest.mapinfo_drv is None: - return 'skip' + pytest.skip() gdaltest.mapinfo_ds = ogr.Open('tmp') gdaltest.mapinfo_lyr = gdaltest.mapinfo_ds.GetLayer(0) @@ -296,57 +287,46 @@ def ogr_mitab_9(): orig_feat = gdaltest.poly_feat[i] read_feat = gdaltest.mapinfo_lyr.GetNextFeature() - if ogrtest.check_feature_geometry(read_feat, orig_feat.GetGeometryRef(), - max_error=0.000000001) != 0: - return 'fail' + assert (ogrtest.check_feature_geometry(read_feat, orig_feat.GetGeometryRef(), + max_error=0.000000001) == 0) for fld in range(3): - if orig_feat.GetField(fld) != read_feat.GetField(fld): - gdaltest.post_reason('Attribute %d does not match' % fld) - return 'fail' + assert orig_feat.GetField(fld) == read_feat.GetField(fld), \ + ('Attribute %d does not match' % fld) gdaltest.poly_feat = None gdaltest.shp_ds = None - return 'success' if tr else 'fail' + assert tr ############################################################################### # Read mif file with 2 character .mid delimiter and verify operation. -def ogr_mitab_10(): +def test_ogr_mitab_10(): if gdaltest.mapinfo_drv is None: - return 'skip' + pytest.skip() ds = ogr.Open('data/small.mif') lyr = ds.GetLayer(0) feat = lyr.GetNextFeature() - if feat.NAME != " S. 11th St.": - gdaltest.post_reason('name attribute wrong.') - return 'fail' + assert feat.NAME == " S. 11th St.", 'name attribute wrong.' - if feat.FLOODZONE != 10: - gdaltest.post_reason('FLOODZONE attribute wrong.') - return 'fail' + assert feat.FLOODZONE == 10, 'FLOODZONE attribute wrong.' - if ogrtest.check_feature_geometry(feat, + assert (ogrtest.check_feature_geometry(feat, 'POLYGON ((407131.721 155322.441,407134.468 155329.616,407142.741 155327.242,407141.503 155322.467,407140.875 155320.049,407131.721 155322.441))', - max_error=0.000000001) != 0: - return 'fail' + max_error=0.000000001) == 0) feat = lyr.GetNextFeature() - if feat.OWNER != 'Guarino "Chucky" Sandra': - gdaltest.post_reason('owner attribute wrong.') - return 'fail' + assert feat.OWNER == 'Guarino "Chucky" Sandra', 'owner attribute wrong.' lyr = None ds = None - return 'success' - ############################################################################### # Verify support for NTF datum with non-greenwich datum per # http://trac.osgeo.org/gdal/ticket/1416 @@ -355,58 +335,52 @@ def ogr_mitab_10(): # http://trac.osgeo.org/gdal/ticket/1680 -def ogr_mitab_11(): +def test_ogr_mitab_11(): if gdaltest.mapinfo_drv is None: - return 'skip' + pytest.skip() ds = ogr.Open('data/small_ntf.mif') srs = ds.GetLayer(0).GetSpatialRef() ds = None pm_value = srs.GetAttrValue('PROJCS|GEOGCS|PRIMEM', 1) - if pm_value[:6] != '2.3372': - gdaltest.post_reason('got unexpected prime meridian, not paris: ' + pm_value) - return 'fail' - - return 'success' + assert pm_value[:6] == '2.3372', \ + ('got unexpected prime meridian, not paris: ' + pm_value) ############################################################################### # Verify that a newly created mif layer returns a non null layer definition -def ogr_mitab_12(): +def test_ogr_mitab_12(): if gdaltest.mapinfo_drv is None: - return 'skip' + pytest.skip() ds = gdaltest.mapinfo_drv.CreateDataSource('tmp', options=['FORMAT=MIF']) lyr = ds.CreateLayer('testlyrdef') defn = lyr.GetLayerDefn() - if defn is None: - return 'fail' + assert defn is not None ogrtest.quick_create_layer_def(lyr, [('AREA', ogr.OFTReal)]) ds = None - return 'success' ############################################################################### # Verify that field widths and precisions are propagated correctly in TAB. -def ogr_mitab_13(): +def test_ogr_mitab_13(): if gdaltest.mapinfo_drv is None: - return 'skip' + pytest.skip() import ogr_gml_read - if ogr_gml_read.ogr_gml_1() != 'success': - return 'skip' + ogr_gml_read.test_ogr_gml_1() if test_cli_utilities.get_ogr2ogr_path() is None: - return 'skip' + pytest.skip() try: os.stat('tmp/testlyrdef.tab') @@ -420,9 +394,7 @@ def ogr_mitab_13(): # Check if the width and precision are as preserved. lyr = ds.GetLayer('testlyrdef') - if lyr is None: - gdaltest.post_reason('Layer missing.') - return 'fail' + assert lyr is not None, 'Layer missing.' defn = lyr.GetLayerDefn() @@ -433,31 +405,27 @@ def ogr_mitab_13(): for field in data: fld = defn.GetFieldDefn(defn.GetFieldIndex(field[0])) - if fld.GetType() != field[1] or fld.GetWidth() != field[2] or fld.GetPrecision() != field[3]: - gdaltest.post_reason(field[0] + ' field definition wrong.') - return 'fail' + assert fld.GetType() == field[1] and fld.GetWidth() == field[2] and fld.GetPrecision() == field[3], \ + (field[0] + ' field definition wrong.') ds = None ogr.GetDriverByName('MapInfo File').DeleteDataSource('tmp/testlyrdef.tab') - return 'success' - ############################################################################### # Verify that field widths and precisions are propagated correctly in MIF. -def ogr_mitab_14(): +def test_ogr_mitab_14(): if gdaltest.mapinfo_drv is None: - return 'skip' + pytest.skip() import ogr_gml_read - if ogr_gml_read.ogr_gml_1() != 'success': - return 'skip' + ogr_gml_read.test_ogr_gml_1() if test_cli_utilities.get_ogr2ogr_path() is None: - return 'skip' + pytest.skip() try: os.stat('tmp/testlyrdef.mif') @@ -471,9 +439,7 @@ def ogr_mitab_14(): # Check if the width and precision are as preserved. lyr = ds.GetLayer('testlyrdef') - if lyr is None: - gdaltest.post_reason('Layer missing.') - return 'fail' + assert lyr is not None, 'Layer missing.' defn = lyr.GetLayerDefn() @@ -487,30 +453,26 @@ def ogr_mitab_14(): expected_with = field[2] if fld.GetType() == ogr.OFTInteger: expected_with = 0 - if fld.GetType() != field[1] or fld.GetWidth() != expected_with or fld.GetPrecision() != field[3]: - gdaltest.post_reason(field[0] + ' field definition wrong.') - return 'fail' + assert fld.GetType() == field[1] and fld.GetWidth() == expected_with and fld.GetPrecision() == field[3], \ + (field[0] + ' field definition wrong.') ds = None ogr.GetDriverByName('MapInfo File').DeleteDataSource('tmp/testlyrdef.mif') - return 'success' - ############################################################################### # Test .mif without .mid (#5141) -def ogr_mitab_15(): +def test_ogr_mitab_15(): if gdaltest.mapinfo_drv is None: - return 'skip' + pytest.skip() ds = ogr.Open('data/nomid.mif') lyr = ds.GetLayer(0) feat = lyr.GetNextFeature() - if feat is None: - return 'fail' + assert feat is not None ds = None # Test opening .mif without .mid even if there are declared attributes @@ -528,21 +490,18 @@ def ogr_mitab_15(): lyr = ds.GetLayer(0) f = lyr.GetNextFeature() if f.IsFieldSet(0) or f.GetGeometryRef() is None: - gdaltest.post_reason('failure') f.DumpReadable() - return 'fail' + pytest.fail() gdal.Unlink('/vsimem/nomid.mif') - return 'success' - ############################################################################### # Test empty .mif -def ogr_mitab_16(): +def test_ogr_mitab_16(): if gdaltest.mapinfo_drv is None: - return 'skip' + pytest.skip() ds = ogr.GetDriverByName('MapInfo File').CreateDataSource('tmp/empty.mif') lyr = ds.CreateLayer('empty') @@ -550,49 +509,39 @@ def ogr_mitab_16(): ds = None ds = ogr.Open('tmp/empty.mif') - if ds is None: - return 'fail' + assert ds is not None ds = None - return 'success' - ############################################################################### # Run test_ogrsf -def ogr_mitab_17(): +def test_ogr_mitab_17(): if gdaltest.mapinfo_drv is None: - return 'skip' + pytest.skip() import ogr_gml_read - if ogr_gml_read.ogr_gml_1() != 'success': - return 'skip' + ogr_gml_read.test_ogr_gml_1() if test_cli_utilities.get_test_ogrsf_path() is None: - return 'skip' + pytest.skip() ret = gdaltest.runexternal(test_cli_utilities.get_test_ogrsf_path() + ' tmp') - if ret.find('INFO') == -1 or ret.find('ERROR') != -1: - print(ret) - return 'fail' + assert ret.find('INFO') != -1 and ret.find('ERROR') == -1 ret = gdaltest.runexternal(test_cli_utilities.get_test_ogrsf_path() + ' tmp/wrk.mif') - if ret.find('INFO') == -1 or ret.find('ERROR') != -1: - print(ret) - return 'fail' - - return 'success' + assert ret.find('INFO') != -1 and ret.find('ERROR') == -1 ############################################################################### # Test EPSG:2154 # (https://github.com/mapgears/mitab/issues/1) -def ogr_mitab_18(): +def test_ogr_mitab_18(): if gdaltest.mapinfo_drv is None: - return 'skip' + pytest.skip() ds = ogr.GetDriverByName('MapInfo File').CreateDataSource('/vsimem/ogr_mitab_18.tab') sr = osr.SpatialReference() @@ -608,30 +557,23 @@ def ogr_mitab_18(): sr_got = lyr.GetSpatialRef() wkt = sr_got.ExportToWkt() if wkt.find('2154') < 0: - gdaltest.post_reason('failure') print(filename) - print(sr_got) - return 'fail' + pytest.fail(sr_got) proj4 = sr_got.ExportToProj4() - if proj4.find('+proj=lcc +lat_1=49 +lat_2=44 +lat_0=46.5 +lon_0=3 +x_0=700000 +y_0=6600000 +ellps=GRS80 +towgs84=0,0,0,0,0,0,0 +units=m +no_defs') != 0: - gdaltest.post_reason('failure') - print(proj4) - return 'fail' + assert proj4.find('+proj=lcc +lat_1=49 +lat_2=44 +lat_0=46.5 +lon_0=3 +x_0=700000 +y_0=6600000 +ellps=GRS80 +towgs84=0,0,0,0,0,0,0 +units=m +no_defs') == 0 ds = None ogr.GetDriverByName('MapInfo File').DeleteDataSource('/vsimem/ogr_mitab_18.tab') - return 'success' - ############################################################################### # Check that we correctly round coordinate to the appropriate precision # (https://github.com/mapgears/mitab/issues/2) -def ogr_mitab_19(): +def test_ogr_mitab_19(): if gdaltest.mapinfo_drv is None: - return 'skip' + pytest.skip() ds = ogr.Open('data/utm31.TAB') lyr = ds.GetLayer(0) @@ -639,20 +581,19 @@ def ogr_mitab_19(): # Strict text comparison to check precision if feat.GetGeometryRef().ExportToWkt() != 'POINT (485248.12 2261.45)': feat.DumpReadable() - return 'fail' - - return 'success' + pytest.fail() + ############################################################################### # Check that we take into account the user defined bound file # (https://github.com/mapgears/mitab/issues/3) # Also test BOUNDS layer creation option (http://trac.osgeo.org/gdal/ticket/5642) -def ogr_mitab_20(): +def test_ogr_mitab_20(): if gdaltest.mapinfo_drv is None: - return 'skip' + pytest.skip() # Pass i==0: without MITAB_BOUNDS_FILE # Pass i==1: with MITAB_BOUNDS_FILE and French bounds : first load @@ -717,28 +658,20 @@ def ogr_mitab_20(): ds = ogr.Open('/vsimem/ogr_mitab_20.' + fmt) lyr = ds.GetLayer(0) feat = lyr.GetNextFeature() - if i == 6 and lyr.GetSpatialRef().ExportToWkt().find('49.00000000001') < 0: - gdaltest.post_reason('fail') - print(fmt) - print(i) - print(lyr.GetSpatialRef().ExportToWkt()) - return 'fail' + assert not (i == 6 and lyr.GetSpatialRef().ExportToWkt().find('49.00000000001') < 0), \ + fmt # Strict text comparison to check precision if fmt == 'tab': if i == 1 or i == 2 or i == 4: if feat.GetGeometryRef().ExportToWkt() != 'POINT (700000.001 6600000.001)': - gdaltest.post_reason('fail') - print(fmt) print(i) feat.DumpReadable() - return 'fail' + pytest.fail(fmt) else: if feat.GetGeometryRef().ExportToWkt() == 'POINT (700000.001 6600000.001)': - gdaltest.post_reason('fail') - print(fmt) print(i) feat.DumpReadable() - return 'fail' + pytest.fail(fmt) ds = None @@ -779,28 +712,24 @@ def ogr_mitab_20(): else: expected = '49.00000000002' if lyr.GetSpatialRef().ExportToWkt().find(expected) < 0: - gdaltest.post_reason('fail') - print(lyr.GetSpatialRef().ExportToWkt()) print(i) gdal.SetConfigOption('MITAB_BOUNDS_FILE', None) os.unlink('tmp/mitab_bounds.txt') - return 'fail' + pytest.fail(lyr.GetSpatialRef().ExportToWkt()) ds = None ogr.GetDriverByName('MapInfo File').DeleteDataSource('/vsimem/ogr_mitab_20.tab') gdal.SetConfigOption('MITAB_BOUNDS_FILE', None) os.unlink('tmp/mitab_bounds.txt') - return 'success' - ############################################################################### # Create .tab without explicit field -def ogr_mitab_21(): +def test_ogr_mitab_21(): if gdaltest.mapinfo_drv is None: - return 'skip' + pytest.skip() ds = ogr.GetDriverByName('MapInfo File').CreateDataSource('/vsimem/ogr_mitab_21.tab') lyr = ds.CreateLayer('test') @@ -816,18 +745,16 @@ def ogr_mitab_21(): feat = lyr.GetNextFeature() if feat.GetField('FID') != 1: feat.DumpReadable() - return 'fail' + pytest.fail() ds = None ogr.GetDriverByName('MapInfo File').DeleteDataSource('/vsimem/ogr_mitab_21.tab') - return 'success' - ############################################################################### # Test append in update mode -def ogr_mitab_22(): +def test_ogr_mitab_22(): filename = '/vsimem/ogr_mitab_22.tab' for nb_features in (2, 1000): @@ -849,9 +776,7 @@ def ogr_mitab_22(): feat.SetGeometryDirectly(ogr.CreateGeometryFromWkt("POINT (%d %d)" % (i, i))) if lyr.CreateFeature(feat) != 0: print(i) - print(nb_features) - gdaltest.post_reason('fail') - return 'fail' + pytest.fail(nb_features) ds = None for i in range(nb_features - (1 - j)): @@ -862,31 +787,23 @@ def ogr_mitab_22(): feat.SetGeometryDirectly(ogr.CreateGeometryFromWkt("POINT (%d %d)" % (i + (1 - j), i + (1 - j)))) if lyr.CreateFeature(feat) != 0: print(i) - print(nb_features) - gdaltest.post_reason('fail') - return 'fail' + pytest.fail(nb_features) ds = None ds = ogr.Open(filename) lyr = ds.GetLayer(0) for i in range(nb_features): f = lyr.GetNextFeature() - if f is None or f.GetField('ID') != i + 1: - print(nb_features) - print(i) - gdaltest.post_reason('fail') - return 'fail' + assert f is not None and f.GetField('ID') == i + 1, nb_features ds = None ogr.GetDriverByName('MapInfo File').DeleteDataSource(filename) - return 'success' - ############################################################################### # Test creating features then reading -def ogr_mitab_23(): +def test_ogr_mitab_23(): filename = '/vsimem/ogr_mitab_23.tab' @@ -903,26 +820,19 @@ def ogr_mitab_23(): lyr.ResetReading() for i in range(nb_features): f = lyr.GetNextFeature() - if f is None or f.GetField('ID') != i + 1: - print(nb_features) - print(i) - gdaltest.post_reason('fail') - return 'fail' + assert f is not None and f.GetField('ID') == i + 1, nb_features f = lyr.GetNextFeature() - if f is not None: - gdaltest.post_reason('fail') - return 'fail' + assert f is None ds = None ogr.GetDriverByName('MapInfo File').DeleteDataSource(filename) - return 'success' - + ############################################################################### # Test creating features then reading then creating again then reading -def ogr_mitab_24(): +def test_ogr_mitab_24(): filename = '/vsimem/ogr_mitab_24.tab' @@ -939,15 +849,9 @@ def ogr_mitab_24(): lyr.ResetReading() for i in range(int(nb_features / 2)): f = lyr.GetNextFeature() - if f is None or f.GetField('ID') != i + 1: - print(nb_features) - print(i) - gdaltest.post_reason('fail') - return 'fail' + assert f is not None and f.GetField('ID') == i + 1, nb_features f = lyr.GetNextFeature() - if f is not None: - gdaltest.post_reason('fail') - return 'fail' + assert f is None for i in range(int(nb_features / 2)): feat = ogr.Feature(lyr.GetLayerDefn()) @@ -958,28 +862,21 @@ def ogr_mitab_24(): lyr.ResetReading() for i in range(nb_features): f = lyr.GetNextFeature() - if f is None or f.GetField('ID') != i + 1: - print(nb_features) - print(i) - gdaltest.post_reason('fail') - return 'fail' + assert f is not None and f.GetField('ID') == i + 1, nb_features f = lyr.GetNextFeature() - if f is not None: - gdaltest.post_reason('fail') - return 'fail' + assert f is None ds = None ogr.GetDriverByName('MapInfo File').DeleteDataSource(filename) - return 'success' - + ############################################################################### # Test that opening in update mode without doing any change does not alter # file -def ogr_mitab_25(): +def test_ogr_mitab_25(): filename = 'tmp/ogr_mitab_25.tab' @@ -1010,10 +907,7 @@ def ogr_mitab_25(): ds = None for ext in ('map', 'tab', 'dat', 'id'): mtime = os.stat(filename[0:-3] + ext).st_mtime - if mtime_dict[ext] != mtime: - print('mtime of .%s has changed !' % ext) - gdaltest.post_reason('fail') - return 'fail' + assert mtime_dict[ext] == mtime, ('mtime of .%s has changed !' % ext) # Try by reading all features ds = ogr.Open(filename, update=1) @@ -1022,10 +916,7 @@ def ogr_mitab_25(): ds = None for ext in ('map', 'tab', 'dat', 'id'): mtime = os.stat(filename[0:-3] + ext).st_mtime - if mtime_dict[ext] != mtime: - print('mtime of .%s has changed !' % ext) - gdaltest.post_reason('fail') - return 'fail' + assert mtime_dict[ext] == mtime, ('mtime of .%s has changed !' % ext) # Try by reading all features with a spatial index ds = ogr.Open(filename, update=1) @@ -1035,26 +926,20 @@ def ogr_mitab_25(): ds = None for ext in ('map', 'tab', 'dat', 'id'): mtime = os.stat(filename[0:-3] + ext).st_mtime - if mtime_dict[ext] != mtime: - print('mtime of .%s has changed !' % ext) - gdaltest.post_reason('fail') - return 'fail' + assert mtime_dict[ext] == mtime, ('mtime of .%s has changed !' % ext) if test_cli_utilities.get_test_ogrsf_path() is not None: ret = gdaltest.runexternal(test_cli_utilities.get_test_ogrsf_path() + ' -ro -fsf ' + filename) - if ret.find('INFO') == -1 or ret.find('ERROR') != -1: - print(ret) - return 'fail' + assert ret.find('INFO') != -1 and ret.find('ERROR') == -1 ogr.GetDriverByName('MapInfo File').DeleteDataSource(filename) - return 'success' - + ############################################################################### # Test DeleteFeature() -def ogr_mitab_26(): +def test_ogr_mitab_26(): filename = '/vsimem/ogr_mitab_26.tab' @@ -1074,52 +959,34 @@ def ogr_mitab_26(): lyr.CreateFeature(feat) if nb_features == 2: - if lyr.DeleteFeature(int(nb_features / 2)) != 0: - print(j) - print(nb_features) - gdaltest.post_reason('fail') - return 'fail' + assert lyr.DeleteFeature(int(nb_features / 2)) == 0, j else: for k in range(int(nb_features / 2)): - if lyr.DeleteFeature(int(nb_features / 4) + k) != 0: - print(j) - print(k) - print(nb_features) - gdaltest.post_reason('fail') - return 'fail' + assert lyr.DeleteFeature(int(nb_features / 4) + k) == 0, j if j == 1: # Expected failure : already deleted feature ret = lyr.DeleteFeature(int(nb_features / 2)) if ret != ogr.OGRERR_NON_EXISTING_FEATURE: print(j) - print(nb_features) - gdaltest.post_reason('fail') - return 'fail' + pytest.fail(nb_features) feat = lyr.GetFeature(int(nb_features / 2)) if feat is not None: print(j) - print(nb_features) - gdaltest.post_reason('fail') - return 'fail' + pytest.fail(nb_features) # Expected failure : illegal feature id ret = lyr.DeleteFeature(nb_features + 1) if ret != ogr.OGRERR_NON_EXISTING_FEATURE: print(j) - print(nb_features) - gdaltest.post_reason('fail') - return 'fail' + pytest.fail(nb_features) ds = None ds = ogr.Open(filename) lyr = ds.GetLayer(0) - if lyr.GetFeatureCount() != nb_features / 2: - print(nb_features) - gdaltest.post_reason('fail') - return 'fail' + assert lyr.GetFeatureCount() == nb_features / 2 ds = None # This used to trigger a bug in DAT record deletion during implementation... @@ -1131,21 +998,17 @@ def ogr_mitab_26(): ds = ogr.Open(filename) lyr = ds.GetLayer(0) - if lyr.GetFeatureCount() != nb_features / 2 - 1: - print(nb_features) - gdaltest.post_reason('fail') - return 'fail' + assert lyr.GetFeatureCount() == nb_features / 2 - 1 ds = None ogr.GetDriverByName('MapInfo File').DeleteDataSource(filename) - return 'success' - + ############################################################################### # Test SetFeature() -def ogr_mitab_27(): +def test_ogr_mitab_27(): filename = '/vsimem/ogr_mitab_27.tab' @@ -1160,9 +1023,7 @@ def ogr_mitab_27(): gdal.PushErrorHandler('CPLQuietErrorHandler') ret = lyr.SetFeature(f) gdal.PopErrorHandler() - if ret == 0: - gdaltest.post_reason('fail') - return 'fail' + assert ret != 0 # Invalid call : feature with FID <= 0 f = ogr.Feature(lyr.GetLayerDefn()) @@ -1170,9 +1031,7 @@ def ogr_mitab_27(): gdal.PushErrorHandler('CPLQuietErrorHandler') ret = lyr.SetFeature(f) gdal.PopErrorHandler() - if ret == 0: - gdaltest.post_reason('fail') - return 'fail' + assert ret != 0 f = ogr.Feature(lyr.GetLayerDefn()) f.SetField('intfield', 1) @@ -1188,9 +1047,7 @@ def ogr_mitab_27(): gdal.PushErrorHandler('CPLQuietErrorHandler') ret = lyr.SetFeature(f) gdal.PopErrorHandler() - if ret == 0: - gdaltest.post_reason('fail') - return 'fail' + assert ret != 0 # Update previously created object with blank feature f = ogr.Feature(lyr.GetLayerDefn()) @@ -1204,9 +1061,8 @@ def ogr_mitab_27(): f = lyr.GetNextFeature() if f.GetField('intfield') != 0 or f.GetField('realfield') != 0 or f.GetField('stringfield') != '' or \ f.GetGeometryRef() is not None: - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' + pytest.fail() f.SetField('intfield', 1) f.SetField('realfield', 2.34) @@ -1220,9 +1076,8 @@ def ogr_mitab_27(): f = lyr.GetNextFeature() if f.GetField('intfield') != 1 or f.GetField('realfield') != 2.34 or f.GetField('stringfield') != 'foo' or \ f.GetGeometryRef() is None: - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' + pytest.fail() lyr.DeleteFeature(f.GetFID()) ds = None @@ -1235,9 +1090,8 @@ def ogr_mitab_27(): f = lyr.GetFeature(1) if f.GetField('intfield') != 1 or f.GetField('realfield') != 2.34 or f.GetField('stringfield') != 'foo' or \ f.GetGeometryRef() is None: - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' + pytest.fail() ds = None ds = ogr.Open(filename, update=1) @@ -1245,9 +1099,7 @@ def ogr_mitab_27(): f = lyr.GetFeature(1) # SetFeature() with identical feature : no-op - if lyr.SetFeature(f) != 0: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.SetFeature(f) == 0 ds = None stat = gdal.VSIStatL(filename[0:-3] + "map") @@ -1262,15 +1114,11 @@ def ogr_mitab_27(): f = lyr.GetFeature(1) for _ in range(100): f.SetGeometryDirectly(ogr.CreateGeometryFromWkt('POINT (2 3)')) - if lyr.SetFeature(f) != 0: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.SetFeature(f) == 0 ds = None stat = gdal.VSIStatL(filename[0:-3] + "map") - if stat.size != old_size: - gdaltest.post_reason('fail') - return 'fail' + assert stat.size == old_size ds = ogr.Open(filename, update=1) lyr = ds.GetLayer(0) @@ -1278,23 +1126,18 @@ def ogr_mitab_27(): f = lyr.GetFeature(1) # SetFeature() with identical geometry : rewrite only attributes f.SetField('intfield', -1) - if lyr.SetFeature(f) != 0: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.SetFeature(f) == 0 f = lyr.GetFeature(1) if f.GetField('intfield') != -1 or f.GetField('realfield') != 2.34 or f.GetField('stringfield') != 'foo' or \ f.GetGeometryRef() is None: - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' + pytest.fail() ds = None ogr.GetDriverByName('MapInfo File').DeleteDataSource(filename) - return 'success' - ############################################################################### @@ -1311,7 +1154,7 @@ def generate_permutation(n): # Test updating object blocks with deleted objects -def ogr_mitab_28(): +def test_ogr_mitab_28(): filename = '/vsimem/ogr_mitab_28.tab' @@ -1362,9 +1205,7 @@ def ogr_mitab_28(): n = permutation[i] x_ref = int(n / N2) y_ref = n % N2 - if abs(x - x_ref) + abs(y - y_ref) > 0.1: - gdaltest.post_reason('fail') - return 'fail' + assert abs(x - x_ref) + abs(y - y_ref) <= 0.1 i = i + 1 # Check spatial index integrity @@ -1372,21 +1213,17 @@ def ogr_mitab_28(): x = int(n / N2) y = n % N2 lyr.SetSpatialFilterRect(x - 0.5, y - 0.5, x + 0.5, y + 0.5) - if lyr.GetFeatureCount() != 1: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.GetFeatureCount() == 1 ds = None ogr.GetDriverByName('MapInfo File').DeleteDataSource(filename) - return 'success' - ############################################################################### # Test updating a file with compressed geometries. -def ogr_mitab_29(): +def test_ogr_mitab_29(): try: os.stat('tmp/cache/compr_symb_deleted_records.tab') except OSError: @@ -1395,9 +1232,9 @@ def ogr_mitab_29(): try: os.stat('tmp/cache/compr_symb_deleted_records.tab') except OSError: - return 'skip' + pytest.skip() except OSError: - return 'skip' + pytest.skip() shutil.copy('tmp/cache/compr_symb_deleted_records.tab', 'tmp') shutil.copy('tmp/cache/compr_symb_deleted_records.dat', 'tmp') @@ -1430,36 +1267,27 @@ def ogr_mitab_29(): lyr.SetSpatialFilterRect(x - 0.01, y - 0.01, x + 0.01, y + 0.01) if lyr.GetFeatureCount() != 1: print(n) - print(lyr.GetFeatureCount()) - print(x - 0.01, y - 0.01, x + 0.01, y + 0.01) - gdaltest.post_reason('fail') - return 'fail' + pytest.fail(x - 0.01, y - 0.01, x + 0.01, y + 0.01) ds = None ogr.GetDriverByName('MapInfo File').DeleteDataSource('tmp/compr_symb_deleted_records.tab') - return 'success' - ############################################################################### # Test SyncToDisk() in create mode -def ogr_mitab_30(update=0): +def test_ogr_mitab_30(update=0): filename = 'tmp/ogr_mitab_30.tab' ds = ogr.GetDriverByName('MapInfo File').CreateDataSource(filename) lyr = ds.CreateLayer('test', options=['BOUNDS=0,0,100,100']) lyr.CreateField(ogr.FieldDefn('ID', ogr.OFTInteger)) - if lyr.SyncToDisk() != 0: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.SyncToDisk() == 0 ds2 = ogr.Open(filename) lyr2 = ds2.GetLayer(0) - if lyr2.GetFeatureCount() != 0 or lyr2.GetLayerDefn().GetFieldCount() != 1: - gdaltest.post_reason('fail') - return 'fail' + assert lyr2.GetFeatureCount() == 0 and lyr2.GetLayerDefn().GetFieldCount() == 1 ds2 = None # Check that the files are not updated in between @@ -1474,14 +1302,10 @@ def ogr_mitab_30(update=0): if not sys.platform.startswith('linux'): time.sleep(1) - if lyr.SyncToDisk() != 0: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.SyncToDisk() == 0 for ext in ('map', 'tab', 'dat', 'id'): stat2 = gdal.VSIStatL(filename[0:-3] + ext) - if stat[ext].size != stat2.size or stat[ext].mtime != stat2.mtime: - gdaltest.post_reason('fail') - return 'fail' + assert stat[ext].size == stat2.size and stat[ext].mtime == stat2.mtime if update == 1: ds = None @@ -1500,9 +1324,7 @@ def ogr_mitab_30(update=0): for i in range(2): ret = lyr.SyncToDisk() - if ret != 0: - gdaltest.post_reason('fail') - return 'fail' + assert ret == 0 if i == 0: for ext in ('map', 'tab', 'dat', 'id'): @@ -1511,96 +1333,67 @@ def ogr_mitab_30(update=0): for ext in ('map', 'tab', 'dat', 'id'): stat2 = gdal.VSIStatL(filename[0:-3] + ext) if stat[ext].size != stat2.size: - print(ext) print(j) - print(i) - gdaltest.post_reason('fail') - return 'fail' + pytest.fail(i) ds2 = ogr.Open(filename) lyr2 = ds2.GetLayer(0) - if lyr2.GetFeatureCount() != j + 1: - print(j) - print(i) - gdaltest.post_reason('fail') - return 'fail' + assert lyr2.GetFeatureCount() == j + 1, i feat2 = lyr2.GetFeature(j + 1) if feat2.GetField('ID') != j + 1 or feat2.GetGeometryRef().ExportToWkt() != 'POINT (%d %d)' % (j, j): - print(j) print(i) feat2.DumpReadable() - gdaltest.post_reason('fail') - return 'fail' + pytest.fail(j) lyr2.ResetReading() for _ in range(j + 1): feat2 = lyr2.GetNextFeature() if feat2.GetField('ID') != j + 1 or feat2.GetGeometryRef().ExportToWkt() != 'POINT (%d %d)' % (j, j): - print(j) print(i) feat2.DumpReadable() - gdaltest.post_reason('fail') - return 'fail' + pytest.fail(j) ds2 = None ds = None ogr.GetDriverByName('MapInfo File').DeleteDataSource(filename) - return 'success' - ############################################################################### # Test SyncToDisk() in update mode -def ogr_mitab_31(): - return ogr_mitab_30(update=1) +def test_ogr_mitab_31(): + return test_ogr_mitab_30(update=1) ############################################################################### # Check read support of non-spatial .tab/.data without .map or .id (#5718) # We only check read-only behaviour though. -def ogr_mitab_32(): +def test_ogr_mitab_32(): for update in (0, 1): ds = ogr.Open('data/aspatial-table.tab', update=update) lyr = ds.GetLayer(0) - if lyr.GetFeatureCount() != 2: - print(update) - gdaltest.post_reason('fail') - return 'fail' + assert lyr.GetFeatureCount() == 2, update f = lyr.GetNextFeature() - if f.GetField('a') != 1 or f.GetField('b') != 2 or f.GetField('d') != 'hello': - print(update) - gdaltest.post_reason('fail') - return 'fail' + assert f.GetField('a') == 1 and f.GetField('b') == 2 and f.GetField('d') == 'hello', \ + update f = lyr.GetFeature(2) - if f.GetField('a') != 4: - print(update) - gdaltest.post_reason('fail') - return 'fail' + assert f.GetField('a') == 4, update ds = None - return 'success' - ############################################################################### # Test opening and modifying a file created with MapInfo that consists of # a single object block, without index block -def ogr_mitab_33(): +def test_ogr_mitab_33(): for update in (0, 1): ds = ogr.Open('data/single_point_mapinfo.tab', update=update) lyr = ds.GetLayer(0) - if lyr.GetFeatureCount() != 1: - print(update) - gdaltest.post_reason('fail') - return 'fail' + assert lyr.GetFeatureCount() == 1, update f = lyr.GetNextFeature() - if f.GetField('toto') != '': - print(update) - gdaltest.post_reason('fail') - return 'fail' + assert f.GetField('toto') == '', update ds = None # Test adding a new object @@ -1619,17 +1412,11 @@ def ogr_mitab_33(): ds = ogr.Open('tmp/single_point_mapinfo.tab') lyr = ds.GetLayer(0) - if lyr.GetFeatureCount() != 2: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.GetFeatureCount() == 2 f = lyr.GetNextFeature() - if f is None: - gdaltest.post_reason('fail') - return 'fail' + assert f is not None f = lyr.GetNextFeature() - if f is None: - gdaltest.post_reason('fail') - return 'fail' + assert f is not None ds = None # Test replacing the existing object @@ -1649,24 +1436,18 @@ def ogr_mitab_33(): ds = ogr.Open('tmp/single_point_mapinfo.tab') lyr = ds.GetLayer(0) - if lyr.GetFeatureCount() != 1: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.GetFeatureCount() == 1 f = lyr.GetNextFeature() - if f is None: - gdaltest.post_reason('fail') - return 'fail' + assert f is not None ds = None ogr.GetDriverByName('MapInfo File').DeleteDataSource('tmp/single_point_mapinfo.tab') - return 'success' - ############################################################################### # Test updating a line that spans over several coordinate blocks -def ogr_mitab_34(): +def test_ogr_mitab_34(): filename = '/vsimem/ogr_mitab_34.tab' ds = ogr.GetDriverByName('MapInfo File').CreateDataSource(filename) @@ -1695,25 +1476,17 @@ def ogr_mitab_34(): lyr = ds.GetLayer(0) f = lyr.GetNextFeature() geom = f.GetGeometryRef() - if abs(geom.GetX(0) - -1000) > 1e-2 or abs(geom.GetY(0) - 3000) > 1e-2: - gdaltest.post_reason('fail') - return 'fail' + assert abs(geom.GetX(0) - -1000) <= 1e-2 and abs(geom.GetY(0) - 3000) <= 1e-2 for i in range(999): - if abs(geom.GetX(i + 1) - (i + 1)) > 1e-2 or abs(geom.GetY(i + 1) - (i + 1)) > 1e-2: - gdaltest.post_reason('fail') - return 'fail' + assert abs(geom.GetX(i + 1) - (i + 1)) <= 1e-2 and abs(geom.GetY(i + 1) - (i + 1)) <= 1e-2 f = lyr.GetNextFeature() geom = f.GetGeometryRef() for i in range(1000): - if abs(geom.GetX(i) - (i)) > 1e-2 or abs(geom.GetY(i) - (i)) > 1e-2: - gdaltest.post_reason('fail') - return 'fail' + assert abs(geom.GetX(i) - (i)) <= 1e-2 and abs(geom.GetY(i) - (i)) <= 1e-2 ds = None ogr.GetDriverByName('MapInfo File').DeleteDataSource(filename) - return 'success' - ############################################################################### # Test SRS support @@ -1771,28 +1544,19 @@ def get_coordsys_from_srs(srs): return data -def ogr_mitab_35(): +def test_ogr_mitab_35(): # Local/non-earth srs = osr.SpatialReference() coordsys = get_coordsys_from_srs(srs) - if coordsys != 'CoordSys NonEarth Units "m"': - gdaltest.post_reason('fail') - print(coordsys) - return 'fail' + assert coordsys == 'CoordSys NonEarth Units "m"' srs = osr.SpatialReference('LOCAL_CS["foo"]') coordsys = get_coordsys_from_srs(srs) - if coordsys != 'CoordSys NonEarth Units "m"': - gdaltest.post_reason('fail') - print(coordsys) - return 'fail' + assert coordsys == 'CoordSys NonEarth Units "m"' srs = get_srs_from_coordsys(coordsys) wkt = srs.ExportToWkt() - if wkt != 'LOCAL_CS["Nonearth",UNIT["Meter",1.0]]': - gdaltest.post_reason('fail') - print(wkt) - return 'fail' + assert wkt == 'LOCAL_CS["Nonearth",UNIT["Meter",1.0]]' # Test units for mif_unit in ['mi', 'km', 'in', 'ft', 'yd', 'mm', 'cm', 'm', 'survey ft', 'nmi', 'li', 'ch', 'rd']: @@ -1800,52 +1564,29 @@ def ogr_mitab_35(): srs = get_srs_from_coordsys(coordsys) # print(srs) got_coordsys = get_coordsys_from_srs(srs) - if coordsys != got_coordsys: - gdaltest.post_reason('fail') - print(coordsys) - print(srs) - print(got_coordsys) - return 'fail' + assert coordsys == got_coordsys, srs # Geographic srs = osr.SpatialReference() srs.ImportFromEPSG(4326) coordsys = get_coordsys_from_srs(srs) - if coordsys != 'CoordSys Earth Projection 1, 104': - gdaltest.post_reason('fail') - print(coordsys) - return 'fail' + assert coordsys == 'CoordSys Earth Projection 1, 104' srs = get_srs_from_coordsys(coordsys) wkt = srs.ExportToWkt() - if wkt != 'GEOGCS["unnamed",DATUM["WGS_1984",SPHEROID["WGS 84",6378137,298.257223563],TOWGS84[0,0,0,0,0,0,0]],PRIMEM["Greenwich",0],UNIT["degree",0.0174532925199433]]': - gdaltest.post_reason('fail') - print(wkt) - return 'fail' + assert wkt == 'GEOGCS["unnamed",DATUM["WGS_1984",SPHEROID["WGS 84",6378137,298.257223563],TOWGS84[0,0,0,0,0,0,0]],PRIMEM["Greenwich",0],UNIT["degree",0.0174532925199433]]' coordsys = get_coordsys_from_srs(srs) - if coordsys != 'CoordSys Earth Projection 1, 104': - gdaltest.post_reason('fail') - print(coordsys) - return 'fail' + assert coordsys == 'CoordSys Earth Projection 1, 104' # Projected srs = osr.SpatialReference() srs.ImportFromEPSG(32631) coordsys = get_coordsys_from_srs(srs) - if coordsys != 'CoordSys Earth Projection 8, 104, "m", 3, 0, 0.9996, 500000, 0': - gdaltest.post_reason('fail') - print(coordsys) - return 'fail' + assert coordsys == 'CoordSys Earth Projection 8, 104, "m", 3, 0, 0.9996, 500000, 0' srs = get_srs_from_coordsys(coordsys) wkt = srs.ExportToWkt() - if wkt != 'PROJCS["unnamed",GEOGCS["unnamed",DATUM["WGS_1984",SPHEROID["WGS 84",6378137,298.257223563],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",3],PARAMETER["scale_factor",0.9996],PARAMETER["false_easting",500000],PARAMETER["false_northing",0],UNIT["Meter",1.0]]': - gdaltest.post_reason('fail') - print(wkt) - return 'fail' + assert wkt == 'PROJCS["unnamed",GEOGCS["unnamed",DATUM["WGS_1984",SPHEROID["WGS 84",6378137,298.257223563],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",3],PARAMETER["scale_factor",0.9996],PARAMETER["false_easting",500000],PARAMETER["false_northing",0],UNIT["Meter",1.0]]' coordsys = get_coordsys_from_srs(srs) - if coordsys != 'CoordSys Earth Projection 8, 104, "m", 3, 0, 0.9996, 500000, 0': - gdaltest.post_reason('fail') - print(coordsys) - return 'fail' + assert coordsys == 'CoordSys Earth Projection 8, 104, "m", 3, 0, 0.9996, 500000, 0' # Test round-tripping of projection methods for coordsys in ['CoordSys Earth Projection 1, 104', @@ -1887,74 +1628,42 @@ def ogr_mitab_35(): got_coordsys = get_coordsys_from_srs(srs) # if got_coordsys.find(' Bounds') >= 0: # got_coordsys = got_coordsys[0:got_coordsys.find(' Bounds')] - if coordsys != got_coordsys: - gdaltest.post_reason('fail') - print(coordsys) - print(srs) - print(got_coordsys) - return 'fail' + assert coordsys == got_coordsys, srs # Test TOWGS84 srs = osr.SpatialReference() srs.ImportFromEPSG(4322) coordsys = get_coordsys_from_srs(srs) - if coordsys != 'CoordSys Earth Projection 1, 103': - gdaltest.post_reason('fail') - print(coordsys) - return 'fail' + assert coordsys == 'CoordSys Earth Projection 1, 103' srs = get_srs_from_coordsys(coordsys) wkt = srs.ExportToWkt() - if wkt != 'GEOGCS["unnamed",DATUM["WGS_1972",SPHEROID["WGS 72",6378135,298.26],TOWGS84[0,8,10,0,0,0,0]],PRIMEM["Greenwich",0],UNIT["degree",0.0174532925199433]]': - gdaltest.post_reason('fail') - print(wkt) - return 'fail' + assert wkt == 'GEOGCS["unnamed",DATUM["WGS_1972",SPHEROID["WGS 72",6378135,298.26],TOWGS84[0,8,10,0,0,0,0]],PRIMEM["Greenwich",0],UNIT["degree",0.0174532925199433]]' coordsys = get_coordsys_from_srs(srs) - if coordsys != 'CoordSys Earth Projection 1, 103': - gdaltest.post_reason('fail') - print(coordsys) - return 'fail' + assert coordsys == 'CoordSys Earth Projection 1, 103' # Test Lambert 93 srs = osr.SpatialReference() srs.ImportFromEPSG(2154) coordsys = get_coordsys_from_srs(srs) - if coordsys != 'CoordSys Earth Projection 3, 33, "m", 3, 46.5, 44, 49, 700000, 6600000': - gdaltest.post_reason('fail') - print(coordsys) - return 'fail' + assert coordsys == 'CoordSys Earth Projection 3, 33, "m", 3, 46.5, 44, 49, 700000, 6600000' srs = get_srs_from_coordsys(coordsys) wkt = srs.ExportToWkt() - if wkt != 'PROJCS["RGF93 / Lambert-93",GEOGCS["RGF93",DATUM["Reseau_Geodesique_Francais_1993",SPHEROID["GRS 80",6378137,298.257222101],TOWGS84[0,0,0,0,0,0,0]],PRIMEM["Greenwich",0],UNIT["degree",0.0174532925199433]],PROJECTION["Lambert_Conformal_Conic_2SP"],PARAMETER["standard_parallel_1",49],PARAMETER["standard_parallel_2",44],PARAMETER["latitude_of_origin",46.5],PARAMETER["central_meridian",3],PARAMETER["false_easting",700000],PARAMETER["false_northing",6600000],UNIT["Meter",1.0],AUTHORITY["EPSG","2154"]]': - gdaltest.post_reason('fail') - print(wkt) - return 'fail' + assert wkt == 'PROJCS["RGF93 / Lambert-93",GEOGCS["RGF93",DATUM["Reseau_Geodesique_Francais_1993",SPHEROID["GRS 80",6378137,298.257222101],TOWGS84[0,0,0,0,0,0,0]],PRIMEM["Greenwich",0],UNIT["degree",0.0174532925199433]],PROJECTION["Lambert_Conformal_Conic_2SP"],PARAMETER["standard_parallel_1",49],PARAMETER["standard_parallel_2",44],PARAMETER["latitude_of_origin",46.5],PARAMETER["central_meridian",3],PARAMETER["false_easting",700000],PARAMETER["false_northing",6600000],UNIT["Meter",1.0],AUTHORITY["EPSG","2154"]]' coordsys = get_coordsys_from_srs(srs) - if coordsys != 'CoordSys Earth Projection 3, 33, "m", 3, 46.5, 44, 49, 700000, 6600000': - gdaltest.post_reason('fail') - print(coordsys) - return 'fail' + assert coordsys == 'CoordSys Earth Projection 3, 33, "m", 3, 46.5, 44, 49, 700000, 6600000' srs = osr.SpatialReference('PROJCS["RGF93 / Lambert-93",GEOGCS["RGF93",DATUM["Reseau_Geodesique_Francais_1993",SPHEROID["GRS 80",6378137,298.257222101],TOWGS84[0,0,0,0,0,0,0]],PRIMEM["Greenwich",0],UNIT["degree",0.0174532925199433]],PROJECTION["Lambert_Conformal_Conic_2SP"],PARAMETER["standard_parallel_1",49.00000000002],PARAMETER["standard_parallel_2",44],PARAMETER["latitude_of_origin",46.5],PARAMETER["central_meridian",3],PARAMETER["false_easting",700000],PARAMETER["false_northing",6600000],UNIT["Meter",1.0],AUTHORITY["EPSG","2154"]]') coordsys = get_coordsys_from_srs(srs) - if coordsys != 'CoordSys Earth Projection 3, 33, "m", 3, 46.5, 44, 49.00000000002, 700000, 6600000': - gdaltest.post_reason('fail') - print(coordsys) - return 'fail' + assert coordsys == 'CoordSys Earth Projection 3, 33, "m", 3, 46.5, 44, 49.00000000002, 700000, 6600000' gdal.SetConfigOption('MITAB_BOUNDS_FILE', 'data/mitab_bounds.txt') coordsys = get_coordsys_from_srs(srs) gdal.SetConfigOption('MITAB_BOUNDS_FILE', None) - if coordsys != 'CoordSys Earth Projection 3, 33, "m", 3, 46.5, 44, 49.00000000002, 700000, 6600000 Bounds (75000, 6000000) (1275000, 7200000)': - gdaltest.post_reason('fail') - print(coordsys) - return 'fail' + assert coordsys == 'CoordSys Earth Projection 3, 33, "m", 3, 46.5, 44, 49.00000000002, 700000, 6600000 Bounds (75000, 6000000) (1275000, 7200000)' # http://trac.osgeo.org/gdal/ticket/4115 srs = get_srs_from_coordsys('CoordSys Earth Projection 10, 157, "m", 0') wkt = srs.ExportToWkt() - if wkt != 'PROJCS["WGS 84 / Pseudo-Mercator",GEOGCS["unnamed",DATUM["WGS_1984",SPHEROID["WGS 84 (MAPINFO Datum 157)",6378137.01,298.257223563],TOWGS84[0,0,0,0,0,0,0]],PRIMEM["Greenwich",0],UNIT["degree",0.0174532925199433]],PROJECTION["Mercator_1SP"],PARAMETER["central_meridian",0],PARAMETER["scale_factor",1],PARAMETER["false_easting",0],PARAMETER["false_northing",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' + assert wkt == 'PROJCS["WGS 84 / Pseudo-Mercator",GEOGCS["unnamed",DATUM["WGS_1984",SPHEROID["WGS 84 (MAPINFO Datum 157)",6378137.01,298.257223563],TOWGS84[0,0,0,0,0,0,0]],PRIMEM["Greenwich",0],UNIT["degree",0.0174532925199433]],PROJECTION["Mercator_1SP"],PARAMETER["central_meridian",0],PARAMETER["scale_factor",1],PARAMETER["false_easting",0],PARAMETER["false_northing",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"]]' # We don't round-trip currently # MIF 999 @@ -1963,16 +1672,10 @@ def ogr_mitab_35(): SPHEROID["WGS 72",6378135,298.26]], UNIT["degree",0.0174532925199433]]""") coordsys = get_coordsys_from_srs(srs) - if coordsys != 'CoordSys Earth Projection 1, 999, 1, 1, 2, 3': - gdaltest.post_reason('fail') - print(coordsys) - return 'fail' + assert coordsys == 'CoordSys Earth Projection 1, 999, 1, 1, 2, 3' srs = get_srs_from_coordsys(coordsys) wkt = srs.ExportToWkt() - if wkt != 'GEOGCS["unnamed",DATUM["MIF 999,1,1,2,3",SPHEROID["WGS 72",6378135,298.26],TOWGS84[1,2,3,0,0,0,0]],PRIMEM["Greenwich",0],UNIT["degree",0.0174532925199433]]': - gdaltest.post_reason('fail') - print(wkt) - return 'fail' + assert wkt == 'GEOGCS["unnamed",DATUM["MIF 999,1,1,2,3",SPHEROID["WGS 72",6378135,298.26],TOWGS84[1,2,3,0,0,0,0]],PRIMEM["Greenwich",0],UNIT["degree",0.0174532925199433]]' # MIF 9999 srs = osr.SpatialReference("""GEOGCS["unnamed", @@ -1980,25 +1683,17 @@ def ogr_mitab_35(): SPHEROID["WGS 72",6378135,298.26]], UNIT["degree",0.0174532925199433]]""") coordsys = get_coordsys_from_srs(srs) - if coordsys != 'CoordSys Earth Projection 1, 9999, 1, 1, 2, 3, 4, 5, 6, 7, 3': - gdaltest.post_reason('fail') - print(coordsys) - return 'fail' + assert coordsys == 'CoordSys Earth Projection 1, 9999, 1, 1, 2, 3, 4, 5, 6, 7, 3' srs = get_srs_from_coordsys(coordsys) wkt = srs.ExportToWkt() - if wkt != 'GEOGCS["unnamed",DATUM["MIF 9999,1,1,2,3,4,5,6,7,3",SPHEROID["WGS 72",6378135,298.26],TOWGS84[1,2,3,-4,-5,-6,7]],PRIMEM["non-Greenwich",3],UNIT["degree",0.0174532925199433]]': - gdaltest.post_reason('fail') - print(wkt) - return 'fail' - - return 'success' + assert wkt == 'GEOGCS["unnamed",DATUM["MIF 9999,1,1,2,3,4,5,6,7,3",SPHEROID["WGS 72",6378135,298.26],TOWGS84[1,2,3,-4,-5,-6,7]],PRIMEM["non-Greenwich",3],UNIT["degree",0.0174532925199433]]' ############################################################################### # Test opening and modifying a file with polygons created with MapInfo that consists of # a single object block, without index block -def ogr_mitab_36(): +def test_ogr_mitab_36(): # Test modifying a new object shutil.copy('data/polygon_without_index.tab', 'tmp') @@ -2023,10 +1718,8 @@ def ogr_mitab_36(): f = lyr.GetNextFeature() got_g = f.GetGeometryRef() if ogrtest.check_feature_geometry(f, got_g, max_error=0.1): - gdaltest.post_reason('fail') f.DumpReadable() - print(g) - return 'fail' + pytest.fail(g) while True: f = lyr.GetNextFeature() if f is None: @@ -2035,83 +1728,59 @@ def ogr_mitab_36(): ogr.GetDriverByName('MapInfo File').DeleteDataSource('tmp/polygon_without_index.tab') - return 'success' - ############################################################################### # Simple testing of Seamless tables -def ogr_mitab_37(): +def test_ogr_mitab_37(): ds = ogr.Open('data/seamless.tab') lyr = ds.GetLayer(0) - if lyr.GetFeatureCount() != 4: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.GetFeatureCount() == 4 f = lyr.GetNextFeature() - if f.GetFID() != 4294967297 or f.id != '1': - gdaltest.post_reason('fail') - return 'fail' + assert f.GetFID() == 4294967297 and f.id == '1' f = lyr.GetNextFeature() - if f.GetFID() != 4294967298 or f.id != '2': - gdaltest.post_reason('fail') - return 'fail' + assert f.GetFID() == 4294967298 and f.id == '2' f = lyr.GetNextFeature() - if f.GetFID() != 8589934593 or f.id != '3': - gdaltest.post_reason('fail') - return 'fail' + assert f.GetFID() == 8589934593 and f.id == '3' f = lyr.GetNextFeature() - if f.GetFID() != 8589934594 or f.id != '4': - gdaltest.post_reason('fail') - return 'fail' + assert f.GetFID() == 8589934594 and f.id == '4' f = lyr.GetFeature(4294967297) - if f.GetFID() != 4294967297 or f.id != '1': - gdaltest.post_reason('fail') - return 'fail' + assert f.GetFID() == 4294967297 and f.id == '1' f = lyr.GetFeature(8589934594) - if f.GetFID() != 8589934594 or f.id != '4': - gdaltest.post_reason('fail') - return 'fail' + assert f.GetFID() == 8589934594 and f.id == '4' f = lyr.GetFeature(8589934594 + 1) - if f is not None: - gdaltest.post_reason('fail') - return 'fail' + assert f is None f = lyr.GetFeature(4294967297 * 2 + 1) - if f is not None: - gdaltest.post_reason('fail') - return 'fail' - - return 'success' + assert f is None ############################################################################### # Open MIF with MID with TAB delimiter and empty first field (#5405) -def ogr_mitab_38(): +def test_ogr_mitab_38(): ds = ogr.Open('data/empty_first_field_with_tab_delimiter.mif') lyr = ds.GetLayer(0) f = lyr.GetNextFeature() if f['field1'] != '' or f['field2'] != 'foo': - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' - - return 'success' + pytest.fail() + ############################################################################### # Read various geometry types from .mif -def ogr_mitab_39(): +def test_ogr_mitab_39(): ds = ogr.Open('data/all_geoms.mif') lyr = ds.GetLayer(0) @@ -2122,24 +1791,20 @@ def ogr_mitab_39(): f = lyr.GetNextFeature() f_ref = lyr_ref.GetNextFeature() if f is None: - if f_ref is not None: - gdaltest.post_reason('fail') - return 'fail' + assert f_ref is None break if ogrtest.check_feature_geometry(f, f_ref.GetGeometryRef()) != 0 or \ f.GetStyleString() != f_ref.GetStyleString(): - gdaltest.post_reason('fail') f.DumpReadable() f_ref.DumpReadable() - return 'fail' - - return 'success' + pytest.fail() + ############################################################################### # Read various geometry types from .mif but potentially truncated -def ogr_mitab_40(): +def test_ogr_mitab_40(): content = open('data/all_geoms.mif', 'rt').read() @@ -2154,13 +1819,11 @@ def ogr_mitab_40(): gdal.Unlink('/vsimem/ogr_mitab_40.mif') - return 'success' - ############################################################################### # Read various geometry types from .tab -def ogr_mitab_41(): +def test_ogr_mitab_41(): ds = ogr.Open('data/all_geoms.tab') lyr = ds.GetLayer(0) @@ -2171,24 +1834,20 @@ def ogr_mitab_41(): f = lyr.GetNextFeature() f_ref = lyr_ref.GetNextFeature() if f is None: - if f_ref is not None: - gdaltest.post_reason('fail') - return 'fail' + assert f_ref is None break if ogrtest.check_feature_geometry(f, f_ref.GetGeometryRef()) != 0 or \ f.GetStyleString() != f_ref.GetStyleString(): - gdaltest.post_reason('fail') f.DumpReadable() f_ref.DumpReadable() - return 'fail' - - return 'success' + pytest.fail() + ############################################################################### # Read various geometry types from .tab with block size = 32256 -def ogr_mitab_42(): +def test_ogr_mitab_42(): ds = ogr.Open('/vsizip/data/all_geoms_block_32256.zip') lyr = ds.GetLayer(0) @@ -2199,47 +1858,35 @@ def ogr_mitab_42(): f = lyr.GetNextFeature() f_ref = lyr_ref.GetNextFeature() if f is None: - if f_ref is not None: - gdaltest.post_reason('fail') - return 'fail' + assert f_ref is None break if ogrtest.check_feature_geometry(f, f_ref.GetGeometryRef()) != 0 or \ f.GetStyleString() != f_ref.GetStyleString(): - gdaltest.post_reason('fail') f.DumpReadable() f_ref.DumpReadable() - return 'fail' - - return 'success' + pytest.fail() + ############################################################################### # Test creating tab with block size = 32256 -def ogr_mitab_43(): +def test_ogr_mitab_43(): src_ds = gdal.OpenEx('/vsizip/data/all_geoms_block_32256.zip') gdal.VectorTranslate('/vsimem/all_geoms_block_512.tab', src_ds, format='MapInfo File') gdal.VectorTranslate('/vsimem/all_geoms_block_32256.tab', src_ds, format='MapInfo File', datasetCreationOptions=['BLOCKSIZE=32256']) with gdaltest.error_handler(): out_ds = gdal.VectorTranslate('/vsimem/all_geoms_block_invalid.tab', src_ds, format='MapInfo File', datasetCreationOptions=['BLOCKSIZE=32768']) - if out_ds is not None: - gdaltest.post_reason('fail') - return 'fail' + assert out_ds is None gdal.Unlink('/vsimem/all_geoms_block_invalid.dat') src_ds = None size = gdal.VSIStatL('/vsimem/all_geoms_block_512.map').size - if size != 6144: - gdaltest.post_reason('fail') - print(size) - return 'fail' + assert size == 6144 size = gdal.VSIStatL('/vsimem/all_geoms_block_32256.map').size - if size != 161280: - gdaltest.post_reason('fail') - print(size) - return 'fail' + assert size == 161280 ds = ogr.Open('/vsimem/all_geoms_block_32256.tab') lyr = ds.GetLayer(0) @@ -2250,28 +1897,23 @@ def ogr_mitab_43(): f = lyr.GetNextFeature() f_ref = lyr_ref.GetNextFeature() if f is None: - if f_ref is not None: - gdaltest.post_reason('fail') - return 'fail' + assert f_ref is None break if ogrtest.check_feature_geometry(f, f_ref.GetGeometryRef()) != 0 or \ f.GetStyleString() != f_ref.GetStyleString(): - gdaltest.post_reason('fail') f.DumpReadable() f_ref.DumpReadable() - return 'fail' + pytest.fail() gdaltest.mapinfo_drv.DeleteDataSource('/vsimem/all_geoms_block_512.tab') gdaltest.mapinfo_drv.DeleteDataSource('/vsimem/all_geoms_block_32256.tab') gdal.Unlink('/vsimem/all_geoms_block_32768.dat') - return 'success' - ############################################################################### # Test limitation on width and precision of numeric fields in creation (#6392) -def ogr_mitab_44(): +def test_ogr_mitab_44(): ds = gdaltest.mapinfo_drv.CreateDataSource('/vsimem/ogr_mitab_44.mif') lyr = ds.CreateLayer('test') @@ -2284,22 +1926,16 @@ def ogr_mitab_44(): ds = ogr.Open('/vsimem/ogr_mitab_44.mif') lyr = ds.GetLayer(0) fld_defn = lyr.GetLayerDefn().GetFieldDefn(0) - if fld_defn.GetWidth() != 20 or fld_defn.GetPrecision() != 16: - gdaltest.post_reason('fail') - print(fld_defn.GetWidth()) - print(fld_defn.GetPrecision()) - return 'fail' + assert fld_defn.GetWidth() == 20 and fld_defn.GetPrecision() == 16 ds = None gdaltest.mapinfo_drv.DeleteDataSource('/vsimem/ogr_mitab_44.mif') - return 'success' - ############################################################################### # Test read/write MapInfo layers with encoding specified -def ogr_mitab_45(): +def test_ogr_mitab_45(): lyrNames = ['lyr1', 'lyr2'] fldNames = ['field1', 'поле1'] @@ -2317,20 +1953,15 @@ def ogr_mitab_45(): ds = gdaltest.mapinfo_drv.CreateDataSource(dsName, options=['FORMAT=' + frmt]) - if ds is None: - gdaltest.post_reason('Can\'t create dataset: ' + dsName) - return 'fail' + assert ds is not None, ('Can\'t create dataset: ' + dsName) for i in range(lyrCount): lyr = ds.CreateLayer(lyrNames[i], options=['ENCODING=CP1251']) - if lyr is None: - gdaltest.post_reason('Can\'t create layer ' + lyrNames[i] + + assert lyr is not None, ('Can\'t create layer ' + lyrNames[i] + ' for ' + dsName) - return 'fail' if lyr.TestCapability(ogr.OLCStringsAsUTF8) != 1: - gdaltest.post_reason('skipping test: recode is not possible') - return 'skip' + pytest.skip('skipping test: recode is not possible') for fldName in fldNames: fld_defn = ogr.FieldDefn(fldName, ogr.OFTString) @@ -2348,26 +1979,20 @@ def ogr_mitab_45(): # reopen and check ds = ogr.Open(dsName) - if ds is None: - gdaltest.post_reason('Can\'t reopen dataset: ' + dsName) - return 'fail' + assert ds is not None, ('Can\'t reopen dataset: ' + dsName) for i in range(lyrCount): lyr = ds.GetLayer(i) - if lyr is None: - gdaltest.post_reason('Can\'t get layer ' + lyrNames[i] + + assert lyr is not None, ('Can\'t get layer ' + lyrNames[i] + ' from ' + dsName) - return 'fail' for fldN, expectedName in enumerate(fldNames): fldName = lyr.GetLayerDefn().GetFieldDefn(fldN).GetName() - if fldName != expectedName: - gdaltest.post_reason('Can\'t get field name\n' + + assert fldName == expectedName, ('Can\'t get field name\n' + ' result name: "' + fldName + '"\n' ' expected name: "' + expectedName + '"\n' ' from layer : ' + lyrNames[i] + ' from dataset :' + dsName) - return 'fail' for featName in featNames: feat = lyr.GetNextFeature() @@ -2375,32 +2000,29 @@ def ogr_mitab_45(): expectedValue = fldName + ' ' + featName # column value by number value = feat.GetField(fldN) - if value != expectedValue: - gdaltest.post_reason('Can\'t get field value by number\n' + + assert value == expectedValue, \ + ('Can\'t get field value by number\n' + ' result value: "' + value + '"\n' ' expected value: "' + expectedValue + '"\n' ' from layer : ' + lyrNames[i] + ' from dataset :' + dsName) - return 'fail' # column value by name value = feat.GetField(fldNames[fldN]) - if value != expectedValue: - gdaltest.post_reason('Can\'t get field value by name\n' + + assert value == expectedValue, \ + ('Can\'t get field value by name\n' + ' result value: "' + value + '"\n' ' expected value: "' + expectedValue + '"\n' ' from layer : ' + lyrNames[i] + ' from dataset :' + dsName) - return 'fail' gdaltest.mapinfo_drv.DeleteDataSource(dsName) - return 'success' - + ############################################################################### # Test read MapInfo layers with encoding specified -def ogr_mitab_46(): +def test_ogr_mitab_46(): dsNames = ['data/mitab/tab-win1251.TAB', 'data/mitab/win1251.mif'] @@ -2412,27 +2034,20 @@ def ogr_mitab_46(): for dsName in dsNames: ds = ogr.Open(dsName) - if ds is None: - gdaltest.post_reason('Can\'t open dataset: ' + dsName) - return 'fail' + assert ds is not None, ('Can\'t open dataset: ' + dsName) lyr = ds.GetLayer(0) - if lyr is None: - gdaltest.post_reason('Can\'t get layer 0 from ' + dsName) - return 'fail' + assert lyr is not None, ('Can\'t get layer 0 from ' + dsName) if lyr.TestCapability(ogr.OLCStringsAsUTF8) != 1: - gdaltest.post_reason('skipping test: recode is not possible') - return 'skip' + pytest.skip('skipping test: recode is not possible') for fldN, expectedName in enumerate(fldNames): fldName = lyr.GetLayerDefn().GetFieldDefn(fldN).GetName() - if fldName != expectedName: - gdaltest.post_reason('Can\'t get field\n' + + assert fldName == expectedName, ('Can\'t get field\n' + ' result name: "' + fldName + '"\n' ' expected name: "' + expectedName + '"\n' ' from dataset :' + dsName) - return 'fail' for featFldVal in fldVal: feat = lyr.GetNextFeature() @@ -2440,34 +2055,28 @@ def ogr_mitab_46(): expectedValue = featFldVal[fldN] # column value by number value = feat.GetField(fldN) - if value != expectedValue: - gdaltest.post_reason('Can\'t get field value by number\n' + + assert value == expectedValue, ('Can\'t get field value by number\n' + ' result value: "' + value + '"\n' ' expected value: "' + expectedValue + '"\n' ' from dataset :' + dsName) - return 'fail' # column value by name value = feat.GetField(fldName) - if value != expectedValue: - gdaltest.post_reason('Can\'t get field value by name\n' + + assert value == expectedValue, ('Can\'t get field value by name\n' + ' result value: "' + value + '"\n' ' expected value: "' + expectedValue + '"\n' ' from dataset :' + dsName) - return 'fail' - - return 'success' + ############################################################################### # Test opening a dataset with a .ind file -def ogr_mitab_47(): +def test_ogr_mitab_47(): ds = ogr.Open('data/poly_indexed.tab') lyr = ds.GetLayer(0) lyr.SetAttributeFilter("PRFEDEA = '35043413'") - if lyr.GetFeatureCount() != 1: - return 'fail' + assert lyr.GetFeatureCount() == 1 for ext in ('tab', 'dat', 'map', 'id'): gdal.FileFromMemBuffer('/vsimem/poly_indexed.' + ext, @@ -2475,19 +2084,17 @@ def ogr_mitab_47(): ds = ogr.Open('/vsimem/poly_indexed.tab') lyr = ds.GetLayer(0) lyr.SetAttributeFilter("PRFEDEA = '35043413'") - if lyr.GetFeatureCount() != 1: - return 'fail' + assert lyr.GetFeatureCount() == 1 ds = None for ext in ('tab', 'dat', 'map', 'id'): gdal.Unlink('/vsimem/poly_indexed.' + ext) - return 'success' - + ############################################################################### # Test writing and reading LCC_1SP -def ogr_mitab_48(): +def test_ogr_mitab_48(): ds = ogr.GetDriverByName('MapInfo File').CreateDataSource('/vsimem/test.mif') sr = osr.SpatialReference() @@ -2539,41 +2146,29 @@ def ogr_mitab_48(): PARAMETER["false_easting",234.358], PARAMETER["false_northing",4185861.369]]""") - if sr_got.IsSame(sr_expected) == 0: - print(sr_got) - return 'fail' - - return 'success' + assert sr_got.IsSame(sr_expected) != 0 ############################################################################### # Test reading an aspatial TAB file. -def ogr_mitab_49_aspatial(): +def test_ogr_mitab_49_aspatial(): ds = ogr.GetDriverByName('MapInfo File').Open('data/mitab/aspatial.tab') lyr = ds.GetLayer(0) geom_type = lyr.GetLayerDefn().GetGeomType() - if geom_type != ogr.wkbNone: - gdaltest.post_reason('fail') - return 'fail' + assert geom_type == ogr.wkbNone - if lyr.GetSpatialRef() is not None: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.GetSpatialRef() is None - if lyr.GetExtent(can_return_null=True) is not None: - gdaltest.post_reason('fail') - return 'fail' - - return 'success' + assert lyr.GetExtent(can_return_null=True) is None ############################################################################### # Test creating an indexed field -def ogr_mitab_tab_field_index_creation(): +def test_ogr_mitab_tab_field_index_creation(): layername = 'ogr_mitab_tab_field_index_creation' filename = '/vsimem/' + layername + '.tab' @@ -2594,61 +2189,47 @@ def ogr_mitab_tab_field_index_creation(): lyr.CreateFeature(f) ds = None - if gdal.VSIStatL('/vsimem/' + layername + '.ind') is None: - gdaltest.post_reason('no ind file') - return 'fail' + assert gdal.VSIStatL('/vsimem/' + layername + '.ind') is not None, 'no ind file' ds = ogr.Open(filename) with gdaltest.error_handler(): ds.ExecuteSQL('CREATE INDEX ON ' + layername + ' USING other_field') lyr = ds.GetLayer(0) lyr.SetAttributeFilter('id = 200') - if lyr.GetFeatureCount() != 1: - gdaltest.post_reason('bad feature count') - return 'fail' + assert lyr.GetFeatureCount() == 1, 'bad feature count' ds = None ogr.GetDriverByName('MapInfo File').DeleteDataSource(filename) - return 'success' - ############################################################################### # Test reading a tab_view file -def ogr_mitab_tab_view(): +def test_ogr_mitab_tab_view(): ds = ogr.Open('data/mitab/view_first_table_second_table.tab') lyr = ds.GetLayer(0) - if lyr.GetLayerDefn().GetFieldCount() != 2: - gdaltest.post_reason('bad field count') - return 'fail' + assert lyr.GetLayerDefn().GetFieldCount() == 2, 'bad field count' f = lyr.GetNextFeature() if f['ID'] != 100 or f['foo'] != 'foo': - gdaltest.post_reason('bad feature') f.DumpReadable() - return 'fail' + pytest.fail('bad feature') ds = None ds = ogr.Open('data/mitab/view_select_all_first_table_second_table.tab') lyr = ds.GetLayer(0) - if lyr.GetLayerDefn().GetFieldCount() != 3: - gdaltest.post_reason('bad field count') - return 'fail' + assert lyr.GetLayerDefn().GetFieldCount() == 3, 'bad field count' f = lyr.GetNextFeature() if f['joint_field'] != 1 or f['ID'] != 100 or f['foo'] != 'foo': - gdaltest.post_reason('bad feature') f.DumpReadable() - return 'fail' + pytest.fail('bad feature') ds = None - return 'success' - ############################################################################### -def ogr_mitab_style(): +def test_ogr_mitab_style(): tmpfile = '/vsimem/ogr_mitab_style.tab' ds = ogr.GetDriverByName('MapInfo File').CreateDataSource(tmpfile) @@ -2672,29 +2253,24 @@ def ogr_mitab_style(): lyr = ds.GetLayer(0) f = lyr.GetNextFeature() if f.GetStyleString() != 'BRUSH(fc:#aabbcc,bc:#ddeeff,id:"mapinfo-brush-2,ogr-brush-0");PEN(w:1px,c:#ddeeff,id:"mapinfo-pen-2,ogr-pen-0")': - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' + pytest.fail() f = lyr.GetNextFeature() if f.GetStyleString() != 'BRUSH(fc:#aabbcc,id:"mapinfo-brush-1,ogr-brush-1");PEN(w:1px,c:#000000,id:"mapinfo-pen-2,ogr-pen-0")': - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' + pytest.fail() f = lyr.GetNextFeature() if f.GetStyleString() != 'BRUSH(fc:#aabbcc,id:"mapinfo-brush-1,ogr-brush-1");PEN(w:1px,c:#000000,id:"mapinfo-pen-2,ogr-pen-0")': - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' + pytest.fail() ds = None ogr.GetDriverByName('MapInfo File').DeleteDataSource(tmpfile) - return 'success' - ############################################################################### -def ogr_mitab_tab_write_field_name_with_dot(): +def test_ogr_mitab_tab_write_field_name_with_dot(): tmpfile = '/vsimem/ogr_mitab_tab_write_field_name_with_dot.tab' ds = ogr.GetDriverByName('MapInfo File').CreateDataSource(tmpfile) @@ -2710,22 +2286,19 @@ def ogr_mitab_tab_write_field_name_with_dot(): ds = ogr.Open(tmpfile) lyr = ds.GetLayer(0) f = lyr.GetNextFeature() - if f['with_dot'] != 1: - return 'fail' + assert f['with_dot'] == 1 ds = None ogr.GetDriverByName('MapInfo File').DeleteDataSource(tmpfile) - return 'success' - ############################################################################### # -def ogr_mitab_cleanup(): +def test_ogr_mitab_cleanup(): if gdaltest.mapinfo_ds is None: - return 'skip' + pytest.skip() fl = gdal.ReadDir('/vsimem/') if fl is not None: @@ -2734,70 +2307,5 @@ def ogr_mitab_cleanup(): gdaltest.mapinfo_ds = None gdaltest.mapinfo_drv.DeleteDataSource('tmp') - return 'success' - - -gdaltest_list = [ - ogr_mitab_1, - ogr_mitab_2, - ogr_mitab_3, - ogr_mitab_4, - ogr_mitab_5, - ogr_mitab_6, - ogr_mitab_7, - ogr_mitab_8, - ogr_mitab_9, - ogr_mitab_10, - ogr_mitab_11, - ogr_mitab_12, - ogr_mitab_13, - ogr_mitab_14, - ogr_mitab_15, - ogr_mitab_16, - ogr_mitab_17, - ogr_mitab_18, - ogr_mitab_19, - ogr_mitab_20, - ogr_mitab_21, - ogr_mitab_22, - ogr_mitab_23, - ogr_mitab_24, - ogr_mitab_25, - ogr_mitab_26, - ogr_mitab_27, - ogr_mitab_28, - ogr_mitab_29, - ogr_mitab_30, - ogr_mitab_31, - ogr_mitab_32, - ogr_mitab_33, - ogr_mitab_34, - ogr_mitab_35, - ogr_mitab_36, - ogr_mitab_37, - ogr_mitab_38, - ogr_mitab_39, - ogr_mitab_40, - ogr_mitab_41, - ogr_mitab_42, - ogr_mitab_43, - ogr_mitab_44, - ogr_mitab_45, - ogr_mitab_46, - ogr_mitab_47, - ogr_mitab_48, - ogr_mitab_49_aspatial, - ogr_mitab_tab_field_index_creation, - ogr_mitab_tab_view, - ogr_mitab_style, - ogr_mitab_tab_write_field_name_with_dot, - ogr_mitab_cleanup -] - -if __name__ == '__main__': - - gdaltest.setup_run('ogr_mitab') - - gdaltest.run_tests(gdaltest_list) - - sys.exit(gdaltest.summarize()) + + diff --git a/autotest/ogr/ogr_mongodb.py b/autotest/ogr/ogr_mongodb.py index 7c2dfad0048c..9270cf770a6a 100755 --- a/autotest/ogr/ogr_mongodb.py +++ b/autotest/ogr/ogr_mongodb.py @@ -30,28 +30,27 @@ ############################################################################### import os -import sys import uuid -sys.path.append('../pymod') import gdaltest import ogrtest from osgeo import gdal from osgeo import ogr from osgeo import osr +import pytest ############################################################################### # Test if driver is available -def ogr_mongodb_init(): +def test_ogr_mongodb_init(): ogrtest.mongodb_drv = None ogrtest.mongodb_drv = ogr.GetDriverByName('MongoDB') if ogrtest.mongodb_drv is None: - return 'skip' + pytest.skip() if 'MONGODB_TEST_HOST' in os.environ: ogrtest.mongodb_test_host = os.environ['MONGODB_TEST_HOST'] @@ -91,19 +90,17 @@ def ogr_mongodb_init(): ds = ogr.Open(ogrtest.mongodb_test_uri) if ds is None: - print('cannot open %s' % ogrtest.mongodb_test_uri) ogrtest.mongodb_drv = None - return 'skip' - - return 'success' + pytest.skip('cannot open %s' % ogrtest.mongodb_test_uri) + ############################################################################### # Test various open methods -def ogr_mongodb_1(): +def test_ogr_mongodb_1(): if ogrtest.mongodb_drv is None: - return 'skip' + pytest.skip() # The below options must be used the very first time mongoDB is initialized # otherwise they will get ignored @@ -128,25 +125,19 @@ def ogr_mongodb_1(): gdal.PushErrorHandler() ds = ogr.Open("mongodb://") gdal.PopErrorHandler() - if ds is not None: - gdaltest.post_reason('fail') - return 'fail' + assert ds is None # URI to non existent host. gdal.PushErrorHandler() ds = ogr.Open("mongodb://non_existing") gdal.PopErrorHandler() - if ds is not None: - gdaltest.post_reason('fail') - return 'fail' + assert ds is None # Connect to non existent host. gdal.PushErrorHandler() ds = gdal.OpenEx('mongodb:', open_options=['HOST=non_existing']) gdal.PopErrorHandler() - if ds is not None: - gdaltest.post_reason('fail') - return 'fail' + assert ds is None # All arguments split up open_options = [] @@ -157,9 +148,7 @@ def ogr_mongodb_1(): open_options += ['USER=' + ogrtest.mongodb_test_user] open_options += ['PASSWORD=' + ogrtest.mongodb_test_password] ds = gdal.OpenEx('mongodb:', open_options=open_options) - if ds is None: - gdaltest.post_reason('fail') - return 'fail' + assert ds is not None # Without DBNAME open_options = [] @@ -184,9 +173,7 @@ def ogr_mongodb_1(): gdal.PushErrorHandler() ds = gdal.OpenEx('mongodb:', open_options=open_options) gdal.PopErrorHandler() - if ds is not None: - gdaltest.post_reason('fail') - return 'fail' + assert ds is None open_options = [] open_options += ['HOST=' + ogrtest.mongodb_test_host] @@ -197,9 +184,7 @@ def ogr_mongodb_1(): gdal.PushErrorHandler() ds = gdal.OpenEx('mongodb:', open_options=open_options) gdal.PopErrorHandler() - if ds is not None: - gdaltest.post_reason('fail') - return 'fail' + assert ds is None open_options = [] open_options += ['HOST=' + ogrtest.mongodb_test_host] @@ -210,9 +195,7 @@ def ogr_mongodb_1(): gdal.PushErrorHandler() ds = gdal.OpenEx('mongodb:', open_options=open_options) gdal.PopErrorHandler() - if ds is not None: - gdaltest.post_reason('fail') - return 'fail' + assert ds is None open_options = [] open_options += ['HOST=' + ogrtest.mongodb_test_host] @@ -224,9 +207,7 @@ def ogr_mongodb_1(): gdal.PushErrorHandler() ds = gdal.OpenEx('mongodb:', open_options=open_options) gdal.PopErrorHandler() - if ds is not None: - gdaltest.post_reason('fail') - return 'fail' + assert ds is None # Test AUTH_JSON: invalid JSon gdal.PushErrorHandler() @@ -237,9 +218,7 @@ def ogr_mongodb_1(): open_options += ['AUTH_JSON={'] ds = gdal.OpenEx('mongodb:', open_options=open_options) gdal.PopErrorHandler() - if ds is not None: - gdaltest.post_reason('fail') - return 'fail' + assert ds is None # Test AUTH_JSON: missing mechanism gdal.PushErrorHandler() @@ -250,9 +229,7 @@ def ogr_mongodb_1(): open_options += ['AUTH_JSON={}'] ds = gdal.OpenEx('mongodb:', open_options=open_options) gdal.PopErrorHandler() - if ds is not None: - gdaltest.post_reason('fail') - return 'fail' + assert ds is None # Successful AUTH_JSON use if ogrtest.mongodb_test_user is not None: @@ -263,36 +240,25 @@ def ogr_mongodb_1(): open_options += ['AUTH_JSON={ "mechanism" : "SCRAM-SHA-1", "db": "%s", "user": "%s", "pwd": "%s" }' % (ogrtest.mongodb_test_dbname, ogrtest.mongodb_test_user, ogrtest.mongodb_test_password)] ds = gdal.OpenEx('mongodb:', open_options=open_options) - if ds is None: - gdaltest.post_reason('fail') - return 'fail' - - return 'success' + assert ds is not None + ############################################################################### # Basic tests -def ogr_mongodb_2(): +def test_ogr_mongodb_2(): if ogrtest.mongodb_drv is None: - return 'skip' + pytest.skip() ogrtest.mongodb_ds = ogr.Open(ogrtest.mongodb_test_uri, update=1) - if ogrtest.mongodb_ds.GetLayerByName('not_existing') is not None: - gdaltest.post_reason('fail') - return 'fail' + assert ogrtest.mongodb_ds.GetLayerByName('not_existing') is None - if ogrtest.mongodb_ds.TestCapability(ogr.ODsCCreateLayer) != 1: - gdaltest.post_reason('fail') - return 'fail' + assert ogrtest.mongodb_ds.TestCapability(ogr.ODsCCreateLayer) == 1 - if ogrtest.mongodb_ds.TestCapability(ogr.ODsCDeleteLayer) != 1: - gdaltest.post_reason('fail') - return 'fail' + assert ogrtest.mongodb_ds.TestCapability(ogr.ODsCDeleteLayer) == 1 - if ogrtest.mongodb_ds.TestCapability(ogr.ODsCCreateGeomFieldAfterCreateLayer) != 1: - gdaltest.post_reason('fail') - return 'fail' + assert ogrtest.mongodb_ds.TestCapability(ogr.ODsCCreateGeomFieldAfterCreateLayer) == 1 # Create layer a_uuid = str(uuid.uuid1()).replace('-', '_') @@ -304,21 +270,15 @@ def ogr_mongodb_2(): gdal.PushErrorHandler() ret = lyr.CreateGeomField(ogr.GeomFieldDefn('location.mygeom', ogr.wkbPoint)) gdal.PopErrorHandler() - if ret == 0: - gdaltest.post_reason('fail') - return 'fail' + assert ret != 0 ret = lyr.CreateField(ogr.FieldDefn('str', ogr.OFTString)) - if ret != 0: - gdaltest.post_reason('fail') - return 'fail' + assert ret == 0 gdal.PushErrorHandler() ret = lyr.CreateField(ogr.FieldDefn('str', ogr.OFTString)) gdal.PopErrorHandler() - if ret == 0: - gdaltest.post_reason('fail') - return 'fail' + assert ret != 0 lyr.CreateField(ogr.FieldDefn('location.name', ogr.OFTString)) bool_field = ogr.FieldDefn('bool', ogr.OFTInteger) @@ -358,92 +318,74 @@ def ogr_mongodb_2(): f['embed.embed2.real'] = 3.45 f.SetFieldNull('str_is_null') f.SetGeometryDirectly(ogr.CreateGeometryFromWkt('POLYGON((2 49,2 50,3 50,3 49,2 49))')) - if lyr.CreateFeature(f) != 0: - gdaltest.post_reason('fail') - return 'fail' - if f['_id'] is None: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.CreateFeature(f) == 0 + assert f['_id'] is not None f_ref = f.Clone() # Test GetFeatureCount() - if lyr.GetFeatureCount() != 1: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.GetFeatureCount() == 1 # Test GetNextFeature() lyr.ResetReading() f = lyr.GetNextFeature() if not f.Equal(f_ref): - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' + pytest.fail() f = lyr.GetNextFeature() if f is not None: - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' + pytest.fail() # Test GetFeature() f = lyr.GetFeature(1) if not f.Equal(f_ref): - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' + pytest.fail() # Test SetFeature() f['bool'] = 0 - if lyr.SetFeature(f) != 0: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.SetFeature(f) == 0 f_ref = f.Clone() f = lyr.GetFeature(1) if f['bool'] != 0: - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' + pytest.fail() # Test (not working) DeleteFeature() gdal.PushErrorHandler() ret = lyr.DeleteFeature(1) gdal.PopErrorHandler() - if ret == 0: - gdaltest.post_reason('fail') - return 'fail' + assert ret != 0 # Test Mongo filter lyr.SetAttributeFilter('{ "int": 1 }') lyr.ResetReading() f = lyr.GetNextFeature() if not f.Equal(f_ref): - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' + pytest.fail() lyr.SetAttributeFilter('{ "int": 2 }') lyr.ResetReading() f = lyr.GetNextFeature() if f is not None: - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' + pytest.fail() # Test OGR filter lyr.SetAttributeFilter('int = 1') lyr.ResetReading() f = lyr.GetNextFeature() if not f.Equal(f_ref): - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' + pytest.fail() lyr.SetAttributeFilter('int = 2') lyr.ResetReading() f = lyr.GetNextFeature() if f is not None: - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' + pytest.fail() # Test geometry filter lyr.SetAttributeFilter(None) @@ -451,48 +393,38 @@ def ogr_mongodb_2(): lyr.ResetReading() f = lyr.GetNextFeature() if not f.Equal(f_ref): - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' + pytest.fail() lyr.SetSpatialFilterRect(1.1, 49.1, 1.9, 49.9) lyr.ResetReading() f = lyr.GetNextFeature() if f is not None: - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' + pytest.fail() f = f_ref.Clone() f.SetFID(-1) f.SetGeometryDirectly(None) - if lyr.CreateFeature(f) != 0: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.CreateFeature(f) == 0 # Duplicate key gdal.PushErrorHandler() ret = lyr.SyncToDisk() gdal.PopErrorHandler() - if ret == 0: - gdaltest.post_reason('fail') - return 'fail' + assert ret != 0 f['_id'] = None lyr.CreateFeature(f) ret = lyr.SyncToDisk() - if ret != 0: - gdaltest.post_reason('fail') - return 'fail' + assert ret == 0 # Missing _id f.UnsetField('_id') gdal.PushErrorHandler() ret = lyr.SetFeature(f) gdal.PopErrorHandler() - if ret == 0: - gdaltest.post_reason('fail') - return 'fail' + assert ret != 0 # MongoDB dialect of ExecuteSQL() with invalid JSON gdal.PushErrorHandler() @@ -501,25 +433,17 @@ def ogr_mongodb_2(): # MongoDB dialect of ExecuteSQL() with nonexistent command. sql_lyr = ogrtest.mongodb_ds.ExecuteSQL('{ "foo": 1 }', dialect='MongoDB') - if sql_lyr is None: - gdaltest.post_reason('fail') - return 'fail' + assert sql_lyr is not None ogrtest.mongodb_ds.ReleaseResultSet(sql_lyr) # MongoDB dialect of ExecuteSQL() with existing commnand sql_lyr = ogrtest.mongodb_ds.ExecuteSQL('{ "listCommands" : 1 }', dialect='MongoDB') - if sql_lyr is None: - gdaltest.post_reason('fail') - return 'fail' + assert sql_lyr is not None f = sql_lyr.GetNextFeature() - if f is None: - gdaltest.post_reason('fail') - return 'fail' + assert f is not None f = sql_lyr.GetNextFeature() - if f is not None: - gdaltest.post_reason('fail') - return 'fail' + assert f is None sql_lyr.GetLayerDefn() sql_lyr.ResetReading() sql_lyr.TestCapability('') @@ -527,26 +451,21 @@ def ogr_mongodb_2(): # Regular ExecuteSQL() sql_lyr = ogrtest.mongodb_ds.ExecuteSQL('SELECT * FROM ' + ogrtest.mongodb_layer_name) - if sql_lyr is None: - gdaltest.post_reason('fail') - return 'fail' + assert sql_lyr is not None ogrtest.mongodb_ds.ReleaseResultSet(sql_lyr) # Test CreateLayer again with same name gdal.PushErrorHandler() lyr = ogrtest.mongodb_ds.CreateLayer(ogrtest.mongodb_layer_name) gdal.PopErrorHandler() - if lyr is not None: - return 'fail' + assert lyr is None ogrtest.mongodb_ds = gdal.OpenEx(ogrtest.mongodb_test_uri, gdal.OF_UPDATE, open_options=['FEATURE_COUNT_TO_ESTABLISH_FEATURE_DEFN=-1', 'BULK_INSERT=NO', 'JSON_FIELD=TRUE']) # Check after reopening lyr = ogrtest.mongodb_ds.GetLayerByName(ogrtest.mongodb_layer_name) - if lyr.TestCapability(ogr.OLCFastSpatialFilter) == 0: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.TestCapability(ogr.OLCFastSpatialFilter) != 0 f = lyr.GetNextFeature() json_field = f['_json'] # We cannot use feature.Equal() has the C++ layer defn has changed @@ -554,34 +473,29 @@ def ogr_mongodb_2(): if f.GetField(i) != f_ref.GetField(i) or \ f.GetFieldDefnRef(i).GetType() != f_ref.GetFieldDefnRef(i).GetType() or \ f.GetFieldDefnRef(i).GetSubType() != f_ref.GetFieldDefnRef(i).GetSubType(): - gdaltest.post_reason('fail') f.DumpReadable() f_ref.DumpReadable() - return 'fail' + pytest.fail() for i in range(f_ref.GetDefnRef().GetGeomFieldCount()): if not f.GetGeomFieldRef(i).Equals(f_ref.GetGeomFieldRef(i)) or \ f.GetGeomFieldDefnRef(i).GetName() != f_ref.GetGeomFieldDefnRef(i).GetName() or \ f.GetGeomFieldDefnRef(i).GetType() != f_ref.GetGeomFieldDefnRef(i).GetType(): - gdaltest.post_reason('fail') f.DumpReadable() f_ref.DumpReadable() - return 'fail' + pytest.fail() lyr.SetSpatialFilterRect(2.1, 49.1, 2.9, 49.9) lyr.ResetReading() if f is None: - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' + pytest.fail() # Create a feature only from its _json content and do not store any ogr metadata related to the layer ogrtest.mongodb_layer_name_no_ogr_metadata = ogrtest.mongodb_layer_name + "_no_ogr_metadata" lyr = ogrtest.mongodb_ds.CreateLayer(ogrtest.mongodb_layer_name_no_ogr_metadata, options=['GEOMETRY_NAME=location.mygeom', 'FID=', 'WRITE_OGR_METADATA=NO']) f = ogr.Feature(lyr.GetLayerDefn()) f['_json'] = json_field - if lyr.CreateFeature(f) != 0: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.CreateFeature(f) == 0 ogrtest.mongodb_layer_name_guess_types = ogrtest.mongodb_layer_name + "_guess_types" lyr = ogrtest.mongodb_ds.CreateLayer(ogrtest.mongodb_layer_name_guess_types, geom_type=ogr.wkbNone, options=['FID=', 'WRITE_OGR_METADATA=NO']) @@ -620,9 +534,7 @@ def ogr_mongodb_2(): f['_json'] += '"mixedlist": [true,1,{ "$numberLong" : "1234567890123456" },3.45],' f['_json'] += '"mixedlist2": [true,1,{ "$numberLong" : "1234567890123456" },3.45,"str"]' f['_json'] += '}' - if lyr.CreateFeature(f) != 0: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.CreateFeature(f) == 0 f = ogr.Feature(lyr.GetLayerDefn()) f['_json'] = '{' @@ -651,9 +563,7 @@ def ogr_mongodb_2(): f['_json'] += '"intlist_boollist" : [true], ' f['_json'] += '"boollist_intlist" : [2]' f['_json'] += '}' - if lyr.CreateFeature(f) != 0: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.CreateFeature(f) == 0 # This new features will not be taken into account by below the FEATURE_COUNT_TO_ESTABLISH_FEATURE_DEFN=2 f = ogr.Feature(lyr.GetLayerDefn()) @@ -665,9 +575,7 @@ def ogr_mongodb_2(): f['_json'] += '"int64list" : [1, { "$numberLong" : "1234567890123456" }, "1", { "$minKey": 1 },{ "$maxKey": 1 }, -1e300, 1e300, 1.23 ], ' f['_json'] += '"reallist" : [1, { "$numberLong" : "1234567890123456" }, 1.0, "1", { "$minKey": 1 },{ "$maxKey": 1 }, { "$numberLong" : "1234567890123456" } ] ' f['_json'] += '}' - if lyr.CreateFeature(f) != 0: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.CreateFeature(f) == 0 f = ogr.Feature(lyr.GetLayerDefn()) f['_json'] = '{' @@ -675,9 +583,7 @@ def ogr_mongodb_2(): f['_json'] += '"int64": { "$maxKey": 1 }, ' f['_json'] += '"real": { "$maxKey": 1 } ' f['_json'] += '}' - if lyr.CreateFeature(f) != 0: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.CreateFeature(f) == 0 ogrtest.mongodb_layer_name_with_2d_index = ogrtest.mongodb_layer_name + "_with_2d_index" gdal.SetConfigOption('OGR_MONGODB_SPAT_INDEX_TYPE', '2d') @@ -685,39 +591,26 @@ def ogr_mongodb_2(): gdal.SetConfigOption('OGR_MONGODB_SPAT_INDEX_TYPE', None) f = ogr.Feature(lyr.GetLayerDefn()) f.SetGeometryDirectly(ogr.CreateGeometryFromWkt('POINT(2 49)')) - if lyr.CreateFeature(f) != 0: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.CreateFeature(f) == 0 ogrtest.mongodb_layer_name_no_spatial_index = ogrtest.mongodb_layer_name + "_no_spatial_index" for i in range(2): lyr = ogrtest.mongodb_ds.CreateLayer(ogrtest.mongodb_layer_name_no_spatial_index, options=['SPATIAL_INDEX=NO', 'OVERWRITE=YES']) f = ogr.Feature(lyr.GetLayerDefn()) f.SetGeometryDirectly(ogr.CreateGeometryFromWkt('POINT(2 49)')) - if lyr.CreateFeature(f) != 0: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.CreateFeature(f) == 0 ogrtest.mongodb_ds.ExecuteSQL('WRITE_OGR_METADATA ' + ogrtest.mongodb_layer_name_no_spatial_index) # Open "ghost" layer lyr = ogrtest.mongodb_ds.GetLayerByName('_ogr_metadata') - if lyr is None: - gdaltest.post_reason('fail') - return 'fail' + assert lyr is not None lyr.SetAttributeFilter("layer LIKE '%s%%'" % ogrtest.mongodb_layer_name) - if lyr.GetFeatureCount() != 2: - print(lyr.GetFeatureCount()) - gdaltest.post_reason('fail') - return 'fail' + assert lyr.GetFeatureCount() == 2 - if ogrtest.mongodb_ds.DeleteLayer(-1) == 0: - gdaltest.post_reason('fail') - return 'fail' + assert ogrtest.mongodb_ds.DeleteLayer(-1) != 0 lyr = ogrtest.mongodb_ds.GetLayerByName(ogrtest.mongodb_test_dbname + '.' + '_ogr_metadata') - if lyr is None: - gdaltest.post_reason('fail') - return 'fail' + assert lyr is not None ogrtest.mongodb_ds = None @@ -725,9 +618,7 @@ def ogr_mongodb_2(): ogrtest.mongodb_ds = gdal.OpenEx(ogrtest.mongodb_test_uri, 0, open_options=['FEATURE_COUNT_TO_ESTABLISH_FEATURE_DEFN=2', 'JSON_FIELD=TRUE']) lyr = ogrtest.mongodb_ds.GetLayerByName(ogrtest.mongodb_layer_name_no_ogr_metadata) - if lyr.TestCapability(ogr.OLCFastSpatialFilter) != 0: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.TestCapability(ogr.OLCFastSpatialFilter) == 0 f = lyr.GetNextFeature() for i in range(f_ref.GetDefnRef().GetFieldCount()): if f_ref.GetFieldDefnRef(i).GetNameRef() == "str_is_null": @@ -739,29 +630,25 @@ def ogr_mongodb_2(): if f.GetField(j) != f_ref.GetField(i) or \ f.GetFieldDefnRef(j).GetType() != f_ref.GetFieldDefnRef(i).GetType() or \ f.GetFieldDefnRef(j).GetSubType() != f_ref.GetFieldDefnRef(i).GetSubType(): - gdaltest.post_reason('fail') f.DumpReadable() f_ref.DumpReadable() - return 'fail' + pytest.fail() for i in range(f_ref.GetDefnRef().GetGeomFieldCount()): # Order might be a bit different... j = f.GetDefnRef().GetGeomFieldIndex(f_ref.GetGeomFieldDefnRef(i).GetNameRef()) if not f.GetGeomFieldRef(j).Equals(f_ref.GetGeomFieldRef(i)) or \ f.GetGeomFieldDefnRef(j).GetName() != f_ref.GetGeomFieldDefnRef(i).GetName() or \ f.GetGeomFieldDefnRef(j).GetType() != f_ref.GetGeomFieldDefnRef(i).GetType(): - gdaltest.post_reason('fail') f.DumpReadable() f_ref.DumpReadable() - print(f.GetGeomFieldDefnRef(j).GetType()) print(f_ref.GetGeomFieldDefnRef(i).GetType()) - return 'fail' + pytest.fail(f.GetGeomFieldDefnRef(j).GetType()) lyr.SetSpatialFilterRect(2.1, 49.1, 2.9, 49.9) lyr.ResetReading() if f is None: - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' + pytest.fail() lyr = ogrtest.mongodb_ds.GetLayerByName(ogrtest.mongodb_layer_name_guess_types) @@ -800,14 +687,8 @@ def ogr_mongodb_2(): ("mixedlist2", ogr.OFTStringList)] for (fieldname, fieldtype) in expected_fields: fld_defn = lyr.GetLayerDefn().GetFieldDefn(lyr.GetLayerDefn().GetFieldIndex(fieldname)) - if fld_defn.GetType() != fieldtype: - gdaltest.post_reason('fail') - print(fieldname) - print(fld_defn.GetType()) - return 'fail' - if fld_defn.GetSubType() != ogr.OFSTNone: - gdaltest.post_reason('fail') - return 'fail' + assert fld_defn.GetType() == fieldtype, fieldname + assert fld_defn.GetSubType() == ogr.OFSTNone f = lyr.GetNextFeature() f = lyr.GetNextFeature() @@ -815,133 +696,98 @@ def ogr_mongodb_2(): if f['intlist'] != [1, 1, -2147483648, 2147483647, -2147483648, 2147483647, -2147483648, 2147483647, 1, 1] or \ f['int64list'] != [1, 1234567890123456, 1, -9223372036854775808, 9223372036854775807, -9223372036854775808, 9223372036854775807, 1] or \ f['int'] != -2147483648 or f['int64'] != -9223372036854775808 or f['real'] - 1 != f['real']: - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' + pytest.fail() f = lyr.GetNextFeature() if f['int'] != 2147483647 or f['int64'] != 9223372036854775807 or f['real'] + 1 != f['real']: - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' + pytest.fail() lyr = ogrtest.mongodb_ds.GetLayerByName(ogrtest.mongodb_layer_name_with_2d_index) - if lyr.TestCapability(ogr.OLCFastSpatialFilter) == 0: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.TestCapability(ogr.OLCFastSpatialFilter) != 0 lyr.SetSpatialFilterRect(1.9, 48.9, 2.1, 49.1) lyr.ResetReading() f = lyr.GetNextFeature() - if f is None: - gdaltest.post_reason('fail') - return 'fail' + assert f is not None lyr.SetSpatialFilterRect(1.9, 48.9, 1.95, 48.95) lyr.ResetReading() f = lyr.GetNextFeature() - if f is not None: - gdaltest.post_reason('fail') - return 'fail' + assert f is None lyr = ogrtest.mongodb_ds.GetLayerByName(ogrtest.mongodb_layer_name_no_spatial_index) - if lyr.TestCapability(ogr.OLCFastSpatialFilter) != 0: - gdaltest.post_reason('fail') - print(lyr.TestCapability(ogr.OLCFastSpatialFilter)) - return 'fail' + assert lyr.TestCapability(ogr.OLCFastSpatialFilter) == 0 lyr.SetSpatialFilterRect(1.9, 48.9, 2.1, 49.1) lyr.ResetReading() f = lyr.GetNextFeature() - if f is None: - gdaltest.post_reason('fail') - return 'fail' + assert f is not None gdal.PushErrorHandler() lyr = ogrtest.mongodb_ds.CreateLayer('foo') gdal.PopErrorHandler() - if lyr is not None: - gdaltest.post_reason('fail') - return 'fail' + assert lyr is None gdal.ErrorReset() gdal.PushErrorHandler() ogrtest.mongodb_ds.ExecuteSQL('WRITE_OGR_METADATA ' + ogrtest.mongodb_layer_name) gdal.PopErrorHandler() - if gdal.GetLastErrorMsg() == '': - gdaltest.post_reason('fail') - return 'fail' + assert gdal.GetLastErrorMsg() != '' lyr_count_before = ogrtest.mongodb_ds.GetLayerCount() gdal.PushErrorHandler() ogrtest.mongodb_ds.ExecuteSQL('DELLAYER:' + ogrtest.mongodb_layer_name) gdal.PopErrorHandler() - if ogrtest.mongodb_ds.GetLayerCount() != lyr_count_before: - gdaltest.post_reason('fail') - return 'fail' + assert ogrtest.mongodb_ds.GetLayerCount() == lyr_count_before lyr = ogrtest.mongodb_ds.GetLayerByName(ogrtest.mongodb_layer_name) gdal.PushErrorHandler() ret = lyr.CreateField(ogr.FieldDefn('foo', ogr.OFTString)) gdal.PopErrorHandler() - if ret == 0: - gdaltest.post_reason('fail') - return 'fail' + assert ret != 0 gdal.PushErrorHandler() ret = lyr.CreateGeomField(ogr.GeomFieldDefn('foo', ogr.wkbPoint)) gdal.PopErrorHandler() - if ret == 0: - gdaltest.post_reason('fail') - return 'fail' + assert ret != 0 f = ogr.Feature(lyr.GetLayerDefn()) gdal.PushErrorHandler() ret = lyr.CreateFeature(f) gdal.PopErrorHandler() - if ret == 0: - gdaltest.post_reason('fail') - return 'fail' + assert ret != 0 gdal.PushErrorHandler() ret = lyr.SetFeature(f) gdal.PopErrorHandler() - if ret == 0: - gdaltest.post_reason('fail') - return 'fail' + assert ret != 0 gdal.PushErrorHandler() ret = lyr.DeleteFeature(1) gdal.PopErrorHandler() - if ret == 0: - gdaltest.post_reason('fail') - return 'fail' - - return 'success' + assert ret != 0 ############################################################################### # test_ogrsf -def ogr_mongodb_3(): +def test_ogr_mongodb_3(): if ogrtest.mongodb_drv is None: - return 'skip' + pytest.skip() import test_cli_utilities if test_cli_utilities.get_test_ogrsf_path() is None: - return 'skip' + pytest.skip() ret = gdaltest.runexternal(test_cli_utilities.get_test_ogrsf_path() + ' -ro ' + ogrtest.mongodb_test_uri) - if ret.find('INFO') == -1 or ret.find('ERROR') != -1: - print(ret) - return 'fail' - - return 'success' + assert ret.find('INFO') != -1 and ret.find('ERROR') == -1 ############################################################################### # Cleanup -def ogr_mongodb_cleanup(): +def test_ogr_mongodb_cleanup(): if ogrtest.mongodb_drv is None: - return 'skip' + pytest.skip() ogrtest.mongodb_ds = None @@ -961,24 +807,5 @@ def ogr_mongodb_cleanup(): ogrtest.mongodb_ds = None - return 'success' - - -gdaltest_list = [ - ogr_mongodb_init, - ogr_mongodb_1, - ogr_mongodb_2, - ogr_mongodb_3, - ogr_mongodb_cleanup, -] - -if __name__ == '__main__': - - import locale - locale.setlocale(locale.LC_ALL, '') - - gdaltest.setup_run('ogr_mongodb') - gdaltest.run_tests(gdaltest_list) - sys.exit(gdaltest.summarize()) diff --git a/autotest/ogr/ogr_mssqlspatial.py b/autotest/ogr/ogr_mssqlspatial.py index 733c1e70e07b..ce19b62a4570 100755 --- a/autotest/ogr/ogr_mssqlspatial.py +++ b/autotest/ogr/ogr_mssqlspatial.py @@ -29,26 +29,25 @@ # DEALINGS IN THE SOFTWARE. ############################################################################### -import sys -sys.path.append('../pymod') import gdaltest import ogrtest from osgeo import gdal from osgeo import ogr from osgeo import osr +import pytest ############################################################################### # Open Database. -def ogr_mssqlspatial_1(): +def test_ogr_mssqlspatial_1(): gdaltest.mssqlspatial_ds = None if ogr.GetDriverByName('MSSQLSpatial') is None: - return 'skip' + pytest.skip() gdaltest.mssqlspatial_dsname = gdal.GetConfigOption( 'OGR_MSSQL_CONNECTION_STRING', @@ -56,7 +55,7 @@ def ogr_mssqlspatial_1(): 'MSSQL:server=127.0.0.1;database=TestDB;driver=ODBC Driver 17 for SQL Server;UID=SA;PWD=DummyPassw0rd') gdaltest.mssqlspatial_ds = ogr.Open(gdaltest.mssqlspatial_dsname, update=1) if gdaltest.mssqlspatial_ds is None: - return 'skip' + pytest.skip() # Fetch and store the major-version number of the SQL Server engine in use sql_lyr = gdaltest.mssqlspatial_ds.ExecuteSQL( @@ -76,16 +75,14 @@ def ogr_mssqlspatial_1(): # available since SQL Server 2012 gdaltest.mssqlspatial_has_z_m = (gdaltest.mssqlspatial_version_major >= 11) - return 'success' - ############################################################################### # Create table from data/poly.shp -def ogr_mssqlspatial_2(): +def test_ogr_mssqlspatial_2(): if gdaltest.mssqlspatial_ds is None: - return 'skip' + pytest.skip() shp_ds = ogr.Open('data/poly.shp') gdaltest.shp_ds = shp_ds @@ -126,33 +123,23 @@ def ogr_mssqlspatial_2(): dst_feat = None - if gdaltest.mssqlspatial_lyr.GetFeatureCount() != shp_lyr.GetFeatureCount(): - gdaltest.post_reason('not matching feature count') - return 'fail' - - if not gdaltest.mssqlspatial_lyr.GetSpatialRef().IsSame(shp_lyr.GetSpatialRef()): - gdaltest.post_reason('not matching spatial ref') - return 'fail' + assert gdaltest.mssqlspatial_lyr.GetFeatureCount() == shp_lyr.GetFeatureCount(), \ + 'not matching feature count' - return 'success' + assert gdaltest.mssqlspatial_lyr.GetSpatialRef().IsSame(shp_lyr.GetSpatialRef()), \ + 'not matching spatial ref' ############################################################################### # Verify that stuff we just wrote is still OK. -def ogr_mssqlspatial_3(): +def test_ogr_mssqlspatial_3(): if gdaltest.mssqlspatial_ds is None: - return 'skip' + pytest.skip() - if gdaltest.mssqlspatial_lyr.GetGeometryColumn() != 'ogr_geometry': - gdaltest.post_reason('fail') - print(gdaltest.mssqlspatial_lyr.GetGeometryColumn()) - return 'fail' + assert gdaltest.mssqlspatial_lyr.GetGeometryColumn() == 'ogr_geometry' - if gdaltest.mssqlspatial_lyr.GetFeatureCount() != 10: - gdaltest.post_reason('GetFeatureCount() returned %d instead of 10' % - gdaltest.mssqlspatial_lyr.GetFeatureCount()) - return 'fail' + assert gdaltest.mssqlspatial_lyr.GetFeatureCount() == 10 expect = [168, 169, 166, 158, 165] @@ -160,10 +147,7 @@ def ogr_mssqlspatial_3(): tr = ogrtest.check_features_against_list(gdaltest.mssqlspatial_lyr, 'eas_id', expect) - if gdaltest.mssqlspatial_lyr.GetFeatureCount() != 5: - gdaltest.post_reason('GetFeatureCount() returned %d instead of 5' % - gdaltest.mssqlspatial_lyr.GetFeatureCount()) - return 'fail' + assert gdaltest.mssqlspatial_lyr.GetFeatureCount() == 5 gdaltest.mssqlspatial_lyr.SetAttributeFilter(None) @@ -171,17 +155,13 @@ def ogr_mssqlspatial_3(): orig_feat = gdaltest.poly_feat[i] read_feat = gdaltest.mssqlspatial_lyr.GetNextFeature() - if ogrtest.check_feature_geometry(read_feat, orig_feat.GetGeometryRef(), - max_error=0.001) != 0: - return 'fail' + assert (ogrtest.check_feature_geometry(read_feat, orig_feat.GetGeometryRef(), + max_error=0.001) == 0) for fld in range(3): - if orig_feat.GetField(fld) != read_feat.GetField(fld): - gdaltest.post_reason('Attribute %d does not match' % fld) - return 'fail' - if read_feat.GetField('INT64') != 1234567890123: - gdaltest.post_reason('failure') - return 'fail' + assert orig_feat.GetField(fld) == read_feat.GetField(fld), \ + ('Attribute %d does not match' % fld) + assert read_feat.GetField('INT64') == 1234567890123 read_feat = None orig_feat = None @@ -189,16 +169,16 @@ def ogr_mssqlspatial_3(): gdaltest.poly_feat = None gdaltest.shp_ds = None - return 'success' if tr else 'fail' + assert tr ############################################################################### # Write more features with a bunch of different geometries, and verify the # geometries are still OK. -def ogr_mssqlspatial_4(): +def test_ogr_mssqlspatial_4(): if gdaltest.mssqlspatial_ds is None: - return 'skip' + pytest.skip() dst_feat = ogr.Feature( feature_def=gdaltest.mssqlspatial_lyr.GetLayerDefn()) @@ -219,19 +199,16 @@ def ogr_mssqlspatial_4(): dst_feat.SetGeometryDirectly(geom) dst_feat.SetField('PRFEDEA', item) dst_feat.SetFID(-1) - if gdaltest.mssqlspatial_lyr.CreateFeature(dst_feat) \ - != ogr.OGRERR_NONE: - gdaltest.post_reason('CreateFeature failed creating feature ' + + assert gdaltest.mssqlspatial_lyr.CreateFeature(dst_feat) == ogr.OGRERR_NONE, \ + ('CreateFeature failed creating feature ' + 'from file "' + wkt_filename + '"') - return 'fail' ###################################################################### # Before reading back the record, verify that the newly added feature # is returned from the CreateFeature method with a newly assigned FID. - if dst_feat.GetFID() == -1: - gdaltest.post_reason('Assigned FID was not returned in the new feature') - return 'fail' + assert dst_feat.GetFID() != -1, \ + 'Assigned FID was not returned in the new feature' ###################################################################### # Read back the feature and get the geometry. @@ -243,45 +220,38 @@ def ogr_mssqlspatial_4(): if ogrtest.check_feature_geometry(feat_read, geom) != 0: print(item) print(wkt) - print(geom_read) - return 'fail' + pytest.fail(geom_read) feat_read.Destroy() dst_feat.Destroy() gdaltest.mssqlspatial_lyr.ResetReading() # to close implicit transaction - return 'success' - ############################################################################### # Run test_ogrsf -def ogr_mssqlspatial_test_ogrsf(): +def test_ogr_mssqlspatial_test_ogrsf(): if gdaltest.mssqlspatial_ds is None: - return 'skip' + pytest.skip() import test_cli_utilities if test_cli_utilities.get_test_ogrsf_path() is None: - return 'skip' + pytest.skip() ret = gdaltest.runexternal(test_cli_utilities.get_test_ogrsf_path() + " -ro '" + gdaltest.mssqlspatial_dsname + "' tpoly") - if ret.find('INFO') == -1 or ret.find('ERROR') != -1: - print(ret) - return 'fail' - - return 'success' + assert ret.find('INFO') != -1 and ret.find('ERROR') == -1 ############################################################################### # Verify features can be created in an existing table that includes a geometry # column but is not registered in the "geometry_columns" table. -def ogr_mssqlspatial_create_feature_in_unregistered_table(): +def test_ogr_mssqlspatial_create_feature_in_unregistered_table(): if gdaltest.mssqlspatial_ds is None: - return 'skip' + pytest.skip() # Create a feature that specifies a spatial-reference system spatial_reference = osr.SpatialReference() @@ -311,58 +281,47 @@ def ogr_mssqlspatial_create_feature_in_unregistered_table(): gdal.SetConfigOption('MSSQLSPATIAL_USE_GEOMETRY_COLUMNS', use_geometry_columns) - if test_ds is None: - gdaltest.post_reason('cannot open data source') - return 'fail' + assert test_ds is not None, 'cannot open data source' # Get a layer backed by the newly created table and verify that (as it is # unregistered) it has no associated spatial-reference system unregistered_layer = test_ds.GetLayerByName('Unregistered'); - if unregistered_layer is None: - gdaltest.post_reason('did not get Unregistered layer') - return 'fail' + assert unregistered_layer is not None, 'did not get Unregistered layer' unregistered_spatial_reference = unregistered_layer.GetSpatialRef() - if unregistered_spatial_reference is not None: - gdaltest.post_reason('layer Unregistered unexpectedly has an SRS') - return 'fail' + assert unregistered_spatial_reference is None, \ + 'layer Unregistered unexpectedly has an SRS' # Verify creating the feature in the layer succeeds despite the lack of an # associated spatial-reference system - if unregistered_layer.CreateFeature(feature) != ogr.OGRERR_NONE: - gdaltest.post_reason('CreateFeature failed') - return 'fail' + assert unregistered_layer.CreateFeature(feature) == ogr.OGRERR_NONE, \ + 'CreateFeature failed' # Verify the created feature received the spatial-reference system of the # original, as none was associated with the table unregistered_layer.ResetReading() created_feature = unregistered_layer.GetNextFeature() - if created_feature is None: - gdaltest.post_reason('did not get feature') - return 'fail' + assert created_feature is not None, 'did not get feature' created_feature_geometry = created_feature.GetGeometryRef() created_spatial_reference = created_feature_geometry.GetSpatialReference() - if not ((created_spatial_reference == spatial_reference) + assert ((created_spatial_reference == spatial_reference) or ((created_spatial_reference is not None) - and created_spatial_reference.IsSame(spatial_reference))): - gdaltest.post_reason('created-feature SRS does not match original') - return 'fail' + and created_spatial_reference.IsSame(spatial_reference))), \ + 'created-feature SRS does not match original' # Clean up test_ds.Destroy() feature.Destroy() - return 'success' - ############################################################################### # -def ogr_mssqlspatial_cleanup(): +def test_ogr_mssqlspatial_cleanup(): if gdaltest.mssqlspatial_ds is None: - return 'skip' + pytest.skip() gdaltest.mssqlspatial_ds = None @@ -372,23 +331,5 @@ def ogr_mssqlspatial_cleanup(): gdaltest.mssqlspatial_ds = None - return 'success' - - -gdaltest_list = [ - ogr_mssqlspatial_1, - ogr_mssqlspatial_2, - ogr_mssqlspatial_3, - ogr_mssqlspatial_4, - ogr_mssqlspatial_test_ogrsf, - ogr_mssqlspatial_create_feature_in_unregistered_table, - ogr_mssqlspatial_cleanup -] - -if __name__ == '__main__': - - gdaltest.setup_run('ogr_mssqlspatial') - gdaltest.run_tests(gdaltest_list) - sys.exit(gdaltest.summarize()) diff --git a/autotest/ogr/ogr_mvt.py b/autotest/ogr/ogr_mvt.py index 133ab7a472d7..a58b53d883c5 100644 --- a/autotest/ogr/ogr_mvt.py +++ b/autotest/ogr/ogr_mvt.py @@ -31,7 +31,6 @@ import json import sys -sys.path.append('../pymod') import gdaltest import ogrtest @@ -39,11 +38,12 @@ from osgeo import gdal from osgeo import ogr from osgeo import osr +import pytest ############################################################################### -def ogr_mvt_datatypes(): +def test_ogr_mvt_datatypes(): # With metadata.json ds = ogr.Open('data/mvt/datatypes/0/0/0.pbf') @@ -64,9 +64,8 @@ def ogr_mvt_datatypes(): f['float_value'] != 1.25 or \ f['real_value'] != 1.23456789 or \ f['string_value'] != 'str': - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' + pytest.fail() # Without metadata.json ds = gdal.OpenEx('data/mvt/datatypes/0/0/0.pbf', @@ -74,10 +73,7 @@ def ogr_mvt_datatypes(): lyr = ds.GetLayer(0) count = lyr.GetLayerDefn().GetFieldCount() - if count != 16: - gdaltest.post_reason('fail') - print(count) - return 'fail' + assert count == 16 tab = [] for i in range(lyr.GetLayerDefn().GetFieldCount()): @@ -102,11 +98,7 @@ def ogr_mvt_datatypes(): ('real_value', ogr.OFTReal, ogr.OFSTNone), ('string_value', ogr.OFTString, ogr.OFSTNone), ] - if tab != expected_tab: - gdaltest.post_reason('fail') - print(tab) - print(expected_tab) - return 'fail' + assert tab == expected_tab f = lyr.GetNextFeature() if f['bool_false'] != 0 or \ @@ -124,16 +116,14 @@ def ogr_mvt_datatypes(): f['float_value'] != 1.25 or \ f['real_value'] != 1.23456789 or \ f['string_value'] != 'str': - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' - - return 'success' + pytest.fail() + ############################################################################### -def ogr_mvt_datatype_promotion(): +def test_ogr_mvt_datatype_promotion(): ds = ogr.Open('data/mvt/datatype_promotion.pbf') tab = [('int_to_int64', ogr.OFTInteger64), @@ -145,202 +135,165 @@ def ogr_mvt_datatype_promotion(): for layer_name, dt in tab: lyr = ds.GetLayerByName(layer_name) fld_defn = lyr.GetLayerDefn().GetFieldDefn(1) - if fld_defn.GetType() != dt: - gdaltest.post_reason('fail') - print(layer_name) - print(fld_defn.GetType(), dt) - return 'fail' - if fld_defn.GetSubType() != ogr.OFSTNone: - gdaltest.post_reason('fail') - print(layer_name) - return 'fail' - - return 'success' + assert fld_defn.GetType() == dt, layer_name + assert fld_defn.GetSubType() == ogr.OFSTNone, layer_name + ############################################################################### -def ogr_mvt_limit_cases(): +def test_ogr_mvt_limit_cases(): with gdaltest.error_handler(): ds = ogr.Open('data/mvt/limit_cases.pbf') lyr = ds.GetLayerByName('empty') - if lyr.GetFeatureCount() != 0: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.GetFeatureCount() == 0 lyr = ds.GetLayerByName('layer1') - if lyr.GetFeatureCount() != 7: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.GetFeatureCount() == 7 f = lyr.GetFeature(1) - if f['mvt_id'] != 1: - gdaltest.post_reason('fail') - return 'fail' + assert f['mvt_id'] == 1 with gdaltest.error_handler(): f = lyr.GetFeature(6) - if f['b'] != 1: - gdaltest.post_reason('fail') - return 'fail' + assert f['b'] == 1 lyr = ds.GetLayerByName('layer2') - if lyr.GetFeatureCount() != 0: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.GetFeatureCount() == 0 lyr = ds.GetLayerByName('layer3') - if lyr.GetFeatureCount() != 0: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.GetFeatureCount() == 0 lyr = ds.GetLayerByName('layer4') - if lyr.GetFeatureCount() != 0: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.GetFeatureCount() == 0 lyr = ds.GetLayerByName('layer5') - if lyr.GetFeatureCount() != 1: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.GetFeatureCount() == 1 f = lyr.GetNextFeature() - if f.GetGeometryRef().ExportToWkt() != 'POINT (2070 2690)': - gdaltest.post_reason('fail') - return 'fail' - - return 'success' + assert f.GetGeometryRef().ExportToWkt() == 'POINT (2070 2690)' ############################################################################### -def ogr_mvt_with_extension_fields(): +def test_ogr_mvt_with_extension_fields(): ds = ogr.Open('data/mvt/with_extension_fields.pbf') lyr = ds.GetLayer(0) f = lyr.GetNextFeature() if ogrtest.check_feature_geometry(f, 'LINESTRING (2070 2690,2082 2707)') != 0: - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' - - return 'success' + pytest.fail() + ############################################################################### -def ogr_mvt_mixed(): +def test_ogr_mvt_mixed(): ds = ogr.Open('data/mvt/mixed/0/0/0.pbf') lyr = ds.GetLayer(0) f = lyr.GetNextFeature() if ogrtest.check_feature_geometry(f, 'MULTIPOINT ((215246.671651058 6281289.23636264),(332653.947097085 6447616.20991119))') != 0: - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' + pytest.fail() f = lyr.GetNextFeature() if ogrtest.check_feature_geometry(f, 'LINESTRING (215246.671651058 6281289.23636264,332653.947097085 6447616.20991119)') != 0: - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' - - return 'success' + pytest.fail() + ############################################################################### -def ogr_mvt_linestring(): +def test_ogr_mvt_linestring(): ds = ogr.Open('data/mvt/linestring/0/0/0.pbf') lyr = ds.GetLayer(0) f = lyr.GetNextFeature() if ogrtest.check_feature_geometry(f, 'MULTILINESTRING ((215246.671651058 6281289.23636264,332653.947097085 6447616.20991119))') != 0: f.DumpReadable() - return 'fail' + pytest.fail() ds = gdal.OpenEx('data/mvt/linestring/0/0/0.pbf', open_options=['METADATA_FILE=']) lyr = ds.GetLayer(0) f = lyr.GetNextFeature() if ogrtest.check_feature_geometry(f, 'LINESTRING (215246.671651058 6281289.23636264,332653.947097085 6447616.20991119)') != 0: f.DumpReadable() - return 'fail' - - return 'success' + pytest.fail() + ############################################################################### -def ogr_mvt_multilinestring(): +def test_ogr_mvt_multilinestring(): ds = ogr.Open('data/mvt/multilinestring/0/0/0.pbf') lyr = ds.GetLayer(0) f = lyr.GetNextFeature() if ogrtest.check_feature_geometry(f, 'MULTILINESTRING ((215246.671651058 6281289.23636264,332653.947097085 6447616.20991119),(440277.282922614 6623727.12308023,547900.618748143 6809621.97586978),(665307.894194175 6985732.88903883,772931.230019704 7171627.74182838))') != 0: f.DumpReadable() - return 'fail' + pytest.fail() ds = gdal.OpenEx('data/mvt/multilinestring/0/0/0.pbf', open_options=['METADATA_FILE=']) lyr = ds.GetLayer(0) f = lyr.GetNextFeature() if ogrtest.check_feature_geometry(f, 'MULTILINESTRING ((215246.671651058 6281289.23636264,332653.947097085 6447616.20991119),(440277.282922614 6623727.12308023,547900.618748143 6809621.97586978),(665307.894194175 6985732.88903883,772931.230019704 7171627.74182838))') != 0: f.DumpReadable() - return 'fail' - - return 'success' + pytest.fail() + ############################################################################### -def ogr_mvt_polygon(): +def test_ogr_mvt_polygon(): ds = ogr.Open('data/mvt/polygon/0/0/0.pbf') lyr = ds.GetLayer(0) f = lyr.GetNextFeature() if ogrtest.check_feature_geometry(f, 'MULTIPOLYGON (((332653.947097085 6447616.20991119,332653.947097085 6281289.23636264,215246.671651058 6281289.23636264,215246.671651058 6447616.20991119,332653.947097085 6447616.20991119)))') != 0: f.DumpReadable() - return 'fail' + pytest.fail() ds = gdal.OpenEx('data/mvt/polygon/0/0/0.pbf', open_options=['METADATA_FILE=']) lyr = ds.GetLayer(0) f = lyr.GetNextFeature() if ogrtest.check_feature_geometry(f, 'POLYGON ((332653.947097085 6447616.20991119,332653.947097085 6281289.23636264,215246.671651058 6281289.23636264,215246.671651058 6447616.20991119,332653.947097085 6447616.20991119))') != 0: f.DumpReadable() - return 'fail' - - return 'success' + pytest.fail() + ############################################################################### -def ogr_mvt_point_polygon(): +def test_ogr_mvt_point_polygon(): ds = ogr.Open('data/mvt/point_polygon/0') lyr = ds.GetLayer(0) f = lyr.GetNextFeature() if ogrtest.check_feature_geometry(f, 'MULTIPOINT ((215246.671651058 6281289.23636264))') != 0: f.DumpReadable() - return 'fail' + pytest.fail() lyr = ds.GetLayer(1) f = lyr.GetNextFeature() if ogrtest.check_feature_geometry(f, 'MULTIPOLYGON (((440277.282922614 450061.222543117,440277.282922614 -440277.282922614,0.0 -440277.282922614,0.0 -215246.671651058,215246.671651058 -215246.671651058,215246.671651058 225030.61127156,0.0 225030.61127156,0.0 450061.222543117,440277.282922614 450061.222543117)),((0.0 117407.275446031,0.0 -107623.335825529,-117407.275446031 -107623.335825529,-117407.275446031 117407.275446031,0.0 117407.275446031)),((107623.335825529 58703.6377230138,107623.335825529 -48919.6981025115,48919.6981025115 -48919.6981025115,48919.6981025115 58703.6377230138,107623.335825529 58703.6377230138)))') != 0: f.DumpReadable() - return 'fail' - - return 'success' + pytest.fail() + ############################################################################### -def ogr_mvt_point_polygon_clip(): +def test_ogr_mvt_point_polygon_clip(): if not ogrtest.have_geos() or gdal.GetConfigOption('OGR_MVT_CLIP') is not None: - return 'skip' + pytest.skip() if gdal.GetConfigOption('APPVEYOR') is not None: - return 'skip' + pytest.skip() if sys.platform == 'darwin' and gdal.GetConfigOption('TRAVIS', None) is not None: - return 'skip' + pytest.skip() ds = ogr.Open('data/mvt/point_polygon/1') lyr = ds.GetLayer(1) @@ -348,77 +301,57 @@ def ogr_mvt_point_polygon_clip(): if ogrtest.check_feature_geometry(f, 'MULTIPOLYGON (((445169.252732867 450061.222543117,445169.252732867 0.0,220138.641461308 0.0,220138.641461308 225030.61127156,0.0 225030.61127156,0.0 450061.222543117,445169.252732867 450061.222543117)),((107623.335825528 58703.6377230138,107623.335825528 0.0,53811.6679127641 0.0,53811.6679127641 58703.6377230138,107623.335825528 58703.6377230138)))') != 0 and \ ogrtest.check_feature_geometry(f, 'MULTIPOLYGON (((445169.252732867 0.0,445169.252732867 -445169.252732867,0.0 -445169.252732867,0.0 -220138.641461308,220138.641461308 -220138.641461308,220138.641461308 0.0,445169.252732867 0.0)),((107623.335825528 0.0,107623.335825528 -53811.6679127641,53811.6679127641 -53811.6679127641,53811.6679127641 0.0,107623.335825528 0.0)))') != 0: f.DumpReadable() - return 'fail' - - return 'success' + pytest.fail() + ############################################################################### -def ogr_mvt_tileset_without_readdir(): +def test_ogr_mvt_tileset_without_readdir(): with gdaltest.config_option('MVT_USE_READDIR', 'NO'): ds = gdal.OpenEx('data/mvt/linestring/0') lyr = ds.GetLayer(0) f = lyr.GetNextFeature() - if f is None: - return 'fail' - - return 'success' + assert f is not None ############################################################################### -def ogr_mvt_tileset_tilegl(): +def test_ogr_mvt_tileset_tilegl(): ds = ogr.Open('data/mvt/linestring_tilejson_gl/0') lyr = ds.GetLayer(0) - if lyr.GetLayerDefn().GetFieldCount() != 2: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.GetLayerDefn().GetFieldCount() == 2 f = lyr.GetNextFeature() - if f is None: - gdaltest.post_reason('fail') - return 'fail' - - return 'success' + assert f is not None ############################################################################### -def ogr_mvt_tileset_without_metadata_file(): +def test_ogr_mvt_tileset_without_metadata_file(): ds = gdal.OpenEx('data/mvt/point_polygon/1', open_options=['METADATA_FILE=', 'CLIP=NO']) lyr = ds.GetLayerByName('point') - if lyr.GetGeomType() != ogr.wkbMultiPoint: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.GetGeomType() == ogr.wkbMultiPoint lyr = ds.GetLayerByName('polygon2') - if lyr.GetGeomType() != ogr.wkbMultiPolygon: - gdaltest.post_reason('fail') - return 'fail' - if lyr.GetLayerDefn().GetFieldCount() != 2: - gdaltest.post_reason('fail') - return 'fail' - - return 'success' + assert lyr.GetGeomType() == ogr.wkbMultiPolygon + assert lyr.GetLayerDefn().GetFieldCount() == 2 ############################################################################### -def ogr_mvt_tileset_json_field(): +def test_ogr_mvt_tileset_json_field(): ds = gdal.OpenEx('data/mvt/datatypes/0', open_options=['METADATA_FILE=', 'JSON_FIELD=YES', 'CLIP=NO']) lyr = ds.GetLayer(0) - if lyr.GetLayerDefn().GetFieldCount() != 2: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.GetLayerDefn().GetFieldCount() == 2 f = lyr.GetNextFeature() d = json.loads(f.GetFieldAsString("json")) - if d != { + assert (d == { "bool_true": True, "bool_false": False, "pos_int_value": 1, @@ -434,17 +367,12 @@ def ogr_mvt_tileset_json_field(): "float_value": 1.25, "real_value": 1.23456789, "string_value": "str" - }: - gdaltest.post_reason('fail') - print(f.GetFieldAsString("json")) - return 'fail' - - return 'success' + }), f.GetFieldAsString("json") ############################################################################### -def ogr_mvt_open_variants(): +def test_ogr_mvt_open_variants(): expected_geom = 'MULTILINESTRING ((215246.671651058 6281289.23636264,332653.947097085 6447616.20991119))' @@ -452,129 +380,111 @@ def ogr_mvt_open_variants(): lyr = ds.GetLayer(0) f = lyr.GetNextFeature() if ogrtest.check_feature_geometry(f, expected_geom) != 0: - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' + pytest.fail() ds = ogr.Open('MVT:data/mvt/linestring/0') lyr = ds.GetLayer(0) f = lyr.GetNextFeature() if ogrtest.check_feature_geometry(f, expected_geom) != 0: - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' + pytest.fail() ds = ogr.Open('/vsigzip/data/mvt/linestring/0/0/0.pbf') lyr = ds.GetLayer(0) f = lyr.GetNextFeature() if ogrtest.check_feature_geometry(f, expected_geom) != 0: - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' + pytest.fail() ds = ogr.Open('MVT:/vsigzip/data/mvt/linestring/0/0/0.pbf') lyr = ds.GetLayer(0) f = lyr.GetNextFeature() if ogrtest.check_feature_geometry(f, expected_geom) != 0: - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' - - return 'success' + pytest.fail() + ############################################################################### -def ogr_mvt_xyz_options(): +def test_ogr_mvt_xyz_options(): ds = gdal.OpenEx('data/mvt/datatypes/0/0/0.pbf', open_options=['X=1', 'Y=2', 'Z=3']) lyr = ds.GetLayer(0) f = lyr.GetNextFeature() if ogrtest.check_feature_geometry(f, 'POINT (-12496536.8802869 8299226.7830913)') != 0: - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' - - return 'success' + pytest.fail() + ############################################################################### -def ogr_mvt_test_ogrsf_pbf(): +def test_ogr_mvt_test_ogrsf_pbf(): import test_cli_utilities if test_cli_utilities.get_test_ogrsf_path() is None: - return 'skip' + pytest.skip() ret = gdaltest.runexternal(test_cli_utilities.get_test_ogrsf_path() + ' -ro data/mvt/datatypes/0/0/0.pbf') - if ret.find('INFO') == -1 or ret.find('ERROR') != -1: - print(ret) - return 'fail' - - return 'success' + assert ret.find('INFO') != -1 and ret.find('ERROR') == -1 ############################################################################### -def ogr_mvt_test_ogrsf_directory(): +def test_ogr_mvt_test_ogrsf_directory(): import test_cli_utilities if test_cli_utilities.get_test_ogrsf_path() is None: - return 'skip' + pytest.skip() ret = gdaltest.runexternal(test_cli_utilities.get_test_ogrsf_path() + ' -ro data/mvt/datatypes/0') - if ret.find('INFO') == -1 or ret.find('ERROR') != -1: - print(ret) - return 'fail' - - return 'success' + assert ret.find('INFO') != -1 and ret.find('ERROR') == -1 ############################################################################### -def ogr_mvt_mbtiles(): +def test_ogr_mvt_mbtiles(): if ogr.GetDriverByName('MBTILES') is None: - return 'skip' + pytest.skip() ds = ogr.Open('data/mvt/point_polygon.mbtiles') lyr = ds.GetLayerByName('point') f = lyr.GetNextFeature() if ogrtest.check_feature_geometry(f, 'MULTIPOINT ((220138.641461308 6276397.26655239))') != 0: f.DumpReadable() - return 'fail' + pytest.fail() lyr.SetSpatialFilterRect(0, 0, 10000000, 10000000) lyr.ResetReading() f = lyr.GetNextFeature() if ogrtest.check_feature_geometry(f, 'MULTIPOINT ((220138.641461308 6276397.26655239))') != 0: f.DumpReadable() - return 'fail' - - return 'success' + pytest.fail() + ############################################################################### -def ogr_mvt_mbtiles_json_field(): +def test_ogr_mvt_mbtiles_json_field(): if ogr.GetDriverByName('MBTILES') is None: - return 'skip' + pytest.skip() ds = gdal.OpenEx('data/mvt/datatypes.mbtiles', open_options=['JSON_FIELD=YES', 'CLIP=NO']) lyr = ds.GetLayer(0) - if lyr.GetLayerDefn().GetFieldCount() != 2: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.GetLayerDefn().GetFieldCount() == 2 f = lyr.GetNextFeature() d = json.loads(f.GetFieldAsString("json")) - if d != {'int64_value': 123456789012345, + assert (d == {'int64_value': 123456789012345, 'string_value': 'str', 'real_value': 1.23456789, 'bool_false': False, @@ -582,30 +492,23 @@ def ogr_mvt_mbtiles_json_field(): 'neg_int_value': -1, 'bool_true': True, 'float_value': 1.25 - }: - gdaltest.post_reason('fail') - print(f.GetFieldAsString("json")) - return 'fail' - - return 'success' + }), f.GetFieldAsString("json") ############################################################################### -def ogr_mvt_mbtiles_json_field_auto(): +def test_ogr_mvt_mbtiles_json_field_auto(): if ogr.GetDriverByName('MBTILES') is None: - return 'skip' + pytest.skip() ds = gdal.OpenEx('data/mvt/datatypes_json_field_auto.mbtiles', open_options=['CLIP=NO']) lyr = ds.GetLayer(0) - if lyr.GetLayerDefn().GetFieldCount() != 2: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.GetLayerDefn().GetFieldCount() == 2 f = lyr.GetNextFeature() d = json.loads(f.GetFieldAsString("json")) - if d != {'int64_value': 123456789012345, + assert (d == {'int64_value': 123456789012345, 'string_value': 'str', 'real_value': 1.23456789, 'bool_false': False, @@ -613,52 +516,40 @@ def ogr_mvt_mbtiles_json_field_auto(): 'neg_int_value': -1, 'bool_true': True, 'float_value': 1.25 - }: - gdaltest.post_reason('fail') - print(f.GetFieldAsString("json")) - return 'fail' - - return 'success' + }), f.GetFieldAsString("json") ############################################################################### -def ogr_mvt_mbtiles_test_ogrsf(): +def test_ogr_mvt_mbtiles_test_ogrsf(): import test_cli_utilities if test_cli_utilities.get_test_ogrsf_path() is None: - return 'skip' + pytest.skip() if ogr.GetDriverByName('MBTILES') is None: - return 'skip' + pytest.skip() ret = gdaltest.runexternal(test_cli_utilities.get_test_ogrsf_path() + ' -ro data/mvt/point_polygon.mbtiles polygon2') - if ret.find('INFO') == -1 or ret.find('ERROR') != -1: - print(ret) - return 'fail' - - return 'success' + assert ret.find('INFO') != -1 and ret.find('ERROR') == -1 ############################################################################### -def ogr_mvt_mbtiles_open_vector_in_raster_mode(): +def test_ogr_mvt_mbtiles_open_vector_in_raster_mode(): if ogr.GetDriverByName('MBTILES') is None: - return 'skip' + pytest.skip() ds = gdal.OpenEx('data/mvt/datatypes.mbtiles', gdal.OF_RASTER) - if ds is not None: - return 'fail' - - return 'success' + assert ds is None ############################################################################### -def ogr_mvt_x_y_z_filename_scheme(): +def test_ogr_mvt_x_y_z_filename_scheme(): tmpfilename = '/vsimem/0-0-0.pbf' gdal.FileFromMemBuffer(tmpfilename, @@ -668,79 +559,60 @@ def ogr_mvt_x_y_z_filename_scheme(): f = lyr.GetNextFeature() if ogrtest.check_feature_geometry(f, 'LINESTRING (215246.671651058 6281289.23636264,332653.947097085 6447616.20991119)') != 0: f.DumpReadable() - return 'fail' + pytest.fail() ds = None gdal.Unlink(tmpfilename) - return 'success' - ############################################################################### -def ogr_mvt_polygon_larger_than_header(): +def test_ogr_mvt_polygon_larger_than_header(): ds = gdal.OpenEx('data/mvt/polygon_larger_than_header.pbf', open_options=['CLIP=NO']) lyr = ds.GetLayer(0) f = lyr.GetNextFeature() - if f is None: - return 'fail' - - return 'success' + assert f is not None ############################################################################### -def ogr_mvt_errors(): +def test_ogr_mvt_errors(): - if ogr.Open('MVT:/i_do_not/exist') is not None: - gdaltest.post_reason('fail') - return 'fail' + assert ogr.Open('MVT:/i_do_not/exist') is None # Cannot detect Z in directory name - if ogr.Open('MVT:data') is not None: - gdaltest.post_reason('fail') - return 'fail' + assert ogr.Open('MVT:data') is None # Invalid Z gdal.Mkdir('/vsimem/33', 0) - if ogr.Open('MVT:/vsimem/33') is not None: - gdaltest.post_reason('fail') - return 'fail' + assert ogr.Open('MVT:/vsimem/33') is None gdal.Rmdir('/vsimem/33') # Inexisting metadata with gdaltest.error_handler(): - if gdal.OpenEx('data/mvt/linestring/0/0/0.pbf', - open_options=['METADATA_FILE=/i_do_not/exist']) is None: - gdaltest.post_reason('fail') - return 'fail' + assert (gdal.OpenEx('data/mvt/linestring/0/0/0.pbf', + open_options=['METADATA_FILE=/i_do_not/exist']) is not None) # Invalid metadata with gdaltest.error_handler(): - if gdal.OpenEx('data/mvt/linestring/0/0/0.pbf', - open_options=['METADATA_FILE=ogr_mvt.py']) is None: - gdaltest.post_reason('fail') - return 'fail' + assert (gdal.OpenEx('data/mvt/linestring/0/0/0.pbf', + open_options=['METADATA_FILE=ogr_mvt.py']) is not None) # Invalid metadata gdal.FileFromMemBuffer('/vsimem/my.json', '{}') with gdaltest.error_handler(): - if gdal.OpenEx('data/mvt/linestring/0/0/0.pbf', - open_options=['METADATA_FILE=/vsimem/my.json']) is None: - gdaltest.post_reason('fail') - return 'fail' + assert (gdal.OpenEx('data/mvt/linestring/0/0/0.pbf', + open_options=['METADATA_FILE=/vsimem/my.json']) is not None) gdal.Unlink('/vsimem/my.json') # Invalid metadata gdal.FileFromMemBuffer('/vsimem/my.json', '{ "json": "x y" }') with gdaltest.error_handler(): - if gdal.OpenEx('data/mvt/linestring/0/0/0.pbf', - open_options=['METADATA_FILE=/vsimem/my.json']) is None: - gdaltest.post_reason('fail') - return 'fail' + assert (gdal.OpenEx('data/mvt/linestring/0/0/0.pbf', + open_options=['METADATA_FILE=/vsimem/my.json']) is not None) gdal.Unlink('/vsimem/my.json') # Too big file @@ -753,36 +625,31 @@ def ogr_mvt_errors(): gdal.VSIFCloseL(f) ds = ogr.Open(tmpfilename) gdal.Unlink(tmpfilename) - if ds is not None: - gdaltest.post_reason('fail') - return 'fail' - - return 'success' + assert ds is None ############################################################################### -def ogr_mvt_http_start(): +def test_ogr_mvt_http_start(): 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 ogr_mvt_http(): +def test_ogr_mvt_http(): if gdaltest.webserver_port == 0: - return 'skip' + pytest.skip() handler = webserver.SequentialHandler() handler.add('GET', '/linestring/metadata.json', 200, {}, @@ -795,9 +662,7 @@ def ogr_mvt_http(): ds = ogr.Open('MVT:http://127.0.0.1:%d/linestring/0' % gdaltest.webserver_port) lyr = ds.GetLayer(0) f = lyr.GetNextFeature() - if f is None: - gdaltest.post_reason('fail') - return 'fail' + assert f is not None # No metadata file nor tile handler = webserver.SequentialHandler() @@ -807,9 +672,7 @@ def ogr_mvt_http(): with webserver.install_http_handler(handler): with gdaltest.error_handler(): ds = ogr.Open('MVT:http://127.0.0.1:%d/linestring/0' % gdaltest.webserver_port) - if ds is not None: - gdaltest.post_reason('fail') - return 'fail' + assert ds is None # No metadata file, but tiles handler = webserver.SequentialHandler() @@ -823,9 +686,7 @@ def ogr_mvt_http(): ds = ogr.Open('MVT:http://127.0.0.1:%d/linestring/0' % gdaltest.webserver_port) lyr = ds.GetLayer(0) f = lyr.GetNextFeature() - if f is None: - gdaltest.post_reason('fail') - return 'fail' + assert f is not None # metadata.json file, but no tiles handler = webserver.SequentialHandler() @@ -837,9 +698,7 @@ def ogr_mvt_http(): ds = ogr.Open('MVT:http://127.0.0.1:%d/linestring/0' % gdaltest.webserver_port) lyr = ds.GetLayer(0) f = lyr.GetNextFeature() - if f is not None: - gdaltest.post_reason('fail') - return 'fail' + assert f is None # No metadata.json file, but a linestring.json and no tiles handler = webserver.SequentialHandler() @@ -852,9 +711,7 @@ def ogr_mvt_http(): ds = ogr.Open('MVT:http://127.0.0.1:%d/linestring/0' % gdaltest.webserver_port) lyr = ds.GetLayer(0) f = lyr.GetNextFeature() - if f is not None: - gdaltest.post_reason('fail') - return 'fail' + assert f is None # Open pbf file handler = webserver.SequentialHandler() @@ -864,31 +721,26 @@ def ogr_mvt_http(): ds = ogr.Open('MVT:http://127.0.0.1:%d/linestring/0/0/0.pbf' % gdaltest.webserver_port) lyr = ds.GetLayer(0) f = lyr.GetNextFeature() - if f is None: - gdaltest.post_reason('fail') - return 'fail' - - return 'success' + assert f is not None + ############################################################################### -def ogr_mvt_http_stop(): +def test_ogr_mvt_http_stop(): if gdaltest.webserver_port == 0: - return 'skip' + pytest.skip() webserver.server_stop(gdaltest.webserver_process, gdaltest.webserver_port) - return 'success' - ############################################################################### -def ogr_mvt_write_one_layer(): +def test_ogr_mvt_write_one_layer(): if not ogrtest.have_geos() or ogr.GetDriverByName('SQLITE') is None: - return 'skip' + pytest.skip() src_ds = gdal.GetDriverByName('Memory').Create('', 0, 0, 0, gdal.GDT_Unknown) lyr = src_ds.CreateLayer('mylayer') @@ -905,23 +757,17 @@ def ogr_mvt_write_one_layer(): # Test empty layer: OK with gdaltest.error_handler(): out_ds = gdal.VectorTranslate('/vsimem/outmvt', src_ds, format='MVT') - if out_ds is None: - gdaltest.post_reason('fail') - return 'fail' + assert out_ds is not None # Cannot create directory with gdaltest.error_handler(): out_ds = gdal.VectorTranslate('/i_dont/exist/outmvt', src_ds, format='MVT') - if out_ds is not None: - gdaltest.post_reason('fail') - return 'fail' + assert out_ds is None # Directory already exists with gdaltest.error_handler(): out_ds = gdal.VectorTranslate('/vsimem/outmvt', src_ds, format='MVT') - if out_ds is not None: - gdaltest.post_reason('fail') - return 'fail' + assert out_ds is None gdal.RmdirRecursive('/vsimem/outmvt') @@ -981,15 +827,11 @@ def ogr_mvt_write_one_layer(): with gdaltest.error_handler(): out_ds = gdal.VectorTranslate('/vsimem/outmvt', src_ds, options='-f MVT -preserve_fid') - if out_ds is None: - gdaltest.post_reason('fail') - return 'fail' + assert out_ds is not None out_ds = None out_ds = ogr.Open('/vsimem/outmvt/0') - if out_ds is None: - gdaltest.post_reason('fail') - return 'fail' + assert out_ds is not None out_lyr = out_ds.GetLayerByName('mylayer') out_f = out_lyr.GetNextFeature() if out_f['mvt_id'] != 123 or \ @@ -1001,9 +843,8 @@ def ogr_mvt_write_one_layer(): out_f['datetimefield'] != '2018-02-01T12:34:56' or \ out_f['boolfield'] is False or \ ogrtest.check_feature_geometry(out_f, 'POINT (498980.920645632 997961.84129126)') != 0: - gdaltest.post_reason('fail') out_f.DumpReadable() - return 'fail' + pytest.fail() out_f = out_lyr.GetNextFeature() if out_f['strfield'] != 'foo' or \ @@ -1014,9 +855,8 @@ def ogr_mvt_write_one_layer(): out_f['datetimefield'] != '2018-02-01T12:34:56' or \ out_f['boolfield'] is False or \ ogrtest.check_feature_geometry(out_f, 'MULTILINESTRING ((498980.920645632 997961.84129126,508764.860266134 1007745.78091176,518548.799886636 1017529.72053226))') != 0: - gdaltest.post_reason('fail') out_f.DumpReadable() - return 'fail' + pytest.fail() out_f = out_lyr.GetNextFeature() if out_f['strfield'] != 'foobarbazbaw' or \ @@ -1027,58 +867,45 @@ def ogr_mvt_write_one_layer(): out_f.IsFieldSet('datetimefield') or \ out_f.IsFieldSet('boolfield') or \ ogrtest.check_feature_geometry(out_f, 'POLYGON ((498980.920645632 997961.84129126,508764.860266134 1007745.78091176,508764.860266134 997961.84129126,498980.920645632 997961.84129126))') != 0: - gdaltest.post_reason('fail') out_f.DumpReadable() - return 'fail' + pytest.fail() out_f = out_lyr.GetNextFeature() if ogrtest.check_feature_geometry(out_f, 'MULTIPOINT ((498980.920645632 997961.84129126),(508764.860266134 1007745.78091176))') != 0: - gdaltest.post_reason('fail') out_f.DumpReadable() - return 'fail' + pytest.fail() out_f = out_lyr.GetNextFeature() if ogrtest.check_feature_geometry(out_f, 'MULTILINESTRING ((498980.920645632 997961.84129126,508764.860266134 1007745.78091176),(508764.860266134 1007745.78091176,508764.860266134 997961.84129126))') != 0: - gdaltest.post_reason('fail') out_f.DumpReadable() - return 'fail' + pytest.fail() out_f = out_lyr.GetNextFeature() if ogrtest.check_feature_geometry(out_f, 'MULTIPOLYGON (((498980.920645632 997961.84129126,508764.860266134 1007745.78091176,508764.860266134 997961.84129126,498980.920645632 997961.84129126)),((-498980.920645632 997961.84129126,-508764.860266134 997961.84129126,-508764.860266134 1007745.78091176,-498980.920645632 997961.84129126)))') != 0: - gdaltest.post_reason('fail') out_f.DumpReadable() - return 'fail' + pytest.fail() out_f = out_lyr.GetNextFeature() if (out_f.GetGeometryRef().GetGeometryType() == ogr.wkbPoint and ogrtest.check_feature_geometry(out_f, 'POINT (498980.920645632 997961.84129126)') != 0) or \ (out_f.GetGeometryRef().GetGeometryType() == ogr.wkbMultiLineString and ogrtest.check_feature_geometry(out_f, 'MULTILINESTRING ((498980.920645632 997961.84129126,508764.860266134 1007745.78091176,518548.799886636 1017529.72053226))') != 0) or \ out_f.GetGeometryRef().GetGeometryType() not in (ogr.wkbPoint, ogr.wkbMultiLineString): - gdaltest.post_reason('fail') out_f.DumpReadable() - return 'fail' + pytest.fail() out_f = out_lyr.GetNextFeature() if (out_f.GetGeometryRef().GetGeometryType() == ogr.wkbPoint and ogrtest.check_feature_geometry(out_f, 'POINT (498980.920645632 997961.84129126)') != 0) or \ (out_f.GetGeometryRef().GetGeometryType() == ogr.wkbMultiLineString and ogrtest.check_feature_geometry(out_f, 'MULTILINESTRING ((498980.920645632 997961.84129126,508764.860266134 1007745.78091176,518548.799886636 1017529.72053226))') != 0) or \ out_f.GetGeometryRef().GetGeometryType() not in (ogr.wkbPoint, ogr.wkbMultiLineString): - gdaltest.post_reason('fail') out_f.DumpReadable() - return 'fail' + pytest.fail() out_ds = ogr.Open('/vsimem/outmvt/5') - if out_ds is None: - gdaltest.post_reason('fail') - return 'fail' + assert out_ds is not None out_lyr = out_ds.GetLayerByName('mylayer') - if out_lyr.GetFeatureCount() != 9: - gdaltest.post_reason('fail') - print(out_lyr.GetFeatureCount()) - return 'fail' + assert out_lyr.GetFeatureCount() == 9 f = gdal.VSIFOpenL('/vsimem/outmvt/metadata.json', 'rb') - if f is None: - gdaltest.post_reason('fail') - return 'fail' + assert f is not None data = gdal.VSIFReadL(1, 100000, f).decode('ASCII') gdal.VSIFCloseL(f) data_json = json.loads(data) @@ -1094,10 +921,7 @@ def ogr_mvt_write_one_layer(): "format": "pbf", } for k in expected_json: - if k not in data_json or data_json[k] != expected_json[k]: - gdaltest.post_reason('fail') - print(data) - return 'fail' + assert k in data_json and data_json[k] == expected_json[k], data json_json = json.loads(data_json['json']) expected_json_json = { "vector_layers": [ @@ -1198,22 +1022,17 @@ def ogr_mvt_write_one_layer(): } } - if json_json != expected_json_json: - gdaltest.post_reason('fail') - print(data_json['json']) - return 'fail' + assert json_json == expected_json_json, data_json['json'] gdal.RmdirRecursive('/vsimem/outmvt') - return 'success' - ############################################################################### -def ogr_mvt_write_conf(): +def test_ogr_mvt_write_conf(): if not ogrtest.have_geos() or ogr.GetDriverByName('SQLITE') is None: - return 'skip' + pytest.skip() src_ds = gdal.GetDriverByName('Memory').Create('', 0, 0, 0, gdal.GDT_Unknown) lyr = src_ds.CreateLayer('mylayer') @@ -1228,26 +1047,19 @@ def ogr_mvt_write_conf(): 'maxzoom': 2}} out_ds = gdal.VectorTranslate('/vsimem/outmvt', src_ds, format='MVT', datasetCreationOptions=["CONF=%s" % json.dumps(conf)]) - if out_ds is None: - gdaltest.post_reason('fail') - return 'fail' + assert out_ds is not None out_ds = None out_ds = ogr.Open('/vsimem/outmvt/1') - if out_ds is None: - gdaltest.post_reason('fail') - return 'fail' + assert out_ds is not None out_lyr = out_ds.GetLayerByName('TheLayer') out_f = out_lyr.GetNextFeature() if ogrtest.check_feature_geometry(out_f, 'MULTIPOINT (498980.920645632 997961.84129126)') != 0: - gdaltest.post_reason('fail') out_f.DumpReadable() - return 'fail' + pytest.fail() f = gdal.VSIFOpenL('/vsimem/outmvt/metadata.json', 'rb') - if f is None: - gdaltest.post_reason('fail') - return 'fail' + assert f is not None data = gdal.VSIFReadL(1, 100000, f).decode('ASCII') gdal.VSIFCloseL(f) data_json = json.loads(data) @@ -1278,22 +1090,17 @@ def ogr_mvt_write_conf(): } } - if json_json != expected_json_json: - gdaltest.post_reason('fail') - print(data_json['json']) - return 'fail' + assert json_json == expected_json_json, data_json['json'] gdal.RmdirRecursive('/vsimem/outmvt') - return 'success' - ############################################################################### -def ogr_mvt_write_mbtiles(): +def test_ogr_mvt_write_mbtiles(): if not ogrtest.have_geos() or ogr.GetDriverByName('SQLITE') is None: - return 'skip' + pytest.skip() src_ds = gdal.GetDriverByName('Memory').Create('', 0, 0, 0, gdal.GDT_Unknown) lyr = src_ds.CreateLayer('mylayer') @@ -1303,34 +1110,27 @@ def ogr_mvt_write_mbtiles(): lyr.CreateFeature(f) out_ds = gdal.VectorTranslate('/vsimem/out.mbtiles', src_ds) - if out_ds is None: - gdaltest.post_reason('fail') - return 'fail' + assert out_ds is not None out_ds = None out_ds = ogr.Open('/vsimem/out.mbtiles') - if out_ds is None: - gdaltest.post_reason('fail') - return 'fail' + assert out_ds is not None out_lyr = out_ds.GetLayerByName('mylayer') out_f = out_lyr.GetNextFeature() if ogrtest.check_feature_geometry(out_f, 'MULTIPOINT ((499898.164985053 1000102.07808325))') != 0: - gdaltest.post_reason('fail') out_f.DumpReadable() - return 'fail' + pytest.fail() out_ds = None gdal.Unlink('/vsimem/out.mbtiles') - return 'success' - ############################################################################### -def ogr_mvt_write_limitations_max_size(): +def test_ogr_mvt_write_limitations_max_size(): if not ogrtest.have_geos() or ogr.GetDriverByName('SQLITE') is None: - return 'skip' + pytest.skip() src_ds = gdal.GetDriverByName('Memory').Create('', 0, 0, 0, gdal.GDT_Unknown) lyr = src_ds.CreateLayer('mylayer') @@ -1349,39 +1149,31 @@ def ogr_mvt_write_limitations_max_size(): with gdaltest.config_option('GDAL_NUM_THREADS', '1'): out_ds = gdal.VectorTranslate('/vsimem/out.mbtiles', src_ds, datasetCreationOptions=['MAX_SIZE=100', 'SIMPLIFICATION=1']) - if out_ds is None: - gdaltest.post_reason('fail') - return 'fail' + assert out_ds is not None out_ds = None out_ds = ogr.Open('/vsimem/out.mbtiles') - if out_ds is None: - gdaltest.post_reason('fail') - return 'fail' + assert out_ds is not None out_lyr = out_ds.GetLayerByName('mylayer') out_f = out_lyr.GetNextFeature() if ogrtest.check_feature_geometry(out_f, 'MULTILINESTRING ((498980.920645631 1007745.78091176,508764.860266133 1007745.78091176))') != 0: - gdaltest.post_reason('fail') out_f.DumpReadable() - return 'fail' + pytest.fail() out_f = out_lyr.GetNextFeature() if ogrtest.check_feature_geometry(out_f, 'POINT (498980.920645631 1007745.78091176)') != 0: - gdaltest.post_reason('fail') out_f.DumpReadable() - return 'fail' + pytest.fail() out_ds = None gdal.Unlink('/vsimem/out.mbtiles') - return 'success' - ############################################################################### -def ogr_mvt_write_polygon_repaired(): +def test_ogr_mvt_write_polygon_repaired(): if not ogrtest.have_geos() or ogr.GetDriverByName('SQLITE') is None: - return 'skip' + pytest.skip() src_ds = gdal.GetDriverByName('Memory').Create('', 0, 0, 0, gdal.GDT_Unknown) lyr = src_ds.CreateLayer('mylayer') @@ -1401,44 +1193,35 @@ def ogr_mvt_write_polygon_repaired(): lyr.CreateFeature(f) out_ds = gdal.VectorTranslate('/vsimem/out.mbtiles', src_ds, datasetCreationOptions=['MAXZOOM=0']) - if out_ds is None: - gdaltest.post_reason('fail') - return 'fail' + assert out_ds is not None out_ds = None out_ds = ogr.Open('/vsimem/out.mbtiles') - if out_ds is None: - gdaltest.post_reason('fail') - return 'fail' + assert out_ds is not None out_lyr = out_ds.GetLayerByName('mylayer') out_f = out_lyr.GetNextFeature() if ogrtest.check_feature_geometry(out_f, 'MULTIPOLYGON (((0 0,0.0 498980.920645632,498980.920645632 498980.920645632,498980.920645632 0.0,0 0)))') != 0: - gdaltest.post_reason('fail') out_f.DumpReadable() - return 'fail' + pytest.fail() out_f = out_lyr.GetNextFeature() if ogrtest.check_feature_geometry(out_f, 'MULTIPOLYGON (((0 0,0.0 498980.920645632,498980.920645632 498980.920645632,498980.920645632 0.0,0 0)),((997961.84129126 0.0,997961.84129126 997961.84129126,1995923.68258252 997961.84129126,997961.84129126 0.0)))') != 0: - gdaltest.post_reason('fail') out_f.DumpReadable() - return 'fail' + pytest.fail() out_f = out_lyr.GetNextFeature() if out_f is not None: - gdaltest.post_reason('fail') out_f.DumpReadable() - return 'fail' + pytest.fail() out_ds = None gdal.Unlink('/vsimem/out.mbtiles') - return 'success' - ############################################################################### -def ogr_mvt_write_conflicting_innner_ring(): +def test_ogr_mvt_write_conflicting_innner_ring(): if not ogrtest.have_geos() or ogr.GetDriverByName('SQLITE') is None: - return 'skip' + pytest.skip() src_ds = gdal.GetDriverByName('Memory').Create('', 0, 0, 0, gdal.GDT_Unknown) lyr = src_ds.CreateLayer('mylayer') @@ -1450,34 +1233,27 @@ def ogr_mvt_write_conflicting_innner_ring(): lyr.CreateFeature(f) out_ds = gdal.VectorTranslate('/vsimem/out.mbtiles', src_ds) - if out_ds is None: - gdaltest.post_reason('fail') - return 'fail' + assert out_ds is not None out_ds = None out_ds = ogr.Open('/vsimem/out.mbtiles') - if out_ds is None: - gdaltest.post_reason('fail') - return 'fail' + assert out_ds is not None out_lyr = out_ds.GetLayerByName('mylayer') out_f = out_lyr.GetNextFeature() if ogrtest.check_feature_geometry(out_f, 'MULTIPOLYGON (((-499898.164985052 1000102.07808325,-509987.852718695 1000102.07808325,-509987.852718695 1009886.01770375,-499898.164985052 1000102.07808325),(-502038.401777037 1001019.32242267,-509070.608379273 1008357.27713804,-509070.608379273 1001019.32242267,-502038.401777037 1001019.32242267)))') != 0: - gdaltest.post_reason('fail') out_f.DumpReadable() - return 'fail' + pytest.fail() out_ds = None gdal.Unlink('/vsimem/out.mbtiles') - return 'success' - ############################################################################### -def ogr_mvt_write_limitations_max_size_polygon(): +def test_ogr_mvt_write_limitations_max_size_polygon(): if not ogrtest.have_geos() or ogr.GetDriverByName('SQLITE') is None: - return 'skip' + pytest.skip() src_ds = gdal.GetDriverByName('Memory').Create('', 0, 0, 0, gdal.GDT_Unknown) lyr = src_ds.CreateLayer('mylayer') @@ -1490,34 +1266,27 @@ def ogr_mvt_write_limitations_max_size_polygon(): out_ds = gdal.VectorTranslate('/vsimem/out.mbtiles', src_ds, datasetCreationOptions=['MAX_SIZE=100']) - if out_ds is None: - gdaltest.post_reason('fail') - return 'fail' + assert out_ds is not None out_ds = None out_ds = ogr.Open('/vsimem/out.mbtiles') - if out_ds is None: - gdaltest.post_reason('fail') - return 'fail' + assert out_ds is not None out_lyr = out_ds.GetLayerByName('mylayer') out_f = out_lyr.GetNextFeature() if ogrtest.check_feature_geometry(out_f, 'MULTIPOLYGON (((498980.920645631 1007745.78091176,508764.860266133 1017529.72053227,508764.860266133 1007745.78091176,498980.920645631 1007745.78091176)))') != 0: - gdaltest.post_reason('fail') out_f.DumpReadable() - return 'fail' + pytest.fail() out_ds = None gdal.Unlink('/vsimem/out.mbtiles') - return 'success' - ############################################################################### -def ogr_mvt_write_limitations_max_features(): +def test_ogr_mvt_write_limitations_max_features(): if not ogrtest.have_geos() or ogr.GetDriverByName('SQLITE') is None: - return 'skip' + pytest.skip() src_ds = gdal.GetDriverByName('Memory').Create('', 0, 0, 0, gdal.GDT_Unknown) lyr = src_ds.CreateLayer('mylayer') @@ -1532,39 +1301,31 @@ def ogr_mvt_write_limitations_max_features(): out_ds = gdal.VectorTranslate('/vsimem/out.mbtiles', src_ds, format='MVT', datasetCreationOptions=['MAX_FEATURES=1']) - if out_ds is None: - gdaltest.post_reason('fail') - return 'fail' + assert out_ds is not None out_ds = None out_ds = ogr.Open('/vsimem/out.mbtiles') - if out_ds is None: - gdaltest.post_reason('fail') - return 'fail' + assert out_ds is not None out_lyr = out_ds.GetLayerByName('mylayer') out_f = out_lyr.GetNextFeature() if ogrtest.check_feature_geometry(out_f, 'POLYGON ((499898.164985053 1000102.07808325,509987.852718696 1100081.71108026,509987.852718696 1000102.07808325,499898.164985053 1000102.07808325))') != 0: - gdaltest.post_reason('fail') out_f.DumpReadable() - return 'fail' + pytest.fail() out_f = out_lyr.GetNextFeature() if out_f is not None: - gdaltest.post_reason('fail') out_f.DumpReadable() - return 'fail' + pytest.fail() out_ds = None gdal.Unlink('/vsimem/out.mbtiles') - return 'success' - ############################################################################### -def ogr_mvt_write_custom_tiling_scheme(): +def test_ogr_mvt_write_custom_tiling_scheme(): if not ogrtest.have_geos() or ogr.GetDriverByName('SQLITE') is None: - return 'skip' + pytest.skip() src_ds = gdal.GetDriverByName('Memory').Create('', 0, 0, 0, gdal.GDT_Unknown) srs = osr.SpatialReference() @@ -1577,71 +1338,54 @@ def ogr_mvt_write_custom_tiling_scheme(): out_ds = gdal.VectorTranslate('/vsimem/out', src_ds, format='MVT', datasetCreationOptions=['TILING_SCHEME=EPSG:3067,-548576,8388608,2097152']) - if out_ds is None: - gdaltest.post_reason('fail') - return 'fail' + assert out_ds is not None out_ds = None out_ds = ogr.Open('/vsimem/out/1') - if out_ds is None: - gdaltest.post_reason('fail') - return 'fail' + assert out_ds is not None out_lyr = out_ds.GetLayerByName('mylayer') - if out_lyr.GetSpatialRef().ExportToWkt().find('3067') < 0: - gdaltest.post_reason('fail') - return 'fail' + assert out_lyr.GetSpatialRef().ExportToWkt().find('3067') >= 0 out_f = out_lyr.GetNextFeature() if ogrtest.check_feature_geometry(out_f, 'MULTILINESTRING ((-40160 7944704,21024 8044800))') != 0: - gdaltest.post_reason('fail') out_f.DumpReadable() - return 'fail' + pytest.fail() out_ds = None gdal.RmdirRecursive('/vsimem/out') - return 'success' - ############################################################################### -def ogr_mvt_write_errors(): +def test_ogr_mvt_write_errors(): if not ogrtest.have_geos() or ogr.GetDriverByName('SQLITE') is None: - return 'skip' + pytest.skip() # Raster creation attempt gdal.RmdirRecursive('/vsimem/foo') with gdaltest.error_handler(): ds = gdal.GetDriverByName('MVT').Create('/vsimem/foo', 1, 1) - if ds is not None: - gdaltest.post_reason('fail') - return 'fail' + assert ds is None # should have mbtiles extension gdal.RmdirRecursive('/vsimem/foo.bar') with gdaltest.error_handler(): ds = ogr.GetDriverByName('MVT').CreateDataSource('/vsimem/foo.bar', options=['FORMAT=MBTILES']) - if ds is not None: - gdaltest.post_reason('fail') - return 'fail' + assert ds is None # Cannot create temporary database gdal.RmdirRecursive('/vsimem/foo') with gdaltest.error_handler(): ds = ogr.GetDriverByName('MVT').CreateDataSource('/vsimem/foo', options=['TEMPORARY_DB=/i/do_not/exist.db']) - if ds is not None: - gdaltest.post_reason('fail') - return 'fail' + assert ds is None # cannot create mbtiles file with gdaltest.error_handler(): ds = ogr.GetDriverByName('MVT').CreateDataSource('/i/do_not/exist.mbtiles', options=['TEMPORARY_DB=/vsimem/temp.db']) - if ds is not None: - gdaltest.post_reason('fail') - return 'fail' + assert ds is None gdal.Unlink('/vsimem/temp.db') # invalid MINZOOM @@ -1649,48 +1393,36 @@ def ogr_mvt_write_errors(): with gdaltest.error_handler(): ds = ogr.GetDriverByName('MVT').CreateDataSource('/vsimem/foo', options=['MINZOOM=-1']) - if ds is not None: - gdaltest.post_reason('fail') - return 'fail' + assert ds is None with gdaltest.error_handler(): ds = ogr.GetDriverByName('MVT').CreateDataSource('/vsimem/foo', options=['MINZOOM=30']) - if ds is not None: - gdaltest.post_reason('fail') - return 'fail' + assert ds is None # invalid MAXZOOM gdal.RmdirRecursive('/vsimem/foo') with gdaltest.error_handler(): ds = ogr.GetDriverByName('MVT').CreateDataSource('/vsimem/foo', options=['MAXZOOM=-1']) - if ds is not None: - gdaltest.post_reason('fail') - return 'fail' + assert ds is None with gdaltest.error_handler(): ds = ogr.GetDriverByName('MVT').CreateDataSource('/vsimem/foo', options=['MAXZOOM=30']) - if ds is not None: - gdaltest.post_reason('fail') - return 'fail' + assert ds is None # invalid MINZOOM vs MAXZOOM gdal.RmdirRecursive('/vsimem/foo') with gdaltest.error_handler(): ds = ogr.GetDriverByName('MVT').CreateDataSource('/vsimem/foo', options=['MINZOOM=1', 'MAXZOOM=0']) - if ds is not None: - gdaltest.post_reason('fail') - return 'fail' + assert ds is None # invalid MINZOOM for layer gdal.RmdirRecursive('/vsimem/foo') ds = ogr.GetDriverByName('MVT').CreateDataSource('/vsimem/foo') with gdaltest.error_handler(): lyr = ds.CreateLayer('foo', options=['MINZOOM=-1']) - if lyr is not None: - gdaltest.post_reason('fail') - return 'fail' + assert lyr is None # invalid CONF gdal.RmdirRecursive('/vsimem/foo') @@ -1699,26 +1431,20 @@ def ogr_mvt_write_errors(): ds = ogr.GetDriverByName('MVT').CreateDataSource('/vsimem/foo', options=['CONF=/vsimem/invalid.json']) gdal.Unlink('/vsimem/invalid.json') - if ds is not None: - gdaltest.post_reason('fail') - return 'fail' + assert ds is None # TILING_SCHEME not allowed with MBTILES with gdaltest.error_handler(): ds = ogr.GetDriverByName('MVT').CreateDataSource('/vsimem/foo.mbtiles', options=['TILING_SCHEME=EPSG:4326,-180,180,360']) - if ds is not None: - gdaltest.post_reason('fail') - return 'fail' + assert ds is None # Invalid TILING_SCHEME gdal.RmdirRecursive('/vsimem/foo') with gdaltest.error_handler(): ds = ogr.GetDriverByName('MVT').CreateDataSource('/vsimem/foo', options=['TILING_SCHEME=EPSG:4326']) - if ds is not None: - gdaltest.post_reason('fail') - return 'fail' + assert ds is None # Test failure in creating tile gdal.RmdirRecursive('tmp/tmpmvt') @@ -1730,9 +1456,7 @@ def ogr_mvt_write_errors(): lyr.CreateFeature(f) with gdaltest.error_handler(): ds = None - if gdal.GetLastErrorMsg() == '': - gdaltest.post_reason('fail') - return 'fail' + assert gdal.GetLastErrorMsg() != '' gdal.RmdirRecursive('tmp/tmpmvt') # Test failure in writing in temp db (multi-threaded) @@ -1749,9 +1473,7 @@ def ogr_mvt_write_errors(): with gdaltest.error_handler(): lyr.CreateFeature(f) ds = None - if gdal.GetLastErrorMsg() == '': - gdaltest.post_reason('fail') - return 'fail' + assert gdal.GetLastErrorMsg() != '' gdal.RmdirRecursive('tmp/tmpmvt') # Test failure in writing in temp db (single-threaded) @@ -1769,9 +1491,7 @@ def ogr_mvt_write_errors(): with gdaltest.error_handler(): lyr.CreateFeature(f) ds = None - if gdal.GetLastErrorMsg() == '': - gdaltest.post_reason('fail') - return 'fail' + assert gdal.GetLastErrorMsg() != '' gdal.RmdirRecursive('tmp/tmpmvt') # Test reprojection failure @@ -1786,16 +1506,14 @@ def ogr_mvt_write_errors(): gdal.RmdirRecursive('/vsimem/foo') - return 'success' - ############################################################################### # -def ogr_mvt_write_reuse_temp_db(): +def test_ogr_mvt_write_reuse_temp_db(): if not ogrtest.have_geos() or ogr.GetDriverByName('SQLITE') is None: - return 'skip' + pytest.skip() src_ds = gdal.GetDriverByName('Memory').Create('', 0, 0, 0, gdal.GDT_Unknown) lyr = src_ds.CreateLayer('mylayer') @@ -1807,9 +1525,7 @@ def ogr_mvt_write_reuse_temp_db(): with gdaltest.config_option('OGR_MVT_REMOVE_TEMP_FILE', 'NO'): gdal.VectorTranslate('/vsimem/out', src_ds, format='MVT') - if gdal.VSIStatL('/vsimem/out.temp.db') is None: - gdaltest.post_reason('fail') - return 'fail' + assert gdal.VSIStatL('/vsimem/out.temp.db') is not None gdal.RmdirRecursive('/vsimem/out') @@ -1817,74 +1533,15 @@ def ogr_mvt_write_reuse_temp_db(): gdal.VectorTranslate('/vsimem/out', src_ds, format='MVT') out_ds = ogr.Open('/vsimem/out/5') - if out_ds is None: - gdaltest.post_reason('fail') - return 'fail' + assert out_ds is not None out_lyr = out_ds.GetLayerByName('mylayer') out_f = out_lyr.GetNextFeature() - if out_f is None: - gdaltest.post_reason('fail') - return 'fail' + assert out_f is not None out_ds = None gdal.RmdirRecursive('/vsimem/out') gdal.Unlink('/vsimem/out.temp.db') - return 'success' - ############################################################################### # - -gdaltest_list = [ - ogr_mvt_datatypes, - ogr_mvt_datatype_promotion, - ogr_mvt_limit_cases, - ogr_mvt_with_extension_fields, - ogr_mvt_mixed, - ogr_mvt_linestring, - ogr_mvt_multilinestring, - ogr_mvt_polygon, - ogr_mvt_point_polygon, - ogr_mvt_point_polygon_clip, - ogr_mvt_tileset_without_readdir, - ogr_mvt_tileset_without_metadata_file, - ogr_mvt_tileset_json_field, - ogr_mvt_tileset_tilegl, - ogr_mvt_open_variants, - ogr_mvt_xyz_options, - ogr_mvt_test_ogrsf_pbf, - ogr_mvt_test_ogrsf_directory, - ogr_mvt_mbtiles, - ogr_mvt_mbtiles_json_field, - ogr_mvt_mbtiles_json_field_auto, - ogr_mvt_mbtiles_open_vector_in_raster_mode, - ogr_mvt_mbtiles_test_ogrsf, - ogr_mvt_x_y_z_filename_scheme, - ogr_mvt_polygon_larger_than_header, - ogr_mvt_errors, - ogr_mvt_http_start, - ogr_mvt_http, - ogr_mvt_http_stop, - ogr_mvt_write_one_layer, - ogr_mvt_write_conf, - ogr_mvt_write_mbtiles, - ogr_mvt_write_polygon_repaired, - ogr_mvt_write_conflicting_innner_ring, - ogr_mvt_write_limitations_max_size, - ogr_mvt_write_limitations_max_size_polygon, - ogr_mvt_write_limitations_max_features, - ogr_mvt_write_custom_tiling_scheme, - ogr_mvt_write_errors, - ogr_mvt_write_reuse_temp_db, -] - -# gdaltest_list = [ ogr_mvt_http_start, ogr_mvt_http, ogr_mvt_http_stop ] - -if __name__ == '__main__': - - gdaltest.setup_run('ogr_mvt') - - gdaltest.run_tests(gdaltest_list) - - sys.exit(gdaltest.summarize()) diff --git a/autotest/ogr/ogr_mysql.py b/autotest/ogr/ogr_mysql.py index e3b95c700ac3..c3f323d7c342 100755 --- a/autotest/ogr/ogr_mysql.py +++ b/autotest/ogr/ogr_mysql.py @@ -27,15 +27,14 @@ # Boston, MA 02111-1307, USA. ############################################################################### -import sys -sys.path.append('../pymod') import gdaltest import ogrtest from osgeo import ogr from osgeo import gdal from osgeo import osr +import pytest # E. Rouault : this is almost a copy & paste from ogr_pg.py @@ -51,14 +50,14 @@ # Open Database. -def ogr_mysql_1(): +def test_ogr_mysql_1(): gdaltest.mysql_ds = None try: ogr.GetDriverByName('MySQL') except: - return 'skip' + pytest.skip() val = gdal.GetConfigOption('OGR_MYSQL_CONNECTION_STRING', None) if val is not None: @@ -68,7 +67,7 @@ def ogr_mysql_1(): gdaltest.mysql_ds = ogr.Open(gdaltest.mysql_connection_string, update=1) if gdaltest.mysql_ds is None: - return 'skip' + pytest.skip() sql_lyr = gdaltest.mysql_ds.ExecuteSQL("SELECT VERSION()") f = sql_lyr.GetNextFeature() @@ -76,16 +75,14 @@ def ogr_mysql_1(): gdaltest.is_mysql_8_or_later = int(f.GetField(0).split('.')[0]) >= 8 and f.GetField(0).find('MariaDB') < 0 gdaltest.mysql_ds.ReleaseResultSet(sql_lyr) - return 'success' - ############################################################################### # Create table from data/poly.shp -def ogr_mysql_2(): +def test_ogr_mysql_2(): if gdaltest.mysql_ds is None: - return 'skip' + pytest.skip() shp_ds = ogr.Open('data/poly.shp') gdaltest.shp_ds = shp_ds @@ -125,31 +122,48 @@ def ogr_mysql_2(): dst_feat.Destroy() - if gdaltest.mysql_lyr.GetFeatureCount() != shp_lyr.GetFeatureCount(): - gdaltest.post_reason('not matching feature count') - return 'fail' + assert gdaltest.mysql_lyr.GetFeatureCount() == shp_lyr.GetFeatureCount(), \ + 'not matching feature count' + + assert gdaltest.mysql_lyr.GetSpatialRef().IsSame(shp_lyr.GetSpatialRef()), \ + 'not matching spatial ref' + +############################################################################### +# Test reading a layer extent + + +def test_ogr_mysql_19(): + + if gdaltest.mysql_ds is None: + pytest.skip() - if not gdaltest.mysql_lyr.GetSpatialRef().IsSame(shp_lyr.GetSpatialRef()): - gdaltest.post_reason('not matching spatial ref') - return 'fail' + layer = gdaltest.mysql_ds.GetLayerByName('tpoly') + if layer is None: + pytest.fail('did not get tpoly layer') - return 'success' + extent = layer.GetExtent() + expect = (478315.53125, 481645.3125, 4762880.5, 4765610.5) + + minx = abs(extent[0] - expect[0]) + maxx = abs(extent[1] - expect[1]) + miny = abs(extent[2] - expect[2]) + maxy = abs(extent[3] - expect[3]) + + if max(minx, maxx, miny, maxy) > 0.0001: + print(extent) + pytest.fail('Extents do not match') ############################################################################### # Verify that stuff we just wrote is still OK. -def ogr_mysql_3(): +def test_ogr_mysql_3(): if gdaltest.mysql_ds is None: - return 'skip' + pytest.skip() - if gdaltest.mysql_lyr.GetGeometryColumn() != 'SHAPE': - gdaltest.post_reason('fail') - return 'fail' + assert gdaltest.mysql_lyr.GetGeometryColumn() == 'SHAPE' - if gdaltest.mysql_lyr.GetFeatureCount() != 10: - gdaltest.post_reason('GetFeatureCount() returned %d instead of 10' % gdaltest.mysql_lyr.GetFeatureCount()) - return 'fail' + assert gdaltest.mysql_lyr.GetFeatureCount() == 10 expect = [168, 169, 166, 158, 165] @@ -157,9 +171,7 @@ def ogr_mysql_3(): tr = ogrtest.check_features_against_list(gdaltest.mysql_lyr, 'eas_id', expect) - if gdaltest.mysql_lyr.GetFeatureCount() != 5: - gdaltest.post_reason('GetFeatureCount() returned %d instead of 5' % gdaltest.mysql_lyr.GetFeatureCount()) - return 'fail' + assert gdaltest.mysql_lyr.GetFeatureCount() == 5 gdaltest.mysql_lyr.SetAttributeFilter(None) @@ -167,17 +179,13 @@ def ogr_mysql_3(): orig_feat = gdaltest.poly_feat[i] read_feat = gdaltest.mysql_lyr.GetNextFeature() - if ogrtest.check_feature_geometry(read_feat, orig_feat.GetGeometryRef(), - max_error=0.001) != 0: - return 'fail' + assert (ogrtest.check_feature_geometry(read_feat, orig_feat.GetGeometryRef(), + max_error=0.001) == 0) for fld in range(3): - if orig_feat.GetField(fld) != read_feat.GetField(fld): - gdaltest.post_reason('Attribute %d does not match' % fld) - return 'fail' - if read_feat.GetField('INT64') != 1234567890123: - gdaltest.post_reason('failure') - return 'fail' + assert orig_feat.GetField(fld) == read_feat.GetField(fld), \ + ('Attribute %d does not match' % fld) + assert read_feat.GetField('INT64') == 1234567890123 read_feat.Destroy() orig_feat.Destroy() @@ -185,17 +193,17 @@ def ogr_mysql_3(): gdaltest.poly_feat = None gdaltest.shp_ds.Destroy() - return 'success' if tr else 'fail' + assert tr ############################################################################### # Write more features with a bunch of different geometries, and verify the # geometries are still OK. -def ogr_mysql_4(): +def test_ogr_mysql_4(): if gdaltest.mysql_ds is None: - return 'skip' + pytest.skip() # E. Rouault : the mySQL driver doesn't seem to like adding new features and # iterating over a query at the same time. @@ -243,45 +251,41 @@ def ogr_mysql_4(): print('(before):', geom.ExportToWkt()) geom.CloseRings() print('(after) :', geom.ExportToWkt()) - if ogrtest.check_feature_geometry(feat_read, geom) != 0: - return 'fail' + assert ogrtest.check_feature_geometry(feat_read, geom) == 0 feat_read.Destroy() - return 'success' - + ############################################################################### # Test ExecuteSQL() results layers without geometry. -def ogr_mysql_5(): +def test_ogr_mysql_5(): if gdaltest.mysql_ds is None: - return 'skip' + pytest.skip() # E. Rouault : unlike PostgreSQL driver : None is sorted in last position expect = [179, 173, 172, 171, 170, 169, 168, 166, 165, 158, None] sql_lyr = gdaltest.mysql_ds.ExecuteSQL('select distinct eas_id from tpoly order by eas_id desc') - if sql_lyr.GetFeatureCount() != 11: - gdaltest.post_reason('GetFeatureCount() returned %d instead of 11' % sql_lyr.GetFeatureCount()) - return 'fail' + assert sql_lyr.GetFeatureCount() == 11 tr = ogrtest.check_features_against_list(sql_lyr, 'eas_id', expect) gdaltest.mysql_ds.ReleaseResultSet(sql_lyr) - return 'success' if tr else 'fail' + assert tr ############################################################################### # Test ExecuteSQL() results layers with geometry. -def ogr_mysql_6(): +def test_ogr_mysql_6(): if gdaltest.mysql_ds is None: - return 'skip' + pytest.skip() sql_lyr = gdaltest.mysql_ds.ExecuteSQL("select * from tpoly where prfedea = '2'") @@ -299,26 +303,22 @@ def ogr_mysql_6(): sql_lyr.SetSpatialFilter(geom) geom.Destroy() - if sql_lyr.GetFeatureCount() != 0: - gdaltest.post_reason('GetFeatureCount() returned %d instead of 0' % sql_lyr.GetFeatureCount()) - return 'fail' + assert sql_lyr.GetFeatureCount() == 0 - if sql_lyr.GetNextFeature() is not None: - gdaltest.post_reason('GetNextFeature() did not return None') - return 'fail' + assert sql_lyr.GetNextFeature() is None, 'GetNextFeature() did not return None' gdaltest.mysql_ds.ReleaseResultSet(sql_lyr) - return 'success' if tr else 'fail' + assert tr ############################################################################### # Test spatial filtering. -def ogr_mysql_7(): +def test_ogr_mysql_7(): if gdaltest.mysql_ds is None: - return 'skip' + pytest.skip() gdaltest.mysql_lyr.SetAttributeFilter(None) @@ -327,24 +327,20 @@ def ogr_mysql_7(): gdaltest.mysql_lyr.SetSpatialFilter(geom) geom.Destroy() - if gdaltest.mysql_lyr.GetFeatureCount() != 1: - gdaltest.post_reason('GetFeatureCount() returned %d instead of 1' % gdaltest.mysql_lyr.GetFeatureCount()) - return 'fail' + assert gdaltest.mysql_lyr.GetFeatureCount() == 1 tr = ogrtest.check_features_against_list(gdaltest.mysql_lyr, 'eas_id', [158]) gdaltest.mysql_lyr.SetAttributeFilter('eas_id = 158') - if gdaltest.mysql_lyr.GetFeatureCount() != 1: - gdaltest.post_reason('GetFeatureCount() returned %d instead of 1' % gdaltest.mysql_lyr.GetFeatureCount()) - return 'fail' + assert gdaltest.mysql_lyr.GetFeatureCount() == 1 gdaltest.mysql_lyr.SetAttributeFilter(None) gdaltest.mysql_lyr.SetSpatialFilter(None) - return 'success' if tr else 'fail' + assert tr ############################################################################### # Write a feature with too long a text value for a fixed length text field. @@ -355,10 +351,10 @@ def ogr_mysql_7(): # No geometry in this test. -def ogr_mysql_8(): +def test_ogr_mysql_8(): if gdaltest.mysql_ds is None: - return 'skip' + pytest.skip() dst_feat = ogr.Feature(feature_def=gdaltest.mysql_lyr.GetLayerDefn()) @@ -372,27 +368,22 @@ def ogr_mysql_8(): gdaltest.mysql_lyr.SetAttributeFilter("PRFEDEA = 'CrazyKey'") feat_read = gdaltest.mysql_lyr.GetNextFeature() - if feat_read is None: - gdaltest.post_reason('creating crazy feature failed!') - return 'fail' + assert feat_read is not None, 'creating crazy feature failed!' - if feat_read.GetField('shortname') != 'Crazy"\'L': - gdaltest.post_reason('Vvalue not properly escaped or truncated:' + + assert feat_read.GetField('shortname') == 'Crazy"\'L', \ + ('Vvalue not properly escaped or truncated:' + feat_read.GetField('shortname')) - return 'fail' feat_read.Destroy() - return 'success' - ############################################################################### # Verify inplace update of a feature with SetFeature(). -def ogr_mysql_9(): +def test_ogr_mysql_9(): if gdaltest.mysql_ds is None: - return 'skip' + pytest.skip() gdaltest.mysql_lyr.SetAttributeFilter("PRFEDEA = 'CrazyKey'") feat = gdaltest.mysql_lyr.GetNextFeature() @@ -406,53 +397,43 @@ def ogr_mysql_9(): if gdaltest.mysql_lyr.SetFeature(feat) != 0: feat.Destroy() - gdaltest.post_reason('SetFeature() method failed.') - return 'fail' + pytest.fail('SetFeature() method failed.') fid = feat.GetFID() feat.Destroy() feat = gdaltest.mysql_lyr.GetFeature(fid) - if feat is None: - gdaltest.post_reason('GetFeature(%d) failed.' % fid) - return 'fail' + assert feat is not None, ('GetFeature(%d) failed.' % fid) shortname = feat.GetField('SHORTNAME') - if shortname[:5] != 'Reset': - gdaltest.post_reason('SetFeature() did not update SHORTNAME, got %s.' + assert shortname[:5] == 'Reset', ('SetFeature() did not update SHORTNAME, got %s.' % shortname) - return 'fail' if ogrtest.check_feature_geometry(feat, 'POINT(5 6)') != 0: print(feat.GetGeometryRef()) - gdaltest.post_reason('Geometry update failed') - return 'fail' + pytest.fail('Geometry update failed') # Test updating non-existing feature feat.SetFID(-10) if gdaltest.mysql_lyr.SetFeature(feat) != ogr.OGRERR_NON_EXISTING_FEATURE: feat.Destroy() - gdaltest.post_reason('Expected failure of SetFeature().') - return 'fail' + pytest.fail('Expected failure of SetFeature().') # Test deleting non-existing feature if gdaltest.mysql_lyr.DeleteFeature(-10) != ogr.OGRERR_NON_EXISTING_FEATURE: feat.Destroy() - gdaltest.post_reason('Expected failure of DeleteFeature().') - return 'fail' + pytest.fail('Expected failure of DeleteFeature().') feat.Destroy() - return 'success' - ############################################################################### # Verify that DeleteFeature() works properly. -def ogr_mysql_10(): +def test_ogr_mysql_10(): if gdaltest.mysql_ds is None: - return 'skip' + pytest.skip() gdaltest.mysql_lyr.SetAttributeFilter("PRFEDEA = 'CrazyKey'") feat = gdaltest.mysql_lyr.GetNextFeature() @@ -461,29 +442,26 @@ def ogr_mysql_10(): fid = feat.GetFID() feat.Destroy() - if gdaltest.mysql_lyr.DeleteFeature(fid) != 0: - gdaltest.post_reason('DeleteFeature() method failed.') - return 'fail' + assert gdaltest.mysql_lyr.DeleteFeature(fid) == 0, 'DeleteFeature() method failed.' gdaltest.mysql_lyr.SetAttributeFilter("PRFEDEA = 'CrazyKey'") feat = gdaltest.mysql_lyr.GetNextFeature() gdaltest.mysql_lyr.SetAttributeFilter(None) if feat is None: - return 'success' + return feat.Destroy() - gdaltest.post_reason('DeleteFeature() seems to have had no effect.') - return 'fail' + pytest.fail('DeleteFeature() seems to have had no effect.') ############################################################################### # Test very large query. -def ogr_mysql_15(): +def test_ogr_mysql_15(): if gdaltest.mysql_ds is None: - return 'skip' + pytest.skip() expect = [169] @@ -497,16 +475,16 @@ def ogr_mysql_15(): 'eas_id', expect) gdaltest.mysql_lyr.SetAttributeFilter(None) - return 'success' if tr else 'fail' + assert tr ############################################################################### # Test very large statement. -def ogr_mysql_16(): +def test_ogr_mysql_16(): if gdaltest.mysql_ds is None: - return 'skip' + pytest.skip() expect = [169] @@ -523,28 +501,23 @@ def ogr_mysql_16(): gdaltest.mysql_ds.ReleaseResultSet(lyr) - return 'success' if tr else 'fail' + assert tr ############################################################################### # Test requesting a non-existent table by name (bug 1480). -def ogr_mysql_17(): +def test_ogr_mysql_17(): if gdaltest.mysql_ds is None: - return 'skip' + pytest.skip() count = gdaltest.mysql_ds.GetLayerCount() layer = gdaltest.mysql_ds.GetLayerByName('JunkTableName') - if layer is not None: - gdaltest.post_reason('got layer for non-existent table!') - return 'fail' - - if count != gdaltest.mysql_ds.GetLayerCount(): - gdaltest.post_reason('layer count changed unexpectedly.') - return 'fail' + assert layer is None, 'got layer for non-existent table!' - return 'success' + assert count == gdaltest.mysql_ds.GetLayerCount(), \ + 'layer count changed unexpectedly.' ############################################################################### # Test getting a layer by name that was not previously a layer. @@ -553,57 +526,22 @@ def ogr_mysql_17(): def ogr_mysql_18(): if gdaltest.mysql_ds is None: - return 'skip' + pytest.skip() count = gdaltest.mysql_ds.GetLayerCount() layer = gdaltest.mysql_ds.GetLayerByName('geometry_columns') - if layer is None: - gdaltest.post_reason('did not get geometry_columns layer') - return 'fail' - - if count + 1 != gdaltest.mysql_ds.GetLayerCount(): - gdaltest.post_reason('layer count unexpectedly unchanged.') - return 'fail' + assert layer is not None, 'did not get geometry_columns layer' - return 'success' + assert count + 1 == gdaltest.mysql_ds.GetLayerCount(), \ + 'layer count unexpectedly unchanged.' ############################################################################### -# Test reading a layer extent -def ogr_mysql_19(): +def test_ogr_mysql_20(): if gdaltest.mysql_ds is None: - return 'skip' - - layer = gdaltest.mysql_ds.GetLayerByName('tpoly') - if layer is None: - gdaltest.post_reason('did not get tpoly layer') - return 'fail' - - extent = layer.GetExtent() - expect = (478315.53125, 481645.3125, 4762880.5, 4765610.5) - - minx = abs(extent[0] - expect[0]) - maxx = abs(extent[1] - expect[1]) - miny = abs(extent[2] - expect[2]) - maxy = abs(extent[3] - expect[3]) - - if max(minx, maxx, miny, maxy) > 0.0001: - gdaltest.post_reason('Extents do not match') - print(extent) - return 'fail' - - return 'success' - -############################################################################### -# Test using reserved keywords as column names and table names - - -def ogr_mysql_20(): - - if gdaltest.mysql_ds is None: - return 'skip' + pytest.skip() layer = gdaltest.mysql_ds.CreateLayer('select', options=['ENGINE=MyISAM']) ogrtest.quick_create_layer_def(layer, @@ -622,17 +560,17 @@ def ogr_mysql_20(): layer.ResetReading() feat = layer.GetNextFeature() if feat.desc == 'desc' and feat.select == 'select': - return 'success' - return 'fail' + return + pytest.fail() ############################################################################### # Test inserting NULL geometries into a table with a spatial index -> must FAIL -def ogr_mysql_21(): +def test_ogr_mysql_21(): if gdaltest.mysql_ds is None: - return 'skip' + pytest.skip() layer = gdaltest.mysql_ds.CreateLayer('tablewithspatialindex', geom_type=ogr.wkbPoint, options=['ENGINE=MyISAM']) ogrtest.quick_create_layer_def(layer, [('name', ogr.OFTString)]) @@ -648,19 +586,16 @@ def ogr_mysql_21(): layer.ResetReading() feat = layer.GetNextFeature() - if feat is not None: - return 'fail' - - return 'success' + assert feat is None ############################################################################### # Test inserting NULL geometries into a table without a spatial index -def ogr_mysql_22(): +def test_ogr_mysql_22(): if gdaltest.mysql_ds is None: - return 'skip' + pytest.skip() layer = gdaltest.mysql_ds.CreateLayer('tablewithoutspatialindex', geom_type=ogr.wkbPoint, options=['SPATIAL_INDEX=NO', 'ENGINE=MyISAM']) @@ -674,19 +609,16 @@ def ogr_mysql_22(): layer.ResetReading() feat = layer.GetNextFeature() - if feat is None: - return 'fail' - - return 'success' + assert feat is not None ############################################################################### # Check for right precision -def ogr_mysql_23(): +def test_ogr_mysql_23(): if gdaltest.mysql_ds is None: - return 'skip' + pytest.skip() fields = ('zero', 'widthonly', 'onedecimal', 'twentynine', 'thirtyone') values = (1, 2, 1.1, 0.12345678901234567890123456789, 0.1234567890123456789012345678901) @@ -701,114 +633,85 @@ def ogr_mysql_23(): gdaltest.mysql_lyr = gdaltest.mysql_ds.ExecuteSQL("SELECT ROUND(1.1,0) AS zero, ROUND(2.0, 0) AS widthonly, ROUND(1.1,1) AS onedecimal, ROUND(0.12345678901234567890123456789,29) AS twentynine, GeomFromText(CONVERT('POINT(1.0 2.0)',CHAR)) as the_geom;") feat = gdaltest.mysql_lyr.GetNextFeature() - if feat is None: - return 'fail' + assert feat is not None ###################################################### # Check the values and the precisions for i in range(4): - if feat.GetFieldIndex(fields[i]) < 0: - print('field not found') - return 'fail' - if feat.GetField(feat.GetFieldIndex(fields[i])) != values[i]: - print('value not right') -# print feat.GetField( feat.GetFieldIndex(fields[i]) ) - return 'fail' - if feat.GetFieldDefnRef(feat.GetFieldIndex(fields[i])).GetPrecision() != precision[i]: - print('precision not right') -# print feat.GetFieldDefnRef( feat.GetFieldIndex(fields[i]) ).GetPrecision() - return 'fail' + assert feat.GetFieldIndex(fields[i]) >= 0, 'field not found' + assert feat.GetField(feat.GetFieldIndex(fields[i])) == values[i], \ + 'value not right' + assert feat.GetFieldDefnRef(feat.GetFieldIndex(fields[i])).GetPrecision() == precision[i], \ + 'precision not right' gdaltest.mysql_ds.ReleaseResultSet(gdaltest.mysql_lyr) gdaltest.mysql_lyr = None - return 'success' - ############################################################################### # Run test_ogrsf -def ogr_mysql_24(): +def test_ogr_mysql_24(): if gdaltest.mysql_ds is None: - return 'skip' + pytest.skip() import test_cli_utilities if test_cli_utilities.get_test_ogrsf_path() is None: - return 'skip' + pytest.skip() ret = gdaltest.runexternal(test_cli_utilities.get_test_ogrsf_path() + " '" + gdaltest.mysql_connection_string + "' tpoly") - if ret.find('INFO') == -1 or ret.find('ERROR') != -1: - print(ret) - return 'fail' - - return 'success' + assert ret.find('INFO') != -1 and ret.find('ERROR') == -1 ############################################################################### # Test 64 bit FID -def ogr_mysql_72(): +def test_ogr_mysql_72(): if gdaltest.mysql_ds is None: - return 'skip' + pytest.skip() # Regular layer with 32 bit IDs lyr = gdaltest.mysql_ds.CreateLayer('ogr_mysql_72', geom_type=ogr.wkbNone) - if lyr.GetMetadataItem(ogr.OLMD_FID64) is not None: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.GetMetadataItem(ogr.OLMD_FID64) is None lyr.CreateField(ogr.FieldDefn('foo')) f = ogr.Feature(lyr.GetLayerDefn()) f.SetFID(123456789012345) f.SetField(0, 'bar') - if lyr.CreateFeature(f) != 0: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.CreateFeature(f) == 0 f = lyr.GetFeature(123456789012345) - if f is None: - gdaltest.post_reason('fail') - return 'fail' + assert f is not None lyr = gdaltest.mysql_ds.CreateLayer('ogr_mysql_72', geom_type=ogr.wkbNone, options=['FID64=YES', 'OVERWRITE=YES']) - if lyr.GetMetadataItem(ogr.OLMD_FID64) is None: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.GetMetadataItem(ogr.OLMD_FID64) is not None lyr.CreateField(ogr.FieldDefn('foo')) f = ogr.Feature(lyr.GetLayerDefn()) f.SetFID(123456789012345) f.SetField(0, 'bar') - if lyr.CreateFeature(f) != 0: - gdaltest.post_reason('fail') - return 'fail' - if lyr.SetFeature(f) != 0: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.CreateFeature(f) == 0 + assert lyr.SetFeature(f) == 0 gdaltest.mysql_ds = None # Test with normal protocol gdaltest.mysql_ds = ogr.Open(gdaltest.mysql_connection_string, update=1) lyr = gdaltest.mysql_ds.GetLayerByName('ogr_mysql_72') - if lyr.GetMetadataItem(ogr.OLMD_FID64) is None: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.GetMetadataItem(ogr.OLMD_FID64) is not None f = lyr.GetNextFeature() if f.GetFID() != 123456789012345: - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' - - return 'success' + pytest.fail() + ############################################################################### # Test nullable -def ogr_mysql_25(): +def test_ogr_mysql_25(): if gdaltest.mysql_ds is None: - return 'skip' + pytest.skip() lyr = gdaltest.mysql_ds.CreateLayer('ogr_mysql_25', geom_type=ogr.wkbPoint, options=['ENGINE=MyISAM']) field_defn = ogr.FieldDefn('field_not_nullable', ogr.OFTString) @@ -829,9 +732,7 @@ def ogr_mysql_25(): gdal.PushErrorHandler() ret = lyr.CreateFeature(f) gdal.PopErrorHandler() - if ret == 0: - gdaltest.post_reason('fail') - return 'fail' + assert ret != 0 f = None # Error case: missing non-nullable field @@ -842,34 +743,24 @@ def ogr_mysql_25(): gdal.PushErrorHandler() ret = lyr.CreateFeature(f) gdal.PopErrorHandler() - if ret == 0: - gdaltest.post_reason('fail') - return 'fail' + assert ret != 0 f = None gdaltest.mysql_ds = None gdaltest.mysql_ds = ogr.Open(gdaltest.mysql_connection_string, update=1) lyr = gdaltest.mysql_ds.GetLayerByName('ogr_mysql_25') - if lyr.GetLayerDefn().GetFieldDefn(lyr.GetLayerDefn().GetFieldIndex('field_not_nullable')).IsNullable() != 0: - gdaltest.post_reason('fail') - return 'fail' - if lyr.GetLayerDefn().GetFieldDefn(lyr.GetLayerDefn().GetFieldIndex('field_nullable')).IsNullable() != 1: - gdaltest.post_reason('fail') - return 'fail' - if lyr.GetLayerDefn().GetGeomFieldDefn(0).IsNullable() != 0: - gdaltest.post_reason('fail') - return 'fail' - - return 'success' + assert lyr.GetLayerDefn().GetFieldDefn(lyr.GetLayerDefn().GetFieldIndex('field_not_nullable')).IsNullable() == 0 + assert lyr.GetLayerDefn().GetFieldDefn(lyr.GetLayerDefn().GetFieldIndex('field_nullable')).IsNullable() == 1 + assert lyr.GetLayerDefn().GetGeomFieldDefn(0).IsNullable() == 0 ############################################################################### # Test default values -def ogr_mysql_26(): +def test_ogr_mysql_26(): if gdaltest.mysql_ds is None: - return 'skip' + pytest.skip() lyr = gdaltest.mysql_ds.CreateLayer('ogr_mysql_26', geom_type=ogr.wkbPoint, options=['ENGINE=MyISAM']) @@ -917,26 +808,12 @@ def ogr_mysql_26(): gdaltest.mysql_ds = None gdaltest.mysql_ds = ogr.Open(gdaltest.mysql_connection_string, update=1) lyr = gdaltest.mysql_ds.GetLayerByName('ogr_mysql_26') - if lyr.GetLayerDefn().GetFieldDefn(lyr.GetLayerDefn().GetFieldIndex('field_string')).GetDefault() != "'a''b'": - gdaltest.post_reason('fail') - return 'fail' - if lyr.GetLayerDefn().GetFieldDefn(lyr.GetLayerDefn().GetFieldIndex('field_int')).GetDefault() != '123': - gdaltest.post_reason('fail') - return 'fail' - if lyr.GetLayerDefn().GetFieldDefn(lyr.GetLayerDefn().GetFieldIndex('field_real')).GetDefault() != '1.23': - gdaltest.post_reason('fail') - return 'fail' - if lyr.GetLayerDefn().GetFieldDefn(lyr.GetLayerDefn().GetFieldIndex('field_nodefault')).GetDefault() is not None: - gdaltest.post_reason('fail') - return 'fail' - if lyr.GetLayerDefn().GetFieldDefn(lyr.GetLayerDefn().GetFieldIndex('field_datetime')).GetDefault() != 'CURRENT_TIMESTAMP': - gdaltest.post_reason('fail') - print(lyr.GetLayerDefn().GetFieldDefn(lyr.GetLayerDefn().GetFieldIndex('field_datetime')).GetDefault()) - return 'fail' - if lyr.GetLayerDefn().GetFieldDefn(lyr.GetLayerDefn().GetFieldIndex('field_datetime2')).GetDefault() != "'2015/06/30 12:34:56'": - gdaltest.post_reason('fail') - print(lyr.GetLayerDefn().GetFieldDefn(lyr.GetLayerDefn().GetFieldIndex('field_datetime2')).GetDefault()) - return 'fail' + assert lyr.GetLayerDefn().GetFieldDefn(lyr.GetLayerDefn().GetFieldIndex('field_string')).GetDefault() == "'a''b'" + assert lyr.GetLayerDefn().GetFieldDefn(lyr.GetLayerDefn().GetFieldIndex('field_int')).GetDefault() == '123' + assert lyr.GetLayerDefn().GetFieldDefn(lyr.GetLayerDefn().GetFieldIndex('field_real')).GetDefault() == '1.23' + assert lyr.GetLayerDefn().GetFieldDefn(lyr.GetLayerDefn().GetFieldIndex('field_nodefault')).GetDefault() is None + assert lyr.GetLayerDefn().GetFieldDefn(lyr.GetLayerDefn().GetFieldIndex('field_datetime')).GetDefault() == 'CURRENT_TIMESTAMP' + assert lyr.GetLayerDefn().GetFieldDefn(lyr.GetLayerDefn().GetFieldIndex('field_datetime2')).GetDefault() == "'2015/06/30 12:34:56'" # if lyr.GetLayerDefn().GetFieldDefn(lyr.GetLayerDefn().GetFieldIndex('field_date')).GetDefault() != "CURRENT_DATE": # gdaltest.post_reason('fail') # print(lyr.GetLayerDefn().GetFieldDefn(lyr.GetLayerDefn().GetFieldIndex('field_date')).GetDefault()) @@ -950,22 +827,19 @@ def ogr_mysql_26(): not f.IsFieldNull('field_string_null') or \ not f.IsFieldNull('field_nodefault') or not f.IsFieldSet('field_datetime') or \ f.GetField('field_datetime2') != '2015/06/30 12:34:56': - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' + pytest.fail() gdal.Unlink('/vsimem/ogr_gpkg_24.gpkg') - return 'success' - ############################################################################### # -def ogr_mysql_longlat(): +def test_ogr_mysql_longlat(): if gdaltest.mysql_ds is None: - return 'skip' + pytest.skip() srs = osr.SpatialReference() srs.SetFromUserInput('WGS84') @@ -980,8 +854,7 @@ def ogr_mysql_longlat(): lyr.SetSpatialFilterRect(149.5, 1.5, 150.5, 2.5) f = lyr.GetNextFeature() - if ogrtest.check_feature_geometry(f, geom) != 0: - return 'fail' + assert ogrtest.check_feature_geometry(f, geom) == 0 extent = lyr.GetExtent() expect = (150.0, 150.0, 2.0, 2.0) @@ -992,21 +865,19 @@ def ogr_mysql_longlat(): maxy = abs(extent[3] - expect[3]) if max(minx, maxx, miny, maxy) > 0.0001: - gdaltest.post_reason('Extents do not match') print(extent) - return 'fail' + pytest.fail('Extents do not match') - return 'success' - + ############################################################################### # -def ogr_mysql_cleanup(): +def test_ogr_mysql_cleanup(): if gdaltest.mysql_ds is None: - return 'skip' + pytest.skip() gdaltest.mysql_ds.ExecuteSQL('DROP TABLE tpoly') gdaltest.mysql_ds.ExecuteSQL('DROP TABLE `select`') @@ -1024,44 +895,5 @@ def ogr_mysql_cleanup(): gdaltest.mysql_ds.Destroy() gdaltest.mysql_ds = None - return 'success' - - -gdaltest_list = [ - ogr_mysql_1, - # ogr_mysql_cleanup, - ogr_mysql_2, - ogr_mysql_19, - ogr_mysql_3, - ogr_mysql_4, - ogr_mysql_5, - ogr_mysql_6, - ogr_mysql_7, - ogr_mysql_8, - ogr_mysql_9, - ogr_mysql_10, - # ogr_mysql_11 to _14 are PG only features - ogr_mysql_15, - ogr_mysql_16, - ogr_mysql_17, - # Fails but it is probably OK - # ogr_mysql_18, - ogr_mysql_20, - ogr_mysql_21, - ogr_mysql_22, - ogr_mysql_23, - ogr_mysql_24, - ogr_mysql_72, - ogr_mysql_25, - ogr_mysql_26, - ogr_mysql_longlat, - ogr_mysql_cleanup -] - -if __name__ == '__main__': - - gdaltest.setup_run('ogr_mysql') - - gdaltest.run_tests(gdaltest_list) - - sys.exit(gdaltest.summarize()) + + diff --git a/autotest/ogr/ogr_nas.py b/autotest/ogr/ogr_nas.py index 4ac7070a8e75..5940c3d064a4 100755 --- a/autotest/ogr/ogr_nas.py +++ b/autotest/ogr/ogr_nas.py @@ -29,13 +29,12 @@ ############################################################################### import os -import sys -sys.path.append('../pymod') import gdaltest import ogrtest from osgeo import ogr +import pytest # Other test data : # http://www.lv-bw.de/alkis.info/nas-bsp.html @@ -47,14 +46,14 @@ # -def ogr_nas_1(): +def test_ogr_nas_1(): drv = ogr.GetDriverByName('NAS') if drv is None: - return 'skip' + pytest.skip() if not gdaltest.download_file('http://www.geodatenzentrum.de/gdz1/abgabe/testdaten/vektor/nas_testdaten_peine.zip', 'nas_testdaten_peine.zip'): - return 'skip' + pytest.skip() try: os.stat('tmp/cache/BKG_NAS_Peine.xml') @@ -64,9 +63,9 @@ def ogr_nas_1(): try: os.stat('tmp/cache/BKG_NAS_Peine.xml') except OSError: - return 'skip' + pytest.skip() except OSError: - return 'skip' + pytest.skip() try: os.remove('tmp/cache/BKG_NAS_Peine.gfs') @@ -74,13 +73,9 @@ def ogr_nas_1(): pass ds = ogr.Open('tmp/cache/BKG_NAS_Peine.xml') - if ds is None: - gdaltest.post_reason('could not open dataset') - return 'fail' + assert ds is not None, 'could not open dataset' - if ds.GetLayerCount() != 41: - gdaltest.post_reason('did not get expected layer count') - return 'fail' + assert ds.GetLayerCount() == 41, 'did not get expected layer count' lyr = ds.GetLayerByName('AX_Wohnplatz') feat = lyr.GetNextFeature() @@ -88,7 +83,7 @@ def ogr_nas_1(): if feat.GetField('name') != 'Ziegelei' or geom.ExportToWkt() != 'POINT (3575300 5805100)': feat.DumpReadable() - return 'fail' + pytest.fail() relation_lyr = ds.GetLayerByName('ALKIS_beziehungen') feat = relation_lyr.GetNextFeature() @@ -96,25 +91,23 @@ def ogr_nas_1(): feat.GetField('beziehungsart') != 'istTeilVon' or \ feat.GetField('beziehung_zu') != 'DENIBKG1000000T6': feat.DumpReadable() - return 'fail' + pytest.fail() ds = None - return 'success' - ############################################################################### # Test reading a sample NAS file from PostNAS # -def ogr_nas_2(): +def test_ogr_nas_2(): drv = ogr.GetDriverByName('NAS') if drv is None: - return 'skip' + pytest.skip() if not gdaltest.download_file('http://trac.wheregroup.com/PostNAS/browser/trunk/demodaten/lverm_geo_rlp/gid-6.0/gm2566-testdaten-gid60-2008-11-11.xml.zip?format=raw', 'gm2566-testdaten-gid60-2008-11-11.xml.zip'): - return 'skip' + pytest.skip() try: os.stat('tmp/cache/gm2566-testdaten-gid60-2008-11-11.xml') @@ -124,9 +117,9 @@ def ogr_nas_2(): try: os.stat('tmp/cache/gm2566-testdaten-gid60-2008-11-11.xml') except OSError: - return 'skip' + pytest.skip() except OSError: - return 'skip' + pytest.skip() try: os.remove('tmp/cache/gm2566-testdaten-gid60-2008-11-11.gfs') @@ -134,14 +127,9 @@ def ogr_nas_2(): pass ds = ogr.Open('tmp/cache/gm2566-testdaten-gid60-2008-11-11.xml') - if ds is None: - gdaltest.post_reason('could not open dataset') - return 'fail' + assert ds is not None, 'could not open dataset' - if ds.GetLayerCount() != 85: - gdaltest.post_reason('did not get expected layer count') - print(ds.GetLayerCount()) - return 'fail' + assert ds.GetLayerCount() == 85, 'did not get expected layer count' lyr = ds.GetLayerByName('AX_Flurstueck') @@ -149,55 +137,44 @@ def ogr_nas_2(): feat = lyr.GetNextFeature() while feat is not None and feat.GetField('identifier') != 'urn:adv:oid:DERP1234000002Iz': feat = lyr.GetNextFeature() - if feat is None: - return 'fail' + assert feat is not None # expected_geom = 'POLYGON ((350821.045 5532031.37,350924.309 5532029.513,350938.493 5532026.622,350951.435 5532021.471,350978.7 5532007.18,351026.406 5531971.088,351032.251 5531951.162,351080.623 5531942.67,351154.886 5531963.718,351207.689 5532019.797,351211.063 5532044.067,351203.83 5532074.034,351165.959 5532114.315,351152.85 5532135.774,351141.396 5532140.355,351110.659 5532137.542,351080.17 5532132.742,351002.887 5532120.75,350925.682 5532108.264,350848.556 5532095.285,350771.515 5532081.814,350769.548 5532071.196,350812.194 5532034.716,350821.045 5532031.37))' expected_geom = 'CURVEPOLYGON (COMPOUNDCURVE ((350821.045 5532031.37,350924.309 5532029.513,350938.493 5532026.622,350951.435 5532021.471,350978.7 5532007.18,351026.406 5531971.088,351032.251 5531951.16199999955),(351032.251 5531951.16199999955,351080.623 5531942.67,351154.886 5531963.718),(351154.886 5531963.718,351207.689 5532019.797),(351207.689 5532019.797,351211.063 5532044.06699999981,351203.83 5532074.034,351165.959 5532114.315,351152.85 5532135.774),(351152.85 5532135.774,351141.396 5532140.355),CIRCULARSTRING (351141.396 5532140.355,351110.659 5532137.542,351080.17 5532132.74199999962),CIRCULARSTRING (351080.17 5532132.74199999962,351002.887 5532120.75,350925.682 5532108.264),CIRCULARSTRING (350925.682 5532108.264,350848.556 5532095.285,350771.515 5532081.814),(350771.515 5532081.814,350769.548 5532071.196,350812.194 5532034.716,350821.045 5532031.37)))' if ogrtest.check_feature_geometry(feat, expected_geom) != 0: geom = feat.GetGeometryRef() - print(geom) - return 'fail' + pytest.fail(geom) ds = None - return 'success' - ############################################################################### # Test that we can open and read empty files successfully. # -def ogr_nas_3(): +def test_ogr_nas_3(): drv = ogr.GetDriverByName('NAS') if drv is None: - return 'skip' + pytest.skip() ds = ogr.Open('data/empty_nas.xml') - if ds is None: - gdaltest.post_reason('could not open dataset') - return 'fail' + assert ds is not None, 'could not open dataset' - if ds.GetLayerCount() != 1: - gdaltest.post_reason('did not get expected layer count') - print(ds.GetLayerCount()) - return 'fail' + assert ds.GetLayerCount() == 1, 'did not get expected layer count' ds = None - return 'success' - ############################################################################### # Test that we can read files with wfs:Delete transactions in them properly. # -def ogr_nas_4(): +def test_ogr_nas_4(): drv = ogr.GetDriverByName('NAS') if drv is None: - return 'skip' + pytest.skip() try: os.remove('data/delete_nas.gfs') @@ -205,35 +182,24 @@ def ogr_nas_4(): pass ds = ogr.Open('data/delete_nas.xml') - if ds is None: - gdaltest.post_reason('could not open dataset') - return 'fail' + assert ds is not None, 'could not open dataset' - if ds.GetLayerCount() != 2: - gdaltest.post_reason('did not get expected layer count') - print(ds.GetLayerCount()) - return 'fail' + assert ds.GetLayerCount() == 2, 'did not get expected layer count' del_lyr = ds.GetLayerByName('Delete') - if del_lyr.GetFeatureCount() != 3: - gdaltest.post_reason('did not get expected number of features') - return 'fail' + assert del_lyr.GetFeatureCount() == 3, 'did not get expected number of features' del_lyr.ResetReading() feat = del_lyr.GetNextFeature() - if feat.GetField('context') != 'Delete': - gdaltest.post_reason('did not get expected context') - return 'fail' + assert feat.GetField('context') == 'Delete', 'did not get expected context' - if feat.GetField('typeName') != 'AX_Namensnummer': - gdaltest.post_reason('did not get expected typeName') - return 'fail' + assert feat.GetField('typeName') == 'AX_Namensnummer', \ + 'did not get expected typeName' - if feat.GetField('FeatureId') != 'DENW44AL00000HJU20100730T092847Z': - gdaltest.post_reason('did not get expected FeatureId') - return 'fail' + assert feat.GetField('FeatureId') == 'DENW44AL00000HJU20100730T092847Z', \ + 'did not get expected FeatureId' del_lyr = None ds = None @@ -243,18 +209,17 @@ def ogr_nas_4(): except OSError: pass - return 'success' - + ############################################################################### # Test that we can read files with wfsext:Replace transactions properly # -def ogr_nas_5(): +def test_ogr_nas_5(): drv = ogr.GetDriverByName('NAS') if drv is None: - return 'skip' + pytest.skip() try: os.remove('data/replace_nas.gfs') @@ -262,45 +227,30 @@ def ogr_nas_5(): pass ds = ogr.Open('data/replace_nas.xml') - if ds is None: - gdaltest.post_reason('could not open dataset') - return 'fail' + assert ds is not None, 'could not open dataset' - if ds.GetLayerCount() != 3: - gdaltest.post_reason('did not get expected layer count') - print(ds.GetLayerCount()) - return 'fail' + assert ds.GetLayerCount() == 3, 'did not get expected layer count' # Check the delete operation created for the replace del_lyr = ds.GetLayerByName('Delete') - if del_lyr.GetFeatureCount() != 1: - gdaltest.post_reason('did not get expected number of features') - return 'fail' + assert del_lyr.GetFeatureCount() == 1, 'did not get expected number of features' del_lyr.ResetReading() feat = del_lyr.GetNextFeature() - if feat.GetField('context') != 'Replace': - gdaltest.post_reason('did not get expected context') - return 'fail' + assert feat.GetField('context') == 'Replace', 'did not get expected context' - if feat.GetField('replacedBy') != 'DENW44AL00003IkM20110429T070635Z': - gdaltest.post_reason('did not get expected replacedBy') - return 'fail' + assert feat.GetField('replacedBy') == 'DENW44AL00003IkM20110429T070635Z', \ + 'did not get expected replacedBy' - if feat.GetField('safeToIgnore') != 'false': - gdaltest.post_reason('did not get expected safeToIgnore') - return 'fail' + assert feat.GetField('safeToIgnore') == 'false', 'did not get expected safeToIgnore' - if feat.GetField('typeName') != 'AX_Flurstueck': - gdaltest.post_reason('did not get expected typeName') - return 'fail' + assert feat.GetField('typeName') == 'AX_Flurstueck', 'did not get expected typeName' - if feat.GetField('FeatureId') != 'DENW44AL00003IkM20100809T071726Z': - gdaltest.post_reason('did not get expected FeatureId') - return 'fail' + assert feat.GetField('FeatureId') == 'DENW44AL00003IkM20100809T071726Z', \ + 'did not get expected FeatureId' del_lyr = None @@ -308,20 +258,15 @@ def ogr_nas_5(): lyr = ds.GetLayerByName('AX_Flurstueck') - if lyr.GetFeatureCount() != 1: - gdaltest.post_reason('did not get expected number of features') - return 'fail' + assert lyr.GetFeatureCount() == 1, 'did not get expected number of features' lyr.ResetReading() feat = lyr.GetNextFeature() - if feat.GetField('gml_id') != 'DENW44AL00003IkM20110429T070635Z': - gdaltest.post_reason('did not get expected gml_id') - return 'fail' + assert feat.GetField('gml_id') == 'DENW44AL00003IkM20110429T070635Z', \ + 'did not get expected gml_id' - if feat.GetField('stelle') != 5212: - gdaltest.post_reason('did not get expected stelle') - return 'fail' + assert feat.GetField('stelle') == 5212, 'did not get expected stelle' lyr = None @@ -332,20 +277,6 @@ def ogr_nas_5(): except OSError: pass - return 'success' - - -gdaltest_list = [ - ogr_nas_1, - ogr_nas_2, - ogr_nas_3, - ogr_nas_4, - ogr_nas_5] - -if __name__ == '__main__': - - gdaltest.setup_run('ogr_nas') + - gdaltest.run_tests(gdaltest_list) - sys.exit(gdaltest.summarize()) diff --git a/autotest/ogr/ogr_ntf.py b/autotest/ogr/ogr_ntf.py index 7de31c0cf161..09d18efe13fe 100755 --- a/autotest/ogr/ogr_ntf.py +++ b/autotest/ogr/ogr_ntf.py @@ -77,20 +77,19 @@ import os -import sys from osgeo import ogr -sys.path.append('../pymod') import gdaltest +import pytest ############################################################################### -def ogr_ntf_1(): +def test_ogr_ntf_1(): if not gdaltest.download_file('http://www.ordnancesurvey.co.uk/oswebsite/products/strategi/sampledata/stratntf.exe', 'stratntf.exe'): - return 'skip' + pytest.skip() try: os.stat('tmp/cache/SS.ntf') @@ -100,13 +99,12 @@ def ogr_ntf_1(): try: os.stat('tmp/cache/SS.ntf') except OSError: - return 'skip' + pytest.skip() except OSError: - return 'skip' + pytest.skip() ds = ogr.Open('tmp/cache/SS.ntf') - if ds.GetLayerCount() != 5: - return 'fail' + assert ds.GetLayerCount() == 5 layers = [('STRATEGI_POINT', ogr.wkbPoint, 9193), ('STRATEGI_LINE', ogr.wkbLineString, 8369), @@ -116,31 +114,23 @@ def ogr_ntf_1(): for l in layers: lyr = ds.GetLayerByName(l[0]) - if lyr.GetLayerDefn().GetGeomType() != l[1]: - return 'fail' - if lyr.GetFeatureCount() != l[2]: - print(lyr.GetFeatureCount()) - return 'fail' + assert lyr.GetLayerDefn().GetGeomType() == l[1] + assert lyr.GetFeatureCount() == l[2] if l[1] != ogr.wkbNone: - if lyr.GetSpatialRef().ExportToWkt().find('OSGB 1936') == -1: - return 'fail' + assert lyr.GetSpatialRef().ExportToWkt().find('OSGB 1936') != -1 lyr = ds.GetLayerByName('STRATEGI_POINT') feat = lyr.GetNextFeature() - if feat.GetGeometryRef().ExportToWkt() != 'POINT (222904 127850)': - print(feat.GetGeometryRef().ExportToWkt()) - return 'fail' + assert feat.GetGeometryRef().ExportToWkt() == 'POINT (222904 127850)' ds.Destroy() - return 'success' - ############################################################################### -def ogr_ntf_2(): +def test_ogr_ntf_2(): if not gdaltest.download_file('http://www.ordnancesurvey.co.uk/oswebsite/products/meridian2/sampledata/meridian2ntf.exe', 'meridian2ntf.exe'): - return 'skip' + pytest.skip() try: os.stat('tmp/cache/Port_Talbot_NTF/SS78.ntf') @@ -150,13 +140,12 @@ def ogr_ntf_2(): try: os.stat('tmp/cache/Port_Talbot_NTF/SS78.ntf') except OSError: - return 'skip' + pytest.skip() except OSError: - return 'skip' + pytest.skip() ds = ogr.Open('tmp/cache/Port_Talbot_NTF/SS78.ntf') - if ds.GetLayerCount() != 5: - return 'fail' + assert ds.GetLayerCount() == 5 layers = [('MERIDIAN2_POINT', ogr.wkbPoint, 408), ('MERIDIAN2_LINE', ogr.wkbLineString, 513), @@ -166,40 +155,20 @@ def ogr_ntf_2(): for l in layers: lyr = ds.GetLayerByName(l[0]) - if lyr.GetLayerDefn().GetGeomType() != l[1]: - return 'fail' - if lyr.GetFeatureCount() != l[2]: - print(lyr.GetFeatureCount()) - return 'fail' + assert lyr.GetLayerDefn().GetGeomType() == l[1] + assert lyr.GetFeatureCount() == l[2] if l[1] != ogr.wkbNone: - if lyr.GetSpatialRef().ExportToWkt().find('OSGB 1936') == -1: - return 'fail' + assert lyr.GetSpatialRef().ExportToWkt().find('OSGB 1936') != -1 lyr = ds.GetLayerByName('MERIDIAN2_POINT') feat = lyr.GetNextFeature() - if feat.GetGeometryRef().ExportToWkt() != 'POINT (275324 189274)': - print(feat.GetGeometryRef().ExportToWkt()) - return 'fail' + assert feat.GetGeometryRef().ExportToWkt() == 'POINT (275324 189274)' lyr = ds.GetLayerByName('MERIDIAN2_LINE') feat = lyr.GetNextFeature() - if feat.GetGeometryRef().ExportToWkt() != 'LINESTRING (275324 189274,275233 189114,275153 189048)': - print(feat.GetGeometryRef().ExportToWkt()) - return 'fail' + assert feat.GetGeometryRef().ExportToWkt() == 'LINESTRING (275324 189274,275233 189114,275153 189048)' ds.Destroy() - return 'success' - - -gdaltest_list = [ - ogr_ntf_1, - ogr_ntf_2] - -if __name__ == '__main__': - - gdaltest.setup_run('ogr_ntf') - gdaltest.run_tests(gdaltest_list) - sys.exit(gdaltest.summarize()) diff --git a/autotest/ogr/ogr_oci.py b/autotest/ogr/ogr_oci.py index 684f46aa12da..0c969734e831 100755 --- a/autotest/ogr/ogr_oci.py +++ b/autotest/ogr/ogr_oci.py @@ -27,46 +27,45 @@ ############################################################################### import os -import sys -sys.path.append('../pymod') import gdaltest import ogrtest from osgeo import ogr from osgeo import osr from osgeo import gdal +import pytest ############################################################################### # Open ORACLE. -def ogr_oci_1(): +def test_ogr_oci_1(): gdaltest.oci_ds = None try: ogr.GetDriverByName('OCI') except: - return 'skip' + pytest.skip() if 'OCI_DSNAME' not in os.environ: - return 'skip' + pytest.skip() gdaltest.oci_ds = ogr.Open(os.environ['OCI_DSNAME']) if gdaltest.oci_ds is not None: - return 'success' - return 'fail' + return + pytest.fail() ############################################################################### # Create Oracle table from data/poly.shp -def ogr_oci_2(): +def test_ogr_oci_2(): if gdaltest.oci_ds is None: - return 'skip' + pytest.skip() gdal.PushErrorHandler('CPLQuietErrorHandler') gdaltest.oci_ds.ExecuteSQL('DELLAYER:tpoly') @@ -110,16 +109,12 @@ def ogr_oci_2(): shp_lyr.ResetReading() feat = shp_lyr.GetNextFeature() feat.SetFID(-10) - if gdaltest.oci_lyr.SetFeature(feat) != ogr.OGRERR_NON_EXISTING_FEATURE: - gdaltest.post_reason('Expected failure of SetFeature().') - return 'fail' + assert gdaltest.oci_lyr.SetFeature(feat) == ogr.OGRERR_NON_EXISTING_FEATURE, \ + 'Expected failure of SetFeature().' # Test deleting non-existing feature - if gdaltest.oci_lyr.DeleteFeature(-10) != ogr.OGRERR_NON_EXISTING_FEATURE: - gdaltest.post_reason('Expected failure of DeleteFeature().') - return 'fail' - - return 'success' + assert gdaltest.oci_lyr.DeleteFeature(-10) == ogr.OGRERR_NON_EXISTING_FEATURE, \ + 'Expected failure of DeleteFeature().' ############################################################################### # Helper method to reverse ring winding. This is needed because the @@ -141,9 +136,9 @@ def reverse_rings(poly): # Verify that stuff we just wrote is still OK. -def ogr_oci_3(): +def test_ogr_oci_3(): if gdaltest.oci_ds is None: - return 'skip' + pytest.skip() expect = [168, 169, 166, 158, 165] @@ -161,17 +156,15 @@ def ogr_oci_3(): if ogrtest.check_feature_geometry(read_feat, orig_feat.GetGeometryRef(), max_error=0.000000001) != 0: print('expected:', orig_feat.GetGeometryRef().ExportToWkt()) - print('got:', read_feat.GetGeometryRef().ExportToWkt()) - return 'fail' + pytest.fail('got:', read_feat.GetGeometryRef().ExportToWkt()) for fld in range(3): if orig_feat.GetField(fld) != read_feat.GetField(fld): - gdaltest.post_reason('Attribute %d does not match' % fld) print('expected:') print(orig_feat.DumpReadable()) print('got:') print(read_feat.DumpReadable()) - return 'fail' + pytest.fail('Attribute %d does not match' % fld) read_feat.Destroy() orig_feat.Destroy() @@ -179,17 +172,17 @@ def ogr_oci_3(): gdaltest.poly_feat = None gdaltest.shp_ds.Destroy() - return 'success' if tr else 'fail' + assert tr ############################################################################### # Write more features with a bunch of different geometries, and verify the # geometries are still OK. -def ogr_oci_4(): +def test_ogr_oci_4(): if gdaltest.oci_ds is None: - return 'skip' + pytest.skip() wkt_list = ['10', '2', '1', '3d_1', '4', '5', '6'] @@ -211,50 +204,43 @@ def ogr_oci_4(): gdaltest.oci_lyr.SetAttributeFilter("PRFEDEA = '%s'" % item) feat_read = gdaltest.oci_lyr.GetNextFeature() - if ogrtest.check_feature_geometry(feat_read, geom) != 0: - return 'fail' + assert ogrtest.check_feature_geometry(feat_read, geom) == 0 feat_read.Destroy() dst_feat.Destroy() - return 'success' - ############################################################################### # Test ExecuteSQL() results layers without geometry. -def ogr_oci_5(): +def test_ogr_oci_5(): if gdaltest.oci_ds is None: - return 'skip' + pytest.skip() expect = [None, 179, 173, 172, 171, 170, 169, 168, 166, 165, 158] sql_lyr = gdaltest.oci_ds.ExecuteSQL('select distinct eas_id from tpoly order by eas_id desc') - if sql_lyr.GetLayerDefn().GetGeomFieldCount() != 0: - gdaltest.post_reason('fail') - return 'fail' + assert sql_lyr.GetLayerDefn().GetGeomFieldCount() == 0 tr = ogrtest.check_features_against_list(sql_lyr, 'eas_id', expect) gdaltest.oci_ds.ReleaseResultSet(sql_lyr) - return 'success' if tr else 'fail' + assert tr ############################################################################### # Test ExecuteSQL() results layers with geometry. -def ogr_oci_6(): +def test_ogr_oci_6(): if gdaltest.oci_ds is None: - return 'skip' + pytest.skip() sql_lyr = gdaltest.oci_ds.ExecuteSQL("select * from tpoly where prfedea = '2'") - if sql_lyr.GetLayerDefn().GetGeomFieldCount() != 1: - gdaltest.post_reason('fail') - return 'fail' + assert sql_lyr.GetLayerDefn().GetGeomFieldCount() == 1 tr = ogrtest.check_features_against_list(sql_lyr, 'prfedea', ['2']) if tr: @@ -266,16 +252,16 @@ def ogr_oci_6(): gdaltest.oci_ds.ReleaseResultSet(sql_lyr) - return 'success' if tr else 'fail' + assert tr ############################################################################### # Test spatial filtering. -def ogr_oci_7(): +def test_ogr_oci_7(): if gdaltest.oci_ds is None: - return 'skip' + pytest.skip() gdaltest.oci_lyr.SetAttributeFilter(None) @@ -289,17 +275,17 @@ def ogr_oci_7(): gdaltest.oci_lyr.SetSpatialFilter(None) - return 'success' if tr else 'fail' + assert tr ############################################################################### # Test that we can create a layer with a coordinate system that is mapped # to an oracle coordinate system using the ORACLE authority code. -def ogr_oci_8(): +def test_ogr_oci_8(): if gdaltest.oci_ds is None: - return 'skip' + pytest.skip() ####################################################### # Preclean. @@ -325,29 +311,24 @@ def ogr_oci_8(): # oracle SRS. srs2 = oci_lyr2.GetSpatialRef() - if srs2.GetAuthorityCode('GEOGCS') != '8241': - gdaltest.post_reason('Did not get expected authority code') - return 'fail' + assert srs2.GetAuthorityCode('GEOGCS') == '8241', \ + 'Did not get expected authority code' - if srs2.GetAuthorityName('GEOGCS') != 'Oracle': - gdaltest.post_reason('Did not get expected authority name') - return 'fail' + assert srs2.GetAuthorityName('GEOGCS') == 'Oracle', \ + 'Did not get expected authority name' - if srs2.GetAttrValue('GEOGCS|DATUM') != 'Kertau 1948': - gdaltest.post_reason('Did not get expected datum name') - return 'fail' - - return 'success' + assert srs2.GetAttrValue('GEOGCS|DATUM') == 'Kertau 1948', \ + 'Did not get expected datum name' ############################################################################### # This time we create a layer with a EPSG marked GEOGCS, and verify that # the coordinate system gets properly remapped to the Oracle WGS84. -def ogr_oci_9(): +def test_ogr_oci_9(): if gdaltest.oci_ds is None: - return 'skip' + pytest.skip() ####################################################### # Preclean. @@ -371,28 +352,23 @@ def ogr_oci_9(): # oracle SRS we expect. srs2 = oci_lyr2.GetSpatialRef() - if srs2.GetAuthorityCode('GEOGCS') != '4326': - gdaltest.post_reason('Did not get expected authority code') - return 'fail' - - if srs2.GetAuthorityName('GEOGCS') != 'EPSG': - gdaltest.post_reason('Did not get expected authority name') - return 'fail' + assert srs2.GetAuthorityCode('GEOGCS') == '4326', \ + 'Did not get expected authority code' - if srs2.GetAttrValue('GEOGCS|DATUM') != 'WGS 84': - gdaltest.post_reason('Did not get expected datum name') - return 'fail' + assert srs2.GetAuthorityName('GEOGCS') == 'EPSG', \ + 'Did not get expected authority name' - return 'success' + assert srs2.GetAttrValue('GEOGCS|DATUM') == 'WGS 84', \ + 'Did not get expected datum name' ############################################################################### # Test handling of specialized Oracle Rectangle Geometries. -def ogr_oci_10(): +def test_ogr_oci_10(): if gdaltest.oci_ds is None: - return 'skip' + pytest.skip() # Create a test table. gdal.PushErrorHandler('CPLQuietErrorHandler') @@ -431,16 +407,16 @@ def ogr_oci_10(): feat_read.Destroy() gdaltest.oci_ds.ReleaseResultSet(sql_lyr) - return 'success' if tr else 'fail' + assert tr ############################################################################### # Test handling of specialized Oracle circle Geometries. -def ogr_oci_11(): +def test_ogr_oci_11(): if gdaltest.oci_ds is None: - return 'skip' + pytest.skip() # insert a rectangle geometry. gdaltest.oci_ds.ExecuteSQL(""" @@ -470,16 +446,16 @@ def ogr_oci_11(): feat_read.Destroy() gdaltest.oci_ds.ReleaseResultSet(sql_lyr) - return 'success' if tr else 'fail' + assert tr ############################################################################### # Test handling of specialized Oracle circular arc linestring Geometries. -def ogr_oci_12(): +def test_ogr_oci_12(): if gdaltest.oci_ds is None: - return 'skip' + pytest.skip() # insert a rectangle geometry. gdaltest.oci_ds.ExecuteSQL(""" @@ -508,16 +484,16 @@ def ogr_oci_12(): feat_read.Destroy() gdaltest.oci_ds.ReleaseResultSet(sql_lyr) - return 'success' if tr else 'fail' + assert tr ############################################################################### # Test handling of specialized Oracle circular arc polygon Geometries. -def ogr_oci_13(): +def test_ogr_oci_13(): if gdaltest.oci_ds is None: - return 'skip' + pytest.skip() # insert a rectangle geometry. gdaltest.oci_ds.ExecuteSQL(""" @@ -547,16 +523,16 @@ def ogr_oci_13(): feat_read.Destroy() gdaltest.oci_ds.ReleaseResultSet(sql_lyr) - return 'success' if tr else 'fail' + assert tr ############################################################################### # Test handling of compount linestring. -def ogr_oci_14(): +def test_ogr_oci_14(): if gdaltest.oci_ds is None: - return 'skip' + pytest.skip() # insert a rectangle geometry. gdaltest.oci_ds.ExecuteSQL(""" @@ -586,16 +562,16 @@ def ogr_oci_14(): feat_read.Destroy() gdaltest.oci_ds.ReleaseResultSet(sql_lyr) - return 'success' if tr else 'fail' + assert tr ############################################################################### # Test handling of compount polygon. -def ogr_oci_15(): +def test_ogr_oci_15(): if gdaltest.oci_ds is None: - return 'skip' + pytest.skip() # insert a rectangle geometry. gdaltest.oci_ds.ExecuteSQL(""" @@ -625,16 +601,16 @@ def ogr_oci_15(): feat_read.Destroy() gdaltest.oci_ds.ReleaseResultSet(sql_lyr) - return 'success' if tr else 'fail' + assert tr ############################################################################### # Test deleting an existing layer. -def ogr_oci_16(): +def test_ogr_oci_16(): if gdaltest.oci_ds is None: - return 'skip' + pytest.skip() target_index = -1 lc = gdaltest.oci_ds.GetLayerCount() @@ -647,30 +623,22 @@ def ogr_oci_16(): lyr = None - if target_index == -1: - gdaltest.post_reason('did not find testsrs2 layer') - return 'fail' + assert target_index != -1, 'did not find testsrs2 layer' result = gdaltest.oci_ds.DeleteLayer(target_index) - if result != 0: - gdaltest.post_reason('DeleteLayer() failed.') - return 'fail' + assert result == 0, 'DeleteLayer() failed.' lyr = gdaltest.oci_ds.GetLayerByName('testsrs2') - if lyr is not None: - gdaltest.post_reason('apparently failed to remove testsrs2 layer') - return 'fail' - - return 'success' + assert lyr is None, 'apparently failed to remove testsrs2 layer' ############################################################################### # Test that synctodisk actually sets the layer bounds metadata. -def ogr_oci_17(): +def test_ogr_oci_17(): if gdaltest.oci_ds is None: - return 'skip' + pytest.skip() gdaltest.oci_ds.ExecuteSQL('DELLAYER:xpoly') @@ -715,36 +683,28 @@ def ogr_oci_17(): oci_ds2 = ogr.Open(os.environ['OCI_DSNAME']) sql_lyr = oci_ds2.ExecuteSQL("select column_name from user_sdo_geom_metadata where table_name = 'XPOLY'") - if sql_lyr.GetFeatureCount() > 0: - gdaltest.post_reason('user_sdo_geom_metadata already populated!') - return 'fail' + assert sql_lyr.GetFeatureCount() <= 0, 'user_sdo_geom_metadata already populated!' oci_ds2.ReleaseResultSet(sql_lyr) result = gdaltest.oci_ds.SyncToDisk() - if result != 0: - gdaltest.post_reason('SyncToDisk() failed.') - return 'fail' + assert result == 0, 'SyncToDisk() failed.' sql_lyr = oci_ds2.ExecuteSQL("select column_name from user_sdo_geom_metadata where table_name = 'XPOLY'") - if sql_lyr.GetFeatureCount() == 0: - gdaltest.post_reason('user_sdo_geom_metadata still not populated!') - return 'fail' + assert sql_lyr.GetFeatureCount() != 0, 'user_sdo_geom_metadata still not populated!' oci_ds2.ReleaseResultSet(sql_lyr) oci_ds2 = None - return 'success' - ############################################################################### # Test layer geometry types -def ogr_oci_18(): +def test_ogr_oci_18(): if gdaltest.oci_ds is None: - return 'skip' + pytest.skip() wkts = ['POINT (0 1)', 'LINESTRING (0 1,2 3)', 'POLYGON ((0 0,1 0,1 1,0 1,0 0))', 'MULTIPOINT (0 1)', 'MULTILINESTRING ((0 1,2 3))', 'MULTIPOLYGON (((0 0,1 0,1 1,0 1,0 0)))', @@ -781,17 +741,9 @@ def ogr_oci_18(): strgeomtype = strgeomtype + '3' lyr = oci_ds2.GetLayerByName('test_%s' % strgeomtype) - if lyr.GetGeomType() != geomtype: - gdaltest.post_reason('fail') - print(wkt) - print(lyr.GetGeomType()) - return 'fail' + assert lyr.GetGeomType() == geomtype, wkt feat = lyr.GetNextFeature() - if feat.GetGeometryRef().ExportToWkt() != wkt: - gdaltest.post_reason('fail') - print(wkt) - print(feat.GetGeometryRef().ExportToWkt()) - return 'fail' + assert feat.GetGeometryRef().ExportToWkt() == wkt dsname = os.environ['OCI_DSNAME'] if dsname.find('@') < 0: @@ -801,20 +753,16 @@ def ogr_oci_18(): oci_ds2 = ogr.Open(dsname) lyr = oci_ds2.GetLayerByName('test_NONE') - if lyr.GetGeomType() != ogr.wkbNone: - gdaltest.post_reason('fail') - return 'fail' - - return 'success' + assert lyr.GetGeomType() == ogr.wkbNone ############################################################################### # Test date / datetime -def ogr_oci_19(): +def test_ogr_oci_19(): if gdaltest.oci_ds is None: - return 'skip' + pytest.skip() lyr = gdaltest.oci_ds.CreateLayer('testdate', geom_type=ogr.wkbNone) lyr.CreateField(ogr.FieldDefn('MYDATE', ogr.OFTDate)) @@ -826,33 +774,24 @@ def ogr_oci_19(): lyr.SyncToDisk() sql_lyr = gdaltest.oci_ds.ExecuteSQL('SELECT MYDATE, MYDATETIME FROM testdate') - if sql_lyr.GetLayerDefn().GetFieldDefn(0).GetType() != ogr.OFTDate: - gdaltest.post_reason('fail') - return 'fail' - if sql_lyr.GetLayerDefn().GetFieldDefn(1).GetType() != ogr.OFTDateTime: - gdaltest.post_reason('fail') - return 'fail' + assert sql_lyr.GetLayerDefn().GetFieldDefn(0).GetType() == ogr.OFTDate + assert sql_lyr.GetLayerDefn().GetFieldDefn(1).GetType() == ogr.OFTDateTime f = sql_lyr.GetNextFeature() if f.GetField(0) != '2015/02/03' or f.GetField(1) != '2015/02/03 11:33:44': - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' + pytest.fail() gdaltest.oci_ds.ReleaseResultSet(sql_lyr) - return 'success' - ############################################################################### # Test not nullable fields -def ogr_oci_20(): +def test_ogr_oci_20(): if gdaltest.oci_ds is None: - return 'skip' + pytest.skip() lyr = gdaltest.oci_ds.CreateLayer('ogr_oci_20', geom_type=ogr.wkbPoint, options=['GEOMETRY_NULLABLE=NO', 'DIM=2']) - if lyr.GetLayerDefn().GetGeomFieldDefn(0).IsNullable() != 0: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.GetLayerDefn().GetGeomFieldDefn(0).IsNullable() == 0 field_defn = ogr.FieldDefn('field_not_nullable', ogr.OFTString) field_defn.SetNullable(0) lyr.CreateField(field_defn) @@ -864,9 +803,7 @@ def ogr_oci_20(): f.SetGeometryDirectly(ogr.CreateGeometryFromWkt('POINT(0 1)')) ret = lyr.CreateFeature(f) f = None - if ret != 0: - gdaltest.post_reason('fail') - return 'fail' + assert ret == 0 # Error case: missing geometry f = ogr.Feature(lyr.GetLayerDefn()) @@ -874,9 +811,7 @@ def ogr_oci_20(): gdal.PushErrorHandler() ret = lyr.CreateFeature(f) gdal.PopErrorHandler() - if ret == 0: - gdaltest.post_reason('fail') - return 'fail' + assert ret != 0 f = None # Error case: missing non-nullable field @@ -885,69 +820,47 @@ def ogr_oci_20(): gdal.PushErrorHandler() ret = lyr.CreateFeature(f) gdal.PopErrorHandler() - if ret == 0: - gdaltest.post_reason('fail') - return 'fail' + assert ret != 0 f = None lyr.SyncToDisk() # Test with nullable geometry lyr = gdaltest.oci_ds.CreateLayer('ogr_oci_20bis', geom_type=ogr.wkbPoint, options=['DIM=2']) - if lyr.GetLayerDefn().GetGeomFieldDefn(0).IsNullable() != 1: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.GetLayerDefn().GetGeomFieldDefn(0).IsNullable() == 1 f = ogr.Feature(lyr.GetLayerDefn()) f.SetGeometryDirectly(ogr.CreateGeometryFromWkt('POINT(0 1)')) ret = lyr.CreateFeature(f) f = None - if ret != 0: - gdaltest.post_reason('fail') - return 'fail' + assert ret == 0 f = ogr.Feature(lyr.GetLayerDefn()) ret = lyr.CreateFeature(f) f = None - if ret != 0: - gdaltest.post_reason('fail') - return 'fail' + assert ret == 0 lyr.SyncToDisk() oci_ds2 = ogr.Open(os.environ['OCI_DSNAME']) lyr = oci_ds2.GetLayerByName('ogr_oci_20') - if lyr.GetLayerDefn().GetFieldDefn(lyr.GetLayerDefn().GetFieldIndex('field_not_nullable')).IsNullable() != 0: - gdaltest.post_reason('fail') - return 'fail' - if lyr.GetLayerDefn().GetFieldDefn(lyr.GetLayerDefn().GetFieldIndex('field_nullable')).IsNullable() != 1: - gdaltest.post_reason('fail') - return 'fail' - if lyr.GetLayerDefn().GetGeomFieldDefn(0).IsNullable() != 0: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.GetLayerDefn().GetFieldDefn(lyr.GetLayerDefn().GetFieldIndex('field_not_nullable')).IsNullable() == 0 + assert lyr.GetLayerDefn().GetFieldDefn(lyr.GetLayerDefn().GetFieldIndex('field_nullable')).IsNullable() == 1 + assert lyr.GetLayerDefn().GetGeomFieldDefn(0).IsNullable() == 0 lyr = oci_ds2.GetLayerByName('ogr_oci_20bis') - if lyr.GetLayerDefn().GetGeomFieldDefn(0).IsNullable() != 1: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.GetLayerDefn().GetGeomFieldDefn(0).IsNullable() == 1 feat = lyr.GetNextFeature() - if feat.GetGeometryRef() is None: - gdaltest.post_reason('fail') - return 'fail' + assert feat.GetGeometryRef() is not None feat = lyr.GetNextFeature() - if feat.GetGeometryRef() is not None: - gdaltest.post_reason('fail') - return 'fail' - - return 'success' + assert feat.GetGeometryRef() is None ############################################################################### # Test default values -def ogr_oci_21(): +def test_ogr_oci_21(): if gdaltest.oci_ds is None: - return 'skip' + pytest.skip() lyr = gdaltest.oci_ds.CreateLayer('ogr_oci_21', geom_type=ogr.wkbPoint, options=['DIM=2']) @@ -1003,25 +916,12 @@ def ogr_oci_21(): oci_ds2 = ogr.Open(os.environ['OCI_DSNAME']) lyr = oci_ds2.GetLayerByName('ogr_oci_21') - if lyr.GetLayerDefn().GetFieldDefn(lyr.GetLayerDefn().GetFieldIndex('field_string')).GetDefault() != "'a''b'": - gdaltest.post_reason('fail') - return 'fail' - if lyr.GetLayerDefn().GetFieldDefn(lyr.GetLayerDefn().GetFieldIndex('field_int')).GetDefault() != '123': - gdaltest.post_reason('fail') - return 'fail' - if lyr.GetLayerDefn().GetFieldDefn(lyr.GetLayerDefn().GetFieldIndex('field_real')).GetDefault() != '1.23': - gdaltest.post_reason('fail') - return 'fail' - if lyr.GetLayerDefn().GetFieldDefn(lyr.GetLayerDefn().GetFieldIndex('field_nodefault')).GetDefault() is not None: - gdaltest.post_reason('fail') - return 'fail' - if lyr.GetLayerDefn().GetFieldDefn(lyr.GetLayerDefn().GetFieldIndex('field_datetime')).GetDefault() != 'CURRENT_TIMESTAMP': - gdaltest.post_reason('fail') - return 'fail' - if lyr.GetLayerDefn().GetFieldDefn(lyr.GetLayerDefn().GetFieldIndex('field_datetime2')).GetDefault() != "'2015/06/30 12:34:56'": - gdaltest.post_reason('fail') - print(lyr.GetLayerDefn().GetFieldDefn(lyr.GetLayerDefn().GetFieldIndex('field_datetime2')).GetDefault()) - return 'fail' + assert lyr.GetLayerDefn().GetFieldDefn(lyr.GetLayerDefn().GetFieldIndex('field_string')).GetDefault() == "'a''b'" + assert lyr.GetLayerDefn().GetFieldDefn(lyr.GetLayerDefn().GetFieldIndex('field_int')).GetDefault() == '123' + assert lyr.GetLayerDefn().GetFieldDefn(lyr.GetLayerDefn().GetFieldIndex('field_real')).GetDefault() == '1.23' + assert lyr.GetLayerDefn().GetFieldDefn(lyr.GetLayerDefn().GetFieldIndex('field_nodefault')).GetDefault() is None + assert lyr.GetLayerDefn().GetFieldDefn(lyr.GetLayerDefn().GetFieldIndex('field_datetime')).GetDefault() == 'CURRENT_TIMESTAMP' + assert lyr.GetLayerDefn().GetFieldDefn(lyr.GetLayerDefn().GetFieldIndex('field_datetime2')).GetDefault() == "'2015/06/30 12:34:56'" # if lyr.GetLayerDefn().GetFieldDefn(lyr.GetLayerDefn().GetFieldIndex('field_date')).GetDefault() != "CURRENT_DATE": # gdaltest.post_reason('fail') # print(lyr.GetLayerDefn().GetFieldDefn(lyr.GetLayerDefn().GetFieldIndex('field_date')).GetDefault()) @@ -1032,31 +932,27 @@ def ogr_oci_21(): f = lyr.GetNextFeature() if f.GetField('field_string') != 'c': - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' + pytest.fail() f = lyr.GetNextFeature() if f.GetField('field_string') != 'a\'b' or f.GetField('field_int') != 123 or \ f.GetField('field_real') != 1.23 or \ not f.IsFieldNull('field_nodefault') or not f.IsFieldSet('field_datetime') or \ f.GetField('field_datetime2') != '2015/06/30 12:34:56': - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' + pytest.fail() gdal.Unlink('/vsimem/ogr_gpkg_24.gpkg') - return 'success' - ############################################################################### # -def ogr_oci_cleanup(): +def test_ogr_oci_cleanup(): if gdaltest.oci_ds is None: - return 'skip' + pytest.skip() gdaltest.oci_ds.ExecuteSQL('DELLAYER:tpoly') gdaltest.oci_ds.ExecuteSQL('DELLAYER:xpoly') @@ -1083,42 +979,5 @@ def ogr_oci_cleanup(): gdaltest.oci_ds = None gdaltest.shp_ds = None - return 'success' - - -gdaltest_list = [ - ogr_oci_1, - ogr_oci_2, - ogr_oci_3, - ogr_oci_4, - ogr_oci_5, - ogr_oci_6, - ogr_oci_7, - ogr_oci_8, - ogr_oci_9, - ogr_oci_10, - ogr_oci_11, - ogr_oci_12, - ogr_oci_13, - ogr_oci_14, - ogr_oci_15, - ogr_oci_16, - ogr_oci_17, - ogr_oci_18, - ogr_oci_19, - ogr_oci_20, - ogr_oci_21, - ogr_oci_cleanup] - -if __name__ == '__main__': - - if 'OCI_DSNAME' not in os.environ: - print('Enter ORACLE DataSource (e.g. OCI:scott/tiger):') - oci_dsname = sys.stdin.readline().strip() - os.environ['OCI_DSNAME'] = oci_dsname - - gdaltest.setup_run('ogr_oci') - gdaltest.run_tests(gdaltest_list) - sys.exit(gdaltest.summarize()) diff --git a/autotest/ogr/ogr_odbc.py b/autotest/ogr/ogr_odbc.py index 26f7e097eb7f..e0d006c2c3bb 100755 --- a/autotest/ogr/ogr_odbc.py +++ b/autotest/ogr/ogr_odbc.py @@ -33,29 +33,29 @@ from osgeo import ogr from osgeo import gdal -sys.path.append('../pymod') import gdaltest import ogrtest +import pytest ############################################################################### # Basic testing -def ogr_odbc_1(): +def test_ogr_odbc_1(): ogrtest.odbc_drv = None if sys.platform != 'win32': - return 'skip' + pytest.skip() ogrtest.odbc_drv = ogr.GetDriverByName('ODBC') if ogrtest.odbc_drv is None: - return 'skip' + pytest.skip() ds = ogrtest.odbc_drv.Open('data/empty.mdb') if ds is None: ogrtest.odbc_drv = None - return 'skip' + pytest.skip() ds = None @@ -76,118 +76,82 @@ def ogr_odbc_1(): # Test with ODBC:user/pwd@dsn syntax ds = ogrtest.odbc_drv.Open('ODBC:user/pwd@DRIVER=Microsoft Access Driver (*.mdb);DBQ=tmp/odbc.mdb') - if ds is None: - gdaltest.post_reason('failure') - return 'fail' + assert ds is not None ds = None # Test with ODBC:dsn syntax ds = ogrtest.odbc_drv.Open('ODBC:DRIVER=Microsoft Access Driver (*.mdb);DBQ=tmp/odbc.mdb') - if ds is None: - gdaltest.post_reason('failure') - return 'fail' + assert ds is not None ds = None # Test with ODBC:dsn,table_list syntax ds = ogrtest.odbc_drv.Open('ODBC:DRIVER=Microsoft Access Driver (*.mdb);DBQ=tmp/odbc.mdb,test') - if ds is None: - gdaltest.post_reason('failure') - return 'fail' - if ds.GetLayerCount() != 1: - gdaltest.post_reason('failure') - return 'fail' + assert ds is not None + assert ds.GetLayerCount() == 1 ds = None # Reopen and check ds = ogrtest.odbc_drv.Open('tmp/odbc.mdb') - if ds.GetLayerCount() != 2: - gdaltest.post_reason('failure') - return 'fail' + assert ds.GetLayerCount() == 2 lyr = ds.GetLayerByName('test') feat = lyr.GetNextFeature() if feat.GetField('intfield') != 1 or feat.GetField('doublefield') != 2.34 or feat.GetField('stringfield') != 'foo': - gdaltest.post_reason('failure') feat.DumpReadable() - return 'fail' + pytest.fail() lyr = ds.GetLayerByName('test_with_pk') # Test GetFeatureCount() - if lyr.GetFeatureCount() != 5: - gdaltest.post_reason('failure') - return 'fail' + assert lyr.GetFeatureCount() == 5 # Test GetFeature() feat = lyr.GetFeature(4) if feat.GetField('intfield') != 5: - gdaltest.post_reason('failure') feat.DumpReadable() - return 'fail' + pytest.fail() # Test SetAttributeFilter() lyr.SetAttributeFilter('intfield = 6') feat = lyr.GetNextFeature() if feat.GetFID() != 5: - gdaltest.post_reason('failure') feat.DumpReadable() - return 'fail' + pytest.fail() # Test ExecuteSQL() sql_lyr = ds.ExecuteSQL("SELECT * FROM test") feat = sql_lyr.GetNextFeature() if feat.GetField('intfield') != 1 or feat.GetField('doublefield') != 2.34 or feat.GetField('stringfield') != 'foo': - gdaltest.post_reason('failure') feat.DumpReadable() - return 'fail' + pytest.fail() ds.ReleaseResultSet(sql_lyr) ds = None - return 'success' - ############################################################################### # Run test_ogrsf -def ogr_odbc_2(): +def test_ogr_odbc_2(): if ogrtest.odbc_drv is None: - return 'skip' + pytest.skip() import test_cli_utilities if test_cli_utilities.get_test_ogrsf_path() is None: - return 'skip' + pytest.skip() ret = gdaltest.runexternal(test_cli_utilities.get_test_ogrsf_path() + ' tmp/odbc.mdb') - if ret.find('INFO') == -1 or ret.find('ERROR') != -1: - print(ret) - return 'fail' - - return 'success' + assert ret.find('INFO') != -1 and ret.find('ERROR') == -1 ############################################################################### # Cleanup -def ogr_odbc_cleanup(): +def test_ogr_odbc_cleanup(): if ogrtest.odbc_drv is None: - return 'skip' + pytest.skip() gdal.Unlink('tmp/odbc.mdb') - return 'success' - - -gdaltest_list = [ - ogr_odbc_1, - ogr_odbc_2, - ogr_odbc_cleanup -] - -if __name__ == '__main__': - - gdaltest.setup_run('ogr_odbc') - gdaltest.run_tests(gdaltest_list) - sys.exit(gdaltest.summarize()) diff --git a/autotest/ogr/ogr_ods.py b/autotest/ogr/ogr_ods.py index 64eb13ddca6e..cea0a864b1e8 100755 --- a/autotest/ogr/ogr_ods.py +++ b/autotest/ogr/ogr_ods.py @@ -29,14 +29,13 @@ ############################################################################### import os -import sys import shutil -sys.path.append('../pymod') import gdaltest from osgeo import gdal from osgeo import ogr +import pytest ############################################################################### # Check @@ -44,45 +43,25 @@ def ogr_ods_check(ds): - if ds.TestCapability("foo") != 0: - gdaltest.post_reason('fail') - return 'fail' + assert ds.TestCapability("foo") == 0 - if ds.GetLayerCount() != 8: - gdaltest.post_reason('bad layer count') - return 'fail' + assert ds.GetLayerCount() == 8, 'bad layer count' lyr = ds.GetLayer(0) - if lyr.GetName() != 'Feuille1': - gdaltest.post_reason('bad layer name') - return 'fail' + assert lyr.GetName() == 'Feuille1', 'bad layer name' - if lyr.GetGeomType() != ogr.wkbNone: - gdaltest.post_reason('bad layer geometry type') - return 'fail' + assert lyr.GetGeomType() == ogr.wkbNone, 'bad layer geometry type' - if lyr.GetSpatialRef() is not None: - gdaltest.post_reason('bad spatial ref') - return 'fail' + assert lyr.GetSpatialRef() is None, 'bad spatial ref' - if lyr.GetFeatureCount() != 26: - gdaltest.post_reason('fail') - print(lyr.GetFeatureCount()) - return 'fail' + assert lyr.GetFeatureCount() == 26 - if lyr.TestCapability("foo") != 0: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.TestCapability("foo") == 0 lyr = ds.GetLayer(6) - if lyr.GetName() != 'Feuille7': - gdaltest.post_reason('bad layer name') - return 'fail' + assert lyr.GetName() == 'Feuille7', 'bad layer name' - if lyr.GetLayerDefn().GetFieldCount() != 12: - gdaltest.post_reason('fail') - print(lyr.GetLayerDefn().GetFieldCount()) - return 'fail' + assert lyr.GetLayerDefn().GetFieldCount() == 12 type_array = [ogr.OFTString, ogr.OFTInteger, @@ -98,11 +77,7 @@ def ogr_ods_check(ds): ogr.OFTDateTime] for i, typ in enumerate(type_array): - if lyr.GetLayerDefn().GetFieldDefn(i).GetType() != typ: - gdaltest.post_reason('fail') - print(i) - print(lyr.GetLayerDefn().GetFieldDefn(i).GetType()) - return 'fail' + assert lyr.GetLayerDefn().GetFieldDefn(i).GetType() == typ feat = lyr.GetNextFeature() if feat.GetFieldAsString(0) != 'val' or \ @@ -111,36 +86,29 @@ def ogr_ods_check(ds): feat.GetFieldAsDouble(3) != 0.52 or \ feat.GetFieldAsString(4) != '2012/01/22' or \ feat.GetFieldAsString(5) != '2012/01/22 18:49:00': - gdaltest.post_reason('fail') feat.DumpReadable() - return 'fail' + pytest.fail() feat = lyr.GetNextFeature() if feat.IsFieldSet(2): - gdaltest.post_reason('fail') feat.DumpReadable() - return 'fail' - - return 'success' + pytest.fail() + ############################################################################### # Basic tests -def ogr_ods_1(): +def test_ogr_ods_1(): drv = ogr.GetDriverByName('ODS') if drv is None: - return 'skip' + pytest.skip() - if drv.TestCapability("foo") != 0: - gdaltest.post_reason('fail') - return 'fail' + assert drv.TestCapability("foo") == 0 ds = ogr.Open('data/test.ods') - if ds is None: - gdaltest.post_reason('cannot open dataset') - return 'fail' + assert ds is not None, 'cannot open dataset' return ogr_ods_check(ds) @@ -148,60 +116,36 @@ def ogr_ods_1(): # Basic tests -def ogr_ods_kspread_1(): +def test_ogr_ods_kspread_1(): drv = ogr.GetDriverByName('ODS') if drv is None: - return 'skip' + pytest.skip() - if drv.TestCapability("foo") != 0: - gdaltest.post_reason('fail') - return 'fail' + assert drv.TestCapability("foo") == 0 ds = ogr.Open('data/test_kspread.ods') - if ds is None: - gdaltest.post_reason('cannot open dataset') - return 'fail' + assert ds is not None, 'cannot open dataset' - if ds.TestCapability("foo") != 0: - gdaltest.post_reason('fail') - return 'fail' + assert ds.TestCapability("foo") == 0 - if ds.GetLayerCount() != 8: - gdaltest.post_reason('bad layer count') - return 'fail' + assert ds.GetLayerCount() == 8, 'bad layer count' lyr = ds.GetLayer(0) - if lyr.GetName() != 'Feuille1': - gdaltest.post_reason('bad layer name') - return 'fail' + assert lyr.GetName() == 'Feuille1', 'bad layer name' - if lyr.GetGeomType() != ogr.wkbNone: - gdaltest.post_reason('bad layer geometry type') - return 'fail' + assert lyr.GetGeomType() == ogr.wkbNone, 'bad layer geometry type' - if lyr.GetSpatialRef() is not None: - gdaltest.post_reason('bad spatial ref') - return 'fail' + assert lyr.GetSpatialRef() is None, 'bad spatial ref' - if lyr.GetFeatureCount() != 26: - gdaltest.post_reason('fail') - print(lyr.GetFeatureCount()) - return 'fail' + assert lyr.GetFeatureCount() == 26 - if lyr.TestCapability("foo") != 0: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.TestCapability("foo") == 0 lyr = ds.GetLayer(6) - if lyr.GetName() != 'Feuille7': - gdaltest.post_reason('bad layer name') - return 'fail' + assert lyr.GetName() == 'Feuille7', 'bad layer name' - if lyr.GetLayerDefn().GetFieldCount() != 12: - gdaltest.post_reason('fail') - print(lyr.GetLayerDefn().GetFieldCount()) - return 'fail' + assert lyr.GetLayerDefn().GetFieldCount() == 12 type_array = [ogr.OFTString, ogr.OFTInteger, @@ -218,10 +162,7 @@ def ogr_ods_kspread_1(): ] for i, typ in enumerate(type_array): - if lyr.GetLayerDefn().GetFieldDefn(i).GetType() != typ: - gdaltest.post_reason('fail') - print(i) - return 'fail' + assert lyr.GetLayerDefn().GetFieldDefn(i).GetType() == typ feat = lyr.GetNextFeature() if feat.GetFieldAsString(0) != 'val' or \ @@ -230,100 +171,84 @@ def ogr_ods_kspread_1(): feat.GetFieldAsDouble(3) != 0.52 or \ feat.GetFieldAsString(4) != '2012/01/22' or \ feat.GetFieldAsString(5) != '22/01/2012 18:49:00': # 2012/01/22 18:49:00 - gdaltest.post_reason('fail') feat.DumpReadable() - return 'fail' + pytest.fail() feat = lyr.GetNextFeature() if feat.IsFieldSet(2): - gdaltest.post_reason('fail') feat.DumpReadable() - return 'fail' - - return 'success' + pytest.fail() + ############################################################################### # Test OGR_ODS_HEADERS = DISABLE -def ogr_ods_2(): +def test_ogr_ods_2(): drv = ogr.GetDriverByName('ODS') if drv is None: - return 'skip' + pytest.skip() gdal.SetConfigOption('OGR_ODS_HEADERS', 'DISABLE') ds = ogr.Open('data/test.ods') lyr = ds.GetLayerByName('Feuille7') - if lyr.GetFeatureCount() != 3: - gdaltest.post_reason('fail') - print(lyr.GetFeatureCount()) - return 'fail' + assert lyr.GetFeatureCount() == 3 gdal.SetConfigOption('OGR_ODS_HEADERS', None) - return 'success' - ############################################################################### # Test OGR_ODS_FIELD_TYPES = STRING -def ogr_ods_3(): +def test_ogr_ods_3(): drv = ogr.GetDriverByName('ODS') if drv is None: - return 'skip' + pytest.skip() gdal.SetConfigOption('OGR_ODS_FIELD_TYPES', 'STRING') ds = ogr.Open('data/test.ods') lyr = ds.GetLayerByName('Feuille7') - if lyr.GetLayerDefn().GetFieldDefn(1).GetType() != ogr.OFTString: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.GetLayerDefn().GetFieldDefn(1).GetType() == ogr.OFTString gdal.SetConfigOption('OGR_ODS_FIELD_TYPES', None) - return 'success' - ############################################################################### # Run test_ogrsf -def ogr_ods_4(): +def test_ogr_ods_4(): drv = ogr.GetDriverByName('ODS') if drv is None: - return 'skip' + pytest.skip() import test_cli_utilities if test_cli_utilities.get_test_ogrsf_path() is None: - return 'skip' + pytest.skip() ret = gdaltest.runexternal(test_cli_utilities.get_test_ogrsf_path() + ' -ro data/test.ods') - if ret.find('INFO') == -1 or ret.find('ERROR') != -1: - print(ret) - return 'fail' - - return 'success' + assert ret.find('INFO') != -1 and ret.find('ERROR') == -1 ############################################################################### # Test write support -def ogr_ods_5(): +def test_ogr_ods_5(): drv = ogr.GetDriverByName('ODS') if drv is None: - return 'skip' + pytest.skip() import test_cli_utilities if test_cli_utilities.get_ogr2ogr_path() is None: - return 'skip' + pytest.skip() gdaltest.runexternal(test_cli_utilities.get_ogr2ogr_path() + ' -f ODS tmp/test.ods data/test.ods') @@ -339,19 +264,17 @@ def ogr_ods_5(): # Test formula evaluation -def ogr_ods_6(): +def test_ogr_ods_6(): drv = ogr.GetDriverByName('ODS') if drv is None: - return 'skip' + pytest.skip() src_ds = ogr.Open('ODS:data/content_formulas.xml') filepath = '/vsimem/content_formulas.csv' with gdaltest.error_handler(): out_ds = ogr.GetDriverByName('CSV').CopyDataSource(src_ds, filepath) - if out_ds is None: - gdaltest.post_reason('Unable to create %s.' % filepath) - return 'fail' + assert out_ds is not None, ('Unable to create %s.' % filepath) out_ds = None src_ds = None @@ -376,21 +299,17 @@ def ogr_ods_6(): "0","0","0","0","0","0","0","0","0","0","0","0","0","0","0","0","0","0","0","0","0","0","0","0","0","0","0","0","0","0","0","0" """.split() - if res != expected_res: - gdaltest.post_reason('did not get expected result: %s' % res) - return 'fail' - - return 'success' + assert res == expected_res, ('did not get expected result: %s' % res) ############################################################################### # Test update support -def ogr_ods_7(): +def test_ogr_ods_7(): drv = ogr.GetDriverByName('ODS') if drv is None: - return 'skip' + pytest.skip() filepath = 'tmp/ogr_ods_7.ods' if os.path.exists(filepath): @@ -401,9 +320,8 @@ def ogr_ods_7(): lyr = ds.GetLayerByName('Feuille7') feat = lyr.GetNextFeature() if feat.GetFID() != 2: - gdaltest.post_reason('did not get expected FID') feat.DumpReadable() - return 'fail' + pytest.fail('did not get expected FID') feat.SetField(0, 'modified_value') lyr.SetFeature(feat) feat = None @@ -413,29 +331,25 @@ def ogr_ods_7(): lyr = ds.GetLayerByName('Feuille7') feat = lyr.GetNextFeature() if feat.GetFID() != 2: - gdaltest.post_reason('did not get expected FID') feat.DumpReadable() - return 'fail' + pytest.fail('did not get expected FID') if feat.GetField(0) != 'modified_value': - gdaltest.post_reason('did not get expected value') feat.DumpReadable() - return 'fail' + pytest.fail('did not get expected value') feat = None ds = None os.unlink(filepath) - return 'success' - ############################################################################### # Test Integer64 -def ogr_ods_8(): +def test_ogr_ods_8(): drv = ogr.GetDriverByName('ODS') if drv is None: - return 'skip' + pytest.skip() ds = drv.CreateDataSource('/vsimem/ogr_ods_8.ods') lyr = ds.CreateLayer('foo') @@ -454,29 +368,23 @@ def ogr_ods_8(): ds = ogr.Open('/vsimem/ogr_ods_8.ods') lyr = ds.GetLayer(0) - if lyr.GetLayerDefn().GetFieldDefn(0).GetType() != ogr.OFTInteger64: - gdaltest.post_reason('failure') - return 'fail' + assert lyr.GetLayerDefn().GetFieldDefn(0).GetType() == ogr.OFTInteger64 f = lyr.GetNextFeature() f = lyr.GetNextFeature() - if f.GetField(0) != 12345678901234: - gdaltest.post_reason('failure') - return 'fail' + assert f.GetField(0) == 12345678901234 ds = None gdal.Unlink('/vsimem/ogr_ods_8.ods') - return 'success' - ############################################################################### # Test DateTime with milliseconds -def ogr_ods_9(): +def test_ogr_ods_9(): drv = ogr.GetDriverByName('ODS') if drv is None: - return 'skip' + pytest.skip() ds = drv.CreateDataSource('/vsimem/ogr_ods_9.ods') lyr = ds.CreateLayer('foo') @@ -494,37 +402,30 @@ def ogr_ods_9(): ds = ogr.Open('/vsimem/ogr_ods_9.ods') lyr = ds.GetLayer(0) for i in range(3): - if lyr.GetLayerDefn().GetFieldDefn(i).GetType() != ogr.OFTDateTime: - gdaltest.post_reason('failure') - return 'fail' + assert lyr.GetLayerDefn().GetFieldDefn(i).GetType() == ogr.OFTDateTime f = lyr.GetNextFeature() if f.GetField(0) != '2015/12/23 12:34:56.789': - gdaltest.post_reason('failure') f.DumpReadable() - return 'fail' + pytest.fail() if f.GetField(1) != '2015/12/23 12:34:56': - gdaltest.post_reason('failure') f.DumpReadable() - return 'fail' + pytest.fail() if f.GetField(2) != '2015/12/23 12:34:56': - gdaltest.post_reason('failure') f.DumpReadable() - return 'fail' + pytest.fail() ds = None gdal.Unlink('/vsimem/ogr_ods_9.ods') - return 'success' - ############################################################################### # Test Boolean -def ogr_ods_boolean(): +def test_ogr_ods_boolean(): drv = ogr.GetDriverByName('ODS') if drv is None: - return 'skip' + pytest.skip() out_filename = '/vsimem/ogr_ods_boolean.ods' ds = drv.CreateDataSource(out_filename) @@ -543,45 +444,15 @@ def ogr_ods_boolean(): ds = ogr.Open(out_filename) lyr = ds.GetLayer(0) - if lyr.GetLayerDefn().GetFieldDefn(0).GetType() != ogr.OFTInteger: - gdaltest.post_reason('failure') - return 'fail' - if lyr.GetLayerDefn().GetFieldDefn(0).GetSubType() != ogr.OFSTBoolean: - gdaltest.post_reason('failure') - return 'fail' + assert lyr.GetLayerDefn().GetFieldDefn(0).GetType() == ogr.OFTInteger + assert lyr.GetLayerDefn().GetFieldDefn(0).GetSubType() == ogr.OFSTBoolean f = lyr.GetNextFeature() - if not f.GetField(0): - gdaltest.post_reason('failure') - return 'fail' + assert f.GetField(0) f = lyr.GetNextFeature() - if f.GetField(0): - gdaltest.post_reason('failure') - return 'fail' + assert not f.GetField(0) ds = None gdal.Unlink(out_filename) - return 'success' - - -gdaltest_list = [ - ogr_ods_1, - ogr_ods_kspread_1, - ogr_ods_2, - ogr_ods_3, - ogr_ods_4, - ogr_ods_5, - ogr_ods_6, - ogr_ods_7, - ogr_ods_8, - ogr_ods_9, - ogr_ods_boolean, -] - -if __name__ == '__main__': - - gdaltest.setup_run('ogr_ods') - gdaltest.run_tests(gdaltest_list) - sys.exit(gdaltest.summarize()) diff --git a/autotest/ogr/ogr_ogdi.py b/autotest/ogr/ogr_ogdi.py index 788879733076..dd890633f782 100755 --- a/autotest/ogr/ogr_ogdi.py +++ b/autotest/ogr/ogr_ogdi.py @@ -29,33 +29,31 @@ ############################################################################### import os -import sys from osgeo import ogr -sys.path.append('../pymod') import gdaltest import ogrtest +import pytest ############################################################################### -def ogr_ogdi_1(): +def test_ogr_ogdi_1(): ogrtest.ogdi_ds = None # Skip tests when -fsanitize is used because of memleaks in libogdi if gdaltest.is_travis_branch('sanitize'): - print('Skipping because of memory leaks in OGDI') ogrtest.ogdi_drv = None - return 'skip' + pytest.skip('Skipping because of memory leaks in OGDI') ogrtest.ogdi_drv = ogr.GetDriverByName('OGDI') if ogrtest.ogdi_drv is None: - return 'skip' + pytest.skip() if not gdaltest.download_file('http://freefr.dl.sourceforge.net/project/ogdi/OGDI_Test_Suite/3.1/ogdits-3.1.0.zip', 'ogdits-3.1.0.zip'): - return 'skip' + pytest.skip() try: os.stat('tmp/cache/ogdits-3.1') @@ -65,21 +63,16 @@ def ogr_ogdi_1(): try: os.stat('tmp/cache/ogdits-3.1') except OSError: - return 'skip' + pytest.skip() except OSError: - return 'skip' + pytest.skip() url_name = 'gltp:/vrf/' + os.getcwd() + '/tmp/cache/ogdits-3.1/data/vpf/vm2alv2/texash' ds = ogr.Open(url_name) ogrtest.ogdi_ds = ds - if ds is None: - gdaltest.post_reason('cannot open ' + url_name) - return 'fail' - if ds.GetLayerCount() != 57: - print(ds.GetLayerCount()) - gdaltest.post_reason('did not get expected layer count') - return 'fail' + assert ds is not None, ('cannot open ' + url_name) + assert ds.GetLayerCount() == 57, 'did not get expected layer count' layers = [('libref@libref(*)_line', ogr.wkbLineString, 15), ('libreft@libref(*)_text', ogr.wkbPoint, 4), @@ -88,11 +81,8 @@ def ogr_ogdi_1(): for l in layers: lyr = ds.GetLayerByName(l[0]) - if lyr.GetLayerDefn().GetGeomType() != l[1]: - return 'fail' - if lyr.GetFeatureCount() != l[2]: - print(lyr.GetFeatureCount()) - return 'fail' + assert lyr.GetLayerDefn().GetGeomType() == l[1] + assert lyr.GetFeatureCount() == l[2] # if l[1] != ogr.wkbNone: # if lyr.GetSpatialRef().ExportToWkt().find('WGS 84') == -1: # return 'fail' @@ -103,43 +93,36 @@ def ogr_ogdi_1(): wkt = 'LINESTRING (-97.570159912109375 31.242000579833984,-97.569938659667969 31.242116928100586,-97.562828063964844 31.245765686035156,-97.558868408203125 31.247797012329102,-97.555778503417969 31.249361038208008,-97.55413818359375 31.250171661376953)' ref_geom = ogr.CreateGeometryFromWkt(wkt) - if ogrtest.check_feature_geometry(feat, ref_geom) != 0: - print(feat.GetGeometryRef().ExportToWkt()) - return 'fail' - - return 'success' + assert ogrtest.check_feature_geometry(feat, ref_geom) == 0, \ + feat.GetGeometryRef().ExportToWkt() ############################################################################### # Run test_ogrsf -def ogr_ogdi_2(): +def test_ogr_ogdi_2(): if ogrtest.ogdi_ds is None: - return 'skip' + pytest.skip() import test_cli_utilities if test_cli_utilities.get_test_ogrsf_path() is None: - return 'skip' + pytest.skip() url_name = 'gltp:/vrf/' + os.getcwd() + '/tmp/cache/ogdits-3.1/data/vpf/vm2alv2/texash' ret = gdaltest.runexternal(test_cli_utilities.get_test_ogrsf_path() + ' --config OGR_OGDI_LAUNDER_LAYER_NAMES YES -ro "' + url_name + '" markersp_bnd contourl_elev polbnda_bnd extractp_ind') - if ret.find('INFO') == -1 or ret.find('ERROR') != -1: - print(ret) - return 'fail' - - return 'success' + assert ret.find('INFO') != -1 and ret.find('ERROR') == -1 ############################################################################### # Test GetFeature() -def ogr_ogdi_3(): +def test_ogr_ogdi_3(): if ogrtest.ogdi_ds is None: - return 'skip' + pytest.skip() lyr0 = ogrtest.ogdi_ds.GetLayer(0) lyr0.ResetReading() @@ -158,134 +141,86 @@ def ogr_ogdi_3(): feat10 = lyr1.GetFeature(0) feat11 = lyr1.GetFeature(1) - if not feat00.Equal(feat00_ref): - gdaltest.post_reason('features not equal') - return 'fail' + assert feat00.Equal(feat00_ref), 'features not equal' - if not feat01.Equal(feat01_ref): - gdaltest.post_reason('features not equal') - return 'fail' + assert feat01.Equal(feat01_ref), 'features not equal' - if not feat02.Equal(feat02_ref): - gdaltest.post_reason('features not equal') - return 'fail' + assert feat02.Equal(feat02_ref), 'features not equal' - if not feat10.Equal(feat10_ref): - gdaltest.post_reason('features not equal') - return 'fail' + assert feat10.Equal(feat10_ref), 'features not equal' - if not feat11.Equal(feat11_ref): - gdaltest.post_reason('features not equal') - return 'fail' - - return 'success' + assert feat11.Equal(feat11_ref), 'features not equal' ############################################################################### # Extract of full dataset -def ogr_ogdi_4(): +def test_ogr_ogdi_4(): if ogrtest.ogdi_drv is None: - return 'skip' + pytest.skip() url_name = 'gltp:/vrf/' + os.getcwd() + '/data/vm2alv2_texash/texash' ds = ogr.Open(url_name) - if ds is None: - gdaltest.post_reason('cannot open dataset') - return 'fail' + assert ds is not None, 'cannot open dataset' - if ds.GetLayerCount() != 6: - print(ds.GetLayerCount()) - gdaltest.post_reason('did not get expected layer count') - return 'fail' + assert ds.GetLayerCount() == 6, 'did not get expected layer count' layers = [('polbnda@bnd(*)_area', ogr.wkbPolygon, 6)] for l in layers: lyr = ds.GetLayerByName(l[0]) - if lyr.GetLayerDefn().GetGeomType() != l[1]: - return 'fail' - if lyr.GetFeatureCount() != l[2]: - print(lyr.GetFeatureCount()) - return 'fail' + assert lyr.GetLayerDefn().GetGeomType() == l[1] + assert lyr.GetFeatureCount() == l[2] lyr = ds.GetLayerByName('polbnda@bnd(*)_area') feat = lyr.GetNextFeature() if feat['id'] != 1 or feat['f_code'] != 'FA001' or feat['acc'] != 1: - gdaltest.post_reason('bad attributes') feat.DumpReadable() - return 'fail' + pytest.fail('bad attributes') wkt = 'POLYGON ((-97.6672973632812 31.250171661377,-97.5832977294922 31.250171661377,-97.5780029296875 31.250171661377,-97.5780029296875 31.250171661377,-97.5780944824219 31.2494583129883,-97.5779724121094 31.2492084503174,-97.577751159668 31.24880027771,-97.5776443481445 31.2484683990479,-97.5775451660156 31.2482070922852,-97.5774078369141 31.2479457855225,-97.5772705078125 31.2477989196777,-97.5771331787109 31.2477321624756,-97.5768661499023 31.2476787567139,-97.5766830444336 31.2476959228516,-97.5763168334961 31.2477016448975,-97.576042175293 31.247673034668,-97.5757141113281 31.2475509643555,-97.5754852294922 31.2473278045654,-97.5752792358398 31.2470207214356,-97.5751190185547 31.2467250823975,-97.5750122070312 31.2465076446533,-97.5748443603516 31.2462825775147,-97.5746002197266 31.2460918426514,-97.5742874145508 31.2459144592285,-97.5739288330078 31.2458171844482,-97.5736083984375 31.2457542419434,-97.5731201171875 31.2456817626953,-97.5728302001953 31.245641708374,-97.5724792480469 31.2455806732178,-97.5721817016602 31.2454471588135,-97.5719223022461 31.2453022003174,-97.5717086791992 31.2450218200684,-97.5715408325195 31.2446899414062,-97.5713882446289 31.2445201873779,-97.5711669921875 31.2442722320557,-97.5710678100586 31.2440910339355,-97.5711975097656 31.2438926696777,-97.5713577270508 31.2437191009521,-97.5718154907227 31.2434253692627,-97.5724258422852 31.2431831359863,-97.5726470947266 31.2430419921875,-97.5728530883789 31.2427291870117,-97.5728759765625 31.2424869537354,-97.57275390625 31.2423858642578,-97.5727996826172 31.2423534393311,-97.5712738037109 31.2422771453857,-97.5710067749023 31.2422466278076,-97.5707092285156 31.2421951293945,-97.5702285766602 31.2420444488525,-97.5701599121094 31.242000579834,-97.5701599121094 31.242000579834,-97.5794296264648 31.2372093200684,-97.5909194946289 31.2314224243164,-97.6050415039062 31.2241363525391,-97.6213302612305 31.2157878875732,-97.6490707397461 31.201566696167,-97.6662445068359 31.1928386688232,-97.6803207397461 31.1855792999268,-97.6936721801758 31.1787204742432,-97.7042617797852 31.1732997894287,-97.7107391357422 31.1699485778809,-97.7178192138672 31.1663246154785,-97.7325134277344 31.1587982177734,-97.7502975463867 31.1499614715576,-97.7502975463867 31.1499614715576,-97.7502975463867 31.1671733856201,-97.7502975463867 31.1671733856201,-97.7502975463867 31.250171661377,-97.6672973632812 31.250171661377))' ref_geom = ogr.CreateGeometryFromWkt(wkt) - if ogrtest.check_feature_geometry(feat, ref_geom) != 0: - print(feat.GetGeometryRef().ExportToWkt()) - return 'fail' + assert ogrtest.check_feature_geometry(feat, ref_geom) == 0, \ + feat.GetGeometryRef().ExportToWkt() ds = None # Test opening one single layer ds = ogr.Open(url_name + ':polbnda@bnd(*):area') - if ds is None: - gdaltest.post_reason('cannot open dataset') - return 'fail' - if ds.GetLayerCount() != 1: - print(ds.GetLayerCount()) - gdaltest.post_reason('did not get expected layer count') - return 'fail' - - return 'success' + assert ds is not None, 'cannot open dataset' + assert ds.GetLayerCount() == 1, 'did not get expected layer count' ############################################################################### # Run test_ogrsf -def ogr_ogdi_5(): +def test_ogr_ogdi_5(): if ogrtest.ogdi_drv is None: - return 'skip' + pytest.skip() import test_cli_utilities if test_cli_utilities.get_test_ogrsf_path() is None: - return 'skip' + pytest.skip() url_name = 'gltp:/vrf/' + os.getcwd() + '/data/vm2alv2_texash/texash' ret = gdaltest.runexternal(test_cli_utilities.get_test_ogrsf_path() + ' --config OGR_OGDI_LAUNDER_LAYER_NAMES YES -ro "' + url_name + '"') - if ret.find('INFO') == -1 or ret.find('ERROR') != -1: - print(ret) - return 'fail' - - return 'success' + assert ret.find('INFO') != -1 and ret.find('ERROR') == -1 ############################################################################### -def ogr_ogdi_cleanup(): +def test_ogr_ogdi_cleanup(): if ogrtest.ogdi_ds is None: - return 'skip' + pytest.skip() ogrtest.ogdi_ds = None - return 'success' - - -gdaltest_list = [ - ogr_ogdi_1, - ogr_ogdi_2, - ogr_ogdi_3, - ogr_ogdi_4, - ogr_ogdi_5, - ogr_ogdi_cleanup] - -if __name__ == '__main__': - gdaltest.setup_run('ogr_ogdi') - gdaltest.run_tests(gdaltest_list) - sys.exit(gdaltest.summarize()) diff --git a/autotest/ogr/ogr_openair.py b/autotest/ogr/ogr_openair.py index 63957daafce9..6dec943a0a7a 100755 --- a/autotest/ogr/ogr_openair.py +++ b/autotest/ogr/ogr_openair.py @@ -28,29 +28,23 @@ # DEALINGS IN THE SOFTWARE. ############################################################################### -import sys -sys.path.append('../pymod') -import gdaltest import ogrtest from osgeo import ogr +import pytest ############################################################################### # Basic test -def ogr_openair_1(): +def test_ogr_openair_1(): ds = ogr.Open('data/openair_test.txt') - if ds is None: - gdaltest.post_reason('cannot open dataset') - return 'fail' + assert ds is not None, 'cannot open dataset' lyr = ds.GetLayerByName('airspaces') - if lyr is None: - gdaltest.post_reason('cannot find layer airspaces') - return 'fail' + assert lyr is not None, 'cannot find layer airspaces' feat = lyr.GetNextFeature() feat = lyr.GetNextFeature() @@ -59,37 +53,21 @@ def ogr_openair_1(): if ogrtest.check_feature_geometry(feat, 'POLYGON ((49.75 2.75,49.75 3.0,49.5 3.0,49.5 2.75,49.75 2.75))', max_error=0.0000001) != 0: print('did not get expected first geom') - print(geom.ExportToWkt()) - return 'fail' + pytest.fail(geom.ExportToWkt()) style = feat.GetStyleString() - if style != 'PEN(c:#0000FF,w:2pt,p:"5px 5px");BRUSH(fc:#00FF00)': - print('did not get expected style') - print(style) - return 'fail' + assert style == 'PEN(c:#0000FF,w:2pt,p:"5px 5px");BRUSH(fc:#00FF00)', \ + 'did not get expected style' lyr = ds.GetLayerByName('labels') - if lyr is None: - gdaltest.post_reason('cannot find layer labels') - return 'fail' + assert lyr is not None, 'cannot find layer labels' feat = lyr.GetNextFeature() geom = feat.GetGeometryRef() if ogrtest.check_feature_geometry(feat, 'POINT (49.2625 2.504166666666667)', max_error=0.0000001) != 0: print('did not get expected geom on labels layer') - print(geom.ExportToWkt()) - return 'fail' + pytest.fail(geom.ExportToWkt()) - return 'success' + -gdaltest_list = [ - ogr_openair_1] - -if __name__ == '__main__': - - gdaltest.setup_run('ogr_openair') - - gdaltest.run_tests(gdaltest_list) - - sys.exit(gdaltest.summarize()) diff --git a/autotest/ogr/ogr_openfilegdb.py b/autotest/ogr/ogr_openfilegdb.py index b7aeca15d457..cf943e773053 100755 --- a/autotest/ogr/ogr_openfilegdb.py +++ b/autotest/ogr/ogr_openfilegdb.py @@ -33,13 +33,13 @@ import sys import shutil -sys.path.append('../pymod') import gdaltest import ogrtest from osgeo import gdal from osgeo import ogr from osgeo import osr +import pytest ogrtest.openfilegdb_datalist = [["none", ogr.wkbNone, None], ["point", ogr.wkbPoint, "POINT (1 2)"], @@ -82,14 +82,13 @@ ############################################################################### # Disable FileGDB driver -def ogr_openfilegdb_init(): +def test_ogr_openfilegdb_init(): ogrtest.fgdb_drv = ogr.GetDriverByName('FileGDB') if ogrtest.fgdb_drv is not None: ogrtest.fgdb_drv.Deregister() - return 'success' - + ############################################################################### # Make test data @@ -264,13 +263,11 @@ def ogr_openfilegdb_make_test_data(): os.chdir('..') shutil.rmtree('data/testopenfilegdb.gdb') - return 'success' - ############################################################################### # Basic tests -def ogr_openfilegdb_1(filename='data/testopenfilegdb.gdb.zip', version10=True): +def test_ogr_openfilegdb_1(filename='data/testopenfilegdb.gdb.zip', version10=True): srs = osr.SpatialReference() srs.SetFromUserInput("WGS84") @@ -293,28 +290,13 @@ def ogr_openfilegdb_1(filename='data/testopenfilegdb.gdb.zip', version10=True): expected_geom_type = ogr.wkbMultiPolygon elif expected_geom_type == ogr.wkbPolygon25D: expected_geom_type = ogr.wkbMultiPolygon25D - if lyr.GetGeomType() != expected_geom_type: - gdaltest.post_reason('fail') - print(lyr.GetName()) - print(lyr.GetGeomType()) - return 'fail' - if expected_geom_type is not ogr.wkbNone and lyr.GetLayerDefn().GetGeomFieldDefn(0).IsNullable() != 1: - gdaltest.post_reason('fail') - return 'fail' - if lyr.GetLayerDefn().GetFieldDefn(lyr.GetLayerDefn().GetFieldIndex('str')).GetWidth() != 0: - gdaltest.post_reason('fail') - return 'fail' - if lyr.GetLayerDefn().GetFieldDefn(lyr.GetLayerDefn().GetFieldIndex('smallint')).GetSubType() != ogr.OFSTInt16: - gdaltest.post_reason('fail') - return 'fail' - if lyr.GetLayerDefn().GetFieldDefn(lyr.GetLayerDefn().GetFieldIndex('float')).GetSubType() != ogr.OFSTFloat32: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.GetGeomType() == expected_geom_type, lyr.GetName() + assert expected_geom_type is ogr.wkbNone or lyr.GetLayerDefn().GetGeomFieldDefn(0).IsNullable() == 1 + assert lyr.GetLayerDefn().GetFieldDefn(lyr.GetLayerDefn().GetFieldIndex('str')).GetWidth() == 0 + assert lyr.GetLayerDefn().GetFieldDefn(lyr.GetLayerDefn().GetFieldIndex('smallint')).GetSubType() == ogr.OFSTInt16 + assert lyr.GetLayerDefn().GetFieldDefn(lyr.GetLayerDefn().GetFieldIndex('float')).GetSubType() == ogr.OFSTFloat32 if data[1] != ogr.wkbNone: - if lyr.GetSpatialRef().IsSame(srs) != 1: - gdaltest.post_reason('fail') - print(lyr.GetSpatialRef()) - return 'fail' + assert lyr.GetSpatialRef().IsSame(srs) == 1 feat = lyr.GetNextFeature() if data[1] != ogr.wkbNone: try: @@ -325,10 +307,8 @@ def ogr_openfilegdb_1(filename='data/testopenfilegdb.gdb.zip', version10=True): if geom: geom = geom.ExportToWkt() if geom != expected_wkt and ogrtest.check_feature_geometry(feat, expected_wkt) == 1: - gdaltest.post_reason('fail') feat.DumpReadable() - print(expected_wkt) - return 'fail' + pytest.fail(expected_wkt) if feat.GetField('id') != 1 or \ feat.GetField('smallint') != -13 or \ @@ -340,47 +320,32 @@ def ogr_openfilegdb_1(filename='data/testopenfilegdb.gdb.zip', version10=True): (version10 and feat.GetField('xml') != "<foo></foo>") or \ feat.GetField('binary') != "00FF7F" or \ feat.GetField('binary2') != "123456": - gdaltest.post_reason('fail') feat.DumpReadable() - return 'fail' + pytest.fail() if version10: sql_lyr = ds.ExecuteSQL("GetLayerDefinition %s" % lyr.GetName()) - if sql_lyr is None: - gdaltest.post_reason('failure') - return 'fail' + assert sql_lyr is not None feat = sql_lyr.GetNextFeature() - if feat is None: - gdaltest.post_reason('failure') - return 'fail' + assert feat is not None feat = sql_lyr.GetNextFeature() - if feat is not None: - gdaltest.post_reason('failure') - return 'fail' + assert feat is None lyr.ResetReading() lyr.TestCapability("foo") ds.ReleaseResultSet(sql_lyr) sql_lyr = ds.ExecuteSQL("GetLayerMetadata %s" % lyr.GetName()) - if sql_lyr is None: - gdaltest.post_reason('failure') - return 'fail' + assert sql_lyr is not None feat = sql_lyr.GetNextFeature() - if feat is None: - gdaltest.post_reason('failure') - return 'fail' + assert feat is not None ds.ReleaseResultSet(sql_lyr) if version10: sql_lyr = ds.ExecuteSQL("GetLayerDefinition foo") - if sql_lyr is not None: - gdaltest.post_reason('failure') - return 'fail' + assert sql_lyr is None sql_lyr = ds.ExecuteSQL("GetLayerMetadata foo") - if sql_lyr is not None: - gdaltest.post_reason('failure') - return 'fail' + assert sql_lyr is None if version10: for data in ogrtest.openfilegdb_datalist_m: @@ -395,11 +360,7 @@ def ogr_openfilegdb_1(filename='data/testopenfilegdb.gdb.zip', version10=True): elif expected_geom_type == ogr.wkbPolygonZM: expected_geom_type = ogr.wkbMultiPolygonZM - if lyr.GetGeomType() != expected_geom_type: - gdaltest.post_reason('fail') - print(data) - print(lyr.GetGeomType()) - return 'fail' + assert lyr.GetGeomType() == expected_geom_type, data feat = lyr.GetNextFeature() try: expected_wkt = data[3] @@ -407,92 +368,70 @@ def ogr_openfilegdb_1(filename='data/testopenfilegdb.gdb.zip', version10=True): expected_wkt = data[2] if expected_wkt is None: if feat.GetGeometryRef() is not None: - gdaltest.post_reason('fail') - print(data) feat.DumpReadable() - return 'fail' + pytest.fail(data) elif ogrtest.check_feature_geometry(feat, expected_wkt) != 0: - gdaltest.post_reason('fail') - print(data) feat.DumpReadable() - return 'fail' + pytest.fail(data) ds = None - return 'success' - -def ogr_openfilegdb_1_92(): - return ogr_openfilegdb_1(filename='data/testopenfilegdb92.gdb.zip', version10=False) +def test_ogr_openfilegdb_1_92(): + return test_ogr_openfilegdb_1(filename='data/testopenfilegdb92.gdb.zip', version10=False) -def ogr_openfilegdb_1_93(): - return ogr_openfilegdb_1(filename='data/testopenfilegdb93.gdb.zip', version10=False) +def test_ogr_openfilegdb_1_93(): + return test_ogr_openfilegdb_1(filename='data/testopenfilegdb93.gdb.zip', version10=False) ############################################################################### # Run test_ogrsf -def ogr_openfilegdb_2(filename='data/testopenfilegdb.gdb.zip'): +def test_ogr_openfilegdb_2(filename='data/testopenfilegdb.gdb.zip'): import test_cli_utilities if test_cli_utilities.get_test_ogrsf_path() is None: - return 'skip' + pytest.skip() ret = gdaltest.runexternal(test_cli_utilities.get_test_ogrsf_path() + ' -ro ' + filename) - if ret.find('INFO') == -1 or ret.find('ERROR') != -1: - print(ret) - return 'fail' + assert ret.find('INFO') != -1 and ret.find('ERROR') == -1 - return 'success' +def test_ogr_openfilegdb_2_92(): + return test_ogr_openfilegdb_2(filename='data/testopenfilegdb92.gdb.zip') -def ogr_openfilegdb_2_92(): - return ogr_openfilegdb_2(filename='data/testopenfilegdb92.gdb.zip') - -def ogr_openfilegdb_2_93(): - return ogr_openfilegdb_2(filename='data/testopenfilegdb93.gdb.zip') +def test_ogr_openfilegdb_2_93(): + return test_ogr_openfilegdb_2(filename='data/testopenfilegdb93.gdb.zip') ############################################################################### # Open a .gdbtable directly -def ogr_openfilegdb_3(): +def test_ogr_openfilegdb_3(): ds = ogr.Open('/vsizip/data/testopenfilegdb.gdb.zip/testopenfilegdb.gdb/a00000009.gdbtable') - if ds.GetLayerCount() != 1: - gdaltest.post_reason('fail') - return 'fail' + assert ds.GetLayerCount() == 1 lyr = ds.GetLayer(0) - if lyr.GetName() != 'none': - gdaltest.post_reason('fail') - return 'fail' + assert lyr.GetName() == 'none' # Try opening a system table lyr = ds.GetLayerByName('GDB_SystemCatalog') - if lyr.GetName() != 'GDB_SystemCatalog': - gdaltest.post_reason('fail') - return 'fail' + assert lyr.GetName() == 'GDB_SystemCatalog' feat = lyr.GetNextFeature() - if feat.GetField('Name') != 'GDB_SystemCatalog': - gdaltest.post_reason('fail') - return 'fail' + assert feat.GetField('Name') == 'GDB_SystemCatalog' lyr = ds.GetLayerByName('GDB_SystemCatalog') - if lyr.GetName() != 'GDB_SystemCatalog': - gdaltest.post_reason('fail') - return 'fail' + assert lyr.GetName() == 'GDB_SystemCatalog' ds = None - return 'success' - ############################################################################### # Test use of attribute indexes -def ogr_openfilegdb_4(): +def test_ogr_openfilegdb_4(): ds = ogr.Open('/vsizip/data/testopenfilegdb.gdb.zip/testopenfilegdb.gdb') @@ -612,27 +551,14 @@ def ogr_openfilegdb_4(): sql_lyr = ds.ExecuteSQL('GetLayerAttrIndexUse %s' % lyr.GetName()) attr_index_use = int(sql_lyr.GetNextFeature().GetField(0)) ds.ReleaseResultSet(sql_lyr) - if attr_index_use != expected_attr_index_use: - print(where_clause, fids, expected_attr_index_use) - print(attr_index_use) - gdaltest.post_reason('fail') - return 'fail' - if lyr.GetFeatureCount() != len(fids): - print(where_clause, fids) - print(lyr.GetFeatureCount()) - gdaltest.post_reason('fail') - return 'fail' + assert attr_index_use == expected_attr_index_use, \ + (where_clause, fids, expected_attr_index_use) + assert lyr.GetFeatureCount() == len(fids), (where_clause, fids) for fid in fids: feat = lyr.GetNextFeature() - if feat.GetFID() != fid: - print(where_clause, fids) - gdaltest.post_reason('fail') - return 'fail' + assert feat.GetFID() == fid, (where_clause, fids) feat = lyr.GetNextFeature() - if feat is not None: - print(where_clause, fids) - gdaltest.post_reason('fail') - return 'fail' + assert feat is None, (where_clause, fids) lyr = ds.GetLayerByName('none') tests = [('id = 1', [1]), @@ -654,27 +580,14 @@ def ogr_openfilegdb_4(): sql_lyr = ds.ExecuteSQL('GetLayerAttrIndexUse %s' % lyr.GetName()) attr_index_use = int(sql_lyr.GetNextFeature().GetField(0)) ds.ReleaseResultSet(sql_lyr) - if attr_index_use != expected_attr_index_use: - print(where_clause, fids, expected_attr_index_use) - print(attr_index_use) - gdaltest.post_reason('fail') - return 'fail' - if lyr.GetFeatureCount() != len(fids): - print(where_clause, fids) - print(lyr.GetFeatureCount()) - gdaltest.post_reason('fail') - return 'fail' + assert attr_index_use == expected_attr_index_use, \ + (where_clause, fids, expected_attr_index_use) + assert lyr.GetFeatureCount() == len(fids), (where_clause, fids) for fid in fids: feat = lyr.GetNextFeature() - if feat.GetFID() != fid: - print(where_clause, fids) - gdaltest.post_reason('fail') - return 'fail' + assert feat.GetFID() == fid, (where_clause, fids) feat = lyr.GetNextFeature() - if feat is not None: - print(where_clause, fids) - gdaltest.post_reason('fail') - return 'fail' + assert feat is None, (where_clause, fids) lyr = ds.GetLayerByName('big_layer') tests = [('real = 0', 86, 1), @@ -689,33 +602,22 @@ def ogr_openfilegdb_4(): for (where_clause, count, start) in tests: lyr.SetAttributeFilter(where_clause) - if lyr.GetFeatureCount() != count: - print(where_clause, count) - print(lyr.GetFeatureCount()) - gdaltest.post_reason('fail') - return 'fail' + assert lyr.GetFeatureCount() == count, (where_clause, count) for i in range(count): feat = lyr.GetNextFeature() - if feat is None or \ + assert (not (feat is None or \ (start is not None and - feat.GetFID() != i * 4 + start): - print(where_clause, count) - gdaltest.post_reason('fail') - return 'fail' + feat.GetFID() != i * 4 + start))), (where_clause, count) feat = lyr.GetNextFeature() - if feat is not None: - print(where_clause, count) - gdaltest.post_reason('fail') - return 'fail' + assert feat is None, (where_clause, count) ds = None - return 'success' ############################################################################### # Test opening an unzipped dataset -def ogr_openfilegdb_5(): +def test_ogr_openfilegdb_5(): try: shutil.rmtree('tmp/testopenfilegdb.gdb') @@ -724,32 +626,27 @@ def ogr_openfilegdb_5(): try: gdaltest.unzip('tmp/', 'data/testopenfilegdb.gdb.zip') except OSError: - return 'skip' + pytest.skip() try: os.stat('tmp/testopenfilegdb.gdb') except OSError: - return 'skip' + pytest.skip() ds = ogr.Open('tmp/testopenfilegdb.gdb') - if ds is None: - gdaltest.post_reason('fail') - return 'fail' - - return 'success' + assert ds is not None ############################################################################### # Test special SQL processing for min/max/count/sum/avg values -def ogr_openfilegdb_6(): +def test_ogr_openfilegdb_6(): ds = ogr.Open('data/testopenfilegdb.gdb.zip') # With indices sql_lyr = ds.ExecuteSQL("select min(id), max(id), count(id), sum(id), avg(id), min(str), min(smallint), " "avg(smallint), min(float), avg(float), min(real), avg(real), min(adate), avg(adate), min(guid), min(nullint), avg(nullint) from point") - if sql_lyr is None: - return 'fail' + assert sql_lyr is not None feat = sql_lyr.GetNextFeature() if feat.GetField('MIN_id') != 1 or \ feat.GetField('MAX_id') != 5 or \ @@ -770,7 +667,7 @@ def ogr_openfilegdb_6(): feat.IsFieldSet('AVG_nullint'): feat.DumpReadable() ds.ReleaseResultSet(sql_lyr) - return 'fail' + pytest.fail() ds.ReleaseResultSet(sql_lyr) # No index @@ -780,16 +677,14 @@ def ogr_openfilegdb_6(): feat.GetField('AVG_id') != 3.0: feat.DumpReadable() ds.ReleaseResultSet(sql_lyr) - return 'fail' + pytest.fail() ds.ReleaseResultSet(sql_lyr) - return 'success' - ############################################################################### # Test special SQL processing for ORDER BY -def ogr_openfilegdb_7(): +def test_ogr_openfilegdb_7(): ds = ogr.Open('data/testopenfilegdb.gdb.zip') @@ -825,54 +720,38 @@ def ogr_openfilegdb_7(): if expected_optimized is None: if sql_lyr is not None: ds.ReleaseResultSet(sql_lyr) - print(sql, feat_count, first_fid) - gdaltest.post_reason('fail') - return 'fail' + pytest.fail(sql, feat_count, first_fid) continue - if sql_lyr is None: - print(sql, feat_count, first_fid) - gdaltest.post_reason('fail') - return 'fail' + assert sql_lyr is not None, (sql, feat_count, first_fid) if expected_optimized: if sql_lyr.GetFeatureCount() != feat_count: - print(sql, feat_count, first_fid) ds.ReleaseResultSet(sql_lyr) - gdaltest.post_reason('fail') - return 'fail' + pytest.fail(sql, feat_count, first_fid) feat = sql_lyr.GetNextFeature() if feat.GetFID() != first_fid: - print(sql, feat_count, first_fid) ds.ReleaseResultSet(sql_lyr) feat.DumpReadable() - gdaltest.post_reason('fail') - return 'fail' + pytest.fail(sql, feat_count, first_fid) ds.ReleaseResultSet(sql_lyr) sql_lyr = ds.ExecuteSQL('GetLastSQLUsedOptimizedImplementation') optimized = int(sql_lyr.GetNextFeature().GetField(0)) ds.ReleaseResultSet(sql_lyr) - if optimized != expected_optimized: - print(sql, feat_count, first_fid) - gdaltest.post_reason('fail') - return 'fail' + assert optimized == expected_optimized, (sql, feat_count, first_fid) if optimized and sql.find('big_layer') < 0: import test_cli_utilities if test_cli_utilities.get_test_ogrsf_path() is not None: ret = gdaltest.runexternal(test_cli_utilities.get_test_ogrsf_path() + ' -ro data/testopenfilegdb.gdb.zip -sql "%s"' % sql) - if ret.find('INFO') == -1 or ret.find('ERROR') != -1: - print(sql, feat_count, first_fid) - print(ret) - gdaltest.post_reason('fail') - return 'fail' - - return 'success' + assert ret.find('INFO') != -1 and ret.find('ERROR') == -1, \ + (sql, feat_count, first_fid) + ############################################################################### # Test reading a .gdbtable without .gdbtablx -def ogr_openfilegdb_8(): +def test_ogr_openfilegdb_8(): ds = ogr.Open('data/testopenfilegdb.gdb.zip') dict_feat_count = {} @@ -889,10 +768,7 @@ def ogr_openfilegdb_8(): dict_feat_count2[lyr.GetName()] = lyr.GetFeatureCount() gdal.SetConfigOption('OPENFILEGDB_IGNORE_GDBTABLX', None) - if dict_feat_count != dict_feat_count2: - print(dict_feat_count) - print(dict_feat_count2) - return 'fail' + assert dict_feat_count == dict_feat_count2 lyr = ds.GetLayerByName('hole') # Not exactly in the order that one might expect, but logical when @@ -903,34 +779,29 @@ def ogr_openfilegdb_8(): while feat is not None: if feat.GetField('str') != expected_str[i]: feat.DumpReadable() - return 'fail' + pytest.fail() i = i + 1 feat = lyr.GetNextFeature() - return 'success' - + ############################################################################### # Test reading a .gdbtable outside a .gdb -def ogr_openfilegdb_9(): +def test_ogr_openfilegdb_9(): try: os.stat('tmp/testopenfilegdb.gdb') except OSError: - return 'skip' + pytest.skip() shutil.copy('tmp/testopenfilegdb.gdb/a00000009.gdbtable', 'tmp/a00000009.gdbtable') shutil.copy('tmp/testopenfilegdb.gdb/a00000009.gdbtablx', 'tmp/a00000009.gdbtablx') ds = ogr.Open('tmp/a00000009.gdbtable') - if ds is None: - return 'fail' + assert ds is not None lyr = ds.GetLayer(0) feat = lyr.GetNextFeature() - if feat is None: - return 'fail' - - return 'success' + assert feat is not None ############################################################################### # Test various error conditions @@ -960,12 +831,12 @@ def unfuzz(backup): f.close() -def ogr_openfilegdb_10(): +def test_ogr_openfilegdb_10(): try: os.stat('tmp/testopenfilegdb.gdb') except OSError: - return 'skip' + pytest.skip() shutil.copytree('tmp/testopenfilegdb.gdb', 'tmp/testopenfilegdb_fuzzed.gdb') @@ -1099,8 +970,7 @@ def ogr_openfilegdb_10(): gdal.PopErrorHandler() unfuzz(backup) - return 'success' - + ############################################################################### # Test spatial filtering @@ -1117,41 +987,27 @@ def get_spi_state(ds, lyr): return value -def ogr_openfilegdb_11(): +def test_ogr_openfilegdb_11(): # Test building spatial index with GetFeatureCount() ds = ogr.Open('data/testopenfilegdb.gdb.zip') lyr = ds.GetLayerByName('several_polygons') - if get_spi_state(ds, lyr) != SPI_IN_BUILDING: - gdaltest.post_reason('failure') - return 'fail' + assert get_spi_state(ds, lyr) == SPI_IN_BUILDING lyr.ResetReading() - if get_spi_state(ds, lyr) != SPI_IN_BUILDING: - gdaltest.post_reason('failure') - return 'fail' - if lyr.TestCapability(ogr.OLCFastFeatureCount) != 1: - gdaltest.post_reason('failure') - return 'fail' + assert get_spi_state(ds, lyr) == SPI_IN_BUILDING + assert lyr.TestCapability(ogr.OLCFastFeatureCount) == 1 lyr.SetSpatialFilterRect(0.25, 0.25, 0.5, 0.5) - if lyr.GetFeatureCount() != 1: - gdaltest.post_reason('failure') - return 'fail' - if get_spi_state(ds, lyr) != SPI_COMPLETED: - gdaltest.post_reason('failure') - return 'fail' + assert lyr.GetFeatureCount() == 1 + assert get_spi_state(ds, lyr) == SPI_COMPLETED # Should return cached value - if lyr.GetFeatureCount() != 1: - gdaltest.post_reason('failure') - return 'fail' + assert lyr.GetFeatureCount() == 1 # Should use index c = 0 feat = lyr.GetNextFeature() while feat is not None: c = c + 1 feat = lyr.GetNextFeature() - if c != 1: - gdaltest.post_reason('failure') - return 'fail' + assert c == 1 feat = None lyr = None ds = None @@ -1162,18 +1018,12 @@ def ogr_openfilegdb_11(): lyr.SetSpatialFilterRect(0.25, 0.25, 0.5, 0.5) c = 0 feat = lyr.GetNextFeature() - if get_spi_state(ds, lyr) != SPI_IN_BUILDING: - gdaltest.post_reason('failure') - return 'fail' + assert get_spi_state(ds, lyr) == SPI_IN_BUILDING while feat is not None: c = c + 1 feat = lyr.GetNextFeature() - if c != 1: - gdaltest.post_reason('failure') - return 'fail' - if get_spi_state(ds, lyr) != SPI_COMPLETED: - gdaltest.post_reason('failure') - return 'fail' + assert c == 1 + assert get_spi_state(ds, lyr) == SPI_COMPLETED feat = None lyr = None ds = None @@ -1188,9 +1038,7 @@ def ogr_openfilegdb_11(): ds = ogr.Open('data/testopenfilegdb.gdb.zip') lyr = ds.GetLayerByName('multipolygon') lyr.SetSpatialFilterRect(1.4, 0.4, 1.6, 0.6) - if lyr.GetFeatureCount() != expected_count: - gdaltest.post_reason('failure') - return 'fail' + assert lyr.GetFeatureCount() == expected_count lyr = None ds = None @@ -1204,12 +1052,8 @@ def ogr_openfilegdb_11(): while feat is not None: c = c + 1 feat = lyr.GetNextFeature() - if c != expected_count: - gdaltest.post_reason('failure') - return 'fail' - if lyr.GetFeatureCount() != expected_count: - gdaltest.post_reason('failure') - return 'fail' + assert c == expected_count + assert lyr.GetFeatureCount() == expected_count feat = None lyr = None ds = None @@ -1220,50 +1064,30 @@ def ogr_openfilegdb_11(): lyr.SetSpatialFilterRect(0.25, 0.25, 0.5, 0.5) feat = lyr.GetFeature(1) feat = lyr.GetFeature(1) - if get_spi_state(ds, lyr) != SPI_IN_BUILDING: - gdaltest.post_reason('failure') - return 'fail' + assert get_spi_state(ds, lyr) == SPI_IN_BUILDING feat = lyr.GetNextFeature() while feat is not None: feat = lyr.GetNextFeature() - if get_spi_state(ds, lyr) != SPI_COMPLETED: - gdaltest.post_reason('failure') - return 'fail' + assert get_spi_state(ds, lyr) == SPI_COMPLETED lyr.ResetReading() c = 0 feat = lyr.GetNextFeature() while feat is not None: c = c + 1 feat = lyr.GetNextFeature() - if c != 1: - gdaltest.post_reason('failure') - return 'fail' - if get_spi_state(ds, lyr) != SPI_COMPLETED: - gdaltest.post_reason('failure') - return 'fail' + assert c == 1 + assert get_spi_state(ds, lyr) == SPI_COMPLETED # This will create an array of filtered features lyr.SetSpatialFilterRect(0.25, 0.25, 0.5, 0.5) - if lyr.TestCapability(ogr.OLCFastSetNextByIndex) != 1: - gdaltest.post_reason('failure') - return 'fail' + assert lyr.TestCapability(ogr.OLCFastSetNextByIndex) == 1 # Test SetNextByIndex() with filtered features - if lyr.SetNextByIndex(-1) == 0: - gdaltest.post_reason('failure') - return 'fail' - if lyr.SetNextByIndex(1) == 0: - gdaltest.post_reason('failure') - return 'fail' - if lyr.SetNextByIndex(0) != 0: - gdaltest.post_reason('failure') - return 'fail' + assert lyr.SetNextByIndex(-1) != 0 + assert lyr.SetNextByIndex(1) != 0 + assert lyr.SetNextByIndex(0) == 0 feat = lyr.GetNextFeature() - if feat.GetFID() != 1: - gdaltest.post_reason('failure') - return 'fail' - if get_spi_state(ds, lyr) != SPI_COMPLETED: - gdaltest.post_reason('failure') - return 'fail' + assert feat.GetFID() == 1 + assert get_spi_state(ds, lyr) == SPI_COMPLETED feat = None lyr = None @@ -1273,9 +1097,7 @@ def ogr_openfilegdb_11(): ds = ogr.Open('data/testopenfilegdb.gdb.zip') lyr = ds.GetLayerByName('multipolygon') lyr.SetNextByIndex(3) - if get_spi_state(ds, lyr) != SPI_INVALID: - gdaltest.post_reason('failure') - return 'fail' + assert get_spi_state(ds, lyr) == SPI_INVALID feat = None lyr = None ds = None @@ -1285,9 +1107,7 @@ def ogr_openfilegdb_11(): lyr = ds.GetLayerByName('multipolygon') feat = lyr.GetNextFeature() lyr.ResetReading() - if get_spi_state(ds, lyr) != SPI_INVALID: - gdaltest.post_reason('failure') - return 'fail' + assert get_spi_state(ds, lyr) == SPI_INVALID feat = None lyr = None ds = None @@ -1296,19 +1116,16 @@ def ogr_openfilegdb_11(): ds = ogr.Open('data/testopenfilegdb.gdb.zip') lyr = ds.GetLayerByName('point') lyr.SetAttributeFilter('id = 1') - if get_spi_state(ds, lyr) != SPI_INVALID: - gdaltest.post_reason('failure') - return 'fail' + assert get_spi_state(ds, lyr) == SPI_INVALID feat = None lyr = None ds = None - return 'success' ############################################################################### # Test opening a FGDB with both SRID and LatestSRID set (#5638) -def ogr_openfilegdb_12(): +def test_ogr_openfilegdb_12(): ds = ogr.Open('/vsizip/data/test3005.gdb.zip') lyr = ds.GetLayer(0) @@ -1316,150 +1133,94 @@ def ogr_openfilegdb_12(): sr = osr.SpatialReference() sr.ImportFromEPSG(3005) expected_wkt = sr.ExportToWkt() - if got_wkt != expected_wkt: - gdaltest.post_reason('fail') - print(got_wkt) - print(expected_wkt) - return 'fail' + assert got_wkt == expected_wkt ds = None - return 'success' - ############################################################################### # Test opening a FGDB v9 with a non spatial table (#5673) -def ogr_openfilegdb_13(): +def test_ogr_openfilegdb_13(): ds = ogr.Open('/vsizip/data/ESSENCE_NAIPF_ORI_PROV_sub93.gdb.zip') lyr = ds.GetLayer(0) - if lyr.GetName() != 'DDE_ESSEN_NAIPF_ORI_VUE': - gdaltest.post_reason('fail') - return 'fail' - if lyr.GetSpatialRef() is not None: - gdaltest.post_reason('fail') - return 'fail' - if lyr.GetGeomType() != ogr.wkbNone: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.GetName() == 'DDE_ESSEN_NAIPF_ORI_VUE' + assert lyr.GetSpatialRef() is None + assert lyr.GetGeomType() == ogr.wkbNone f = lyr.GetNextFeature() if f.GetField('GEOCODE') != '-673985,22+745574,77': f.DumpReadable() - gdaltest.post_reason('fail') - return 'fail' + pytest.fail() ds = None - return 'success' - ############################################################################### # Test not nullable fields -def ogr_openfilegdb_14(): +def test_ogr_openfilegdb_14(): ds = ogr.Open('data/testopenfilegdb.gdb.zip') lyr = ds.GetLayerByName('testnotnullable') - if lyr.GetLayerDefn().GetFieldDefn(lyr.GetLayerDefn().GetFieldIndex('field_not_nullable')).IsNullable() != 0: - gdaltest.post_reason('fail') - return 'fail' - if lyr.GetLayerDefn().GetFieldDefn(lyr.GetLayerDefn().GetFieldIndex('field_nullable')).IsNullable() != 1: - gdaltest.post_reason('fail') - return 'fail' - if lyr.GetLayerDefn().GetGeomFieldDefn(0).IsNullable() != 0: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.GetLayerDefn().GetFieldDefn(lyr.GetLayerDefn().GetFieldIndex('field_not_nullable')).IsNullable() == 0 + assert lyr.GetLayerDefn().GetFieldDefn(lyr.GetLayerDefn().GetFieldIndex('field_nullable')).IsNullable() == 1 + assert lyr.GetLayerDefn().GetGeomFieldDefn(0).IsNullable() == 0 ds = None - return 'success' - ############################################################################### # Test default values -def ogr_openfilegdb_15(): +def test_ogr_openfilegdb_15(): ds = ogr.Open('data/test_default_val.gdb.zip') lyr = ds.GetLayer(0) - if lyr.GetLayerDefn().GetFieldDefn(lyr.GetLayerDefn().GetFieldIndex('STR')).GetDefault() != "'default_val'": - gdaltest.post_reason('fail') - return 'fail' - if lyr.GetLayerDefn().GetFieldDefn(lyr.GetLayerDefn().GetFieldIndex('STR')).GetWidth() != 50: - gdaltest.post_reason('fail') - return 'fail' - if lyr.GetLayerDefn().GetFieldDefn(lyr.GetLayerDefn().GetFieldIndex('INT32')).GetDefault() != "123456788": - gdaltest.post_reason('fail') - return 'fail' - if lyr.GetLayerDefn().GetFieldDefn(lyr.GetLayerDefn().GetFieldIndex('INT16')).GetDefault() != "12345": - gdaltest.post_reason('fail') - return 'fail' - if lyr.GetLayerDefn().GetFieldDefn(lyr.GetLayerDefn().GetFieldIndex('FLOAT32')).GetDefault().find('1.23') != 0: - gdaltest.post_reason('fail') - return 'fail' - if lyr.GetLayerDefn().GetFieldDefn(lyr.GetLayerDefn().GetFieldIndex('FLOAT64')).GetDefault().find('1.23456') != 0: - gdaltest.post_reason('fail') - return 'fail' - if lyr.GetLayerDefn().GetFieldDefn(lyr.GetLayerDefn().GetFieldIndex('DATETIME')).GetDefault() != "'2015/06/30 12:34:56'": - gdaltest.post_reason('fail') - return 'fail' - return 'success' + assert lyr.GetLayerDefn().GetFieldDefn(lyr.GetLayerDefn().GetFieldIndex('STR')).GetDefault() == "'default_val'" + assert lyr.GetLayerDefn().GetFieldDefn(lyr.GetLayerDefn().GetFieldIndex('STR')).GetWidth() == 50 + assert lyr.GetLayerDefn().GetFieldDefn(lyr.GetLayerDefn().GetFieldIndex('INT32')).GetDefault() == "123456788" + assert lyr.GetLayerDefn().GetFieldDefn(lyr.GetLayerDefn().GetFieldIndex('INT16')).GetDefault() == "12345" + assert lyr.GetLayerDefn().GetFieldDefn(lyr.GetLayerDefn().GetFieldIndex('FLOAT32')).GetDefault().find('1.23') == 0 + assert lyr.GetLayerDefn().GetFieldDefn(lyr.GetLayerDefn().GetFieldIndex('FLOAT64')).GetDefault().find('1.23456') == 0 + assert lyr.GetLayerDefn().GetFieldDefn(lyr.GetLayerDefn().GetFieldIndex('DATETIME')).GetDefault() == "'2015/06/30 12:34:56'" ############################################################################### # Read layers with sparse pages -def ogr_openfilegdb_16(): +def test_ogr_openfilegdb_16(): ds = ogr.Open('data/sparse.gdb.zip') lyr = ds.GetLayer(0) for fid in [2, 3, 4, 7, 8, 9, 10, 2049, 8191, 16384, 10000000, 10000001]: f = lyr.GetNextFeature() - if f.GetFID() != fid: - gdaltest.post_reason('fail') - print(f.GetFID()) - print(fid) - return 'fail' + assert f.GetFID() == fid f = lyr.GetFeature(100000) - if f is not None: - gdaltest.post_reason('fail') - return 'fail' + assert f is None f = lyr.GetFeature(10000000 - 1) - if f is not None: - gdaltest.post_reason('fail') - return 'fail' + assert f is None f = lyr.GetNextFeature() - if f is not None: - gdaltest.post_reason('fail') - return 'fail' + assert f is None f = lyr.GetFeature(16384) - if f is None: - gdaltest.post_reason('fail') - return 'fail' - - return 'success' + assert f is not None ############################################################################### # Read a MULTILINESTRING ZM with a dummy M array (#6528) -def ogr_openfilegdb_17(): +def test_ogr_openfilegdb_17(): ds = ogr.Open('data/multilinestringzm_with_dummy_m_array.gdb.zip') lyr = ds.GetLayer(0) f = lyr.GetNextFeature() - if f.GetGeometryRef() is None: - gdaltest.post_reason('fail') - return 'fail' - - return 'success' + assert f.GetGeometryRef() is not None ############################################################################### # Read curves -def ogr_openfilegdb_18(): +def test_ogr_openfilegdb_18(): ds = ogr.Open('data/curves.gdb') lyr = ds.GetLayerByName('line') @@ -1468,10 +1229,8 @@ def ogr_openfilegdb_18(): for f in lyr: f_ref = lyr_ref.GetNextFeature() if ogrtest.check_feature_geometry(f, f_ref.GetGeometryRef()) != 0: - gdaltest.post_reason('fail') print(f.GetGeometryRef().ExportToWkt()) - print(f_ref.GetGeometryRef().ExportToWkt()) - return 'fail' + pytest.fail(f_ref.GetGeometryRef().ExportToWkt()) lyr = ds.GetLayerByName('polygon') ds_ref = ogr.Open('data/curves_polygon.csv') @@ -1479,10 +1238,8 @@ def ogr_openfilegdb_18(): for f in lyr: f_ref = lyr_ref.GetNextFeature() if ogrtest.check_feature_geometry(f, f_ref.GetGeometryRef()) != 0: - gdaltest.post_reason('fail') print(f.GetGeometryRef().ExportToWkt()) - print(f_ref.GetGeometryRef().ExportToWkt()) - return 'fail' + pytest.fail(f_ref.GetGeometryRef().ExportToWkt()) ds = ogr.Open('data/curve_circle_by_center.gdb') lyr = ds.GetLayer(0) @@ -1491,33 +1248,27 @@ def ogr_openfilegdb_18(): for f in lyr: f_ref = lyr_ref.GetNextFeature() if ogrtest.check_feature_geometry(f, f_ref.GetGeometryRef()) != 0: - gdaltest.post_reason('fail') print(f.GetGeometryRef().ExportToWkt()) - print(f_ref.GetGeometryRef().ExportToWkt()) - return 'fail' - - return 'success' + pytest.fail(f_ref.GetGeometryRef().ExportToWkt()) + ############################################################################### # Test opening '.' -def ogr_openfilegdb_19(): +def test_ogr_openfilegdb_19(): os.chdir('data/curves.gdb') ds = ogr.Open('.') os.chdir('../..') - if ds is None: - return 'fail' - - return 'success' + assert ds is not None ############################################################################### # Read polygons with M component where the M of the closing point is not the # one of the starting point (#7017) -def ogr_openfilegdb_20(): +def test_ogr_openfilegdb_20(): ds = ogr.Open('data/filegdb_polygonzm_m_not_closing_with_curves.gdb') lyr = ds.GetLayer(0) @@ -1526,10 +1277,8 @@ def ogr_openfilegdb_20(): for f in lyr: f_ref = lyr_ref.GetNextFeature() if ogrtest.check_feature_geometry(f, f_ref.GetGeometryRef()) != 0: - gdaltest.post_reason('fail') print(f.GetGeometryRef().ExportToIsoWkt()) - print(f_ref.GetGeometryRef().ExportToIsoWkt()) - return 'fail' + pytest.fail(f_ref.GetGeometryRef().ExportToIsoWkt()) ds = ogr.Open('data/filegdb_polygonzm_nan_m_with_curves.gdb') lyr = ds.GetLayer(0) @@ -1538,50 +1287,40 @@ def ogr_openfilegdb_20(): for f in lyr: f_ref = lyr_ref.GetNextFeature() if ogrtest.check_feature_geometry(f, f_ref.GetGeometryRef()) != 0: - gdaltest.post_reason('fail') print(f.GetGeometryRef().ExportToIsoWkt()) - print(f_ref.GetGeometryRef().ExportToIsoWkt()) - return 'fail' - - return 'success' + pytest.fail(f_ref.GetGeometryRef().ExportToIsoWkt()) + ############################################################################### # Test selecting FID column with OGRSQL -def ogr_openfilegdb_21(): +def test_ogr_openfilegdb_21(): ds = ogr.Open('data/curves.gdb') sql_lyr = ds.ExecuteSQL('SELECT OBJECTID FROM polygon WHERE OBJECTID = 2') - if sql_lyr is None: - gdaltest.post_reason('fail') - return 'fail' + assert sql_lyr is not None f = sql_lyr.GetNextFeature() if f.GetFID() != 2: - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' + pytest.fail() f = sql_lyr.GetNextFeature() - if f is not None: - gdaltest.post_reason('fail') - return 'fail' + assert f is None ds.ReleaseResultSet(sql_lyr) lyr = ds.GetLayerByName('polygon') lyr.SetAttributeFilter('OBJECTID = 2') f = lyr.GetNextFeature() if f.GetFID() != 2: - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' - - return 'success' + pytest.fail() + ############################################################################### # Cleanup -def ogr_openfilegdb_cleanup(): +def test_ogr_openfilegdb_cleanup(): if ogrtest.fgdb_drv is not None: ogrtest.fgdb_drv.Register() @@ -1600,44 +1339,6 @@ def ogr_openfilegdb_cleanup(): except OSError: pass - return 'success' - - -gdaltest_list = [ - ogr_openfilegdb_init, - # ogr_openfilegdb_make_test_data, - ogr_openfilegdb_1, - ogr_openfilegdb_1_92, - ogr_openfilegdb_1_93, - ogr_openfilegdb_2, - ogr_openfilegdb_2_92, - ogr_openfilegdb_2_93, - ogr_openfilegdb_3, - ogr_openfilegdb_4, - ogr_openfilegdb_5, - ogr_openfilegdb_6, - ogr_openfilegdb_7, - ogr_openfilegdb_8, - ogr_openfilegdb_9, - ogr_openfilegdb_10, - ogr_openfilegdb_11, - ogr_openfilegdb_12, - ogr_openfilegdb_13, - ogr_openfilegdb_14, - ogr_openfilegdb_15, - ogr_openfilegdb_16, - ogr_openfilegdb_17, - ogr_openfilegdb_18, - ogr_openfilegdb_19, - ogr_openfilegdb_20, - ogr_openfilegdb_21, - ogr_openfilegdb_cleanup, -] - -if __name__ == '__main__': - - gdaltest.setup_run('ogr_openfilegdb') - - gdaltest.run_tests(gdaltest_list) - - sys.exit(gdaltest.summarize()) + + + diff --git a/autotest/ogr/ogr_osm.py b/autotest/ogr/ogr_osm.py index 8f1ddb3cd307..a4587e83665b 100755 --- a/autotest/ogr/ogr_osm.py +++ b/autotest/ogr/ogr_osm.py @@ -30,269 +30,214 @@ ############################################################################### import os -import sys from osgeo import ogr from osgeo import gdal -sys.path.append('../pymod') import gdaltest import ogrtest +import pytest ############################################################################### # Test .pbf -def ogr_osm_1(filename='data/test.pbf'): +def test_ogr_osm_1(filename='data/test.pbf'): ogrtest.osm_drv = ogr.GetDriverByName('OSM') if ogrtest.osm_drv is None: - return 'skip' + pytest.skip() ds = ogr.Open(filename) if ds is None: if filename == 'data/test.osm': ogrtest.osm_drv_parse_osm = False if gdal.GetLastErrorMsg().find('OSM XML detected, but Expat parser not available') == 0: - return 'skip' + pytest.skip() - gdaltest.post_reason('fail') - return 'fail' + pytest.fail() else: if filename == 'data/test.osm': ogrtest.osm_drv_parse_osm = True # Test points lyr = ds.GetLayer('points') - if lyr.GetGeomType() != ogr.wkbPoint: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.GetGeomType() == ogr.wkbPoint sr = lyr.GetSpatialRef() - if sr.ExportToWkt().find('GEOGCS["WGS 84",DATUM["WGS_1984",') != 0 and \ - sr.ExportToWkt().find('GEOGCS["GCS_WGS_1984",DATUM["WGS_1984"') != 0: - gdaltest.post_reason('fail') - print(sr.ExportToWkt()) - return 'fail' + assert (sr.ExportToWkt().find('GEOGCS["WGS 84",DATUM["WGS_1984",') == 0 or \ + sr.ExportToWkt().find('GEOGCS["GCS_WGS_1984",DATUM["WGS_1984"') == 0) if filename == 'data/test.osm': - if lyr.GetExtent() != (2.0, 3.0, 49.0, 50.0): - gdaltest.post_reason('fail') - print(lyr.GetExtent()) - return 'fail' + assert lyr.GetExtent() == (2.0, 3.0, 49.0, 50.0) feat = lyr.GetNextFeature() if feat.GetFieldAsString('osm_id') != '3' or \ feat.GetFieldAsString('name') != 'Some interesting point' or \ feat.GetFieldAsString('other_tags') != '"foo"=>"bar","bar"=>"baz"': - gdaltest.post_reason('fail') feat.DumpReadable() - return 'fail' + pytest.fail() if ogrtest.check_feature_geometry(feat, ogr.CreateGeometryFromWkt('POINT (3.0 49.5)')) != 0: - gdaltest.post_reason('fail') feat.DumpReadable() - return 'fail' + pytest.fail() feat = lyr.GetNextFeature() if feat is not None: - gdaltest.post_reason('fail') feat.DumpReadable() - return 'fail' + pytest.fail() # Test lines lyr = ds.GetLayer('lines') - if lyr.GetGeomType() != ogr.wkbLineString: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.GetGeomType() == ogr.wkbLineString feat = lyr.GetNextFeature() if feat.GetFieldAsString('osm_id') != '1' or \ feat.GetFieldAsString('highway') != 'motorway' or \ feat.GetFieldAsInteger('z_order') != 9 or \ feat.GetFieldAsString('other_tags') != '"foo"=>"bar"': - gdaltest.post_reason('fail') feat.DumpReadable() - return 'fail' + pytest.fail() if ogrtest.check_feature_geometry(feat, ogr.CreateGeometryFromWkt('LINESTRING (2 49,3 50)')) != 0: - gdaltest.post_reason('fail') feat.DumpReadable() - return 'fail' + pytest.fail() feat = lyr.GetNextFeature() if feat.GetFieldAsString('osm_id') != '6': - gdaltest.post_reason('fail') feat.DumpReadable() - return 'fail' + pytest.fail() if ogrtest.check_feature_geometry(feat, ogr.CreateGeometryFromWkt('LINESTRING (2 49,3 49,3 50,2 50,2 49)')) != 0: - gdaltest.post_reason('fail') feat.DumpReadable() - return 'fail' + pytest.fail() feat = lyr.GetNextFeature() if feat is not None: - gdaltest.post_reason('fail') feat.DumpReadable() - return 'fail' + pytest.fail() # Test multipolygons lyr = ds.GetLayer('multipolygons') if filename == 'tmp/ogr_osm_3': - if lyr.GetGeomType() != ogr.wkbPolygon: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.GetGeomType() == ogr.wkbPolygon else: - if lyr.GetGeomType() != ogr.wkbMultiPolygon: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.GetGeomType() == ogr.wkbMultiPolygon feat = lyr.GetNextFeature() if feat.GetFieldAsString('osm_id') != '1' or \ feat.GetFieldAsString('type') != 'multipolygon' or \ feat.GetFieldAsString('natural') != 'forest': - gdaltest.post_reason('fail') feat.DumpReadable() - return 'fail' + pytest.fail() if filename == 'tmp/ogr_osm_3': if ogrtest.check_feature_geometry(feat, ogr.CreateGeometryFromWkt('POLYGON ((2 49,2 50,3 50,3 49,2 49),(2.1 49.1,2.2 49.1,2.2 49.2,2.1 49.2,2.1 49.1))')) != 0: - gdaltest.post_reason('fail') feat.DumpReadable() - return 'fail' + pytest.fail() else: if ogrtest.check_feature_geometry(feat, ogr.CreateGeometryFromWkt('MULTIPOLYGON (((2 49,3 49,3 50,2 50,2 49),(2.1 49.1,2.2 49.1,2.2 49.2,2.1 49.2,2.1 49.1)))')) != 0: - gdaltest.post_reason('fail') feat.DumpReadable() - return 'fail' + pytest.fail() feat = lyr.GetNextFeature() if feat.GetFieldAsString('osm_id') != '5' or \ feat.GetFieldAsString('type') != 'multipolygon' or \ feat.GetFieldAsString('natural') != 'wood': - gdaltest.post_reason('fail') feat.DumpReadable() - return 'fail' + pytest.fail() feat = lyr.GetNextFeature() if feat.GetFieldAsString('osm_way_id') != '8' or \ feat.GetFieldAsString('name') != 'standalone_polygon': - gdaltest.post_reason('fail') feat.DumpReadable() - return 'fail' + pytest.fail() feat = lyr.GetNextFeature() if feat is not None: - gdaltest.post_reason('fail') feat.DumpReadable() - return 'fail' + pytest.fail() # Test multilinestrings lyr = ds.GetLayer('multilinestrings') if filename == 'tmp/ogr_osm_3': - if lyr.GetGeomType() != ogr.wkbLineString: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.GetGeomType() == ogr.wkbLineString else: - if lyr.GetGeomType() != ogr.wkbMultiLineString: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.GetGeomType() == ogr.wkbMultiLineString feat = lyr.GetNextFeature() if feat.GetFieldAsString('osm_id') != '3' or \ feat.GetFieldAsString('type') != 'route': - gdaltest.post_reason('fail') feat.DumpReadable() - return 'fail' + pytest.fail() if filename == 'tmp/ogr_osm_3': if ogrtest.check_feature_geometry(feat, ogr.CreateGeometryFromWkt('LINESTRING (2 49,3 50)')) != 0: - gdaltest.post_reason('fail') feat.DumpReadable() - return 'fail' + pytest.fail() else: if ogrtest.check_feature_geometry(feat, ogr.CreateGeometryFromWkt('MULTILINESTRING ((2 49,3 50))')) != 0: - gdaltest.post_reason('fail') feat.DumpReadable() - return 'fail' + pytest.fail() feat = lyr.GetNextFeature() if feat is not None: - gdaltest.post_reason('fail') feat.DumpReadable() - return 'fail' + pytest.fail() # Test other_relations lyr = ds.GetLayer('other_relations') if filename == 'tmp/ogr_osm_3': - if lyr is not None: - gdaltest.post_reason('fail') - return 'fail' + assert lyr is None else: - if lyr.GetGeomType() != ogr.wkbGeometryCollection: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.GetGeomType() == ogr.wkbGeometryCollection feat = lyr.GetNextFeature() if feat.GetFieldAsString('osm_id') != '4' or \ feat.GetFieldAsString('type') != 'other_type': - gdaltest.post_reason('fail') feat.DumpReadable() - return 'fail' + pytest.fail() if ogrtest.check_feature_geometry(feat, ogr.CreateGeometryFromWkt('GEOMETRYCOLLECTION (POINT (2 49),LINESTRING (2 49,3 50))')) != 0: - gdaltest.post_reason('fail') feat.DumpReadable() - return 'fail' + pytest.fail() feat = lyr.GetNextFeature() if feat is not None: - gdaltest.post_reason('fail') feat.DumpReadable() - return 'fail' + pytest.fail() if ds.GetDriver().GetName() == 'OSM': sql_lyr = ds.ExecuteSQL("GetBytesRead()") - if sql_lyr is None: - gdaltest.post_reason('fail') - return 'fail' + assert sql_lyr is not None feat = sql_lyr.GetNextFeature() - if feat is None: - gdaltest.post_reason('fail') - return 'fail' + assert feat is not None feat = sql_lyr.GetNextFeature() - if feat is not None: - gdaltest.post_reason('fail') - return 'fail' + assert feat is None sql_lyr.ResetReading() feat = sql_lyr.GetNextFeature() - if feat is None: - gdaltest.post_reason('fail') - return 'fail' + assert feat is not None sql_lyr.GetLayerDefn() sql_lyr.TestCapability("foo") ds.ReleaseResultSet(sql_lyr) ds = None - return 'success' - ############################################################################### # Test .osm -def ogr_osm_2(): - return ogr_osm_1('data/test.osm') +def test_ogr_osm_2(): + return test_ogr_osm_1('data/test.osm') ############################################################################### # Test ogr2ogr -def ogr_osm_3(options=None, all_layers=False): +def test_ogr_osm_3(options=None, all_layers=False): if ogrtest.osm_drv is None: - return 'skip' + pytest.skip() filepath = 'tmp/ogr_osm_3' if os.path.exists(filepath): @@ -309,7 +254,7 @@ def ogr_osm_3(options=None, all_layers=False): with gdaltest.error_handler(): gdal.VectorTranslate('tmp/ogr_osm_3', 'data/test.pbf', options=layers + options) - ret = ogr_osm_1(filepath) + ret = test_ogr_osm_1(filepath) ogr.GetDriverByName('ESRI Shapefile').DeleteDataSource(filepath) @@ -319,9 +264,9 @@ def ogr_osm_3(options=None, all_layers=False): # Test ogr2ogr with --config OSM_USE_CUSTOM_INDEXING NO and -skip -def ogr_osm_3_sqlite_nodes(): +def test_ogr_osm_3_sqlite_nodes(): gdal.SetConfigOption('OSM_USE_CUSTOM_INDEXING', 'NO') - ret = ogr_osm_3(options='-skip') + ret = test_ogr_osm_3(options='-skip') gdal.SetConfigOption('OSM_USE_CUSTOM_INDEXING', None) return ret @@ -329,9 +274,9 @@ def ogr_osm_3_sqlite_nodes(): # Test ogr2ogr with --config OSM_COMPRESS_NODES YES -def ogr_osm_3_custom_compress_nodes(): +def test_ogr_osm_3_custom_compress_nodes(): gdal.SetConfigOption('OSM_COMPRESS_NODES', 'YES') - ret = ogr_osm_3() + ret = test_ogr_osm_3() gdal.SetConfigOption('OSM_COMPRESS_NODES', None) return ret @@ -339,22 +284,20 @@ def ogr_osm_3_custom_compress_nodes(): # Test ogr2ogr with all layers -def ogr_osm_3_all_layers(): - return ogr_osm_3(options='-skip', all_layers=True) +def test_ogr_osm_3_all_layers(): + return test_ogr_osm_3(options='-skip', all_layers=True) ############################################################################### # Test optimization when reading only the points layer through a SQL request -def ogr_osm_4(): +def test_ogr_osm_4(): if ogrtest.osm_drv is None: - return 'skip' + pytest.skip() ds = ogr.Open('data/test.pbf') - if ds is None: - gdaltest.post_reason('fail') - return 'fail' + assert ds is not None sql_lyr = ds.ExecuteSQL('SELECT * FROM points') @@ -363,9 +306,7 @@ def ogr_osm_4(): ds.ReleaseResultSet(sql_lyr) - if is_none: - gdaltest.post_reason('fail') - return 'fail' + assert not is_none # Test spatial filter @@ -373,9 +314,7 @@ def ogr_osm_4(): lyr.SetSpatialFilterRect(0, 0, 0, 0) lyr.ResetReading() feat = lyr.GetNextFeature() - if feat is not None: - gdaltest.post_reason('Zero filter ') - return 'fail' + assert feat is None, 'Zero filter ' with gdaltest.error_handler(): lyr.SetSpatialFilter(None) @@ -388,9 +327,7 @@ def ogr_osm_4(): ds.ReleaseResultSet(sql_lyr) - if is_none: - gdaltest.post_reason('fail') - return 'fail' + assert not is_none # Change layer sql_lyr = ds.ExecuteSQL('SELECT * FROM points') @@ -400,25 +337,19 @@ def ogr_osm_4(): ds.ReleaseResultSet(sql_lyr) - if is_none: - gdaltest.post_reason('fail') - return 'fail' - - return 'success' + assert not is_none ############################################################################### # Test optimizations for early attribute filter evaluation -def ogr_osm_5(): +def test_ogr_osm_5(): if ogrtest.osm_drv is None: - return 'skip' + pytest.skip() ds = ogr.Open('data/test.pbf') - if ds is None: - gdaltest.post_reason('fail') - return 'fail' + assert ds is not None tests = [['points', '3', True], ['points', 'foo', False], @@ -436,10 +367,7 @@ def ogr_osm_5(): feat = None ds.ReleaseResultSet(sql_lyr) - if not (test[2] ^ is_none): # pylint: disable=superfluous-parens - gdaltest.post_reason('fail') - print(test) - return 'fail' + assert (test[2] ^ is_none) sql_lyr = ds.ExecuteSQL("select * from multipolygons where type = 'multipolygon'") feat = sql_lyr.GetNextFeature() @@ -447,25 +375,20 @@ def ogr_osm_5(): feat = None ds.ReleaseResultSet(sql_lyr) - if is_none: - gdaltest.post_reason('fail') - print(test) - return 'fail' - - return 'success' + assert not is_none, test ############################################################################### # Test ogr2ogr -sql -def ogr_osm_6(): +def test_ogr_osm_6(): if ogrtest.osm_drv is None: - return 'skip' + pytest.skip() import test_cli_utilities if test_cli_utilities.get_ogr2ogr_path() is None: - return 'skip' + pytest.skip() try: os.stat('tmp/ogr_osm_6') @@ -482,53 +405,40 @@ def ogr_osm_6(): ogr.GetDriverByName('ESRI Shapefile').DeleteDataSource('tmp/ogr_osm_6') - if count != 3: - gdaltest.post_reason('fail') - print(count) - return 'fail' - - return 'success' + assert count == 3 ############################################################################### # Test optimization when reading only the points layer through a SQL request # with SQLite dialect (#4825) -def ogr_osm_7(): +def test_ogr_osm_7(): if ogrtest.osm_drv is None: - return 'skip' + pytest.skip() ds = ogr.Open('data/test.pbf') - if ds is None: - gdaltest.post_reason('fail') - return 'fail' + assert ds is not None sql_lyr = ds.ExecuteSQL('SELECT * FROM points LIMIT 10', dialect='SQLite') if sql_lyr is None and gdal.GetLastErrorMsg().find('automatic extension loading failed') != 0: - return 'skip' + pytest.skip() count = sql_lyr.GetFeatureCount() ds.ReleaseResultSet(sql_lyr) - if count != 1: - gdaltest.post_reason('fail') - return 'fail' - - return 'success' + assert count == 1 ############################################################################### # Test 64-bit ids -def ogr_osm_8(): +def test_ogr_osm_8(): if ogrtest.osm_drv is None: - return 'skip' + pytest.skip() ds = ogr.Open('data/base-64.osm.pbf') - if ds is None: - gdaltest.post_reason('fail') - return 'fail' + assert ds is not None lyr = ds.GetLayerByName('points') lyr.SetAttributeFilter("osm_id = '4294967934'") @@ -536,32 +446,29 @@ def ogr_osm_8(): if feat.GetField('name') != 'Treetops' or \ ogrtest.check_feature_geometry(feat, ogr.CreateGeometryFromWkt('POINT (-61.7964321 17.1498319)')) != 0: - gdaltest.post_reason('fail') feat.DumpReadable() - return 'fail' + pytest.fail() lyr = ds.GetLayerByName('multipolygons') feat = lyr.GetFeature(1113) if ogrtest.check_feature_geometry(feat, ogr.CreateGeometryFromWkt('MULTIPOLYGON (((-61.7780345 17.140634,-61.7777002 17.1406069,-61.7776854 17.1407739,-61.7779131 17.1407923,-61.7779158 17.1407624,-61.7780224 17.140771,-61.7780345 17.140634)))')) != 0: - gdaltest.post_reason('fail') feat.DumpReadable() - return 'fail' - - return 'success' + pytest.fail() + ############################################################################### # Same as ogr_osm_8 but with OSM_USE_CUSTOM_INDEXING=NO -def ogr_osm_9(): +def test_ogr_osm_9(): if ogrtest.osm_drv is None: - return 'skip' + pytest.skip() old_val = gdal.GetConfigOption('OSM_USE_CUSTOM_INDEXING') gdal.SetConfigOption('OSM_USE_CUSTOM_INDEXING', 'NO') - ret = ogr_osm_8() + ret = test_ogr_osm_8() gdal.SetConfigOption('OSM_USE_CUSTOM_INDEXING', old_val) return ret @@ -570,25 +477,21 @@ def ogr_osm_9(): # Some error conditions -def ogr_osm_10(): +def test_ogr_osm_10(): if ogrtest.osm_drv is None: - return 'skip' + pytest.skip() # A file that does not exist. ds = ogr.Open('/nonexistent/foo.osm') - if ds is not None: - gdaltest.post_reason('fail') - return 'fail' + assert ds is None # Empty .osm file f = gdal.VSIFOpenL('/vsimem/foo.osm', 'wb') gdal.VSIFCloseL(f) ds = ogr.Open('/vsimem/foo.osm') - if ds is not None: - gdaltest.post_reason('fail') - return 'fail' + assert ds is None gdal.Unlink('/vsimem/foo.osm') @@ -597,9 +500,7 @@ def ogr_osm_10(): gdal.VSIFCloseL(f) ds = ogr.Open('/vsimem/foo.pbf') - if ds is not None: - gdaltest.post_reason('fail') - return 'fail' + assert ds is None gdal.Unlink('/vsimem/foo.pbf') @@ -616,9 +517,7 @@ def ogr_osm_10(): gdal.PushErrorHandler('CPLQuietErrorHandler') feat = lyr.GetNextFeature() gdal.PopErrorHandler() - if gdal.GetLastErrorMsg() == '': - gdaltest.post_reason('fail') - return 'fail' + assert gdal.GetLastErrorMsg() != '' ds = None gdal.Unlink('/vsimem/foo.osm') @@ -635,9 +534,7 @@ def ogr_osm_10(): gdal.PushErrorHandler('CPLQuietErrorHandler') feat = lyr.GetNextFeature() gdal.PopErrorHandler() - if gdal.GetLastErrorMsg() == '': - gdaltest.post_reason('fail') - return 'fail' + assert gdal.GetLastErrorMsg() != '' ds = None gdal.Unlink('/vsimem/foo.pbf') @@ -650,20 +547,17 @@ def ogr_osm_10(): gdal.PushErrorHandler('CPLQuietErrorHandler') feat = lyr.GetNextFeature() gdal.PopErrorHandler() - if feat is not None or gdal.GetLastErrorMsg() == '': - gdaltest.post_reason('fail') - return 'fail' - - return 'success' + assert feat is None and gdal.GetLastErrorMsg() != '' + ############################################################################### # Test all_tags -def ogr_osm_11(): +def test_ogr_osm_11(): if ogrtest.osm_drv is None: - return 'skip' + pytest.skip() gdal.SetConfigOption('OSM_CONFIG_FILE', 'data/osmconf_alltags.ini') ds = ogr.Open('data/test.pbf') @@ -673,28 +567,25 @@ def ogr_osm_11(): if feat.GetFieldAsString('osm_id') != '3' or \ feat.GetFieldAsString('name') != 'Some interesting point' or \ feat.GetFieldAsString('all_tags') != '"name"=>"Some interesting point","foo"=>"bar","bar"=>"baz"': - gdaltest.post_reason('fail') feat.DumpReadable() - return 'fail' + pytest.fail() lyr = ds.GetLayerByName('lines') feat = lyr.GetNextFeature() if feat.GetField('z_order') != 9: - gdaltest.post_reason('fail') feat.DumpReadable() - return 'fail' - - return 'success' + pytest.fail() + ############################################################################### # Test that attribute filter set on a line layer is well taken into # account -def ogr_osm_12(): +def test_ogr_osm_12(): if ogrtest.osm_drv is None: - return 'skip' + pytest.skip() ds = ogr.Open('data/test.pbf') for i in range(2): @@ -707,35 +598,31 @@ def ogr_osm_12(): while feat is not None: count = count + 1 feat = lay.GetNextFeature() - if i == 1 and count != 1: - print(count) - return 'fail' + assert i != 1 or count == 1 ds = None - return 'success' - ############################################################################### # Test test_uncompressed_dense_true_nometadata.pbf -def ogr_osm_test_uncompressed_dense_true_nometadata_pbf(): - return ogr_osm_1('data/test_uncompressed_dense_true_nometadata.pbf') +def test_ogr_osm_test_uncompressed_dense_true_nometadata_pbf(): + return test_ogr_osm_1('data/test_uncompressed_dense_true_nometadata.pbf') ############################################################################### # Test test_uncompressed_dense_false.pbf -def ogr_osm_test_uncompressed_dense_false_pbf(): - return ogr_osm_1('data/test_uncompressed_dense_false.pbf') +def test_ogr_osm_test_uncompressed_dense_false_pbf(): + return test_ogr_osm_1('data/test_uncompressed_dense_false.pbf') # Special case: if an object has a 'osm_id' key, then do not use it to override # "our" osm_id field. But put it in other_fields (#6347) -def ogr_osm_13(): +def test_ogr_osm_13(): if ogrtest.osm_drv is None or not ogrtest.osm_drv_parse_osm: - return 'skip' + pytest.skip() gdal.FileFromMemBuffer('/vsimem/ogr_osm_13.osm', """<osm><node id="123" lon="2" lat="49"><tag k="osm_id" v="0"/></node></osm>""") @@ -744,27 +631,24 @@ def ogr_osm_13(): ds = ogr.Open('/vsimem/ogr_osm_13.osm') if ds is None: gdal.Unlink('/vsimem/ogr_osm_13.osm') - return 'skip' + pytest.skip() lyr = ds.GetLayer(0) f = lyr.GetNextFeature() if f['osm_id'] != '123' or f['other_tags'] != '"osm_id"=>"0"': - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' + pytest.fail() ds = None gdal.Unlink('/vsimem/ogr_osm_13.osm') - return 'success' - ############################################################################### # Test that we handle polygons in other_relations (#6475) -def ogr_osm_14(): +def test_ogr_osm_14(): if ogrtest.osm_drv is None or not ogrtest.osm_drv_parse_osm: - return 'skip' + pytest.skip() gdal.FileFromMemBuffer('/vsimem/ogr_osm_14.osm', """<osm> @@ -789,20 +673,17 @@ def ogr_osm_14(): ds = ogr.Open('/vsimem/ogr_osm_14.osm') if ds is None: gdal.Unlink('/vsimem/ogr_osm_14.osm') - return 'skip' + pytest.skip() sql_lyr = ds.ExecuteSQL('SELECT * FROM other_relations') f = sql_lyr.GetNextFeature() if f.GetGeometryRef().ExportToWkt() != 'GEOMETRYCOLLECTION (POLYGON ((49 2,49.0 2.1,49.1 2.1,49 2)))': - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' + pytest.fail() ds.ReleaseResultSet(sql_lyr) ds = None gdal.Unlink('/vsimem/ogr_osm_14.osm') - return 'success' - ############################################################################### # Test Dataset.GetNextFeature() @@ -818,80 +699,52 @@ def ogr_osm_15_progresscbk_return_false(pct, msg, user_data): return 0 -def ogr_osm_15(): +def test_ogr_osm_15(): if ogrtest.osm_drv is None: - return 'skip' + pytest.skip() ds = gdal.OpenEx('data/test.pbf') - if ds.TestCapability(ogr.ODsCRandomLayerRead) != 1: - gdaltest.post_reason('fail') - return 'fail' + assert ds.TestCapability(ogr.ODsCRandomLayerRead) == 1 count = 0 last_pct = 0 while True: f, l, pct = ds.GetNextFeature(include_pct=True) - if pct < last_pct: - gdaltest.post_reason('fail') - print(last_pct) - print(pct) - return 'fail' + assert pct >= last_pct last_pct = pct if f is None: - if l is not None: - gdaltest.post_reason('fail') - return 'fail' + assert l is None break # f.DumpReadable() count += 1 if f.GetDefnRef().GetName() != l.GetName(): - gdaltest.post_reason('fail') f.DumpReadable() - print(l.GetName()) - return 'fail' + pytest.fail(l.GetName()) - if count != 8: - gdaltest.post_reason('fail') - print(count) - return 'fail' + assert count == 8 - if last_pct != 1.0: - gdaltest.post_reason('fail') - print(last_pct) - return 'fail' + assert last_pct == 1.0 f, l, pct = ds.GetNextFeature(include_pct=True) - if f is not None or l is not None or pct != 1.0: - gdaltest.post_reason('fail') - return 'fail' + assert f is None and l is None and pct == 1.0 ds.ResetReading() for i in range(count): f, lyr = ds.GetNextFeature() # f.DumpReadable() - if f is None or lyr is None: - gdaltest.post_reason('fail') - print(i) - return 'fail' + assert not (f is None or lyr is None), i ds.ResetReading() f, lyr = ds.GetNextFeature(callback=ogr_osm_15_progresscbk_return_false) - if f is not None or lyr is not None: - gdaltest.post_reason('fail') - return 'fail' + assert f is None and lyr is None ds.ResetReading() pct_array = [0] f, lyr = ds.GetNextFeature(callback=ogr_osm_15_progresscbk_return_true, callback_data=pct_array) - if f is None or lyr is None: - gdaltest.post_reason('fail') - return 'fail' - if pct_array[0] != 1.0: - gdaltest.post_reason('fail') - print(pct_array) - return 'fail' + assert not (f is None or lyr is None) + assert pct_array[0] == 1.0 # ds = gdal.OpenEx('/home/even/gdal/data/osm/france.osm.pbf') # ds.ExecuteSQL('SET interest_layers = relations') @@ -902,16 +755,14 @@ def ogr_osm_15(): ds = None - return 'success' - ############################################################################### # Test laundering of tags (https://github.com/OSGeo/gdal/pull/161) -def ogr_osm_16(): +def test_ogr_osm_16(): if ogrtest.osm_drv is None or not ogrtest.osm_drv_parse_osm: - return 'skip' + pytest.skip() gdal.FileFromMemBuffer('/vsimem/ogr_osm_16.osm', """<osm> @@ -933,25 +784,22 @@ def ogr_osm_16(): lyr = ds.GetLayerByName('points') f = lyr.GetNextFeature() if f['foo_baar'] != 'val' or f['foo_bar'] != 'val2': - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' + pytest.fail() ds = None gdal.Unlink('/vsimem/ogr_osm_16.osm') gdal.Unlink('/vsimem/ogr_osm_16_conf.ini') - return 'success' - ############################################################################### # Test converting an empty OSM file (this essentially tests the behaviour of # GDALVectorTranslate() in random feature mode, when there is no feature) -def ogr_osm_17(): +def test_ogr_osm_17(): if ogrtest.osm_drv is None or not ogrtest.osm_drv_parse_osm: - return 'skip' + pytest.skip() with gdaltest.error_handler(): gdal.VectorTranslate('/vsimem/ogr_osm_17', 'data/empty.osm', options='-skip') @@ -962,22 +810,17 @@ def ogr_osm_17(): ogr.GetDriverByName('ESRI Shapefile').DeleteDataSource('/vsimem/ogr_osm_17') - if layer_count != 4: - gdaltest.post_reason('fail') - print(layer_count) - return 'fail' - - return 'success' + assert layer_count == 4 ############################################################################### # Test correct reading of .pbf files with multiple densenode blocks and # regarding EOF -def ogr_osm_18(): +def test_ogr_osm_18(): if ogrtest.osm_drv is None: - return 'skip' + pytest.skip() ds = ogr.Open('data/two_points.pbf') lyr = ds.GetLayerByName('points') @@ -986,44 +829,7 @@ def ogr_osm_18(): count += 1 ds = None - if count != 2: - gdaltest.post_reason('fail') - print(count) - return 'fail' - - return 'success' - - -gdaltest_list = [ - ogr_osm_1, - ogr_osm_2, - ogr_osm_3, - ogr_osm_3_sqlite_nodes, - ogr_osm_3_custom_compress_nodes, - ogr_osm_3_all_layers, - ogr_osm_4, - ogr_osm_5, - ogr_osm_6, - ogr_osm_7, - ogr_osm_8, - ogr_osm_9, - ogr_osm_10, - ogr_osm_11, - ogr_osm_12, - ogr_osm_test_uncompressed_dense_true_nometadata_pbf, - ogr_osm_test_uncompressed_dense_false_pbf, - ogr_osm_13, - ogr_osm_14, - ogr_osm_15, - ogr_osm_16, - ogr_osm_17, - ogr_osm_18, -] - -if __name__ == '__main__': - - gdaltest.setup_run('ogr_osm') - - gdaltest.run_tests(gdaltest_list) - - sys.exit(gdaltest.summarize()) + assert count == 2 + + + diff --git a/autotest/ogr/ogr_pcidsk.py b/autotest/ogr/ogr_pcidsk.py index d13ed311408e..35dd1204e151 100755 --- a/autotest/ogr/ogr_pcidsk.py +++ b/autotest/ogr/ogr_pcidsk.py @@ -28,15 +28,14 @@ # DEALINGS IN THE SOFTWARE. ############################################################################### -import sys -sys.path.append('../pymod') import gdaltest import ogrtest from osgeo import ogr from osgeo import osr from osgeo import gdal +import pytest wkts = [('POINT (0 1 2)', 'points', 0), @@ -49,11 +48,11 @@ # Test creation -def ogr_pcidsk_1(): +def test_ogr_pcidsk_1(): ogr_drv = ogr.GetDriverByName('PCIDSK') if ogr_drv is None: - return 'skip' + pytest.skip() ds = ogr_drv.CreateDataSource('tmp/ogr_pcidsk_1.pix') @@ -63,9 +62,7 @@ def ogr_pcidsk_1(): lyr.ResetReading() feat = lyr.GetNextFeature() - if feat is None: - gdaltest.post_reason('failure') - return 'fail' + assert feat is not None lyr = ds.CreateLayer('fields', geom_type=ogr.wkbNone) lyr.CreateField(ogr.FieldDefn('strfield', ogr.OFTString)) @@ -84,30 +81,18 @@ def ogr_pcidsk_1(): feat.SetField(0, 'bar') lyr.CreateFeature(feat) - if lyr.GetFeatureCount() != 2: - gdaltest.post_reason('failure') - return 'fail' + assert lyr.GetFeatureCount() == 2 lyr.DeleteFeature(1) - if lyr.GetFeatureCount() != 1: - gdaltest.post_reason('failure') - return 'fail' + assert lyr.GetFeatureCount() == 1 lyr.ResetReading() feat = lyr.GetNextFeature() - if feat is None: - gdaltest.post_reason('failure') - return 'fail' - if feat.GetField(0) != 'foo': - gdaltest.post_reason('failure') - return 'fail' - if feat.GetField(1) != 1: - gdaltest.post_reason('failure') - return 'fail' - if feat.GetField(2) != 3.45: - gdaltest.post_reason('failure') - return 'fail' + assert feat is not None + assert feat.GetField(0) == 'foo' + assert feat.GetField(1) == 1 + assert feat.GetField(2) == 3.45 for (wkt, layername, epsgcode) in wkts: geom = ogr.CreateGeometryFromWkt(wkt) @@ -123,104 +108,69 @@ def ogr_pcidsk_1(): lyr.ResetReading() feat = lyr.GetNextFeature() - if feat is None: - gdaltest.post_reason('failure') - print(layername) - return 'fail' + assert feat is not None, layername if feat.GetGeometryRef().ExportToWkt() != wkt: - gdaltest.post_reason('failure') feat.DumpReadable() - print(layername) - return 'fail' + pytest.fail(layername) ds = None - return 'success' - ############################################################################### # Test reading -def ogr_pcidsk_2(): +def test_ogr_pcidsk_2(): ogr_drv = ogr.GetDriverByName('PCIDSK') if ogr_drv is None: - return 'skip' + pytest.skip() ds = ogr.Open('tmp/ogr_pcidsk_1.pix') - if ds.GetLayerCount() != 2 + len(wkts): - return 'fail' + assert ds.GetLayerCount() == 2 + len(wkts) lyr = ds.GetLayerByName('nothing') - if lyr.GetGeomType() != ogr.wkbNone: - gdaltest.post_reason('failure') - return 'fail' + assert lyr.GetGeomType() == ogr.wkbNone feat = lyr.GetNextFeature() - if feat is None: - gdaltest.post_reason('failure') - return 'fail' + assert feat is not None lyr = ds.GetLayerByName('fields') feat = lyr.GetNextFeature() - if feat is None: - gdaltest.post_reason('failure') - return 'fail' - if feat.GetField(0) != 'foo': - gdaltest.post_reason('failure') - return 'fail' - if feat.GetField(1) != 1: - gdaltest.post_reason('failure') - return 'fail' - if feat.GetField(2) != 3.45: - gdaltest.post_reason('failure') - return 'fail' + assert feat is not None + assert feat.GetField(0) == 'foo' + assert feat.GetField(1) == 1 + assert feat.GetField(2) == 3.45 for (wkt, layername, epsgcode) in wkts: geom = ogr.CreateGeometryFromWkt(wkt) lyr = ds.GetLayerByName(layername) - if lyr.GetGeomType() != geom.GetGeometryType(): - gdaltest.post_reason('failure') - print(layername) - return 'fail' + assert lyr.GetGeomType() == geom.GetGeometryType(), layername srs = lyr.GetSpatialRef() if epsgcode != 0: ref_srs = osr.SpatialReference() ref_srs.ImportFromEPSG(epsgcode) - if srs is None or ref_srs.IsSame(srs) != 1: - gdaltest.post_reason('failure') - print(layername) - print(ref_srs) - print(srs) - return 'fail' + assert srs is not None and ref_srs.IsSame(srs) == 1, layername feat = lyr.GetNextFeature() - if feat is None: - gdaltest.post_reason('failure') - print(layername) - return 'fail' + assert feat is not None, layername if feat.GetGeometryRef().ExportToWkt() != wkt: - gdaltest.post_reason('failure') feat.DumpReadable() - print(layername) - return 'fail' + pytest.fail(layername) ds = None - return 'success' - ############################################################################### # Check with test_ogrsf -def ogr_pcidsk_3(): +def test_ogr_pcidsk_3(): import test_cli_utilities if test_cli_utilities.get_test_ogrsf_path() is None: - return 'skip' + pytest.skip() if ogr.GetDriverByName('PCIDSK') is None: - return 'skip' + pytest.skip() ret = gdaltest.runexternal(test_cli_utilities.get_test_ogrsf_path() + ' tmp/ogr_pcidsk_1.pix') @@ -243,47 +193,41 @@ def ogr_pcidsk_3(): # Test that we cannot open a raster only pcidsk in read-only mode -def ogr_pcidsk_4(): +def test_ogr_pcidsk_4(): if ogr.GetDriverByName('PCIDSK') is None: - return 'skip' + pytest.skip() if gdal.GetDriverByName('PCIDSK') is None: - return 'skip' + pytest.skip() ds = ogr.Open('../gdrivers/data/utm.pix') - if ds is not None: - return 'fail' + assert ds is None ds = None - return 'success' - ############################################################################### # Test that we can open a raster only pcidsk in update mode -def ogr_pcidsk_5(): +def test_ogr_pcidsk_5(): if ogr.GetDriverByName('PCIDSK') is None: - return 'skip' + pytest.skip() if gdal.GetDriverByName('PCIDSK') is None: - return 'skip' + pytest.skip() ds = ogr.Open('../gdrivers/data/utm.pix', update=1) - if ds is None: - return 'fail' + assert ds is not None ds = None - return 'success' - ############################################################################### -def ogr_pcidsk_add_field_to_non_empty_layer(): +def test_ogr_pcidsk_add_field_to_non_empty_layer(): if ogr.GetDriverByName('PCIDSK') is None: - return 'skip' + pytest.skip() tmpfile = '/vsimem/tmp.pix' ds = ogr.GetDriverByName('PCIDSK').CreateDataSource(tmpfile) @@ -294,8 +238,7 @@ def ogr_pcidsk_add_field_to_non_empty_layer(): lyr.CreateFeature(f) f = None with gdaltest.error_handler(): - if lyr.CreateField(ogr.FieldDefn('bar', ogr.OFTString)) == 0: - return 'fail' + assert lyr.CreateField(ogr.FieldDefn('bar', ogr.OFTString)) != 0 f = ogr.Feature(lyr.GetLayerDefn()) f['foo'] = 'bar2' lyr.CreateFeature(f) @@ -304,115 +247,78 @@ def ogr_pcidsk_add_field_to_non_empty_layer(): ogr.GetDriverByName('PCIDSK').DeleteDataSource(tmpfile) - return 'success' - ############################################################################### -def ogr_pcidsk_too_many_layers(): +def test_ogr_pcidsk_too_many_layers(): if ogr.GetDriverByName('PCIDSK') is None: - return 'skip' + pytest.skip() tmpfile = '/vsimem/tmp.pix' ds = ogr.GetDriverByName('PCIDSK').CreateDataSource(tmpfile) for i in range(1023): ds.CreateLayer('foo%d' % i) with gdaltest.error_handler(): - if ds.CreateLayer('foo') is not None: - return 'fail' + assert ds.CreateLayer('foo') is None ds = None ogr.GetDriverByName('PCIDSK').DeleteDataSource(tmpfile) - return 'success' - ############################################################################### # Check a polygon layer -def ogr_pcidsk_online_1(): +def test_ogr_pcidsk_online_1(): if ogr.GetDriverByName('PCIDSK') is None: - return 'skip' + pytest.skip() if not gdaltest.download_file('http://download.osgeo.org/gdal/data/pcidsk/sdk_testsuite/polygon.pix', 'polygon.pix'): - return 'skip' + pytest.skip() ds = ogr.Open('tmp/cache/polygon.pix') - if ds is None: - gdaltest.post_reason('failure') - return 'fail' + assert ds is not None lyr = ds.GetLayer(0) - if lyr is None: - gdaltest.post_reason('failure') - return 'fail' + assert lyr is not None feat = lyr.GetNextFeature() - if feat is None: - gdaltest.post_reason('failure') - return 'fail' + assert feat is not None geom = 'POLYGON ((479819.84375 4765180.5 0,479690.1875 4765259.5 0,479647.0 4765369.5 0,479730.375 4765400.5 0,480039.03125 4765539.5 0,480035.34375 4765558.5 0,480159.78125 4765610.5 0,480202.28125 4765482.0 0,480365.0 4765015.5 0,480389.6875 4764950.0 0,480133.96875 4764856.5 0,480080.28125 4764979.5 0,480082.96875 4765049.5 0,480088.8125 4765139.5 0,480059.90625 4765239.5 0,480019.71875 4765319.5 0,479980.21875 4765409.5 0,479909.875 4765370.0 0,479859.875 4765270.0 0,479819.84375 4765180.5 0))' if ogrtest.check_feature_geometry(feat, geom) != 0: - gdaltest.post_reason('failure') feat.DumpReadable() - return 'fail' - - return 'success' + pytest.fail() + ############################################################################### # Check a polygon layer -def ogr_pcidsk_online_2(): +def test_ogr_pcidsk_online_2(): import test_cli_utilities if test_cli_utilities.get_test_ogrsf_path() is None: - return 'skip' + pytest.skip() if ogr.GetDriverByName('PCIDSK') is None: - return 'skip' + pytest.skip() if not gdaltest.download_file('http://download.osgeo.org/gdal/data/pcidsk/sdk_testsuite/polygon.pix', 'polygon.pix'): - return 'skip' + pytest.skip() ret = gdaltest.runexternal(test_cli_utilities.get_test_ogrsf_path() + ' -ro tmp/cache/polygon.pix') - if ret.find('INFO') == -1 or ret.find('ERROR') != -1: - print(ret) - return 'fail' - - return 'success' + assert ret.find('INFO') != -1 and ret.find('ERROR') == -1 ############################################################################### # Cleanup -def ogr_pcidsk_cleanup(): +def test_ogr_pcidsk_cleanup(): gdal.Unlink('tmp/ogr_pcidsk_1.pix') - return 'success' - - -gdaltest_list = [ - ogr_pcidsk_1, - ogr_pcidsk_2, - ogr_pcidsk_3, - ogr_pcidsk_4, - ogr_pcidsk_5, - ogr_pcidsk_add_field_to_non_empty_layer, - ogr_pcidsk_too_many_layers, - ogr_pcidsk_online_1, - ogr_pcidsk_online_2, - ogr_pcidsk_cleanup] - -if __name__ == '__main__': - - gdaltest.setup_run('ogr_pcidsk') - gdaltest.run_tests(gdaltest_list) - sys.exit(gdaltest.summarize()) diff --git a/autotest/ogr/ogr_pdf.py b/autotest/ogr/ogr_pdf.py index 56b7c4b39a78..4cb73d54f9b1 100755 --- a/autotest/ogr/ogr_pdf.py +++ b/autotest/ogr/ogr_pdf.py @@ -29,15 +29,14 @@ # DEALINGS IN THE SOFTWARE. ############################################################################### -import sys -sys.path.append('../pymod') import gdaltest import ogrtest from osgeo import gdal from osgeo import ogr from osgeo import osr +import pytest def has_read_support(): @@ -57,10 +56,10 @@ def has_read_support(): # Test write support -def ogr_pdf_1(name='tmp/ogr_pdf_1.pdf', write_attributes='YES'): +def test_ogr_pdf_1(name='tmp/ogr_pdf_1.pdf', write_attributes='YES'): if ogr.GetDriverByName('PDF') is None: - return 'skip' + pytest.skip() sr = osr.SpatialReference() sr.ImportFromEPSG(4326) @@ -120,45 +119,31 @@ def ogr_pdf_1(name='tmp/ogr_pdf_1.pdf', write_attributes='YES'): with open(name, 'rb') as f: data = f.read(8192) - if wantedstream.encode('utf-8') not in data: - gdaltest.post_reason('Wrong text data in written PDF stream') - return 'fail' - - return 'success' + assert wantedstream.encode('utf-8') in data, \ + 'Wrong text data in written PDF stream' + ############################################################################### # Test read support -def ogr_pdf_2(name='tmp/ogr_pdf_1.pdf', has_attributes=True): +def test_ogr_pdf_2(name='tmp/ogr_pdf_1.pdf', has_attributes=True): if not has_read_support(): - return 'skip' + pytest.skip() ds = ogr.Open(name) - if ds is None: - gdaltest.post_reason('fail') - return 'fail' + assert ds is not None lyr = ds.GetLayerByName('first_layer') - if lyr is None: - gdaltest.post_reason('fail') - return 'fail' + assert lyr is not None if has_attributes: - if lyr.GetLayerDefn().GetFieldDefn(lyr.GetLayerDefn().GetFieldIndex('strfield')).GetType() != ogr.OFTString: - gdaltest.post_reason('fail') - return 'fail' - if lyr.GetLayerDefn().GetFieldDefn(lyr.GetLayerDefn().GetFieldIndex('intfield')).GetType() != ogr.OFTInteger: - gdaltest.post_reason('fail') - return 'fail' - if lyr.GetLayerDefn().GetFieldDefn(lyr.GetLayerDefn().GetFieldIndex('realfield')).GetType() != ogr.OFTReal: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.GetLayerDefn().GetFieldDefn(lyr.GetLayerDefn().GetFieldIndex('strfield')).GetType() == ogr.OFTString + assert lyr.GetLayerDefn().GetFieldDefn(lyr.GetLayerDefn().GetFieldIndex('intfield')).GetType() == ogr.OFTInteger + assert lyr.GetLayerDefn().GetFieldDefn(lyr.GetLayerDefn().GetFieldIndex('realfield')).GetType() == ogr.OFTReal else: - if lyr.GetLayerDefn().GetFieldCount() != 0: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.GetLayerDefn().GetFieldCount() == 0 if has_attributes: feat = lyr.GetNextFeature() @@ -172,119 +157,103 @@ def ogr_pdf_2(name='tmp/ogr_pdf_1.pdf', has_attributes=True): feat = lyr.GetNextFeature() if ogrtest.check_feature_geometry(feat, ogr.CreateGeometryFromWkt('LINESTRING(2 48,3 50)')) != 0: feat.DumpReadable() - gdaltest.post_reason('fail') - return 'fail' + pytest.fail() if has_attributes: if feat.GetField('strfield') != 'str': feat.DumpReadable() - gdaltest.post_reason('fail') - return 'fail' + pytest.fail() if feat.GetField('intfield') != 1: feat.DumpReadable() - gdaltest.post_reason('fail') - return 'fail' + pytest.fail() if abs(feat.GetFieldAsDouble('realfield') - 2.34) > 1e-10: feat.DumpReadable() - gdaltest.post_reason('fail') - return 'fail' + pytest.fail() feat = lyr.GetNextFeature() if ogrtest.check_feature_geometry(feat, ogr.CreateGeometryFromWkt('POLYGON((2 48,2 49,3 49,3 48,2 48))')) != 0: feat.DumpReadable() - gdaltest.post_reason('fail') - return 'fail' + pytest.fail() feat = lyr.GetNextFeature() if ogrtest.check_feature_geometry(feat, ogr.CreateGeometryFromWkt('POLYGON((2 48,2 49,3 49,3 48,2 48),(2.25 48.25,2.25 48.75,2.75 48.75,2.75 48.25,2.25 48.25))')) != 0: feat.DumpReadable() - gdaltest.post_reason('fail') - return 'fail' + pytest.fail() for i in range(10): feat = lyr.GetNextFeature() if ogrtest.check_feature_geometry(feat, ogr.CreateGeometryFromWkt('POINT(%f 49.1)' % (2 + i * 0.05))) != 0: feat.DumpReadable() - gdaltest.post_reason('fail with ogr-sym-%d' % i) - return 'fail' + pytest.fail('fail with ogr-sym-%d' % i) feat = lyr.GetNextFeature() if ogrtest.check_feature_geometry(feat, ogr.CreateGeometryFromWkt('POINT(2.5 49.1)')) != 0: feat.DumpReadable() - gdaltest.post_reason('fail with raster icon') - return 'fail' + pytest.fail('fail with raster icon') ds = None - return 'success' - ############################################################################### # Test write support without writing attributes -def ogr_pdf_3(): - return ogr_pdf_1('tmp/ogr_pdf_2.pdf', 'NO') +def test_ogr_pdf_3(): + return test_ogr_pdf_1('tmp/ogr_pdf_2.pdf', 'NO') ############################################################################### # Check read support without writing attributes -def ogr_pdf_4(): - return ogr_pdf_2('tmp/ogr_pdf_2.pdf', False) +def test_ogr_pdf_4(): + return test_ogr_pdf_2('tmp/ogr_pdf_2.pdf', False) ############################################################################### # Switch from poppler to podofo if both are available -def ogr_pdf_4_podofo(): +def test_ogr_pdf_4_podofo(): gdal_pdf_drv = gdal.GetDriverByName('PDF') if gdal_pdf_drv is None: - return 'skip' + pytest.skip() md = gdal_pdf_drv.GetMetadata() if 'HAVE_POPPLER' in md and 'HAVE_PODOFO' in md: gdal.SetConfigOption("GDAL_PDF_LIB", "PODOFO") print('Using podofo now') - ret = ogr_pdf_4() + ret = test_ogr_pdf_4() gdal.SetConfigOption("GDAL_PDF_LIB", None) return ret - return 'skip' + pytest.skip() ############################################################################### # Test read support with OGR_PDF_READ_NON_STRUCTURED=YES -def ogr_pdf_5(): +def test_ogr_pdf_5(): if not has_read_support(): - return 'skip' + pytest.skip() with gdaltest.config_option('OGR_PDF_READ_NON_STRUCTURED', 'YES'): ds = ogr.Open('data/drawing.pdf') - if ds is None: - gdaltest.post_reason('fail') - return 'fail' + assert ds is not None # Note: the circle is wrongly drawned as a diamond lyr = ds.GetLayer(0) - if lyr.GetFeatureCount() != 8: - gdaltest.post_reason('fail') - return 'fail' - - return 'success' + assert lyr.GetFeatureCount() == 8 ############################################################################### # Test read support with a non-OGR datasource -def ogr_pdf_online_1(): +def test_ogr_pdf_online_1(): if not has_read_support(): - return 'skip' + pytest.skip() if not gdaltest.download_file('http://www.terragotech.com/images/pdf/webmap_urbansample.pdf', 'webmap_urbansample.pdf'): - return 'skip' + pytest.skip() expected_layers = [ ["Cadastral Boundaries", ogr.wkbPolygon], @@ -301,48 +270,35 @@ def ogr_pdf_online_1(): ] ds = ogr.Open('tmp/cache/webmap_urbansample.pdf') - if ds is None: - gdaltest.post_reason('fail') - return 'fail' + assert ds is not None - if ds.GetLayerCount() != len(expected_layers): - gdaltest.post_reason('fail') - print(ds.GetLayerCount()) - return 'fail' + assert ds.GetLayerCount() == len(expected_layers) for i in range(ds.GetLayerCount()): - if ds.GetLayer(i).GetName() != expected_layers[i][0]: - gdaltest.post_reason('fail') - print('%d : %s' % (i, ds.GetLayer(i).GetName())) - return 'fail' + assert ds.GetLayer(i).GetName() == expected_layers[i][0], \ + ('%d : %s' % (i, ds.GetLayer(i).GetName())) - if ds.GetLayer(i).GetGeomType() != expected_layers[i][1]: - gdaltest.post_reason('fail') - print('%d : %d' % (i, ds.GetLayer(i).GetGeomType())) - return 'fail' + assert ds.GetLayer(i).GetGeomType() == expected_layers[i][1], \ + ('%d : %d' % (i, ds.GetLayer(i).GetGeomType())) lyr = ds.GetLayerByName('Water Points') feat = lyr.GetNextFeature() if ogrtest.check_feature_geometry(feat, ogr.CreateGeometryFromWkt('POINT (724431.316665166523308 7672947.212302438914776)')) != 0: feat.DumpReadable() - return 'fail' - if feat.GetField('ID') != 'VL46': - gdaltest.post_reason('fail') - return 'fail' - - return 'success' + pytest.fail() + assert feat.GetField('ID') == 'VL46' ############################################################################### # Test read support of non-structured content -def ogr_pdf_online_2(): +def test_ogr_pdf_online_2(): if not has_read_support(): - return 'skip' + pytest.skip() if not gdaltest.download_file('https://download.osgeo.org/gdal/data/pdf/340711752_Azusa_FSTopo.pdf', '340711752_Azusa_FSTopo.pdf'): - return 'skip' + pytest.skip() expected_layers = [ ['Other_5', 0], @@ -382,61 +338,32 @@ def ogr_pdf_online_2(): ] ds = ogr.Open('tmp/cache/340711752_Azusa_FSTopo.pdf') - if ds is None: - gdaltest.post_reason('fail') - return 'fail' + assert ds is not None if ds.GetLayerCount() != len(expected_layers): - gdaltest.post_reason('fail') - print(ds.GetLayerCount()) for lyr in ds: print(lyr.GetName(), lyr.GetGeomType()) - return 'fail' + pytest.fail(ds.GetLayerCount()) for i in range(ds.GetLayerCount()): - if ds.GetLayer(i).GetName() != expected_layers[i][0]: - gdaltest.post_reason('fail') - print('%d : %s' % (i, ds.GetLayer(i).GetName())) - return 'fail' + assert ds.GetLayer(i).GetName() == expected_layers[i][0], \ + ('%d : %s' % (i, ds.GetLayer(i).GetName())) - if ds.GetLayer(i).GetGeomType() != expected_layers[i][1]: - gdaltest.post_reason('fail') - print('%d : %d' % (i, ds.GetLayer(i).GetGeomType())) - return 'fail' - - return 'success' + assert ds.GetLayer(i).GetGeomType() == expected_layers[i][1], \ + ('%d : %d' % (i, ds.GetLayer(i).GetGeomType())) + ############################################################################### # Cleanup -def ogr_pdf_cleanup(): +def test_ogr_pdf_cleanup(): if ogr.GetDriverByName('PDF') is None: - return 'skip' + pytest.skip() ogr.GetDriverByName('PDF').DeleteDataSource('tmp/ogr_pdf_1.pdf') ogr.GetDriverByName('PDF').DeleteDataSource('tmp/ogr_pdf_2.pdf') - return 'success' - - -gdaltest_list = [ - ogr_pdf_1, - ogr_pdf_2, - ogr_pdf_3, - ogr_pdf_4, - ogr_pdf_4_podofo, - ogr_pdf_5, - ogr_pdf_online_1, - ogr_pdf_online_2, - ogr_pdf_cleanup -] - -if __name__ == '__main__': - - gdaltest.setup_run('ogr_pdf') - gdaltest.run_tests(gdaltest_list) - sys.exit(gdaltest.summarize()) diff --git a/autotest/ogr/ogr_pds.py b/autotest/ogr/ogr_pds.py index 4d55b8c2120b..deacf521fd49 100755 --- a/autotest/ogr/ogr_pds.py +++ b/autotest/ogr/ogr_pds.py @@ -28,79 +28,58 @@ # DEALINGS IN THE SOFTWARE. ############################################################################### -import sys -sys.path.append('../pymod') import gdaltest import ogrtest from osgeo import ogr +import pytest ############################################################################### # Basic test -def ogr_pds_1(): +def test_ogr_pds_1(): ds = ogr.Open('data/ap01578l.lbl') - if ds is None: - gdaltest.post_reason('cannot open dataset') - return 'fail' + assert ds is not None, 'cannot open dataset' lyr = ds.GetLayerByName('RAMAPPING') - if lyr is None: - gdaltest.post_reason('cannot find layer') - return 'fail' + assert lyr is not None, 'cannot find layer' - if lyr.GetFeatureCount() != 74786: - gdaltest.post_reason('did not get expected feature count') - return 'fail' + assert lyr.GetFeatureCount() == 74786, 'did not get expected feature count' with gdaltest.error_handler(): feat = lyr.GetNextFeature() if feat.GetField('NOISE_COUNTS_1') != 96: feat.DumpReadable() - return 'fail' + pytest.fail() geom = feat.GetGeometryRef() if ogrtest.check_feature_geometry(feat, 'POINT (146.1325 -55.648)', max_error=0.000000001) != 0: print('did not get expected geom') - print(geom.ExportToWkt()) - return 'fail' + pytest.fail(geom.ExportToWkt()) with gdaltest.error_handler(): feat = lyr.GetFeature(1) if feat.GetField('MARS_RADIUS') != 3385310.2: feat.DumpReadable() - return 'fail' - - return 'success' + pytest.fail() + ############################################################################### # Read IEEE_FLOAT columns (see https://github.com/OSGeo/gdal/issues/570) -def ogr_pds_2(): +def test_ogr_pds_2(): ds = ogr.Open('data/virsvd_orb_11187_050618.lbl') lyr = ds.GetLayer(0) f = lyr.GetNextFeature() if abs(f['INCIDENCE_ANGLE'] - 3.56775538) > 1e-7 or abs(f['TEMP_2'] - 28.1240005493164) > 1e-7: f.DumpReadable() - return 'fail' - - return 'success' - - -gdaltest_list = [ - ogr_pds_1, - ogr_pds_2, -] - -if __name__ == '__main__': + pytest.fail() - gdaltest.setup_run('ogr_pds') + - gdaltest.run_tests(gdaltest_list) - sys.exit(gdaltest.summarize()) diff --git a/autotest/ogr/ogr_pg.py b/autotest/ogr/ogr_pg.py index 96eb0ebddb4d..c8887b8d451d 100755 --- a/autotest/ogr/ogr_pg.py +++ b/autotest/ogr/ogr_pg.py @@ -31,7 +31,7 @@ import sys import shutil -sys.path.append('../pymod') +import pytest import gdaltest import ogrtest @@ -39,6 +39,10 @@ from osgeo import osr from osgeo import gdal + +pytestmark = pytest.mark.require_driver('PostgreSQL') + + ############################################################################### # Return true if 'layer_name' is one of the reported layers of pg_ds @@ -60,11 +64,33 @@ def ogr_pg_check_layer_in_list(ds, layer_name): # ############################################################################### -# Open Database. +# Run tests with PostGIS enabled and then with PostGIS disabled + + +@pytest.fixture( + params=['postgis', 'no-postgis'], + scope='module', + autouse=True +) +def with_and_without_postgis(request): + test_ogr_pg_1() + if gdaltest.pg_ds is None: + pytest.skip() + + with_postgis = request.param == 'postgis' + + if with_postgis and not gdaltest.pg_has_postgis: + pytest.skip() + with gdaltest.config_option("PG_USE_POSTGIS", 'YES' if with_postgis else 'NO'): + yield with_postgis -def ogr_pg_1(): +############################################################################### +# Open Database. + + +def test_ogr_pg_1(): gdaltest.pg_ds = None gdaltest.pg_use_copy = gdal.GetConfigOption('PG_USE_COPY', None) val = gdal.GetConfigOption('OGR_PG_CONNECTION_STRING', None) @@ -81,10 +107,6 @@ def ogr_pg_1(): # 7.4 # gdaltest.pg_connection_string='dbname=autotest port=5436 user=postgres' - gdaltest.pg_dr = ogr.GetDriverByName('PostgreSQL') - if gdaltest.pg_dr is None: - return 'skip' - try: gdal.PushErrorHandler('CPLQuietErrorHandler') gdaltest.pg_ds = ogr.Open('PG:' + gdaltest.pg_connection_string, update=1) @@ -94,7 +116,7 @@ def ogr_pg_1(): gdal.PopErrorHandler() if gdaltest.pg_ds is None: - return 'skip' + pytest.skip() sql_lyr = gdaltest.pg_ds.ExecuteSQL('SELECT version()') feat = sql_lyr.GetNextFeature() @@ -137,16 +159,15 @@ def ogr_pg_1(): gdaltest.pg_has_postgis = False print('PostGIS NOT available !') - return 'success' - + ############################################################################### # Create table from data/poly.shp -def ogr_pg_2(): +def test_ogr_pg_2(): if gdaltest.pg_ds is None: - return 'skip' + pytest.skip() gdal.PushErrorHandler('CPLQuietErrorHandler') gdaltest.pg_ds.ExecuteSQL('DELLAYER:tpoly') @@ -161,36 +182,24 @@ def ogr_pg_2(): # Check capabilities if gdaltest.pg_has_postgis: - if not gdaltest.pg_lyr.TestCapability(ogr.OLCFastSpatialFilter): - return 'fail' - if not gdaltest.pg_lyr.TestCapability(ogr.OLCFastGetExtent): - return 'fail' + assert gdaltest.pg_lyr.TestCapability(ogr.OLCFastSpatialFilter) + assert gdaltest.pg_lyr.TestCapability(ogr.OLCFastGetExtent) else: - if gdaltest.pg_lyr.TestCapability(ogr.OLCFastSpatialFilter): - return 'fail' - if gdaltest.pg_lyr.TestCapability(ogr.OLCFastGetExtent): - return 'fail' - - if not gdaltest.pg_lyr.TestCapability(ogr.OLCRandomRead): - return 'fail' - if not gdaltest.pg_lyr.TestCapability(ogr.OLCFastFeatureCount): - return 'fail' - if not gdaltest.pg_lyr.TestCapability(ogr.OLCFastSetNextByIndex): - return 'fail' + assert not gdaltest.pg_lyr.TestCapability(ogr.OLCFastSpatialFilter) + assert not gdaltest.pg_lyr.TestCapability(ogr.OLCFastGetExtent) + + assert gdaltest.pg_lyr.TestCapability(ogr.OLCRandomRead) + assert gdaltest.pg_lyr.TestCapability(ogr.OLCFastFeatureCount) + assert gdaltest.pg_lyr.TestCapability(ogr.OLCFastSetNextByIndex) try: ogr.OLCStringsAsUTF8 - if not gdaltest.pg_lyr.TestCapability(ogr.OLCStringsAsUTF8): - return 'fail' + assert gdaltest.pg_lyr.TestCapability(ogr.OLCStringsAsUTF8) except: pass - if not gdaltest.pg_lyr.TestCapability(ogr.OLCSequentialWrite): - return 'fail' - if not gdaltest.pg_lyr.TestCapability(ogr.OLCCreateField): - return 'fail' - if not gdaltest.pg_lyr.TestCapability(ogr.OLCRandomWrite): - return 'fail' - if not gdaltest.pg_lyr.TestCapability(ogr.OLCTransactions): - return 'fail' + assert gdaltest.pg_lyr.TestCapability(ogr.OLCSequentialWrite) + assert gdaltest.pg_lyr.TestCapability(ogr.OLCCreateField) + assert gdaltest.pg_lyr.TestCapability(ogr.OLCRandomWrite) + assert gdaltest.pg_lyr.TestCapability(ogr.OLCTransactions) ###################################################### # Setup Schema @@ -222,9 +231,8 @@ def ogr_pg_2(): gdaltest.pg_lyr.CreateFeature(dst_feat) if gdaltest.pg_retrieve_fid: got_fid = dst_feat.GetFID() - if got_fid != expected_fid: - gdaltest.post_reason("didn't get expected fid : %d instead of %d" % (got_fid, expected_fid)) - return 'fail' + assert got_fid == expected_fid, \ + ("didn't get expected fid : %d instead of %d" % (got_fid, expected_fid)) expected_fid = expected_fid + 1 @@ -232,19 +240,77 @@ def ogr_pg_2(): dst_feat.Destroy() - return 'success' + +############################################################################### +# Test reading a layer extent + + +def test_ogr_pg_19(): + + if gdaltest.pg_ds is None: + pytest.skip() + + layer = gdaltest.pg_ds.GetLayerByName('tpoly') + assert layer is not None, 'did not get tpoly layer' + + extent = layer.GetExtent() + expect = (478315.53125, 481645.3125, 4762880.5, 4765610.5) + + minx = abs(extent[0] - expect[0]) + maxx = abs(extent[1] - expect[1]) + miny = abs(extent[2] - expect[2]) + maxy = abs(extent[3] - expect[3]) + + if max(minx, maxx, miny, maxy) > 0.0001: + print(extent) + pytest.fail('Extents do not match') + + estimated_extent = layer.GetExtent(force=0) + if not gdaltest.pg_has_postgis: + # The OGRLayer default implementation in force = 0 returns error + if estimated_extent != (0, 0, 0, 0): + print(extent) + pytest.fail('Wrong estimated extent') + else: + # Better testing needed ? + if estimated_extent == (0, 0, 0, 0): + print(extent) + pytest.fail('Wrong estimated extent') + + +############################################################################### +# Test reading a SQL result layer extent + + +def test_ogr_pg_19_2(): + + if gdaltest.pg_ds is None: + pytest.skip() + + sql_lyr = gdaltest.pg_ds.ExecuteSQL('select * from tpoly') + + extent = sql_lyr.GetExtent() + expect = (478315.53125, 481645.3125, 4762880.5, 4765610.5) + + minx = abs(extent[0] - expect[0]) + maxx = abs(extent[1] - expect[1]) + miny = abs(extent[2] - expect[2]) + maxy = abs(extent[3] - expect[3]) + + assert max(minx, maxx, miny, maxy) <= 0.0001, 'Extents do not match' + + gdaltest.pg_ds.ReleaseResultSet(sql_lyr) + ############################################################################### # Verify that stuff we just wrote is still OK. -def ogr_pg_3(): +def test_ogr_pg_3(): if gdaltest.pg_ds is None: - return 'skip' + pytest.skip() - if gdaltest.pg_lyr.GetFeatureCount() != 10: - gdaltest.post_reason('GetFeatureCount() returned %d instead of 10' % gdaltest.pg_lyr.GetFeatureCount()) - return 'fail' + assert gdaltest.pg_lyr.GetFeatureCount() == 10 expect = [168, 169, 166, 158, 165] @@ -252,9 +318,7 @@ def ogr_pg_3(): tr = ogrtest.check_features_against_list(gdaltest.pg_lyr, 'eas_id', expect) - if gdaltest.pg_lyr.GetFeatureCount() != 5: - gdaltest.post_reason('GetFeatureCount() returned %d instead of 5' % gdaltest.pg_lyr.GetFeatureCount()) - return 'fail' + assert gdaltest.pg_lyr.GetFeatureCount() == 5 gdaltest.pg_lyr.SetAttributeFilter(None) @@ -262,31 +326,29 @@ def ogr_pg_3(): orig_feat = gdaltest.poly_feat[i] read_feat = gdaltest.pg_lyr.GetNextFeature() - if ogrtest.check_feature_geometry(read_feat, orig_feat.GetGeometryRef(), - max_error=0.001) != 0: - return 'fail' + assert (ogrtest.check_feature_geometry(read_feat, orig_feat.GetGeometryRef(), + max_error=0.001) == 0) for fld in range(3): - if orig_feat.GetField(fld) != read_feat.GetField(fld): - gdaltest.post_reason('Attribute %d does not match' % fld) - return 'fail' + assert orig_feat.GetField(fld) == read_feat.GetField(fld), \ + ('Attribute %d does not match' % fld) read_feat.Destroy() orig_feat.Destroy() gdaltest.poly_feat = None - return 'success' if tr else 'fail' + assert tr ############################################################################### # Write more features with a bunch of different geometries, and verify the # geometries are still OK. -def ogr_pg_4(): +def test_ogr_pg_4(): if gdaltest.pg_ds is None: - return 'skip' + pytest.skip() dst_feat = ogr.Feature(feature_def=gdaltest.pg_lyr.GetLayerDefn()) wkt_list = ['10', '2', '1', '3d_1', '4', '5', '6'] @@ -314,47 +376,42 @@ def ogr_pg_4(): if ogrtest.check_feature_geometry(feat_read, geom) != 0: print(item) print(wkt) - print(geom_read) - return 'fail' + pytest.fail(geom_read) feat_read.Destroy() dst_feat.Destroy() gdaltest.pg_lyr.ResetReading() # to close implicit transaction - return 'success' - ############################################################################### # Test ExecuteSQL() results layers without geometry. -def ogr_pg_5(): +def test_ogr_pg_5(): if gdaltest.pg_ds is None: - return 'skip' + pytest.skip() expect = [None, 179, 173, 172, 171, 170, 169, 168, 166, 165, 158] sql_lyr = gdaltest.pg_ds.ExecuteSQL('select distinct eas_id from tpoly order by eas_id desc') - if sql_lyr.GetFeatureCount() != 11: - gdaltest.post_reason('GetFeatureCount() returned %d instead of 11' % sql_lyr.GetFeatureCount()) - return 'fail' + assert sql_lyr.GetFeatureCount() == 11 tr = ogrtest.check_features_against_list(sql_lyr, 'eas_id', expect) gdaltest.pg_ds.ReleaseResultSet(sql_lyr) - return 'success' if tr else 'fail' + assert tr ############################################################################### # Test ExecuteSQL() results layers with geometry. -def ogr_pg_6(): +def test_ogr_pg_6(): if gdaltest.pg_ds is None: - return 'skip' + pytest.skip() sql_lyr = gdaltest.pg_ds.ExecuteSQL("select * from tpoly where prfedea = '2'") @@ -373,26 +430,22 @@ def ogr_pg_6(): sql_lyr.SetSpatialFilter(geom) geom.Destroy() - if sql_lyr.GetFeatureCount() != 0: - gdaltest.post_reason('GetFeatureCount() returned %d instead of 0' % sql_lyr.GetFeatureCount()) - return 'fail' + assert sql_lyr.GetFeatureCount() == 0 - if sql_lyr.GetNextFeature() is not None: - gdaltest.post_reason('GetNextFeature() did not return None') - return 'fail' + assert sql_lyr.GetNextFeature() is None, 'GetNextFeature() did not return None' gdaltest.pg_ds.ReleaseResultSet(sql_lyr) - return 'success' if tr else 'fail' + assert tr ############################################################################### # Test spatial filtering. -def ogr_pg_7(): +def test_ogr_pg_7(): if gdaltest.pg_ds is None: - return 'skip' + pytest.skip() gdaltest.pg_lyr.SetAttributeFilter(None) @@ -401,24 +454,20 @@ def ogr_pg_7(): gdaltest.pg_lyr.SetSpatialFilter(geom) geom.Destroy() - if gdaltest.pg_lyr.GetFeatureCount() != 1: - gdaltest.post_reason('GetFeatureCount() returned %d instead of 1' % gdaltest.pg_lyr.GetFeatureCount()) - return 'fail' + assert gdaltest.pg_lyr.GetFeatureCount() == 1 tr = ogrtest.check_features_against_list(gdaltest.pg_lyr, 'eas_id', [158]) gdaltest.pg_lyr.SetAttributeFilter('eas_id = 158') - if gdaltest.pg_lyr.GetFeatureCount() != 1: - gdaltest.post_reason('GetFeatureCount() returned %d instead of 1' % gdaltest.pg_lyr.GetFeatureCount()) - return 'fail' + assert gdaltest.pg_lyr.GetFeatureCount() == 1 gdaltest.pg_lyr.SetAttributeFilter(None) gdaltest.pg_lyr.SetSpatialFilter(None) - return 'success' if tr else 'fail' + assert tr ############################################################################### # Write a feature with too long a text value for a fixed length text field. @@ -429,10 +478,10 @@ def ogr_pg_7(): # No geometry in this test. -def ogr_pg_8(): +def test_ogr_pg_8(): if gdaltest.pg_ds is None: - return 'skip' + pytest.skip() dst_feat = ogr.Feature(feature_def=gdaltest.pg_lyr.GetLayerDefn()) @@ -444,27 +493,22 @@ def ogr_pg_8(): gdaltest.pg_lyr.SetAttributeFilter("PRFEDEA = 'CrazyKey'") feat_read = gdaltest.pg_lyr.GetNextFeature() - if feat_read is None: - gdaltest.post_reason('creating crazy feature failed!') - return 'fail' + assert feat_read is not None, 'creating crazy feature failed!' - if feat_read.GetField('shortname') != 'Crazy"\'L': - gdaltest.post_reason('Vvalue not properly escaped or truncated:' + + assert feat_read.GetField('shortname') == 'Crazy"\'L', \ + ('Vvalue not properly escaped or truncated:' + feat_read.GetField('shortname')) - return 'fail' feat_read.Destroy() - return 'success' - ############################################################################### # Verify inplace update of a feature with SetFeature(). -def ogr_pg_9(): +def test_ogr_pg_9(): if gdaltest.pg_ds is None: - return 'skip' + pytest.skip() gdaltest.pg_lyr.SetAttributeFilter("PRFEDEA = 'CrazyKey'") feat = gdaltest.pg_lyr.GetNextFeature() @@ -478,69 +522,55 @@ def ogr_pg_9(): if gdaltest.pg_lyr.SetFeature(feat) != 0: feat.Destroy() - gdaltest.post_reason('SetFeature() method failed.') - return 'fail' + pytest.fail('SetFeature() method failed.') fid = feat.GetFID() feat.Destroy() feat = gdaltest.pg_lyr.GetFeature(fid) - if feat is None: - gdaltest.post_reason('GetFeature(%d) failed.' % fid) - return 'fail' + assert feat is not None, ('GetFeature(%d) failed.' % fid) shortname = feat.GetField('SHORTNAME') - if shortname[:5] != 'Reset': - gdaltest.post_reason('SetFeature() did not update SHORTNAME, got %s.' + assert shortname[:5] == 'Reset', ('SetFeature() did not update SHORTNAME, got %s.' % shortname) - return 'fail' if ogrtest.check_feature_geometry(feat, 'POINT(5 6 7)') != 0: print(feat.GetGeometryRef()) - gdaltest.post_reason('Geometry update failed') - return 'fail' + pytest.fail('Geometry update failed') feat.SetGeometryDirectly(None) if gdaltest.pg_lyr.SetFeature(feat) != 0: feat.Destroy() - gdaltest.post_reason('SetFeature() method failed.') - return 'fail' + pytest.fail('SetFeature() method failed.') feat.Destroy() feat = gdaltest.pg_lyr.GetFeature(fid) - if feat.GetGeometryRef() is not None: - print(feat.GetGeometryRef()) - gdaltest.post_reason('Geometry update failed. null geometry expected') - return 'fail' + assert feat.GetGeometryRef() is None, \ + 'Geometry update failed. null geometry expected' feat.SetFieldNull('SHORTNAME') gdaltest.pg_lyr.SetFeature(feat) feat = gdaltest.pg_lyr.GetFeature(fid) - if not feat.IsFieldNull('SHORTNAME'): - gdaltest.post_reason('SHORTNAME update failed. null value expected') - return 'fail' + assert feat.IsFieldNull('SHORTNAME'), 'SHORTNAME update failed. null value expected' # Test updating non-existing feature feat.SetFID(-10) if gdaltest.pg_lyr.SetFeature(feat) != ogr.OGRERR_NON_EXISTING_FEATURE: feat.Destroy() - gdaltest.post_reason('Expected failure of SetFeature().') - return 'fail' + pytest.fail('Expected failure of SetFeature().') feat.Destroy() - return 'success' - ############################################################################### # Verify that DeleteFeature() works properly. -def ogr_pg_10(): +def test_ogr_pg_10(): if gdaltest.pg_ds is None: - return 'skip' + pytest.skip() gdaltest.pg_lyr.SetAttributeFilter("PRFEDEA = 'CrazyKey'") feat = gdaltest.pg_lyr.GetNextFeature() @@ -549,9 +579,7 @@ def ogr_pg_10(): fid = feat.GetFID() feat.Destroy() - if gdaltest.pg_lyr.DeleteFeature(fid) != 0: - gdaltest.post_reason('DeleteFeature() method failed.') - return 'fail' + assert gdaltest.pg_lyr.DeleteFeature(fid) == 0, 'DeleteFeature() method failed.' gdaltest.pg_lyr.SetAttributeFilter("PRFEDEA = 'CrazyKey'") feat = gdaltest.pg_lyr.GetNextFeature() @@ -559,24 +587,20 @@ def ogr_pg_10(): if feat is not None: feat.Destroy() - gdaltest.post_reason('DeleteFeature() seems to have had no effect.') - return 'fail' + pytest.fail('DeleteFeature() seems to have had no effect.') # Test deleting non-existing feature - if gdaltest.pg_lyr.DeleteFeature(-10) != ogr.OGRERR_NON_EXISTING_FEATURE: - gdaltest.post_reason('Expected failure of DeleteFeature().') - return 'fail' - - return 'success' + assert gdaltest.pg_lyr.DeleteFeature(-10) == ogr.OGRERR_NON_EXISTING_FEATURE, \ + 'Expected failure of DeleteFeature().' ############################################################################### # Create table from data/poly.shp in INSERT mode. -def ogr_pg_11(): +def test_ogr_pg_11(): if gdaltest.pg_ds is None: - return 'skip' + pytest.skip() gdal.PushErrorHandler('CPLQuietErrorHandler') gdaltest.pg_ds.ExecuteSQL('DELLAYER:tpolycopy') @@ -621,15 +645,13 @@ def ogr_pg_11(): gdal.SetConfigOption('PG_USE_COPY', gdaltest.pg_use_copy) - return 'success' - ############################################################################### # Verify that stuff we just wrote is still OK. -def ogr_pg_12(): +def test_ogr_pg_12(): if gdaltest.pg_ds is None: - return 'skip' + pytest.skip() gdaltest.pgc_lyr.ResetReading() gdaltest.pgc_lyr.SetAttributeFilter(None) @@ -638,14 +660,12 @@ def ogr_pg_12(): orig_feat = gdaltest.poly_feat[i] read_feat = gdaltest.pgc_lyr.GetNextFeature() - if ogrtest.check_feature_geometry(read_feat, orig_feat.GetGeometryRef(), - max_error=0.001) != 0: - return 'fail' + assert (ogrtest.check_feature_geometry(read_feat, orig_feat.GetGeometryRef(), + max_error=0.001) == 0) for fld in range(3): - if orig_feat.GetField(fld) != read_feat.GetField(fld): - gdaltest.post_reason('Attribute %d does not match' % fld) - return 'fail' + assert orig_feat.GetField(fld) == read_feat.GetField(fld), \ + ('Attribute %d does not match' % fld) read_feat.Destroy() orig_feat.Destroy() @@ -653,16 +673,14 @@ def ogr_pg_12(): gdaltest.poly_feat = None gdaltest.pgc_lyr.ResetReading() # to close implicit transaction - return 'success' - ############################################################################### # Create a table with some date fields. -def ogr_pg_13(): +def test_ogr_pg_13(): if gdaltest.pg_ds is None: - return 'skip' + pytest.skip() gdal.PushErrorHandler('CPLQuietErrorHandler') gdaltest.pg_ds.ExecuteSQL('DELLAYER:datetest') @@ -689,16 +707,14 @@ def ogr_pg_13(): # Create a populated records. gdaltest.pg_ds.ExecuteSQL("INSERT INTO datetest ( ogrdate, ogrtime, ogrdatetime, tsz, ts, dt, tm) VALUES ( '2005-10-12 10:41:33-05', '2005-10-12 10:41:33-05', '2005-10-12 10:41:33-05', '2005-10-12 10:41:33-05','2005-10-12 10:41:33-05','2005-10-12 10:41:33-05','2005-10-12 10:41:33-05' )") - return 'success' - ############################################################################### # Verify that stuff we just wrote is still OK. # Fetch in several timezones to test our timezone processing. -def ogr_pg_14(): +def test_ogr_pg_14(): if gdaltest.pg_ds is None: - return 'skip' + pytest.skip() ds = ogr.Open('PG:' + gdaltest.pg_connection_string, update=1) @@ -714,9 +730,8 @@ def ogr_pg_14(): or feat.GetFieldAsString('ts') != '2005/10/12 10:41:33' \ or feat.GetFieldAsString('dt') != '2005/10/12' \ or feat.GetFieldAsString('tm') != '10:41:33': - gdaltest.post_reason('UTC value wrong') feat.DumpReadable() - return 'fail' + pytest.fail('UTC value wrong') sql_lyr = ds.ExecuteSQL("select * from pg_timezone_names where name = 'Canada/Newfoundland'") if sql_lyr is None: @@ -737,9 +752,8 @@ def ogr_pg_14(): or feat.GetFieldAsString('ts') != '2005/10/12 10:41:33' \ or feat.GetFieldAsString('dt') != '2005/10/12' \ or feat.GetFieldAsString('tm') != '10:41:33': - gdaltest.post_reason('Newfoundland value wrong') feat.DumpReadable() - return 'fail' + pytest.fail('Newfoundland value wrong') ds.ExecuteSQL('set timezone to "+5"') @@ -748,23 +762,20 @@ def ogr_pg_14(): feat = lyr.GetNextFeature() if feat.GetFieldAsString('ogrdatetime') != '2005/10/12 20:41:33+05' \ or feat.GetFieldAsString('tsz') != '2005/10/12 20:41:33+05': - gdaltest.post_reason('+5 value wrong') feat.DumpReadable() - return 'fail' + pytest.fail('+5 value wrong') feat = None ds.Destroy() - return 'success' - ############################################################################### # Test very large query. -def ogr_pg_15(): +def test_ogr_pg_15(): if gdaltest.pg_ds is None: - return 'skip' + pytest.skip() expect = [169] @@ -778,16 +789,16 @@ def ogr_pg_15(): 'eas_id', expect) gdaltest.pg_lyr.SetAttributeFilter(None) - return 'success' if tr else 'fail' + assert tr ############################################################################### # Test very large statement. -def ogr_pg_16(): +def test_ogr_pg_16(): if gdaltest.pg_ds is None: - return 'skip' + pytest.skip() expect = [169] @@ -804,16 +815,16 @@ def ogr_pg_16(): gdaltest.pg_ds.ReleaseResultSet(lyr) - return 'success' if tr else 'fail' + assert tr ############################################################################### # Test requesting a non-existent table by name (bug 1480). -def ogr_pg_17(): +def test_ogr_pg_17(): if gdaltest.pg_ds is None: - return 'skip' + pytest.skip() count = gdaltest.pg_ds.GetLayerCount() try: @@ -821,115 +832,35 @@ def ogr_pg_17(): except: layer = None - if layer is not None: - gdaltest.post_reason('got layer for non-existent table!') - return 'fail' - - if count != gdaltest.pg_ds.GetLayerCount(): - gdaltest.post_reason('layer count changed unexpectedly.') - return 'fail' + assert layer is None, 'got layer for non-existent table!' - return 'success' + assert count == gdaltest.pg_ds.GetLayerCount(), 'layer count changed unexpectedly.' ############################################################################### # Test getting a layer by name that was not previously a layer. -def ogr_pg_18(): +def test_ogr_pg_18(): if gdaltest.pg_ds is None or not gdaltest.pg_has_postgis: - return 'skip' + pytest.skip() count = gdaltest.pg_ds.GetLayerCount() layer = gdaltest.pg_ds.GetLayerByName('geometry_columns') - if layer is None: - gdaltest.post_reason('did not get geometry_columns layer') - return 'fail' - - if count + 1 != gdaltest.pg_ds.GetLayerCount(): - gdaltest.post_reason('layer count unexpectedly unchanged.') - return 'fail' - - return 'success' - -############################################################################### -# Test reading a layer extent - - -def ogr_pg_19(): - - if gdaltest.pg_ds is None: - return 'skip' - - layer = gdaltest.pg_ds.GetLayerByName('tpoly') - if layer is None: - gdaltest.post_reason('did not get tpoly layer') - return 'fail' - - extent = layer.GetExtent() - expect = (478315.53125, 481645.3125, 4762880.5, 4765610.5) - - minx = abs(extent[0] - expect[0]) - maxx = abs(extent[1] - expect[1]) - miny = abs(extent[2] - expect[2]) - maxy = abs(extent[3] - expect[3]) - - if max(minx, maxx, miny, maxy) > 0.0001: - gdaltest.post_reason('Extents do not match') - print(extent) - return 'fail' + assert layer is not None, 'did not get geometry_columns layer' - estimated_extent = layer.GetExtent(force=0) - if not gdaltest.pg_has_postgis: - # The OGRLayer default implementation in force = 0 returns error - if estimated_extent != (0, 0, 0, 0): - gdaltest.post_reason('Wrong estimated extent') - print(extent) - return 'fail' - else: - # Better testing needed ? - if estimated_extent == (0, 0, 0, 0): - gdaltest.post_reason('Wrong estimated extent') - print(extent) - return 'fail' + assert count + 1 == gdaltest.pg_ds.GetLayerCount(), \ + 'layer count unexpectedly unchanged.' - return 'success' - -############################################################################### -# Test reading a SQL result layer extent - - -def ogr_pg_19_2(): - - if gdaltest.pg_ds is None: - return 'skip' - - sql_lyr = gdaltest.pg_ds.ExecuteSQL('select * from tpoly') - - extent = sql_lyr.GetExtent() - expect = (478315.53125, 481645.3125, 4762880.5, 4765610.5) - - minx = abs(extent[0] - expect[0]) - maxx = abs(extent[1] - expect[1]) - miny = abs(extent[2] - expect[2]) - maxy = abs(extent[3] - expect[3]) - - if max(minx, maxx, miny, maxy) > 0.0001: - gdaltest.post_reason('Extents do not match') - return 'fail' - - gdaltest.pg_ds.ReleaseResultSet(sql_lyr) - - return 'success' ############################################################################### # Test reading 4-dim geometry in EWKT format -def ogr_pg_20(): +def test_ogr_pg_20(): if gdaltest.pg_ds is None or not gdaltest.pg_has_postgis: - return 'skip' + pytest.skip() # # Prepare test layer with 4-dim geometries. @@ -973,18 +904,14 @@ def ogr_pg_20(): # We need to re-read layers gdaltest.pg_ds.Destroy() gdaltest.pg_ds = ogr.Open('PG:' + gdaltest.pg_connection_string, update=1) - if gdaltest.pg_ds is None: - gdaltest.post_reason('can not re-open datasource') - return 'fail' + assert gdaltest.pg_ds is not None, 'can not re-open datasource' # # Test reading 4-dim geometries normalized to OGC WKT form. # layer = gdaltest.pg_ds.GetLayerByName('testgeom') - if layer is None: - gdaltest.post_reason('did not get testgeom layer') - return 'fail' + assert layer is not None, 'did not get testgeom layer' # Test updating the geometries for i in range(len(geometries)): @@ -995,45 +922,37 @@ def ogr_pg_20(): for i, geoms in enumerate(geometries): feat = layer.GetFeature(i) geom = feat.GetGeometryRef() - if geom is None: - gdaltest.post_reason('did not get geometry, expected %s' % geoms[1]) - return 'fail' + assert geom is not None, ('did not get geometry, expected %s' % geoms[1]) wkt = geom.ExportToIsoWkt() feat.Destroy() feat = None - if wkt != geoms[1]: - gdaltest.post_reason('WKT do not match: expected %s, got %s' % (geoms[1], wkt)) - return 'fail' + assert wkt == geoms[1], \ + ('WKT do not match: expected %s, got %s' % (geoms[1], wkt)) layer = None - return 'success' - ############################################################################### # Test reading 4-dimension geometries in EWKB format -def ogr_pg_21(): +def test_ogr_pg_21(): if gdaltest.pg_ds is None or not gdaltest.pg_has_postgis: - return 'skip' + pytest.skip() layer = gdaltest.pg_ds.ExecuteSQL("SELECT wkb_geometry FROM testgeom") - if layer is None: - gdaltest.post_reason('did not get testgeom layer') - return 'fail' + assert layer is not None, 'did not get testgeom layer' feat = layer.GetNextFeature() while feat is not None: geom = feat.GetGeometryRef() if ogr.GT_HasZ(geom.GetGeometryType()) == 0 or ogr.GT_HasM(geom.GetGeometryType()) == 0: - gdaltest.post_reason('expected feature with type >3000') feat.Destroy() feat = None gdaltest.pg_ds.ReleaseResultSet(layer) layer = None - return 'fail' + pytest.fail('expected feature with type >3000') feat.Destroy() feat = layer.GetNextFeature() @@ -1042,16 +961,14 @@ def ogr_pg_21(): gdaltest.pg_ds.ReleaseResultSet(layer) layer = None - return 'success' - ############################################################################### # Check if the sub geometries of TIN and POLYHEDRALSURFACE are valid -def ogr_pg_21_subgeoms(): +def test_ogr_pg_21_subgeoms(): if gdaltest.pg_ds is None or not gdaltest.pg_has_postgis: - return 'skip' + pytest.skip() subgeom_PS = ['POLYGON ZM ((0 0 0 0,0 0 1 0,0 1 1 0,0 1 0 0,0 0 0 0))', 'POLYGON ZM ((0 0 0 0,0 1 0 0,1 1 0 0,1 0 0 0,0 0 0 0))', @@ -1067,36 +984,31 @@ def ogr_pg_21_subgeoms(): for i in range(8, 10): feat = layer.GetFeature(i) geom = feat.GetGeometryRef() - if geom is None: - gdaltest.post_reason('did not get the expected geometry') - return 'fail' + assert geom is not None, 'did not get the expected geometry' if geom.GetGeometryName() == "POLYHEDRALSURFACE": for j in range(0, geom.GetGeometryCount()): sub_geom = geom.GetGeometryRef(j) subgeom_wkt = sub_geom.ExportToIsoWkt() - if subgeom_wkt != subgeom_PS[j]: - gdaltest.post_reason('did not get the expected subgeometry, expected %s' % (subgeom_PS[j])) - return 'fail' + assert subgeom_wkt == subgeom_PS[j], \ + ('did not get the expected subgeometry, expected %s' % (subgeom_PS[j])) if geom.GetGeometryName() == "TIN": for j in range(0, geom.GetGeometryCount()): sub_geom = geom.GetGeometryRef(j) subgeom_wkt = sub_geom.ExportToIsoWkt() - if subgeom_wkt != subgeom_TIN[j]: - gdaltest.post_reason('did not get the expected subgeometry, expected %s' % (subgeom_TIN[j])) - return 'fail' + assert subgeom_wkt == subgeom_TIN[j], \ + ('did not get the expected subgeometry, expected %s' % (subgeom_TIN[j])) feat.Destroy() feat = None - return 'success' - + ############################################################################### # Check if the 3d geometries of TIN, Triangle and POLYHEDRALSURFACE are valid -def ogr_pg_21_3d_geometries(): +def test_ogr_pg_21_3d_geometries(with_and_without_postgis): - if gdaltest.pg_ds is None or gdaltest.ogr_pg_second_run: - return 'skip' + if gdaltest.pg_ds is None or not with_and_without_postgis: + pytest.skip() gdaltest.pg_ds = ogr.Open('PG:' + gdaltest.pg_connection_string, update=1) @@ -1118,14 +1030,10 @@ def ogr_pg_21_3d_geometries(): gdaltest.pg_ds = None gdaltest.pg_ds = ogr.Open('PG:' + gdaltest.pg_connection_string, update=1) - if gdaltest.pg_ds is None: - gdaltest.post_reason('Cannot open the dataset') - return 'fail' + assert gdaltest.pg_ds is not None, 'Cannot open the dataset' layer = gdaltest.pg_ds.GetLayerByName('zgeoms') - if layer is None: - gdaltest.post_reason('No layer received') - return 'fail' + assert layer is not None, 'No layer received' for i in range(0, 3): feat = layer.GetFeature(i) @@ -1133,22 +1041,20 @@ def ogr_pg_21_3d_geometries(): wkt = geom.ExportToIsoWkt() - if wkt != wkt_expected[i]: - gdaltest.post_reason('Unexpected WKT, expected %s and got %s' % (wkt_expected[i], wkt)) - return 'fail' + assert wkt == wkt_expected[i], \ + ('Unexpected WKT, expected %s and got %s' % (wkt_expected[i], wkt)) gdaltest.pg_ds.ExecuteSQL("DROP TABLE zgeoms") - return 'success' ############################################################################### # Create table from data/poly.shp under specified SCHEMA # This test checks if schema support and schema name quoting works well. -def ogr_pg_22(): +def test_ogr_pg_22(): if gdaltest.pg_ds is None: - return 'skip' + pytest.skip() ###################################################### # Create Schema @@ -1194,28 +1100,24 @@ def ogr_pg_22(): found = ogr_pg_check_layer_in_list(gdaltest.pg_ds, layer_name) - if found is False: - gdaltest.post_reason('layer from schema \'' + schema_name + '\' not listed') - return 'fail' - - return 'success' + assert found is not False, ('layer from schema \'' + schema_name + '\' not listed') ############################################################################### # Create table with all data types -def ogr_pg_23(layer_name='datatypetest', include_timestamptz=True): +def test_ogr_pg_23(): if gdaltest.pg_ds is None: - return 'skip' + pytest.skip() gdal.PushErrorHandler('CPLQuietErrorHandler') - gdaltest.pg_ds.ExecuteSQL('DELLAYER:' + layer_name) + gdaltest.pg_ds.ExecuteSQL('DELLAYER:datatypetest') gdal.PopErrorHandler() ###################################################### # Create Table - lyr = gdaltest.pg_ds.CreateLayer(layer_name) + lyr = gdaltest.pg_ds.CreateLayer('datatypetest') ###################################################### # Setup Schema @@ -1223,50 +1125,49 @@ def ogr_pg_23(layer_name='datatypetest', include_timestamptz=True): ###################################################### # add some custom date fields. - gdaltest.pg_ds.ExecuteSQL('ALTER TABLE ' + layer_name + ' ADD COLUMN my_numeric numeric') - gdaltest.pg_ds.ExecuteSQL('ALTER TABLE ' + layer_name + ' ADD COLUMN my_numeric5 numeric(5)') - gdaltest.pg_ds.ExecuteSQL('ALTER TABLE ' + layer_name + ' ADD COLUMN my_numeric5_3 numeric(5,3)') - # gdaltest.pg_ds.ExecuteSQL( 'ALTER TABLE ' + layer_name + ' ADD COLUMN my_bool bool' ) + gdaltest.pg_ds.ExecuteSQL('ALTER TABLE datatypetest ADD COLUMN my_numeric numeric') + gdaltest.pg_ds.ExecuteSQL('ALTER TABLE datatypetest ADD COLUMN my_numeric5 numeric(5)') + gdaltest.pg_ds.ExecuteSQL('ALTER TABLE datatypetest ADD COLUMN my_numeric5_3 numeric(5,3)') + # gdaltest.pg_ds.ExecuteSQL( 'ALTER TABLE datatypetest ADD COLUMN my_bool bool' ) fld = ogr.FieldDefn('my_bool', ogr.OFTInteger) fld.SetSubType(ogr.OFSTBoolean) lyr.CreateField(fld) - # gdaltest.pg_ds.ExecuteSQL( 'ALTER TABLE ' + layer_name + ' ADD COLUMN my_int2 int2' ) + # gdaltest.pg_ds.ExecuteSQL( 'ALTER TABLE datatypetest ADD COLUMN my_int2 int2' ) fld = ogr.FieldDefn('my_int2', ogr.OFTInteger) fld.SetSubType(ogr.OFSTInt16) lyr.CreateField(fld) - gdaltest.pg_ds.ExecuteSQL('ALTER TABLE ' + layer_name + ' ADD COLUMN my_int4 int4') + gdaltest.pg_ds.ExecuteSQL('ALTER TABLE datatypetest ADD COLUMN my_int4 int4') lyr.CreateField(ogr.FieldDefn('my_int8', ogr.OFTInteger64)) - # gdaltest.pg_ds.ExecuteSQL( 'ALTER TABLE ' + layer_name + ' ADD COLUMN my_float4 float4' ) + # gdaltest.pg_ds.ExecuteSQL( 'ALTER TABLE datatypetest ADD COLUMN my_float4 float4' ) fld = ogr.FieldDefn('my_float4', ogr.OFTReal) fld.SetSubType(ogr.OFSTFloat32) lyr.CreateField(fld) - gdaltest.pg_ds.ExecuteSQL('ALTER TABLE ' + layer_name + ' ADD COLUMN my_float8 float8') - gdaltest.pg_ds.ExecuteSQL('ALTER TABLE ' + layer_name + ' ADD COLUMN my_real real') - gdaltest.pg_ds.ExecuteSQL('ALTER TABLE ' + layer_name + ' ADD COLUMN my_char char') - gdaltest.pg_ds.ExecuteSQL('ALTER TABLE ' + layer_name + ' ADD COLUMN my_varchar character varying') - gdaltest.pg_ds.ExecuteSQL('ALTER TABLE ' + layer_name + ' ADD COLUMN my_varchar10 character varying(10)') - gdaltest.pg_ds.ExecuteSQL('ALTER TABLE ' + layer_name + ' ADD COLUMN my_text text') - gdaltest.pg_ds.ExecuteSQL('ALTER TABLE ' + layer_name + ' ADD COLUMN my_bytea bytea') - gdaltest.pg_ds.ExecuteSQL('ALTER TABLE ' + layer_name + ' ADD COLUMN my_time time') - gdaltest.pg_ds.ExecuteSQL('ALTER TABLE ' + layer_name + ' ADD COLUMN my_date date') - gdaltest.pg_ds.ExecuteSQL('ALTER TABLE ' + layer_name + ' ADD COLUMN my_timestamp timestamp without time zone') - if include_timestamptz: - gdaltest.pg_ds.ExecuteSQL('ALTER TABLE ' + layer_name + ' ADD COLUMN my_timestamptz timestamp with time zone') - gdaltest.pg_ds.ExecuteSQL('ALTER TABLE ' + layer_name + ' ADD COLUMN my_chararray char(1)[]') - gdaltest.pg_ds.ExecuteSQL('ALTER TABLE ' + layer_name + ' ADD COLUMN my_textarray text[]') - gdaltest.pg_ds.ExecuteSQL('ALTER TABLE ' + layer_name + ' ADD COLUMN my_varchararray character varying[]') + gdaltest.pg_ds.ExecuteSQL('ALTER TABLE datatypetest ADD COLUMN my_float8 float8') + gdaltest.pg_ds.ExecuteSQL('ALTER TABLE datatypetest ADD COLUMN my_real real') + gdaltest.pg_ds.ExecuteSQL('ALTER TABLE datatypetest ADD COLUMN my_char char') + gdaltest.pg_ds.ExecuteSQL('ALTER TABLE datatypetest ADD COLUMN my_varchar character varying') + gdaltest.pg_ds.ExecuteSQL('ALTER TABLE datatypetest ADD COLUMN my_varchar10 character varying(10)') + gdaltest.pg_ds.ExecuteSQL('ALTER TABLE datatypetest ADD COLUMN my_text text') + gdaltest.pg_ds.ExecuteSQL('ALTER TABLE datatypetest ADD COLUMN my_bytea bytea') + gdaltest.pg_ds.ExecuteSQL('ALTER TABLE datatypetest ADD COLUMN my_time time') + gdaltest.pg_ds.ExecuteSQL('ALTER TABLE datatypetest ADD COLUMN my_date date') + gdaltest.pg_ds.ExecuteSQL('ALTER TABLE datatypetest ADD COLUMN my_timestamp timestamp without time zone') + gdaltest.pg_ds.ExecuteSQL('ALTER TABLE datatypetest ADD COLUMN my_timestamptz timestamp with time zone') + gdaltest.pg_ds.ExecuteSQL('ALTER TABLE datatypetest ADD COLUMN my_chararray char(1)[]') + gdaltest.pg_ds.ExecuteSQL('ALTER TABLE datatypetest ADD COLUMN my_textarray text[]') + gdaltest.pg_ds.ExecuteSQL('ALTER TABLE datatypetest ADD COLUMN my_varchararray character varying[]') fld = ogr.FieldDefn('my_int2array', ogr.OFTIntegerList) fld.SetSubType(ogr.OFSTInt16) lyr.CreateField(fld) - gdaltest.pg_ds.ExecuteSQL('ALTER TABLE ' + layer_name + ' ADD COLUMN my_int4array int4[]') + gdaltest.pg_ds.ExecuteSQL('ALTER TABLE datatypetest ADD COLUMN my_int4array int4[]') lyr.CreateField(ogr.FieldDefn('my_int8array', ogr.OFTInteger64List)) fld = ogr.FieldDefn('my_float4array', ogr.OFTRealList) fld.SetSubType(ogr.OFSTFloat32) lyr.CreateField(fld) - gdaltest.pg_ds.ExecuteSQL('ALTER TABLE ' + layer_name + ' ADD COLUMN my_float8array float8[]') - gdaltest.pg_ds.ExecuteSQL('ALTER TABLE ' + layer_name + ' ADD COLUMN my_numericarray numeric[]') - gdaltest.pg_ds.ExecuteSQL('ALTER TABLE ' + layer_name + ' ADD COLUMN my_numeric5array numeric(5)[]') - gdaltest.pg_ds.ExecuteSQL('ALTER TABLE ' + layer_name + ' ADD COLUMN my_numeric5_3array numeric(5,3)[]') + gdaltest.pg_ds.ExecuteSQL('ALTER TABLE datatypetest ADD COLUMN my_float8array float8[]') + gdaltest.pg_ds.ExecuteSQL('ALTER TABLE datatypetest ADD COLUMN my_numericarray numeric[]') + gdaltest.pg_ds.ExecuteSQL('ALTER TABLE datatypetest ADD COLUMN my_numeric5array numeric(5)[]') + gdaltest.pg_ds.ExecuteSQL('ALTER TABLE datatypetest ADD COLUMN my_numeric5_3array numeric(5,3)[]') fld = ogr.FieldDefn('my_boolarray', ogr.OFTIntegerList) fld.SetSubType(ogr.OFSTBoolean) lyr.CreateField(fld) @@ -1279,74 +1180,59 @@ def ogr_pg_23(layer_name='datatypetest', include_timestamptz=True): geom_str = "'\\\\001\\\\001\\\\000\\\\000\\\\000\\\\000\\\\000\\\\000\\\\000\\\\000\\\\000$@\\\\000\\\\000\\\\000\\\\000\\\\000\\\\0004@'" if gdaltest.pg_quote_with_E: geom_str = "E" + geom_str - sql = "INSERT INTO " + layer_name + " ( my_numeric, my_numeric5, my_numeric5_3, my_bool, my_int2, " + sql = "INSERT INTO datatypetest ( my_numeric, my_numeric5, my_numeric5_3, my_bool, my_int2, " sql += "my_int4, my_int8, my_float4, my_float8, my_real, my_char, my_varchar, " - sql += "my_varchar10, my_text, my_bytea, my_time, my_date, my_timestamp, " - if include_timestamptz: - sql += "my_timestamptz, " + sql += "my_varchar10, my_text, my_bytea, my_time, my_date, my_timestamp, my_timestamptz, " sql += "my_chararray, my_textarray, my_varchararray, my_int2array, my_int4array, " sql += "my_int8array, my_float4array, my_float8array, my_numericarray, my_numeric5array, my_numeric5_3array, my_boolarray, wkb_geometry) " sql += "VALUES ( 1.2, 12345, 0.123, 'T', 12345, 12345678, 1234567901234, 0.123, " sql += "0.12345678, 0.876, 'a', 'ab', 'varchar10 ', 'abc', 'xyz', '12:34:56', " - sql += "'2000-01-01', '2000-01-01 00:00:00', " - if include_timestamptz: - sql += "'2000-01-01 00:00:00+00', " + sql += "'2000-01-01', '2000-01-01 00:00:00', '2000-01-01 00:00:00+00', " sql += "'{a,b}', " sql += "'{aa,bb}', '{cc,dd}', '{100,200}', '{100,200}', '{1234567901234}', " sql += "'{100.1,200.1}', '{100.12,200.12}', ARRAY[100.12,200.12], ARRAY[10,20], ARRAY[10.12,20.12], '{1,0}', " + geom_str + " )" gdaltest.pg_ds.ExecuteSQL(sql) - return 'success' - ############################################################################### -def test_val_test_23(layer_defn, feat): +def check_value_23(layer_defn, feat): field_defn = layer_defn.GetFieldDefn(layer_defn.GetFieldIndex("my_numeric5")) - if field_defn.GetWidth() != 5 or field_defn.GetPrecision() != 0 or field_defn.GetType() != ogr.OFTInteger: - gdaltest.post_reason('Wrong field defn for my_numeric5 : %d, %d, %d' % (field_defn.GetWidth(), field_defn.GetPrecision(), field_defn.GetType())) - return 'fail' + assert field_defn.GetWidth() == 5 and field_defn.GetPrecision() == 0 and field_defn.GetType() == ogr.OFTInteger, \ + ('Wrong field defn for my_numeric5 : %d, %d, %d' % (field_defn.GetWidth(), field_defn.GetPrecision(), field_defn.GetType())) field_defn = layer_defn.GetFieldDefn(layer_defn.GetFieldIndex("my_numeric5_3")) - if field_defn.GetWidth() != 5 or field_defn.GetPrecision() != 3 or field_defn.GetType() != ogr.OFTReal: - gdaltest.post_reason('Wrong field defn for my_numeric5_3 : %d, %d, %d' % (field_defn.GetWidth(), field_defn.GetPrecision(), field_defn.GetType())) - return 'fail' + assert field_defn.GetWidth() == 5 and field_defn.GetPrecision() == 3 and field_defn.GetType() == ogr.OFTReal, \ + ('Wrong field defn for my_numeric5_3 : %d, %d, %d' % (field_defn.GetWidth(), field_defn.GetPrecision(), field_defn.GetType())) field_defn = layer_defn.GetFieldDefn(layer_defn.GetFieldIndex("my_varchar10")) - if field_defn.GetWidth() != 10 or field_defn.GetPrecision() != 0: - gdaltest.post_reason('Wrong field defn for my_varchar10 : %d, %d, %d' % (field_defn.GetWidth(), field_defn.GetPrecision(), field_defn.GetType())) - return 'fail' + assert field_defn.GetWidth() == 10 and field_defn.GetPrecision() == 0, \ + ('Wrong field defn for my_varchar10 : %d, %d, %d' % (field_defn.GetWidth(), field_defn.GetPrecision(), field_defn.GetType())) field_defn = layer_defn.GetFieldDefn(layer_defn.GetFieldIndex("my_bool")) - if field_defn.GetWidth() != 1 or field_defn.GetType() != ogr.OFTInteger or field_defn.GetSubType() != ogr.OFSTBoolean: - gdaltest.post_reason('Wrong field defn for my_bool : %d, %d, %d, %d' % (field_defn.GetWidth(), field_defn.GetPrecision(), field_defn.GetType(), field_defn.GetSubType())) - return 'fail' + assert field_defn.GetWidth() == 1 and field_defn.GetType() == ogr.OFTInteger and field_defn.GetSubType() == ogr.OFSTBoolean, \ + ('Wrong field defn for my_bool : %d, %d, %d, %d' % (field_defn.GetWidth(), field_defn.GetPrecision(), field_defn.GetType(), field_defn.GetSubType())) field_defn = layer_defn.GetFieldDefn(layer_defn.GetFieldIndex("my_boolarray")) - if field_defn.GetType() != ogr.OFTIntegerList or field_defn.GetSubType() != ogr.OFSTBoolean: - gdaltest.post_reason('Wrong field defn for my_boolarray : %d, %d, %d, %d' % (field_defn.GetWidth(), field_defn.GetPrecision(), field_defn.GetType(), field_defn.GetSubType())) - return 'fail' + assert field_defn.GetType() == ogr.OFTIntegerList and field_defn.GetSubType() == ogr.OFSTBoolean, \ + ('Wrong field defn for my_boolarray : %d, %d, %d, %d' % (field_defn.GetWidth(), field_defn.GetPrecision(), field_defn.GetType(), field_defn.GetSubType())) field_defn = layer_defn.GetFieldDefn(layer_defn.GetFieldIndex("my_int2")) - if field_defn.GetType() != ogr.OFTInteger or field_defn.GetSubType() != ogr.OFSTInt16: - gdaltest.post_reason('Wrong field defn for my_int2 : %d, %d, %d, %d' % (field_defn.GetWidth(), field_defn.GetPrecision(), field_defn.GetType(), field_defn.GetSubType())) - return 'fail' + assert field_defn.GetType() == ogr.OFTInteger and field_defn.GetSubType() == ogr.OFSTInt16, \ + ('Wrong field defn for my_int2 : %d, %d, %d, %d' % (field_defn.GetWidth(), field_defn.GetPrecision(), field_defn.GetType(), field_defn.GetSubType())) field_defn = layer_defn.GetFieldDefn(layer_defn.GetFieldIndex("my_float4")) - if field_defn.GetType() != ogr.OFTReal or field_defn.GetSubType() != ogr.OFSTFloat32: - gdaltest.post_reason('Wrong field defn for my_float4 : %d, %d, %d, %d' % (field_defn.GetWidth(), field_defn.GetPrecision(), field_defn.GetType(), field_defn.GetSubType())) - return 'fail' + assert field_defn.GetType() == ogr.OFTReal and field_defn.GetSubType() == ogr.OFSTFloat32, \ + ('Wrong field defn for my_float4 : %d, %d, %d, %d' % (field_defn.GetWidth(), field_defn.GetPrecision(), field_defn.GetType(), field_defn.GetSubType())) field_defn = layer_defn.GetFieldDefn(layer_defn.GetFieldIndex("my_int2array")) - if field_defn.GetType() != ogr.OFTIntegerList or field_defn.GetSubType() != ogr.OFSTInt16: - gdaltest.post_reason('Wrong field defn for my_int2array : %d, %d, %d, %d' % (field_defn.GetWidth(), field_defn.GetPrecision(), field_defn.GetType(), field_defn.GetSubType())) - return 'fail' + assert field_defn.GetType() == ogr.OFTIntegerList and field_defn.GetSubType() == ogr.OFSTInt16, \ + ('Wrong field defn for my_int2array : %d, %d, %d, %d' % (field_defn.GetWidth(), field_defn.GetPrecision(), field_defn.GetType(), field_defn.GetSubType())) field_defn = layer_defn.GetFieldDefn(layer_defn.GetFieldIndex("my_float4array")) - if field_defn.GetType() != ogr.OFTRealList or field_defn.GetSubType() != ogr.OFSTFloat32: - gdaltest.post_reason('Wrong field defn for my_float4array : %d, %d, %d, %d' % (field_defn.GetWidth(), field_defn.GetPrecision(), field_defn.GetType(), field_defn.GetSubType())) - return 'fail' + assert field_defn.GetType() == ogr.OFTRealList and field_defn.GetSubType() == ogr.OFSTFloat32, \ + ('Wrong field defn for my_float4array : %d, %d, %d, %d' % (field_defn.GetWidth(), field_defn.GetPrecision(), field_defn.GetType(), field_defn.GetSubType())) if abs(feat.my_numeric - 1.2) > 1e-8 or \ feat.my_numeric5 != 12345 or \ @@ -1379,30 +1265,23 @@ def test_val_test_23(layer_defn, feat): abs(feat.my_numericarray[0] - 100.12) > 1e-8 or \ abs(feat.my_numeric5array[0] - 10) > 1e-8 or \ abs(feat.my_numeric5_3array[0] - 10.12) > 1e-8: - gdaltest.post_reason('Wrong values') feat.DumpReadable() - return 'fail' + pytest.fail('Wrong values') geom = feat.GetGeometryRef() - if geom is None: - gdaltest.post_reason('geom is none') - return 'fail' + assert geom is not None, 'geom is none' wkt = geom.ExportToWkt() - if wkt != 'POINT (10 20)': - gdaltest.post_reason('Wrong WKT :' + wkt) - return 'fail' - - return 'success' + assert wkt == 'POINT (10 20)', ('Wrong WKT :' + wkt) ############################################################################### # Test with PG: connection -def ogr_pg_24(): +def test_ogr_pg_24(): if gdaltest.pg_ds is None: - return 'skip' + pytest.skip() ds = ogr.Open('PG:' + gdaltest.pg_connection_string, update=1) @@ -1411,23 +1290,20 @@ def ogr_pg_24(): lyr = ds.GetLayerByName('datatypetest') feat = lyr.GetNextFeature() - if test_val_test_23(lyr.GetLayerDefn(), feat) != 'success': - return 'fail' + check_value_23(lyr.GetLayerDefn(), feat) feat = None ds.Destroy() - return 'success' - ############################################################################### # Test with PG: connection and SELECT query -def ogr_pg_25(): +def test_ogr_pg_25(): if gdaltest.pg_ds is None: - return 'skip' + pytest.skip() ds = ogr.Open('PG:' + gdaltest.pg_connection_string, update=1) @@ -1436,8 +1312,7 @@ def ogr_pg_25(): sql_lyr = ds.ExecuteSQL('select * from datatypetest') feat = sql_lyr.GetNextFeature() - if test_val_test_23(sql_lyr.GetLayerDefn(), feat) != 'success': - return 'fail' + check_value_23(sql_lyr.GetLayerDefn(), feat) ds.ReleaseResultSet(sql_lyr) @@ -1445,90 +1320,14 @@ def ogr_pg_25(): ds.Destroy() - return 'success' - -############################################################################### -# Test with PGB: connection - - -def ogr_pg_26_DISABLED_AS_BINARY_CURSOR_NO_LONGER_SUPPORTED(): - - if gdaltest.pg_ds is None: - return 'skip' - - # The presence of timestamptz field currently disables binary cursor - if ogr_pg_23(layer_name='datatypetest_withouttimestamptz', include_timestamptz=False) != 'success': - return 'fail' - - ds = ogr.Open('PGB:' + gdaltest.pg_connection_string, update=1) - - ds.ExecuteSQL('set timezone to "UTC"') - - lyr = ds.GetLayerByName('datatypetest') - - feat = lyr.GetNextFeature() - if test_val_test_23(lyr.GetLayerDefn(), feat) != 'success': - return 'fail' - - feat = None - - lyr = ds.GetLayerByName('datatypetest_withouttimestamptz') - - feat = lyr.GetNextFeature() - if test_val_test_23(lyr.GetLayerDefn(), feat) != 'success': - return 'fail' - - feat = None - - ds = None - - return 'success' - -############################################################################### -# Test with PGB: connection and SELECT query - - -def ogr_pg_27_DISABLED_AS_BINARY_CURSOR_NO_LONGER_SUPPORTED(): - - if gdaltest.pg_ds is None: - return 'skip' - - ds = ogr.Open('PGB:' + gdaltest.pg_connection_string, update=1) - - ds.ExecuteSQL('set timezone to "UTC"') - - sql_lyr = ds.ExecuteSQL('select * from datatypetest') - - feat = sql_lyr.GetNextFeature() - if test_val_test_23(sql_lyr.GetLayerDefn(), feat) != 'success': - return 'fail' - - ds.ReleaseResultSet(sql_lyr) - - feat = None - - sql_lyr = ds.ExecuteSQL('select * from datatypetest_withouttimestamptz') - - feat = sql_lyr.GetNextFeature() - if test_val_test_23(sql_lyr.GetLayerDefn(), feat) != 'success': - return 'fail' - - ds.ReleaseResultSet(sql_lyr) - - feat = None - - ds = None - - return 'success' - ############################################################################### # Duplicate all data types in INSERT mode -def ogr_pg_28(): +def test_ogr_pg_28(): if gdaltest.pg_ds is None: - return 'skip' + pytest.skip() gdal.SetConfigOption('PG_USE_COPY', "NO") @@ -1553,13 +1352,10 @@ def ogr_pg_28(): dst_feat = ogr.Feature(feature_def=dst_lyr.GetLayerDefn()) feat = src_lyr.GetNextFeature() - if feat is None: - return 'fail' + assert feat is not None dst_feat.SetFrom(feat) - if dst_lyr.CreateFeature(dst_feat) != 0: - gdaltest.post_reason('CreateFeature failed.') - return 'fail' + assert dst_lyr.CreateFeature(dst_feat) == 0, 'CreateFeature failed.' dst_feat.Destroy() @@ -1570,16 +1366,14 @@ def ogr_pg_28(): gdal.SetConfigOption('PG_USE_COPY', gdaltest.pg_use_copy) - return 'success' - ############################################################################### # Test with PG: connection -def ogr_pg_29(): +def test_ogr_pg_29(): if gdaltest.pg_ds is None: - return 'skip' + pytest.skip() ds = ogr.Open('PG:' + gdaltest.pg_connection_string, update=1) @@ -1589,29 +1383,24 @@ def ogr_pg_29(): # my_timestamp has now a time zone... feat = lyr.GetNextFeature() - if test_val_test_23(lyr.GetLayerDefn(), feat) != 'success': - return 'fail' + check_value_23(lyr.GetLayerDefn(), feat) geom = feat.GetGeometryRef() wkt = geom.ExportToWkt() - if wkt != 'POINT (10 20)': - gdaltest.post_reason('Wrong WKT :' + wkt) - return 'fail' + assert wkt == 'POINT (10 20)', ('Wrong WKT :' + wkt) feat = None ds.Destroy() - return 'success' - ############################################################################### # Duplicate all data types in PG_USE_COPY mode -def ogr_pg_30(): +def test_ogr_pg_30(): if gdaltest.pg_ds is None: - return 'skip' + pytest.skip() gdal.SetConfigOption('PG_USE_COPY', 'YES') @@ -1636,13 +1425,10 @@ def ogr_pg_30(): dst_feat = ogr.Feature(feature_def=dst_lyr.GetLayerDefn()) feat = src_lyr.GetNextFeature() - if feat is None: - return 'fail' + assert feat is not None dst_feat.SetFrom(feat) - if dst_lyr.CreateFeature(dst_feat) != 0: - gdaltest.post_reason('CreateFeature failed.') - return 'fail' + assert dst_lyr.CreateFeature(dst_feat) == 0, 'CreateFeature failed.' dst_feat.Destroy() @@ -1650,16 +1436,14 @@ def ogr_pg_30(): gdal.SetConfigOption('PG_USE_COPY', gdaltest.pg_use_copy) - return 'success' - ############################################################################### # Test the tables= connection string option -def ogr_pg_31(): +def test_ogr_pg_31(): if gdaltest.pg_ds is None: - return 'skip' + pytest.skip() srs = osr.SpatialReference() srs.ImportFromEPSG(4326) @@ -1673,9 +1457,7 @@ def ogr_pg_31(): ds = ogr.Open('PG:' + gdaltest.pg_connection_string + ' tables=tpoly,tpolycopy', update=1) - if ds is None or ds.GetLayerCount() != 2: - gdaltest.post_reason('fail') - return 'fail' + assert ds is not None and ds.GetLayerCount() == 2 sql_lyr = ds.ExecuteSQL('SELECT * FROM test_for_tables_equal_param') i = 0 @@ -1685,22 +1467,18 @@ def ogr_pg_31(): break i = i + 1 ds.ReleaseResultSet(sql_lyr) - if i != 501: - gdaltest.post_reason('fail') - return 'fail' + assert i == 501 ds.Destroy() - return 'success' - ############################################################################### # Test approximate srtext (#2123, #3508) -def ogr_pg_32(): +def test_ogr_pg_32(): if gdaltest.pg_ds is None or not gdaltest.pg_has_postgis: - return 'skip' + pytest.skip() gdaltest.pg_ds.ExecuteSQL("DELETE FROM spatial_ref_sys") @@ -1714,9 +1492,8 @@ def ogr_pg_32(): sql_lyr = gdaltest.pg_ds.ExecuteSQL("SELECT COUNT(*) FROM spatial_ref_sys") feat = sql_lyr.GetNextFeature() if feat.count != 1: - gdaltest.post_reason('did not get expected count after step (1)') feat.DumpReadable() - return 'fail' + pytest.fail('did not get expected count after step (1)') gdaltest.pg_ds.ReleaseResultSet(sql_lyr) ###################################################### @@ -1730,9 +1507,8 @@ def ogr_pg_32(): sql_lyr = gdaltest.pg_ds.ExecuteSQL("SELECT COUNT(*) FROM spatial_ref_sys") feat = sql_lyr.GetNextFeature() if feat.count != 1: - gdaltest.post_reason('did not get expected count after step (2)') feat.DumpReadable() - return 'fail' + pytest.fail('did not get expected count after step (2)') gdaltest.pg_ds.ReleaseResultSet(sql_lyr) ###################################################### @@ -1746,9 +1522,8 @@ def ogr_pg_32(): sql_lyr = gdaltest.pg_ds.ExecuteSQL("SELECT COUNT(*) FROM spatial_ref_sys") feat = sql_lyr.GetNextFeature() if feat.count != 1: - gdaltest.post_reason('did not get expected count after step (3)') feat.DumpReadable() - return 'fail' + pytest.fail('did not get expected count after step (3)') gdaltest.pg_ds.ReleaseResultSet(sql_lyr) ###################################################### @@ -1763,17 +1538,14 @@ def ogr_pg_32(): gdaltest.pg_lyr.CreateFeature(feat) feat = None sr = gdaltest.pg_lyr.GetSpatialRef() - if sr.ExportToWkt().find('26632') == -1: - gdaltest.post_reason('did not get expected SRS') - return 'fail' + assert sr.ExportToWkt().find('26632') != -1, 'did not get expected SRS' sql_lyr = gdaltest.pg_ds.ExecuteSQL("SELECT COUNT(*) FROM spatial_ref_sys") feat = sql_lyr.GetNextFeature() # Must be 2 now if feat.count != 2: - gdaltest.post_reason('did not get expected count after step (4)') feat.DumpReadable() - return 'fail' + pytest.fail('did not get expected count after step (4)') gdaltest.pg_ds.ReleaseResultSet(sql_lyr) ###################################################### @@ -1781,9 +1553,7 @@ def ogr_pg_32(): sql_lyr = gdaltest.pg_ds.ExecuteSQL('SELECT * FROM testsrtext4') sr = sql_lyr.GetSpatialRef() - if sr.ExportToWkt().find('26632') == -1: - gdaltest.post_reason('did not get expected SRS') - return 'fail' + assert sr.ExportToWkt().find('26632') != -1, 'did not get expected SRS' gdaltest.pg_ds.ReleaseResultSet(sql_lyr) ###################################################### @@ -1806,12 +1576,8 @@ def ogr_pg_32(): sr = lyr.GetSpatialRef() # sys.stderr.write('AFTER GetSpatialRef\n') - if sr.ExportToWkt().find('26632') == -1: - gdaltest.post_reason('did not get expected SRS') - return 'fail' - if geom_type != ogr.wkbPoint: - gdaltest.post_reason('did not get expected geom type') - return 'fail' + assert sr.ExportToWkt().find('26632') != -1, 'did not get expected SRS' + assert geom_type == ogr.wkbPoint, 'did not get expected geom type' ds = None @@ -1827,26 +1593,21 @@ def ogr_pg_32(): feat = sql_lyr.GetNextFeature() # Must be 3 now if feat.count != 3: - gdaltest.post_reason('did not get expected count after step (5)') feat.DumpReadable() - return 'fail' + pytest.fail('did not get expected count after step (5)') gdaltest.pg_ds.ReleaseResultSet(sql_lyr) - return 'success' - ############################################################################### # Test encoding as UTF8 -def ogr_pg_33(): +def test_ogr_pg_33(): if gdaltest.pg_ds is None: - return 'skip' + pytest.skip() gdaltest.pg_lyr = gdaltest.pg_ds.GetLayerByName('tpoly') - if gdaltest.pg_lyr is None: - gdaltest.post_reason('did not get tpoly layer') - return 'fail' + assert gdaltest.pg_lyr is not None, 'did not get tpoly layer' dst_feat = ogr.Feature(feature_def=gdaltest.pg_lyr.GetLayerDefn()) # eacute in UTF8 : 0xc3 0xa9 @@ -1854,37 +1615,33 @@ def ogr_pg_33(): gdaltest.pg_lyr.CreateFeature(dst_feat) dst_feat.Destroy() - return 'success' - ############################################################################### # Test encoding as Latin1 -def ogr_pg_34(): +def test_ogr_pg_34(): if gdaltest.pg_ds is None: - return 'skip' + pytest.skip() # We only test that on Linux since setting os.environ['XXX'] # is not guaranteed to have effects on system not supporting putenv if sys.platform.startswith('linux'): os.environ['PGCLIENTENCODING'] = 'LATIN1' - ogr_pg_1() + test_ogr_pg_1() del os.environ['PGCLIENTENCODING'] # For some unknown reasons, some servers don't like forcing LATIN1 # but prefer LATIN9 instead... if gdaltest.pg_ds is None: os.environ['PGCLIENTENCODING'] = 'LATIN9' - ogr_pg_1() + test_ogr_pg_1() del os.environ['PGCLIENTENCODING'] else: gdaltest.pg_ds.ExecuteSQL('SET client_encoding = LATIN1') gdaltest.pg_lyr = gdaltest.pg_ds.GetLayerByName('tpoly') - if gdaltest.pg_lyr is None: - gdaltest.post_reason('did not get tpoly layer') - return 'fail' + assert gdaltest.pg_lyr is not None, 'did not get tpoly layer' dst_feat = ogr.Feature(feature_def=gdaltest.pg_lyr.GetLayerDefn()) # eacute in Latin1 : 0xe9 @@ -1892,16 +1649,14 @@ def ogr_pg_34(): gdaltest.pg_lyr.CreateFeature(dst_feat) dst_feat.Destroy() - return 'success' - ############################################################################### # Test for buffer overflows -def ogr_pg_35(): +def test_ogr_pg_35(): if gdaltest.pg_ds is None: - return 'skip' + pytest.skip() gdal.PushErrorHandler() try: @@ -1924,16 +1679,15 @@ def ogr_pg_35(): finally: gdal.PopErrorHandler() - return 'success' - + ############################################################################### # Test support for inherited tables : tables inherited from a Postgis Table -def ogr_pg_36(): +def test_ogr_pg_36(): if gdaltest.pg_ds is None: - return 'skip' + pytest.skip() if gdaltest.pg_has_postgis: lyr = gdaltest.pg_ds.CreateLayer('table36_base', geom_type=ogr.wkbPoint) @@ -1956,65 +1710,48 @@ def ogr_pg_36(): ds = ogr.Open('PG:' + gdaltest.pg_connection_string, update=1) found = ogr_pg_check_layer_in_list(ds, 'table36_inherited') - if found is False: - gdaltest.post_reason('layer table36_inherited not listed') - return 'fail' + assert found is not False, 'layer table36_inherited not listed' found = ogr_pg_check_layer_in_list(ds, 'table36_inherited2') - if found is False: - gdaltest.post_reason('layer table36_inherited2 not listed') - return 'fail' + assert found is not False, 'layer table36_inherited2 not listed' lyr = ds.GetLayerByName('table36_inherited2') - if lyr is None: - return 'fail' - if gdaltest.pg_has_postgis and lyr.GetGeomType() != ogr.wkbPoint: - gdaltest.post_reason('wrong geometry type for layer table36_inherited2') - print(lyr.GetGeomType()) - return 'fail' + assert lyr is not None + assert not gdaltest.pg_has_postgis or lyr.GetGeomType() == ogr.wkbPoint, \ + 'wrong geometry type for layer table36_inherited2' lyr = ds.GetLayerByName('AutoTest-schema.table36_inherited2') - if lyr is None: - return 'fail' - if gdaltest.pg_has_postgis and lyr.GetGeomType() != ogr.wkbLineString: - gdaltest.post_reason('wrong geometry type for layer AutoTest-schema.table36_inherited2') - return 'fail' + assert lyr is not None + assert not gdaltest.pg_has_postgis or lyr.GetGeomType() == ogr.wkbLineString, \ + 'wrong geometry type for layer AutoTest-schema.table36_inherited2' ds.Destroy() - return 'success' - -def ogr_pg_36_bis(): +def test_ogr_pg_36_bis(): if gdaltest.pg_ds is None: - return 'skip' + pytest.skip() ds = ogr.Open('PG:' + gdaltest.pg_connection_string + ' TABLES=table36_base', update=1) found = ogr_pg_check_layer_in_list(ds, 'table36_inherited') - if found is True: - gdaltest.post_reason('layer table36_inherited is listed but it should not') - return 'fail' + assert found is not True, 'layer table36_inherited is listed but it should not' lyr = ds.GetLayerByName('table36_inherited') - if lyr is None: - return 'fail' - if gdaltest.pg_has_postgis and lyr.GetGeomType() != ogr.wkbPoint: - return 'fail' + assert lyr is not None + assert not gdaltest.pg_has_postgis or lyr.GetGeomType() == ogr.wkbPoint ds.Destroy() - return 'success' - ############################################################################### # Test support for inherited tables : Postgis table inherited from a non-Postgis table -def ogr_pg_37(): +def test_ogr_pg_37(): if gdaltest.pg_ds is None or not gdaltest.pg_has_postgis: - return 'skip' + pytest.skip() gdaltest.pg_ds.ExecuteSQL('CREATE TABLE table37_base ( col1 CHAR(1) )') gdaltest.pg_ds.ExecuteSQL('CREATE TABLE table37_inherited ( col2 CHAR(1) ) INHERITS ( table37_base )') @@ -2024,27 +1761,21 @@ def ogr_pg_37(): ds = ogr.Open('PG:' + gdaltest.pg_connection_string, update=1) found = ogr_pg_check_layer_in_list(ds, 'table37_inherited') - if found is False: - gdaltest.post_reason('layer table37_inherited not listed') - return 'fail' + assert found is not False, 'layer table37_inherited not listed' lyr = ds.GetLayerByName('table37_inherited') - if lyr is None: - return 'fail' - if gdaltest.pg_has_postgis and lyr.GetGeomType() != ogr.wkbPoint: - return 'fail' + assert lyr is not None + assert not gdaltest.pg_has_postgis or lyr.GetGeomType() == ogr.wkbPoint ds.Destroy() - return 'success' - ############################################################################### # Test support for multiple geometry columns (RFC 41) -def ogr_pg_38(): +def test_ogr_pg_38(): if gdaltest.pg_ds is None or not gdaltest.pg_has_postgis: - return 'skip' + pytest.skip() sql_lyr = gdaltest.pg_ds.ExecuteSQL("SELECT AddGeometryColumn('public','table37_base','pointBase',-1,'POINT',2)") gdaltest.pg_ds.ReleaseResultSet(sql_lyr) @@ -2056,55 +1787,31 @@ def ogr_pg_38(): # Check for the layer with the wkb_geometry column found = ogr_pg_check_layer_in_list(ds, 'table37_inherited') - if found is False: - gdaltest.post_reason('layer table37_inherited not listed') - return 'fail' + assert found is not False, 'layer table37_inherited not listed' lyr = ds.GetLayerByName('table37_inherited') - if lyr is None: - gdaltest.post_reason('fail') - return 'fail' + assert lyr is not None gfld_defn = lyr.GetLayerDefn().GetGeomFieldDefn(lyr.GetLayerDefn().GetGeomFieldIndex("wkb_geometry")) - if gfld_defn is None: - gdaltest.post_reason('fail') - return 'fail' - if gfld_defn.GetType() != ogr.wkbPoint: - gdaltest.post_reason('fail') - return 'fail' + assert gfld_defn is not None + assert gfld_defn.GetType() == ogr.wkbPoint if lyr.GetLayerDefn().GetGeomFieldCount() != 3: - gdaltest.post_reason('fail') - print(lyr.GetLayerDefn().GetGeomFieldCount()) for i in range(lyr.GetLayerDefn().GetGeomFieldCount()): print(lyr.GetLayerDefn().GetGeomFieldDefn(i).GetName()) - return 'fail' + pytest.fail(lyr.GetLayerDefn().GetGeomFieldCount()) # Explicit query to 'table37_inherited(wkb_geometry)' should also work lyr = ds.GetLayerByName('table37_inherited(wkb_geometry)') - if lyr is None: - gdaltest.post_reason('fail') - return 'fail' + assert lyr is not None lyr = ds.GetLayerByName('table37_inherited(pointBase)') - if lyr is None: - gdaltest.post_reason('fail') - return 'fail' - if lyr.GetGeomType() != ogr.wkbPoint: - gdaltest.post_reason('fail') - return 'fail' - if lyr.GetGeometryColumn() != 'pointBase': - gdaltest.post_reason('wrong geometry column name') - return 'fail' + assert lyr is not None + assert lyr.GetGeomType() == ogr.wkbPoint + assert lyr.GetGeometryColumn() == 'pointBase', 'wrong geometry column name' lyr = ds.GetLayerByName('table37_inherited(point25D)') - if lyr is None: - gdaltest.post_reason('fail') - return 'fail' - if lyr.GetGeomType() != ogr.wkbPoint25D: - gdaltest.post_reason('fail') - return 'fail' - if lyr.GetGeometryColumn() != 'point25D': - gdaltest.post_reason('wrong geometry column name') - return 'fail' + assert lyr is not None + assert lyr.GetGeomType() == ogr.wkbPoint25D + assert lyr.GetGeometryColumn() == 'point25D', 'wrong geometry column name' ds.Destroy() @@ -2112,37 +1819,27 @@ def ogr_pg_38(): ds = ogr.Open('PG:' + gdaltest.pg_connection_string + ' tables=table37_inherited(point25D)', update=1) lyr = ds.GetLayerByName('table37_inherited(point25D)') - if lyr is None: - gdaltest.post_reason('fail') - return 'fail' - if lyr.GetGeomType() != ogr.wkbPoint25D: - gdaltest.post_reason('fail') - return 'fail' - if lyr.GetGeometryColumn() != 'point25D': - gdaltest.post_reason('wrong geometry column name') - return 'fail' + assert lyr is not None + assert lyr.GetGeomType() == ogr.wkbPoint25D + assert lyr.GetGeometryColumn() == 'point25D', 'wrong geometry column name' ds.Destroy() - return 'success' - ############################################################################### # Test support for named views -def ogr_pg_39(): +def test_ogr_pg_39(): if gdaltest.pg_ds is None: - return 'skip' + pytest.skip() if not gdaltest.pg_has_postgis: gdaltest.pg_ds.ExecuteSQL("CREATE VIEW testview AS SELECT * FROM table36_base") ds = ogr.Open('PG:' + gdaltest.pg_connection_string, update=1) found = ogr_pg_check_layer_in_list(ds, 'testview') - if found is False: - gdaltest.post_reason('layer testview not listed') - return 'fail' + assert found is not False, 'layer testview not listed' ds.Destroy() - return 'success' + return gdaltest.pg_ds.ExecuteSQL("CREATE VIEW testview AS SELECT * FROM table37_inherited") if not gdaltest.pg_has_postgis_2: @@ -2152,30 +1849,20 @@ def ogr_pg_39(): # Check for the layer ds = ogr.Open('PG:' + gdaltest.pg_connection_string, update=1) found = ogr_pg_check_layer_in_list(ds, 'testview') - if found is False: - gdaltest.post_reason('layer testview not listed') - return 'fail' + assert found is not False, 'layer testview not listed' lyr = ds.GetLayerByName('testview') - if lyr is None: - return 'fail' + assert lyr is not None if gdaltest.pg_has_postgis: gfld_defn = lyr.GetLayerDefn().GetGeomFieldDefn(lyr.GetLayerDefn().GetGeomFieldIndex("wkb_geometry")) - if gfld_defn is None: - gdaltest.post_reason('fail') - return 'fail' - if gfld_defn.GetType() != ogr.wkbPoint: - gdaltest.post_reason('fail') - return 'fail' + assert gfld_defn is not None + assert gfld_defn.GetType() == ogr.wkbPoint feat = lyr.GetNextFeature() - if feat is None: - gdaltest.post_reason('no feature') - return 'fail' + assert feat is not None, 'no feature' - if feat.GetGeomFieldRef("wkb_geometry") is None or feat.GetGeomFieldRef("wkb_geometry").ExportToWkt() != 'POINT (0 1)': - gdaltest.post_reason('bad geometry %s' % feat.GetGeometryRef().ExportToWkt()) - return 'fail' + assert feat.GetGeomFieldRef("wkb_geometry") is not None and feat.GetGeomFieldRef("wkb_geometry").ExportToWkt() == 'POINT (0 1)', \ + ('bad geometry %s' % feat.GetGeometryRef().ExportToWkt()) ds.Destroy() @@ -2187,93 +1874,64 @@ def ogr_pg_39(): # Check for the layer ds = ogr.Open('PG:' + gdaltest.pg_connection_string, update=1) found = ogr_pg_check_layer_in_list(ds, 'testview') - if found is False: - gdaltest.post_reason('layer testview not listed') - return 'fail' + assert found is not False, 'layer testview not listed' lyr = ds.GetLayerByName('testview(point25D)') - if lyr is None: - return 'fail' - if gdaltest.pg_has_postgis and lyr.GetGeomType() != ogr.wkbPoint25D: - return 'fail' + assert lyr is not None + assert not gdaltest.pg_has_postgis or lyr.GetGeomType() == ogr.wkbPoint25D try: - if lyr.GetGeometryColumn() != 'point25D': - gdaltest.post_reason('wrong geometry column name') - return 'fail' + assert lyr.GetGeometryColumn() == 'point25D', 'wrong geometry column name' except: pass feat = lyr.GetNextFeature() - if feat is None: - gdaltest.post_reason('no feature') - return 'fail' + assert feat is not None, 'no feature' - if feat.GetGeometryRef() is None or feat.GetGeometryRef().ExportToWkt() != 'POINT (0 1 2)': - gdaltest.post_reason('bad geometry %s' % feat.GetGeometryRef().ExportToWkt()) - return 'fail' + assert feat.GetGeometryRef() is not None and feat.GetGeometryRef().ExportToWkt() == 'POINT (0 1 2)', \ + ('bad geometry %s' % feat.GetGeometryRef().ExportToWkt()) ds.Destroy() - return 'success' - ############################################################################### # Test GetFeature() with an invalid id -def ogr_pg_40(): +def test_ogr_pg_40(): if gdaltest.pg_ds is None: - return 'skip' + pytest.skip() layer = gdaltest.pg_ds.GetLayerByName('tpoly') - if layer.GetFeature(0) is not None: - return 'fail' - - return 'success' + assert layer.GetFeature(0) is None ############################################################################### # Test active_schema= option -def ogr_pg_41(): +def test_ogr_pg_41(): if gdaltest.pg_ds is None: - return 'skip' + pytest.skip() ds = ogr.Open('PG:' + gdaltest.pg_connection_string + ' active_schema=AutoTest-schema', update=1) # tpoly without schema refers to the active schema, that is to say AutoTest-schema found = ogr_pg_check_layer_in_list(ds, 'tpoly') - if found is False: - gdaltest.post_reason('layer tpoly not listed') - return 'fail' + assert found is not False, 'layer tpoly not listed' layer = ds.GetLayerByName('tpoly') - if layer.GetFeatureCount() != 3: - gdaltest.post_reason('wrong feature count') - print(layer.GetFeatureCount()) - return 'fail' + assert layer.GetFeatureCount() == 3, 'wrong feature count' found = ogr_pg_check_layer_in_list(ds, 'AutoTest-schema.tpoly') - if found is True: - gdaltest.post_reason('layer AutoTest-schema.tpoly is listed, but should not') - return 'fail' + assert found is not True, 'layer AutoTest-schema.tpoly is listed, but should not' layer = ds.GetLayerByName('AutoTest-schema.tpoly') - if layer.GetFeatureCount() != 3: - gdaltest.post_reason('wrong feature count') - print(layer.GetFeatureCount()) - return 'fail' + assert layer.GetFeatureCount() == 3, 'wrong feature count' found = ogr_pg_check_layer_in_list(ds, 'public.tpoly') - if found is False: - gdaltest.post_reason('layer tpoly not listed') - return 'fail' + assert found is not False, 'layer tpoly not listed' layer = ds.GetLayerByName('public.tpoly') - if layer.GetFeatureCount() != 19: - gdaltest.post_reason('wrong feature count') - print(layer.GetFeatureCount()) - return 'fail' + assert layer.GetFeatureCount() == 19, 'wrong feature count' gdal.PushErrorHandler('CPLQuietErrorHandler') gdaltest.pg_ds.ExecuteSQL('DELLAYER:test41') @@ -2282,136 +1940,89 @@ def ogr_pg_41(): ds.CreateLayer('test41') found = ogr_pg_check_layer_in_list(ds, 'test41') - if found is False: - gdaltest.post_reason('layer test41 not listed') - return 'fail' + assert found is not False, 'layer test41 not listed' layer = ds.GetLayerByName('test41') - if layer.GetFeatureCount() != 0: - gdaltest.post_reason('wrong feature count') - print(layer.GetFeatureCount()) - return 'fail' + assert layer.GetFeatureCount() == 0, 'wrong feature count' layer = ds.GetLayerByName('AutoTest-schema.test41') - if layer.GetFeatureCount() != 0: - gdaltest.post_reason('wrong feature count') - print(layer.GetFeatureCount()) - return 'fail' + assert layer.GetFeatureCount() == 0, 'wrong feature count' ds.Destroy() - return 'success' - ############################################################################### # Test schemas= option -def ogr_pg_42(): +def test_ogr_pg_42(): if gdaltest.pg_ds is None: - return 'skip' + pytest.skip() ds = ogr.Open('PG:' + gdaltest.pg_connection_string + ' schemas=AutoTest-schema', update=1) # tpoly without schema refers to the active schema, that is to say AutoTest-schema found = ogr_pg_check_layer_in_list(ds, 'tpoly') - if found is False: - gdaltest.post_reason('layer tpoly not listed') - return 'fail' + assert found is not False, 'layer tpoly not listed' layer = ds.GetLayerByName('tpoly') - if layer.GetFeatureCount() != 3: - gdaltest.post_reason('wrong feature count') - print(layer.GetFeatureCount()) - return 'fail' + assert layer.GetFeatureCount() == 3, 'wrong feature count' found = ogr_pg_check_layer_in_list(ds, 'AutoTest-schema.tpoly') - if found is True: - gdaltest.post_reason('layer AutoTest-schema.tpoly is listed, but should not') - return 'fail' + assert found is not True, 'layer AutoTest-schema.tpoly is listed, but should not' layer = ds.GetLayerByName('AutoTest-schema.tpoly') - if layer.GetFeatureCount() != 3: - gdaltest.post_reason('wrong feature count') - print(layer.GetFeatureCount()) - return 'fail' + assert layer.GetFeatureCount() == 3, 'wrong feature count' found = ogr_pg_check_layer_in_list(ds, 'public.tpoly') - if found is True: - gdaltest.post_reason('layer public.tpoly is listed, but should not') - return 'fail' + assert found is not True, 'layer public.tpoly is listed, but should not' layer = ds.GetLayerByName('public.tpoly') - if layer.GetFeatureCount() != 19: - gdaltest.post_reason('wrong feature count') - print(layer.GetFeatureCount()) - return 'fail' + assert layer.GetFeatureCount() == 19, 'wrong feature count' found = ogr_pg_check_layer_in_list(ds, 'test41') - if found is False: - gdaltest.post_reason('layer test41 not listed') - return 'fail' + assert found is not False, 'layer test41 not listed' layer = ds.GetLayerByName('test41') - if layer.GetFeatureCount() != 0: - gdaltest.post_reason('wrong feature count') - print(layer.GetFeatureCount()) - return 'fail' + assert layer.GetFeatureCount() == 0, 'wrong feature count' layer = ds.GetLayerByName('AutoTest-schema.test41') - if layer.GetFeatureCount() != 0: - gdaltest.post_reason('wrong feature count') - print(layer.GetFeatureCount()) - return 'fail' + assert layer.GetFeatureCount() == 0, 'wrong feature count' ds.Destroy() - return 'success' - ############################################################################### # Test schemas= option -def ogr_pg_43(): +def test_ogr_pg_43(): if gdaltest.pg_ds is None: - return 'skip' + pytest.skip() ds = ogr.Open('PG:' + gdaltest.pg_connection_string + ' schemas=public,AutoTest-schema', update=1) # tpoly without schema refers to the active schema, that is to say public found = ogr_pg_check_layer_in_list(ds, 'tpoly') - if found is False: - gdaltest.post_reason('layer tpoly not listed') - return 'fail' + assert found is not False, 'layer tpoly not listed' layer = ds.GetLayerByName('tpoly') - if layer.GetFeatureCount() != 19: - gdaltest.post_reason('wrong feature count') - print(layer.GetFeatureCount()) - return 'fail' + assert layer.GetFeatureCount() == 19, 'wrong feature count' found = ogr_pg_check_layer_in_list(ds, 'AutoTest-schema.tpoly') - if found is False: - gdaltest.post_reason('layer AutoTest-schema.tpoly not listed') - return 'fail' + assert found is not False, 'layer AutoTest-schema.tpoly not listed' layer = ds.GetLayerByName('AutoTest-schema.tpoly') - if layer.GetFeatureCount() != 3: - gdaltest.post_reason('wrong feature count') - print(layer.GetFeatureCount()) - return 'fail' + assert layer.GetFeatureCount() == 3, 'wrong feature count' ds.Destroy() - return 'success' - ############################################################################### # Test for table and column names that need quoting (#2945) -def ogr_pg_44(): +def test_ogr_pg_44(): if gdaltest.pg_ds is None: - return 'skip' + pytest.skip() gdaltest.pg_lyr = gdaltest.pg_ds.CreateLayer('select', options=['OVERWRITE=YES', 'GEOMETRY_NAME=where', 'DIM=3']) ogrtest.quick_create_layer_def(gdaltest.pg_lyr, [('from', ogr.OFTReal)]) @@ -2427,45 +2038,37 @@ def ogr_pg_44(): geom = ogr.CreateGeometryFromWkt('POLYGON((0 0,0 1,1 1,1 0,0 0))') layer.SetSpatialFilter(geom) geom.Destroy() - if layer.GetFeatureCount() != 1: - return 'fail' + assert layer.GetFeatureCount() == 1 feat = layer.GetNextFeature() - if feat.GetGeometryRef().ExportToWkt() != 'POINT (0.5 0.5 1)': - return 'fail' + assert feat.GetGeometryRef().ExportToWkt() == 'POINT (0.5 0.5 1)' feat = layer.GetFeature(1) - if feat.GetGeometryRef().ExportToWkt() != 'POINT (0.5 0.5 1)': - return 'fail' + assert feat.GetGeometryRef().ExportToWkt() == 'POINT (0.5 0.5 1)' sql_lyr = ds.ExecuteSQL('SELECT * FROM "select"') geom = ogr.CreateGeometryFromWkt('POLYGON((0 0,0 1,1 1,1 0,0 0))') sql_lyr.SetSpatialFilter(geom) geom.Destroy() - if sql_lyr.GetFeatureCount() != 1: - return 'fail' + assert sql_lyr.GetFeatureCount() == 1 feat = sql_lyr.GetNextFeature() - if feat.GetGeometryRef().ExportToWkt() != 'POINT (0.5 0.5 1)': - return 'fail' + assert feat.GetGeometryRef().ExportToWkt() == 'POINT (0.5 0.5 1)' ds.ReleaseResultSet(sql_lyr) ds.Destroy() - return 'success' - ############################################################################### # Test SetNextByIndex (#3117) -def ogr_pg_45(): +def test_ogr_pg_45(): if gdaltest.pg_ds is None: - return 'skip' + pytest.skip() lyr = gdaltest.pg_ds.GetLayerByName('tpoly') - if not lyr.TestCapability(ogr.OLCFastSetNextByIndex): - gdaltest.post_reason('OLCFastSetNextByIndex returned false') - return 'fail' + assert lyr.TestCapability(ogr.OLCFastSetNextByIndex), \ + 'OLCFastSetNextByIndex returned false' nb_feat = lyr.GetFeatureCount() tab_feat = [None for i in range(nb_feat)] @@ -2474,26 +2077,21 @@ def ogr_pg_45(): lyr.SetNextByIndex(2) feat = lyr.GetNextFeature() - if feat.GetFID() != tab_feat[2].GetFID(): - gdaltest.post_reason('SetNextByIndex(2) did not return expected feature') - return 'fail' + assert feat.GetFID() == tab_feat[2].GetFID(), \ + 'SetNextByIndex(2) did not return expected feature' feat = lyr.GetNextFeature() - if feat.GetFID() != tab_feat[3].GetFID(): - gdaltest.post_reason('did not get expected feature') - return 'fail' - - return 'success' + assert feat.GetFID() == tab_feat[3].GetFID(), 'did not get expected feature' ############################################################################### # Test that we can read more than 500 features and update each one # with SetFeature() -def ogr_pg_46(): +def test_ogr_pg_46(): if gdaltest.pg_ds is None: - return 'skip' + pytest.skip() nFeatures = 1000 @@ -2520,9 +2118,8 @@ def ogr_pg_46(): feat = sqllyr.GetNextFeature() while feat is not None: expected_val = count - if feat.GetFieldAsInteger(0) != expected_val: - gdaltest.post_reason('expected value was %d. Got %d' % (expected_val, feat.GetFieldAsInteger(0))) - return 'fail' + assert feat.GetFieldAsInteger(0) == expected_val, \ + ('expected value was %d. Got %d' % (expected_val, feat.GetFieldAsInteger(0))) feat.SetField(0, -count) lyr.SetFeature(feat) feat.Destroy() @@ -2531,42 +2128,36 @@ def ogr_pg_46(): feat = sqllyr.GetNextFeature() - if count != nFeatures: - gdaltest.post_reason('did not get expected %d features' % nFeatures) - return 'fail' + assert count == nFeatures, ('did not get expected %d features' % nFeatures) # Check that 1 feature has been correctly updated sqllyr.SetNextByIndex(1) feat = sqllyr.GetNextFeature() expected_val = -1 - if feat.GetFieldAsInteger(0) != expected_val: - gdaltest.post_reason('expected value was %d. Got %d' % (expected_val, feat.GetFieldAsInteger(0))) - return 'fail' + assert feat.GetFieldAsInteger(0) == expected_val, \ + ('expected value was %d. Got %d' % (expected_val, feat.GetFieldAsInteger(0))) feat.Destroy() gdaltest.pg_ds.ReleaseResultSet(sqllyr) - return 'success' - ############################################################################### # Test that we can handle 'geography' column type introduced in PostGIS 1.5 -def ogr_pg_47(): +def test_ogr_pg_47(): if gdaltest.pg_ds is None: - return 'skip' + pytest.skip() if not gdaltest.pg_has_postgis: - return 'skip' + pytest.skip() # Create table with geography column gdaltest.pg_ds.ExecuteSQL("DELETE FROM spatial_ref_sys") gdaltest.pg_ds.ExecuteSQL("""INSERT INTO "spatial_ref_sys" ("srid","auth_name","auth_srid","srtext","proj4text") VALUES (4326,'EPSG',4326,'GEOGCS["WGS 84",DATUM["WGS_1984",SPHEROID["WGS 84",6378137,298.257223563,AUTHORITY["EPSG","7030"]],AUTHORITY["EPSG","6326"]],PRIMEM["Greenwich",0,AUTHORITY["EPSG","8901"]],UNIT["degree",0.01745329251994328,AUTHORITY["EPSG","9122"]],AUTHORITY["EPSG","4326"]]','+proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs ')""") if gdaltest.pg_ds.GetLayerByName('geography_columns') is None: - gdaltest.post_reason('autotest database must be created with PostGIS >= 1.5') - return 'skip' + pytest.skip('autotest database must be created with PostGIS >= 1.5') gdaltest.pg_ds = None gdaltest.pg_ds = ogr.Open('PG:' + gdaltest.pg_connection_string, update=1) @@ -2602,42 +2193,34 @@ def ogr_pg_47(): # Check if the layer is listed found = ogr_pg_check_layer_in_list(gdaltest.pg_ds, 'test_geog') - if found is False: - gdaltest.post_reason('layer test_geog not listed') - return 'fail' + assert found is not False, 'layer test_geog not listed' # Check that the layer is recorder in geometry_columns table geography_columns_lyr = gdaltest.pg_ds.ExecuteSQL("SELECT * FROM geography_columns WHERE f_table_name = 'test_geog'") feat = geography_columns_lyr.GetNextFeature() if feat.GetFieldAsString('f_geography_column') != 'my_geog': feat.DumpReadable() - return 'fail' + pytest.fail() gdaltest.pg_ds.ReleaseResultSet(geography_columns_lyr) # Get the layer by name lyr = gdaltest.pg_ds.GetLayerByName('test_geog') - if lyr.GetExtent() != (2.0, 2.0, 49.0, 49.0): - gdaltest.post_reason('bad extent for test_geog') - return 'fail' + assert lyr.GetExtent() == (2.0, 2.0, 49.0, 49.0), 'bad extent for test_geog' feat = lyr.GetNextFeature() geom = feat.GetGeometryRef() - if geom.ExportToWkt() != 'POINT (2 49)': - gdaltest.post_reason('bad geometry for test_geog') - return 'fail' + assert geom.ExportToWkt() == 'POINT (2 49)', 'bad geometry for test_geog' feat.Destroy() # Check with result set sql_lyr = gdaltest.pg_ds.ExecuteSQL('SELECT * FROM test_geog') - if sql_lyr.GetExtent() != (2.0, 2.0, 49.0, 49.0): - gdaltest.post_reason('bad extent for SELECT * FROM test_geog') - return 'fail' + assert sql_lyr.GetExtent() == (2.0, 2.0, 49.0, 49.0), \ + 'bad extent for SELECT * FROM test_geog' feat = sql_lyr.GetNextFeature() geom = feat.GetGeometryRef() - if geom.ExportToWkt() != 'POINT (2 49)': - gdaltest.post_reason('bad geometry for SELECT * FROM test_geog') - return 'fail' + assert geom.ExportToWkt() == 'POINT (2 49)', \ + 'bad geometry for SELECT * FROM test_geog' feat.Destroy() gdaltest.pg_ds.ReleaseResultSet(sql_lyr) @@ -2645,9 +2228,8 @@ def ogr_pg_47(): sql_lyr = gdaltest.pg_ds.ExecuteSQL('SELECT ST_AsText(my_geog) FROM test_geog') feat = sql_lyr.GetNextFeature() geom = feat.GetGeometryRef() - if geom.ExportToWkt() != 'POINT (2 49)': - gdaltest.post_reason('bad geometry for SELECT ST_AsText(my_geog) FROM test_geog') - return 'fail' + assert geom.ExportToWkt() == 'POINT (2 49)', \ + 'bad geometry for SELECT ST_AsText(my_geog) FROM test_geog' feat.Destroy() gdaltest.pg_ds.ReleaseResultSet(sql_lyr) @@ -2655,24 +2237,21 @@ def ogr_pg_47(): sql_lyr = gdaltest.pg_ds.ExecuteSQL('SELECT ST_AsBinary(my_geog) FROM test_geog') feat = sql_lyr.GetNextFeature() geom = feat.GetGeometryRef() - if geom.ExportToWkt() != 'POINT (2 49)': - gdaltest.post_reason('bad geometry for SELECT ST_AsBinary(my_geog) FROM test_geog') - return 'fail' + assert geom.ExportToWkt() == 'POINT (2 49)', \ + 'bad geometry for SELECT ST_AsBinary(my_geog) FROM test_geog' feat.Destroy() gdaltest.pg_ds.ReleaseResultSet(sql_lyr) - return 'success' - ############################################################################### # Test that we can read a table without any primary key (#2082) # Test also the effect of PG_LIST_ALL_TABLES with a non spatial table in a # PostGIS DB. -def ogr_pg_48(): +def test_ogr_pg_48(): if gdaltest.pg_ds is None: - return 'skip' + pytest.skip() gdaltest.pg_ds.ExecuteSQL("CREATE TABLE no_pk_table (gid serial NOT NULL, other_id INTEGER)") gdaltest.pg_ds.ExecuteSQL("INSERT INTO no_pk_table (gid, other_id) VALUES (1, 10)") @@ -2683,15 +2262,11 @@ def ogr_pg_48(): found = ogr_pg_check_layer_in_list(gdaltest.pg_ds, 'no_pk_table') if gdaltest.pg_has_postgis: # Non spatial table in a PostGIS db -> not listed ... - if found: - gdaltest.post_reason('layer no_pk_table unexpectedly listed') - return 'fail' + assert not found, 'layer no_pk_table unexpectedly listed' # ... but should be found on explicit request lyr = gdaltest.pg_ds.GetLayer('no_pk_table') - if lyr is None: - gdaltest.post_reason('could not get no_pk_table') - return 'fail' + assert lyr is not None, 'could not get no_pk_table' # Try again by setting PG_LIST_ALL_TABLES=YES gdal.SetConfigOption('PG_LIST_ALL_TABLES', 'YES') @@ -2700,64 +2275,47 @@ def ogr_pg_48(): gdal.SetConfigOption('PG_LIST_ALL_TABLES', None) found = ogr_pg_check_layer_in_list(gdaltest.pg_ds, 'no_pk_table') - if found is False: - gdaltest.post_reason('layer no_pk_table not listed') - return 'fail' + assert found is not False, 'layer no_pk_table not listed' # Test LIST_ALL_TABLES=YES open option gdaltest.pg_ds.Destroy() gdaltest.pg_ds = gdal.OpenEx('PG:' + gdaltest.pg_connection_string, gdal.OF_VECTOR | gdal.OF_UPDATE, open_options=['LIST_ALL_TABLES=YES']) found = ogr_pg_check_layer_in_list(gdaltest.pg_ds, 'no_pk_table') - if found is False: - gdaltest.post_reason('layer no_pk_table not listed') - return 'fail' + assert found is not False, 'layer no_pk_table not listed' lyr = gdaltest.pg_ds.GetLayer('no_pk_table') - if lyr is None: - gdaltest.post_reason('could not get no_pk_table') - return 'fail' + assert lyr is not None, 'could not get no_pk_table' sr = lyr.GetSpatialRef() - if sr is not None: - gdaltest.post_reason('did not get expected SRS') - return 'fail' + assert sr is None, 'did not get expected SRS' feat = lyr.GetNextFeature() - if feat is None: - gdaltest.post_reason('did not get feature') - return 'fail' + assert feat is not None, 'did not get feature' - if lyr.GetFIDColumn() != '': - gdaltest.post_reason('got a non NULL FID column') - print(lyr.GetFIDColumn()) - return 'fail' + assert lyr.GetFIDColumn() == '', 'got a non NULL FID column' if feat.GetFID() != 0: - gdaltest.post_reason('did not get expected FID') feat.DumpReadable() - return 'fail' + pytest.fail('did not get expected FID') if feat.GetFieldAsInteger('gid') != 1: - gdaltest.post_reason('did not get expected gid') feat.DumpReadable() - return 'fail' + pytest.fail('did not get expected gid') if feat.GetFieldAsInteger('other_id') != 10: - gdaltest.post_reason('did not get expected other_id') feat.DumpReadable() - return 'fail' - - return 'success' + pytest.fail('did not get expected other_id') + ############################################################################### # Go on with previous test but set PGSQL_OGR_FID this time -def ogr_pg_49(): +def test_ogr_pg_49(): if gdaltest.pg_ds is None: - return 'skip' + pytest.skip() gdal.SetConfigOption('PGSQL_OGR_FID', 'other_id') gdaltest.pg_ds = None @@ -2768,32 +2326,25 @@ def ogr_pg_49(): feat = lyr.GetNextFeature() lyr.ResetReading() # to close implicit transaction - if lyr.GetFIDColumn() != 'other_id': - print(lyr.GetFIDColumn()) - gdaltest.post_reason('did not get expected FID column') - return 'fail' + assert lyr.GetFIDColumn() == 'other_id', 'did not get expected FID column' if feat.GetFID() != 10: - gdaltest.post_reason('did not get expected FID') feat.DumpReadable() - return 'fail' - - return 'success' + pytest.fail('did not get expected FID') + ############################################################################### # Write and read NaN values (#3667) # This tests writing using COPY and INSERT -def ogr_pg_50(): +def test_ogr_pg_50(): if gdaltest.pg_ds is None: - return 'skip' + pytest.skip() gdaltest.pg_lyr = gdaltest.pg_ds.GetLayerByName('tpoly') - if gdaltest.pg_lyr is None: - gdaltest.post_reason('did not get tpoly layer') - return 'fail' + assert gdaltest.pg_lyr is not None, 'did not get tpoly layer' feature_def = gdaltest.pg_lyr.GetLayerDefn() dst_feat = ogr.Feature(feature_def) @@ -2826,82 +2377,68 @@ def ogr_pg_50(): got_val = feat.GetField('AREA') if value == 'NaN': if not gdaltest.isnan(got_val): - print(feat.GetFieldAsString('AREA') + ' returned for AREA instead of ' + value) gdaltest.pg_lyr.ResetReading() # to close implicit transaction - return 'fail' + pytest.fail(feat.GetFieldAsString('AREA') + ' returned for AREA instead of ' + value) elif got_val != float(value): - print(feat.GetFieldAsString('AREA') + ' returned for AREA instead of ' + value) gdaltest.pg_lyr.ResetReading() # to close implicit transaction - return 'fail' + pytest.fail(feat.GetFieldAsString('AREA') + ' returned for AREA instead of ' + value) if bHasSetFieldDoubleList: got_val = feat.GetFieldAsDoubleList(feature_def.GetFieldIndex('REALLIST')) if value == 'NaN': if not gdaltest.isnan(got_val[0]) or not gdaltest.isnan(got_val[1]): - print(feat.GetFieldAsString('REALLIST') + ' returned for REALLIST instead of ' + value) gdaltest.pg_lyr.ResetReading() # to close implicit transaction - return 'fail' + pytest.fail(feat.GetFieldAsString('REALLIST') + ' returned for REALLIST instead of ' + value) elif got_val[0] != float(value) or got_val[1] != float(value): - print(feat.GetFieldAsString('REALLIST') + ' returned for REALLIST instead of ' + value) gdaltest.pg_lyr.ResetReading() # to close implicit transaction - return 'fail' + pytest.fail(feat.GetFieldAsString('REALLIST') + ' returned for REALLIST instead of ' + value) gdaltest.pg_lyr.ResetReading() # to close implicit transaction - return 'success' - ############################################################################### # Run test_ogrsf -def ogr_pg_51(): +def test_ogr_pg_51(): if gdaltest.pg_ds is None: - return 'skip' + pytest.skip() import test_cli_utilities if test_cli_utilities.get_test_ogrsf_path() is None: - return 'skip' + pytest.skip() ret = gdaltest.runexternal(test_cli_utilities.get_test_ogrsf_path() + ' "' + 'PG:' + gdaltest.pg_connection_string + '" tpoly testview') - if ret.find('INFO') == -1 or ret.find('ERROR') != -1: - print(ret) - return 'fail' - - return 'success' + assert ret.find('INFO') != -1 and ret.find('ERROR') == -1 ############################################################################### # Run test_ogrsf with -sql -def ogr_pg_52(): +def test_ogr_pg_52(): if gdaltest.pg_ds is None: - return 'skip' + pytest.skip() import test_cli_utilities if test_cli_utilities.get_test_ogrsf_path() is None: - return 'skip' + pytest.skip() ret = gdaltest.runexternal(test_cli_utilities.get_test_ogrsf_path() + ' "' + 'PG:' + gdaltest.pg_connection_string + '" -sql "SELECT * FROM tpoly"') - if ret.find('INFO') == -1 or ret.find('ERROR') != -1: - print(ret) - return 'fail' - - return 'success' + assert ret.find('INFO') != -1 and ret.find('ERROR') == -1 ############################################################################### # Test creating a layer with explicitly wkbNone geometry type. -def ogr_pg_53(): +def test_ogr_pg_53(): if gdaltest.pg_ds is None: - return 'skip' + pytest.skip() - lyr = gdaltest.pg_ds.CreateLayer('no_geometry_table', geom_type=ogr.wkbNone) + lyr = gdaltest.pg_ds.CreateLayer('no_geometry_table', geom_type=ogr.wkbNone, options=['OVERWRITE=YES']) field_defn = ogr.FieldDefn('foo') lyr.CreateField(field_defn) @@ -2913,21 +2450,17 @@ def ogr_pg_53(): ds = ogr.Open('PG:' + gdaltest.pg_connection_string) - if gdaltest.pg_has_postgis is True and ogr_pg_check_layer_in_list(ds, 'no_geometry_table') is True: - gdaltest.post_reason('did not expected no_geometry_table to be listed at that point') - return 'fail' + assert not (gdaltest.pg_has_postgis is True and ogr_pg_check_layer_in_list(ds, 'no_geometry_table') is True), \ + 'did not expected no_geometry_table to be listed at that point' lyr = ds.GetLayerByName('no_geometry_table') feat = lyr.GetNextFeature() - if feat.GetField(0) != 'bar': - return 'fail' + assert feat.GetField(0) == 'bar' gdal.PushErrorHandler('CPLQuietErrorHandler') lyr = ds.CreateLayer('no_geometry_table', geom_type=ogr.wkbNone) gdal.PopErrorHandler() - if lyr is not None: - gdaltest.post_reason('layer creation should have failed') - return 'fail' + assert lyr is None, 'layer creation should have failed' lyr = ds.CreateLayer('no_geometry_table', geom_type=ogr.wkbNone, options=['OVERWRITE=YES']) field_defn = ogr.FieldDefn('baz') @@ -2941,26 +2474,22 @@ def ogr_pg_53(): lyr.CreateField(field_defn) field_defn = ogr.FieldDefn('baz') lyr.CreateField(field_defn) - if lyr is None: - return 'fail' + assert lyr is not None ds = None ds = ogr.Open('PG:' + gdaltest.pg_connection_string) lyr = ds.GetLayerByName('no_geometry_table') - if lyr.GetLayerDefn().GetFieldCount() != 2: - return 'fail' - - return 'success' + assert lyr.GetLayerDefn().GetFieldCount() == 2 ############################################################################### # Check that we can overwrite a non-spatial geometry table (#4012) -def ogr_pg_53_bis(): +def test_ogr_pg_53_bis(): import test_cli_utilities if test_cli_utilities.get_ogr2ogr_path() is None: - return 'skip' + pytest.skip() f = open('tmp/no_geometry_table.csv', 'wt') f.write('foo,bar\n') @@ -2973,22 +2502,19 @@ def ogr_pg_53_bis(): ds = ogr.Open('PG:' + gdaltest.pg_connection_string) lyr = ds.GetLayerByName('no_geometry_table') feat = lyr.GetNextFeature() - if feat.GetField(0) != 'baz': - return 'fail' - - return 'success' + assert feat.GetField(0) == 'baz' ############################################################################### # Test reading AsEWKB() -def ogr_pg_54(): +def test_ogr_pg_54(): if gdaltest.pg_ds is None: - return 'skip' + pytest.skip() if not gdaltest.pg_has_postgis: - return 'skip' + pytest.skip() if gdaltest.pg_has_postgis_2: sql_lyr = gdaltest.pg_ds.ExecuteSQL("SELECT ST_AsEWKB(GeomFromEWKT('POINT (0 1 2)'))") @@ -2998,22 +2524,19 @@ def ogr_pg_54(): gdaltest.pg_ds.ReleaseResultSet(sql_lyr) geom = feat.GetGeometryRef() - if geom.ExportToWkt() != 'POINT (0 1 2)': - return 'fail' - - return 'success' + assert geom.ExportToWkt() == 'POINT (0 1 2)' ############################################################################### # Test reading geoms as Base64 encoded strings -def ogr_pg_55(): +def test_ogr_pg_55(): if gdaltest.pg_ds is None: - return 'skip' + pytest.skip() if not gdaltest.pg_has_postgis: - return 'skip' + pytest.skip() layer = gdaltest.pg_ds.CreateLayer('ogr_pg_55', options=['DIM=3']) feat = ogr.Feature(layer.GetLayerDefn()) @@ -3029,21 +2552,18 @@ def ogr_pg_55(): layer = ds.GetLayerByName('ogr_pg_55') feat = layer.GetNextFeature() gdal.SetConfigOption('PG_USE_BASE64', old_val) - if feat.GetGeometryRef().ExportToWkt() != 'POINT (1 2 3)': - return 'fail' + assert feat.GetGeometryRef().ExportToWkt() == 'POINT (1 2 3)' ds = None - return 'success' - ############################################################################### # Test insertion of features with first field being a 0-character string in a # non-spatial table and without FID in COPY mode (#4040) -def ogr_pg_56(): +def test_ogr_pg_56(): if gdaltest.pg_ds is None: - return 'skip' + pytest.skip() gdaltest.pg_ds.ExecuteSQL('CREATE TABLE ogr_pg_56 ( bar varchar, baz varchar ) WITH (OIDS=FALSE)') @@ -3087,52 +2607,44 @@ def ogr_pg_56(): feat = lyr.GetNextFeature() if feat.GetField(0) is not None or feat.GetField(1) is not None: - gdaltest.post_reason('did not get expected value for feat %d' % feat.GetFID()) feat.DumpReadable() - return 'fail' + pytest.fail('did not get expected value for feat %d' % feat.GetFID()) feat = lyr.GetNextFeature() if feat.GetField(0) != '' or feat.GetField(1) is not None: - gdaltest.post_reason('did not get expected value for feat %d' % feat.GetFID()) feat.DumpReadable() - return 'fail' + pytest.fail('did not get expected value for feat %d' % feat.GetFID()) feat = lyr.GetNextFeature() if feat.GetField(0) is not None or feat.GetField(1) != '': - gdaltest.post_reason('did not get expected value for feat %d' % feat.GetFID()) feat.DumpReadable() - return 'fail' + pytest.fail('did not get expected value for feat %d' % feat.GetFID()) feat = lyr.GetNextFeature() if feat.GetField(0) != '' or feat.GetField(1) != '': - gdaltest.post_reason('did not get expected value for feat %d' % feat.GetFID()) feat.DumpReadable() - return 'fail' + pytest.fail('did not get expected value for feat %d' % feat.GetFID()) feat = lyr.GetNextFeature() if feat.GetField(0) != 'bar' or feat.GetField(1) != '': - gdaltest.post_reason('did not get expected value for feat %d' % feat.GetFID()) feat.DumpReadable() - return 'fail' + pytest.fail('did not get expected value for feat %d' % feat.GetFID()) feat = lyr.GetNextFeature() if feat.GetField(0) != '' or feat.GetField(1) != 'baz': - gdaltest.post_reason('did not get expected value for feat %d' % feat.GetFID()) feat.DumpReadable() - return 'fail' + pytest.fail('did not get expected value for feat %d' % feat.GetFID()) ds = None - return 'success' - ############################################################################### # Test inserting an empty feature -def ogr_pg_57(): +def test_ogr_pg_57(): if gdaltest.pg_ds is None: - return 'skip' + pytest.skip() lyr = gdaltest.pg_ds.CreateLayer('ogr_pg_57') lyr.CreateField(ogr.FieldDefn('acolumn', ogr.OFTString)) @@ -3140,19 +2652,16 @@ def ogr_pg_57(): ret = lyr.CreateFeature(feat) feat = None - if ret != 0: - return 'fail' - - return 'success' + assert ret == 0 ############################################################################### # Test RFC35 -def ogr_pg_58(): +def test_ogr_pg_58(): if gdaltest.pg_ds is None: - return 'skip' + pytest.skip() lyr = gdaltest.pg_ds.CreateLayer('ogr_pg_58') lyr.CreateField(ogr.FieldDefn('strcolumn', ogr.OFTString)) @@ -3162,12 +2671,9 @@ def ogr_pg_58(): lyr.CreateFeature(feat) feat = None - if lyr.TestCapability(ogr.OLCReorderFields) != 0: - return 'fail' - if lyr.TestCapability(ogr.OLCAlterFieldDefn) != 1: - return 'fail' - if lyr.TestCapability(ogr.OLCDeleteField) != 1: - return 'fail' + assert lyr.TestCapability(ogr.OLCReorderFields) == 0 + assert lyr.TestCapability(ogr.OLCAlterFieldDefn) == 1 + assert lyr.TestCapability(ogr.OLCDeleteField) == 1 fd = ogr.FieldDefn('anotherstrcolumn', ogr.OFTString) fd.SetWidth(5) @@ -3175,9 +2681,7 @@ def ogr_pg_58(): lyr.ResetReading() feat = lyr.GetNextFeature() - if feat.GetField('anotherstrcolumn') != '12345': - gdaltest.post_reason('failed (1)') - return 'fail' + assert feat.GetField('anotherstrcolumn') == '12345', 'failed (1)' gdaltest.pg_ds = None gdaltest.pg_ds = ogr.Open('PG:' + gdaltest.pg_connection_string, update=1) @@ -3185,39 +2689,32 @@ def ogr_pg_58(): lyr.ResetReading() feat = lyr.GetNextFeature() - if feat.GetField('anotherstrcolumn') != '12345': - gdaltest.post_reason('failed (2)') - return 'fail' + assert feat.GetField('anotherstrcolumn') == '12345', 'failed (2)' feat = None lyr.ResetReading() # to close implicit transaction - if lyr.DeleteField(lyr.GetLayerDefn().GetFieldIndex('anotherstrcolumn')) != 0: - gdaltest.post_reason('failed (3)') - return 'fail' + assert lyr.DeleteField(lyr.GetLayerDefn().GetFieldIndex('anotherstrcolumn')) == 0, \ + 'failed (3)' gdaltest.pg_ds = None gdaltest.pg_ds = ogr.Open('PG:' + gdaltest.pg_connection_string, update=1) lyr = gdaltest.pg_ds.GetLayer('ogr_pg_58') - if lyr.GetLayerDefn().GetFieldCount() != 1: - gdaltest.post_reason('failed (4)') - return 'fail' - - return 'success' + assert lyr.GetLayerDefn().GetFieldCount() == 1, 'failed (4)' ############################################################################### # Check that we can use -nln with a layer name that is recognized by GetLayerByName() # but which is not the layer name. -def ogr_pg_59(): +def test_ogr_pg_59(): if gdaltest.pg_ds is None: - return 'skip' + pytest.skip() import test_cli_utilities if test_cli_utilities.get_ogr2ogr_path() is None: - return 'skip' + pytest.skip() gdaltest.runexternal( test_cli_utilities.get_ogr2ogr_path() + @@ -3229,21 +2726,17 @@ def ogr_pg_59(): fc = lyr.GetFeatureCount() ds = None - if fc != 35: - gdaltest.post_reason('did not get expected feature count') - return 'fail' - - return 'success' + assert fc == 35, 'did not get expected feature count' ############################################################################### # Test that we can insert a feature that has a FID on a table with a # non-incrementing PK. -def ogr_pg_60(): +def test_ogr_pg_60(): if gdaltest.pg_ds is None: - return 'skip' + pytest.skip() sql_lyr = gdaltest.pg_ds.ExecuteSQL("CREATE TABLE ogr_pg_60(id integer," "name varchar(50),primary key (id)) " @@ -3254,34 +2747,25 @@ def ogr_pg_60(): gdaltest.pg_ds = ogr.Open('PG:' + gdaltest.pg_connection_string, update=1) lyr = gdaltest.pg_ds.GetLayerByName('ogr_pg_60') - if lyr.GetFIDColumn() != 'id': - gdaltest.post_reason('did not get expected name for FID column') - print(lyr.GetFIDColumn()) - return 'fail' + assert lyr.GetFIDColumn() == 'id', 'did not get expected name for FID column' feat = ogr.Feature(lyr.GetLayerDefn()) feat.SetFID(100) feat.SetField('name', 'a_name') lyr.CreateFeature(feat) - if feat.GetFID() != 100: - gdaltest.post_reason('bad FID value') - return 'fail' + assert feat.GetFID() == 100, 'bad FID value' feat = lyr.GetFeature(100) - if feat is None: - gdaltest.post_reason('did not get feature') - return 'fail' - - return 'success' + assert feat is not None, 'did not get feature' ############################################################################### # Test insertion of features with FID set in COPY mode (#4495) -def ogr_pg_61(): +def test_ogr_pg_61(): if gdaltest.pg_ds is None: - return 'skip' + pytest.skip() gdaltest.pg_ds.ExecuteSQL('CREATE TABLE ogr_pg_61 ( id integer NOT NULL PRIMARY KEY, bar varchar )') @@ -3308,31 +2792,27 @@ def ogr_pg_61(): feat = lyr.GetFeature(10) if not feat.IsFieldNull(0): - gdaltest.post_reason('did not get expected value for feat %d' % feat.GetFID()) feat.DumpReadable() - return 'fail' + pytest.fail('did not get expected value for feat %d' % feat.GetFID()) feat = lyr.GetFeature(20) if feat.GetField(0) != 'baz': - gdaltest.post_reason('did not get expected value for feat %d' % feat.GetFID()) feat.DumpReadable() - return 'fail' + pytest.fail('did not get expected value for feat %d' % feat.GetFID()) ds = None - return 'success' - ############################################################################### # Test ExecuteSQL() and getting SRID of the request (#4699) -def ogr_pg_62(): +def test_ogr_pg_62(): if gdaltest.pg_ds is None: - return 'skip' + pytest.skip() if not gdaltest.pg_has_postgis: - return 'skip' + pytest.skip() # Test on a regular request in a table srs = osr.SpatialReference() @@ -3343,32 +2823,26 @@ def ogr_pg_62(): sql_lyr = gdaltest.pg_ds.ExecuteSQL('SELECT * FROM testsrtext2') got_srs = sql_lyr.GetSpatialRef() gdaltest.pg_ds.ReleaseResultSet(sql_lyr) - if got_srs is None or got_srs.ExportToWkt().find('32631') == -1: - gdaltest.post_reason('fail') - return 'fail' + assert not (got_srs is None or got_srs.ExportToWkt().find('32631') == -1) # Test a request on a table, but with a geometry column not in the table sql_lyr = gdaltest.pg_ds.ExecuteSQL("SELECT eas_id, GeomFromEWKT('SRID=4326;POINT(0 1)') FROM tpoly") got_srs = sql_lyr.GetSpatialRef() gdaltest.pg_ds.ReleaseResultSet(sql_lyr) - if got_srs is None or got_srs.ExportToWkt().find('4326') == -1: - gdaltest.post_reason('fail') - return 'fail' - - return 'success' + assert not (got_srs is None or got_srs.ExportToWkt().find('4326') == -1) ############################################################################### # Test COLUMN_TYPES layer creation option (#4788) -def ogr_pg_63(): +def test_ogr_pg_63(): if gdaltest.pg_ds is None: - return 'skip' + pytest.skip() # No need to test it in the non PostGIS case if not gdaltest.pg_has_postgis: - return 'skip' + pytest.skip() lyr = gdaltest.pg_ds.CreateLayer('ogr_pg_63', options=['COLUMN_TYPES=foo=int8,bar=numeric(10,5),baz=hstore,baw=numeric(20,0)']) lyr.CreateField(ogr.FieldDefn('foo', ogr.OFTString)) @@ -3385,35 +2859,25 @@ def ogr_pg_63(): ds = ogr.Open('PG:' + gdaltest.pg_connection_string) lyr = ds.GetLayerByName('ogr_pg_63') - if lyr.GetLayerDefn().GetFieldDefn(lyr.GetLayerDefn().GetFieldIndex('foo')).GetType() != ogr.OFTInteger64: - gdaltest.post_reason('fail') - return 'fail' - if lyr.GetLayerDefn().GetFieldDefn(lyr.GetLayerDefn().GetFieldIndex('bar')).GetType() != ogr.OFTReal: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.GetLayerDefn().GetFieldDefn(lyr.GetLayerDefn().GetFieldIndex('foo')).GetType() == ogr.OFTInteger64 + assert lyr.GetLayerDefn().GetFieldDefn(lyr.GetLayerDefn().GetFieldIndex('bar')).GetType() == ogr.OFTReal feat = lyr.GetNextFeature() - if feat.GetField('foo') != 123: - gdaltest.post_reason('fail') - return 'fail' - if feat.GetField('baw') != 123456789012345: - gdaltest.post_reason('fail') - return 'fail' - - return 'success' + assert feat.GetField('foo') == 123 + assert feat.GetField('baw') == 123456789012345 ############################################################################### # Test OGR_TRUNCATE config. option (#5091) -def ogr_pg_64(): +def test_ogr_pg_64(): if gdaltest.pg_ds is None: - return 'skip' + pytest.skip() # No need to test it in the non PostGIS case if not gdaltest.pg_has_postgis: - return 'skip' + pytest.skip() ds = ogr.Open('PG:' + gdaltest.pg_connection_string, update=1) lyr = ds.GetLayerByName('ogr_pg_63') @@ -3422,10 +2886,7 @@ def ogr_pg_64(): feat.SetField('foo', '124') lyr.CreateFeature(feat) - if lyr.GetFeatureCount() != 2: - gdaltest.post_reason('fail') - print(lyr.GetFeatureCount()) - return 'fail' + assert lyr.GetFeatureCount() == 2 ds = ogr.Open('PG:' + gdaltest.pg_connection_string, update=1) lyr = ds.GetLayerByName('ogr_pg_63') @@ -3438,81 +2899,60 @@ def ogr_pg_64(): gdal.SetConfigOption('OGR_TRUNCATE', None) # Just one feature because of truncation - if lyr.GetFeatureCount() != 1: - gdaltest.post_reason('fail') - print(lyr.GetFeatureCount()) - return 'fail' - - return 'success' + assert lyr.GetFeatureCount() == 1 ############################################################################### # Test RFC 41 -def ogr_pg_65(): +def test_ogr_pg_65(): if gdaltest.pg_ds is None: - return 'skip' + pytest.skip() if not gdaltest.pg_has_postgis: - return 'skip' + pytest.skip() ds = ogr.Open('PG:' + gdaltest.pg_connection_string, update=1) - if ds.TestCapability(ogr.ODsCCreateGeomFieldAfterCreateLayer) == 0: - gdaltest.post_reason('fail') - return 'fail' + assert ds.TestCapability(ogr.ODsCCreateGeomFieldAfterCreateLayer) != 0 lyr = ds.CreateLayer('ogr_pg_65', geom_type=ogr.wkbNone) - if lyr.TestCapability(ogr.OLCCreateGeomField) == 0: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.TestCapability(ogr.OLCCreateGeomField) != 0 gfld_defn = ogr.GeomFieldDefn('geom1', ogr.wkbPoint) srs = osr.SpatialReference() srs.ImportFromEPSG(4326) gfld_defn.SetSpatialRef(srs) - if lyr.CreateGeomField(gfld_defn) != 0: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.CreateGeomField(gfld_defn) == 0 gfld_defn = ogr.GeomFieldDefn('geom2', ogr.wkbLineString25D) - if lyr.CreateGeomField(gfld_defn) != 0: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.CreateGeomField(gfld_defn) == 0 gfld_defn = ogr.GeomFieldDefn('geom3', ogr.wkbPoint) srs = osr.SpatialReference() srs.ImportFromEPSG(32631) gfld_defn.SetSpatialRef(srs) - if lyr.CreateGeomField(gfld_defn) != 0: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.CreateGeomField(gfld_defn) == 0 lyr.CreateField(ogr.FieldDefn('intfield', ogr.OFTInteger)) feat = ogr.Feature(lyr.GetLayerDefn()) feat.SetField('intfield', 123) feat.SetGeomFieldDirectly('geom1', ogr.CreateGeometryFromWkt('POINT (1 2)')) feat.SetGeomFieldDirectly('geom2', ogr.CreateGeometryFromWkt('LINESTRING (3 4 5,6 7 8)')) - if lyr.CreateFeature(feat) != 0: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.CreateFeature(feat) == 0 feat = ogr.Feature(lyr.GetLayerDefn()) - if lyr.CreateFeature(feat) != 0: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.CreateFeature(feat) == 0 lyr.ResetReading() feat = lyr.GetNextFeature() if feat.GetField('intfield') != 123 or \ feat.GetGeomFieldRef('geom1').ExportToWkt() != 'POINT (1 2)' or \ feat.GetGeomFieldRef('geom2').ExportToWkt() != 'LINESTRING (3 4 5,6 7 8)': feat.DumpReadable() - gdaltest.post_reason('fail') - return 'fail' + pytest.fail() feat = lyr.GetNextFeature() if feat.GetGeomFieldRef('geom1') is not None or \ feat.GetGeomFieldRef('geom2') is not None: feat.DumpReadable() - gdaltest.post_reason('fail') - return 'fail' + pytest.fail() ds = None for i in range(2): @@ -3521,40 +2961,24 @@ def ogr_pg_65(): lyr = ds.GetLayerByName('ogr_pg_65') else: lyr = ds.ExecuteSQL('SELECT * FROM ogr_pg_65') - if lyr.GetLayerDefn().GetGeomFieldDefn(0).GetName() != 'geom1': - gdaltest.post_reason('fail') - return 'fail' - if i == 0 and lyr.GetLayerDefn().GetGeomFieldDefn(0).GetType() != ogr.wkbPoint: - gdaltest.post_reason('fail') - return 'fail' - if lyr.GetLayerDefn().GetGeomFieldDefn(0).GetSpatialRef().ExportToWkt().find('4326') < 0: - gdaltest.post_reason('fail') - return 'fail' - if lyr.GetLayerDefn().GetGeomFieldDefn(1).GetName() != 'geom2': - gdaltest.post_reason('fail') - return 'fail' - if i == 0 and lyr.GetLayerDefn().GetGeomFieldDefn(1).GetType() != ogr.wkbLineString25D: - gdaltest.post_reason('fail') - return 'fail' - if lyr.GetLayerDefn().GetGeomFieldDefn(1).GetSpatialRef() is not None: - gdaltest.post_reason('fail') - return 'fail' - if i == 0 and lyr.GetLayerDefn().GetGeomFieldDefn(2).GetSpatialRef().ExportToWkt().find('32631') < 0: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.GetLayerDefn().GetGeomFieldDefn(0).GetName() == 'geom1' + assert i != 0 or lyr.GetLayerDefn().GetGeomFieldDefn(0).GetType() == ogr.wkbPoint + assert lyr.GetLayerDefn().GetGeomFieldDefn(0).GetSpatialRef().ExportToWkt().find('4326') >= 0 + assert lyr.GetLayerDefn().GetGeomFieldDefn(1).GetName() == 'geom2' + assert i != 0 or lyr.GetLayerDefn().GetGeomFieldDefn(1).GetType() == ogr.wkbLineString25D + assert lyr.GetLayerDefn().GetGeomFieldDefn(1).GetSpatialRef() is None + assert not (i == 0 and lyr.GetLayerDefn().GetGeomFieldDefn(2).GetSpatialRef().ExportToWkt().find('32631') < 0) feat = lyr.GetNextFeature() if feat.GetField('intfield') != 123 or \ feat.GetGeomFieldRef('geom1').ExportToWkt() != 'POINT (1 2)' or \ feat.GetGeomFieldRef('geom2').ExportToWkt() != 'LINESTRING (3 4 5,6 7 8)': feat.DumpReadable() - gdaltest.post_reason('fail') - return 'fail' + pytest.fail() feat = lyr.GetNextFeature() if feat.GetGeomFieldRef('geom1') is not None or \ feat.GetGeomFieldRef('geom2') is not None: feat.DumpReadable() - gdaltest.post_reason('fail') - return 'fail' + pytest.fail() if i == 1: ds.ReleaseResultSet(lyr) @@ -3566,13 +2990,9 @@ def ogr_pg_65(): feat = ogr.Feature(lyr.GetLayerDefn()) feat.SetGeomFieldDirectly('geom1', ogr.CreateGeometryFromWkt('POINT (3 4)')) feat.SetGeomFieldDirectly('geom2', ogr.CreateGeometryFromWkt('LINESTRING (4 5 6,7 8 9)')) - if lyr.CreateFeature(feat) != 0: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.CreateFeature(feat) == 0 feat = ogr.Feature(lyr.GetLayerDefn()) - if lyr.CreateFeature(feat) != 0: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.CreateFeature(feat) == 0 gdal.SetConfigOption('PG_USE_COPY', gdaltest.pg_use_copy) ds = ogr.Open('PG:' + gdaltest.pg_connection_string) @@ -3581,67 +3001,54 @@ def ogr_pg_65(): if feat.GetGeomFieldRef('geom1').ExportToWkt() != 'POINT (3 4)' or \ feat.GetGeomFieldRef('geom2').ExportToWkt() != 'LINESTRING (4 5 6,7 8 9)': feat.DumpReadable() - gdaltest.post_reason('fail') - return 'fail' + pytest.fail() feat = lyr.GetNextFeature() if feat.GetGeomFieldRef('geom1') is not None or \ feat.GetGeomFieldRef('geom2') is not None: feat.DumpReadable() - gdaltest.post_reason('fail') - return 'fail' + pytest.fail() import test_cli_utilities if test_cli_utilities.get_ogr2ogr_path() is not None: gdaltest.runexternal(test_cli_utilities.get_ogr2ogr_path() + ' -update "' + 'PG:' + gdaltest.pg_connection_string + '" "' + 'PG:' + gdaltest.pg_connection_string + '" ogr_pg_65 -nln ogr_pg_65_copied -overwrite') ds = ogr.Open('PG:' + gdaltest.pg_connection_string) lyr = ds.GetLayerByName('ogr_pg_65_copied') - if lyr.GetLayerDefn().GetGeomFieldDefn(0).GetSpatialRef().ExportToWkt().find('4326') < 0: - gdaltest.post_reason('fail') - return 'fail' - if lyr.GetLayerDefn().GetGeomFieldDefn(1).GetSpatialRef() is not None: - gdaltest.post_reason('fail') - return 'fail' - if lyr.GetLayerDefn().GetGeomFieldDefn(2).GetSpatialRef().ExportToWkt().find('32631') < 0: - gdaltest.post_reason('fail') - return 'fail' - - return 'success' + assert lyr.GetLayerDefn().GetGeomFieldDefn(0).GetSpatialRef().ExportToWkt().find('4326') >= 0 + assert lyr.GetLayerDefn().GetGeomFieldDefn(1).GetSpatialRef() is None + assert lyr.GetLayerDefn().GetGeomFieldDefn(2).GetSpatialRef().ExportToWkt().find('32631') >= 0 + ############################################################################### # Run test_ogrsf -def ogr_pg_66(): +def test_ogr_pg_66(): if gdaltest.pg_ds is None: - return 'skip' + pytest.skip() if not gdaltest.pg_has_postgis: - return 'skip' + pytest.skip() import test_cli_utilities if test_cli_utilities.get_test_ogrsf_path() is None: - return 'skip' + pytest.skip() ret = gdaltest.runexternal(test_cli_utilities.get_test_ogrsf_path() + ' "' + 'PG:' + gdaltest.pg_connection_string + '" ogr_pg_65') - if ret.find('INFO') == -1 or ret.find('ERROR') != -1: - print(ret) - return 'fail' - - return 'success' + assert ret.find('INFO') != -1 and ret.find('ERROR') == -1 ############################################################################### # Test retrieving SRID from values (#5131) -def ogr_pg_67(): +def test_ogr_pg_67(): if gdaltest.pg_ds is None: - return 'skip' + pytest.skip() if not gdaltest.pg_has_postgis: - return 'skip' + pytest.skip() lyr = gdaltest.pg_ds.CreateLayer('ogr_pg_67') lyr.ResetReading() # to trigger layer creation @@ -3649,9 +3056,7 @@ def ogr_pg_67(): ds = ogr.Open('PG:' + gdaltest.pg_connection_string, update=1) lyr = ds.GetLayerByName('ogr_pg_67') - if lyr.GetSpatialRef() is not None: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.GetSpatialRef() is None feat = ogr.Feature(lyr.GetLayerDefn()) lyr.CreateFeature(feat) feat = None @@ -3659,40 +3064,32 @@ def ogr_pg_67(): ds = ogr.Open('PG:' + gdaltest.pg_connection_string, update=1) lyr = ds.GetLayerByName('ogr_pg_67') - if lyr.GetSpatialRef() is not None: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.GetSpatialRef() is None ds.ExecuteSQL("ALTER TABLE ogr_pg_67 DROP CONSTRAINT enforce_srid_wkb_geometry") ds.ExecuteSQL("UPDATE ogr_pg_67 SET wkb_geometry = ST_GeomFromEWKT('SRID=4326;POINT(0 1)')") ds = None ds = ogr.Open('PG:' + gdaltest.pg_connection_string, update=1) lyr = ds.GetLayerByName('ogr_pg_67') - if lyr.GetSpatialRef() is None: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.GetSpatialRef() is not None ds = None ds = ogr.Open('PG:' + gdaltest.pg_connection_string + ' tables=fake', update=1) lyr = ds.GetLayerByName('ogr_pg_67') - if lyr.GetSpatialRef() is None: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.GetSpatialRef() is not None ds = None - return 'success' - ############################################################################### # Test retrieving SRID from values even if we don't have select rights on geometry_columns (#5131) -def ogr_pg_68(): +def test_ogr_pg_68(): if gdaltest.pg_ds is None: - return 'skip' + pytest.skip() if not gdaltest.pg_has_postgis: - return 'skip' + pytest.skip() srs = osr.SpatialReference() srs.ImportFromEPSG(4326) @@ -3726,15 +3123,9 @@ def ogr_pg_68(): gdaltest.pg_ds.ExecuteSQL("GRANT SELECT ON geometry_columns TO %s" % current_user) - if got_srs is None: - gdaltest.post_reason('fail') - return 'fail' + assert got_srs is not None - if got_srs2 is None: - gdaltest.post_reason('fail') - return 'fail' - - return 'success' + assert got_srs2 is not None ############################################################################### # Test deferred loading of tables (#5450) @@ -3744,53 +3135,39 @@ def has_run_load_tables(ds): return int(ds.GetMetadataItem("bHasLoadTables", "_DEBUG_")) -def ogr_pg_69(): +def test_ogr_pg_69(): if gdaltest.pg_ds is None: - return 'skip' + pytest.skip() gdaltest.pg_ds = None gdaltest.pg_ds = ogr.Open('PG:' + gdaltest.pg_connection_string) - if has_run_load_tables(gdaltest.pg_ds): - gdaltest.post_reason('fail') - return 'fail' + assert not has_run_load_tables(gdaltest.pg_ds) gdaltest.pg_ds.GetLayerByName('tpoly') - if has_run_load_tables(gdaltest.pg_ds): - gdaltest.post_reason('fail') - return 'fail' + assert not has_run_load_tables(gdaltest.pg_ds) sql_lyr = gdaltest.pg_ds.ExecuteSQL('SELECT * FROM tpoly') - if has_run_load_tables(gdaltest.pg_ds): - gdaltest.post_reason('fail') - return 'fail' + assert not has_run_load_tables(gdaltest.pg_ds) feat = sql_lyr.GetNextFeature() - if has_run_load_tables(gdaltest.pg_ds): - gdaltest.post_reason('fail') - return 'fail' + assert not has_run_load_tables(gdaltest.pg_ds) del feat gdaltest.pg_ds.ReleaseResultSet(sql_lyr) gdaltest.pg_ds.GetLayer(0) - if not has_run_load_tables(gdaltest.pg_ds): - gdaltest.post_reason('fail') - return 'fail' + assert has_run_load_tables(gdaltest.pg_ds) # Test that we can find a layer with non lowercase gdaltest.pg_ds = None gdaltest.pg_ds = ogr.Open('PG:' + gdaltest.pg_connection_string) - if gdaltest.pg_ds.GetLayerByName('TPOLY') is None: - gdaltest.post_reason('fail') - return 'fail' - - return 'success' + assert gdaltest.pg_ds.GetLayerByName('TPOLY') is not None ############################################################################### # Test historical non-differed creation of tables (#5547) -def ogr_pg_70(): +def test_ogr_pg_70(): if gdaltest.pg_ds is None: - return 'skip' + pytest.skip() gdal.SetConfigOption('OGR_PG_DEFERRED_CREATION', 'NO') lyr = gdaltest.pg_ds.CreateLayer('ogr_pg_70') @@ -3798,18 +3175,14 @@ def ogr_pg_70(): ds = ogr.Open('PG:' + gdaltest.pg_connection_string) lyr2 = ds.GetLayerByName('ogr_pg_70') - if lyr2 is None: - gdaltest.post_reason('fail') - return 'fail' + assert lyr2 is not None ds = None lyr.CreateField(ogr.FieldDefn('foo', ogr.OFTString)) ds = ogr.Open('PG:' + gdaltest.pg_connection_string) lyr2 = ds.GetLayerByName('ogr_pg_70') - if lyr2.GetLayerDefn().GetFieldCount() != 1: - gdaltest.post_reason('fail') - return 'fail' + assert lyr2.GetLayerDefn().GetFieldCount() == 1 ds = None gfld_defn = ogr.GeomFieldDefn('geom', ogr.wkbPoint) @@ -3817,9 +3190,7 @@ def ogr_pg_70(): ds = ogr.Open('PG:' + gdaltest.pg_connection_string) lyr2 = ds.GetLayerByName('ogr_pg_70') - if lyr2.GetLayerDefn().GetGeomFieldCount() != 2: - gdaltest.post_reason('fail') - return 'fail' + assert lyr2.GetLayerDefn().GetGeomFieldCount() == 2 ds = None if gdaltest.pg_has_postgis and gdaltest.pg_ds.GetLayerByName('geography_columns') is not None: @@ -3833,29 +3204,24 @@ def ogr_pg_70(): ds = ogr.Open('PG:' + gdaltest.pg_connection_string) lyr2 = ds.GetLayerByName('ogr_pg_70') - if lyr2.GetLayerDefn().GetGeomFieldCount() != 1: - gdaltest.post_reason('fail') - return 'fail' + assert lyr2.GetLayerDefn().GetGeomFieldCount() == 1 geography_columns_lyr = ds.ExecuteSQL("SELECT * FROM geography_columns WHERE f_table_name = 'ogr_pg_70' AND f_geography_column = 'my_geog'") - if geography_columns_lyr.GetFeatureCount() != 1: - gdaltest.post_reason('fail') - return 'fail' + assert geography_columns_lyr.GetFeatureCount() == 1 ds.ReleaseResultSet(geography_columns_lyr) ds = None - return 'success' - + ############################################################################### # Test interoperability of WKT/WKB with PostGIS. -def ogr_pg_71(): +def test_ogr_pg_71(): if gdaltest.pg_ds is None: - return 'skip' + pytest.skip() if not gdaltest.pg_has_postgis: - return 'skip' + pytest.skip() curve_lyr = gdaltest.pg_ds.CreateLayer('test_curve') curve_lyr2 = gdaltest.pg_ds.CreateLayer('test_curve_3d', geom_type=ogr.wkbUnknown | ogr.wkb25DBit) @@ -3916,11 +3282,7 @@ def ogr_pg_71(): expected_wkt = wkt if not gdaltest.pg_has_postgis_2 and wkt.find('EMPTY') >= 0: expected_wkt = 'GEOMETRYCOLLECTION EMPTY' - if out_wkt != expected_wkt: - gdaltest.post_reason('fail') - print(expected_wkt) - print(out_wkt) - return 'fail' + assert out_wkt == expected_wkt # Test parsing PostGIS WKT if gdaltest.pg_has_postgis_2: @@ -3939,11 +3301,7 @@ def ogr_pg_71(): expected_wkt = wkt if not gdaltest.pg_has_postgis_2 and wkt.find('EMPTY') >= 0: expected_wkt = 'GEOMETRYCOLLECTION EMPTY' - if out_wkt != expected_wkt: - gdaltest.post_reason('fail') - print(expected_wkt) - print(out_wkt) - return 'fail' + assert out_wkt == expected_wkt g = ogr.CreateGeometryFromWkt(wkt) if g.GetCoordinateDimension() == 2: @@ -3956,10 +3314,7 @@ def ogr_pg_71(): f = ogr.Feature(active_lyr.GetLayerDefn()) f.SetGeometry(g) ret = active_lyr.CreateFeature(f) - if ret != 0: - gdaltest.post_reason('fail') - print(wkt) - return 'fail' + assert ret == 0, wkt fid = f.GetFID() # AsEWKT() in PostGIS 1.X does not like CIRCULARSTRING EMPTY @@ -3974,54 +3329,37 @@ def ogr_pg_71(): g = None f = None - if out_wkt != wkt: - gdaltest.post_reason('fail') - print(wkt) - print(out_wkt) - return 'fail' - - return 'success' + assert out_wkt == wkt + ############################################################################### # Test 64 bit FID -def ogr_pg_72(): +def test_ogr_pg_72(): if gdaltest.pg_ds is None: - return 'skip' + pytest.skip() # Regular layer with 32 bit IDs lyr = gdaltest.pg_ds.CreateLayer('ogr_pg_72') - if lyr.GetMetadataItem(ogr.OLMD_FID64) is not None: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.GetMetadataItem(ogr.OLMD_FID64) is None lyr.CreateField(ogr.FieldDefn('foo')) f = ogr.Feature(lyr.GetLayerDefn()) f.SetFID(123456789012345) f.SetField(0, 'bar') - if lyr.CreateFeature(f) != 0: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.CreateFeature(f) == 0 f = lyr.GetFeature(123456789012345) - if f is None: - gdaltest.post_reason('fail') - return 'fail' + assert f is not None lyr = gdaltest.pg_ds.CreateLayer('ogr_pg_72', options=['FID64=YES', 'OVERWRITE=YES']) - if lyr.GetMetadataItem(ogr.OLMD_FID64) is None: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.GetMetadataItem(ogr.OLMD_FID64) is not None lyr.CreateField(ogr.FieldDefn('foo')) f = ogr.Feature(lyr.GetLayerDefn()) f.SetFID(123456789012345) f.SetField(0, 'bar') - if lyr.CreateFeature(f) != 0: - gdaltest.post_reason('fail') - return 'fail' - if lyr.SetFeature(f) != 0: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.CreateFeature(f) == 0 + assert lyr.SetFeature(f) == 0 gdaltest.pg_ds = None # Test with binary protocol # gdaltest.pg_ds = ogr.Open( 'PGB:' + gdaltest.pg_connection_string, update = 1 ) @@ -4038,30 +3376,25 @@ def ogr_pg_72(): # Test with normal protocol gdaltest.pg_ds = ogr.Open('PG:' + gdaltest.pg_connection_string, update=1) lyr = gdaltest.pg_ds.GetLayerByName('ogr_pg_72') - if lyr.GetMetadataItem(ogr.OLMD_FID64) is None: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.GetMetadataItem(ogr.OLMD_FID64) is not None f = lyr.GetNextFeature() if f.GetFID() != 123456789012345: - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' + pytest.fail() lyr.ResetReading() # to close implicit transaction - return 'success' - ############################################################################### # Test not nullable fields -def ogr_pg_73(): +def test_ogr_pg_73(): if gdaltest.pg_ds is None: - return 'skip' + pytest.skip() if not gdaltest.pg_has_postgis: - return 'skip' + pytest.skip() gdal.SetConfigOption('PG_USE_COPY', 'NO') @@ -4088,9 +3421,7 @@ def ogr_pg_73(): gdal.PushErrorHandler() ret = lyr.CreateFeature(f) gdal.PopErrorHandler() - if ret == 0: - gdaltest.post_reason('fail') - return 'fail' + assert ret != 0 f = None # Error case: missing non-nullable field @@ -4099,9 +3430,7 @@ def ogr_pg_73(): gdal.PushErrorHandler() ret = lyr.CreateFeature(f) gdal.PopErrorHandler() - if ret == 0: - gdaltest.post_reason('fail') - return 'fail' + assert ret != 0 f = None gdal.SetConfigOption('PG_USE_COPY', gdaltest.pg_use_copy) @@ -4110,27 +3439,17 @@ def ogr_pg_73(): ds = ogr.Open('PG:' + gdaltest.pg_connection_string, update=1) lyr = ds.GetLayerByName('ogr_pg_73') - if lyr.GetLayerDefn().GetFieldDefn(lyr.GetLayerDefn().GetFieldIndex('field_not_nullable')).IsNullable() != 0: - gdaltest.post_reason('fail') - return 'fail' - if lyr.GetLayerDefn().GetFieldDefn(lyr.GetLayerDefn().GetFieldIndex('field_nullable')).IsNullable() != 1: - gdaltest.post_reason('fail') - return 'fail' - if lyr.GetLayerDefn().GetGeomFieldDefn(lyr.GetLayerDefn().GetGeomFieldIndex('geomfield_not_nullable')).IsNullable() != 0: - gdaltest.post_reason('fail') - return 'fail' - if lyr.GetLayerDefn().GetGeomFieldDefn(lyr.GetLayerDefn().GetGeomFieldIndex('geomfield_nullable')).IsNullable() != 1: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.GetLayerDefn().GetFieldDefn(lyr.GetLayerDefn().GetFieldIndex('field_not_nullable')).IsNullable() == 0 + assert lyr.GetLayerDefn().GetFieldDefn(lyr.GetLayerDefn().GetFieldIndex('field_nullable')).IsNullable() == 1 + assert lyr.GetLayerDefn().GetGeomFieldDefn(lyr.GetLayerDefn().GetGeomFieldIndex('geomfield_not_nullable')).IsNullable() == 0 + assert lyr.GetLayerDefn().GetGeomFieldDefn(lyr.GetLayerDefn().GetGeomFieldIndex('geomfield_nullable')).IsNullable() == 1 # Turn not null into nullable src_fd = lyr.GetLayerDefn().GetFieldDefn(lyr.GetLayerDefn().GetFieldIndex('field_not_nullable')) fd = ogr.FieldDefn('now_nullable', src_fd.GetType()) fd.SetNullable(1) lyr.AlterFieldDefn(lyr.GetLayerDefn().GetFieldIndex('field_not_nullable'), fd, ogr.ALTER_ALL_FLAG) - if lyr.GetLayerDefn().GetFieldDefn(lyr.GetLayerDefn().GetFieldIndex('now_nullable')).IsNullable() != 1: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.GetLayerDefn().GetFieldDefn(lyr.GetLayerDefn().GetFieldIndex('now_nullable')).IsNullable() == 1 # Turn nullable into not null, but remove NULL values first ds.ExecuteSQL("UPDATE ogr_pg_73 SET field_nullable = '' WHERE field_nullable IS NULL") @@ -4139,38 +3458,26 @@ def ogr_pg_73(): fd.SetName('now_not_nullable') fd.SetNullable(0) lyr.AlterFieldDefn(lyr.GetLayerDefn().GetFieldIndex('field_nullable'), fd, ogr.ALTER_ALL_FLAG) - if lyr.GetLayerDefn().GetFieldDefn(lyr.GetLayerDefn().GetFieldIndex('now_not_nullable')).IsNullable() != 0: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.GetLayerDefn().GetFieldDefn(lyr.GetLayerDefn().GetFieldIndex('now_not_nullable')).IsNullable() == 0 sql_lyr = ds.ExecuteSQL('SELECT * FROM ogr_pg_73') - if sql_lyr.GetLayerDefn().GetFieldDefn(sql_lyr.GetLayerDefn().GetFieldIndex('now_not_nullable')).IsNullable() != 0: - gdaltest.post_reason('fail') - return 'fail' - if sql_lyr.GetLayerDefn().GetFieldDefn(sql_lyr.GetLayerDefn().GetFieldIndex('now_nullable')).IsNullable() != 1: - gdaltest.post_reason('fail') - return 'fail' - if sql_lyr.GetLayerDefn().GetGeomFieldDefn(sql_lyr.GetLayerDefn().GetGeomFieldIndex('geomfield_not_nullable')).IsNullable() != 0: - gdaltest.post_reason('fail') - return 'fail' - if sql_lyr.GetLayerDefn().GetGeomFieldDefn(sql_lyr.GetLayerDefn().GetGeomFieldIndex('geomfield_nullable')).IsNullable() != 1: - gdaltest.post_reason('fail') - return 'fail' + assert sql_lyr.GetLayerDefn().GetFieldDefn(sql_lyr.GetLayerDefn().GetFieldIndex('now_not_nullable')).IsNullable() == 0 + assert sql_lyr.GetLayerDefn().GetFieldDefn(sql_lyr.GetLayerDefn().GetFieldIndex('now_nullable')).IsNullable() == 1 + assert sql_lyr.GetLayerDefn().GetGeomFieldDefn(sql_lyr.GetLayerDefn().GetGeomFieldIndex('geomfield_not_nullable')).IsNullable() == 0 + assert sql_lyr.GetLayerDefn().GetGeomFieldDefn(sql_lyr.GetLayerDefn().GetGeomFieldIndex('geomfield_nullable')).IsNullable() == 1 ds.ReleaseResultSet(sql_lyr) - return 'success' - ############################################################################### # Test default values -def ogr_pg_74(): +def test_ogr_pg_74(): if gdaltest.pg_ds is None: - return 'skip' + pytest.skip() if not gdaltest.pg_has_postgis: - return 'skip' + pytest.skip() lyr = gdaltest.pg_ds.CreateLayer('ogr_pg_74', geom_type=ogr.wkbNone) @@ -4244,41 +3551,20 @@ def ogr_pg_74(): ds = ogr.Open('PG:' + gdaltest.pg_connection_string, update=1) ds.ExecuteSQL('set timezone to "UTC"') lyr = ds.GetLayerByName('ogr_pg_74') - if lyr.GetLayerDefn().GetFieldDefn(lyr.GetLayerDefn().GetFieldIndex('field_string')).GetDefault() != "'a''b'": - gdaltest.post_reason('fail') - return 'fail' - if lyr.GetLayerDefn().GetFieldDefn(lyr.GetLayerDefn().GetFieldIndex('field_int')).GetDefault() != '123': - gdaltest.post_reason('fail') - return 'fail' - if lyr.GetLayerDefn().GetFieldDefn(lyr.GetLayerDefn().GetFieldIndex('field_real')).GetDefault() != '1.23': - gdaltest.post_reason('fail') - return 'fail' - if lyr.GetLayerDefn().GetFieldDefn(lyr.GetLayerDefn().GetFieldIndex('field_nodefault')).GetDefault() is not None: - gdaltest.post_reason('fail') - return 'fail' - if lyr.GetLayerDefn().GetFieldDefn(lyr.GetLayerDefn().GetFieldIndex('field_datetime')).GetDefault() != 'CURRENT_TIMESTAMP': - gdaltest.post_reason('fail') - return 'fail' - if lyr.GetLayerDefn().GetFieldDefn(lyr.GetLayerDefn().GetFieldIndex('field_datetime2')).GetDefault() != "'2015/06/30 12:34:56'": - gdaltest.post_reason('fail') - print(lyr.GetLayerDefn().GetFieldDefn(lyr.GetLayerDefn().GetFieldIndex('field_datetime2')).GetDefault()) - return 'fail' - if lyr.GetLayerDefn().GetFieldDefn(lyr.GetLayerDefn().GetFieldIndex('field_datetime3')).GetDefault() != "'2015/06/30 12:34:56.123'": - gdaltest.post_reason('fail') - print(lyr.GetLayerDefn().GetFieldDefn(lyr.GetLayerDefn().GetFieldIndex('field_datetime3')).GetDefault()) - return 'fail' - if lyr.GetLayerDefn().GetFieldDefn(lyr.GetLayerDefn().GetFieldIndex('field_date')).GetDefault() != "CURRENT_DATE": - gdaltest.post_reason('fail') - return 'fail' - if lyr.GetLayerDefn().GetFieldDefn(lyr.GetLayerDefn().GetFieldIndex('field_time')).GetDefault() != "CURRENT_TIME": - gdaltest.post_reason('fail') - return 'fail' + assert lyr.GetLayerDefn().GetFieldDefn(lyr.GetLayerDefn().GetFieldIndex('field_string')).GetDefault() == "'a''b'" + assert lyr.GetLayerDefn().GetFieldDefn(lyr.GetLayerDefn().GetFieldIndex('field_int')).GetDefault() == '123' + assert lyr.GetLayerDefn().GetFieldDefn(lyr.GetLayerDefn().GetFieldIndex('field_real')).GetDefault() == '1.23' + assert lyr.GetLayerDefn().GetFieldDefn(lyr.GetLayerDefn().GetFieldIndex('field_nodefault')).GetDefault() is None + assert lyr.GetLayerDefn().GetFieldDefn(lyr.GetLayerDefn().GetFieldIndex('field_datetime')).GetDefault() == 'CURRENT_TIMESTAMP' + assert lyr.GetLayerDefn().GetFieldDefn(lyr.GetLayerDefn().GetFieldIndex('field_datetime2')).GetDefault() == "'2015/06/30 12:34:56'" + assert lyr.GetLayerDefn().GetFieldDefn(lyr.GetLayerDefn().GetFieldIndex('field_datetime3')).GetDefault() == "'2015/06/30 12:34:56.123'" + assert lyr.GetLayerDefn().GetFieldDefn(lyr.GetLayerDefn().GetFieldIndex('field_date')).GetDefault() == "CURRENT_DATE" + assert lyr.GetLayerDefn().GetFieldDefn(lyr.GetLayerDefn().GetFieldIndex('field_time')).GetDefault() == "CURRENT_TIME" f = lyr.GetNextFeature() if not f.IsFieldNull('field_string'): - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' + pytest.fail() f = lyr.GetNextFeature() if f.GetField('field_string') != 'a\'b' or f.GetField('field_int') != 123 or \ @@ -4287,15 +3573,13 @@ def ogr_pg_74(): f.GetField('field_datetime2') != '2015/06/30 12:34:56+00' or \ f.GetField('field_datetime3') != '2015/06/30 12:34:56.123+00' or \ not f.IsFieldSet('field_date') or not f.IsFieldSet('field_time'): - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' + pytest.fail() f = lyr.GetNextFeature() if f.GetField('field_string') != 'b': - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' + pytest.fail() lyr.ResetReading() # to close implicit transaction @@ -4304,45 +3588,33 @@ def ogr_pg_74(): fd = ogr.FieldDefn('field_string', src_fd.GetType()) fd.SetDefault("'c'") lyr.AlterFieldDefn(lyr.GetLayerDefn().GetFieldIndex('field_string'), fd, ogr.ALTER_DEFAULT_FLAG) - if lyr.GetLayerDefn().GetFieldDefn(lyr.GetLayerDefn().GetFieldIndex('field_string')).GetDefault() != "'c'": - gdaltest.post_reason('fail') - print(lyr.GetLayerDefn().GetFieldDefn(lyr.GetLayerDefn().GetFieldIndex('field_string')).GetDefault()) - return 'fail' + assert lyr.GetLayerDefn().GetFieldDefn(lyr.GetLayerDefn().GetFieldIndex('field_string')).GetDefault() == "'c'" # Drop DEFAULT value src_fd = lyr.GetLayerDefn().GetFieldDefn(lyr.GetLayerDefn().GetFieldIndex('field_int')) fd = ogr.FieldDefn('field_int', src_fd.GetType()) fd.SetDefault(None) lyr.AlterFieldDefn(lyr.GetLayerDefn().GetFieldIndex('field_int'), fd, ogr.ALTER_DEFAULT_FLAG) - if lyr.GetLayerDefn().GetFieldDefn(lyr.GetLayerDefn().GetFieldIndex('field_int')).GetDefault() is not None: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.GetLayerDefn().GetFieldDefn(lyr.GetLayerDefn().GetFieldIndex('field_int')).GetDefault() is None ds = None ds = ogr.Open('PG:' + gdaltest.pg_connection_string, update=1) ds.ExecuteSQL('set timezone to "UTC"') lyr = ds.GetLayerByName('ogr_pg_74') - if lyr.GetLayerDefn().GetFieldDefn(lyr.GetLayerDefn().GetFieldIndex('field_string')).GetDefault() != "'c'": - gdaltest.post_reason('fail') - print(lyr.GetLayerDefn().GetFieldDefn(lyr.GetLayerDefn().GetFieldIndex('field_string')).GetDefault()) - return 'fail' - if lyr.GetLayerDefn().GetFieldDefn(lyr.GetLayerDefn().GetFieldIndex('field_int')).GetDefault() is not None: - gdaltest.post_reason('fail') - return 'fail' - - return 'success' + assert lyr.GetLayerDefn().GetFieldDefn(lyr.GetLayerDefn().GetFieldIndex('field_string')).GetDefault() == "'c'" + assert lyr.GetLayerDefn().GetFieldDefn(lyr.GetLayerDefn().GetFieldIndex('field_int')).GetDefault() is None ############################################################################### # Test creating a field with the fid name -def ogr_pg_75(): +def test_ogr_pg_75(): if gdaltest.pg_ds is None: - return 'skip' + pytest.skip() if not gdaltest.pg_has_postgis: - return 'skip' + pytest.skip() lyr = gdaltest.pg_ds.CreateLayer('ogr_pg_75', geom_type=ogr.wkbNone, options=['FID=myfid']) @@ -4350,14 +3622,10 @@ def ogr_pg_75(): gdal.PushErrorHandler() ret = lyr.CreateField(ogr.FieldDefn('myfid', ogr.OFTString)) gdal.PopErrorHandler() - if ret == 0: - gdaltest.post_reason('fail') - return 'fail' + assert ret != 0 ret = lyr.CreateField(ogr.FieldDefn('myfid', ogr.OFTInteger)) - if ret != 0: - gdaltest.post_reason('fail') - return 'fail' + assert ret == 0 lyr.CreateField(ogr.FieldDefn('str2', ogr.OFTString)) feat = ogr.Feature(lyr.GetLayerDefn()) @@ -4365,33 +3633,23 @@ def ogr_pg_75(): feat.SetField('myfid', 10) feat.SetField('str2', 'second string') ret = lyr.CreateFeature(feat) - if ret != 0: - gdaltest.post_reason('fail') - return 'fail' - if feat.GetFID() != 10: - gdaltest.post_reason('fail') - return 'fail' + assert ret == 0 + assert feat.GetFID() == 10 feat = ogr.Feature(lyr.GetLayerDefn()) feat.SetField('str2', 'second string') ret = lyr.CreateFeature(feat) - if ret != 0: - gdaltest.post_reason('fail') - return 'fail' + assert ret == 0 if feat.GetFID() < 0: - gdaltest.post_reason('fail') feat.DumpReadable() - return 'fail' + pytest.fail() if feat.GetField('myfid') != feat.GetFID(): - gdaltest.post_reason('fail') feat.DumpReadable() - return 'fail' + pytest.fail() feat.SetField('str', 'foo') ret = lyr.SetFeature(feat) - if ret != 0: - gdaltest.post_reason('fail') - return 'fail' + assert ret == 0 feat = ogr.Feature(lyr.GetLayerDefn()) feat.SetFID(1) @@ -4399,53 +3657,39 @@ def ogr_pg_75(): gdal.PushErrorHandler() ret = lyr.CreateFeature(feat) gdal.PopErrorHandler() - if ret == 0: - gdaltest.post_reason('fail') - return 'fail' + assert ret != 0 gdal.PushErrorHandler() ret = lyr.SetFeature(feat) gdal.PopErrorHandler() - if ret == 0: - gdaltest.post_reason('fail') - return 'fail' + assert ret != 0 feat.UnsetField('myfid') gdal.PushErrorHandler() ret = lyr.SetFeature(feat) gdal.PopErrorHandler() - if ret == 0: - gdaltest.post_reason('fail') - return 'fail' + assert ret != 0 feat = ogr.Feature(lyr.GetLayerDefn()) feat.SetField('str', 'first string') feat.SetField('myfid', 12) feat.SetField('str2', 'second string') ret = lyr.CreateFeature(feat) - if ret != 0: - gdaltest.post_reason('fail') - return 'fail' - if feat.GetFID() != 12: - gdaltest.post_reason('fail') - return 'fail' + assert ret == 0 + assert feat.GetFID() == 12 lyr.ResetReading() f = lyr.GetNextFeature() if f.GetFID() != 10 or f.GetField('str') != 'first string' or f.GetField('str2') != 'second string' or f.GetField('myfid') != 10: - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' + pytest.fail() f = lyr.GetFeature(f.GetFID()) if f.GetFID() != 10 or f.GetField('str') != 'first string' or f.GetField('str2') != 'second string' or f.GetField('myfid') != 10: - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' + pytest.fail() f = None lyr.ResetReading() # to close implicit transaction - return 'success' - ############################################################################### # Test transactions RFC 54 @@ -4457,20 +3701,15 @@ def ogr_pg_76_get_transaction_state(ds): int(ds.GetMetadataItem("bUserTransactionActive", "_DEBUG_"))) -def ogr_pg_76(): +def test_ogr_pg_76(): if gdaltest.pg_ds is None: - return 'skip' + pytest.skip() - if gdaltest.pg_ds.TestCapability(ogr.ODsCTransactions) != 1: - gdaltest.post_reason('fail') - return 'fail' + assert gdaltest.pg_ds.TestCapability(ogr.ODsCTransactions) == 1 level = int(gdaltest.pg_ds.GetMetadataItem("nSoftTransactionLevel", "_DEBUG_")) - if level != 0: - gdaltest.post_reason('fail') - print(level) - return 'fail' + assert level == 0 if gdaltest.pg_has_postgis_2: gdaltest.pg_ds.StartTransaction() @@ -4481,9 +3720,7 @@ def ogr_pg_76(): f = sql_lyr.GetNextFeature() res = f.GetField(0) gdaltest.pg_ds.ReleaseResultSet(sql_lyr) - if res != 1: - gdaltest.post_reason('fail') - return 'fail' + assert res == 1 gdaltest.pg_ds.RollbackTransaction() @@ -4492,10 +3729,7 @@ def ogr_pg_76(): f = sql_lyr.GetNextFeature() res = f.GetField(0) gdaltest.pg_ds.ReleaseResultSet(sql_lyr) - if res != 0: - gdaltest.post_reason('fail') - print(res) - return 'fail' + assert res == 0 gdal.SetConfigOption('OGR_PG_CURSOR_PAGE', '1') lyr1 = gdaltest.pg_ds.CreateLayer('ogr_pg_76_lyr1', geom_type=ogr.wkbNone, options=['OVERWRITE=YES']) @@ -4510,23 +3744,12 @@ def ogr_pg_76(): lyr2.CreateFeature(ogr.Feature(lyr2.GetLayerDefn())) level = int(gdaltest.pg_ds.GetMetadataItem("nSoftTransactionLevel", "_DEBUG_")) - if level != 0: - gdaltest.post_reason('fail') - print(level) - return 'fail' + assert level == 0 ret = ogr_pg_76_scenario1(lyr1, lyr2) - if ret != 'success': - return ret ret = ogr_pg_76_scenario2(lyr1, lyr2) - if ret != 'success': - return ret ret = ogr_pg_76_scenario3(lyr1, lyr2) - if ret != 'success': - return ret ret = ogr_pg_76_scenario4(lyr1, lyr2) - if ret != 'success': - return ret return ret @@ -4536,406 +3759,229 @@ def ogr_pg_76(): def ogr_pg_76_scenario1(lyr1, lyr2): (_, level, savepoint, usertransac) = ogr_pg_76_get_transaction_state(gdaltest.pg_ds) - if (level, savepoint, usertransac) != (0, 0, 0): - gdaltest.post_reason('fail') - print(level, savepoint, usertransac) - return 'fail' + assert (level, savepoint, usertransac) == (0, 0, 0) f = lyr1.GetNextFeature() - if f is None or f.GetFID() != 1: - gdaltest.post_reason('fail') - return 'fail' + assert f is not None and f.GetFID() == 1 (lastcmd, level, savepoint, usertransac) = ogr_pg_76_get_transaction_state(gdaltest.pg_ds) - if (lastcmd, level, savepoint, usertransac) != ('BEGIN', 1, 0, 0): - gdaltest.post_reason('fail') - print(lastcmd, level, savepoint, usertransac) - return 'fail' + assert (lastcmd, level, savepoint, usertransac) == ('BEGIN', 1, 0, 0) lyr1.SetAttributeFilter("foo is NULL") (lastcmd, level, savepoint, usertransac) = ogr_pg_76_get_transaction_state(gdaltest.pg_ds) - if (lastcmd, level, savepoint, usertransac) != ('COMMIT', 0, 0, 0): - gdaltest.post_reason('fail') - print(lastcmd, level, savepoint, usertransac) - return 'fail' + assert (lastcmd, level, savepoint, usertransac) == ('COMMIT', 0, 0, 0) f = lyr1.GetNextFeature() - if f is None or f.GetFID() != 1: - gdaltest.post_reason('fail') - return 'fail' + assert f is not None and f.GetFID() == 1 (lastcmd, level, savepoint, usertransac) = ogr_pg_76_get_transaction_state(gdaltest.pg_ds) - if (lastcmd, level, savepoint, usertransac) != ('BEGIN', 1, 0, 0): - gdaltest.post_reason('fail') - print(lastcmd, level, savepoint, usertransac) - return 'fail' + assert (lastcmd, level, savepoint, usertransac) == ('BEGIN', 1, 0, 0) f = lyr2.GetNextFeature() - if f is None or f.GetFID() != 1: - gdaltest.post_reason('fail') - return 'fail' + assert f is not None and f.GetFID() == 1 (lastcmd, level, savepoint, usertransac) = ogr_pg_76_get_transaction_state(gdaltest.pg_ds) - if (lastcmd, level, savepoint, usertransac) != ('', 2, 0, 0): - gdaltest.post_reason('fail') - print(lastcmd, level, savepoint, usertransac) - return 'fail' + assert (lastcmd, level, savepoint, usertransac) == ('', 2, 0, 0) f = lyr1.GetNextFeature() - if f is None or f.GetFID() != 2: - gdaltest.post_reason('fail') - return 'fail' + assert f is not None and f.GetFID() == 2 # Check that GetFeature() doesn't reset the cursor f = lyr1.GetFeature(f.GetFID()) - if f is None or f.GetFID() != 2: - gdaltest.post_reason('fail') - return 'fail' + assert f is not None and f.GetFID() == 2 f = lyr1.GetNextFeature() - if f is None or f.GetFID() != 3: - gdaltest.post_reason('fail') - return 'fail' + assert f is not None and f.GetFID() == 3 f = lyr2.GetNextFeature() - if f is None or f.GetFID() != 2: - gdaltest.post_reason('fail') - return 'fail' + assert f is not None and f.GetFID() == 2 (lastcmd, level, savepoint, usertransac) = ogr_pg_76_get_transaction_state(gdaltest.pg_ds) - if (lastcmd, level, savepoint, usertransac) != ('', 2, 0, 0): - gdaltest.post_reason('fail') - print(lastcmd, level, savepoint, usertransac) - return 'fail' + assert (lastcmd, level, savepoint, usertransac) == ('', 2, 0, 0) lyr1.CreateFeature(ogr.Feature(lyr1.GetLayerDefn())) lyr1.ResetReading() (lastcmd, level, savepoint, usertransac) = ogr_pg_76_get_transaction_state(gdaltest.pg_ds) - if (lastcmd, level, savepoint, usertransac) != ('', 1, 0, 0): - gdaltest.post_reason('fail') - print(lastcmd, level, savepoint, usertransac) - return 'fail' + assert (lastcmd, level, savepoint, usertransac) == ('', 1, 0, 0) lyr2.ResetReading() (lastcmd, level, savepoint, usertransac) = ogr_pg_76_get_transaction_state(gdaltest.pg_ds) - if (lastcmd, level, savepoint, usertransac) != ('COMMIT', 0, 0, 0): - gdaltest.post_reason('fail') - print(lastcmd, level, savepoint, usertransac) - return 'fail' - if lyr1.GetFeatureCount() != 4: - gdaltest.post_reason('fail') - return 'fail' - - return 'success' + assert (lastcmd, level, savepoint, usertransac) == ('COMMIT', 0, 0, 0) + assert lyr1.GetFeatureCount() == 4 # Scenario 2 : a CreateFeature done in the middle of GetNextFeature(), themselves between a user transaction def ogr_pg_76_scenario2(lyr1, lyr2): - if gdaltest.pg_ds.StartTransaction() != 0: - gdaltest.post_reason('fail') - return 'fail' + assert gdaltest.pg_ds.StartTransaction() == 0 (lastcmd, level, savepoint, usertransac) = ogr_pg_76_get_transaction_state(gdaltest.pg_ds) - if (lastcmd, level, savepoint, usertransac) != ('BEGIN', 1, 0, 1): - gdaltest.post_reason('fail') - print(lastcmd, level, savepoint, usertransac) - return 'fail' + assert (lastcmd, level, savepoint, usertransac) == ('BEGIN', 1, 0, 1) # Try to re-enter a transaction gdal.ErrorReset() gdal.PushErrorHandler() ret = gdaltest.pg_ds.StartTransaction() gdal.PopErrorHandler() - if gdal.GetLastErrorMsg() == '' or ret == 0: - gdaltest.post_reason('fail') - return 'fail' + assert not (gdal.GetLastErrorMsg() == '' or ret == 0) (lastcmd, level, savepoint, usertransac) = ogr_pg_76_get_transaction_state(gdaltest.pg_ds) - if (lastcmd, level, savepoint, usertransac) != ('', 1, 0, 1): - gdaltest.post_reason('fail') - print(lastcmd, level, savepoint, usertransac) - return 'fail' + assert (lastcmd, level, savepoint, usertransac) == ('', 1, 0, 1) f = lyr1.GetNextFeature() - if f is None or f.GetFID() != 1: - gdaltest.post_reason('fail') - return 'fail' + assert f is not None and f.GetFID() == 1 (lastcmd, level, savepoint, usertransac) = ogr_pg_76_get_transaction_state(gdaltest.pg_ds) - if (lastcmd, level, savepoint, usertransac) != ('', 2, 0, 1): - gdaltest.post_reason('fail') - print(lastcmd, level, savepoint, usertransac) - return 'fail' + assert (lastcmd, level, savepoint, usertransac) == ('', 2, 0, 1) f = lyr2.GetNextFeature() - if f is None or f.GetFID() != 1: - gdaltest.post_reason('fail') - return 'fail' + assert f is not None and f.GetFID() == 1 (lastcmd, level, savepoint, usertransac) = ogr_pg_76_get_transaction_state(gdaltest.pg_ds) - if (lastcmd, level, savepoint, usertransac) != ('', 3, 0, 1): - gdaltest.post_reason('fail') - print(lastcmd, level, savepoint, usertransac) - return 'fail' + assert (lastcmd, level, savepoint, usertransac) == ('', 3, 0, 1) f = lyr1.GetNextFeature() - if f is None or f.GetFID() != 2: - gdaltest.post_reason('fail') - return 'fail' + assert f is not None and f.GetFID() == 2 f = lyr1.GetNextFeature() - if f is None or f.GetFID() != 3: - gdaltest.post_reason('fail') - return 'fail' + assert f is not None and f.GetFID() == 3 f = lyr2.GetNextFeature() - if f is None or f.GetFID() != 2: - gdaltest.post_reason('fail') - return 'fail' + assert f is not None and f.GetFID() == 2 (lastcmd, level, savepoint, usertransac) = ogr_pg_76_get_transaction_state(gdaltest.pg_ds) - if (lastcmd, level, savepoint, usertransac) != ('', 3, 0, 1): - gdaltest.post_reason('fail') - print(lastcmd, level, savepoint, usertransac) - return 'fail' + assert (lastcmd, level, savepoint, usertransac) == ('', 3, 0, 1) lyr1.CreateFeature(ogr.Feature(lyr1.GetLayerDefn())) lyr1.ResetReading() (lastcmd, level, savepoint, usertransac) = ogr_pg_76_get_transaction_state(gdaltest.pg_ds) - if (lastcmd, level, savepoint, usertransac) != ('', 2, 0, 1): - gdaltest.post_reason('fail') - print(lastcmd, level, savepoint, usertransac) - return 'fail' + assert (lastcmd, level, savepoint, usertransac) == ('', 2, 0, 1) lyr2.ResetReading() (lastcmd, level, savepoint, usertransac) = ogr_pg_76_get_transaction_state(gdaltest.pg_ds) - if (lastcmd, level, savepoint, usertransac) != ('', 1, 0, 1): - gdaltest.post_reason('fail') - print(lastcmd, level, savepoint, usertransac) - return 'fail' - - if gdaltest.pg_ds.CommitTransaction() != 0: - gdaltest.post_reason('fail') - return 'fail' + assert (lastcmd, level, savepoint, usertransac) == ('', 1, 0, 1) + + assert gdaltest.pg_ds.CommitTransaction() == 0 (lastcmd, level, savepoint, usertransac) = ogr_pg_76_get_transaction_state(gdaltest.pg_ds) - if (lastcmd, level, savepoint, usertransac) != ('COMMIT', 0, 0, 0): - gdaltest.post_reason('fail') - print(lastcmd, level, savepoint, usertransac) - return 'fail' - - if gdaltest.pg_ds.StartTransaction() != 0: - gdaltest.post_reason('fail') - return 'fail' - - if gdaltest.pg_ds.RollbackTransaction() != 0: - gdaltest.post_reason('fail') - return 'fail' + assert (lastcmd, level, savepoint, usertransac) == ('COMMIT', 0, 0, 0) + + assert gdaltest.pg_ds.StartTransaction() == 0 + + assert gdaltest.pg_ds.RollbackTransaction() == 0 (lastcmd, level, savepoint, usertransac) = ogr_pg_76_get_transaction_state(gdaltest.pg_ds) - if (lastcmd, level, savepoint, usertransac) != ('ROLLBACK', 0, 0, 0): - gdaltest.post_reason('fail') - print(lastcmd, level, savepoint, usertransac) - return 'fail' + assert (lastcmd, level, savepoint, usertransac) == ('ROLLBACK', 0, 0, 0) # Try to re-commit a transaction gdal.ErrorReset() gdal.PushErrorHandler() ret = gdaltest.pg_ds.CommitTransaction() gdal.PopErrorHandler() - if gdal.GetLastErrorMsg() == '' or ret == 0: - gdaltest.post_reason('fail') - return 'fail' + assert not (gdal.GetLastErrorMsg() == '' or ret == 0) (lastcmd, level, savepoint, usertransac) = ogr_pg_76_get_transaction_state(gdaltest.pg_ds) - if (lastcmd, level, savepoint, usertransac) != ('', 0, 0, 0): - gdaltest.post_reason('fail') - print(lastcmd, level, savepoint, usertransac) - return 'fail' + assert (lastcmd, level, savepoint, usertransac) == ('', 0, 0, 0) # Try to rollback a non-transaction gdal.ErrorReset() gdal.PushErrorHandler() ret = gdaltest.pg_ds.RollbackTransaction() gdal.PopErrorHandler() - if gdal.GetLastErrorMsg() == '' or ret == 0: - gdaltest.post_reason('fail') - return 'fail' + assert not (gdal.GetLastErrorMsg() == '' or ret == 0) (lastcmd, level, savepoint, usertransac) = ogr_pg_76_get_transaction_state(gdaltest.pg_ds) - if (lastcmd, level, savepoint, usertransac) != ('', 0, 0, 0): - gdaltest.post_reason('fail') - print(lastcmd, level, savepoint, usertransac) - return 'fail' - - return 'success' + assert (lastcmd, level, savepoint, usertransac) == ('', 0, 0, 0) # Scenario 3 : StartTransaction(), GetNextFeature(), CommitTransaction(), GetNextFeature() def ogr_pg_76_scenario3(lyr1, lyr2): - if gdaltest.pg_ds.StartTransaction() != 0: - gdaltest.post_reason('fail') - return 'fail' + assert gdaltest.pg_ds.StartTransaction() == 0 (lastcmd, level, savepoint, usertransac) = ogr_pg_76_get_transaction_state(gdaltest.pg_ds) - if (lastcmd, level, savepoint, usertransac) != ('BEGIN', 1, 0, 1): - gdaltest.post_reason('fail') - print(lastcmd, level, savepoint, usertransac) - return 'fail' + assert (lastcmd, level, savepoint, usertransac) == ('BEGIN', 1, 0, 1) f = lyr1.GetNextFeature() - if f is None or f.GetFID() != 1: - gdaltest.post_reason('fail') - return 'fail' + assert f is not None and f.GetFID() == 1 (lastcmd, level, savepoint, usertransac) = ogr_pg_76_get_transaction_state(gdaltest.pg_ds) - if (lastcmd, level, savepoint, usertransac) != ('', 2, 0, 1): - gdaltest.post_reason('fail') - print(lastcmd, level, savepoint, usertransac) - return 'fail' - - if gdaltest.pg_ds.CommitTransaction() != 0: - gdaltest.post_reason('fail') - return 'fail' + assert (lastcmd, level, savepoint, usertransac) == ('', 2, 0, 1) + + assert gdaltest.pg_ds.CommitTransaction() == 0 (lastcmd, level, savepoint, usertransac) = ogr_pg_76_get_transaction_state(gdaltest.pg_ds) - if (lastcmd, level, savepoint, usertransac) != ('COMMIT', 0, 0, 0): - gdaltest.post_reason('fail') - print(lastcmd, level, savepoint, usertransac) - return 'fail' + assert (lastcmd, level, savepoint, usertransac) == ('COMMIT', 0, 0, 0) gdal.ErrorReset() gdal.PushErrorHandler() f = lyr1.GetNextFeature() gdal.PopErrorHandler() - if gdal.GetLastErrorMsg() == '' or f is not None: - gdaltest.post_reason('fail') - return 'fail' + assert gdal.GetLastErrorMsg() != '' and f is None # Must re-issue an explicit ResetReading() lyr1.ResetReading() f = lyr1.GetNextFeature() - if f is None or f.GetFID() != 1: - gdaltest.post_reason('fail') - return 'fail' + assert f is not None and f.GetFID() == 1 (lastcmd, level, savepoint, usertransac) = ogr_pg_76_get_transaction_state(gdaltest.pg_ds) - if (lastcmd, level, savepoint, usertransac) != ('BEGIN', 1, 0, 0): - gdaltest.post_reason('fail') - print(lastcmd, level, savepoint, usertransac) - return 'fail' + assert (lastcmd, level, savepoint, usertransac) == ('BEGIN', 1, 0, 0) lyr1.ResetReading() (lastcmd, level, savepoint, usertransac) = ogr_pg_76_get_transaction_state(gdaltest.pg_ds) - if (lastcmd, level, savepoint, usertransac) != ('COMMIT', 0, 0, 0): - gdaltest.post_reason('fail') - print(lastcmd, level, savepoint, usertransac) - return 'fail' + assert (lastcmd, level, savepoint, usertransac) == ('COMMIT', 0, 0, 0) lyr2.ResetReading() - return 'success' - # Scenario 4 : GetNextFeature(), StartTransaction(), CreateFeature(), CommitTransaction(), GetNextFeature(), ResetReading() def ogr_pg_76_scenario4(lyr1, lyr2): (lastcmd, level, savepoint, usertransac) = ogr_pg_76_get_transaction_state(gdaltest.pg_ds) - if (lastcmd, level, savepoint, usertransac) != ('', 0, 0, 0): - gdaltest.post_reason('fail') - print(lastcmd, level, savepoint, usertransac) - return 'fail' + assert (lastcmd, level, savepoint, usertransac) == ('', 0, 0, 0) f = lyr1.GetNextFeature() - if f is None or f.GetFID() != 1: - gdaltest.post_reason('fail') - return 'fail' + assert f is not None and f.GetFID() == 1 (lastcmd, level, savepoint, usertransac) = ogr_pg_76_get_transaction_state(gdaltest.pg_ds) - if (lastcmd, level, savepoint, usertransac) != ('BEGIN', 1, 0, 0): - gdaltest.post_reason('fail') - print(lastcmd, level, savepoint, usertransac) - return 'fail' - - if gdaltest.pg_ds.StartTransaction() != 0: - gdaltest.post_reason('fail') - return 'fail' + assert (lastcmd, level, savepoint, usertransac) == ('BEGIN', 1, 0, 0) + + assert gdaltest.pg_ds.StartTransaction() == 0 (lastcmd, level, savepoint, usertransac) = ogr_pg_76_get_transaction_state(gdaltest.pg_ds) - if (lastcmd, level, savepoint, usertransac) != ('SAVEPOINT ogr_savepoint', 2, 1, 1): - gdaltest.post_reason('fail') - print(lastcmd, level, savepoint, usertransac) - return 'fail' + assert (lastcmd, level, savepoint, usertransac) == ('SAVEPOINT ogr_savepoint', 2, 1, 1) lyr1.CreateFeature(ogr.Feature(lyr1.GetLayerDefn())) f = lyr1.GetNextFeature() - if f is None or f.GetFID() != 2: - gdaltest.post_reason('fail') - return 'fail' + assert f is not None and f.GetFID() == 2 f = lyr2.GetNextFeature() - if f is None or f.GetFID() != 1: - gdaltest.post_reason('fail') - return 'fail' + assert f is not None and f.GetFID() == 1 (lastcmd, level, savepoint, usertransac) = ogr_pg_76_get_transaction_state(gdaltest.pg_ds) - if (lastcmd, level, savepoint, usertransac) != ('', 3, 1, 1): - gdaltest.post_reason('fail') - print(lastcmd, level, savepoint, usertransac) - return 'fail' + assert (lastcmd, level, savepoint, usertransac) == ('', 3, 1, 1) # Check that it doesn't commit the transaction lyr1.SetAttributeFilter("foo is NULL") (lastcmd, level, savepoint, usertransac) = ogr_pg_76_get_transaction_state(gdaltest.pg_ds) - if (lastcmd, level, savepoint, usertransac) != ('', 2, 1, 1): - gdaltest.post_reason('fail') - print(lastcmd, level, savepoint, usertransac) - return 'fail' + assert (lastcmd, level, savepoint, usertransac) == ('', 2, 1, 1) f = lyr1.GetNextFeature() - if f is None or f.GetFID() != 1: - gdaltest.post_reason('fail') - return 'fail' + assert f is not None and f.GetFID() == 1 (lastcmd, level, savepoint, usertransac) = ogr_pg_76_get_transaction_state(gdaltest.pg_ds) - if (lastcmd, level, savepoint, usertransac) != ('', 3, 1, 1): - gdaltest.post_reason('fail') - print(lastcmd, level, savepoint, usertransac) - return 'fail' + assert (lastcmd, level, savepoint, usertransac) == ('', 3, 1, 1) f = lyr2.GetNextFeature() - if f is None or f.GetFID() != 2: - gdaltest.post_reason('fail') - return 'fail' + assert f is not None and f.GetFID() == 2 - if gdaltest.pg_ds.CommitTransaction() != 0: - gdaltest.post_reason('fail') - return 'fail' + assert gdaltest.pg_ds.CommitTransaction() == 0 (lastcmd, level, savepoint, usertransac) = ogr_pg_76_get_transaction_state(gdaltest.pg_ds) - if (lastcmd, level, savepoint, usertransac) != ('RELEASE SAVEPOINT ogr_savepoint', 2, 0, 0): - gdaltest.post_reason('fail') - print(lastcmd, level, savepoint, usertransac) - return 'fail' + assert (lastcmd, level, savepoint, usertransac) == ('RELEASE SAVEPOINT ogr_savepoint', 2, 0, 0) lyr2.ResetReading() - if gdaltest.pg_ds.StartTransaction() != 0: - gdaltest.post_reason('fail') - return 'fail' + assert gdaltest.pg_ds.StartTransaction() == 0 - if gdaltest.pg_ds.RollbackTransaction() != 0: - gdaltest.post_reason('fail') - return 'fail' + assert gdaltest.pg_ds.RollbackTransaction() == 0 (lastcmd, level, savepoint, usertransac) = ogr_pg_76_get_transaction_state(gdaltest.pg_ds) - if (lastcmd, level, savepoint, usertransac) != ('ROLLBACK TO SAVEPOINT ogr_savepoint', 1, 0, 0): - gdaltest.post_reason('fail') - print(lastcmd, level, savepoint, usertransac) - return 'fail' + assert (lastcmd, level, savepoint, usertransac) == ('ROLLBACK TO SAVEPOINT ogr_savepoint', 1, 0, 0) f = lyr1.GetNextFeature() - if f is None or f.GetFID() != 2: - gdaltest.post_reason('fail') - return 'fail' + assert f is not None and f.GetFID() == 2 lyr1.ResetReading() (lastcmd, level, savepoint, usertransac) = ogr_pg_76_get_transaction_state(gdaltest.pg_ds) - if (lastcmd, level, savepoint, usertransac) != ('COMMIT', 0, 0, 0): - gdaltest.post_reason('fail') - print(lastcmd, level, savepoint, usertransac) - return 'fail' - - return 'success' + assert (lastcmd, level, savepoint, usertransac) == ('COMMIT', 0, 0, 0) ############################################################################### # Test ogr2ogr can insert multiple layers at once -def ogr_pg_77(): +def test_ogr_pg_77(): import test_cli_utilities if test_cli_utilities.get_ogr2ogr_path() is None: - return 'skip' + pytest.skip() gdaltest.pg_ds.ExecuteSQL('DELLAYER:ogr_pg_77_1') gdaltest.pg_ds.ExecuteSQL('DELLAYER:ogr_pg_77_2') @@ -4959,14 +4005,12 @@ def ogr_pg_77(): ds = ogr.Open('PG:' + gdaltest.pg_connection_string, update=1) lyr = ds.GetLayerByName('ogr_pg_77_1') feat = lyr.GetNextFeature() - if feat.GetField(0) != '1': - return 'fail' + assert feat.GetField(0) == '1' feat.SetField(0, 10) lyr.SetFeature(feat) lyr = ds.GetLayerByName('ogr_pg_77_2') feat = lyr.GetNextFeature() - if feat.GetField(0) != '2': - return 'fail' + assert feat.GetField(0) == '2' ds = None # Test fix for #6018 @@ -4975,8 +4019,7 @@ def ogr_pg_77(): ds = ogr.Open('PG:' + gdaltest.pg_connection_string) lyr = ds.GetLayerByName('ogr_pg_77_1') feat = lyr.GetNextFeature() - if feat.GetField(0) != '1': - return 'fail' + assert feat.GetField(0) == '1' ds = None try: @@ -4984,16 +4027,15 @@ def ogr_pg_77(): except OSError: pass - return 'success' - + ############################################################################### # Test manually added geometry constraints -def ogr_pg_78(): +def test_ogr_pg_78(): if gdaltest.pg_ds is None or not gdaltest.pg_has_postgis_2: - return 'skip' + pytest.skip() gdaltest.pg_ds.ExecuteSQL("CREATE TABLE ogr_pg_78 (ID INTEGER PRIMARY KEY)") gdaltest.pg_ds.ExecuteSQL("ALTER TABLE ogr_pg_78 ADD COLUMN my_geom GEOMETRY") @@ -5016,26 +4058,14 @@ def ogr_pg_78(): lyr = gdaltest.pg_ds.GetLayer(i) if lyr.GetName() == 'ogr_pg_78': ogr_pg_78_found = True - if lyr.GetGeomType() != ogr.wkbPoint25D: - gdaltest.post_reason('fail') - return 'fail' - if lyr.GetSpatialRef().ExportToWkt().find('4326') < 0: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.GetGeomType() == ogr.wkbPoint25D + assert lyr.GetSpatialRef().ExportToWkt().find('4326') >= 0 if lyr.GetName() == 'ogr_pg_78_2': ogr_pg_78_2_found = True - if lyr.GetGeomType() != ogr.wkbPoint25D: - gdaltest.post_reason('fail') - return 'fail' - if lyr.GetSpatialRef().ExportToWkt().find('4326') < 0: - gdaltest.post_reason('fail') - return 'fail' - if not ogr_pg_78_found: - gdaltest.post_reason('fail') - return 'fail' - if not ogr_pg_78_2_found: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.GetGeomType() == ogr.wkbPoint25D + assert lyr.GetSpatialRef().ExportToWkt().find('4326') >= 0 + assert ogr_pg_78_found + assert ogr_pg_78_2_found gdaltest.pg_ds = None # Test with slow method @@ -5057,15 +4087,13 @@ def ogr_pg_78(): if val is not None: print('Fails on Travis. geom_type = %d' % lyr.GetGeomType()) else: - gdaltest.post_reason('fail') - return 'fail' + pytest.fail() if lyr.GetSpatialRef() is None or lyr.GetSpatialRef().ExportToWkt().find('4326') < 0: val = gdal.GetConfigOption('TRAVIS', None) if val is not None: print('Fails on Travis. GetSpatialRef() = %s' % str(lyr.GetSpatialRef())) else: - gdaltest.post_reason('fail') - return 'fail' + pytest.fail() if lyr.GetName() == 'ogr_pg_78_2': ogr_pg_78_2_found = True # No logic in geography_columns to get type/coordim/srid from constraints @@ -5075,23 +4103,17 @@ def ogr_pg_78(): # if lyr.GetSpatialRef().ExportToWkt().find('4326') < 0: # gdaltest.post_reason('fail') # return 'fail' - if not ogr_pg_78_found: - gdaltest.post_reason('fail') - return 'fail' - if not ogr_pg_78_2_found: - gdaltest.post_reason('fail') - return 'fail' - - return 'success' + assert ogr_pg_78_found + assert ogr_pg_78_2_found ############################################################################### # Test PRELUDE_STATEMENTS and CLOSING_STATEMENTS open options -def ogr_pg_79(): +def test_ogr_pg_79(): if gdaltest.pg_ds is None: - return 'skip' + pytest.skip() # PRELUDE_STATEMENTS starting with BEGIN (use case: pg_bouncer in transaction pooling) ds = gdal.OpenEx('PG:' + gdaltest.pg_connection_string, @@ -5101,23 +4123,16 @@ def ogr_pg_79(): sql_lyr = ds.ExecuteSQL('SHOW statement_timeout') f = sql_lyr.GetNextFeature() if f.GetField(0) != '1h': - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' + pytest.fail() ds.ReleaseResultSet(sql_lyr) ret = ds.StartTransaction() - if ret != 0: - gdaltest.post_reason('fail') - return 'fail' + assert ret == 0 ret = ds.CommitTransaction() - if ret != 0: - gdaltest.post_reason('fail') - return 'fail' + assert ret == 0 gdal.ErrorReset() ds = None - if gdal.GetLastErrorMsg() != '': - gdaltest.post_reason('fail') - return 'fail' + assert gdal.GetLastErrorMsg() == '' # random PRELUDE_STATEMENTS ds = gdal.OpenEx('PG:' + gdaltest.pg_connection_string, @@ -5126,23 +4141,16 @@ def ogr_pg_79(): sql_lyr = ds.ExecuteSQL('SHOW statement_timeout') f = sql_lyr.GetNextFeature() if f.GetField(0) != '1h': - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' + pytest.fail() ds.ReleaseResultSet(sql_lyr) ret = ds.StartTransaction() - if ret != 0: - gdaltest.post_reason('fail') - return 'fail' + assert ret == 0 ret = ds.CommitTransaction() - if ret != 0: - gdaltest.post_reason('fail') - return 'fail' + assert ret == 0 gdal.ErrorReset() ds = None - if gdal.GetLastErrorMsg() != '': - gdaltest.post_reason('fail') - return 'fail' + assert gdal.GetLastErrorMsg() == '' # Test wrong PRELUDE_STATEMENTS with gdaltest.error_handler(): @@ -5150,9 +4158,7 @@ def ogr_pg_79(): gdal.OF_VECTOR | gdal.OF_UPDATE, open_options=['PRELUDE_STATEMENTS=BEGIN;error SET LOCAL statement_timeout TO "1h";', 'CLOSING_STATEMENTS=COMMIT;']) - if ds is not None: - gdaltest.post_reason('fail') - return 'fail' + assert ds is None # Test wrong CLOSING_STATEMENTS ds = gdal.OpenEx('PG:' + gdaltest.pg_connection_string, @@ -5162,41 +4168,31 @@ def ogr_pg_79(): gdal.ErrorReset() with gdaltest.error_handler(): ds = None - if gdal.GetLastErrorMsg() == '': - gdaltest.post_reason('fail') - return 'fail' - - return 'success' + assert gdal.GetLastErrorMsg() != '' ############################################################################### # Test retrieving an error from ExecuteSQL() (#6194) -def ogr_pg_80(): +def test_ogr_pg_80(with_and_without_postgis): - if gdaltest.pg_ds is None or gdaltest.ogr_pg_second_run: - return 'skip' + if gdaltest.pg_ds is None or not with_and_without_postgis: + pytest.skip() gdal.ErrorReset() with gdaltest.error_handler(): sql_lyr = gdaltest.pg_ds.ExecuteSQL('SELECT FROM') - if gdal.GetLastErrorMsg() == '': - gdaltest.post_reason('fail') - return 'fail' - if sql_lyr is not None: - gdaltest.post_reason('fail') - return 'fail' - - return 'success' + assert gdal.GetLastErrorMsg() != '' + assert sql_lyr is None ############################################################################### # Test that ogr2ogr -skip properly rollbacks transactions (#6328) -def ogr_pg_81(): +def test_ogr_pg_81(with_and_without_postgis): - if gdaltest.pg_ds is None or gdaltest.ogr_pg_second_run: - return 'skip' + if gdaltest.pg_ds is None or not with_and_without_postgis: + pytest.skip() gdaltest.pg_ds.ReleaseResultSet(gdaltest.pg_ds.ExecuteSQL("create table ogr_pg_81_1(id varchar unique, foo varchar); SELECT AddGeometryColumn('ogr_pg_81_1','dummy',-1,'POINT',2);")) gdaltest.pg_ds.ReleaseResultSet(gdaltest.pg_ds.ExecuteSQL("create table ogr_pg_81_2(id varchar unique, foo varchar); SELECT AddGeometryColumn('ogr_pg_81_2','dummy',-1,'POINT',2);")) @@ -5228,13 +4224,10 @@ def ogr_pg_81(): f = lyr.GetNextFeature() f = lyr.GetNextFeature() if f['id'] != '2': - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' + pytest.fail() lyr.ResetReading() # flushes implicit transaction - return 'success' - ############################################################################### # Test that GEOMETRY_NAME works even when the geometry column creation is # done through CreateGeomField (#6366) @@ -5242,28 +4235,23 @@ def ogr_pg_81(): # is not-nullable, and hence the CreateGeomField() interface is used. -def ogr_pg_82(): +def test_ogr_pg_82(with_and_without_postgis): - if gdaltest.pg_ds is None or not gdaltest.pg_has_postgis or gdaltest.ogr_pg_second_run: - return 'skip' + if gdaltest.pg_ds is None or not gdaltest.pg_has_postgis or not with_and_without_postgis: + pytest.skip() lyr = gdaltest.pg_ds.CreateLayer('ogr_pg_82', geom_type=ogr.wkbNone, options=['GEOMETRY_NAME=another_name']) lyr.CreateGeomField(ogr.GeomFieldDefn('my_geom', ogr.wkbPoint)) - if lyr.GetLayerDefn().GetGeomFieldDefn(0).GetName() != 'another_name': - gdaltest.post_reason('fail') - print(lyr.GetLayerDefn().GetGeomFieldDefn(0).GetName()) - return 'fail' - - return 'success' + assert lyr.GetLayerDefn().GetGeomFieldDefn(0).GetName() == 'another_name' ############################################################################### # Test ZM support -def ogr_pg_83(): +def test_ogr_pg_83(with_and_without_postgis): - if gdaltest.pg_ds is None or not gdaltest.pg_has_postgis or gdaltest.ogr_pg_second_run: - return 'skip' + if gdaltest.pg_ds is None or not gdaltest.pg_has_postgis or not with_and_without_postgis: + pytest.skip() tests = [[ogr.wkbUnknown, [], 'POINT ZM (1 2 3 4)', 'POINT (1 2)'], [ogr.wkbUnknown, ['DIM=XYZM'], 'POINT ZM (1 2 3 4)', 'POINT ZM (1 2 3 4)'], @@ -5288,10 +4276,7 @@ def ogr_pg_83(): geom = f.GetGeometryRef() if geom is not None: got_wkt = geom.ExportToIsoWkt() - if got_wkt != expected_wkt: - gdaltest.post_reason('fail') - print(geom_type, options, wkt, expected_wkt, got_wkt) - return 'fail' + assert got_wkt == expected_wkt, (geom_type, options, wkt, expected_wkt, got_wkt) lyr.ResetReading() # flushes implicit transaction if 'GEOM_TYPE=geography' in options: @@ -5317,103 +4302,73 @@ def ogr_pg_83(): geom = f.GetGeometryRef() if geom is not None: got_wkt = geom.ExportToIsoWkt() - if got_wkt != expected_wkt: - gdaltest.post_reason('fail') - print(geom_type, options, wkt, expected_wkt, got_wkt) - return 'fail' + assert got_wkt == expected_wkt, (geom_type, options, wkt, expected_wkt, got_wkt) lyr.ResetReading() # flushes implicit transaction - return 'success' - + ############################################################################### # Test description -def ogr_pg_84(): +def test_ogr_pg_84(with_and_without_postgis): - if gdaltest.pg_ds is None or gdaltest.ogr_pg_second_run: - return 'skip' + if gdaltest.pg_ds is None or not with_and_without_postgis: + pytest.skip() ds = ogr.Open('PG:' + gdaltest.pg_connection_string, update=1) lyr = ds.CreateLayer('ogr_pg_84', geom_type=ogr.wkbPoint, options=['OVERWRITE=YES', 'DESCRIPTION=foo']) # Test that SetMetadata() and SetMetadataItem() are without effect lyr.SetMetadata({'DESCRIPTION': 'bar'}) lyr.SetMetadataItem('DESCRIPTION', 'baz') - if lyr.GetMetadataItem('DESCRIPTION') != 'foo': - gdaltest.post_reason('fail') - return 'fail' - if lyr.GetMetadata_List() != ['DESCRIPTION=foo']: - gdaltest.post_reason('fail') - print(lyr.GetMetadata()) - return 'fail' + assert lyr.GetMetadataItem('DESCRIPTION') == 'foo' + assert lyr.GetMetadata_List() == ['DESCRIPTION=foo'], lyr.GetMetadata() ds = None ds = ogr.Open('PG:' + gdaltest.pg_connection_string, update=1) ds.GetLayerCount() # load all layers lyr = ds.GetLayerByName('ogr_pg_84') - if lyr.GetMetadataItem('DESCRIPTION') != 'foo': - gdaltest.post_reason('fail') - return 'fail' - if lyr.GetMetadata_List() != ['DESCRIPTION=foo']: - gdaltest.post_reason('fail') - print(lyr.GetMetadata()) - return 'fail' + assert lyr.GetMetadataItem('DESCRIPTION') == 'foo' + assert lyr.GetMetadata_List() == ['DESCRIPTION=foo'], lyr.GetMetadata() # Set with SetMetadata() lyr.SetMetadata(['DESCRIPTION=bar']) ds = None ds = ogr.Open('PG:' + gdaltest.pg_connection_string, update=1) lyr = ds.GetLayerByName('ogr_pg_84') # load just this layer - if lyr.GetMetadataItem('DESCRIPTION') != 'bar': - gdaltest.post_reason('fail') - return 'fail' - if lyr.GetMetadataDomainList() is None: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.GetMetadataItem('DESCRIPTION') == 'bar' + assert lyr.GetMetadataDomainList() is not None # Set with SetMetadataItem() lyr.SetMetadataItem('DESCRIPTION', 'baz') ds = None ds = ogr.Open('PG:' + gdaltest.pg_connection_string, update=1) lyr = ds.GetLayerByName('ogr_pg_84') - if lyr.GetMetadataDomainList() is None: - gdaltest.post_reason('fail') - return 'fail' - if lyr.GetMetadataItem('DESCRIPTION') != 'baz': - gdaltest.post_reason('fail') - return 'fail' + assert lyr.GetMetadataDomainList() is not None + assert lyr.GetMetadataItem('DESCRIPTION') == 'baz' # Unset with SetMetadataItem() lyr.SetMetadataItem('DESCRIPTION', None) ds = None ds = ogr.Open('PG:' + gdaltest.pg_connection_string) lyr = ds.GetLayerByName('ogr_pg_84') # load just this layer - if lyr.GetMetadataDomainList() is not None: - gdaltest.post_reason('fail') - return 'fail' - if lyr.GetMetadataItem('DESCRIPTION') is not None: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.GetMetadataDomainList() is None + assert lyr.GetMetadataItem('DESCRIPTION') is None ds = None ds = ogr.Open('PG:' + gdaltest.pg_connection_string) ds.GetLayerCount() # load all layers lyr = ds.GetLayerByName('ogr_pg_84') # load just this layer - if lyr.GetMetadataItem('DESCRIPTION') is not None: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.GetMetadataItem('DESCRIPTION') is None ds = None - return 'success' - ############################################################################### # Test append of several layers in PG_USE_COPY mode (#6411) -def ogr_pg_85(): +def test_ogr_pg_85(with_and_without_postgis): - if gdaltest.pg_ds is None or gdaltest.ogr_pg_second_run: - return 'skip' + if gdaltest.pg_ds is None or not with_and_without_postgis: + pytest.skip() gdaltest.pg_ds.CreateLayer('ogr_pg_85_1') lyr = gdaltest.pg_ds.CreateLayer('ogr_pg_85_2') @@ -5430,13 +4385,9 @@ def ogr_pg_85(): lyr.CreateFeature(f) lyr = ds.GetLayerByName('ogr_pg_85_2') feat_defn = lyr.GetLayerDefn() - if feat_defn.GetFieldCount() != 1: - gdaltest.post_reason('fail') - return 'fail' + assert feat_defn.GetFieldCount() == 1 f = ogr.Feature(feat_defn) - if lyr.CreateFeature(f) != 0: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.CreateFeature(f) == 0 ds.CommitTransaction() ds = None @@ -5460,21 +4411,16 @@ def ogr_pg_85(): gdal.SetConfigOption('PG_USE_COPY', old_val) lyr = gdaltest.pg_ds.GetLayerByName('ogr_pg_85_2') - if lyr.GetFeatureCount() != 2: - gdaltest.post_reason('fail') - print(lyr.GetFeatureCount()) - return 'fail' - - return 'success' + assert lyr.GetFeatureCount() == 2 ############################################################################### # Test OFTBinary -def ogr_pg_86(): +def test_ogr_pg_86(with_and_without_postgis): - if gdaltest.pg_ds is None or gdaltest.ogr_pg_second_run: - return 'skip' + if gdaltest.pg_ds is None or not with_and_without_postgis: + pytest.skip() old_val = gdal.GetConfigOption('PG_USE_COPY') @@ -5488,9 +4434,8 @@ def ogr_pg_86(): lyr.ResetReading() f = lyr.GetNextFeature() if f.GetField(0) != '3020': - gdaltest.post_reason('fail') gdal.SetConfigOption('PG_USE_COPY', old_val) - return 'fail' + pytest.fail() gdal.SetConfigOption('PG_USE_COPY', 'NO') @@ -5502,22 +4447,19 @@ def ogr_pg_86(): lyr.ResetReading() f = lyr.GetNextFeature() if f.GetField(0) != '3020': - gdaltest.post_reason('fail') gdal.SetConfigOption('PG_USE_COPY', old_val) - return 'fail' + pytest.fail() gdal.SetConfigOption('PG_USE_COPY', old_val) - return 'success' - ############################################################################### # Test sequence updating (#7032) -def ogr_pg_87(): +def test_ogr_pg_87(with_and_without_postgis): - if gdaltest.pg_ds is None or gdaltest.ogr_pg_second_run: - return 'skip' + if gdaltest.pg_ds is None or not with_and_without_postgis: + pytest.skip() lyr = gdaltest.pg_ds.CreateLayer('ogr_pg_87') lyr.CreateField(ogr.FieldDefn('test', ogr.OFTString)) @@ -5530,29 +4472,23 @@ def ogr_pg_87(): lyr = gdaltest.pg_ds.GetLayerByName('ogr_pg_87') f = ogr.Feature(lyr.GetLayerDefn()) lyr.CreateFeature(f) - if f.GetFID() != 11: - gdaltest.post_reason('fail') - return 'fail' + assert f.GetFID() == 11 # Test updating of sequence after CreateFeatureViaInsert gdaltest.pg_ds = ogr.Open('PG:' + gdaltest.pg_connection_string, update=1) lyr = gdaltest.pg_ds.GetLayerByName('ogr_pg_87') f = ogr.Feature(lyr.GetLayerDefn()) lyr.CreateFeature(f) - if f.GetFID() != 12: - gdaltest.post_reason('fail') - return 'fail' - - return 'success' + assert f.GetFID() == 12 ############################################################################### # Test JSON subtype -def ogr_pg_json(): +def test_ogr_pg_json(): - if gdaltest.pg_ds is None or gdaltest.ogr_pg_second_run: - return 'skip' + if gdaltest.pg_ds is None: + pytest.skip() lyr = gdaltest.pg_ds.CreateLayer('ogr_pg_json') fld_defn = ogr.FieldDefn('test_json', ogr.OFTString) @@ -5564,31 +4500,24 @@ def ogr_pg_json(): gdaltest.pg_ds = ogr.Open('PG:' + gdaltest.pg_connection_string, update=1) lyr = gdaltest.pg_ds.GetLayer('ogr_pg_json') - if lyr.GetLayerDefn().GetFieldDefn(0).GetSubType() != ogr.OFSTJSON: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.GetLayerDefn().GetFieldDefn(0).GetSubType() == ogr.OFSTJSON f = lyr.GetNextFeature() if f.GetField(0) != '{"a": "b"}': - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' + pytest.fail() sql_lyr = gdaltest.pg_ds.ExecuteSQL('SELECT * FROM ogr_pg_json') - if sql_lyr.GetLayerDefn().GetFieldDefn(0).GetSubType() != ogr.OFSTJSON: - gdaltest.post_reason('fail') - return 'fail' + assert sql_lyr.GetLayerDefn().GetFieldDefn(0).GetSubType() == ogr.OFSTJSON gdaltest.pg_ds.ReleaseResultSet(sql_lyr) - return 'success' - ############################################################################### # -def ogr_pg_table_cleanup(): +def test_ogr_pg_table_cleanup(): if gdaltest.pg_ds is None: - return 'skip' + pytest.skip() gdal.PushErrorHandler('CPLQuietErrorHandler') gdaltest.pg_ds.ExecuteSQL('DELLAYER:tpoly') @@ -5661,162 +4590,20 @@ def ogr_pg_table_cleanup(): gdaltest.pg_ds.ExecuteSQL('DROP SCHEMA \"AutoTest-schema\" CASCADE') gdal.PopErrorHandler() - return 'success' - -def ogr_pg_cleanup(): +def test_ogr_pg_cleanup(): if gdaltest.pg_ds is None: - return 'skip' + pytest.skip() gdaltest.pg_ds = ogr.Open('PG:' + gdaltest.pg_connection_string, update=1) - ogr_pg_table_cleanup() + test_ogr_pg_table_cleanup() gdaltest.pg_ds.Destroy() gdaltest.pg_ds = None - return 'success' - # NOTE: The ogr_pg_19 intentionally executed after ogr_pg_2 -gdaltest_list_internal = [ - ogr_pg_table_cleanup, - ogr_pg_2, - ogr_pg_19, - ogr_pg_19_2, - ogr_pg_3, - ogr_pg_4, - ogr_pg_5, - ogr_pg_6, - ogr_pg_7, - ogr_pg_8, - ogr_pg_9, - ogr_pg_10, - ogr_pg_11, - ogr_pg_12, - ogr_pg_13, - ogr_pg_14, - ogr_pg_15, - ogr_pg_16, - ogr_pg_17, - ogr_pg_18, - ogr_pg_20, - ogr_pg_21, - ogr_pg_21_subgeoms, - ogr_pg_21_3d_geometries, - ogr_pg_22, - ogr_pg_23, - ogr_pg_24, - ogr_pg_25, - # ogr_pg_26, - # ogr_pg_27, - ogr_pg_28, - ogr_pg_29, - ogr_pg_30, - ogr_pg_29, - ogr_pg_31, - ogr_pg_32, - ogr_pg_33, - ogr_pg_34, - ogr_pg_35, - ogr_pg_36, - ogr_pg_36_bis, - ogr_pg_37, - ogr_pg_38, - ogr_pg_39, - ogr_pg_40, - ogr_pg_41, - ogr_pg_42, - ogr_pg_43, - ogr_pg_44, - ogr_pg_45, - ogr_pg_46, - ogr_pg_47, - ogr_pg_48, - ogr_pg_49, - ogr_pg_50, - ogr_pg_51, - ogr_pg_52, - ogr_pg_53, - ogr_pg_53_bis, - ogr_pg_54, - ogr_pg_55, - ogr_pg_56, - ogr_pg_57, - ogr_pg_58, - ogr_pg_59, - ogr_pg_60, - ogr_pg_61, - ogr_pg_62, - ogr_pg_63, - ogr_pg_64, - ogr_pg_65, - ogr_pg_66, - ogr_pg_67, - ogr_pg_68, - ogr_pg_69, - ogr_pg_70, - ogr_pg_71, - ogr_pg_72, - ogr_pg_73, - ogr_pg_74, - ogr_pg_75, - ogr_pg_76, - ogr_pg_77, - ogr_pg_78, - ogr_pg_79, - ogr_pg_80, - ogr_pg_81, - ogr_pg_82, - ogr_pg_83, - ogr_pg_84, - ogr_pg_85, - ogr_pg_86, - ogr_pg_87, - ogr_pg_json, - ogr_pg_cleanup -] - -disabled_gdaltest_list_internal = [ - ogr_pg_table_cleanup, - ogr_pg_json, - ogr_pg_cleanup] - -############################################################################### -# Run gdaltest_list_internal with PostGIS enabled and then with PostGIS disabled - - -def ogr_pg_with_and_without_postgis(): - - gdaltest.ogr_pg_second_run = False - gdaltest.run_tests([ogr_pg_1]) - if gdaltest.pg_ds is None: - return 'skip' - # gdaltest.run_tests( [ ogr_pg_71 ] ) - # gdaltest.run_tests( [ ogr_pg_cleanup ] ) - if True: # pylint: disable=using-constant-test - gdaltest.run_tests(gdaltest_list_internal) - - if gdaltest.pg_has_postgis: - gdal.SetConfigOption("PG_USE_POSTGIS", "NO") - gdaltest.ogr_pg_second_run = True - gdaltest.run_tests([ogr_pg_1]) - gdaltest.run_tests(gdaltest_list_internal) - gdal.SetConfigOption("PG_USE_POSTGIS", "YES") - gdaltest.ogr_pg_second_run = False - - return 'success' - - -gdaltest_list = [ - ogr_pg_with_and_without_postgis -] - -if __name__ == '__main__': - - gdaltest.setup_run('ogr_pg') - gdaltest.run_tests(gdaltest_list) - sys.exit(gdaltest.summarize()) diff --git a/autotest/ogr/ogr_pgdump.py b/autotest/ogr/ogr_pgdump.py index 9a6f37d18fb2..55fe1ed0d5df 100755 --- a/autotest/ogr/ogr_pgdump.py +++ b/autotest/ogr/ogr_pgdump.py @@ -31,19 +31,19 @@ import os import sys -sys.path.append('../pymod') import gdaltest import ogrtest from osgeo import ogr from osgeo import osr from osgeo import gdal +import pytest ############################################################################### # Create table from data/poly.shp -def ogr_pgdump_1(): +def test_ogr_pgdump_1(): try: os.remove('tmp/tpoly.sql') @@ -90,7 +90,7 @@ def ogr_pgdump_1(): sql = f.read() f.close() - if sql.find("""DROP TABLE IF EXISTS "public"."tpoly" CASCADE;""") == -1 or \ + assert (not (sql.find("""DROP TABLE IF EXISTS "public"."tpoly" CASCADE;""") == -1 or \ sql.find("""DELETE FROM geometry_columns WHERE f_table_name = 'tpoly' AND f_table_schema = 'public';""") == -1 or \ sql.find("""BEGIN;""") == -1 or \ sql.find("""CREATE TABLE "public"."tpoly" ( "ogc_fid" SERIAL, CONSTRAINT "tpoly_pk" PRIMARY KEY ("ogc_fid") );""") == -1 or \ @@ -101,17 +101,13 @@ def ogr_pgdump_1(): sql.find("""ALTER TABLE "public"."tpoly" ADD COLUMN "prfedea" VARCHAR;""") == -1 or \ sql.find("""ALTER TABLE "public"."tpoly" ADD COLUMN "shortname" VARCHAR(8);""") == -1 or \ sql.find("""INSERT INTO "public"."tpoly" ("wkb_geometry" , "area", "eas_id", "prfedea") VALUES ('01030000800100000005000000000000C01A481D4100000080072D5241000000000000000000000060AA461D4100000080FF2C524100000000000000000000006060461D41000000400C2D52410000000000000000000000A0DF471D4100000000142D52410000000000000000000000C01A481D4100000080072D52410000000000000000', 5268.813, 170, '35043413');""") == -1 or \ - sql.find("""COMMIT;""") == -1: - print(sql) - return 'fail' - - return 'success' + sql.find("""COMMIT;""") == -1)) ############################################################################### # Create table from data/poly.shp with PG_USE_COPY=YES -def ogr_pgdump_2(): +def test_ogr_pgdump_2(): try: os.remove('tmp/tpoly.sql') @@ -162,7 +158,7 @@ def ogr_pgdump_2(): sql = f.read() f.close() - if sql.find("""DROP TABLE IF EXISTS "another_schema"."tpoly" CASCADE;""") == -1 or \ + assert (not (sql.find("""DROP TABLE IF EXISTS "another_schema"."tpoly" CASCADE;""") == -1 or \ sql.find("""DELETE FROM geometry_columns WHERE f_table_name = 'tpoly' AND f_table_schema = 'another_schema';""") == -1 or \ sql.find("""BEGIN;""") == -1 or \ sql.find("""CREATE TABLE "another_schema"."tpoly" ( "ogc_fid" SERIAL, CONSTRAINT "tpoly_pk" PRIMARY KEY ("ogc_fid") );""") == -1 or \ @@ -175,17 +171,13 @@ def ogr_pgdump_2(): sql.find("""COPY "another_schema"."tpoly" ("the_geom", "area", "eas_id", "prfedea", "shortname") FROM STDIN;""") == -1 or \ sql.find("0103000020E61000000100000005000000000000C01A481D4100000080072D524100000060AA461D4100000080FF2C52410000006060461D41000000400C2D5241000000A0DF471D4100000000142D5241000000C01A481D4100000080072D5241 5268.813 170 35043413 \\N") == -1 or \ sql.find("""\.""") == -1 or \ - sql.find("""COMMIT;""") == -1: - print(sql) - return 'fail' - - return 'success' + sql.find("""COMMIT;""") == -1)) ############################################################################### # Create table from data/poly.shp without any geometry -def ogr_pgdump_3(): +def test_ogr_pgdump_3(): try: os.remove('tmp/tpoly.sql') @@ -247,7 +239,7 @@ def ogr_pgdump_3(): sql = f.read() f.close() - if sql.find("""DROP TABLE IF EXISTS "another_schema"."tpoly" CASCADE;""") == -1 or \ + assert (not (sql.find("""DROP TABLE IF EXISTS "another_schema"."tpoly" CASCADE;""") == -1 or \ sql.find("""DELETE FROM geometry_columns""") != -1 or \ sql.find("""BEGIN;""") == -1 or \ sql.find("""CREATE TABLE "another_schema"."tpoly" ( "ogc_fid" SERIAL, CONSTRAINT "tpoly_pk" PRIMARY KEY ("ogc_fid") );""") == -1 or \ @@ -261,29 +253,21 @@ def ogr_pgdump_3(): sql.find("""\\N 215229.266 168 35043411 \\N""") == -1 or \ sql.find(""" 5268.813 170 35043413 \\N""") == -1 or \ sql.find("""\\.""") == -1 or \ - sql.find("""COMMIT;""") == -1: - print(sql) - return 'fail' - - return 'success' + sql.find("""COMMIT;""") == -1)) ############################################################################### # Test multi-geometry support -def ogr_pgdump_4(): +def test_ogr_pgdump_4(): ds = ogr.GetDriverByName('PGDump').CreateDataSource('tmp/ogr_pgdump_4.sql', options=['LINEFORMAT=LF']) - if ds.TestCapability(ogr.ODsCCreateGeomFieldAfterCreateLayer) == 0: - gdaltest.post_reason('fail') - return 'fail' + assert ds.TestCapability(ogr.ODsCCreateGeomFieldAfterCreateLayer) != 0 ###################################################### # Create Layer lyr = ds.CreateLayer('test', geom_type=ogr.wkbNone, options=['WRITE_EWKT_GEOM=YES']) - if lyr.TestCapability(ogr.OLCCreateGeomField) == 0: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.TestCapability(ogr.OLCCreateGeomField) != 0 gfld_defn = ogr.GeomFieldDefn("point_nosrs", ogr.wkbPoint) lyr.CreateGeomField(gfld_defn) @@ -308,23 +292,19 @@ def ogr_pgdump_4(): sql = f.read() f.close() - if sql.find("""CREATE TABLE "public"."test" ( "ogc_fid" SERIAL, CONSTRAINT "test_pk" PRIMARY KEY ("ogc_fid") )""") == -1 or \ + assert (not (sql.find("""CREATE TABLE "public"."test" ( "ogc_fid" SERIAL, CONSTRAINT "test_pk" PRIMARY KEY ("ogc_fid") )""") == -1 or \ sql.find("""SELECT AddGeometryColumn('public','test','point_nosrs',-1,'POINT',2)""") == -1 or \ sql.find("""CREATE INDEX "test_point_nosrs_geom_idx" ON "public"."test" USING GIST ("point_nosrs")""") == -1 or \ sql.find("""SELECT AddGeometryColumn('public','test','poly',4326,'POLYGON',3)""") == -1 or \ sql.find("""CREATE INDEX "test_poly_geom_idx" ON "public"."test" USING GIST ("poly")""") == -1 or \ sql.find("""INSERT INTO "public"."test" DEFAULT VALUES""") == -1 or \ - sql.find("""INSERT INTO "public"."test" ("point_nosrs" , "poly" ) VALUES (GeomFromEWKT('SRID=-1;POINT (1 2)'::TEXT) , GeomFromEWKT('SRID=4326;POLYGON ((0 0 0,0 1 0,1 1 0,1 0 0,0 0 0))'::TEXT) )""") == -1: - print(sql) - return 'fail' - - return 'success' + sql.find("""INSERT INTO "public"."test" ("point_nosrs" , "poly" ) VALUES (GeomFromEWKT('SRID=-1;POINT (1 2)'::TEXT) , GeomFromEWKT('SRID=4326;POLYGON ((0 0 0,0 1 0,1 1 0,1 0 0,0 0 0))'::TEXT) )""") == -1)) ############################################################################### # Test non nullable field support -def ogr_pgdump_5(): +def test_ogr_pgdump_5(): ds = ogr.GetDriverByName('PGDump').CreateDataSource('/vsimem/ogr_pgdump_5.sql', options=['LINEFORMAT=LF']) lyr = ds.CreateLayer('test', geom_type=ogr.wkbNone) @@ -350,9 +330,7 @@ def ogr_pgdump_5(): gdal.PushErrorHandler() ret = lyr.CreateFeature(f) gdal.PopErrorHandler() - if ret == 0: - gdaltest.post_reason('fail') - return 'fail' + assert ret != 0 f = None # Error case: missing non-nullable field @@ -361,9 +339,7 @@ def ogr_pgdump_5(): gdal.PushErrorHandler() ret = lyr.CreateFeature(f) gdal.PopErrorHandler() - if ret == 0: - gdaltest.post_reason('fail') - return 'fail' + assert ret != 0 f = None ds = None @@ -374,19 +350,15 @@ def ogr_pgdump_5(): gdal.Unlink('/vsimem/ogr_pgdump_5.sql') - if sql.find("""ALTER TABLE "public"."test" ADD COLUMN "field_not_nullable" VARCHAR NOT NULL;""") == -1 or \ + assert (not (sql.find("""ALTER TABLE "public"."test" ADD COLUMN "field_not_nullable" VARCHAR NOT NULL;""") == -1 or \ sql.find("""ALTER TABLE "public"."test" ADD COLUMN "field_nullable" VARCHAR;""") == -1 or \ - sql.find("""ALTER TABLE "test" ALTER COLUMN "geomfield_not_nullable" SET NOT NULL;""") == -1: - print(sql) - return 'fail' - - return 'success' + sql.find("""ALTER TABLE "test" ALTER COLUMN "geomfield_not_nullable" SET NOT NULL;""") == -1)) ############################################################################### # Test default values -def ogr_pgdump_6(): +def test_ogr_pgdump_6(): ds = ogr.GetDriverByName('PGDump').CreateDataSource('/vsimem/ogr_pgdump_6.sql', options=['LINEFORMAT=LF']) lyr = ds.CreateLayer('test', geom_type=ogr.wkbNone) @@ -462,7 +434,7 @@ def ogr_pgdump_6(): gdal.Unlink('/vsimem/ogr_pgdump_6.sql') - if sql.find("""a\t456\t4.56\t\\N\t2015/06/30 12:34:56\t2015/06/30 12:34:56\t2015/06/30\t12:34:56""") < 0 or \ + assert (not (sql.find("""a\t456\t4.56\t\\N\t2015/06/30 12:34:56\t2015/06/30 12:34:56\t2015/06/30\t12:34:56""") < 0 or \ sql.find("""ALTER TABLE "public"."test" ADD COLUMN "field_string" VARCHAR DEFAULT 'a''b';""") == -1 or \ sql.find("""ALTER TABLE "public"."test" ADD COLUMN "field_int" INTEGER DEFAULT 123;""") == -1 or \ sql.find("""ALTER TABLE "public"."test" ADD COLUMN "field_real" FLOAT8 DEFAULT 1.23;""") == -1 or \ @@ -470,17 +442,13 @@ def ogr_pgdump_6(): sql.find("""ALTER TABLE "public"."test" ADD COLUMN "field_datetime2" timestamp with time zone DEFAULT '2015/06/30 12:34:56+00'::timestamp with time zone;""") == -1 or \ sql.find("""ALTER TABLE "public"."test" ADD COLUMN "field_date" date DEFAULT CURRENT_DATE;""") == -1 or \ sql.find("""ALTER TABLE "public"."test" ADD COLUMN "field_time" time DEFAULT CURRENT_TIME;""") == -1 or \ - sql.find("""b\t456\t4.56\t\\N\t2015/06/30 12:34:56\t2015/06/30 12:34:56\t2015/06/30\t12:34:56""") < 0: - print(sql) - return 'fail' - - return 'success' + sql.find("""b\t456\t4.56\t\\N\t2015/06/30 12:34:56\t2015/06/30 12:34:56\t2015/06/30\t12:34:56""") < 0)) ############################################################################### # Test creating a field with the fid name (PG_USE_COPY=NO) -def ogr_pgdump_7(): +def test_ogr_pgdump_7(): ds = ogr.GetDriverByName('PGDump').CreateDataSource('/vsimem/ogr_pgdump_7.sql', options=['LINEFORMAT=LF']) lyr = ds.CreateLayer('test', geom_type=ogr.wkbNone, options=['FID=myfid']) @@ -489,14 +457,10 @@ def ogr_pgdump_7(): gdal.PushErrorHandler() ret = lyr.CreateField(ogr.FieldDefn('myfid', ogr.OFTString)) gdal.PopErrorHandler() - if ret == 0: - gdaltest.post_reason('fail') - return 'fail' + assert ret != 0 ret = lyr.CreateField(ogr.FieldDefn('myfid', ogr.OFTInteger)) - if ret != 0: - gdaltest.post_reason('fail') - return 'fail' + assert ret == 0 lyr.CreateField(ogr.FieldDefn('str2', ogr.OFTString)) feat = ogr.Feature(lyr.GetLayerDefn()) @@ -504,27 +468,19 @@ def ogr_pgdump_7(): feat.SetField('myfid', 10) feat.SetField('str2', 'second string') ret = lyr.CreateFeature(feat) - if ret != 0: - gdaltest.post_reason('fail') - return 'fail' - if feat.GetFID() != 10: - gdaltest.post_reason('fail') - return 'fail' + assert ret == 0 + assert feat.GetFID() == 10 feat = ogr.Feature(lyr.GetLayerDefn()) feat.SetField('str2', 'second string') ret = lyr.CreateFeature(feat) - if ret != 0: - gdaltest.post_reason('fail') - return 'fail' + assert ret == 0 if feat.GetFID() < 0: - gdaltest.post_reason('fail') feat.DumpReadable() - return 'fail' + pytest.fail() if feat.GetField('myfid') != feat.GetFID(): - gdaltest.post_reason('fail') feat.DumpReadable() - return 'fail' + pytest.fail() # feat.SetField('str', 'foo') # ret = lyr.SetFeature(feat) @@ -538,9 +494,7 @@ def ogr_pgdump_7(): gdal.PushErrorHandler() ret = lyr.CreateFeature(feat) gdal.PopErrorHandler() - if ret == 0: - gdaltest.post_reason('fail') - return 'fail' + assert ret != 0 # gdal.PushErrorHandler() # ret = lyr.SetFeature(feat) @@ -562,12 +516,8 @@ def ogr_pgdump_7(): feat.SetField('myfid', 12) feat.SetField('str2', 'second string') ret = lyr.CreateFeature(feat) - if ret != 0: - gdaltest.post_reason('fail') - return 'fail' - if feat.GetFID() != 12: - gdaltest.post_reason('fail') - return 'fail' + assert ret == 0 + assert feat.GetFID() == 12 ds = None @@ -577,21 +527,17 @@ def ogr_pgdump_7(): gdal.Unlink('/vsimem/ogr_pgdump_7.sql') - if sql.find("""CREATE TABLE "public"."test" ( "myfid" SERIAL, CONSTRAINT "test_pk" PRIMARY KEY ("myfid") )""") < 0 or \ + assert (not (sql.find("""CREATE TABLE "public"."test" ( "myfid" SERIAL, CONSTRAINT "test_pk" PRIMARY KEY ("myfid") )""") < 0 or \ sql.find("""ALTER TABLE "public"."test" ADD COLUMN "myfid" """) >= 0 or \ sql.find("""INSERT INTO "public"."test" ("myfid" , "str", "str2") VALUES (10, 'first string', 'second string');""") == -1 or \ sql.find("""INSERT INTO "public"."test" ("str2") VALUES ('second string');""") == -1 or \ - sql.find("""INSERT INTO "public"."test" ("myfid" , "str", "str2") VALUES (12, 'first string', 'second string');""") == -1: - print(sql) - return 'fail' - - return 'success' + sql.find("""INSERT INTO "public"."test" ("myfid" , "str", "str2") VALUES (12, 'first string', 'second string');""") == -1)) ############################################################################### # Test creating a field with the fid name (PG_USE_COPY=NO) -def ogr_pgdump_8(): +def test_ogr_pgdump_8(): ds = ogr.GetDriverByName('PGDump').CreateDataSource('/vsimem/ogr_pgdump_8.sql', options=['LINEFORMAT=LF']) lyr = ds.CreateLayer('test', geom_type=ogr.wkbNone, options=['FID=myfid']) @@ -600,14 +546,10 @@ def ogr_pgdump_8(): gdal.PushErrorHandler() ret = lyr.CreateField(ogr.FieldDefn('myfid', ogr.OFTString)) gdal.PopErrorHandler() - if ret == 0: - gdaltest.post_reason('fail') - return 'fail' + assert ret != 0 ret = lyr.CreateField(ogr.FieldDefn('myfid', ogr.OFTInteger)) - if ret != 0: - gdaltest.post_reason('fail') - return 'fail' + assert ret == 0 lyr.CreateField(ogr.FieldDefn('str2', ogr.OFTString)) feat = ogr.Feature(lyr.GetLayerDefn()) @@ -617,29 +559,21 @@ def ogr_pgdump_8(): gdal.SetConfigOption('PG_USE_COPY', 'YES') ret = lyr.CreateFeature(feat) gdal.SetConfigOption('PG_USE_COPY', None) - if ret != 0: - gdaltest.post_reason('fail') - return 'fail' - if feat.GetFID() != 10: - gdaltest.post_reason('fail') - return 'fail' + assert ret == 0 + assert feat.GetFID() == 10 feat = ogr.Feature(lyr.GetLayerDefn()) feat.SetField('str2', 'second string') gdal.SetConfigOption('PG_USE_COPY', 'YES') ret = lyr.CreateFeature(feat) gdal.SetConfigOption('PG_USE_COPY', None) - if ret != 0: - gdaltest.post_reason('fail') - return 'fail' + assert ret == 0 if feat.GetFID() < 0: - gdaltest.post_reason('fail') feat.DumpReadable() - return 'fail' + pytest.fail() if feat.GetField('myfid') != feat.GetFID(): - gdaltest.post_reason('fail') feat.DumpReadable() - return 'fail' + pytest.fail() # feat.SetField('str', 'foo') # ret = lyr.SetFeature(feat) @@ -655,9 +589,7 @@ def ogr_pgdump_8(): ret = lyr.CreateFeature(feat) gdal.SetConfigOption('PG_USE_COPY', None) gdal.PopErrorHandler() - if ret == 0: - gdaltest.post_reason('fail') - return 'fail' + assert ret != 0 # gdal.PushErrorHandler() # ret = lyr.SetFeature(feat) @@ -681,12 +613,8 @@ def ogr_pgdump_8(): gdal.SetConfigOption('PG_USE_COPY', 'YES') ret = lyr.CreateFeature(feat) gdal.SetConfigOption('PG_USE_COPY', None) - if ret != 0: - gdaltest.post_reason('fail') - return 'fail' - if feat.GetFID() != 12: - gdaltest.post_reason('fail') - return 'fail' + assert ret == 0 + assert feat.GetFID() == 12 ds = None @@ -696,21 +624,17 @@ def ogr_pgdump_8(): gdal.Unlink('/vsimem/ogr_pgdump_8.sql') - if sql.find("""CREATE TABLE "public"."test" ( "myfid" SERIAL, CONSTRAINT "test_pk" PRIMARY KEY ("myfid") )""") < 0 or \ + assert (not (sql.find("""CREATE TABLE "public"."test" ( "myfid" SERIAL, CONSTRAINT "test_pk" PRIMARY KEY ("myfid") )""") < 0 or \ sql.find("""ALTER TABLE "public"."test" ADD COLUMN "myfid" """) >= 0 or \ sql.find("""10\tfirst string\tsecond string""") == -1 or \ sql.find("""INSERT INTO "public"."test" ("str2") VALUES ('second string');""") == -1 or \ - sql.find("""12\tfirst string\tsecond string""") == -1: - print(sql) - return 'fail' - - return 'success' + sql.find("""12\tfirst string\tsecond string""") == -1)) ############################################################################### # Test creating a field with the fid name (PG_USE_COPY=NO) -def ogr_pgdump_9(pg_use_copy='YES'): +def test_ogr_pgdump_9(pg_use_copy='YES'): gdal.SetConfigOption('PG_USE_COPY', pg_use_copy) @@ -762,24 +686,20 @@ def ogr_pgdump_9(pg_use_copy='YES'): eofield = '\t' else: eofield = "'" - if sql.find("""01234%s""" % eofield) < 0 or \ - sql.find("""ABCDE%s""" % eofield) < 0 or \ - sql.find("""%s%s""" % (val5, eofield)) < 0 or \ - sql.find("""%s%s""" % ('a' + val4, eofield)) < 0: - print(sql) - return 'fail' + assert (sql.find("""01234%s""" % eofield) >= 0 and \ + sql.find("""ABCDE%s""" % eofield) >= 0 and \ + sql.find("""%s%s""" % (val5, eofield)) >= 0 and \ + sql.find("""%s%s""" % ('a' + val4, eofield)) >= 0) - return 'success' - -def ogr_pgdump_10(): - return ogr_pgdump_9('NO') +def test_ogr_pgdump_10(): + return test_ogr_pgdump_9('NO') ############################################################################### # Export POINT EMPTY for PostGIS 2.2 -def ogr_pgdump_11(): +def test_ogr_pgdump_11(): ds = ogr.GetDriverByName('PGDump').CreateDataSource('/vsimem/ogr_pgdump_11.sql', options=['LINEFORMAT=LF']) lyr = ds.CreateLayer('test', geom_type=ogr.wkbPoint, options=['POSTGIS_VERSION=2.2']) @@ -796,12 +716,8 @@ def ogr_pgdump_11(): gdal.Unlink('/vsimem/ogr_pgdump_11.sql') # clang -m32 generates F8FF..., instead of F87F... for all other systems - if sql.find('0101000000000000000000F87F000000000000F87F') < 0 and \ - sql.find('0101000000000000000000F8FF000000000000F8FF') < 0: - print(sql) - return 'fail' - - return 'success' + assert (sql.find('0101000000000000000000F87F000000000000F87F') >= 0 or \ + sql.find('0101000000000000000000F8FF000000000000F8FF') >= 0) ############################################################################### # Test that GEOMETRY_NAME works even when the geometry column creation is @@ -810,7 +726,7 @@ def ogr_pgdump_11(): # is not-nullable, and hence the CreateGeomField() interface is used. -def ogr_pgdump_12(): +def test_ogr_pgdump_12(): ds = ogr.GetDriverByName('PGDump').CreateDataSource('/vsimem/ogr_pgdump_12.sql', options=['LINEFORMAT=LF']) lyr = ds.CreateLayer('test', geom_type=ogr.wkbNone, options=['GEOMETRY_NAME=another_name']) @@ -823,17 +739,13 @@ def ogr_pgdump_12(): gdal.Unlink('/vsimem/ogr_pgdump_12.sql') - if sql.find('another_name') < 0: - print(sql) - return 'fail' - - return 'success' + assert sql.find('another_name') >= 0 ############################################################################### # Test ZM support -def ogr_pgdump_13(): +def test_ogr_pgdump_13(): tests = [[ogr.wkbUnknown, [], 'POINT ZM (1 2 3 4)', ["'GEOMETRY',2)", "0101000000000000000000F03F0000000000000040"]], [ogr.wkbUnknown, ['GEOM_TYPE=geography'], 'POINT ZM (1 2 3 4)', ["geography(GEOMETRY", "0101000000000000000000F03F0000000000000040"]], @@ -870,11 +782,7 @@ def ogr_pgdump_13(): gdal.Unlink('/vsimem/ogr_pgdump_13.sql') for expected_string in expected_strings: - if sql.find(expected_string) < 0: - gdaltest.post_reason('fail') - print(geom_type, options, wkt, expected_string) - print(sql) - return 'fail' + assert sql.find(expected_string) >= 0, (geom_type, options, wkt, expected_string) if 'GEOM_TYPE=geography' in options: continue @@ -895,19 +803,14 @@ def ogr_pgdump_13(): gdal.Unlink('/vsimem/ogr_pgdump_13.sql') for expected_string in expected_strings: - if sql.find(expected_string) < 0: - gdaltest.post_reason('fail') - print(geom_type, options, wkt, expected_string) - print(sql) - return 'fail' - - return 'success' + assert sql.find(expected_string) >= 0, (geom_type, options, wkt, expected_string) + ############################################################################### # Test description -def ogr_pgdump_14(): +def test_ogr_pgdump_14(): # Set with DESCRIPTION layer creation option ds = ogr.GetDriverByName('PGDump').CreateDataSource('/vsimem/ogr_pgdump_14.sql', options=['LINEFORMAT=LF']) @@ -923,10 +826,7 @@ def ogr_pgdump_14(): gdal.Unlink('/vsimem/ogr_pgdump_14.sql') - if sql.find("""COMMENT ON TABLE "public"."ogr_pgdump_14" IS 'foo';""") < 0 or sql.find('bar') >= 0 or sql.find('baz') >= 0: - gdaltest.post_reason('fail') - print(sql) - return 'fail' + assert sql.find("""COMMENT ON TABLE "public"."ogr_pgdump_14" IS 'foo';""") >= 0 and sql.find('bar') < 0 and sql.find('baz') < 0 # Set with SetMetadataItem() ds = ogr.GetDriverByName('PGDump').CreateDataSource('/vsimem/ogr_pgdump_14.sql', options=['LINEFORMAT=LF']) @@ -939,10 +839,7 @@ def ogr_pgdump_14(): gdal.VSIFCloseL(f) gdal.Unlink('/vsimem/ogr_pgdump_14.sql') - if sql.find("""COMMENT ON TABLE "public"."ogr_pgdump_14" IS 'bar';""") < 0: - gdaltest.post_reason('fail') - print(sql) - return 'fail' + assert sql.find("""COMMENT ON TABLE "public"."ogr_pgdump_14" IS 'bar';""") >= 0 # Set with SetMetadata() ds = ogr.GetDriverByName('PGDump').CreateDataSource('/vsimem/ogr_pgdump_14.sql', options=['LINEFORMAT=LF']) @@ -955,18 +852,13 @@ def ogr_pgdump_14(): gdal.VSIFCloseL(f) gdal.Unlink('/vsimem/ogr_pgdump_14.sql') - if sql.find("""COMMENT ON TABLE "public"."ogr_pgdump_14" IS 'baz';""") < 0: - gdaltest.post_reason('fail') - print(sql) - return 'fail' - - return 'success' + assert sql.find("""COMMENT ON TABLE "public"."ogr_pgdump_14" IS 'baz';""") >= 0 ############################################################################### # NULL vs unset -def ogr_pgdump_15(): +def test_ogr_pgdump_15(): ds = ogr.GetDriverByName('PGDump').CreateDataSource('/vsimem/ogr_pgdump_15.sql', options=['LINEFORMAT=LF']) lyr = ds.CreateLayer('test', geom_type=ogr.wkbNone) @@ -985,18 +877,14 @@ def ogr_pgdump_15(): gdal.Unlink('/vsimem/ogr_pgdump_15.sql') - if sql.find('INSERT INTO "public"."test" ("str") VALUES (NULL)') < 0 and \ - sql.find('INSERT INTO "public"."test" DEFAULT VALUES') < 0: - print(sql) - return 'fail' - - return 'success' + assert (sql.find('INSERT INTO "public"."test" ("str") VALUES (NULL)') >= 0 or \ + sql.find('INSERT INTO "public"."test" DEFAULT VALUES') >= 0) ############################################################################### # Test sequence updating -def ogr_pgdump_16(): +def test_ogr_pgdump_16(): for pg_use_copy in ('YES', 'NO'): @@ -1016,19 +904,15 @@ def ogr_pgdump_16(): gdal.Unlink('/vsimem/ogr_pgdump_16.sql') - if sql.find("""SELECT setval(pg_get_serial_sequence('"public"."test"', 'ogc_fid'), MAX("ogc_fid")) FROM "public"."test";""") < 0: - print(sql) - return 'fail' + assert sql.find("""SELECT setval(pg_get_serial_sequence('"public"."test"', 'ogc_fid'), MAX("ogc_fid")) FROM "public"."test";""") >= 0 gdal.SetConfigOption('PG_USE_COPY', None) - return 'success' - ############################################################################### # Cleanup -def ogr_pgdump_cleanup(): +def test_ogr_pgdump_cleanup(): try: os.remove('tmp/tpoly.sql') @@ -1038,33 +922,7 @@ def ogr_pgdump_cleanup(): os.remove('tmp/ogr_pgdump_4.sql') except OSError: pass - return 'success' - - -gdaltest_list = [ - ogr_pgdump_1, - ogr_pgdump_2, - ogr_pgdump_3, - ogr_pgdump_4, - ogr_pgdump_5, - ogr_pgdump_6, - ogr_pgdump_7, - ogr_pgdump_8, - ogr_pgdump_9, - ogr_pgdump_10, - ogr_pgdump_11, - ogr_pgdump_12, - ogr_pgdump_13, - ogr_pgdump_14, - ogr_pgdump_15, - ogr_pgdump_16, - ogr_pgdump_cleanup] - - -if __name__ == '__main__': + - gdaltest.setup_run('ogr_pgdump') - gdaltest.run_tests(gdaltest_list) - sys.exit(gdaltest.summarize()) diff --git a/autotest/ogr/ogr_pgeo.py b/autotest/ogr/ogr_pgeo.py index 9d0f08e25c04..ed9c63926e67 100755 --- a/autotest/ogr/ogr_pgeo.py +++ b/autotest/ogr/ogr_pgeo.py @@ -30,19 +30,33 @@ ############################################################################### import os -import sys from osgeo import ogr -sys.path.append('../pymod') import gdaltest import ogrtest +import pytest + + +@pytest.fixture( + params=['PGeo', 'MDB'], + autouse=True, +) +def drv(request): + """ + Run all tests against both PGeo and MDB drivers + """ + if request.param == 'PGeo': + switch_driver('PGeo', 'MDB') + else: + switch_driver('MDB', 'PGeo') + ############################################################################### # Basic testing -def ogr_pgeo_1(tested_driver='PGeo', other_driver='MDB'): +def switch_driver(tested_driver='PGeo', other_driver='MDB'): ogrtest.pgeo_ds = None @@ -64,10 +78,10 @@ def ogr_pgeo_1(tested_driver='PGeo', other_driver='MDB'): drv = ogr.GetDriverByName(tested_driver) if drv is None: - return 'skip' + pytest.skip("Driver not available: %s" % tested_driver) if not gdaltest.download_file('http://download.osgeo.org/gdal/data/pgeo/PGeoTest.zip', 'PGeoTest.zip'): - return 'skip' + pytest.skip() try: os.stat('tmp/cache/Autodesk Test.mdb') @@ -77,52 +91,39 @@ def ogr_pgeo_1(tested_driver='PGeo', other_driver='MDB'): try: os.stat('tmp/cache/Autodesk Test.mdb') except OSError: - return 'skip' + pytest.skip() except: - return 'skip' + pytest.skip() ogrtest.pgeo_ds = ogr.Open('tmp/cache/Autodesk Test.mdb') if ogrtest.pgeo_ds is None: - gdaltest.post_reason('could not open DB. Driver probably misconfigured') - return 'skip' + pytest.skip('could not open DB. Driver probably misconfigured') - if ogrtest.pgeo_ds.GetLayerCount() != 3: - gdaltest.post_reason('did not get expected layer count') - return 'fail' + assert ogrtest.pgeo_ds.GetLayerCount() == 3, 'did not get expected layer count' lyr = ogrtest.pgeo_ds.GetLayer(0) feat = lyr.GetNextFeature() if feat.GetField('OBJECTID') != 1 or \ feat.GetField('IDNUM') != 9424 or \ feat.GetField('OWNER') != 'City': - gdaltest.post_reason('did not get expected attributes') feat.DumpReadable() - return 'fail' + pytest.fail('did not get expected attributes') if ogrtest.check_feature_geometry(feat, 'LINESTRING (1910941.703951031 445833.57942859828 0,1910947.927691862 445786.43811868131 0)', max_error=0.0000001) != 0: - gdaltest.post_reason('did not get expected geometry') feat.DumpReadable() - return 'fail' + pytest.fail('did not get expected geometry') feat_count = lyr.GetFeatureCount() - if feat_count != 9418: - gdaltest.post_reason('did not get expected feature count') - print(feat_count) - return 'fail' - - return 'success' + assert feat_count == 9418, 'did not get expected feature count' -def ogr_pgeo_mdb_1(): - return ogr_pgeo_1('MDB', 'PGeo') - ############################################################################### # Test spatial filter -def ogr_pgeo_2(): +def test_ogr_pgeo_2(): if ogrtest.pgeo_ds is None: - return 'skip' + pytest.skip() lyr = ogrtest.pgeo_ds.GetLayer(0) lyr.ResetReading() @@ -133,199 +134,125 @@ def ogr_pgeo_2(): lyr.SetSpatialFilterRect(bbox[0], bbox[1], bbox[2], bbox[3]) feat_count = lyr.GetFeatureCount() - if feat_count != 6957: - gdaltest.post_reason('did not get expected feature count') - print(feat_count) - return 'fail' + assert feat_count == 6957, 'did not get expected feature count' feat = lyr.GetNextFeature() if feat.GetField('OBJECTID') != 1 or \ feat.GetField('IDNUM') != 9424 or \ feat.GetField('OWNER') != 'City': - gdaltest.post_reason('did not get expected attributes') feat.DumpReadable() - return 'fail' + pytest.fail('did not get expected attributes') # Check that geometry filter is well cleared lyr.SetSpatialFilter(None) feat_count = lyr.GetFeatureCount() - if feat_count != 9418: - gdaltest.post_reason('did not get expected feature count') - print(feat_count) - return 'fail' - - return 'success' + assert feat_count == 9418, 'did not get expected feature count' ############################################################################### # Test attribute filter -def ogr_pgeo_3(): +def test_ogr_pgeo_3(): if ogrtest.pgeo_ds is None: - return 'skip' + pytest.skip() lyr = ogrtest.pgeo_ds.GetLayer(0) lyr.SetAttributeFilter('OBJECTID=1') feat_count = lyr.GetFeatureCount() - if feat_count != 1: - gdaltest.post_reason('did not get expected feature count') - print(feat_count) - return 'fail' + assert feat_count == 1, 'did not get expected feature count' feat = lyr.GetNextFeature() if feat.GetField('OBJECTID') != 1 or \ feat.GetField('IDNUM') != 9424 or \ feat.GetField('OWNER') != 'City': - gdaltest.post_reason('did not get expected attributes') feat.DumpReadable() - return 'fail' + pytest.fail('did not get expected attributes') # Check that attribute filter is well cleared (#3706) lyr.SetAttributeFilter(None) feat_count = lyr.GetFeatureCount() - if feat_count != 9418: - gdaltest.post_reason('did not get expected feature count') - print(feat_count) - return 'fail' - - return 'success' + assert feat_count == 9418, 'did not get expected feature count' ############################################################################### # Test ExecuteSQL() -def ogr_pgeo_4(): +def test_ogr_pgeo_4(): if ogrtest.pgeo_ds is None: - return 'skip' + pytest.skip() sql_lyr = ogrtest.pgeo_ds.ExecuteSQL('SELECT * FROM SDPipes WHERE OBJECTID = 1') feat_count = sql_lyr.GetFeatureCount() - if feat_count != 1: - gdaltest.post_reason('did not get expected feature count') - print(feat_count) - return 'fail' + assert feat_count == 1, 'did not get expected feature count' feat = sql_lyr.GetNextFeature() if feat.GetField('OBJECTID') != 1 or \ feat.GetField('IDNUM') != 9424 or \ feat.GetField('OWNER') != 'City': - gdaltest.post_reason('did not get expected attributes') feat.DumpReadable() - return 'fail' + pytest.fail('did not get expected attributes') ogrtest.pgeo_ds.ReleaseResultSet(sql_lyr) - return 'success' - ############################################################################### # Test GetFeature() -def ogr_pgeo_5(): +def test_ogr_pgeo_5(): if ogrtest.pgeo_ds is None: - return 'skip' + pytest.skip() lyr = ogrtest.pgeo_ds.GetLayer(0) feat = lyr.GetFeature(9418) if feat.GetField('OBJECTID') != 9418: - gdaltest.post_reason('did not get expected attributes') feat.DumpReadable() - return 'fail' - - return 'success' + pytest.fail('did not get expected attributes') + ############################################################################### # Run test_ogrsf -def ogr_pgeo_6(): +def test_ogr_pgeo_6(): if ogrtest.pgeo_ds is None: - return 'skip' + pytest.skip() import test_cli_utilities if test_cli_utilities.get_test_ogrsf_path() is None: - return 'skip' + pytest.skip() ret = gdaltest.runexternal(test_cli_utilities.get_test_ogrsf_path() + ' "tmp/cache/Autodesk Test.mdb"') - if ret.find('INFO') == -1 or ret.find('ERROR') != -1: - print(ret) - return 'fail' - - return 'success' + assert ret.find('INFO') != -1 and ret.find('ERROR') == -1 ############################################################################### # Run test_ogrsf with -sql -def ogr_pgeo_7(): +def test_ogr_pgeo_7(): if ogrtest.pgeo_ds is None: - return 'skip' + pytest.skip() import test_cli_utilities if test_cli_utilities.get_test_ogrsf_path() is None: - return 'skip' + pytest.skip() ret = gdaltest.runexternal(test_cli_utilities.get_test_ogrsf_path() + ' "tmp/cache/Autodesk Test.mdb" -sql "SELECT * FROM SDPipes"') - if ret.find('INFO') == -1 or ret.find('ERROR') != -1: - print(ret) - return 'fail' - - return 'success' + assert ret.find('INFO') != -1 and ret.find('ERROR') == -1 ############################################################################### -def ogr_pgeo_cleanup(): +def test_ogr_pgeo_cleanup(): if ogrtest.other_driver is not None: print('Reregistering %s driver' % ogrtest.other_driver.GetName()) ogrtest.other_driver.Register() if ogrtest.pgeo_ds is None: - return 'skip' + pytest.skip() ogrtest.pgeo_ds = None - return 'success' - - -gdaltest_list_internal = [ - ogr_pgeo_2, - ogr_pgeo_3, - ogr_pgeo_4, - ogr_pgeo_5, - ogr_pgeo_6, - ogr_pgeo_7, - ogr_pgeo_cleanup] - -############################################################################### -# - - -def ogr_pgeo_main(): - - # Run with the PGeo driver only (MDB disabled) - gdaltest.run_tests([ogr_pgeo_1]) - gdaltest.run_tests(gdaltest_list_internal) - - # Run with the MDB driver only (PGeo disabled) - gdaltest.run_tests([ogr_pgeo_mdb_1]) - gdaltest.run_tests(gdaltest_list_internal) - - return 'success' - - -gdaltest_list = [ - ogr_pgeo_main -] - -if __name__ == '__main__': - - gdaltest.setup_run('ogr_pgeo') - - gdaltest.run_tests(gdaltest_list) - - sys.exit(gdaltest.summarize()) diff --git a/autotest/ogr/ogr_plscenes.py b/autotest/ogr/ogr_plscenes.py index 95d90b5f53a9..c192413845c0 100755 --- a/autotest/ogr/ogr_plscenes.py +++ b/autotest/ogr/ogr_plscenes.py @@ -29,115 +29,86 @@ # DEALINGS IN THE SOFTWARE. ############################################################################### -import sys -sys.path.append('../pymod') from osgeo import ogr from osgeo import gdal import gdaltest +import pytest ############################################################################### # Find PLScenes driver -def ogr_plscenes_init(): +def test_ogr_plscenes_init(): gdaltest.plscenes_drv = ogr.GetDriverByName('PLScenes') if gdaltest.plscenes_drv is not None: - return 'success' - return 'skip' + return + pytest.skip() ############################################################################### # Test Data V1 API catalog listing with a single catalog -def ogr_plscenes_data_v1_catalog_no_paging(): +def test_ogr_plscenes_data_v1_catalog_no_paging(): if gdaltest.plscenes_drv is None: - return 'skip' + pytest.skip() gdal.FileFromMemBuffer('/vsimem/data_v1/item-types', '{ "item_types": [ { "id": "PSScene3Band" } ] }') gdal.SetConfigOption('PL_URL', '/vsimem/data_v1/') ds = gdal.OpenEx('PLScenes:', gdal.OF_VECTOR, open_options=['VERSION=data_v1', 'API_KEY=foo']) gdal.SetConfigOption('PL_URL', None) - if ds is None: - gdaltest.post_reason('fail') - return 'fail' + assert ds is not None with gdaltest.error_handler(): - if ds.GetLayerByName('non_existing') is not None: - gdaltest.post_reason('fail') - return 'fail' - if ds.GetLayerByName('PSScene3Band') is None: - gdaltest.post_reason('fail') - return 'fail' - if ds.GetLayerCount() != 1: - gdaltest.post_reason('fail') - return 'fail' + assert ds.GetLayerByName('non_existing') is None + assert ds.GetLayerByName('PSScene3Band') is not None + assert ds.GetLayerCount() == 1 with gdaltest.error_handler(): - if ds.GetLayerByName('non_existing') is not None: - gdaltest.post_reason('fail') - return 'fail' + assert ds.GetLayerByName('non_existing') is None gdal.Unlink('/vsimem/data_v1/item-types') - return 'success' - ############################################################################### # Test Data V1 API catalog listing with catalog paging -def ogr_plscenes_data_v1_catalog_paging(): +def test_ogr_plscenes_data_v1_catalog_paging(): if gdaltest.plscenes_drv is None: - return 'skip' + pytest.skip() gdal.FileFromMemBuffer('/vsimem/data_v1/item-types', '{"_links": { "_next" : "/vsimem/data_v1/item-types/page_2"}, "item_types": [ { "id": "PSScene3Band" } ] }') gdal.FileFromMemBuffer('/vsimem/data_v1/item-types/page_2', '{ "item_types": [ { "id": "PSScene4Band" } ] }') gdal.SetConfigOption('PL_URL', '/vsimem/data_v1/') ds = gdal.OpenEx('PLScenes:', gdal.OF_VECTOR, open_options=['VERSION=data_v1', 'API_KEY=foo']) gdal.SetConfigOption('PL_URL', None) - if ds is None: - gdaltest.post_reason('fail') - return 'fail' + assert ds is not None with gdaltest.error_handler(): - if ds.GetLayerByName('non_existing') is not None: - gdaltest.post_reason('fail') - return 'fail' - if ds.GetLayerByName('PSScene3Band') is None: - gdaltest.post_reason('fail') - return 'fail' + assert ds.GetLayerByName('non_existing') is None + assert ds.GetLayerByName('PSScene3Band') is not None gdal.FileFromMemBuffer('/vsimem/data_v1/item-types/PSScene4Band', '{ "id": "PSScene4Band"} }') - if ds.GetLayerByName('PSScene4Band') is None: - gdaltest.post_reason('fail') - return 'fail' - if ds.GetLayerCount() != 2: - gdaltest.post_reason('fail') - return 'fail' - if ds.GetLayerByName('PSScene4Band') is None: - gdaltest.post_reason('fail') - return 'fail' + assert ds.GetLayerByName('PSScene4Band') is not None + assert ds.GetLayerCount() == 2 + assert ds.GetLayerByName('PSScene4Band') is not None with gdaltest.error_handler(): - if ds.GetLayerByName('non_existing') is not None: - gdaltest.post_reason('fail') - return 'fail' + assert ds.GetLayerByName('non_existing') is None gdal.Unlink('/vsimem/data_v1/item-types') gdal.Unlink('/vsimem/data_v1/item-types/page_2') gdal.Unlink('/vsimem/data_v1/item-types/PSScene4Band') - return 'success' - ############################################################################### # Test Data V1 API -def ogr_plscenes_data_v1_nominal(): +def test_ogr_plscenes_data_v1_nominal(): if gdaltest.plscenes_drv is None: - return 'skip' + pytest.skip() gdal.FileFromMemBuffer('/vsimem/data_v1/item-types', """{ "item_types": [ @@ -148,47 +119,29 @@ def ogr_plscenes_data_v1_nominal(): gdal.SetConfigOption('PL_URL', '/vsimem/data_v1/') ds = gdal.OpenEx('PLScenes:', gdal.OF_VECTOR, open_options=['VERSION=data_v1', 'API_KEY=foo']) gdal.SetConfigOption('PL_URL', None) - if ds is None: - gdaltest.post_reason('fail') - return 'fail' + assert ds is not None gdal.SetConfigOption('PL_URL', '/vsimem/data_v1/') ds = gdal.OpenEx('PLScenes:version=data_v1,api_key=foo,FOLLOW_LINKS=YES', gdal.OF_VECTOR) gdal.SetConfigOption('PL_URL', None) - if ds is None: - gdaltest.post_reason('fail') - return 'fail' + assert ds is not None lyr = ds.GetLayer(0) - if lyr.GetName() != 'PSOrthoTile': - gdaltest.post_reason('fail') - return 'fail' - if lyr.TestCapability(ogr.OLCFastFeatureCount) != 1 or \ - lyr.TestCapability(ogr.OLCStringsAsUTF8) != 1 or \ - lyr.TestCapability(ogr.OLCRandomRead) != 0: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.GetName() == 'PSOrthoTile' + assert (lyr.TestCapability(ogr.OLCFastFeatureCount) == 1 and \ + lyr.TestCapability(ogr.OLCStringsAsUTF8) == 1 and \ + lyr.TestCapability(ogr.OLCRandomRead) == 0) # Different serialization depending on libjson versions gdal.FileFromMemBuffer("""/vsimem/data_v1/stats&POSTFIELDS={"interval":"year","item_types":["PSOrthoTile"],"filter":{"type":"AndFilter","config":[{"type":"RangeFilter","field_name":"cloud_cover","config":{"gte":0.000000}}]}}""", """{ "buckets": [ { "count": 1 }, { "count": 1} ] }""") gdal.FileFromMemBuffer("""/vsimem/data_v1/stats&POSTFIELDS={"interval":"year","item_types":["PSOrthoTile"],"filter":{"type":"AndFilter","config":[{"type":"RangeFilter","field_name":"cloud_cover","config":{"gte":0}}]}}""", """{ "buckets": [ { "count": 1 }, { "count": 1} ] }""") gdal.FileFromMemBuffer("""/vsimem/data_v1/stats&POSTFIELDS={"interval":"year","item_types":["PSOrthoTile"],"filter":{"type":"AndFilter","config":[{"type":"RangeFilter","field_name":"cloud_cover","config":{"gte":0.0}}]}}""", """{ "buckets": [ { "count": 1 }, { "count": 1} ] }""") - if lyr.GetFeatureCount() != 2: - gdaltest.post_reason('fail') - return 'fail' - if lyr.GetGeomType() != ogr.wkbMultiPolygon: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.GetFeatureCount() == 2 + assert lyr.GetGeomType() == ogr.wkbMultiPolygon ext = lyr.GetExtent() - if ext != (-180.0, 180.0, -90.0, 90.0): - gdaltest.post_reason('fail') - print(ext) - return 'fail' + assert ext == (-180.0, 180.0, -90.0, 90.0) field_count = lyr.GetLayerDefn().GetFieldCount() - if field_count != 68: - gdaltest.post_reason('fail') - print(field_count) - return 'fail' + assert field_count == 68 # Regular /items/ fetching gdal.FileFromMemBuffer("""/vsimem/data_v1/quick-search?_page_size=250&POSTFIELDS={"item_types":["PSOrthoTile"],"filter":{"type":"AndFilter","config":[]}}""", @@ -253,16 +206,14 @@ def ogr_plscenes_data_v1_nominal(): f['asset_analytic_location'] != '/vsimem/data_v1/item-types/PSOrthoTile/items/id/assets/analytic/my.tiff' or \ f['asset_analytic_status'] != 'active' or \ f.GetGeometryRef().ExportToWkt() != 'MULTIPOLYGON (((2 49,2.0 49.1,2.1 49.1,2.1 49.0,2 49)))': - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' + pytest.fail() lyr.ResetReading() f = lyr.GetNextFeature() if f.GetFID() != 1: - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' + pytest.fail() gdal.FileFromMemBuffer('/vsimem/data_v1/quick-search?page=2', """{ @@ -275,32 +226,25 @@ def ogr_plscenes_data_v1_nominal(): f = lyr.GetNextFeature() if f.GetFID() != 2 or f['id'] != 'id2': - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' + pytest.fail() lyr.ResetReading() f = lyr.GetNextFeature() if f.GetFID() != 1: - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' + pytest.fail() f = lyr.GetNextFeature() if f.GetFID() != 2: - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' + pytest.fail() f = lyr.GetNextFeature() - if f is not None: - gdaltest.post_reason('fail') - return 'fail' + assert f is None f = lyr.GetNextFeature() - if f is not None: - gdaltest.post_reason('fail') - return 'fail' + assert f is None gdal.FileFromMemBuffer("""/vsimem/data_v1/quick-search?_page_size=250&POSTFIELDS={"item_types":["PSOrthoTile"],"filter":{"type":"AndFilter","config":[{"type":"GeometryFilter","field_name":"geometry","config":{"type":"Point","coordinates":[2.0,49.0]}}]}}""", """{"features" : [ { "id": "id3", "geometry": { "type": "Point", "coordinates": [2,49]} } ] }""") @@ -309,23 +253,19 @@ def ogr_plscenes_data_v1_nominal(): lyr.SetSpatialFilterRect(2, 49, 2, 49) f = lyr.GetNextFeature() if f['id'] != 'id3': - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' + pytest.fail() # Cannot find /vsimem/data_v1/stats&POSTFIELDS={"interval":"year","item_types":["PSOrthoTile"],"filter":{"type":"AndFilter","config":[{"type":"GeometryFilter","field_name":"geometry","config":{"type":"Point","coordinates":[2.0,49.0]}}]}} with gdaltest.error_handler(): - if lyr.GetFeatureCount() != 1: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.GetFeatureCount() == 1 # Reset spatial filter lyr.SetSpatialFilter(0, None) f = lyr.GetNextFeature() if f['id'] != 'id': - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' + pytest.fail() # Test attribute filter on id lyr.SetAttributeFilter("id = 'filtered_id'") @@ -337,9 +277,8 @@ def ogr_plscenes_data_v1_nominal(): f = lyr.GetNextFeature() if f['id'] != 'filtered_id': - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' + pytest.fail() # Test attribute filter fully evaluated on server side. lyr.SetAttributeFilter("id != 'a' AND acquired >= '2016/02/11' AND acquired <= '2016/02/12' AND acquired > '1970/01/01 01:23:45' AND acquired < '2100/01/01 01:23:45' AND anomalous_pixels = 1.234567 AND (NOT id = 'b') AND columns > 0 AND columns < 2 AND columns = 1 AND columns IN (1, 2) AND (id IN ('filtered_2') OR id = 'foo') AND permissions = 'download' AND permissions IN ('download')") @@ -370,9 +309,8 @@ def ogr_plscenes_data_v1_nominal(): gdal.FileFromMemBuffer("""/vsimem/data_v1/quick-search?_page_size=250&POSTFIELDS={"item_types":["PSOrthoTile"],"filter":{"type":"AndFilter","config":[{"type":"AndFilter","config":[{"type":"AndFilter","config":[{"type":"AndFilter","config":[{"type":"AndFilter","config":[{"type":"AndFilter","config":[{"type":"AndFilter","config":[{"type":"AndFilter","config":[{"type":"AndFilter","config":[{"type":"AndFilter","config":[{"type":"AndFilter","config":[{"type":"AndFilter","config":[{"type":"AndFilter","config":[{"type":"AndFilter","config":[{"type":"NotFilter","config":{"type":"StringInFilter","field_name":"id","config":["a"]}},{"type":"DateRangeFilter","field_name":"acquired","config":{"gte":"2016-02-11T00:00:00Z"}}]},{"type":"DateRangeFilter","field_name":"acquired","config":{"lte":"2016-02-12T00:00:00Z"}}]},{"type":"DateRangeFilter","field_name":"acquired","config":{"gt":"1970-01-01T01:23:45Z"}}]},{"type":"DateRangeFilter","field_name":"acquired","config":{"lt":"2100-01-01T01:23:45Z"}}]},{"type":"RangeFilter","field_name":"anomalous_pixels","config":{"gte":1.23456699,"lte":1.2345670099999999}}]},{"type":"NotFilter","config":{"type":"StringInFilter","field_name":"id","config":["b"]}}]},{"type":"RangeFilter","field_name":"columns","config":{"gt":0}}]},{"type":"RangeFilter","field_name":"columns","config":{"lt":2}}]},{"type":"NumberInFilter","field_name":"columns","config":[1]}]},{"type":"NumberInFilter","field_name":"columns","config":[1,2]}]},{"type":"OrFilter","config":[{"type":"StringInFilter","field_name":"id","config":["filtered_2"]},{"type":"StringInFilter","field_name":"id","config":["foo"]}]}]},{"type":"PermissionFilter","config":["download"]}]},{"type":"PermissionFilter","config":["download"]}]}]}}""", content) f = lyr.GetNextFeature() if f['id'] != 'filtered_2': - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' + pytest.fail() # Partly server / partly client lyr.SetAttributeFilter("id = 'filtered_3' AND id > 'a'") @@ -388,40 +326,35 @@ def ogr_plscenes_data_v1_nominal(): }""") f = lyr.GetNextFeature() if f['id'] != 'filtered_3': - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' + pytest.fail() lyr.SetAttributeFilter("id > 'a' AND id = 'filtered_3'") f = lyr.GetNextFeature() if f['id'] != 'filtered_3': - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' + pytest.fail() # Completely client side lyr.SetAttributeFilter("id > 'a' OR id = 'id'") f = lyr.GetNextFeature() if f['id'] != 'id': - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' + pytest.fail() # Completely client side lyr.SetAttributeFilter("NOT id > 'z'") f = lyr.GetNextFeature() if f['id'] != 'id': - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' + pytest.fail() # Reset attribute filter lyr.SetAttributeFilter(None) f = lyr.GetNextFeature() if f['id'] != 'id': - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' + pytest.fail() # Try raster access @@ -430,9 +363,7 @@ def ogr_plscenes_data_v1_nominal(): with gdaltest.error_handler(): ds_raster = gdal.OpenEx('PLScenes:', gdal.OF_RASTER, open_options=['VERSION=data_v1', 'API_KEY=foo', 'SCENE=id']) gdal.SetConfigOption('PL_URL', None) - if ds_raster is not None or gdal.GetLastErrorMsg().find('Missing catalog') < 0: - gdaltest.post_reason('fail') - return 'fail' + assert ds_raster is None and gdal.GetLastErrorMsg().find('Missing catalog') >= 0 # Invalid catalog gdal.SetConfigOption('PL_URL', '/vsimem/data_v1/') @@ -447,9 +378,7 @@ def ogr_plscenes_data_v1_nominal(): with gdaltest.error_handler(): ds_raster = gdal.OpenEx('PLScenes:', gdal.OF_RASTER, open_options=['VERSION=data_v1', 'API_KEY=foo', 'ITEMTYPES=PSOrthoTile', 'SCENE=id']) gdal.SetConfigOption('PL_URL', None) - if ds_raster is not None: - gdaltest.post_reason('fail') - return 'fail' + assert ds_raster is None # Inactive file, and activation link not working gdal.FileFromMemBuffer('/vsimem/data_v1/item-types/PSOrthoTile/items/id/assets', @@ -467,9 +396,7 @@ def ogr_plscenes_data_v1_nominal(): with gdaltest.error_handler(): ds_raster = gdal.OpenEx('PLScenes:', gdal.OF_RASTER, open_options=['VERSION=data_v1', 'API_KEY=foo', 'ITEMTYPES=PSOrthoTile', 'SCENE=id', 'ACTIVATION_TIMEOUT=1', 'ASSET=analytic']) gdal.SetConfigOption('PL_URL', None) - if ds_raster is not None: - gdaltest.post_reason('fail') - return 'fail' + assert ds_raster is None # File in activation gdal.FileFromMemBuffer('/vsimem/data_v1/item-types/PSOrthoTile/items/id/assets', @@ -487,9 +414,7 @@ def ogr_plscenes_data_v1_nominal(): with gdaltest.error_handler(): ds_raster = gdal.OpenEx('PLScenes:', gdal.OF_RASTER, open_options=['VERSION=data_v1', 'API_KEY=foo', 'ITEMTYPES=PSOrthoTile', 'SCENE=id', 'ACTIVATION_TIMEOUT=1', 'ASSET=analytic']) gdal.SetConfigOption('PL_URL', None) - if ds_raster is not None: - gdaltest.post_reason('fail') - return 'fail' + assert ds_raster is None gdal.FileFromMemBuffer('/vsimem/data_v1/item-types/PSOrthoTile/items/id/assets', """{ @@ -510,9 +435,7 @@ def ogr_plscenes_data_v1_nominal(): with gdaltest.error_handler(): ds_raster = gdal.OpenEx('PLScenes:', gdal.OF_RASTER, open_options=['VERSION=data_v1', 'API_KEY=foo', 'ITEMTYPES=PSOrthoTile', 'SCENE=id', 'ACTIVATION_TIMEOUT=1', 'ASSET=analytic']) gdal.SetConfigOption('PL_URL', None) - if ds_raster is not None: - gdaltest.post_reason('fail') - return 'fail' + assert ds_raster is None # JSon content for /vsimem/data_v1/item-types/PSOrthoTile/items/id/assets/analytic/my.tiff gdal.FileFromMemBuffer('/vsimem/data_v1/item-types/PSOrthoTile/items/id/assets/analytic/my.tiff', @@ -521,9 +444,7 @@ def ogr_plscenes_data_v1_nominal(): with gdaltest.error_handler(): ds_raster = gdal.OpenEx('PLScenes:', gdal.OF_RASTER, open_options=['VERSION=data_v1', 'API_KEY=foo', 'ITEMTYPES=PSOrthoTile', 'SCENE=id', 'ACTIVATION_TIMEOUT=1', 'ASSET=analytic']) gdal.SetConfigOption('PL_URL', None) - if ds_raster is not None: - gdaltest.post_reason('fail') - return 'fail' + assert ds_raster is None # Missing metadata gdal.FileFromMemBuffer('/vsimem/data_v1/item-types/PSOrthoTile/items/id/assets/analytic/my.tiff', @@ -532,9 +453,7 @@ def ogr_plscenes_data_v1_nominal(): with gdaltest.error_handler(): ds_raster = gdal.OpenEx('PLScenes:', gdal.OF_RASTER, open_options=['VERSION=data_v1', 'API_KEY=foo', 'ITEMTYPES=PSOrthoTile', 'SCENE=id', 'ACTIVATION_TIMEOUT=1', 'ASSET=analytic']) gdal.SetConfigOption('PL_URL', None) - if ds_raster is None: - gdaltest.post_reason('fail') - return 'fail' + assert ds_raster is not None ds_raster = None # Failed filter by scene id @@ -543,9 +462,7 @@ def ogr_plscenes_data_v1_nominal(): gdal.SetConfigOption('PL_URL', '/vsimem/data_v1/') ds_raster = gdal.OpenEx('PLScenes:', gdal.OF_RASTER, open_options=['VERSION=data_v1', 'API_KEY=foo', 'ITEMTYPES=PSOrthoTile', 'SCENE=id', 'ACTIVATION_TIMEOUT=1', 'ASSET=analytic']) gdal.SetConfigOption('PL_URL', None) - if ds_raster is None: - gdaltest.post_reason('fail') - return 'fail' + assert ds_raster is not None ds_raster = None # Test metadata items attached to dataset @@ -559,12 +476,8 @@ def ogr_plscenes_data_v1_nominal(): gdal.SetConfigOption('PL_URL', '/vsimem/data_v1/') ds_raster = gdal.OpenEx('PLScenes:', gdal.OF_RASTER, open_options=['VERSION=data_v1', 'API_KEY=foo', 'ITEMTYPES=PSOrthoTile', 'SCENE=id', 'ACTIVATION_TIMEOUT=1', 'ASSET=analytic']) gdal.SetConfigOption('PL_URL', None) - if ds_raster is None: - gdaltest.post_reason('fail') - return 'fail' - if ds_raster.GetMetadataItem('anomalous_pixels') != '1.23': - gdaltest.post_reason('fail') - return 'fail' + assert ds_raster is not None + assert ds_raster.GetMetadataItem('anomalous_pixels') == '1.23' ds_raster = None # Test invalid ASSET @@ -572,17 +485,13 @@ def ogr_plscenes_data_v1_nominal(): with gdaltest.error_handler(): ds_raster = gdal.OpenEx('PLScenes:', gdal.OF_RASTER, open_options=['VERSION=data_v1', 'API_KEY=foo', 'ITEMTYPES=PSOrthoTile', 'SCENE=id', 'ACTIVATION_TIMEOUT=1', 'ASSET=invalid']) gdal.SetConfigOption('PL_URL', None) - if ds_raster is not None: - gdaltest.post_reason('fail') - return 'fail' + assert ds_raster is None # Test subdatasets gdal.SetConfigOption('PL_URL', '/vsimem/data_v1/') ds_raster = gdal.OpenEx('PLScenes:', gdal.OF_RASTER, open_options=['VERSION=data_v1', 'API_KEY=foo', 'ITEMTYPES=PSOrthoTile', 'ASSET=list', 'SCENE=id']) gdal.SetConfigOption('PL_URL', None) - if len(ds_raster.GetSubDatasets()) != 1: - gdaltest.post_reason('fail') - return 'fail' + assert len(ds_raster.GetSubDatasets()) == 1 ds_raster = None # Unsupported option @@ -590,40 +499,33 @@ def ogr_plscenes_data_v1_nominal(): with gdaltest.error_handler(): ds_raster = gdal.OpenEx('PLScenes:unsupported=yes', gdal.OF_RASTER, open_options=['VERSION=data_v1', 'API_KEY=foo', 'ITEMTYPES=PSOrthoTile', 'SCENE=id']) gdal.SetConfigOption('PL_URL', None) - if ds_raster is not None: - gdaltest.post_reason('fail') - return 'fail' + assert ds_raster is None # Test catalog with vector access gdal.SetConfigOption('PL_URL', '/vsimem/data_v1/') ds2 = gdal.OpenEx('PLScenes:', gdal.OF_VECTOR, open_options=['VERSION=data_v1', 'API_KEY=foo', 'ITEMTYPES=PSOrthoTile']) gdal.SetConfigOption('PL_URL', None) - if ds2 is None or ds2.GetLayerCount() != 1: - gdaltest.post_reason('fail') - return 'fail' + assert ds2 is not None and ds2.GetLayerCount() == 1 gdal.SetConfigOption('PL_URL', '/vsimem/data_v1/') with gdaltest.error_handler(): ds2 = gdal.OpenEx('PLScenes:', gdal.OF_VECTOR, open_options=['VERSION=data_v1', 'API_KEY=foo', 'ITEMTYPES=invalid']) gdal.SetConfigOption('PL_URL', None) - if ds2 is not None: - gdaltest.post_reason('fail') - return 'fail' + assert ds2 is None fl = gdal.ReadDir('/vsimem/data_v1') for filename in fl: gdal.Unlink(filename) - return 'success' - + ############################################################################### # Test robustness to errors in Data V1 API -def ogr_plscenes_data_v1_errors(): +def test_ogr_plscenes_data_v1_errors(): if gdaltest.plscenes_drv is None: - return 'skip' + pytest.skip() # No PL_API_KEY gdal.SetConfigOption('PL_URL', '/vsimem/data_v1/') @@ -635,9 +537,7 @@ def ogr_plscenes_data_v1_errors(): if old_key: gdal.SetConfigOption('PL_API_KEY', old_key) gdal.SetConfigOption('PL_URL', None) - if ds is not None: - gdaltest.post_reason('fail') - return 'fail' + assert ds is None # Invalid option gdal.FileFromMemBuffer('/vsimem/data_v1/item-types', '{ "item-types": [] }') @@ -645,9 +545,7 @@ def ogr_plscenes_data_v1_errors(): gdal.SetConfigOption('PL_URL', '/vsimem/data_v1/') ds = gdal.OpenEx('PLScenes:version=data_v1,api_key=foo,invalid=invalid', gdal.OF_VECTOR) gdal.SetConfigOption('PL_URL', None) - if ds is not None: - gdaltest.post_reason('fail') - return 'fail' + assert ds is None # Invalid JSON gdal.FileFromMemBuffer('/vsimem/data_v1/item-types', '{invalid_json') @@ -655,9 +553,7 @@ def ogr_plscenes_data_v1_errors(): gdal.SetConfigOption('PL_URL', '/vsimem/data_v1/') ds = gdal.OpenEx('PLScenes:', gdal.OF_VECTOR, open_options=['VERSION=data_v1', 'API_KEY=foo']) gdal.SetConfigOption('PL_URL', None) - if ds is not None: - gdaltest.post_reason('fail') - return 'fail' + assert ds is None # Not an object gdal.FileFromMemBuffer('/vsimem/data_v1/item-types', 'false') @@ -665,9 +561,7 @@ def ogr_plscenes_data_v1_errors(): gdal.SetConfigOption('PL_URL', '/vsimem/data_v1/') ds = gdal.OpenEx('PLScenes:', gdal.OF_VECTOR, open_options=['VERSION=data_v1', 'API_KEY=foo']) gdal.SetConfigOption('PL_URL', None) - if ds is not None: - gdaltest.post_reason('fail') - return 'fail' + assert ds is None # Lack of "item_types" gdal.FileFromMemBuffer('/vsimem/data_v1/item-types', '{}') @@ -675,9 +569,7 @@ def ogr_plscenes_data_v1_errors(): gdal.SetConfigOption('PL_URL', '/vsimem/data_v1/') ds = gdal.OpenEx('PLScenes:', gdal.OF_VECTOR, open_options=['VERSION=data_v1', 'API_KEY=foo']) gdal.SetConfigOption('PL_URL', None) - if ds is not None: - gdaltest.post_reason('fail') - return 'fail' + assert ds is None # Invalid catalog objects gdal.FileFromMemBuffer('/vsimem/data_v1/item-types', """{"item_types": [{}, [], null, {"id":null}, @@ -685,9 +577,7 @@ def ogr_plscenes_data_v1_errors(): gdal.SetConfigOption('PL_URL', '/vsimem/data_v1/') ds = gdal.OpenEx('PLScenes:', gdal.OF_VECTOR, open_options=['VERSION=data_v1', 'API_KEY=foo']) gdal.SetConfigOption('PL_URL', None) - if ds.GetLayerCount() != 1: - gdaltest.post_reason('fail') - return 'fail' + assert ds.GetLayerCount() == 1 # Invalid next URL gdal.FileFromMemBuffer('/vsimem/data_v1/item-types', '{"_links": { "_next": "/vsimem/inexisting" }, "item_types": [{"id": "my_catalog"}]}') @@ -696,9 +586,7 @@ def ogr_plscenes_data_v1_errors(): gdal.SetConfigOption('PL_URL', None) with gdaltest.error_handler(): lyr_count = ds.GetLayerCount() - if lyr_count != 1: - gdaltest.post_reason('fail') - return 'fail' + assert lyr_count == 1 gdal.FileFromMemBuffer('/vsimem/data_v1/item-types', '{"item_types": [{"id": "PSScene3Band"}]}') gdal.SetConfigOption('PL_URL', '/vsimem/data_v1/') @@ -730,39 +618,30 @@ def ogr_plscenes_data_v1_errors(): gdal.Unlink('/vsimem/data_v1/item-types') gdal.Unlink('/vsimem/data_v1/quick-search?_page_size=250&POSTFIELDS={"item_types":["PSScene3Band"],"filter":{"type":"AndFilter","config":[]}}') - return 'success' - ############################################################################### # Test Data V1 API against real server -def ogr_plscenes_data_v1_live(): +def test_ogr_plscenes_data_v1_live(): if gdaltest.plscenes_drv is None: - return 'skip' + pytest.skip() api_key = gdal.GetConfigOption('PL_API_KEY') if api_key is None: - print('Skipping test as PL_API_KEY not defined') - return 'skip' + pytest.skip('Skipping test as PL_API_KEY not defined') gdal.SetConfigOption('PLSCENES_PAGE_SIZE', '10') ds = ogr.Open('PLScenes:version=data_v1,FOLLOW_LINKS=YES') gdal.SetConfigOption('PLSCENES_PAGE_SIZE', None) - if ds is None: - gdaltest.post_reason('fail') - return 'fail' + assert ds is not None lyr = ds.GetLayer(0) - if lyr is None: - gdaltest.post_reason('fail') - return 'fail' + assert lyr is not None lyr.SetAttributeFilter("permissions = 'assets:download'") f = lyr.GetNextFeature() - if f is None: - gdaltest.post_reason('fail') - return 'fail' + assert f is not None catalog = lyr.GetName() scene = f['id'] f.DumpReadable() @@ -778,19 +657,14 @@ def ogr_plscenes_data_v1_live(): elif name.startswith('asset_') and name.endswith('_location') and f.GetFieldAsString(i) != '': asset_name = name[len('asset_'):-len('_location')] break - if asset_name is None: - gdaltest.post_reason('fail') - return 'fail' + assert asset_name is not None acquired_field = lyr_defn.GetFieldIndex('acquired') - if acquired_field < 0 or lyr_defn.GetFieldDefn(acquired_field).GetType() != ogr.OFTDateTime: - gdaltest.post_reason('fail') - return 'fail' + assert acquired_field >= 0 and lyr_defn.GetFieldDefn(acquired_field).GetType() == ogr.OFTDateTime if not f.IsFieldSet(acquired_field): - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' + pytest.fail() int_field = -1 float_field = -1 @@ -822,36 +696,13 @@ def ogr_plscenes_data_v1_live(): lyr.SetAttributeFilter(filtr) f = lyr.GetNextFeature() - if f is None: - gdaltest.post_reason('fail') - return 'fail' + assert f is not None ds = None ds = gdal.Open('PLScenes:version=data_v1,itemtypes=%s,scene=%s,asset=%s' % (catalog, scene, asset_name)) - if ds is None: - gdaltest.post_reason('fail') - return 'fail' - if ds.RasterCount == 0: - gdaltest.post_reason('fail') - return 'fail' - - return 'success' - - -gdaltest_list = [ - ogr_plscenes_init, - ogr_plscenes_data_v1_catalog_no_paging, - ogr_plscenes_data_v1_catalog_paging, - ogr_plscenes_data_v1_nominal, - ogr_plscenes_data_v1_errors, - ogr_plscenes_data_v1_live -] - -if __name__ == '__main__': + assert ds is not None + assert ds.RasterCount != 0 - gdaltest.setup_run('ogr_plscenes') - gdaltest.run_tests(gdaltest_list) - sys.exit(gdaltest.summarize()) diff --git a/autotest/ogr/ogr_rec.py b/autotest/ogr/ogr_rec.py index 199a45b4e7dd..768d1603f35f 100755 --- a/autotest/ogr/ogr_rec.py +++ b/autotest/ogr/ogr_rec.py @@ -29,38 +29,23 @@ # DEALINGS IN THE SOFTWARE. ############################################################################### -import sys -sys.path.append('../pymod') import gdaltest +import pytest ############################################################################### -def ogr_rec_1(): +def test_ogr_rec_1(): import test_cli_utilities if test_cli_utilities.get_test_ogrsf_path() is None: - return 'skip' + pytest.skip() ret = gdaltest.runexternal(test_cli_utilities.get_test_ogrsf_path() + ' -ro data/test.rec') - if ret.find('INFO') == -1 or ret.find('ERROR') != -1: - print(ret) - return 'fail' + assert ret.find('INFO') != -1 and ret.find('ERROR') == -1 - return 'success' -gdaltest_list = [ - ogr_rec_1 -] - -if __name__ == '__main__': - - gdaltest.setup_run('ogr_rec') - - gdaltest.run_tests(gdaltest_list) - - sys.exit(gdaltest.summarize()) diff --git a/autotest/ogr/ogr_refcount.py b/autotest/ogr/ogr_refcount.py index 2e492e51c6f5..2031da9623c0 100755 --- a/autotest/ogr/ogr_refcount.py +++ b/autotest/ogr/ogr_refcount.py @@ -26,9 +26,7 @@ # Boston, MA 02111-1307, USA. ############################################################################### -import sys -sys.path.append('../pymod') import gdaltest from osgeo import ogr @@ -37,7 +35,7 @@ # Open two datasets in shared mode. -def ogr_refcount_1(): +def test_ogr_refcount_1(): # if ogr.GetOpenDSCount() != 0: # gdaltest.post_reason( 'Initial Open DS count is not zero!' ) # return 'failed' @@ -53,13 +51,12 @@ def ogr_refcount_1(): gdaltest.post_reason('Reference count not 1 on one of datasources.') return 'failed' - return 'success' - + ############################################################################### # Verify that reopening one of the datasets returns the existing shared handle. -def ogr_refcount_2(): +def test_ogr_refcount_2(): ds_3 = ogr.OpenShared('data/idlink.dbf') @@ -81,13 +78,11 @@ def ogr_refcount_2(): gdaltest.ds_3 = ds_3 - return 'success' - ############################################################################### # Verify that releasing the datasources has the expected behaviour. -def ogr_refcount_3(): +def test_ogr_refcount_3(): gdaltest.ds_3.Release() @@ -97,17 +92,11 @@ def ogr_refcount_3(): gdaltest.ds_1.Release() - # if ogr.GetOpenDSCount() != 1: - # gdaltest.post_reason( 'Open DS count not back to one.' ) - # return 'failed' - - return 'success' - ############################################################################### # Verify that we can walk the open datasource list. -def ogr_refcount_4(): +def test_ogr_refcount_4(): with gdaltest.error_handler(): ds = ogr.GetOpenDS(0) @@ -118,32 +107,12 @@ def ogr_refcount_4(): except: pass - return 'success' - + ############################################################################### -def ogr_refcount_cleanup(): +def test_ogr_refcount_cleanup(): gdaltest.ds_2.Release() - # if ogr.GetOpenDSCount() != 0: - # gdaltest.post_reason( 'Open DS count not back to zero.' ) - # return 'failed' - - return 'success' - - -gdaltest_list = [ - ogr_refcount_1, - ogr_refcount_2, - ogr_refcount_3, - ogr_refcount_4, - ogr_refcount_cleanup] - -if __name__ == '__main__': - - gdaltest.setup_run('ogr_refcount') - gdaltest.run_tests(gdaltest_list) - sys.exit(gdaltest.summarize()) diff --git a/autotest/ogr/ogr_rfc30.py b/autotest/ogr/ogr_rfc30.py index f316404a90d0..9710d528fa52 100755 --- a/autotest/ogr/ogr_rfc30.py +++ b/autotest/ogr/ogr_rfc30.py @@ -28,13 +28,11 @@ # DEALINGS IN THE SOFTWARE. ############################################################################### -import sys from sys import version_info from osgeo import ogr -sys.path.append('../pymod') -import gdaltest +import pytest ############################################################################### # Try ogr.Open(), Driver.CreateDataSource(), Driver.DeleteDataSource() @@ -47,21 +45,15 @@ def ogr_rfc30_1_internal(filename, layer_name): ds = None ds = ogr.Open(filename) - if ds is None: - gdaltest.post_reason('cannot reopen datasource') - return 'fail' + assert ds is not None, 'cannot reopen datasource' lyr = ds.GetLayerByName(layer_name) - if lyr is None: - gdaltest.post_reason('cannot find layer') - return 'fail' + assert lyr is not None, 'cannot find layer' ds = None ogr.GetDriverByName('ESRI Shapefile').DeleteDataSource(filename) - return 'success' - -def ogr_rfc30_1(): +def test_ogr_rfc30_1(): if version_info >= (3, 0, 0): filename = '/vsimem/\u00e9.shp' @@ -74,10 +66,10 @@ def ogr_rfc30_1(): return ogr_rfc30_1_internal(filename, layer_name) -def ogr_rfc30_1_bis(): +def test_ogr_rfc30_1_bis(): if version_info >= (3, 0, 0): - return 'skip' + pytest.skip() filename = None layer_name = None @@ -88,12 +80,4 @@ def ogr_rfc30_1_bis(): return ogr_rfc30_1_internal(filename, layer_name) -gdaltest_list = [ogr_rfc30_1, ogr_rfc30_1_bis] - -if __name__ == '__main__': - - gdaltest.setup_run('ogr_rfc30') - - gdaltest.run_tests(gdaltest_list) - sys.exit(gdaltest.summarize()) diff --git a/autotest/ogr/ogr_rfc35_mem.py b/autotest/ogr/ogr_rfc35_mem.py index a5160f8b0a7e..baafade8294d 100755 --- a/autotest/ogr/ogr_rfc35_mem.py +++ b/autotest/ogr/ogr_rfc35_mem.py @@ -28,19 +28,18 @@ # DEALINGS IN THE SOFTWARE. ############################################################################### -import sys -sys.path.append('../pymod') import gdaltest from osgeo import ogr from osgeo import gdal +import pytest ############################################################################### # Initiate the test file -def ogr_rfc35_mem_1(): +def test_ogr_rfc35_mem_1(): gdaltest.rfc35_mem_ds = ogr.GetDriverByName('Memory').CreateDataSource('rfc35_test') lyr = gdaltest.rfc35_mem_ds.CreateLayer('rfc35_test') @@ -81,8 +80,6 @@ def ogr_rfc35_mem_1(): fd.SetWidth(20) lyr.CreateField(fd) - return 'success' - ############################################################################### # Test ReorderField() @@ -118,42 +115,32 @@ def CheckFeatures(lyr, field1='foo5', field2='bar10', field3='baz15', field4='ba (field3 is not None and feat.GetField(field3) != Truncate(expected_values[i][2], lyr_defn, field3)) or \ (field4 is not None and feat.GetField(field4) != Truncate(expected_values[i][3], lyr_defn, field4)): feat.DumpReadable() - return 'fail' + pytest.fail() feat = lyr.GetNextFeature() i = i + 1 - return 'success' - + def CheckColumnOrder(lyr, expected_order): lyr_defn = lyr.GetLayerDefn() for i, exp_order in enumerate(expected_order): - if lyr_defn.GetFieldDefn(i).GetName() != exp_order: - return 'fail' - - return 'success' + assert lyr_defn.GetFieldDefn(i).GetName() == exp_order + def Check(lyr, expected_order): - ret = CheckColumnOrder(lyr, expected_order) - if ret != 'success': - return ret + CheckColumnOrder(lyr, expected_order) - ret = CheckFeatures(lyr) - if ret != 'success': - return ret + CheckFeatures(lyr) - return 'success' - -def ogr_rfc35_mem_2(): +def test_ogr_rfc35_mem_2(): lyr = gdaltest.rfc35_mem_ds.GetLayer(0) - if lyr.TestCapability(ogr.OLCReorderFields) != 1: - return 'fail' + assert lyr.TestCapability(ogr.OLCReorderFields) == 1 feat = ogr.Feature(lyr.GetLayerDefn()) feat.SetField(0, 'foo3') @@ -163,60 +150,40 @@ def ogr_rfc35_mem_2(): lyr.CreateFeature(feat) feat = None - if lyr.ReorderField(1, 3) != 0: - return 'fail' + assert lyr.ReorderField(1, 3) == 0 ret = Check(lyr, ['foo5', 'baz15', 'baw20', 'bar10']) - if ret != 'success': - return ret lyr.ReorderField(3, 1) ret = Check(lyr, ['foo5', 'bar10', 'baz15', 'baw20']) - if ret != 'success': - return ret lyr.ReorderField(0, 2) ret = Check(lyr, ['bar10', 'baz15', 'foo5', 'baw20']) - if ret != 'success': - return ret lyr.ReorderField(2, 0) ret = Check(lyr, ['foo5', 'bar10', 'baz15', 'baw20']) - if ret != 'success': - return ret lyr.ReorderField(0, 1) ret = Check(lyr, ['bar10', 'foo5', 'baz15', 'baw20']) - if ret != 'success': - return ret lyr.ReorderField(1, 0) ret = Check(lyr, ['foo5', 'bar10', 'baz15', 'baw20']) - if ret != 'success': - return ret lyr.ReorderFields([3, 2, 1, 0]) ret = Check(lyr, ['baw20', 'baz15', 'bar10', 'foo5']) - if ret != 'success': - return ret lyr.ReorderFields([3, 2, 1, 0]) ret = Check(lyr, ['foo5', 'bar10', 'baz15', 'baw20']) - if ret != 'success': - return ret gdal.PushErrorHandler('CPLQuietErrorHandler') ret = lyr.ReorderFields([0, 0, 0, 0]) gdal.PopErrorHandler() - if ret == 0: - return 'fail' - - return 'success' + assert ret != 0 ############################################################################### # Test AlterFieldDefn() for change of name and width -def ogr_rfc35_mem_3(): +def test_ogr_rfc35_mem_3(): lyr = gdaltest.rfc35_mem_ds.GetLayer(0) @@ -228,20 +195,16 @@ def ogr_rfc35_mem_3(): gdal.PushErrorHandler('CPLQuietErrorHandler') ret = lyr.AlterFieldDefn(-1, fd, ogr.ALTER_ALL_FLAG) gdal.PopErrorHandler() - if ret == 0: - return 'fail' + assert ret != 0 gdal.PushErrorHandler('CPLQuietErrorHandler') ret = lyr.AlterFieldDefn(lyr_defn.GetFieldCount(), fd, ogr.ALTER_ALL_FLAG) gdal.PopErrorHandler() - if ret == 0: - return 'fail' + assert ret != 0 lyr.AlterFieldDefn(lyr_defn.GetFieldIndex("baz15"), fd, ogr.ALTER_ALL_FLAG) ret = CheckFeatures(lyr, field3='baz25') - if ret != 'success': - return ret fd = ogr.FieldDefn("baz5", ogr.OFTString) fd.SetWidth(5) @@ -250,31 +213,23 @@ def ogr_rfc35_mem_3(): lyr.AlterFieldDefn(lyr_defn.GetFieldIndex("baz25"), fd, ogr.ALTER_ALL_FLAG) ret = CheckFeatures(lyr, field3='baz5') - if ret != 'success': - return ret lyr_defn = lyr.GetLayerDefn() fld_defn = lyr_defn.GetFieldDefn(lyr_defn.GetFieldIndex('baz5')) - if fld_defn.GetWidth() != 5: - return 'fail' + assert fld_defn.GetWidth() == 5 ret = CheckFeatures(lyr, field3='baz5') - if ret != 'success': - return ret - - return 'success' ############################################################################### # Test AlterFieldDefn() for change of type -def ogr_rfc35_mem_4(): +def test_ogr_rfc35_mem_4(): lyr = gdaltest.rfc35_mem_ds.GetLayer(0) lyr_defn = lyr.GetLayerDefn() - if lyr.TestCapability(ogr.OLCAlterFieldDefn) != 1: - return 'fail' + assert lyr.TestCapability(ogr.OLCAlterFieldDefn) == 1 fd = ogr.FieldDefn("intfield", ogr.OFTInteger) lyr.CreateField(fd) @@ -292,26 +247,20 @@ def ogr_rfc35_mem_4(): lyr.ResetReading() feat = lyr.GetNextFeature() - if feat.GetField("intfield") != 12345: - return 'fail' + assert feat.GetField("intfield") == 12345 feat = None - ret = CheckFeatures(lyr, field3='baz5') - if ret != 'success': - return ret + CheckFeatures(lyr, field3='baz5') fd.SetWidth(5) lyr.AlterFieldDefn(lyr_defn.GetFieldIndex("intfield"), fd, ogr.ALTER_ALL_FLAG) lyr.ResetReading() feat = lyr.GetNextFeature() - if feat.GetField("intfield") != 12345: - return 'fail' + assert feat.GetField("intfield") == 12345 feat = None - ret = CheckFeatures(lyr, field3='baz5') - if ret != 'success': - return ret + CheckFeatures(lyr, field3='baz5') fd.SetWidth(4) lyr.AlterFieldDefn(lyr_defn.GetFieldIndex("intfield"), fd, ogr.ALTER_ALL_FLAG) @@ -319,13 +268,10 @@ def ogr_rfc35_mem_4(): lyr.ResetReading() feat = lyr.GetNextFeature() # if feat.GetField("intfield") != 1234: - if feat.GetField("intfield") != 12345: - return 'fail' + assert feat.GetField("intfield") == 12345 feat = None - ret = CheckFeatures(lyr, field3='baz5') - if ret != 'success': - return ret + CheckFeatures(lyr, field3='baz5') fd = ogr.FieldDefn("oldintfld", ogr.OFTString) fd.SetWidth(15) @@ -334,29 +280,23 @@ def ogr_rfc35_mem_4(): lyr.ResetReading() feat = lyr.GetNextFeature() # if feat.GetField("oldintfld") != '1234': - if feat.GetField("oldintfld") != '12345': - return 'fail' + assert feat.GetField("oldintfld") == '12345' feat = None - ret = CheckFeatures(lyr, field3='baz5') - if ret != 'success': - return ret + CheckFeatures(lyr, field3='baz5') lyr.DeleteField(lyr_defn.GetFieldIndex("oldintfld")) fd = ogr.FieldDefn("intfield", ogr.OFTInteger) fd.SetWidth(10) - if lyr.CreateField(fd) != 0: - return 'fail' + assert lyr.CreateField(fd) == 0 - if lyr.ReorderField(lyr_defn.GetFieldIndex("intfield"), 0) != 0: - return 'fail' + assert lyr.ReorderField(lyr_defn.GetFieldIndex("intfield"), 0) == 0 lyr.ResetReading() feat = lyr.GetNextFeature() feat.SetField("intfield", 98765) - if lyr.SetFeature(feat) != 0: - return 'fail' + assert lyr.SetFeature(feat) == 0 feat = None fd = ogr.FieldDefn("oldintfld", ogr.OFTString) @@ -365,97 +305,58 @@ def ogr_rfc35_mem_4(): lyr.ResetReading() feat = lyr.GetNextFeature() - if feat.GetField("oldintfld") != '98765': - return 'fail' + assert feat.GetField("oldintfld") == '98765' feat = None - ret = CheckFeatures(lyr, field3='baz5') - if ret != 'success': - return ret - - return 'success' + CheckFeatures(lyr, field3='baz5') ############################################################################### # Test DeleteField() -def ogr_rfc35_mem_5(): +def test_ogr_rfc35_mem_5(): lyr = gdaltest.rfc35_mem_ds.GetLayer(0) lyr_defn = lyr.GetLayerDefn() - if lyr.TestCapability(ogr.OLCDeleteField) != 1: - return 'fail' + assert lyr.TestCapability(ogr.OLCDeleteField) == 1 gdal.PushErrorHandler('CPLQuietErrorHandler') ret = lyr.DeleteField(-1) gdal.PopErrorHandler() - if ret == 0: - return 'fail' + assert ret != 0 gdal.PushErrorHandler('CPLQuietErrorHandler') ret = lyr.DeleteField(lyr.GetLayerDefn().GetFieldCount()) gdal.PopErrorHandler() - if ret == 0: - return 'fail' + assert ret != 0 - if lyr.DeleteField(0) != 0: - return 'fail' + assert lyr.DeleteField(0) == 0 ret = CheckFeatures(lyr, field3='baz5') - if ret != 'success': - return ret - if lyr.DeleteField(lyr_defn.GetFieldIndex('baw20')) != 0: - return 'fail' + assert lyr.DeleteField(lyr_defn.GetFieldIndex('baw20')) == 0 ret = CheckFeatures(lyr, field3='baz5', field4=None) - if ret != 'success': - return ret - if lyr.DeleteField(lyr_defn.GetFieldIndex('baz5')) != 0: - return 'fail' + assert lyr.DeleteField(lyr_defn.GetFieldIndex('baz5')) == 0 ret = CheckFeatures(lyr, field3=None, field4=None) - if ret != 'success': - return ret - if lyr.DeleteField(lyr_defn.GetFieldIndex('foo5')) != 0: - return 'fail' + assert lyr.DeleteField(lyr_defn.GetFieldIndex('foo5')) == 0 - if lyr.DeleteField(lyr_defn.GetFieldIndex('bar10')) != 0: - return 'fail' + assert lyr.DeleteField(lyr_defn.GetFieldIndex('bar10')) == 0 ret = CheckFeatures(lyr, field1=None, field2=None, field3=None, field4=None) - if ret != 'success': - return ret - - return 'success' ############################################################################### # Initiate the test file -def ogr_rfc35_mem_cleanup(): +def test_ogr_rfc35_mem_cleanup(): gdaltest.rfc35_mem_ds = None - return 'success' - - -gdaltest_list = [ - ogr_rfc35_mem_1, - ogr_rfc35_mem_2, - ogr_rfc35_mem_3, - ogr_rfc35_mem_4, - ogr_rfc35_mem_5, - ogr_rfc35_mem_cleanup] - - -if __name__ == '__main__': - gdaltest.setup_run('ogr_rfc35_mem') - gdaltest.run_tests(gdaltest_list) - sys.exit(gdaltest.summarize()) diff --git a/autotest/ogr/ogr_rfc35_mitab.py b/autotest/ogr/ogr_rfc35_mitab.py index d979eaef4ee2..a494a109b250 100755 --- a/autotest/ogr/ogr_rfc35_mitab.py +++ b/autotest/ogr/ogr_rfc35_mitab.py @@ -29,43 +29,36 @@ # DEALINGS IN THE SOFTWARE. ############################################################################### -import sys - -sys.path.append('../pymod') import gdaltest from osgeo import ogr from osgeo import gdal +import pytest ############################################################################### # def CheckFileSize(src_filename): - import test_py_scripts script_path = test_py_scripts.get_py_script('ogr2ogr') if script_path is None: - return 'skip' + pytest.skip() - test_py_scripts.run_py_script(script_path, 'ogr2ogr', '-f "MapInfo File" /vsimem/CheckFileSize.tab ' + src_filename) + test_py_scripts.run_py_script(script_path, 'ogr2ogr', '-f "MapInfo File" tmp/CheckFileSize.tab ' + src_filename) statBufSrc = gdal.VSIStatL(src_filename[0:-3] + "dat", gdal.VSI_STAT_EXISTS_FLAG | gdal.VSI_STAT_NATURE_FLAG | gdal.VSI_STAT_SIZE_FLAG) - statBufDst = gdal.VSIStatL('/vsimem/CheckFileSize.dat', gdal.VSI_STAT_EXISTS_FLAG | gdal.VSI_STAT_NATURE_FLAG | gdal.VSI_STAT_SIZE_FLAG) - ogr.GetDriverByName('MapInfo File').DeleteDataSource('/vsimem/CheckFileSize.tab') + statBufDst = gdal.VSIStatL('tmp/CheckFileSize.dat', gdal.VSI_STAT_EXISTS_FLAG | gdal.VSI_STAT_NATURE_FLAG | gdal.VSI_STAT_SIZE_FLAG) + ogr.GetDriverByName('MapInfo File').DeleteDataSource('tmp/CheckFileSize.tab') - if statBufSrc.size != statBufDst.size: - print('src_size = %d, dst_size = %d', statBufSrc.size, statBufDst.size) - return 'fail' - - return 'success' + assert statBufSrc.size == statBufDst.size ############################################################################### # Initiate the test file -def ogr_rfc35_mitab_1(): +def test_ogr_rfc35_mitab_1(): - ds = ogr.GetDriverByName('MapInfo File').CreateDataSource('/vsimem/rfc35_test.tab') + ds = ogr.GetDriverByName('MapInfo File').CreateDataSource('tmp/rfc35_test.tab') lyr = ds.CreateLayer('rfc35_test') lyr.ReorderFields([]) @@ -104,8 +97,6 @@ def ogr_rfc35_mitab_1(): fd.SetWidth(20) lyr.CreateField(fd) - return 'success' - ############################################################################### # Test ReorderField() @@ -137,55 +128,40 @@ def CheckFeatures(lyr, field1='foo5', field2='bar10', field3='baz15', field4='ba (field3 is not None and feat.GetField(field3) != Truncate(expected_values[i][2], lyr_defn, field3)) or \ (field4 is not None and feat.GetField(field4) != Truncate(expected_values[i][3], lyr_defn, field4)): feat.DumpReadable() - return 'fail' + pytest.fail() feat = lyr.GetNextFeature() i = i + 1 - return 'success' - + def CheckColumnOrder(lyr, expected_order): lyr_defn = lyr.GetLayerDefn() for i, exp_order in enumerate(expected_order): - if lyr_defn.GetFieldDefn(i).GetName() != exp_order: - return 'fail' + assert lyr_defn.GetFieldDefn(i).GetName() == exp_order - return 'success' def Check(lyr, expected_order): - ret = CheckColumnOrder(lyr, expected_order) - if ret != 'success': - return ret + CheckColumnOrder(lyr, expected_order) - ret = CheckFeatures(lyr) - if ret != 'success': - return ret + CheckFeatures(lyr) - ds = ogr.Open('/vsimem/rfc35_test.tab', update=1) + ds = ogr.Open('tmp/rfc35_test.tab', update=1) lyr_reopen = ds.GetLayer(0) - ret = CheckColumnOrder(lyr_reopen, expected_order) - if ret != 'success': - return ret + CheckColumnOrder(lyr_reopen, expected_order) - ret = CheckFeatures(lyr_reopen) - if ret != 'success': - return ret - - return 'success' + CheckFeatures(lyr_reopen) -def ogr_rfc35_mitab_2(): +def test_ogr_rfc35_mitab_2(): - ds = ogr.Open('/vsimem/rfc35_test.tab', update=1) + ds = ogr.Open('tmp/rfc35_test.tab', update=1) lyr = ds.GetLayer(0) - if lyr.TestCapability(ogr.OLCReorderFields) != 1: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.TestCapability(ogr.OLCReorderFields) == 1 feat = ogr.Feature(lyr.GetLayerDefn()) feat.SetField(0, 'foo3') @@ -195,111 +171,76 @@ def ogr_rfc35_mitab_2(): lyr.CreateFeature(feat) feat = None - if lyr.ReorderField(1, 3) != 0: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.ReorderField(1, 3) == 0 # ds = None - # ds = ogr.Open('/vsimem/rfc35_test.tab', update = 1) + # ds = ogr.Open('tmp/rfc35_test.tab', update = 1) # lyr = ds.GetLayer(0) - ret = Check(lyr, ['foo5', 'baz15', 'baw20', 'bar10']) - if ret != 'success': - gdaltest.post_reason(ret) - return ret + Check(lyr, ['foo5', 'baz15', 'baw20', 'bar10']) lyr.ReorderField(3, 1) # ds = None - # ds = ogr.Open('/vsimem/rfc35_test.tab', update = 1) + # ds = ogr.Open('tmp/rfc35_test.tab', update = 1) # lyr = ds.GetLayer(0) - ret = Check(lyr, ['foo5', 'bar10', 'baz15', 'baw20']) - if ret != 'success': - gdaltest.post_reason(ret) - return ret + Check(lyr, ['foo5', 'bar10', 'baz15', 'baw20']) lyr.ReorderField(0, 2) # ds = None - # ds = ogr.Open('/vsimem/rfc35_test.tab', update = 1) + # ds = ogr.Open('tmp/rfc35_test.tab', update = 1) # lyr = ds.GetLayer(0) - ret = Check(lyr, ['bar10', 'baz15', 'foo5', 'baw20']) - if ret != 'success': - gdaltest.post_reason(ret) - return ret + Check(lyr, ['bar10', 'baz15', 'foo5', 'baw20']) lyr.ReorderField(2, 0) # ds = None - # ds = ogr.Open('/vsimem/rfc35_test.tab', update = 1) + # ds = ogr.Open('tmp/rfc35_test.tab', update = 1) # lyr = ds.GetLayer(0) - ret = Check(lyr, ['foo5', 'bar10', 'baz15', 'baw20']) - if ret != 'success': - gdaltest.post_reason(ret) - return ret + Check(lyr, ['foo5', 'bar10', 'baz15', 'baw20']) lyr.ReorderField(0, 1) # ds = None - # ds = ogr.Open('/vsimem/rfc35_test.tab', update = 1) + # ds = ogr.Open('tmp/rfc35_test.tab', update = 1) # lyr = ds.GetLayer(0) - ret = Check(lyr, ['bar10', 'foo5', 'baz15', 'baw20']) - if ret != 'success': - gdaltest.post_reason(ret) - return ret + Check(lyr, ['bar10', 'foo5', 'baz15', 'baw20']) lyr.ReorderField(1, 0) # ds = None - # ds = ogr.Open('/vsimem/rfc35_test.tab', update = 1) + # ds = ogr.Open('tmp/rfc35_test.tab', update = 1) # lyr = ds.GetLayer(0) - ret = Check(lyr, ['foo5', 'bar10', 'baz15', 'baw20']) - if ret != 'success': - gdaltest.post_reason(ret) - return ret + Check(lyr, ['foo5', 'bar10', 'baz15', 'baw20']) lyr.ReorderFields([3, 2, 1, 0]) # ds = None - # ds = ogr.Open('/vsimem/rfc35_test.tab', update = 1) + # ds = ogr.Open('tmp/rfc35_test.tab', update = 1) # lyr = ds.GetLayer(0) - ret = Check(lyr, ['baw20', 'baz15', 'bar10', 'foo5']) - if ret != 'success': - gdaltest.post_reason(ret) - return ret + Check(lyr, ['baw20', 'baz15', 'bar10', 'foo5']) lyr.ReorderFields([3, 2, 1, 0]) # ds = None - # ds = ogr.Open('/vsimem/rfc35_test.tab', update = 1) + # ds = ogr.Open('tmp/rfc35_test.tab', update = 1) # lyr = ds.GetLayer(0) - ret = Check(lyr, ['foo5', 'bar10', 'baz15', 'baw20']) - if ret != 'success': - gdaltest.post_reason(ret) - return ret + Check(lyr, ['foo5', 'bar10', 'baz15', 'baw20']) gdal.PushErrorHandler('CPLQuietErrorHandler') ret = lyr.ReorderFields([0, 0, 0, 0]) gdal.PopErrorHandler() - if ret == 0: - gdaltest.post_reason('fail') - return 'fail' + assert ret != 0 # ds = None - # ds = ogr.Open('/vsimem/rfc35_test.tab', update = 1) + # ds = ogr.Open('tmp/rfc35_test.tab', update = 1) lyr = ds.GetLayer(0) - ret = CheckColumnOrder(lyr, ['foo5', 'bar10', 'baz15', 'baw20']) - if ret != 'success': - gdaltest.post_reason(ret) - return ret + CheckColumnOrder(lyr, ['foo5', 'bar10', 'baz15', 'baw20']) - ret = CheckFeatures(lyr) - if ret != 'success': - gdaltest.post_reason(ret) - return ret + CheckFeatures(lyr) - return 'success' ############################################################################### # Test AlterFieldDefn() for change of name and width -def ogr_rfc35_mitab_3(): +def test_ogr_rfc35_mitab_3(): - ds = ogr.Open('/vsimem/rfc35_test.tab', update=1) + ds = ogr.Open('tmp/rfc35_test.tab', update=1) lyr = ds.GetLayer(0) fd = ogr.FieldDefn("baz25", ogr.OFTString) @@ -310,23 +251,16 @@ def ogr_rfc35_mitab_3(): gdal.PushErrorHandler('CPLQuietErrorHandler') ret = lyr.AlterFieldDefn(-1, fd, ogr.ALTER_ALL_FLAG) gdal.PopErrorHandler() - if ret == 0: - gdaltest.post_reason('fail') - return 'fail' + assert ret != 0 gdal.PushErrorHandler('CPLQuietErrorHandler') ret = lyr.AlterFieldDefn(lyr_defn.GetFieldCount(), fd, ogr.ALTER_ALL_FLAG) gdal.PopErrorHandler() - if ret == 0: - gdaltest.post_reason('fail') - return 'fail' + assert ret != 0 lyr.AlterFieldDefn(lyr_defn.GetFieldIndex("baz15"), fd, ogr.ALTER_ALL_FLAG) - ret = CheckFeatures(lyr, field3='baz25') - if ret != 'success': - gdaltest.post_reason(ret) - return ret + CheckFeatures(lyr, field3='baz25') fd = ogr.FieldDefn("baz5", ogr.OFTString) fd.SetWidth(5) @@ -334,40 +268,29 @@ def ogr_rfc35_mitab_3(): lyr_defn = lyr.GetLayerDefn() lyr.AlterFieldDefn(lyr_defn.GetFieldIndex("baz25"), fd, ogr.ALTER_ALL_FLAG) - ret = CheckFeatures(lyr, field3='baz5') - if ret != 'success': - gdaltest.post_reason(ret) - return ret + CheckFeatures(lyr, field3='baz5') ds = None - ds = ogr.Open('/vsimem/rfc35_test.tab', update=1) + ds = ogr.Open('tmp/rfc35_test.tab', update=1) lyr = ds.GetLayer(0) lyr_defn = lyr.GetLayerDefn() fld_defn = lyr_defn.GetFieldDefn(lyr_defn.GetFieldIndex('baz5')) - if fld_defn.GetWidth() != 5: - gdaltest.post_reason('fail') - return 'fail' + assert fld_defn.GetWidth() == 5 - ret = CheckFeatures(lyr, field3='baz5') - if ret != 'success': - return ret - - return 'success' + CheckFeatures(lyr, field3='baz5') ############################################################################### # Test AlterFieldDefn() for change of type -def ogr_rfc35_mitab_4(): +def test_ogr_rfc35_mitab_4(): - ds = ogr.Open('/vsimem/rfc35_test.tab', update=1) + ds = ogr.Open('tmp/rfc35_test.tab', update=1) lyr = ds.GetLayer(0) lyr_defn = lyr.GetLayerDefn() - if lyr.TestCapability(ogr.OLCAlterFieldDefn) != 1: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.TestCapability(ogr.OLCAlterFieldDefn) == 1 fd = ogr.FieldDefn("intfield", ogr.OFTInteger) lyr.CreateField(fd) @@ -384,21 +307,14 @@ def ogr_rfc35_mitab_4(): gdal.PushErrorHandler('CPLQuietErrorHandler') ret = lyr.AlterFieldDefn(lyr_defn.GetFieldIndex("intfield"), fd, ogr.ALTER_ALL_FLAG) gdal.PopErrorHandler() - if ret == 0: - gdaltest.post_reason('fail') - return 'fail' + assert ret != 0 lyr.ResetReading() feat = lyr.GetNextFeature() - if feat.GetField("intfield") != 12345: - gdaltest.post_reason('fail') - return 'fail' + assert feat.GetField("intfield") == 12345 feat = None - ret = CheckFeatures(lyr, field3='baz5') - if ret != 'success': - gdaltest.post_reason(ret) - return ret + CheckFeatures(lyr, field3='baz5') if False: # pylint: disable=using-constant-test fd.SetWidth(5) @@ -406,20 +322,15 @@ def ogr_rfc35_mitab_4(): lyr.ResetReading() feat = lyr.GetNextFeature() - if feat.GetField("intfield") != 12345: - gdaltest.post_reason('fail') - return 'fail' + assert feat.GetField("intfield") == 12345 feat = None - ret = CheckFeatures(lyr, field3='baz5') - if ret != 'success': - gdaltest.post_reason(ret) - return ret + CheckFeatures(lyr, field3='baz5') ds = None if False: # pylint: disable=using-constant-test - ds = ogr.Open('/vsimem/rfc35_test.tab', update=1) + ds = ogr.Open('tmp/rfc35_test.tab', update=1) lyr = ds.GetLayer(0) lyr_defn = lyr.GetLayerDefn() @@ -428,25 +339,17 @@ def ogr_rfc35_mitab_4(): lyr.ResetReading() feat = lyr.GetNextFeature() - if feat.GetField("intfield") != 1234: - gdaltest.post_reason('fail') - return 'fail' + assert feat.GetField("intfield") == 1234 feat = None - ret = CheckFeatures(lyr, field3='baz5') - if ret != 'success': - gdaltest.post_reason(ret) - return ret + CheckFeatures(lyr, field3='baz5') ds = None # Check that the file size has decreased after column shrinking - ret = CheckFileSize('/vsimem/rfc35_test.tab') - if ret == 'fail': - gdaltest.post_reason(ret) - return ret + CheckFileSize('tmp/rfc35_test.tab') - ds = ogr.Open('/vsimem/rfc35_test.tab', update=1) + ds = ogr.Open('tmp/rfc35_test.tab', update=1) lyr = ds.GetLayer(0) lyr_defn = lyr.GetLayerDefn() @@ -456,52 +359,36 @@ def ogr_rfc35_mitab_4(): lyr.ResetReading() feat = lyr.GetNextFeature() - if feat.GetField("oldintfld") != '12345': - gdaltest.post_reason('fail') - return 'fail' + assert feat.GetField("oldintfld") == '12345' feat = None - ret = CheckFeatures(lyr, field3='baz5') - if ret != 'success': - gdaltest.post_reason(ret) - return ret + CheckFeatures(lyr, field3='baz5') ds = None - ds = ogr.Open('/vsimem/rfc35_test.tab', update=1) + ds = ogr.Open('tmp/rfc35_test.tab', update=1) lyr = ds.GetLayer(0) lyr_defn = lyr.GetLayerDefn() lyr.ResetReading() feat = lyr.GetNextFeature() - if feat.GetField("oldintfld") != '12345': - gdaltest.post_reason('fail') - return 'fail' + assert feat.GetField("oldintfld") == '12345' feat = None - ret = CheckFeatures(lyr, field3='baz5') - if ret != 'success': - gdaltest.post_reason(ret) - return ret + CheckFeatures(lyr, field3='baz5') lyr.DeleteField(lyr_defn.GetFieldIndex("oldintfld")) fd = ogr.FieldDefn("intfield", ogr.OFTInteger) fd.SetWidth(10) - if lyr.CreateField(fd) != 0: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.CreateField(fd) == 0 - if lyr.ReorderField(lyr_defn.GetFieldIndex("intfield"), 0) != 0: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.ReorderField(lyr_defn.GetFieldIndex("intfield"), 0) == 0 lyr.ResetReading() feat = lyr.GetNextFeature() feat.SetField("intfield", 98765) - if lyr.SetFeature(feat) != 0: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.SetFeature(feat) == 0 feat = None fd = ogr.FieldDefn("oldintfld", ogr.OFTString) @@ -510,157 +397,98 @@ def ogr_rfc35_mitab_4(): lyr.ResetReading() feat = lyr.GetNextFeature() - if feat.GetField("oldintfld") != '98765': - gdaltest.post_reason('fail') - return 'fail' + assert feat.GetField("oldintfld") == '98765' feat = None - ret = CheckFeatures(lyr, field3='baz5') - if ret != 'success': - gdaltest.post_reason(ret) - return ret + CheckFeatures(lyr, field3='baz5') ds = None - ds = ogr.Open('/vsimem/rfc35_test.tab', update=1) + ds = ogr.Open('tmp/rfc35_test.tab', update=1) lyr = ds.GetLayer(0) lyr_defn = lyr.GetLayerDefn() lyr.ResetReading() feat = lyr.GetNextFeature() - if feat.GetField("oldintfld") != '98765': - gdaltest.post_reason('fail') - return 'fail' + assert feat.GetField("oldintfld") == '98765' feat = None - ret = CheckFeatures(lyr, field3='baz5') - if ret != 'success': - gdaltest.post_reason(ret) - return ret + CheckFeatures(lyr, field3='baz5') - return 'success' ############################################################################### # Test DeleteField() -def ogr_rfc35_mitab_5(): +def test_ogr_rfc35_mitab_5(): - ds = ogr.Open('/vsimem/rfc35_test.tab', update=1) + ds = ogr.Open('tmp/rfc35_test.tab', update=1) lyr = ds.GetLayer(0) lyr_defn = lyr.GetLayerDefn() - if lyr.TestCapability(ogr.OLCDeleteField) != 1: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.TestCapability(ogr.OLCDeleteField) == 1 - if lyr.DeleteField(0) != 0: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.DeleteField(0) == 0 gdal.PushErrorHandler('CPLQuietErrorHandler') ret = lyr.DeleteField(-1) gdal.PopErrorHandler() - if ret == 0: - gdaltest.post_reason('fail') - return 'fail' + assert ret != 0 gdal.PushErrorHandler('CPLQuietErrorHandler') ret = lyr.DeleteField(lyr.GetLayerDefn().GetFieldCount()) gdal.PopErrorHandler() - if ret == 0: - gdaltest.post_reason('fail') - return 'fail' + assert ret != 0 - ret = CheckFeatures(lyr, field3='baz5') - if ret != 'success': - gdaltest.post_reason(ret) - return ret + CheckFeatures(lyr, field3='baz5') - if lyr.DeleteField(lyr_defn.GetFieldIndex('baw20')) != 0: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.DeleteField(lyr_defn.GetFieldIndex('baw20')) == 0 ds = None # Check that the file size has decreased after column removing - ret = CheckFileSize('/vsimem/rfc35_test.tab') + CheckFileSize('tmp/rfc35_test.tab') if ret == 'fail': gdaltest.post_reason(ret) return ret - ds = ogr.Open('/vsimem/rfc35_test.tab', update=1) + ds = ogr.Open('tmp/rfc35_test.tab', update=1) lyr = ds.GetLayer(0) lyr_defn = lyr.GetLayerDefn() - ret = CheckFeatures(lyr, field3='baz5', field4=None) - if ret != 'success': - gdaltest.post_reason(ret) - return ret + CheckFeatures(lyr, field3='baz5', field4=None) - if lyr.DeleteField(lyr_defn.GetFieldIndex('baz5')) != 0: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.DeleteField(lyr_defn.GetFieldIndex('baz5')) == 0 - ret = CheckFeatures(lyr, field3=None, field4=None) - if ret != 'success': - gdaltest.post_reason(ret) - return ret + CheckFeatures(lyr, field3=None, field4=None) - if lyr.DeleteField(lyr_defn.GetFieldIndex('foo5')) != 0: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.DeleteField(lyr_defn.GetFieldIndex('foo5')) == 0 # We cannot delete the only one remaining field (well MapInfo prohibits that) gdal.PushErrorHandler('CPLQuietErrorHandler') ret = lyr.DeleteField(lyr_defn.GetFieldIndex('bar10')) gdal.PopErrorHandler() - if ret == 0: - gdaltest.post_reason('fail') - return 'fail' + assert ret != 0 - ret = CheckFeatures(lyr, field1=None, field2=None, field3=None, field4=None) - if ret != 'success': - gdaltest.post_reason(ret) - return ret + CheckFeatures(lyr, field1=None, field2=None, field3=None, field4=None) ds = None - ds = ogr.Open('/vsimem/rfc35_test.tab', update=1) + ds = ogr.Open('tmp/rfc35_test.tab', update=1) lyr = ds.GetLayer(0) lyr_defn = lyr.GetLayerDefn() - ret = CheckFeatures(lyr, field1=None, field2=None, field3=None, field4=None) - if ret != 'success': - gdaltest.post_reason(ret) - return ret + CheckFeatures(lyr, field1=None, field2=None, field3=None, field4=None) - return 'success' ############################################################################### # Initiate the test file -def ogr_rfc35_mitab_cleanup(): - - ogr.GetDriverByName('MapInfo File').DeleteDataSource('/vsimem/rfc35_test.tab') - - return 'success' - - -gdaltest_list = [ - ogr_rfc35_mitab_1, - ogr_rfc35_mitab_2, - ogr_rfc35_mitab_3, - ogr_rfc35_mitab_4, - ogr_rfc35_mitab_5, - ogr_rfc35_mitab_cleanup] +def test_ogr_rfc35_mitab_cleanup(): + ogr.GetDriverByName('MapInfo File').DeleteDataSource('tmp/rfc35_test.tab') -if __name__ == '__main__': - gdaltest.setup_run('ogr_rfc35_mitab') - gdaltest.run_tests(gdaltest_list) - sys.exit(gdaltest.summarize()) diff --git a/autotest/ogr/ogr_rfc35_shape.py b/autotest/ogr/ogr_rfc35_shape.py index 9f140696a614..6ab987455d46 100755 --- a/autotest/ogr/ogr_rfc35_shape.py +++ b/autotest/ogr/ogr_rfc35_shape.py @@ -29,43 +29,36 @@ # DEALINGS IN THE SOFTWARE. ############################################################################### -import sys -sys.path.append('../pymod') - -import gdaltest from osgeo import ogr from osgeo import gdal +import pytest ############################################################################### # - def CheckFileSize(src_filename): import test_py_scripts script_path = test_py_scripts.get_py_script('ogr2ogr') if script_path is None: - return 'skip' + pytest.skip() - test_py_scripts.run_py_script(script_path, 'ogr2ogr', '/vsimem/CheckFileSize.dbf ' + src_filename) + test_py_scripts.run_py_script(script_path, 'ogr2ogr', 'tmp/CheckFileSize.dbf ' + src_filename) statBufSrc = gdal.VSIStatL(src_filename, gdal.VSI_STAT_EXISTS_FLAG | gdal.VSI_STAT_NATURE_FLAG | gdal.VSI_STAT_SIZE_FLAG) - statBufDst = gdal.VSIStatL('/vsimem/CheckFileSize.dbf', gdal.VSI_STAT_EXISTS_FLAG | gdal.VSI_STAT_NATURE_FLAG | gdal.VSI_STAT_SIZE_FLAG) - ogr.GetDriverByName('ESRI Shapefile').DeleteDataSource('/vsimem/CheckFileSize.dbf') - - if statBufSrc.size != statBufDst.size: - print('src_size = %d, dst_size = %d', statBufSrc.size, statBufDst.size) - return 'fail' + statBufDst = gdal.VSIStatL('tmp/CheckFileSize.dbf', gdal.VSI_STAT_EXISTS_FLAG | gdal.VSI_STAT_NATURE_FLAG | gdal.VSI_STAT_SIZE_FLAG) + ogr.GetDriverByName('ESRI Shapefile').DeleteDataSource('tmp/CheckFileSize.dbf') - return 'success' + assert statBufSrc.size == statBufDst.size, \ + ('src_size = %d, dst_size = %d', statBufSrc.size, statBufDst.size) ############################################################################### # Initiate the test file -def ogr_rfc35_shape_1(): +def test_ogr_rfc35_shape_1(): - ds = ogr.GetDriverByName('ESRI Shapefile').CreateDataSource('/vsimem/rfc35_test.dbf') + ds = ogr.GetDriverByName('ESRI Shapefile').CreateDataSource('tmp/rfc35_test.dbf') lyr = ds.CreateLayer('rfc35_test') lyr.ReorderFields([]) @@ -104,8 +97,6 @@ def ogr_rfc35_shape_1(): fd.SetWidth(20) lyr.CreateField(fd) - return 'success' - ############################################################################### # Test ReorderField() @@ -137,54 +128,40 @@ def CheckFeatures(lyr, field1='foo5', field2='bar10', field3='baz15', field4='ba (field3 is not None and feat.GetField(field3) != Truncate(expected_values[i][2], lyr_defn, field3)) or \ (field4 is not None and feat.GetField(field4) != Truncate(expected_values[i][3], lyr_defn, field4)): feat.DumpReadable() - return 'fail' + pytest.fail() feat = lyr.GetNextFeature() i = i + 1 - return 'success' - + def CheckColumnOrder(lyr, expected_order): lyr_defn = lyr.GetLayerDefn() for i, exp_order in enumerate(expected_order): - if lyr_defn.GetFieldDefn(i).GetName() != exp_order: - return 'fail' - - return 'success' + assert lyr_defn.GetFieldDefn(i).GetName() == exp_order + def Check(lyr, expected_order): - ret = CheckColumnOrder(lyr, expected_order) - if ret != 'success': - return ret + CheckColumnOrder(lyr, expected_order) - ret = CheckFeatures(lyr) - if ret != 'success': - return ret + CheckFeatures(lyr) - ds = ogr.Open('/vsimem/rfc35_test.dbf', update=1) + ds = ogr.Open('tmp/rfc35_test.dbf', update=1) lyr_reopen = ds.GetLayer(0) - ret = CheckColumnOrder(lyr_reopen, expected_order) - if ret != 'success': - return ret - - ret = CheckFeatures(lyr_reopen) - if ret != 'success': - return ret + CheckColumnOrder(lyr_reopen, expected_order) - return 'success' + CheckFeatures(lyr_reopen) -def ogr_rfc35_shape_2(): +def test_ogr_rfc35_shape_2(): - ds = ogr.Open('/vsimem/rfc35_test.dbf', update=1) + ds = ogr.Open('tmp/rfc35_test.dbf', update=1) lyr = ds.GetLayer(0) - if lyr.TestCapability(ogr.OLCReorderFields) != 1: - return 'fail' + assert lyr.TestCapability(ogr.OLCReorderFields) == 1 feat = ogr.Feature(lyr.GetLayerDefn()) feat.SetField(0, 'foo3') @@ -194,75 +171,51 @@ def ogr_rfc35_shape_2(): lyr.CreateFeature(feat) feat = None - if lyr.ReorderField(1, 3) != 0: - return 'fail' - ret = Check(lyr, ['foo5', 'baz15', 'baw20', 'bar10']) - if ret != 'success': - return ret + assert lyr.ReorderField(1, 3) == 0 + Check(lyr, ['foo5', 'baz15', 'baw20', 'bar10']) lyr.ReorderField(3, 1) - ret = Check(lyr, ['foo5', 'bar10', 'baz15', 'baw20']) - if ret != 'success': - return ret + Check(lyr, ['foo5', 'bar10', 'baz15', 'baw20']) lyr.ReorderField(0, 2) - ret = Check(lyr, ['bar10', 'baz15', 'foo5', 'baw20']) - if ret != 'success': - return ret + Check(lyr, ['bar10', 'baz15', 'foo5', 'baw20']) lyr.ReorderField(2, 0) - ret = Check(lyr, ['foo5', 'bar10', 'baz15', 'baw20']) - if ret != 'success': - return ret + Check(lyr, ['foo5', 'bar10', 'baz15', 'baw20']) lyr.ReorderField(0, 1) - ret = Check(lyr, ['bar10', 'foo5', 'baz15', 'baw20']) - if ret != 'success': - return ret + Check(lyr, ['bar10', 'foo5', 'baz15', 'baw20']) lyr.ReorderField(1, 0) - ret = Check(lyr, ['foo5', 'bar10', 'baz15', 'baw20']) - if ret != 'success': - return ret + Check(lyr, ['foo5', 'bar10', 'baz15', 'baw20']) lyr.ReorderFields([3, 2, 1, 0]) - ret = Check(lyr, ['baw20', 'baz15', 'bar10', 'foo5']) - if ret != 'success': - return ret + Check(lyr, ['baw20', 'baz15', 'bar10', 'foo5']) lyr.ReorderFields([3, 2, 1, 0]) - ret = Check(lyr, ['foo5', 'bar10', 'baz15', 'baw20']) - if ret != 'success': - return ret + Check(lyr, ['foo5', 'bar10', 'baz15', 'baw20']) gdal.PushErrorHandler('CPLQuietErrorHandler') ret = lyr.ReorderFields([0, 0, 0, 0]) gdal.PopErrorHandler() - if ret == 0: - return 'fail' + assert ret != 0 ds = None - ds = ogr.Open('/vsimem/rfc35_test.dbf', update=1) + ds = ogr.Open('tmp/rfc35_test.dbf', update=1) lyr = ds.GetLayer(0) - ret = CheckColumnOrder(lyr, ['foo5', 'bar10', 'baz15', 'baw20']) - if ret != 'success': - return ret + CheckColumnOrder(lyr, ['foo5', 'bar10', 'baz15', 'baw20']) - ret = CheckFeatures(lyr) - if ret != 'success': - return ret - - return 'success' + CheckFeatures(lyr) ############################################################################### # Test AlterFieldDefn() for change of name and width -def ogr_rfc35_shape_3(): +def test_ogr_rfc35_shape_3(): - ds = ogr.Open('/vsimem/rfc35_test.dbf', update=1) + ds = ogr.Open('tmp/rfc35_test.dbf', update=1) lyr = ds.GetLayer(0) fd = ogr.FieldDefn("baz25", ogr.OFTString) @@ -273,20 +226,16 @@ def ogr_rfc35_shape_3(): gdal.PushErrorHandler('CPLQuietErrorHandler') ret = lyr.AlterFieldDefn(-1, fd, ogr.ALTER_ALL_FLAG) gdal.PopErrorHandler() - if ret == 0: - return 'fail' + assert ret != 0 gdal.PushErrorHandler('CPLQuietErrorHandler') ret = lyr.AlterFieldDefn(lyr_defn.GetFieldCount(), fd, ogr.ALTER_ALL_FLAG) gdal.PopErrorHandler() - if ret == 0: - return 'fail' + assert ret != 0 lyr.AlterFieldDefn(lyr_defn.GetFieldIndex("baz15"), fd, ogr.ALTER_ALL_FLAG) - ret = CheckFeatures(lyr, field3='baz25') - if ret != 'success': - return ret + CheckFeatures(lyr, field3='baz25') fd = ogr.FieldDefn("baz5", ogr.OFTString) fd.SetWidth(5) @@ -294,37 +243,29 @@ def ogr_rfc35_shape_3(): lyr_defn = lyr.GetLayerDefn() lyr.AlterFieldDefn(lyr_defn.GetFieldIndex("baz25"), fd, ogr.ALTER_ALL_FLAG) - ret = CheckFeatures(lyr, field3='baz5') - if ret != 'success': - return ret + CheckFeatures(lyr, field3='baz5') ds = None - ds = ogr.Open('/vsimem/rfc35_test.dbf', update=1) + ds = ogr.Open('tmp/rfc35_test.dbf', update=1) lyr = ds.GetLayer(0) lyr_defn = lyr.GetLayerDefn() fld_defn = lyr_defn.GetFieldDefn(lyr_defn.GetFieldIndex('baz5')) - if fld_defn.GetWidth() != 5: - return 'fail' - - ret = CheckFeatures(lyr, field3='baz5') - if ret != 'success': - return ret + assert fld_defn.GetWidth() == 5 - return 'success' + CheckFeatures(lyr, field3='baz5') ############################################################################### # Test AlterFieldDefn() for change of type -def ogr_rfc35_shape_4(): +def test_ogr_rfc35_shape_4(): - ds = ogr.Open('/vsimem/rfc35_test.dbf', update=1) + ds = ogr.Open('tmp/rfc35_test.dbf', update=1) lyr = ds.GetLayer(0) lyr_defn = lyr.GetLayerDefn() - if lyr.TestCapability(ogr.OLCAlterFieldDefn) != 1: - return 'fail' + assert lyr.TestCapability(ogr.OLCAlterFieldDefn) == 1 fd = ogr.FieldDefn("intfield", ogr.OFTInteger) lyr.CreateField(fd) @@ -342,30 +283,24 @@ def ogr_rfc35_shape_4(): lyr.ResetReading() feat = lyr.GetNextFeature() - if feat.GetField("intfield") != 12345: - return 'fail' + assert feat.GetField("intfield") == 12345 feat = None - ret = CheckFeatures(lyr, field3='baz5') - if ret != 'success': - return ret + CheckFeatures(lyr, field3='baz5') fd.SetWidth(5) lyr.AlterFieldDefn(lyr_defn.GetFieldIndex("intfield"), fd, ogr.ALTER_ALL_FLAG) lyr.ResetReading() feat = lyr.GetNextFeature() - if feat.GetField("intfield") != 12345: - return 'fail' + assert feat.GetField("intfield") == 12345 feat = None - ret = CheckFeatures(lyr, field3='baz5') - if ret != 'success': - return ret + CheckFeatures(lyr, field3='baz5') ds = None - ds = ogr.Open('/vsimem/rfc35_test.dbf', update=1) + ds = ogr.Open('tmp/rfc35_test.dbf', update=1) lyr = ds.GetLayer(0) lyr_defn = lyr.GetLayerDefn() @@ -374,22 +309,17 @@ def ogr_rfc35_shape_4(): lyr.ResetReading() feat = lyr.GetNextFeature() - if feat.GetField("intfield") != 1234: - return 'fail' + assert feat.GetField("intfield") == 1234 feat = None - ret = CheckFeatures(lyr, field3='baz5') - if ret != 'success': - return ret + CheckFeatures(lyr, field3='baz5') ds = None # Check that the file size has decreased after column shrinking - ret = CheckFileSize('/vsimem/rfc35_test.dbf') - if ret == 'fail': - return ret + CheckFileSize('tmp/rfc35_test.dbf') - ds = ogr.Open('/vsimem/rfc35_test.dbf', update=1) + ds = ogr.Open('tmp/rfc35_test.dbf', update=1) lyr = ds.GetLayer(0) lyr_defn = lyr.GetLayerDefn() @@ -399,45 +329,36 @@ def ogr_rfc35_shape_4(): lyr.ResetReading() feat = lyr.GetNextFeature() - if feat.GetField("oldintfld") != '1234': - return 'fail' + assert feat.GetField("oldintfld") == '1234' feat = None - ret = CheckFeatures(lyr, field3='baz5') - if ret != 'success': - return ret + CheckFeatures(lyr, field3='baz5') ds = None - ds = ogr.Open('/vsimem/rfc35_test.dbf', update=1) + ds = ogr.Open('tmp/rfc35_test.dbf', update=1) lyr = ds.GetLayer(0) lyr_defn = lyr.GetLayerDefn() lyr.ResetReading() feat = lyr.GetNextFeature() - if feat.GetField("oldintfld") != '1234': - return 'fail' + assert feat.GetField("oldintfld") == '1234' feat = None - ret = CheckFeatures(lyr, field3='baz5') - if ret != 'success': - return ret + CheckFeatures(lyr, field3='baz5') lyr.DeleteField(lyr_defn.GetFieldIndex("oldintfld")) fd = ogr.FieldDefn("intfield", ogr.OFTInteger) fd.SetWidth(10) - if lyr.CreateField(fd) != 0: - return 'fail' + assert lyr.CreateField(fd) == 0 - if lyr.ReorderField(lyr_defn.GetFieldIndex("intfield"), 0) != 0: - return 'fail' + assert lyr.ReorderField(lyr_defn.GetFieldIndex("intfield"), 0) == 0 lyr.ResetReading() feat = lyr.GetNextFeature() feat.SetField("intfield", 98765) - if lyr.SetFeature(feat) != 0: - return 'fail' + assert lyr.SetFeature(feat) == 0 feat = None fd = ogr.FieldDefn("oldintfld", ogr.OFTString) @@ -446,135 +367,91 @@ def ogr_rfc35_shape_4(): lyr.ResetReading() feat = lyr.GetNextFeature() - if feat.GetField("oldintfld") != '98765': - return 'fail' + assert feat.GetField("oldintfld") == '98765' feat = None - ret = CheckFeatures(lyr, field3='baz5') - if ret != 'success': - return ret + CheckFeatures(lyr, field3='baz5') ds = None - ds = ogr.Open('/vsimem/rfc35_test.dbf', update=1) + ds = ogr.Open('tmp/rfc35_test.dbf', update=1) lyr = ds.GetLayer(0) lyr_defn = lyr.GetLayerDefn() lyr.ResetReading() feat = lyr.GetNextFeature() - if feat.GetField("oldintfld") != '98765': - return 'fail' + assert feat.GetField("oldintfld") == '98765' feat = None - ret = CheckFeatures(lyr, field3='baz5') - if ret != 'success': - return ret - - return 'success' + CheckFeatures(lyr, field3='baz5') ############################################################################### # Test DeleteField() -def ogr_rfc35_shape_5(): +def test_ogr_rfc35_shape_5(): - ds = ogr.Open('/vsimem/rfc35_test.dbf', update=1) + ds = ogr.Open('tmp/rfc35_test.dbf', update=1) lyr = ds.GetLayer(0) lyr_defn = lyr.GetLayerDefn() - if lyr.TestCapability(ogr.OLCDeleteField) != 1: - return 'fail' + assert lyr.TestCapability(ogr.OLCDeleteField) == 1 - if lyr.DeleteField(0) != 0: - return 'fail' + assert lyr.DeleteField(0) == 0 gdal.PushErrorHandler('CPLQuietErrorHandler') ret = lyr.DeleteField(-1) gdal.PopErrorHandler() - if ret == 0: - return 'fail' + assert ret != 0 gdal.PushErrorHandler('CPLQuietErrorHandler') ret = lyr.DeleteField(lyr.GetLayerDefn().GetFieldCount()) gdal.PopErrorHandler() - if ret == 0: - return 'fail' + assert ret != 0 - ret = CheckFeatures(lyr, field3='baz5') - if ret != 'success': - return ret + CheckFeatures(lyr, field3='baz5') - if lyr.DeleteField(lyr_defn.GetFieldIndex('baw20')) != 0: - return 'fail' + assert lyr.DeleteField(lyr_defn.GetFieldIndex('baw20')) == 0 ds = None # Check that the file size has decreased after column removing - ret = CheckFileSize('/vsimem/rfc35_test.dbf') + CheckFileSize('tmp/rfc35_test.dbf') if ret == 'fail': return ret - ds = ogr.Open('/vsimem/rfc35_test.dbf', update=1) + ds = ogr.Open('tmp/rfc35_test.dbf', update=1) lyr = ds.GetLayer(0) lyr_defn = lyr.GetLayerDefn() - ret = CheckFeatures(lyr, field3='baz5', field4=None) - if ret != 'success': - return ret + CheckFeatures(lyr, field3='baz5', field4=None) - if lyr.DeleteField(lyr_defn.GetFieldIndex('baz5')) != 0: - return 'fail' + assert lyr.DeleteField(lyr_defn.GetFieldIndex('baz5')) == 0 - ret = CheckFeatures(lyr, field3=None, field4=None) - if ret != 'success': - return ret + CheckFeatures(lyr, field3=None, field4=None) - if lyr.DeleteField(lyr_defn.GetFieldIndex('foo5')) != 0: - return 'fail' + assert lyr.DeleteField(lyr_defn.GetFieldIndex('foo5')) == 0 - if lyr.DeleteField(lyr_defn.GetFieldIndex('bar10')) != 0: - return 'fail' + assert lyr.DeleteField(lyr_defn.GetFieldIndex('bar10')) == 0 - ret = CheckFeatures(lyr, field1=None, field2=None, field3=None, field4=None) - if ret != 'success': - return ret + CheckFeatures(lyr, field1=None, field2=None, field3=None, field4=None) ds = None - ds = ogr.Open('/vsimem/rfc35_test.dbf', update=1) + ds = ogr.Open('tmp/rfc35_test.dbf', update=1) lyr = ds.GetLayer(0) lyr_defn = lyr.GetLayerDefn() - ret = CheckFeatures(lyr, field1=None, field2=None, field3=None, field4=None) - if ret != 'success': - return ret - - return 'success' + CheckFeatures(lyr, field1=None, field2=None, field3=None, field4=None) ############################################################################### # Initiate the test file -def ogr_rfc35_shape_cleanup(): - - ogr.GetDriverByName('ESRI Shapefile').DeleteDataSource('/vsimem/rfc35_test.dbf') - - return 'success' - - -gdaltest_list = [ - ogr_rfc35_shape_1, - ogr_rfc35_shape_2, - ogr_rfc35_shape_3, - ogr_rfc35_shape_4, - ogr_rfc35_shape_5, - ogr_rfc35_shape_cleanup] +def test_ogr_rfc35_shape_cleanup(): + ogr.GetDriverByName('ESRI Shapefile').DeleteDataSource('tmp/rfc35_test.dbf') -if __name__ == '__main__': - gdaltest.setup_run('ogr_rfc35_shape') - gdaltest.run_tests(gdaltest_list) - sys.exit(gdaltest.summarize()) diff --git a/autotest/ogr/ogr_rfc35_sqlite.py b/autotest/ogr/ogr_rfc35_sqlite.py index af24a67da84f..d8eede33d6f0 100755 --- a/autotest/ogr/ogr_rfc35_sqlite.py +++ b/autotest/ogr/ogr_rfc35_sqlite.py @@ -28,25 +28,24 @@ # DEALINGS IN THE SOFTWARE. ############################################################################### -import sys -sys.path.append('../pymod') import gdaltest from osgeo import ogr from osgeo import gdal +import pytest ############################################################################### # Initiate the test file -def ogr_rfc35_sqlite_1(): +def test_ogr_rfc35_sqlite_1(): gdaltest.rfc35_sqlite_ds = None gdaltest.rfc35_sqlite_ds_name = None sqlite_dr = ogr.GetDriverByName('SQLite') if sqlite_dr is None: - return 'skip' + pytest.skip() gdal.Unlink('tmp/rfc35_test.sqlite') @@ -100,8 +99,6 @@ def ogr_rfc35_sqlite_1(): fd.SetWidth(20) lyr.CreateField(fd) - return 'success' - ############################################################################### # Test ReorderField() @@ -132,46 +129,32 @@ def CheckFeatures(lyr, field1='foo5', field2='bar10', field3='baz15', field4='ba (field3 is not None and feat.GetField(field3) != Truncate(expected_values[i][2], lyr_defn, field3)) or \ (field4 is not None and feat.GetField(field4) != Truncate(expected_values[i][3], lyr_defn, field4)): feat.DumpReadable() - return 'fail' + pytest.fail() feat = lyr.GetNextFeature() i = i + 1 - return 'success' - + def CheckColumnOrder(lyr, expected_order): lyr_defn = lyr.GetLayerDefn() for i, exp_order in enumerate(expected_order): - if lyr_defn.GetFieldDefn(i).GetName() != exp_order: - return 'fail' - - return 'success' + assert lyr_defn.GetFieldDefn(i).GetName() == exp_order def Check(lyr, expected_order): + CheckColumnOrder(lyr, expected_order) + CheckFeatures(lyr) - ret = CheckColumnOrder(lyr, expected_order) - if ret != 'success': - return ret - - ret = CheckFeatures(lyr) - if ret != 'success': - return ret - return 'success' - - -def ogr_rfc35_sqlite_2(): +def test_ogr_rfc35_sqlite_2(): if gdaltest.rfc35_sqlite_ds is None: - return 'skip' + pytest.skip() lyr = gdaltest.rfc35_sqlite_ds.GetLayer(0) - if lyr.TestCapability(ogr.OLCReorderFields) != 1: - gdaltest.post_reason('failed') - return 'fail' + assert lyr.TestCapability(ogr.OLCReorderFields) == 1 feat = ogr.Feature(lyr.GetLayerDefn()) feat.SetField(0, 'foo3') @@ -181,74 +164,44 @@ def ogr_rfc35_sqlite_2(): lyr.CreateFeature(feat) feat = None - if lyr.ReorderField(1, 3) != 0: - gdaltest.post_reason('failed') - return 'fail' + assert lyr.ReorderField(1, 3) == 0 - ret = Check(lyr, ['foo5', 'baz15', 'baw20', 'bar10']) - if ret != 'success': - gdaltest.post_reason('failed') - return ret + Check(lyr, ['foo5', 'baz15', 'baw20', 'bar10']) lyr.ReorderField(3, 1) - ret = Check(lyr, ['foo5', 'bar10', 'baz15', 'baw20']) - if ret != 'success': - gdaltest.post_reason('failed') - return ret + Check(lyr, ['foo5', 'bar10', 'baz15', 'baw20']) lyr.ReorderField(0, 2) - ret = Check(lyr, ['bar10', 'baz15', 'foo5', 'baw20']) - if ret != 'success': - gdaltest.post_reason('failed') - return ret + Check(lyr, ['bar10', 'baz15', 'foo5', 'baw20']) lyr.ReorderField(2, 0) - ret = Check(lyr, ['foo5', 'bar10', 'baz15', 'baw20']) - if ret != 'success': - gdaltest.post_reason('failed') - return ret + Check(lyr, ['foo5', 'bar10', 'baz15', 'baw20']) lyr.ReorderField(0, 1) - ret = Check(lyr, ['bar10', 'foo5', 'baz15', 'baw20']) - if ret != 'success': - gdaltest.post_reason('failed') - return ret + Check(lyr, ['bar10', 'foo5', 'baz15', 'baw20']) lyr.ReorderField(1, 0) - ret = Check(lyr, ['foo5', 'bar10', 'baz15', 'baw20']) - if ret != 'success': - gdaltest.post_reason('failed') - return ret + Check(lyr, ['foo5', 'bar10', 'baz15', 'baw20']) lyr.ReorderFields([3, 2, 1, 0]) - ret = Check(lyr, ['baw20', 'baz15', 'bar10', 'foo5']) - if ret != 'success': - gdaltest.post_reason('failed') - return ret + Check(lyr, ['baw20', 'baz15', 'bar10', 'foo5']) lyr.ReorderFields([3, 2, 1, 0]) - ret = Check(lyr, ['foo5', 'bar10', 'baz15', 'baw20']) - if ret != 'success': - gdaltest.post_reason('failed') - return ret + Check(lyr, ['foo5', 'bar10', 'baz15', 'baw20']) gdal.PushErrorHandler('CPLQuietErrorHandler') ret = lyr.ReorderFields([0, 0, 0, 0]) gdal.PopErrorHandler() - if ret == 0: - gdaltest.post_reason('failed') - return 'fail' - - return 'success' + assert ret != 0 ############################################################################### # Test AlterFieldDefn() for change of name and width -def ogr_rfc35_sqlite_3(): +def test_ogr_rfc35_sqlite_3(): if gdaltest.rfc35_sqlite_ds is None: - return 'skip' + pytest.skip() lyr = gdaltest.rfc35_sqlite_ds.GetLayer(0) @@ -260,23 +213,16 @@ def ogr_rfc35_sqlite_3(): gdal.PushErrorHandler('CPLQuietErrorHandler') ret = lyr.AlterFieldDefn(-1, fd, ogr.ALTER_ALL_FLAG) gdal.PopErrorHandler() - if ret == 0: - gdaltest.post_reason('failed') - return 'fail' + assert ret != 0 gdal.PushErrorHandler('CPLQuietErrorHandler') ret = lyr.AlterFieldDefn(lyr_defn.GetFieldCount(), fd, ogr.ALTER_ALL_FLAG) gdal.PopErrorHandler() - if ret == 0: - gdaltest.post_reason('failed') - return 'fail' + assert ret != 0 lyr.AlterFieldDefn(lyr_defn.GetFieldIndex("baz15"), fd, ogr.ALTER_ALL_FLAG) - ret = CheckFeatures(lyr, field3='baz25') - if ret != 'success': - gdaltest.post_reason('failed') - return ret + CheckFeatures(lyr, field3='baz25') fd = ogr.FieldDefn("baz5", ogr.OFTString) fd.SetWidth(5) @@ -284,39 +230,27 @@ def ogr_rfc35_sqlite_3(): lyr_defn = lyr.GetLayerDefn() lyr.AlterFieldDefn(lyr_defn.GetFieldIndex("baz25"), fd, ogr.ALTER_ALL_FLAG) - ret = CheckFeatures(lyr, field3='baz5') - if ret != 'success': - gdaltest.post_reason('failed') - return ret + CheckFeatures(lyr, field3='baz5') lyr_defn = lyr.GetLayerDefn() fld_defn = lyr_defn.GetFieldDefn(lyr_defn.GetFieldIndex('baz5')) - if fld_defn.GetWidth() != 5: - gdaltest.post_reason('failed') - return 'fail' + assert fld_defn.GetWidth() == 5 - ret = CheckFeatures(lyr, field3='baz5') - if ret != 'success': - gdaltest.post_reason('failed') - return ret - - return 'success' + CheckFeatures(lyr, field3='baz5') ############################################################################### # Test AlterFieldDefn() for change of type -def ogr_rfc35_sqlite_4(): +def test_ogr_rfc35_sqlite_4(): if gdaltest.rfc35_sqlite_ds is None: - return 'skip' + pytest.skip() lyr = gdaltest.rfc35_sqlite_ds.GetLayer(0) lyr_defn = lyr.GetLayerDefn() - if lyr.TestCapability(ogr.OLCAlterFieldDefn) != 1: - gdaltest.post_reason('failed') - return 'fail' + assert lyr.TestCapability(ogr.OLCAlterFieldDefn) == 1 fd = ogr.FieldDefn("intfield", ogr.OFTInteger) lyr.CreateField(fd) @@ -334,30 +268,20 @@ def ogr_rfc35_sqlite_4(): lyr.ResetReading() feat = lyr.GetNextFeature() - if feat.GetField("intfield") != 12345: - gdaltest.post_reason('failed') - return 'fail' + assert feat.GetField("intfield") == 12345 feat = None - ret = CheckFeatures(lyr, field3='baz5') - if ret != 'success': - gdaltest.post_reason('failed') - return ret + CheckFeatures(lyr, field3='baz5') fd.SetWidth(5) lyr.AlterFieldDefn(lyr_defn.GetFieldIndex("intfield"), fd, ogr.ALTER_ALL_FLAG) lyr.ResetReading() feat = lyr.GetNextFeature() - if feat.GetField("intfield") != 12345: - gdaltest.post_reason('failed') - return 'fail' + assert feat.GetField("intfield") == 12345 feat = None - ret = CheckFeatures(lyr, field3='baz5') - if ret != 'success': - gdaltest.post_reason('failed') - return ret + CheckFeatures(lyr, field3='baz5') fd.SetWidth(4) lyr.AlterFieldDefn(lyr_defn.GetFieldIndex("intfield"), fd, ogr.ALTER_ALL_FLAG) @@ -365,15 +289,10 @@ def ogr_rfc35_sqlite_4(): lyr.ResetReading() feat = lyr.GetNextFeature() # if feat.GetField("intfield") != 1234: - if feat.GetField("intfield") != 12345: - gdaltest.post_reason('failed') - return 'fail' + assert feat.GetField("intfield") == 12345 feat = None - ret = CheckFeatures(lyr, field3='baz5') - if ret != 'success': - gdaltest.post_reason('failed') - return ret + CheckFeatures(lyr, field3='baz5') fd = ogr.FieldDefn("oldintfld", ogr.OFTString) fd.SetWidth(15) @@ -382,34 +301,23 @@ def ogr_rfc35_sqlite_4(): lyr.ResetReading() feat = lyr.GetNextFeature() # if feat.GetField("oldintfld") != '1234': - if feat.GetField("oldintfld") != '12345': - gdaltest.post_reason('failed') - return 'fail' + assert feat.GetField("oldintfld") == '12345' feat = None - ret = CheckFeatures(lyr, field3='baz5') - if ret != 'success': - gdaltest.post_reason('failed') - return ret + CheckFeatures(lyr, field3='baz5') lyr.DeleteField(lyr_defn.GetFieldIndex("oldintfld")) fd = ogr.FieldDefn("intfield", ogr.OFTInteger) fd.SetWidth(10) - if lyr.CreateField(fd) != 0: - gdaltest.post_reason('failed') - return 'fail' + assert lyr.CreateField(fd) == 0 - if lyr.ReorderField(lyr_defn.GetFieldIndex("intfield"), 0) != 0: - gdaltest.post_reason('failed') - return 'fail' + assert lyr.ReorderField(lyr_defn.GetFieldIndex("intfield"), 0) == 0 lyr.ResetReading() feat = lyr.GetNextFeature() feat.SetField("intfield", 98765) - if lyr.SetFeature(feat) != 0: - gdaltest.post_reason('failed') - return 'fail' + assert lyr.SetFeature(feat) == 0 feat = None fd = ogr.FieldDefn("oldintfld", ogr.OFTString) @@ -418,118 +326,65 @@ def ogr_rfc35_sqlite_4(): lyr.ResetReading() feat = lyr.GetNextFeature() - if feat.GetField("oldintfld") != '98765': - gdaltest.post_reason('failed') - return 'fail' + assert feat.GetField("oldintfld") == '98765' feat = None - ret = CheckFeatures(lyr, field3='baz5') - if ret != 'success': - gdaltest.post_reason('failed') - return ret - - return 'success' + CheckFeatures(lyr, field3='baz5') ############################################################################### # Test DeleteField() -def ogr_rfc35_sqlite_5(): +def test_ogr_rfc35_sqlite_5(): if gdaltest.rfc35_sqlite_ds is None: - return 'skip' + pytest.skip() lyr = gdaltest.rfc35_sqlite_ds.GetLayer(0) lyr_defn = lyr.GetLayerDefn() - if lyr.TestCapability(ogr.OLCDeleteField) != 1: - gdaltest.post_reason('failed') - return 'fail' + assert lyr.TestCapability(ogr.OLCDeleteField) == 1 gdal.PushErrorHandler('CPLQuietErrorHandler') ret = lyr.DeleteField(-1) gdal.PopErrorHandler() - if ret == 0: - gdaltest.post_reason('failed') - return 'fail' + assert ret != 0 gdal.PushErrorHandler('CPLQuietErrorHandler') ret = lyr.DeleteField(lyr.GetLayerDefn().GetFieldCount()) gdal.PopErrorHandler() - if ret == 0: - gdaltest.post_reason('failed') - return 'fail' + assert ret != 0 - if lyr.DeleteField(0) != 0: - gdaltest.post_reason('failed') - return 'fail' + assert lyr.DeleteField(0) == 0 - ret = CheckFeatures(lyr, field3='baz5') - if ret != 'success': - gdaltest.post_reason('failed') - return ret + CheckFeatures(lyr, field3='baz5') - if lyr.DeleteField(lyr_defn.GetFieldIndex('baw20')) != 0: - gdaltest.post_reason('failed') - return 'fail' + assert lyr.DeleteField(lyr_defn.GetFieldIndex('baw20')) == 0 - ret = CheckFeatures(lyr, field3='baz5', field4=None) - if ret != 'success': - gdaltest.post_reason('failed') - return ret + CheckFeatures(lyr, field3='baz5', field4=None) - if lyr.DeleteField(lyr_defn.GetFieldIndex('baz5')) != 0: - gdaltest.post_reason('failed') - return 'fail' + assert lyr.DeleteField(lyr_defn.GetFieldIndex('baz5')) == 0 - ret = CheckFeatures(lyr, field3=None, field4=None) - if ret != 'success': - gdaltest.post_reason('failed') - return ret + CheckFeatures(lyr, field3=None, field4=None) - if lyr.DeleteField(lyr_defn.GetFieldIndex('foo5')) != 0: - gdaltest.post_reason('failed') - return 'fail' + assert lyr.DeleteField(lyr_defn.GetFieldIndex('foo5')) == 0 - if lyr.DeleteField(lyr_defn.GetFieldIndex('bar10')) != 0: - gdaltest.post_reason('failed') - return 'fail' + assert lyr.DeleteField(lyr_defn.GetFieldIndex('bar10')) == 0 - ret = CheckFeatures(lyr, field1=None, field2=None, field3=None, field4=None) - if ret != 'success': - gdaltest.post_reason('failed') - return ret - - return 'success' + CheckFeatures(lyr, field1=None, field2=None, field3=None, field4=None) ############################################################################### # Initiate the test file -def ogr_rfc35_sqlite_cleanup(): +def test_ogr_rfc35_sqlite_cleanup(): if gdaltest.rfc35_sqlite_ds_name is None: - return 'skip' + pytest.skip() gdaltest.rfc35_sqlite_ds = None ogr.GetDriverByName('SQLite').DeleteDataSource(gdaltest.rfc35_sqlite_ds_name) - return 'success' - - -gdaltest_list = [ - ogr_rfc35_sqlite_1, - ogr_rfc35_sqlite_2, - ogr_rfc35_sqlite_3, - ogr_rfc35_sqlite_4, - ogr_rfc35_sqlite_5, - ogr_rfc35_sqlite_cleanup] - - -if __name__ == '__main__': - gdaltest.setup_run('ogr_rfc35_sqlite') - gdaltest.run_tests(gdaltest_list) - sys.exit(gdaltest.summarize()) diff --git a/autotest/ogr/ogr_rfc41.py b/autotest/ogr/ogr_rfc41.py index 08669b2fdfb3..096c8ca44064 100755 --- a/autotest/ogr/ogr_rfc41.py +++ b/autotest/ogr/ogr_rfc41.py @@ -29,352 +29,201 @@ # DEALINGS IN THE SOFTWARE. ############################################################################### -import sys -sys.path.append('../pymod') - -import gdaltest from osgeo import ogr from osgeo import osr from osgeo import gdal +import pytest + +from ogr.ogr_sql_sqlite import require_ogr_sql_sqlite # noqa ############################################################################### # Test OGRGeomFieldDefn class -def ogr_rfc41_1(): +def test_ogr_rfc41_1(): gfld_defn = ogr.GeomFieldDefn() # Check default values - if gfld_defn.GetName() != '': - gdaltest.post_reason('fail') - return 'fail' - if gfld_defn.GetType() != ogr.wkbUnknown: - gdaltest.post_reason('fail') - return 'fail' - if gfld_defn.GetSpatialRef() is not None: - gdaltest.post_reason('fail') - return 'fail' - if gfld_defn.IsIgnored() != 0: - gdaltest.post_reason('fail') - return 'fail' + assert gfld_defn.GetName() == '' + assert gfld_defn.GetType() == ogr.wkbUnknown + assert gfld_defn.GetSpatialRef() is None + assert gfld_defn.IsIgnored() == 0 # Test SetName() / GetName() gfld_defn.SetName('foo') - if gfld_defn.GetName() != 'foo': - gdaltest.post_reason('fail') - return 'fail' + assert gfld_defn.GetName() == 'foo' # Test SetType() / GetType() gfld_defn.SetType(ogr.wkbPoint) - if gfld_defn.GetType() != ogr.wkbPoint: - gdaltest.post_reason('fail') - return 'fail' + assert gfld_defn.GetType() == ogr.wkbPoint # Test SetSpatialRef() / GetSpatialRef() sr = osr.SpatialReference() gfld_defn.SetSpatialRef(sr) got_sr = gfld_defn.GetSpatialRef() - if got_sr.IsSame(sr) == 0: - gdaltest.post_reason('fail') - return 'fail' + assert got_sr.IsSame(sr) != 0 gfld_defn.SetSpatialRef(None) - if gfld_defn.GetSpatialRef() is not None: - gdaltest.post_reason('fail') - return 'fail' + assert gfld_defn.GetSpatialRef() is None gfld_defn.SetSpatialRef(sr) # Test SetIgnored() / IsIgnored() gfld_defn.SetIgnored(1) - if gfld_defn.IsIgnored() != 1: - gdaltest.post_reason('fail') - return 'fail' + assert gfld_defn.IsIgnored() == 1 # Test setting invalid value old_val = gfld_defn.GetType() gdal.PushErrorHandler('CPLQuietErrorHandler') gfld_defn.SetType(-3) gdal.PopErrorHandler() - if gfld_defn.GetType() != old_val: - gdaltest.post_reason('fail') - return 'fail' + assert gfld_defn.GetType() == old_val gfld_defn = None - return 'success' - ############################################################################### # Test OGRFeatureDefn methods related to OGRGeomFieldDefn class -def ogr_rfc41_2(): +def test_ogr_rfc41_2(): # Check implicit geometry field creation feature_defn = ogr.FeatureDefn() - if feature_defn.GetGeomFieldCount() != 1: - gdaltest.post_reason('fail') - return 'fail' - if feature_defn.GetGeomType() != ogr.wkbUnknown: - gdaltest.post_reason('fail') - return 'fail' + assert feature_defn.GetGeomFieldCount() == 1 + assert feature_defn.GetGeomType() == ogr.wkbUnknown # Test IsSame() - if feature_defn.IsSame(feature_defn) != 1: - gdaltest.post_reason('fail') - return 'fail' + assert feature_defn.IsSame(feature_defn) == 1 other_feature_defn = ogr.FeatureDefn() - if feature_defn.IsSame(other_feature_defn) != 1: - gdaltest.post_reason('fail') - return 'fail' + assert feature_defn.IsSame(other_feature_defn) == 1 other_feature_defn.GetGeomFieldDefn(0).SetSpatialRef(osr.SpatialReference()) - if feature_defn.IsSame(other_feature_defn) != 0: - gdaltest.post_reason('fail') - return 'fail' + assert feature_defn.IsSame(other_feature_defn) == 0 feature_defn.GetGeomFieldDefn(0).SetSpatialRef(osr.SpatialReference()) - if feature_defn.IsSame(other_feature_defn) != 1: - gdaltest.post_reason('fail') - return 'fail' + assert feature_defn.IsSame(other_feature_defn) == 1 other_feature_defn.GetGeomFieldDefn(0).SetSpatialRef(None) - if feature_defn.IsSame(other_feature_defn) != 0: - gdaltest.post_reason('fail') - return 'fail' + assert feature_defn.IsSame(other_feature_defn) == 0 feature_defn = None feature_defn = ogr.FeatureDefn() # Check changing geometry type feature_defn.SetGeomType(ogr.wkbPoint) - if feature_defn.GetGeomType() != ogr.wkbPoint: - gdaltest.post_reason('fail') - return 'fail' - if feature_defn.GetGeomFieldDefn(0).GetType() != ogr.wkbPoint: - gdaltest.post_reason('fail') - return 'fail' + assert feature_defn.GetGeomType() == ogr.wkbPoint + assert feature_defn.GetGeomFieldDefn(0).GetType() == ogr.wkbPoint # Check setting to wkbNone and implicitly destroying the field. for _ in range(2): feature_defn.SetGeomType(ogr.wkbNone) - if feature_defn.GetGeomFieldCount() != 0: - gdaltest.post_reason('fail') - return 'fail' - if feature_defn.GetGeomType() != ogr.wkbNone: - gdaltest.post_reason('fail') - return 'fail' + assert feature_defn.GetGeomFieldCount() == 0 + assert feature_defn.GetGeomType() == ogr.wkbNone # Recreate the field for t in [ogr.wkbPoint, ogr.wkbLineString]: feature_defn.SetGeomType(t) - if feature_defn.GetGeomFieldCount() != 1: - gdaltest.post_reason('fail') - return 'fail' - if feature_defn.GetGeomType() != t: - gdaltest.post_reason('fail') - return 'fail' - if feature_defn.GetGeomFieldDefn(0).GetType() != t: - gdaltest.post_reason('fail') - return 'fail' + assert feature_defn.GetGeomFieldCount() == 1 + assert feature_defn.GetGeomType() == t + assert feature_defn.GetGeomFieldDefn(0).GetType() == t # Test setting invalid value old_val = feature_defn.GetGeomType() gdal.PushErrorHandler('CPLQuietErrorHandler') feature_defn.SetGeomType(-3) gdal.PopErrorHandler() - if feature_defn.GetGeomType() != old_val: - gdaltest.post_reason('fail') - return 'fail' + assert feature_defn.GetGeomType() == old_val # Test SetIgnored() / IsIgnored() - if feature_defn.IsGeometryIgnored() != 0: - gdaltest.post_reason('fail') - return 'fail' - if feature_defn.GetGeomFieldDefn(0).IsIgnored() != 0: - gdaltest.post_reason('fail') - return 'fail' + assert feature_defn.IsGeometryIgnored() == 0 + assert feature_defn.GetGeomFieldDefn(0).IsIgnored() == 0 feature_defn.SetGeometryIgnored(1) - if feature_defn.IsGeometryIgnored() != 1: - gdaltest.post_reason('fail') - return 'fail' - if feature_defn.GetGeomFieldDefn(0).IsIgnored() != 1: - gdaltest.post_reason('fail') - return 'fail' + assert feature_defn.IsGeometryIgnored() == 1 + assert feature_defn.GetGeomFieldDefn(0).IsIgnored() == 1 # Test wrong index values for GetGeomFieldDefn() for idx in [-1, 1]: gdal.PushErrorHandler('CPLQuietErrorHandler') ret = feature_defn.GetGeomFieldDefn(idx) gdal.PopErrorHandler() - if ret is not None: - gdaltest.post_reason('fail') - return 'fail' + assert ret is None # Test GetGeomFieldIndex() - if feature_defn.GetGeomFieldIndex("") != 0: - gdaltest.post_reason('fail') - return 'fail' - if feature_defn.GetGeomFieldIndex("invalid") != -1: - gdaltest.post_reason('fail') - return 'fail' + assert feature_defn.GetGeomFieldIndex("") == 0 + assert feature_defn.GetGeomFieldIndex("invalid") == -1 # Test AddGeomFieldDefn() gfld_defn = ogr.GeomFieldDefn('polygon_field', ogr.wkbPolygon) feature_defn.AddGeomFieldDefn(gfld_defn) - if feature_defn.GetGeomFieldCount() != 2: - gdaltest.post_reason('fail') - return 'fail' - if feature_defn.GetGeomFieldIndex("polygon_field") != 1: - gdaltest.post_reason('fail') - return 'fail' - if feature_defn.GetGeomFieldDefn(1).GetName() != 'polygon_field': - gdaltest.post_reason('fail') - return 'fail' + assert feature_defn.GetGeomFieldCount() == 2 + assert feature_defn.GetGeomFieldIndex("polygon_field") == 1 + assert feature_defn.GetGeomFieldDefn(1).GetName() == 'polygon_field' # Test DeleteGeomFieldDefn() : error cases - if feature_defn.DeleteGeomFieldDefn(-1) == 0: - gdaltest.post_reason('fail') - return 'fail' - if feature_defn.DeleteGeomFieldDefn(2) == 0: - gdaltest.post_reason('fail') - return 'fail' - if feature_defn.GetGeomFieldCount() != 2: - gdaltest.post_reason('fail') - return 'fail' + assert feature_defn.DeleteGeomFieldDefn(-1) != 0 + assert feature_defn.DeleteGeomFieldDefn(2) != 0 + assert feature_defn.GetGeomFieldCount() == 2 # Test DeleteGeomFieldDefn() : valid cases - if feature_defn.DeleteGeomFieldDefn(0) != 0: - gdaltest.post_reason('fail') - return 'fail' - if feature_defn.GetGeomFieldCount() != 1: - gdaltest.post_reason('fail') - return 'fail' - if feature_defn.GetGeomFieldIndex("polygon_field") != 0: - gdaltest.post_reason('fail') - return 'fail' - - if feature_defn.DeleteGeomFieldDefn(0) != 0: - gdaltest.post_reason('fail') - return 'fail' - if feature_defn.GetGeomFieldCount() != 0: - gdaltest.post_reason('fail') - return 'fail' - - if feature_defn.IsSame(feature_defn) != 1: - gdaltest.post_reason('fail') - return 'fail' - if feature_defn.IsSame(ogr.FeatureDefn()) != 0: - gdaltest.post_reason('fail') - return 'fail' + assert feature_defn.DeleteGeomFieldDefn(0) == 0 + assert feature_defn.GetGeomFieldCount() == 1 + assert feature_defn.GetGeomFieldIndex("polygon_field") == 0 - feature_defn = None + assert feature_defn.DeleteGeomFieldDefn(0) == 0 + assert feature_defn.GetGeomFieldCount() == 0 + + assert feature_defn.IsSame(feature_defn) == 1 + assert feature_defn.IsSame(ogr.FeatureDefn()) == 0 - return 'success' + feature_defn = None ############################################################################### # Test OGRFeature methods -def ogr_rfc41_3(): +def test_ogr_rfc41_3(): # Test with just one geometry field feature_defn = ogr.FeatureDefn() feature = ogr.Feature(feature_defn) - if feature.GetGeomFieldCount() != 1: - gdaltest.post_reason('fail') - return 'fail' - if feature.GetGeomFieldDefnRef(0).GetName() != '': - gdaltest.post_reason('fail') - return 'fail' - if feature.GetGeomFieldDefnRef(0).GetType() != ogr.wkbUnknown: - gdaltest.post_reason('fail') - return 'fail' - if feature.GetGeomFieldIndex('') != 0: - gdaltest.post_reason('fail') - return 'fail' - if feature.GetGeomFieldIndex('non_existing') != -1: - gdaltest.post_reason('fail') - return 'fail' - if feature.GetGeomFieldRef(-1) is not None: - gdaltest.post_reason('fail') - return 'fail' - if feature.GetGeomFieldRef(0) is not None: - gdaltest.post_reason('fail') - return 'fail' - if feature.GetGeomFieldRef(1) is not None: - gdaltest.post_reason('fail') - return 'fail' + assert feature.GetGeomFieldCount() == 1 + assert feature.GetGeomFieldDefnRef(0).GetName() == '' + assert feature.GetGeomFieldDefnRef(0).GetType() == ogr.wkbUnknown + assert feature.GetGeomFieldIndex('') == 0 + assert feature.GetGeomFieldIndex('non_existing') == -1 + assert feature.GetGeomFieldRef(-1) is None + assert feature.GetGeomFieldRef(0) is None + assert feature.GetGeomFieldRef(1) is None feature_clone_without_geom = feature.Clone() - if not feature.Equal(feature_clone_without_geom): - gdaltest.post_reason('fail') - return 'fail' - if feature.SetGeomField(0, ogr.Geometry(ogr.wkbPoint)) != 0: - gdaltest.post_reason('fail') - return 'fail' - if feature.GetGeomFieldRef(0).ExportToWkt() != 'POINT EMPTY': - gdaltest.post_reason('fail') - return 'fail' - if not feature.Equal(feature.Clone()): - gdaltest.post_reason('fail') - return 'fail' - if feature.Equal(feature_clone_without_geom): - gdaltest.post_reason('fail') - return 'fail' + assert feature.Equal(feature_clone_without_geom) + assert feature.SetGeomField(0, ogr.Geometry(ogr.wkbPoint)) == 0 + assert feature.GetGeomFieldRef(0).ExportToWkt() == 'POINT EMPTY' + assert feature.Equal(feature.Clone()) + assert not feature.Equal(feature_clone_without_geom) feature_clone_with_other_geom = feature.Clone() feature_clone_with_other_geom.SetGeometry(ogr.Geometry(ogr.wkbLineString)) - if feature.Equal(feature_clone_with_other_geom): - gdaltest.post_reason('fail') - return 'fail' - if feature.SetGeomFieldDirectly(-1, None) == 0: - gdaltest.post_reason('fail') - return 'fail' - if feature.SetGeomFieldDirectly(0, ogr.Geometry(ogr.wkbLineString)) != 0: - gdaltest.post_reason('fail') - return 'fail' - if feature.GetGeomFieldRef(0).ExportToWkt() != 'LINESTRING EMPTY': - gdaltest.post_reason('fail') - return 'fail' + assert not feature.Equal(feature_clone_with_other_geom) + assert feature.SetGeomFieldDirectly(-1, None) != 0 + assert feature.SetGeomFieldDirectly(0, ogr.Geometry(ogr.wkbLineString)) == 0 + assert feature.GetGeomFieldRef(0).ExportToWkt() == 'LINESTRING EMPTY' feature_clone_with_geom = feature.Clone() - if feature.SetGeomFieldDirectly(0, None) != 0: - gdaltest.post_reason('fail') - return 'fail' - if feature.GetGeomFieldRef(0) is not None: - gdaltest.post_reason('fail') - return 'fail' - if feature.Equal(feature_clone_with_geom): - gdaltest.post_reason('fail') - return 'fail' + assert feature.SetGeomFieldDirectly(0, None) == 0 + assert feature.GetGeomFieldRef(0) is None + assert not feature.Equal(feature_clone_with_geom) feature = None # Test one a feature with 0 geometry field feature_defn = ogr.FeatureDefn() feature_defn.SetGeomType(ogr.wkbNone) feature = ogr.Feature(feature_defn) - if not feature.Equal(feature.Clone()): - gdaltest.post_reason('fail') - return 'fail' - if feature.GetGeomFieldCount() != 0: - gdaltest.post_reason('fail') - return 'fail' + assert feature.Equal(feature.Clone()) + assert feature.GetGeomFieldCount() == 0 # This used to work before RFC 41, but it no longer will - if feature.SetGeometry(ogr.Geometry(ogr.wkbPoint)) == 0: - gdaltest.post_reason('fail') - return 'fail' - if feature.SetGeomField(0, ogr.Geometry(ogr.wkbPoint)) == 0: - gdaltest.post_reason('fail') - return 'fail' - if feature.GetGeometryRef() is not None: - gdaltest.post_reason('fail') - return 'fail' - if feature.GetGeomFieldRef(0) is not None: - gdaltest.post_reason('fail') - return 'fail' - if feature.SetGeometryDirectly(ogr.Geometry(ogr.wkbPoint)) == 0: - gdaltest.post_reason('fail') - return 'fail' - if feature.SetGeomFieldDirectly(0, ogr.Geometry(ogr.wkbPoint)) == 0: - gdaltest.post_reason('fail') - return 'fail' + assert feature.SetGeometry(ogr.Geometry(ogr.wkbPoint)) != 0 + assert feature.SetGeomField(0, ogr.Geometry(ogr.wkbPoint)) != 0 + assert feature.GetGeometryRef() is None + assert feature.GetGeomFieldRef(0) is None + assert feature.SetGeometryDirectly(ogr.Geometry(ogr.wkbPoint)) != 0 + assert feature.SetGeomFieldDirectly(0, ogr.Geometry(ogr.wkbPoint)) != 0 feature = None # Test one a feature with several geometry fields @@ -387,23 +236,13 @@ def ogr_rfc41_3(): feature = ogr.Feature(feature_defn) feature.SetGeomField(0, ogr.Geometry(ogr.wkbPolygon)) feature.SetGeomField(1, ogr.Geometry(ogr.wkbPoint)) - if feature.GetGeomFieldRef(0).ExportToWkt() != 'POLYGON EMPTY': - gdaltest.post_reason('fail') - return 'fail' - if feature.GetGeomFieldRef(1).ExportToWkt() != 'POINT EMPTY': - gdaltest.post_reason('fail') - return 'fail' - if not feature.Equal(feature.Clone()): - gdaltest.post_reason('fail') - return 'fail' + assert feature.GetGeomFieldRef(0).ExportToWkt() == 'POLYGON EMPTY' + assert feature.GetGeomFieldRef(1).ExportToWkt() == 'POINT EMPTY' + assert feature.Equal(feature.Clone()) other_feature = ogr.Feature(feature_defn) - if feature.Equal(other_feature): - gdaltest.post_reason('fail') - return 'fail' + assert not feature.Equal(other_feature) other_feature.SetFrom(feature) - if not feature.Equal(other_feature): - gdaltest.post_reason('fail') - return 'fail' + assert feature.Equal(other_feature) # Test that in SetFrom() where target has a single geometry field, # we get the first geometry of the source even if we cannot find a @@ -411,33 +250,21 @@ def ogr_rfc41_3(): feature_defn_default = ogr.FeatureDefn() feature_default = ogr.Feature(feature_defn_default) feature_default.SetFrom(feature) - if feature_default.GetGeomFieldRef(0).ExportToWkt() != 'POLYGON EMPTY': - gdaltest.post_reason('fail') - return 'fail' - - return 'success' + assert feature_default.GetGeomFieldRef(0).ExportToWkt() == 'POLYGON EMPTY' ############################################################################### # Test OGRLayer methods -def ogr_rfc41_4(): +def test_ogr_rfc41_4(): ds = ogr.GetDriverByName('memory').CreateDataSource('') - if ds.TestCapability(ogr.ODsCCreateGeomFieldAfterCreateLayer) == 0: - gdaltest.post_reason('fail') - return 'fail' + assert ds.TestCapability(ogr.ODsCCreateGeomFieldAfterCreateLayer) != 0 sr = osr.SpatialReference() lyr = ds.CreateLayer('test', geom_type=ogr.wkbPoint, srs=sr) - if lyr.TestCapability(ogr.OLCCreateGeomField) == 0: - gdaltest.post_reason('fail') - return 'fail' - if lyr.GetSpatialRef().IsSame(sr) == 0: - gdaltest.post_reason('fail') - return 'fail' - if lyr.GetLayerDefn().GetGeomFieldDefn(0).GetSpatialRef().IsSame(sr) == 0: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.TestCapability(ogr.OLCCreateGeomField) != 0 + assert lyr.GetSpatialRef().IsSame(sr) != 0 + assert lyr.GetLayerDefn().GetGeomFieldDefn(0).GetSpatialRef().IsSame(sr) != 0 lyr.GetLayerDefn().GetGeomFieldDefn(0).SetName('a_name') feat = ogr.Feature(lyr.GetLayerDefn()) feat.SetGeometry(ogr.CreateGeometryFromWkt('POINT (1 2)')) @@ -445,9 +272,7 @@ def ogr_rfc41_4(): lyr.ResetReading() feat = lyr.GetNextFeature() geom = feat.GetGeometryRef() - if geom.GetSpatialReference().IsSame(sr) == 0: - gdaltest.post_reason('fail') - return 'fail' + assert geom.GetSpatialReference().IsSame(sr) != 0 feat = None lyr.CreateGeomField(ogr.GeomFieldDefn('another_geom_field', ogr.wkbPolygon)) lyr.ResetReading() @@ -457,75 +282,53 @@ def ogr_rfc41_4(): lyr.ResetReading() feat = lyr.GetNextFeature() geom = feat.GetGeomFieldRef(0) - if geom.ExportToWkt() != 'POINT (1 2)': - gdaltest.post_reason('fail') - return 'fail' + assert geom.ExportToWkt() == 'POINT (1 2)' geom = feat.GetGeomFieldRef('another_geom_field') - if geom.ExportToWkt() != 'POLYGON ((10 10,10 11,11 11,11 10,10 10))': - gdaltest.post_reason('fail') - return 'fail' + assert geom.ExportToWkt() == 'POLYGON ((10 10,10 11,11 11,11 10,10 10))' # Test GetExtent() got_extent = lyr.GetExtent(geom_field=1) - if got_extent != (10.0, 11.0, 10.0, 11.0): - gdaltest.post_reason('fail') - return 'fail' + assert got_extent == (10.0, 11.0, 10.0, 11.0) # Test invalid geometry field index gdal.ErrorReset() gdal.PushErrorHandler('CPLQuietErrorHandler') got_extent = lyr.GetExtent(geom_field=2) gdal.PopErrorHandler() - if gdal.GetLastErrorMsg() == '': - gdaltest.post_reason('fail') - return 'fail' + assert gdal.GetLastErrorMsg() != '' # Test SetSpatialFilter() lyr.SetSpatialFilter(1, ogr.CreateGeometryFromWkt('POLYGON ((-10 10,-10 11,-11 11,-11 10,-10 10))')) lyr.ResetReading() feat = lyr.GetNextFeature() - if feat is not None: - gdaltest.post_reason('fail') - return 'fail' + assert feat is None lyr.SetSpatialFilter(1, ogr.CreateGeometryFromWkt('POLYGON ((10 10,10 11,11 11,11 10,10 10))')) lyr.ResetReading() feat = lyr.GetNextFeature() - if feat is None: - gdaltest.post_reason('fail') - return 'fail' + assert feat is not None lyr.SetSpatialFilterRect(1, 10, 10, 11, 11) lyr.ResetReading() feat = lyr.GetNextFeature() - if feat is None: - gdaltest.post_reason('fail') - return 'fail' + assert feat is not None # Test invalid spatial filter index gdal.ErrorReset() gdal.PushErrorHandler('CPLQuietErrorHandler') lyr.SetSpatialFilterRect(2, 0, 0, 0, 0) gdal.PopErrorHandler() - if gdal.GetLastErrorMsg() == '': - gdaltest.post_reason('fail') - return 'fail' + assert gdal.GetLastErrorMsg() != '' lyr.SetSpatialFilter(None) another_lyr = ds.CopyLayer(lyr, 'dup_test') dup_feat = another_lyr.GetNextFeature() geom = dup_feat.GetGeomFieldRef('a_name') - if geom.ExportToWkt() != 'POINT (1 2)': - gdaltest.post_reason('fail') - return 'fail' + assert geom.ExportToWkt() == 'POINT (1 2)' geom = dup_feat.GetGeomFieldRef('another_geom_field') - if geom.ExportToWkt() != 'POLYGON ((10 10,10 11,11 11,11 10,10 10))': - gdaltest.post_reason('fail') - return 'fail' - - return 'success' + assert geom.ExportToWkt() == 'POLYGON ((10 10,10 11,11 11,11 10,10 10))' ############################################################################### # Test Python field accessors facilities -def ogr_rfc41_5(): +def test_ogr_rfc41_5(): feature_defn = ogr.FeatureDefn() field_defn = ogr.FieldDefn('strfield', ogr.OFTString) @@ -534,88 +337,51 @@ def ogr_rfc41_5(): f = ogr.Feature(feature_defn) - if f['strfield'] is not None: - gdaltest.post_reason('fail') - return 'fail' - if f.strfield is not None: - gdaltest.post_reason('fail') - return 'fail' - - if f['geomfield'] is not None: - gdaltest.post_reason('fail') - return 'fail' - if f.geomfield is not None: - gdaltest.post_reason('fail') - return 'fail' - - try: + assert f['strfield'] is None + assert f.strfield is None + + assert f['geomfield'] is None + assert f.geomfield is None + + with pytest.raises(KeyError): f['nonexistent_field'] - gdaltest.post_reason('fail') - return 'fail' - except KeyError: - pass + - try: + with pytest.raises(AttributeError): f.nonexistent_field - gdaltest.post_reason('fail') - return 'fail' - except AttributeError: - pass + - try: + with pytest.raises(KeyError): f['nonexistent_field'] = 'foo' - gdaltest.post_reason('fail') - return 'fail' - except KeyError: - pass + # This works. Default Python behaviour. Stored in a dictionary f.nonexistent_field = 'bar' - if f.nonexistent_field != 'bar': - gdaltest.post_reason('fail') - return 'fail' + assert f.nonexistent_field == 'bar' f['strfield'] = 'foo' - if f['strfield'] != 'foo': - gdaltest.post_reason('fail') - return 'fail' - if f.strfield != 'foo': - gdaltest.post_reason('fail') - return 'fail' + assert f['strfield'] == 'foo' + assert f.strfield == 'foo' f.strfield = 'bar' - if f['strfield'] != 'bar': - gdaltest.post_reason('fail') - return 'fail' - if f.strfield != 'bar': - gdaltest.post_reason('fail') - return 'fail' + assert f['strfield'] == 'bar' + assert f.strfield == 'bar' wkt = 'POINT EMPTY' f['geomfield'] = ogr.CreateGeometryFromWkt(wkt) - if f['geomfield'].ExportToWkt() != wkt: - gdaltest.post_reason('fail') - return 'fail' - if f.geomfield.ExportToWkt() != wkt: - gdaltest.post_reason('fail') - return 'fail' + assert f['geomfield'].ExportToWkt() == wkt + assert f.geomfield.ExportToWkt() == wkt wkt2 = 'POLYGON EMPTY' f.geomfield = ogr.CreateGeometryFromWkt(wkt2) - if f['geomfield'].ExportToWkt() != wkt2: - gdaltest.post_reason('fail') - return 'fail' - if f.geomfield.ExportToWkt() != wkt2: - gdaltest.post_reason('fail') - return 'fail' - - return 'success' + assert f['geomfield'].ExportToWkt() == wkt2 + assert f.geomfield.ExportToWkt() == wkt2 ############################################################################### # Test OGRSQL with geometries -def ogr_rfc41_6(): +def test_ogr_rfc41_6(): ds = ogr.GetDriverByName('memory').CreateDataSource('') sr = osr.SpatialReference() @@ -639,158 +405,102 @@ def ogr_rfc41_6(): 'SELECT intfield, geomfield FROM poly', 'SELECT geomfield, intfield FROM poly']: sql_lyr = ds.ExecuteSQL(sql) - if sql_lyr.GetLayerDefn().GetGeomFieldDefn(0).GetType() != ogr.wkbPolygon: - gdaltest.post_reason('fail') - return 'fail' - if sql_lyr.GetLayerDefn().GetGeomFieldDefn(0).GetSpatialRef() is None: - gdaltest.post_reason('fail') - return 'fail' + assert sql_lyr.GetLayerDefn().GetGeomFieldDefn(0).GetType() == ogr.wkbPolygon + assert sql_lyr.GetLayerDefn().GetGeomFieldDefn(0).GetSpatialRef() is not None feat = sql_lyr.GetNextFeature() - if feat.GetField('intfield') != 1: - gdaltest.post_reason('fail') - return 'fail' - if feat.GetGeomFieldRef('geomfield') is None: - gdaltest.post_reason('fail') - return 'fail' + assert feat.GetField('intfield') == 1 + assert feat.GetGeomFieldRef('geomfield') is not None feat = sql_lyr.GetNextFeature() - if feat.GetGeomFieldRef('geomfield') is not None: - gdaltest.post_reason('fail') - return 'fail' + assert feat.GetGeomFieldRef('geomfield') is None feat = None ds.ReleaseResultSet(sql_lyr) # Test CAST(geometry_field AS GEOMETRY) sql_lyr = ds.ExecuteSQL('SELECT CAST(geomfield AS GEOMETRY) AS mygeom FROM poly WHERE CAST(geomfield AS GEOMETRY) IS NOT NULL') - if sql_lyr.GetLayerDefn().GetGeomFieldDefn(0).GetType() != ogr.wkbUnknown: - gdaltest.post_reason('fail') - return 'fail' - if sql_lyr.GetLayerDefn().GetGeomFieldDefn(0).GetSpatialRef() is not None: - gdaltest.post_reason('fail') - return 'fail' + assert sql_lyr.GetLayerDefn().GetGeomFieldDefn(0).GetType() == ogr.wkbUnknown + assert sql_lyr.GetLayerDefn().GetGeomFieldDefn(0).GetSpatialRef() is None feat = sql_lyr.GetNextFeature() - if feat.GetGeomFieldRef('mygeom') is None: - gdaltest.post_reason('fail') - return 'fail' + assert feat.GetGeomFieldRef('mygeom') is not None feat = None ds.ReleaseResultSet(sql_lyr) # Test CAST(xxx AS GEOMETRY(POLYGON)) sql_lyr = ds.ExecuteSQL('SELECT CAST(geomfield AS GEOMETRY(POLYGON)) AS mygeom FROM poly WHERE CAST(geomfield AS GEOMETRY(POLYGON)) IS NOT NULL') - if sql_lyr.GetLayerDefn().GetGeomFieldDefn(0).GetType() != ogr.wkbPolygon: - gdaltest.post_reason('fail') - return 'fail' - if sql_lyr.GetLayerDefn().GetGeomFieldDefn(0).GetSpatialRef() is not None: - gdaltest.post_reason('fail') - return 'fail' + assert sql_lyr.GetLayerDefn().GetGeomFieldDefn(0).GetType() == ogr.wkbPolygon + assert sql_lyr.GetLayerDefn().GetGeomFieldDefn(0).GetSpatialRef() is None feat = sql_lyr.GetNextFeature() - if feat.GetGeomFieldRef('mygeom') is None: - gdaltest.post_reason('fail') - return 'fail' + assert feat.GetGeomFieldRef('mygeom') is not None feat = None ds.ReleaseResultSet(sql_lyr) # Test CAST(xxx AS GEOMETRY(POLYGON,4326)) sql_lyr = ds.ExecuteSQL('SELECT CAST(geomfield AS GEOMETRY(POLYGON,4326)) AS mygeom FROM poly WHERE CAST(geomfield AS GEOMETRY(POLYGON,4326)) IS NOT NULL') - if sql_lyr.GetLayerDefn().GetGeomFieldDefn(0).GetType() != ogr.wkbPolygon: - gdaltest.post_reason('fail') - return 'fail' - if sql_lyr.GetLayerDefn().GetGeomFieldDefn(0).GetSpatialRef().ExportToWkt().find('4326') < 0: - gdaltest.post_reason('fail') - return 'fail' + assert sql_lyr.GetLayerDefn().GetGeomFieldDefn(0).GetType() == ogr.wkbPolygon + assert sql_lyr.GetLayerDefn().GetGeomFieldDefn(0).GetSpatialRef().ExportToWkt().find('4326') >= 0 feat = sql_lyr.GetNextFeature() - if feat.GetGeomFieldRef('mygeom') is None: - gdaltest.post_reason('fail') - return 'fail' + assert feat.GetGeomFieldRef('mygeom') is not None feat = None ds.ReleaseResultSet(sql_lyr) # Test CAST(a_multipolygon AS GEOMETRY(POLYGON)) sql_lyr = ds.ExecuteSQL("SELECT CAST('MULTIPOLYGON (((0 0,0 1,1 1,1 0,0 0)))' AS GEOMETRY(POLYGON)) AS mygeom FROM poly") feat = sql_lyr.GetNextFeature() - if feat.GetGeomFieldRef('mygeom').ExportToWkt() != 'POLYGON ((0 0,0 1,1 1,1 0,0 0))': - gdaltest.post_reason('fail') - return 'fail' + assert feat.GetGeomFieldRef('mygeom').ExportToWkt() == 'POLYGON ((0 0,0 1,1 1,1 0,0 0))' feat = None ds.ReleaseResultSet(sql_lyr) # Test CAST(a_polygon AS GEOMETRY(MULTIPOLYGON)) sql_lyr = ds.ExecuteSQL("SELECT CAST('POLYGON ((0 0,0 1,1 1,1 0,0 0))' AS GEOMETRY(MULTIPOLYGON)) AS mygeom FROM poly") feat = sql_lyr.GetNextFeature() - if feat.GetGeomFieldRef('mygeom').ExportToWkt() != 'MULTIPOLYGON (((0 0,0 1,1 1,1 0,0 0)))': - gdaltest.post_reason('fail') - return 'fail' + assert feat.GetGeomFieldRef('mygeom').ExportToWkt() == 'MULTIPOLYGON (((0 0,0 1,1 1,1 0,0 0)))' feat = None ds.ReleaseResultSet(sql_lyr) # Test CAST(a_multilinestring AS GEOMETRY(LINESTRING)) sql_lyr = ds.ExecuteSQL("SELECT CAST('MULTILINESTRING ((0 0,0 1,1 1,1 0,0 0))' AS GEOMETRY(LINESTRING)) AS mygeom FROM poly") feat = sql_lyr.GetNextFeature() - if feat.GetGeomFieldRef('mygeom').ExportToWkt() != 'LINESTRING (0 0,0 1,1 1,1 0,0 0)': - gdaltest.post_reason('fail') - return 'fail' + assert feat.GetGeomFieldRef('mygeom').ExportToWkt() == 'LINESTRING (0 0,0 1,1 1,1 0,0 0)' feat = None ds.ReleaseResultSet(sql_lyr) # Test CAST(a_linestring AS GEOMETRY(MULTILINESTRING)) sql_lyr = ds.ExecuteSQL("SELECT CAST('LINESTRING (0 0,0 1,1 1,1 0,0 0)' AS GEOMETRY(MULTILINESTRING)) AS mygeom FROM poly") feat = sql_lyr.GetNextFeature() - if feat.GetGeomFieldRef('mygeom').ExportToWkt() != 'MULTILINESTRING ((0 0,0 1,1 1,1 0,0 0))': - gdaltest.post_reason('fail') - return 'fail' + assert feat.GetGeomFieldRef('mygeom').ExportToWkt() == 'MULTILINESTRING ((0 0,0 1,1 1,1 0,0 0))' feat = None ds.ReleaseResultSet(sql_lyr) # Test expression with cast CHARACTER <--> GEOMETRY sql_lyr = ds.ExecuteSQL('SELECT CAST(CAST(geomfield AS CHARACTER) AS GEOMETRY) AS mygeom, intfield FROM poly') - if sql_lyr.GetLayerDefn().GetGeomFieldDefn(0).GetType() != ogr.wkbUnknown: - gdaltest.post_reason('fail') - return 'fail' - if sql_lyr.GetLayerDefn().GetGeomFieldDefn(0).GetSpatialRef() is not None: - gdaltest.post_reason('fail') - return 'fail' + assert sql_lyr.GetLayerDefn().GetGeomFieldDefn(0).GetType() == ogr.wkbUnknown + assert sql_lyr.GetLayerDefn().GetGeomFieldDefn(0).GetSpatialRef() is None feat = sql_lyr.GetNextFeature() - if feat.GetField('intfield') != 1: - gdaltest.post_reason('fail') - return 'fail' - if feat.GetGeomFieldRef('mygeom') is None: - gdaltest.post_reason('fail') - return 'fail' + assert feat.GetField('intfield') == 1 + assert feat.GetGeomFieldRef('mygeom') is not None feat = None ds.ReleaseResultSet(sql_lyr) # Test CAST(NULL AS GEOMETRY) sql_lyr = ds.ExecuteSQL('SELECT CAST(NULL AS GEOMETRY) FROM poly') - if sql_lyr.GetLayerDefn().GetGeomFieldDefn(0).GetType() != ogr.wkbUnknown: - gdaltest.post_reason('fail') - return 'fail' + assert sql_lyr.GetLayerDefn().GetGeomFieldDefn(0).GetType() == ogr.wkbUnknown feat = sql_lyr.GetNextFeature() - if feat.GetGeomFieldRef('') is not None: - gdaltest.post_reason('fail') - return 'fail' + assert feat.GetGeomFieldRef('') is None feat = None ds.ReleaseResultSet(sql_lyr) # Test CAST(stringfield AS GEOMETRY) sql_lyr = ds.ExecuteSQL('SELECT CAST(wkt AS GEOMETRY) FROM poly') - if sql_lyr.GetLayerDefn().GetGeomFieldDefn(0).GetType() != ogr.wkbUnknown: - gdaltest.post_reason('fail') - return 'fail' + assert sql_lyr.GetLayerDefn().GetGeomFieldDefn(0).GetType() == ogr.wkbUnknown feat = sql_lyr.GetNextFeature() - if feat.GetGeomFieldRef('wkt').ExportToWkt() != 'POINT (0 0)': - gdaltest.post_reason('fail') - return 'fail' + assert feat.GetGeomFieldRef('wkt').ExportToWkt() == 'POINT (0 0)' feat = None ds.ReleaseResultSet(sql_lyr) # Test COUNT(geometry) sql_lyr = ds.ExecuteSQL('SELECT COUNT(geomfield) FROM poly') feat = sql_lyr.GetNextFeature() - if feat is None: - gdaltest.post_reason('fail') - return 'fail' - if feat.GetField(0) != 1: - gdaltest.post_reason('fail') - return 'fail' + assert feat is not None + assert feat.GetField(0) == 1 feat = None ds.ReleaseResultSet(sql_lyr) @@ -810,13 +520,9 @@ def ogr_rfc41_6(): gdal.PushErrorHandler('CPLQuietErrorHandler') sql_lyr = ds.ExecuteSQL(sql) gdal.PopErrorHandler() - if gdal.GetLastErrorMsg().find(error_msg) != 0: - gdaltest.post_reason('fail') - print('For %s, expected error %s, got %s' % (sql, error_msg, gdal.GetLastErrorMsg())) - return 'fail' - if sql_lyr is not None: - gdaltest.post_reason('fail') - return 'fail' + assert gdal.GetLastErrorMsg().find(error_msg) == 0, \ + ('For %s, expected error %s, got %s' % (sql, error_msg, gdal.GetLastErrorMsg())) + assert sql_lyr is None # Test invalid expressions with geometry for sql in ["SELECT geomfield + 'a' FROM poly", @@ -833,64 +539,43 @@ def ogr_rfc41_6(): gdal.PushErrorHandler('CPLQuietErrorHandler') sql_lyr = ds.ExecuteSQL(sql) gdal.PopErrorHandler() - if gdal.GetLastErrorMsg().find('Cannot use geometry field in this operation') != 0: - gdaltest.post_reason('fail') - print(gdal.GetLastErrorMsg()) - return 'fail' - if sql_lyr is not None: - gdaltest.post_reason('fail') - return 'fail' + assert gdal.GetLastErrorMsg().find('Cannot use geometry field in this operation') == 0 + assert sql_lyr is None # Test expression with geometry in WHERE sql_lyr = ds.ExecuteSQL('SELECT * FROM poly WHERE geomfield IS NOT NULL') feat = sql_lyr.GetNextFeature() - if feat.GetField('intfield') != 1: - gdaltest.post_reason('fail') - return 'fail' + assert feat.GetField('intfield') == 1 feat = sql_lyr.GetNextFeature() - if feat is not None: - gdaltest.post_reason('fail') - return 'fail' + assert feat is None feat = None ds.ReleaseResultSet(sql_lyr) sql_lyr = ds.ExecuteSQL('SELECT * FROM poly WHERE geomfield IS NULL') feat = sql_lyr.GetNextFeature() - if feat.IsFieldSet(0): - gdaltest.post_reason('fail') - return 'fail' + assert not feat.IsFieldSet(0) feat = sql_lyr.GetNextFeature() - if feat is not None: - gdaltest.post_reason('fail') - return 'fail' + assert feat is None feat = None ds.ReleaseResultSet(sql_lyr) sql_lyr = ds.ExecuteSQL("SELECT * FROM poly WHERE CAST(geomfield AS CHARACTER) = 'POLYGON EMPTY'") feat = sql_lyr.GetNextFeature() - if feat is None: - gdaltest.post_reason('fail') - return 'fail' + assert feat is not None feat = sql_lyr.GetNextFeature() - if feat is not None: - gdaltest.post_reason('fail') - return 'fail' + assert feat is None feat = None ds.ReleaseResultSet(sql_lyr) sql_lyr = ds.ExecuteSQL('SELECT count(*) FROM poly WHERE geomfield IS NULL') feat = sql_lyr.GetNextFeature() - if feat.GetField(0) != 1: - gdaltest.post_reason('fail') - return 'fail' + assert feat.GetField(0) == 1 feat = None ds.ReleaseResultSet(sql_lyr) sql_lyr = ds.ExecuteSQL('SELECT count(*) FROM poly WHERE geomfield IS NOT NULL') feat = sql_lyr.GetNextFeature() - if feat.GetField(0) != 1: - gdaltest.post_reason('fail') - return 'fail' + assert feat.GetField(0) == 1 feat = None ds.ReleaseResultSet(sql_lyr) @@ -905,16 +590,12 @@ def ogr_rfc41_6(): sql_lyr = ds.ExecuteSQL("SELECT * FROM poly") sql_lyr.SetSpatialFilterRect(0, 0, 0, 0) feat = sql_lyr.GetNextFeature() - if feat is not None: - gdaltest.post_reason('fail') - return 'fail' + assert feat is None feat = None sql_lyr.SetSpatialFilterRect(0, 1, 2, 1, 2) feat = sql_lyr.GetNextFeature() - if feat is None: - gdaltest.post_reason('fail') - return 'fail' + assert feat is not None feat = None # Test invalid spatial filter index @@ -922,33 +603,23 @@ def ogr_rfc41_6(): gdal.PushErrorHandler('CPLQuietErrorHandler') sql_lyr.SetSpatialFilterRect(2, 0, 0, 0, 0) gdal.PopErrorHandler() - if gdal.GetLastErrorMsg() == '': - gdaltest.post_reason('fail') - return 'fail' + assert gdal.GetLastErrorMsg() != '' # Test invalid geometry field index gdal.ErrorReset() gdal.PushErrorHandler('CPLQuietErrorHandler') sql_lyr.GetExtent(geom_field=2) gdal.PopErrorHandler() - if gdal.GetLastErrorMsg() == '': - gdaltest.post_reason('fail') - return 'fail' + assert gdal.GetLastErrorMsg() != '' ds.ReleaseResultSet(sql_lyr) # Test querying several geometry fields sql_lyr = ds.ExecuteSQL('SELECT geomfield as geom1, geomfield as geom2 FROM poly') feat = sql_lyr.GetNextFeature() - if feat is None: - gdaltest.post_reason('fail') - return 'fail' - if feat.GetGeomFieldRef('geom1') is None: - gdaltest.post_reason('fail') - return 'fail' - if feat.GetGeomFieldRef('geom2') is None: - gdaltest.post_reason('fail') - return 'fail' + assert feat is not None + assert feat.GetGeomFieldRef('geom1') is not None + assert feat.GetGeomFieldRef('geom2') is not None feat = None ds.ReleaseResultSet(sql_lyr) @@ -965,57 +636,37 @@ def ogr_rfc41_6(): 'SELECT secondarygeom, geomfield FROM poly']: sql_lyr = ds.ExecuteSQL(sql) feat = sql_lyr.GetNextFeature() - if feat.GetGeomFieldRef('geomfield').ExportToWkt() != 'POINT (1 2)': - gdaltest.post_reason('fail') - return 'fail' - if feat.GetGeomFieldRef('secondarygeom').ExportToWkt() != 'POINT (10 100)': - gdaltest.post_reason('fail') - return 'fail' + assert feat.GetGeomFieldRef('geomfield').ExportToWkt() == 'POINT (1 2)' + assert feat.GetGeomFieldRef('secondarygeom').ExportToWkt() == 'POINT (10 100)' feat = None ds.ReleaseResultSet(sql_lyr) # Check that we don't get an implicit geometry field sql_lyr = ds.ExecuteSQL('SELECT intfield FROM poly') - if sql_lyr.GetLayerDefn().GetGeomFieldCount() != 0: - gdaltest.post_reason('fail') - return 'fail' + assert sql_lyr.GetLayerDefn().GetGeomFieldCount() == 0 ds.ReleaseResultSet(sql_lyr) # Check GetExtent() and SetSpatialFilter() sql_lyr = ds.ExecuteSQL('SELECT * FROM poly') - if sql_lyr.GetExtent(geom_field=0) != (1.0, 1.0, 2.0, 2.0): - gdaltest.post_reason('fail') - return 'fail' - if sql_lyr.GetExtent(geom_field=1) != (10.0, 10.0, 100.0, 100.0): - gdaltest.post_reason('fail') - return 'fail' + assert sql_lyr.GetExtent(geom_field=0) == (1.0, 1.0, 2.0, 2.0) + assert sql_lyr.GetExtent(geom_field=1) == (10.0, 10.0, 100.0, 100.0) sql_lyr.SetSpatialFilterRect(0, 0.5, 1.5, 1.5, 2.5) - if sql_lyr.GetFeatureCount() != 1: - gdaltest.post_reason('fail') - return 'fail' + assert sql_lyr.GetFeatureCount() == 1 sql_lyr.SetSpatialFilterRect(0, 0, 0, 0.5, 0.5) - if sql_lyr.GetFeatureCount() != 0: - gdaltest.post_reason('fail') - return 'fail' + assert sql_lyr.GetFeatureCount() == 0 sql_lyr.SetSpatialFilterRect(1, 9, 99, 11, 101) - if sql_lyr.GetFeatureCount() != 1: - gdaltest.post_reason('fail') - return 'fail' + assert sql_lyr.GetFeatureCount() == 1 sql_lyr.SetSpatialFilterRect(1, 0, 0, 0.5, 0.5) - if sql_lyr.GetFeatureCount() != 0: - gdaltest.post_reason('fail') - return 'fail' + assert sql_lyr.GetFeatureCount() == 0 ds.ReleaseResultSet(sql_lyr) ds = None - return 'success' - ############################################################################### # Test crazy OGRSQL -def ogr_rfc41_7(): +def test_ogr_rfc41_7(): ds = ogr.Open('data') sql = "select eas_id, \"_ogr_geometry_\" as geom1, cast(null as geometry) as geom2, " + \ @@ -1037,24 +688,16 @@ def ogr_rfc41_7(): feat.geom4.GetGeometryType() != ogr.wkbPolygon or \ feat['_ogr_geometry_'].GetGeometryType() != ogr.wkbPolygon: feat.DumpReadable() - gdaltest.post_reason('fail') - return 'fail' + pytest.fail() ds.ReleaseResultSet(sql_lyr) ds = None - return 'success' - ############################################################################### # Test SQLite dialect -def ogr_rfc41_8(): - - import ogr_sql_sqlite - if not ogr_sql_sqlite.ogr_sql_sqlite_available(): - return 'skip' - +def test_ogr_rfc41_8(require_ogr_sql_sqlite): # noqa ds = ogr.GetDriverByName('memory').CreateDataSource('') lyr = ds.CreateLayer('mytable', geom_type=ogr.wkbPolygon) lyr.GetLayerDefn().GetGeomFieldDefn(0).SetName('geomfield') @@ -1066,23 +709,12 @@ def ogr_rfc41_8(): # Check that we get the geometry columns, even with no features sql_lyr = ds.ExecuteSQL('SELECT * FROM mytable', dialect='SQLite') - if sql_lyr.GetLayerDefn().GetGeomFieldCount() != 2: - print(sql_lyr.GetLayerDefn().GetGeomFieldCount()) - gdaltest.post_reason('fail') - return 'fail' - if sql_lyr.GetLayerDefn().GetGeomFieldDefn(0).GetType() != ogr.wkbPolygon: - gdaltest.post_reason('fail') - return 'fail' - if sql_lyr.GetLayerDefn().GetGeomFieldDefn(0).GetSpatialRef() is not None: - gdaltest.post_reason('fail') - return 'fail' - if sql_lyr.GetLayerDefn().GetGeomFieldDefn(1).GetType() != ogr.wkbPoint25D: - gdaltest.post_reason('fail') - return 'fail' + assert sql_lyr.GetLayerDefn().GetGeomFieldCount() == 2 + assert sql_lyr.GetLayerDefn().GetGeomFieldDefn(0).GetType() == ogr.wkbPolygon + assert sql_lyr.GetLayerDefn().GetGeomFieldDefn(0).GetSpatialRef() is None + assert sql_lyr.GetLayerDefn().GetGeomFieldDefn(1).GetType() == ogr.wkbPoint25D srs = sql_lyr.GetLayerDefn().GetGeomFieldDefn(1).GetSpatialRef() - if srs.GetAuthorityCode(None) != '4326': - gdaltest.post_reason('fail') - return 'fail' + assert srs.GetAuthorityCode(None) == '4326' ds.ReleaseResultSet(sql_lyr) # Test INSERT INTO request @@ -1096,13 +728,11 @@ def ogr_rfc41_8(): geom = feat.GetGeomFieldRef('geomfield') if geom.ExportToWkt() != 'POLYGON ((0 0,0 1,1 1,1 0,0 0))': feat.DumpReadable() - gdaltest.post_reason('fail') - return 'fail' + pytest.fail() geom = feat.GetGeomFieldRef('geomfield2') if geom.ExportToWkt() != 'POINT (0 1 2)': feat.DumpReadable() - gdaltest.post_reason('fail') - return 'fail' + pytest.fail() feat = None ds.ReleaseResultSet(sql_lyr) @@ -1116,34 +746,13 @@ def ogr_rfc41_8(): geom = feat.GetGeomFieldRef('geomfield') if geom.ExportToWkt() != 'POLYGON ((0 0,0 1,1 1,1 0,0 0))': feat.DumpReadable() - gdaltest.post_reason('fail') - return 'fail' + pytest.fail() geom = feat.GetGeomFieldRef('geomfield2') if geom.ExportToWkt() != 'POINT (3 4 5)': feat.DumpReadable() - gdaltest.post_reason('fail') - return 'fail' + pytest.fail() feat = None ds.ReleaseResultSet(sql_lyr) - return 'success' - - -gdaltest_list = [ - ogr_rfc41_1, - ogr_rfc41_2, - ogr_rfc41_3, - ogr_rfc41_4, - ogr_rfc41_5, - ogr_rfc41_6, - ogr_rfc41_7, - ogr_rfc41_8, -] - -if __name__ == '__main__': - - gdaltest.setup_run('ogr_rfc41') - gdaltest.run_tests(gdaltest_list) - sys.exit(gdaltest.summarize()) diff --git a/autotest/ogr/ogr_s57.py b/autotest/ogr/ogr_s57.py index d6c43ea3d7fe..d389d92ecd76 100755 --- a/autotest/ogr/ogr_s57.py +++ b/autotest/ogr/ogr_s57.py @@ -34,18 +34,18 @@ import sys import shutil -sys.path.append('../pymod') import gdaltest import ogrtest from osgeo import ogr from osgeo import gdal +import pytest ############################################################################### # Verify we can open the test file. -def ogr_s57_1(): +def test_ogr_s57_1(): gdaltest.s57_ds = None @@ -54,20 +54,16 @@ def ogr_s57_1(): gdal.SetConfigOption('OGR_S57_OPTIONS', '') gdaltest.s57_ds = ogr.Open('data/1B5X02NE.000') - if gdaltest.s57_ds is None: - gdaltest.post_reason('failed to open test file.') - return 'fail' - - return 'success' + assert gdaltest.s57_ds is not None, 'failed to open test file.' ############################################################################### # Verify we have the set of expected layers and that some rough information # matches our expectations. -def ogr_s57_2(): +def test_ogr_s57_2(): if gdaltest.s57_ds is None: - return 'skip' + pytest.skip() layer_list = [('DSID', ogr.wkbNone, 1), ('COALNE', ogr.wkbUnknown, 1), @@ -83,178 +79,133 @@ def ogr_s57_2(): ('M_NSYS', ogr.wkbPolygon, 1), ('M_QUAL', ogr.wkbPolygon, 1)] - if gdaltest.s57_ds.GetLayerCount() != len(layer_list): - gdaltest.post_reason('Did not get expected number of layers, likely cannot find support files.') - return 'fail' + assert gdaltest.s57_ds.GetLayerCount() == len(layer_list), \ + 'Did not get expected number of layers, likely cannot find support files.' for i, lyr_info in enumerate(layer_list): lyr = gdaltest.s57_ds.GetLayer(i) - if lyr.GetName() != lyr_info[0]: - gdaltest.post_reason('Expected layer %d to be %s but it was %s.' + assert lyr.GetName() == lyr_info[0], \ + ('Expected layer %d to be %s but it was %s.' % (i + 1, lyr_info[0], lyr.GetName())) - return 'fail' count = lyr.GetFeatureCount(force=1) - if count != lyr_info[2]: - gdaltest.post_reason('Expected %d features in layer %s, but got %d.' % (lyr_info[2], lyr_info[0], count)) - return 'fail' - - if lyr.GetLayerDefn().GetGeomType() != lyr_info[1]: - gdaltest.post_reason('Expected %d layer type in layer %s, but got %d.' % (lyr_info[1], lyr_info[0], lyr.GetLayerDefn().GetGeomType())) - return 'fail' + assert count == lyr_info[2], \ + ('Expected %d features in layer %s, but got %d.' % (lyr_info[2], lyr_info[0], count)) - return 'success' + assert lyr.GetLayerDefn().GetGeomType() == lyr_info[1], \ + ('Expected %d layer type in layer %s, but got %d.' % (lyr_info[1], lyr_info[0], lyr.GetLayerDefn().GetGeomType())) + ############################################################################### # Check the COALNE feature. -def ogr_s57_3(): +def test_ogr_s57_3(): if gdaltest.s57_ds is None: - return 'skip' + pytest.skip() feat = gdaltest.s57_ds.GetLayerByName('COALNE').GetNextFeature() - if feat is None: - gdaltest.post_reason('Did not get expected COALNE feature at all.') - return 'fail' + assert feat is not None, 'Did not get expected COALNE feature at all.' - if feat.GetField('RCID') != 1 \ - or feat.GetField('LNAM') != 'FFFF7F4F0FB002D3' \ - or feat.GetField('OBJL') != 30 \ - or feat.GetField('AGEN') != 65535: - gdaltest.post_reason('COALNE: did not get expected attributes') - return 'fail' + assert feat.GetField('RCID') == 1 and feat.GetField('LNAM') == 'FFFF7F4F0FB002D3' and feat.GetField('OBJL') == 30 and feat.GetField('AGEN') == 65535, \ + 'COALNE: did not get expected attributes' wkt = 'LINESTRING (60.97683400 -32.49442600,60.97718200 -32.49453800,60.97742400 -32.49477400,60.97774800 -32.49504000,60.97791600 -32.49547200,60.97793000 -32.49581800,60.97794400 -32.49617800,60.97804400 -32.49647600,60.97800200 -32.49703800,60.97800200 -32.49726600,60.97805800 -32.49749400,60.97812800 -32.49773200,60.97827000 -32.49794800,60.97910200 -32.49848600,60.97942600 -32.49866600)' - if ogrtest.check_feature_geometry(feat, wkt): - return 'fail' - - return 'success' + assert not ogrtest.check_feature_geometry(feat, wkt) ############################################################################### # Check the M_QUAL feature. -def ogr_s57_4(): +def test_ogr_s57_4(): if gdaltest.s57_ds is None: - return 'skip' + pytest.skip() feat = gdaltest.s57_ds.GetLayerByName('M_QUAL').GetNextFeature() - if feat is None: - gdaltest.post_reason('Did not get expected M_QUAL feature at all.') - return 'fail' + assert feat is not None, 'Did not get expected M_QUAL feature at all.' - if feat.GetField('RCID') != 15 \ - or feat.GetField('OBJL') != 308 \ - or feat.GetField('AGEN') != 65535: - gdaltest.post_reason('M_QUAL: did not get expected attributes') - return 'fail' + assert feat.GetField('RCID') == 15 and feat.GetField('OBJL') == 308 and feat.GetField('AGEN') == 65535, \ + 'M_QUAL: did not get expected attributes' wkt = 'POLYGON ((60.97683400 -32.49534000,60.97683400 -32.49762000,60.97683400 -32.49866600,60.97869000 -32.49866600,60.97942600 -32.49866600,60.98215200 -32.49866600,60.98316600 -32.49866600,60.98316600 -32.49755800,60.98316600 -32.49477000,60.98316600 -32.49350000,60.98146800 -32.49350000,60.98029800 -32.49350000,60.97947400 -32.49350000,60.97901600 -32.49350000,60.97683400 -32.49350000,60.97683400 -32.49442600,60.97683400 -32.49469800,60.97683400 -32.49534000))' - if ogrtest.check_feature_geometry(feat, wkt): - return 'fail' - - return 'success' + assert not ogrtest.check_feature_geometry(feat, wkt) ############################################################################### # Check the SOUNDG feature. -def ogr_s57_5(): +def test_ogr_s57_5(): if gdaltest.s57_ds is None: - return 'skip' + pytest.skip() feat = gdaltest.s57_ds.GetLayerByName('SOUNDG').GetNextFeature() - if feat is None: - gdaltest.post_reason('Did not get expected SOUNDG feature at all.') - return 'fail' + assert feat is not None, 'Did not get expected SOUNDG feature at all.' - if feat.GetField('RCID') != 20 \ - or feat.GetField('OBJL') != 129 \ - or feat.GetField('AGEN') != 65535: - gdaltest.post_reason('SOUNDG: did not get expected attributes') - return 'fail' + assert feat.GetField('RCID') == 20 and feat.GetField('OBJL') == 129 and feat.GetField('AGEN') == 65535, \ + 'SOUNDG: did not get expected attributes' wkt = 'MULTIPOINT (60.98164400 -32.49449000 3.400,60.98134400 -32.49642400 1.400,60.97814200 -32.49487400 -3.200,60.98071200 -32.49519600 1.200)' - if ogrtest.check_feature_geometry(feat, wkt): - return 'fail' + assert not ogrtest.check_feature_geometry(feat, wkt) gdaltest.s57_ds = None - return 'success' - ############################################################################### # Test reading features from dataset with some double byte attributes. (#1526) -def ogr_s57_6(): +def test_ogr_s57_6(): ds = ogr.Open('data/bug1526.000') feat = ds.GetLayerByName('FOGSIG').GetNextFeature() - if feat is None: - gdaltest.post_reason('Did not get expected FOGSIG feature at all.') - return 'fail' - - if feat.GetField('INFORM') != 'During South winds nautophone is not always heard in S direction from lighthouse' \ - or len(feat.GetField('NINFOM')) < 1: - gdaltest.post_reason('FOGSIG: did not get expected attributes') - return 'fail' + assert feat is not None, 'Did not get expected FOGSIG feature at all.' - return 'success' + assert feat.GetField('INFORM') == 'During South winds nautophone is not always heard in S direction from lighthouse' and len(feat.GetField('NINFOM')) >= 1, \ + 'FOGSIG: did not get expected attributes' ############################################################################### # Test handling of a dataset with a multilinestring feature (#2147). -def ogr_s57_7(): +def test_ogr_s57_7(): ds = ogr.Open('data/bug2147_3R7D0889.000') feat = ds.GetLayerByName('ROADWY').GetNextFeature() - if feat is None: - gdaltest.post_reason('Did not get expected feature at all.') - return 'fail' + assert feat is not None, 'Did not get expected feature at all.' exp_wkt = 'MULTILINESTRING ((22.5659615 44.5541942,22.5652045 44.5531651,22.5654315 44.5517774,22.5663008 44.5510096,22.5656187 44.5500822,22.5654462 44.5495941,22.5637522 44.5486793,22.563408 44.5477286,22.5654087 44.5471198,22.5670327 44.5463937,22.5667729 44.5456512,22.5657613 44.544027,22.5636273 44.5411638,22.5623421 44.5400398,22.559403 44.5367489,22.5579112 44.534544,22.5566466 44.5309514,22.5563888 44.5295231,22.5549946 44.5285915,22.5541939 44.5259331,22.5526434 44.5237888),(22.5656187 44.5500822,22.5670219 44.5493519,22.5684077 44.5491452),(22.5350702 44.4918838,22.5329111 44.4935825,22.5318719 44.4964337,22.5249608 44.5027089,22.5254709 44.5031914,22.5295138 44.5052214,22.5331359 44.5077711,22.5362468 44.5092751,22.5408091 44.5115306,22.5441312 44.5127374,22.5461053 44.5132675,22.5465694 44.5149956),(22.5094658 44.4989464,22.5105135 44.4992481,22.5158217 44.4994216,22.5206067 44.4998907,22.523096 44.5009452,22.5249608 44.5027089),(22.5762962 44.4645734,22.5767653 44.4773213,22.5769802 44.4796618,22.5775485 44.4815858,22.5762434 44.4842544,22.5765836 44.4855091,22.5775087 44.4865991,22.5769145 44.4879336,22.5708196 44.4910838,22.5694028 44.4930833,22.5692354 44.4958977),(22.5763768 44.5029527,22.5799605 44.501315,22.5831172 44.5007428,22.584524 44.4999964,22.5848604 44.4999039),(22.5731362 44.5129105,22.5801378 44.5261859,22.5825748 44.5301187),(22.5093748 44.5311182,22.5107969 44.5285258,22.5108905 44.5267978,22.5076679 44.5223309))' - if ogrtest.check_feature_geometry(feat, exp_wkt): - return 'fail' - - return 'success' + assert not ogrtest.check_feature_geometry(feat, exp_wkt) ############################################################################### # Run test_ogrsf -def ogr_s57_8(): +def test_ogr_s57_8(): import test_cli_utilities if test_cli_utilities.get_test_ogrsf_path() is None: - return 'skip' + pytest.skip() ret = gdaltest.runexternal(test_cli_utilities.get_test_ogrsf_path() + ' -ro data/1B5X02NE.000') - if ret.find('INFO') == -1 or ret.find('ERROR') != -1: - print(ret) - return 'fail' - - return 'success' + assert ret.find('INFO') != -1 and ret.find('ERROR') == -1 ############################################################################### # Test S57 to S57 conversion -def ogr_s57_9(): +def test_ogr_s57_9(): gdal.Unlink('tmp/ogr_s57_9.000') @@ -274,18 +225,13 @@ def ogr_s57_9(): ds = None ds = ogr.Open('tmp/ogr_s57_9.000') - if ds is None: - return 'fail' + assert ds is not None gdaltest.s57_ds = ds - if ogr_s57_2() != 'success': - return 'fail' - if ogr_s57_3() != 'success': - return 'fail' - if ogr_s57_4() != 'success': - return 'fail' - if ogr_s57_5() != 'success': - return 'fail' + test_ogr_s57_2() + test_ogr_s57_3() + test_ogr_s57_4() + test_ogr_s57_5() gdaltest.s57_ds = None @@ -296,151 +242,118 @@ def ogr_s57_9(): gdal.SetConfigOption('OGR_S57_OPTIONS', None) ds = gdal.OpenEx('tmp/ogr_s57_9.000', open_options=['RETURN_PRIMITIVES=ON']) - if ds is None: - gdaltest.post_reason('fail') - return 'fail' + assert ds is not None - if ds.GetLayerByName('IsolatedNode') is None: - gdaltest.post_reason('fail') - return 'fail' + assert ds.GetLayerByName('IsolatedNode') is not None gdaltest.s57_ds = ds - if ogr_s57_4() != 'success': - return 'fail' + test_ogr_s57_4() gdaltest.s57_ds = None gdal.Unlink('tmp/ogr_s57_9.000') - return 'success' - ############################################################################### # Test opening a fake very small S57 file -def ogr_s57_10(): +def test_ogr_s57_10(): ds = ogr.Open('data/fake_s57.000') lyr = ds.GetLayer(0) f = lyr.GetNextFeature() - if f['DSID_EXPP'] != 2: - return 'fail' - return 'success' + assert f['DSID_EXPP'] == 2 ############################################################################### # Test opening a fake very small S57 file with ISO8211 record with zero length, # using variant (C.1.5.1) logic. -def ogr_s57_11(): +def test_ogr_s57_11(): ds = ogr.Open('data/fake_s57_variant_C151.000') lyr = ds.GetLayer(0) f = lyr.GetNextFeature() - if f['DSID_EXPP'] != 2: - return 'fail' - return 'success' + assert f['DSID_EXPP'] == 2 ############################################################################### # Test decoding of Dutch inland ENCs (#3881). -def ogr_s57_online_1(): +def test_ogr_s57_online_1(): if not gdaltest.download_file('ftp://sdg.ivs90.nl/ENC/1R5MK050.000', '1R5MK050.000'): - return 'skip' + pytest.skip() ds = ogr.Open('tmp/cache/1R5MK050.000') - if ds is None: - return 'fail' + assert ds is not None lyr = ds.GetLayerByName('BUISGL') feat = lyr.GetNextFeature() - if feat is None: - gdaltest.post_reason('Did not get expected feature at all.') - return 'fail' + assert feat is not None, 'Did not get expected feature at all.' exp_wkt = 'POLYGON ((5.6666667 53.0279027,5.6666667 53.0281667,5.6667012 53.0281685,5.666673 53.0282377,5.666788 53.0282616,5.6669018 53.0281507,5.6668145 53.0281138,5.6668121 53.0280649,5.6666686 53.0280248,5.6666713 53.0279647,5.6667572 53.0279713,5.6667568 53.0279089,5.6666667 53.0279027))' - if ogrtest.check_feature_geometry(feat, exp_wkt): - return 'fail' + assert not ogrtest.check_feature_geometry(feat, exp_wkt) feat = None ds = None - return 'success' - ############################################################################### # Test with ENC 3.0 TDS - tile without updates. -def ogr_s57_online_2(): +def test_ogr_s57_online_2(): if not gdaltest.download_file('http://download.osgeo.org/gdal/data/s57/enctds/GB5X01SW.000', 'GB5X01SW.000'): - return 'skip' + pytest.skip() gdaltest.clean_tmp() shutil.copy('tmp/cache/GB5X01SW.000', 'tmp/GB5X01SW.000') ds = ogr.Open('tmp/GB5X01SW.000') - if ds is None: - return 'fail' + assert ds is not None lyr = ds.GetLayerByName('LIGHTS') feat = lyr.GetFeature(542) - if feat is None: - gdaltest.post_reason('Did not get expected feature at all.') - return 'fail' + assert feat is not None, 'Did not get expected feature at all.' - if feat.rver != 1: - gdaltest.post_reason('Did not get expected RVER value (%d).' % feat.rver) - return 'fail' + assert feat.rver == 1, ('Did not get expected RVER value (%d).' % feat.rver) lyr = ds.GetLayerByName('BOYCAR') feat = lyr.GetFeature(975) - if feat is not None: - gdaltest.post_reason('unexpected got feature id 975 before update!') - return 'fail' + assert feat is None, 'unexpected got feature id 975 before update!' feat = None ds = None - return 'success' - ############################################################################### # Test with ENC 3.0 TDS - tile with updates. -def ogr_s57_online_3(): +def test_ogr_s57_online_3(): if not gdaltest.download_file('http://download.osgeo.org/gdal/data/s57/enctds/GB5X01SW.001', 'GB5X01SW.001'): - return 'skip' + pytest.skip() shutil.copy('tmp/cache/GB5X01SW.001', 'tmp/GB5X01SW.001') ds = ogr.Open('tmp/GB5X01SW.000') - if ds is None: - return 'fail' + assert ds is not None lyr = ds.GetLayerByName('LIGHTS') feat = lyr.GetFeature(542) - if feat is None: - gdaltest.post_reason('Did not get expected feature at all.') - return 'fail' + assert feat is not None, 'Did not get expected feature at all.' - if feat.rver != 2: - gdaltest.post_reason('Did not get expected RVER value (%d).' % feat.rver) - return 'fail' + assert feat.rver == 2, ('Did not get expected RVER value (%d).' % feat.rver) lyr = ds.GetLayerByName('BOYCAR') feat = lyr.GetFeature(975) - if feat is None: - gdaltest.post_reason('unexpected did not get feature id 975 ' + assert feat is not None, ('unexpected did not get feature id 975 ' 'after update!') - return 'fail' feat = None @@ -448,16 +361,14 @@ def ogr_s57_online_3(): gdaltest.clean_tmp() - return 'success' - ############################################################################### # Test ENC LL2 (#5048) -def ogr_s57_online_4(): +def test_ogr_s57_online_4(): if not gdaltest.download_file('http://www1.kaiho.mlit.go.jp/KOKAI/ENC/images/sample/sample.zip', 'sample.zip'): - return 'skip' + pytest.skip() try: os.stat('tmp/cache/ENC_ROOT/JP34NC94.000') @@ -467,9 +378,9 @@ def ogr_s57_online_4(): try: os.stat('tmp/cache/ENC_ROOT/JP34NC94.000') except OSError: - return 'skip' + pytest.skip() except OSError: - return 'skip' + pytest.skip() gdal.SetConfigOption('OGR_S57_OPTIONS', 'RETURN_PRIMITIVES=ON,RETURN_LINKAGES=ON,LNAM_REFS=ON,RECODE_BY_DSSI=ON') ds = ogr.Open('tmp/cache/ENC_ROOT/JP34NC94.000') @@ -480,41 +391,14 @@ def ogr_s57_online_4(): if mystr and sys.version_info < (3, 0, 0): mystr.decode('UTF-8').encode('UTF-8') - return 'success' - + ############################################################################### # Cleanup -def ogr_s57_cleanup(): +def test_ogr_s57_cleanup(): gdaltest.s57_ds = None - return 'success' - - -gdaltest_list = [ - ogr_s57_1, - ogr_s57_2, - ogr_s57_3, - ogr_s57_4, - ogr_s57_5, - ogr_s57_6, - ogr_s57_7, - ogr_s57_8, - ogr_s57_9, - ogr_s57_10, - ogr_s57_11, - ogr_s57_online_1, - ogr_s57_online_2, - ogr_s57_online_3, - ogr_s57_online_4, - ogr_s57_cleanup] - -if __name__ == '__main__': - - gdaltest.setup_run('ogr_s57') - gdaltest.run_tests(gdaltest_list) - sys.exit(gdaltest.summarize()) diff --git a/autotest/ogr/ogr_sde.py b/autotest/ogr/ogr_sde.py index 7d4a4f204cba..49861ee53b0c 100755 --- a/autotest/ogr/ogr_sde.py +++ b/autotest/ogr/ogr_sde.py @@ -28,9 +28,7 @@ # DEALINGS IN THE SOFTWARE. ############################################################################### -import sys -sys.path.append('../pymod') import gdaltest import ogrtest @@ -38,6 +36,7 @@ from osgeo import ogr from osgeo import osr from osgeo import gdal +import pytest ############################################################################### # Open ArcSDE datasource. @@ -55,30 +54,27 @@ pass -def ogr_sde_1(): +def test_ogr_sde_1(): "Test basic opening of a database" if gdaltest.sde_dr is None: - return 'skip' + pytest.skip() base = 'SDE:%s,%s,%s,%s,%s' % (sde_server, sde_port, sde_db, sde_user, sde_password) ds = ogr.Open(base) if ds is None: - print("Could not open %s" % base) gdaltest.sde_dr = None - return 'skip' + pytest.skip("Could not open %s" % base) ds.Destroy() ds = ogr.Open(base, update=1) ds.Destroy() - return 'success' - -def ogr_sde_2(): +def test_ogr_sde_2(): "Test creation of a layer" if gdaltest.sde_dr is None: - return 'skip' + pytest.skip() base = 'SDE:%s,%s,%s,%s,%s' % (sde_server, sde_port, sde_db, sde_user, sde_password) shp_ds = ogr.Open('data/poly.shp') @@ -113,32 +109,27 @@ def ogr_sde_2(): feat = shp_lyr.GetNextFeature() dst_feat.Destroy() - return 'success' -def ogr_sde_3(): +def test_ogr_sde_3(): "Test basic version locking" if gdaltest.sde_dr is None: - return 'skip' + pytest.skip() base = 'SDE:%s,%s,%s,%s,%s,SDE.TPOLY,SDE.DEFAULT' % (sde_server, sde_port, sde_db, sde_user, sde_password) ds = ogr.Open(base, update=1) ds2 = ogr.Open(base, update=1) - if ds2 is not None: - gdaltest.post_reason('A locked version was able to be opened') - return 'fail' + assert ds2 is None, 'A locked version was able to be opened' ds.Destroy() - return 'success' - -def ogr_sde_4(): +def test_ogr_sde_4(): "Test basic version creation" if gdaltest.sde_dr is None: - return 'skip' + pytest.skip() version_name = 'TESTING' gdal.SetConfigOption('SDE_VERSIONOVERWRITE', 'TRUE') @@ -152,14 +143,12 @@ def ogr_sde_4(): ds = ogr.Open(base, update=1) ds.Destroy() - return 'success' - -def ogr_sde_5(): +def test_ogr_sde_5(): "Test versioned editing" if gdaltest.sde_dr is None: - return 'skip' + pytest.skip() version_name = 'TESTING' gdal.SetConfigOption('SDE_VERSIONOVERWRITE', 'TRUE') @@ -196,9 +185,8 @@ def ogr_sde_5(): ds3 = ogr.Open(base) l3 = ds3.GetLayerByName('SDE.TPOLY') f3 = l3.GetFeature(1) - if f3.GetField("PRFEDEA") != "SDE.TESTING": - gdaltest.post_reason('versioned editing failed for child version SDE.TESTING') - return 'fail' + assert f3.GetField("PRFEDEA") == "SDE.TESTING", \ + 'versioned editing failed for child version SDE.TESTING' ds3.Destroy() del ds3 @@ -206,9 +194,8 @@ def ogr_sde_5(): ds4 = ogr.Open(default) l4 = ds4.GetLayerByName('SDE.TPOLY') f4 = l4.GetFeature(1) - if f4.GetField("PRFEDEA") != "SDE.DEFAULT": - gdaltest.post_reason('versioned editing failed for parent version SDE.DEFAULT') - return 'fail' + assert f4.GetField("PRFEDEA") == "SDE.DEFAULT", \ + 'versioned editing failed for parent version SDE.DEFAULT' idx = f4.GetFieldIndex('WHEN') df = f4.GetField(idx) @@ -216,14 +203,13 @@ def ogr_sde_5(): gdaltest.post_reason("datetime handling did not work -- expected '2008/03/19 16:15:00' got '%s' " % df) ds4.Destroy() del ds4 - return 'success' -def ogr_sde_6(): +def test_ogr_sde_6(): "Extent fetching" if gdaltest.sde_dr is None: - return 'skip' + pytest.skip() base = 'SDE:%s,%s,%s,%s,%s,SDE.TPOLY,SDE.DEFAULT' % ( sde_server, sde_port, sde_db, sde_user, sde_password) @@ -237,14 +223,13 @@ def ogr_sde_6(): extent = l1.GetExtent(force=1) if extent != (478316.0, 481645.0, 4762881.0, 4765611.0): gdaltest.post_reason("forced extent did not equal expected value") - return 'success' + - -def ogr_sde_7(): +def test_ogr_sde_7(): "Bad layer test" if gdaltest.sde_dr is None: - return 'skip' + pytest.skip() base = 'SDE:%s,%s,%s,%s,%s,SDE.TPOLY,SDE.DEFAULT' % ( sde_server, sde_port, sde_db, sde_user, sde_password) @@ -280,13 +265,11 @@ def ogr_sde_7(): gdaltest.post_reason("we got a layer when we should not have") ds.Destroy() - return 'success' - -def ogr_sde_8(): +def test_ogr_sde_8(): "Test spatial references" if gdaltest.sde_dr is None: - return 'skip' + pytest.skip() base = 'SDE:%s,%s,%s,%s,%s' % (sde_server, sde_port, sde_db, sde_user, sde_password) shp_ds = ogr.Open('data/poly.shp') @@ -324,37 +307,15 @@ def ogr_sde_8(): feat = shp_lyr.GetNextFeature() dst_feat.Destroy() - return 'success' -def ogr_sde_cleanup(): +def test_ogr_sde_cleanup(): if gdaltest.sde_dr is None: - return 'skip' + pytest.skip() base = 'SDE:%s,%s,%s,%s,%s' % (sde_server, sde_port, sde_db, sde_user, sde_password) ds = ogr.Open(base, update=1) ds.DeleteLayer('%s.%s' % (sde_user.upper(), 'TPOLY')) ds.Destroy() - return 'success' - - -gdaltest_list = [ - ogr_sde_1, - ogr_sde_2, - ogr_sde_3, - ogr_sde_4, - ogr_sde_5, - ogr_sde_6, - ogr_sde_7, - ogr_sde_8, - - ogr_sde_cleanup -] - -if __name__ == '__main__': - - gdaltest.setup_run('ogr_sde') - gdaltest.run_tests(gdaltest_list) - sys.exit(gdaltest.summarize()) diff --git a/autotest/ogr/ogr_sdts.py b/autotest/ogr/ogr_sdts.py index 0973fa9c620a..7d8e4af1ade9 100755 --- a/autotest/ogr/ogr_sdts.py +++ b/autotest/ogr/ogr_sdts.py @@ -28,23 +28,21 @@ # DEALINGS IN THE SOFTWARE. ############################################################################### -import sys -sys.path.append('../pymod') import gdaltest from osgeo import ogr +import pytest ############################################################################### # Test reading -def ogr_sdts_1(): +def test_ogr_sdts_1(): gdaltest.sdts_ds = ogr.Open('data/D3607551_rd0s_1_sdts_truncated/TR01CATD.DDF') - if gdaltest.sdts_ds is None: - return 'fail' + assert gdaltest.sdts_ds is not None layers = [('ARDF', 164, ogr.wkbNone, [('ENTITY_LABEL', '1700005')]), ('ARDM', 21, ogr.wkbNone, [('ROUTE_NUMBER', 'SR 1200')]), @@ -58,37 +56,21 @@ def ogr_sdts_1(): for layer in layers: lyr = gdaltest.sdts_ds.GetLayerByName(layer[0]) - if lyr is None: - gdaltest.post_reason('could not get layer %s' % (layer[0])) - return 'fail' - if lyr.GetFeatureCount() != layer[1]: - gdaltest.post_reason('wrong number of features for layer %s : %d. %d were expected ' % (layer[0], lyr.GetFeatureCount(), layer[1])) - return 'fail' - if lyr.GetLayerDefn().GetGeomType() != layer[2]: - return 'fail' + assert lyr is not None, ('could not get layer %s' % (layer[0])) + assert lyr.GetFeatureCount() == layer[1], \ + ('wrong number of features for layer %s : %d. %d were expected ' % (layer[0], lyr.GetFeatureCount(), layer[1])) + assert lyr.GetLayerDefn().GetGeomType() == layer[2] feat_read = lyr.GetNextFeature() for item in layer[3]: if feat_read.GetFieldAsString(item[0]) != item[1]: print(layer[0]) print('"%s"' % (item[1])) - print('"%s"' % (feat_read.GetField(item[0]))) - return 'fail' + pytest.fail('"%s"' % (feat_read.GetField(item[0]))) gdaltest.sdts_ds = None - return 'success' - ############################################################################### # -gdaltest_list = [ - ogr_sdts_1] - -if __name__ == '__main__': - - gdaltest.setup_run('ogr_sdts') - - gdaltest.run_tests(gdaltest_list) - sys.exit(gdaltest.summarize()) diff --git a/autotest/ogr/ogr_segukooa.py b/autotest/ogr/ogr_segukooa.py index 37544bb1cfaa..ef5f092b30de 100755 --- a/autotest/ogr/ogr_segukooa.py +++ b/autotest/ogr/ogr_segukooa.py @@ -28,33 +28,25 @@ # DEALINGS IN THE SOFTWARE. ############################################################################### -import sys -sys.path.append('../pymod') -import gdaltest import ogrtest from osgeo import ogr +import pytest ############################################################################### # Read SEGP1 -def ogr_segp1_points(): +def test_ogr_segp1_points(): ds = ogr.Open('data/test.segp1') - if ds is None: - gdaltest.post_reason('cannot open dataset') - return 'fail' + assert ds is not None, 'cannot open dataset' - if ds.GetLayerCount() != 2: - gdaltest.post_reason('bad layer count') - return 'fail' + assert ds.GetLayerCount() == 2, 'bad layer count' lyr = ds.GetLayer(0) - if lyr.GetGeomType() != ogr.wkbPoint: - gdaltest.post_reason('bad layer geometry type') - return 'fail' + assert lyr.GetGeomType() == ogr.wkbPoint, 'bad layer geometry type' feat = lyr.GetNextFeature() @@ -71,85 +63,65 @@ def ogr_segp1_points(): for values in expected_values: if feat.GetField(values[0]) != values[1]: - print('did not get expected value for %s' % values[0]) feat.DumpReadable() - return 'fail' + pytest.fail('did not get expected value for %s' % values[0]) if ogrtest.check_feature_geometry(feat, 'POINT (2 49)', max_error=0.0000001) != 0: - print('did not get expected first geom') feat.DumpReadable() - return 'fail' - - return 'success' + pytest.fail('did not get expected first geom') + ############################################################################### # Read SEGP1 lines -def ogr_segp1_lines(): +def test_ogr_segp1_lines(): ds = ogr.Open('data/test.segp1') - if ds is None: - gdaltest.post_reason('cannot open dataset') - return 'fail' + assert ds is not None, 'cannot open dataset' - if ds.GetLayerCount() != 2: - gdaltest.post_reason('bad layer count') - return 'fail' + assert ds.GetLayerCount() == 2, 'bad layer count' lyr = ds.GetLayer(1) - if lyr.GetGeomType() != ogr.wkbLineString: - gdaltest.post_reason('bad layer geometry type') - return 'fail' + assert lyr.GetGeomType() == ogr.wkbLineString, 'bad layer geometry type' feat = lyr.GetNextFeature() if feat.GetField('LINENAME') != 'firstline': - print('did not get expected value for LINENAME') feat.DumpReadable() - return 'fail' + pytest.fail('did not get expected value for LINENAME') if ogrtest.check_feature_geometry(feat, 'LINESTRING (2 49,2.0 49.5)', max_error=0.0000001) != 0: - print('did not get expected first geom') feat.DumpReadable() - return 'fail' + pytest.fail('did not get expected first geom') feat = lyr.GetNextFeature() if feat.GetField('LINENAME') != 'secondline': - print('did not get expected value for LINENAME') feat.DumpReadable() - return 'fail' + pytest.fail('did not get expected value for LINENAME') if ogrtest.check_feature_geometry(feat, 'LINESTRING (-2 -49,-2.5 -49.0)', max_error=0.0000001) != 0: - print('did not get expected first geom') feat.DumpReadable() - return 'fail' - - return 'success' + pytest.fail('did not get expected first geom') + ############################################################################### # Read UKOOA -def ogr_ukooa_points(): +def test_ogr_ukooa_points(): ds = ogr.Open('data/test.ukooa') - if ds is None: - gdaltest.post_reason('cannot open dataset') - return 'fail' + assert ds is not None, 'cannot open dataset' - if ds.GetLayerCount() != 2: - gdaltest.post_reason('bad layer count') - return 'fail' + assert ds.GetLayerCount() == 2, 'bad layer count' lyr = ds.GetLayer(0) - if lyr.GetGeomType() != ogr.wkbPoint: - gdaltest.post_reason('bad layer geometry type') - return 'fail' + assert lyr.GetGeomType() == ogr.wkbPoint, 'bad layer geometry type' feat = lyr.GetNextFeature() @@ -165,79 +137,52 @@ def ogr_ukooa_points(): for values in expected_values: if feat.GetField(values[0]) != values[1]: - print('did not get expected value for %s' % values[0]) feat.DumpReadable() - return 'fail' + pytest.fail('did not get expected value for %s' % values[0]) if ogrtest.check_feature_geometry(feat, 'POINT (2 49)', max_error=0.0000001) != 0: - print('did not get expected first geom') feat.DumpReadable() - return 'fail' - - return 'success' + pytest.fail('did not get expected first geom') + ############################################################################### # Read UKOOA lines -def ogr_ukooa_lines(): +def test_ogr_ukooa_lines(): ds = ogr.Open('data/test.ukooa') - if ds is None: - gdaltest.post_reason('cannot open dataset') - return 'fail' + assert ds is not None, 'cannot open dataset' - if ds.GetLayerCount() != 2: - gdaltest.post_reason('bad layer count') - return 'fail' + assert ds.GetLayerCount() == 2, 'bad layer count' lyr = ds.GetLayer(1) - if lyr.GetGeomType() != ogr.wkbLineString: - gdaltest.post_reason('bad layer geometry type') - return 'fail' + assert lyr.GetGeomType() == ogr.wkbLineString, 'bad layer geometry type' feat = lyr.GetNextFeature() if feat.GetField('LINENAME') != 'firstline': - print('did not get expected value for LINENAME') feat.DumpReadable() - return 'fail' + pytest.fail('did not get expected value for LINENAME') if ogrtest.check_feature_geometry(feat, 'LINESTRING (2 49,2.0 49.5)', max_error=0.0000001) != 0: - print('did not get expected first geom') feat.DumpReadable() - return 'fail' + pytest.fail('did not get expected first geom') feat = lyr.GetNextFeature() if feat.GetField('LINENAME') != 'secondline': - print('did not get expected value for LINENAME') feat.DumpReadable() - return 'fail' + pytest.fail('did not get expected value for LINENAME') if ogrtest.check_feature_geometry(feat, 'LINESTRING (-2 -49,-2.5 -49.0)', max_error=0.0000001) != 0: - print('did not get expected first geom') feat.DumpReadable() - return 'fail' - - return 'success' - - -gdaltest_list = [ - ogr_segp1_points, - ogr_segp1_lines, - ogr_ukooa_points, - ogr_ukooa_lines, -] - + pytest.fail('did not get expected first geom') -if __name__ == '__main__': + - gdaltest.setup_run('ogr_segukooa') - gdaltest.run_tests(gdaltest_list) - sys.exit(gdaltest.summarize()) diff --git a/autotest/ogr/ogr_segy.py b/autotest/ogr/ogr_segy.py index 0c6ed2f2e576..fefd4603036e 100755 --- a/autotest/ogr/ogr_segy.py +++ b/autotest/ogr/ogr_segy.py @@ -28,127 +28,71 @@ # DEALINGS IN THE SOFTWARE. ############################################################################### -import sys -sys.path.append('../pymod') -import gdaltest import ogrtest from osgeo import ogr +import pytest ############################################################################### # Read SEG-Y -def ogr_segy_1(): +def test_ogr_segy_1(): ds = ogr.Open('data/segy/testsegy.segy') - if ds is None: - gdaltest.post_reason('cannot open dataset') - return 'fail' + assert ds is not None, 'cannot open dataset' - if ds.TestCapability("foo") != 0: - gdaltest.post_reason('fail') - return 'fail' + assert ds.TestCapability("foo") == 0 - if ds.GetLayerCount() != 2: - gdaltest.post_reason('bad layer count') - return 'fail' + assert ds.GetLayerCount() == 2, 'bad layer count' lyr = ds.GetLayer(0) - if lyr.GetGeomType() != ogr.wkbPoint: - gdaltest.post_reason('bad layer geometry type') - return 'fail' + assert lyr.GetGeomType() == ogr.wkbPoint, 'bad layer geometry type' - if lyr.GetSpatialRef() is not None: - gdaltest.post_reason('bad spatial ref') - return 'fail' + assert lyr.GetSpatialRef() is None, 'bad spatial ref' - if lyr.TestCapability("foo") != 0: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.TestCapability("foo") == 0 - if lyr.GetLayerDefn().GetFieldCount() != 71: - gdaltest.post_reason('fail') - print(lyr.GetLayerDefn().GetFieldCount()) - return 'fail' + assert lyr.GetLayerDefn().GetFieldCount() == 71 feat = lyr.GetNextFeature() if ogrtest.check_feature_geometry(feat, 'POINT (500000 4500000)', max_error=0.0000001) != 0: - print('did not get expected first geom') feat.DumpReadable() - return 'fail' + pytest.fail('did not get expected first geom') feat = lyr.GetNextFeature() - if feat is not None: - gdaltest.post_reason('fail') - return 'fail' + assert feat is None lyr = ds.GetLayer(1) - if lyr.GetGeomType() != ogr.wkbNone: - gdaltest.post_reason('bad layer geometry type') - return 'fail' + assert lyr.GetGeomType() == ogr.wkbNone, 'bad layer geometry type' - if lyr.GetSpatialRef() is not None: - gdaltest.post_reason('bad spatial ref') - return 'fail' + assert lyr.GetSpatialRef() is None, 'bad spatial ref' - if lyr.TestCapability("foo") != 0: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.TestCapability("foo") == 0 - if lyr.GetLayerDefn().GetFieldCount() != 32: - gdaltest.post_reason('fail') - print(lyr.GetLayerDefn().GetFieldCount()) - return 'fail' + assert lyr.GetLayerDefn().GetFieldCount() == 32 feat = lyr.GetNextFeature() - if feat is None: - gdaltest.post_reason('fail') - return 'fail' + assert feat is not None feat = lyr.GetNextFeature() - if feat is not None: - gdaltest.post_reason('fail') - return 'fail' - - return 'success' + assert feat is None ############################################################################### # Read ASCII header SEG-Y -def ogr_segy_2(): +def test_ogr_segy_2(): ds = ogr.Open('data/segy/ascii-header-with-nuls.sgy') - if ds is None: - gdaltest.post_reason('cannot open dataset') - return 'fail' + assert ds is not None, 'cannot open dataset' - if ds.GetLayerCount() != 2: - gdaltest.post_reason('bad layer count') - return 'fail' + assert ds.GetLayerCount() == 2, 'bad layer count' lyr = ds.GetLayer(0) - if lyr.GetGeomType() != ogr.wkbPoint: - gdaltest.post_reason('bad layer geometry type') - return 'fail' - - # TODO(schwehr): Test the values of fields and data. - - return 'success' - - -gdaltest_list = [ - ogr_segy_1, - ogr_segy_2, -] - + assert lyr.GetGeomType() == ogr.wkbPoint, 'bad layer geometry type' -if __name__ == '__main__': - gdaltest.setup_run('ogr_segy') - gdaltest.run_tests(gdaltest_list) - sys.exit(gdaltest.summarize()) diff --git a/autotest/ogr/ogr_selafin.py b/autotest/ogr/ogr_selafin.py index 2581b6ead55e..147a2d5efead 100755 --- a/autotest/ogr/ogr_selafin.py +++ b/autotest/ogr/ogr_selafin.py @@ -29,22 +29,19 @@ ############################################################################### import os -import sys import math -sys.path.append('../pymod') import gdaltest -import ogrtest -from osgeo import gdal from osgeo import ogr from osgeo import osr +import pytest ############################################################################### # Create wasp datasource -def ogr_selafin_create_ds(): +def test_ogr_selafin_create_ds(): gdaltest.selafin_ds = None try: @@ -56,22 +53,19 @@ def ogr_selafin_create_ds(): gdaltest.selafin_ds = selafin_drv.CreateDataSource('tmp/tmp.slf') if gdaltest.selafin_ds is not None: - return 'success' - return 'fail' + return + pytest.fail() ############################################################################### # Add a few points to the datasource -def ogr_selafin_create_nodes(): - if ogr_selafin_create_ds() != 'success': - return 'skip' +def test_ogr_selafin_create_nodes(): + test_ogr_selafin_create_ds() ref = osr.SpatialReference() ref.ImportFromEPSG(4326) layer = gdaltest.selafin_ds.CreateLayer('name', ref, geom_type=ogr.wkbPoint) - if layer is None: - gdaltest.post_reason('unable to create layer') - return 'fail' + assert layer is not None, 'unable to create layer' layer.CreateField(ogr.FieldDefn('value', ogr.OFTReal)) dfn = layer.GetLayerDefn() for i in range(5): @@ -81,31 +75,25 @@ def ogr_selafin_create_nodes(): feat = ogr.Feature(dfn) feat.SetGeometry(pt) feat.SetField(0, (float)(i * 5 + j)) - if layer.CreateFeature(feat) != 0: - gdaltest.post_reason('unable to create node feature') - return 'fail' + assert layer.CreateFeature(feat) == 0, 'unable to create node feature' # do some checks - if layer.GetFeatureCount() != 25: - gdaltest.post_reason('wrong number of features after point layer creation') - return 'fail' + assert layer.GetFeatureCount() == 25, \ + 'wrong number of features after point layer creation' # return del gdaltest.selafin_ds del layer - return 'success' ############################################################################### # Add a set of elements to the datasource -def ogr_selafin_create_elements(): +def test_ogr_selafin_create_elements(): gdaltest.selafin_ds = ogr.Open('tmp/tmp.slf', 1) if gdaltest.selafin_ds is None: - return 'skip' + pytest.skip() layerCount = gdaltest.selafin_ds.GetLayerCount() - if layerCount < 2: - gdaltest.post_reason('elements layer not created with nodes layer') - return 'fail' + assert layerCount >= 2, 'elements layer not created with nodes layer' for i in range(layerCount): name = gdaltest.selafin_ds.GetLayer(i).GetName() if '_e' in name: @@ -126,9 +114,7 @@ def ogr_selafin_create_elements(): pol.AddGeometry(poll) feat = ogr.Feature(dfn) feat.SetGeometry(pol) - if layere.CreateFeature(feat) != 0: - gdaltest.post_reason('unable to create element feature') - return 'fail' + assert layere.CreateFeature(feat) == 0, 'unable to create element feature' pol = ogr.Geometry(type=ogr.wkbPolygon) poll = ogr.Geometry(type=ogr.wkbLinearRing) poll.AddPoint_2D(4.0, 4.0) @@ -139,36 +125,28 @@ def ogr_selafin_create_elements(): pol.AddGeometry(poll) feat = ogr.Feature(dfn) feat.SetGeometry(pol) - if layere.CreateFeature(feat) != 0: - gdaltest.post_reason('unable to create element feature') - return 'fail' + assert layere.CreateFeature(feat) == 0, 'unable to create element feature' # do some checks - if gdaltest.selafin_ds.GetLayer(k).GetFeatureCount() != 28: - gdaltest.post_reason('wrong number of point features after elements layer creation') - return 'fail' - if math.fabs(layere.GetFeature(5).GetFieldAsDouble(0) - 9) > 0.01: - gdaltest.post_reason('wrong value of attribute in element layer') - return 'fail' - if math.fabs(layere.GetFeature(10).GetFieldAsDouble(0) - 15) > 0.01: - gdaltest.post_reason('wrong value of attribute in element layer') - return 'fail' + assert gdaltest.selafin_ds.GetLayer(k).GetFeatureCount() == 28, \ + 'wrong number of point features after elements layer creation' + assert math.fabs(layere.GetFeature(5).GetFieldAsDouble(0) - 9) <= 0.01, \ + 'wrong value of attribute in element layer' + assert math.fabs(layere.GetFeature(10).GetFieldAsDouble(0) - 15) <= 0.01, \ + 'wrong value of attribute in element layer' # return del gdaltest.selafin_ds - return 'success' ############################################################################### # Add a field and set its values for point features -def ogr_selafin_set_field(): +def test_ogr_selafin_set_field(): gdaltest.selafin_ds = ogr.Open('tmp/tmp.slf', 1) if gdaltest.selafin_ds is None: - return 'skip' + pytest.skip() layerCount = gdaltest.selafin_ds.GetLayerCount() - if layerCount < 2: - gdaltest.post_reason('elements layer not created with nodes layer') - return 'fail' + assert layerCount >= 2, 'elements layer not created with nodes layer' for i in range(layerCount): name = gdaltest.selafin_ds.GetLayer(i).GetName() if '_e' in name: @@ -187,39 +165,19 @@ def ogr_selafin_set_field(): feat.SetField(0, (float)(val * 10)) layern.SetFeature(feat) # do some checks - if math.fabs(layern.GetFeature(11).GetFieldAsDouble(0) - 110) > 0.01: - gdaltest.post_reason('wrong value of attribute in point layer') - return 'fail' + assert math.fabs(layern.GetFeature(11).GetFieldAsDouble(0) - 110) <= 0.01, \ + 'wrong value of attribute in point layer' # return del gdaltest.selafin_ds - return 'success' ############################################################################### # Cleanup -def ogr_selafin_cleanup(): +def test_ogr_selafin_cleanup(): selafin_drv = ogr.GetDriverByName('Selafin') selafin_drv.DeleteDataSource('tmp/tmp.slf') - return 'success' -gdaltest_list = [ - ogr_selafin_create_ds, - ogr_selafin_create_nodes, - ogr_selafin_create_elements, - ogr_selafin_set_field, - ogr_selafin_cleanup -] -if __name__ == '__main__': - gdal.PushErrorHandler('CPLQuietErrorHandler') - ogrtest.have_geos() - gdal.PopErrorHandler() - - gdaltest.setup_run('ogr_selafin') - - gdaltest.run_tests(gdaltest_list) - - sys.exit(gdaltest.summarize()) diff --git a/autotest/ogr/ogr_shape.py b/autotest/ogr/ogr_shape.py index a11ec426796b..0e049cd76fb8 100755 --- a/autotest/ogr/ogr_shape.py +++ b/autotest/ogr/ogr_shape.py @@ -32,19 +32,19 @@ import struct import sys -sys.path.append('../pymod') import gdaltest import ogrtest from osgeo import gdal from osgeo import ogr from osgeo import osr +import pytest ############################################################################### # Open Shapefile -def ogr_shape_1(): +def test_ogr_shape_1(): shape_drv = ogr.GetDriverByName('ESRI Shapefile') shape_drv.DeleteDataSource('tmp') @@ -52,17 +52,17 @@ def ogr_shape_1(): gdaltest.shape_ds = shape_drv.CreateDataSource('tmp') if gdaltest.shape_ds is not None: - return 'success' - return 'fail' + return + pytest.fail() ############################################################################### # Create table from data/poly.shp -def ogr_shape_2(): +def test_ogr_shape_2(): if gdaltest.shape_ds is None: - return 'skip' + pytest.skip() ####################################################### # Create memory Layer @@ -99,15 +99,13 @@ def ogr_shape_2(): # Destroy required. shp_ds.Destroy() - return 'success' - ############################################################################### # Verify that stuff we just wrote is still OK. -def ogr_shape_3(): +def test_ogr_shape_3(): if gdaltest.shape_ds is None: - return 'skip' + pytest.skip() expect = [168, 169, 166, 158, 165] @@ -120,27 +118,25 @@ def ogr_shape_3(): orig_feat = gdaltest.poly_feat[i] read_feat = gdaltest.shape_lyr.GetNextFeature() - if ogrtest.check_feature_geometry(read_feat, orig_feat.GetGeometryRef(), - max_error=0.000000001) != 0: - return 'fail' + assert (ogrtest.check_feature_geometry(read_feat, orig_feat.GetGeometryRef(), + max_error=0.000000001) == 0) for fld in range(3): - if orig_feat.GetField(fld) != read_feat.GetField(fld): - gdaltest.post_reason('Attribute %d does not match' % fld) - return 'fail' + assert orig_feat.GetField(fld) == read_feat.GetField(fld), \ + ('Attribute %d does not match' % fld) gdaltest.poly_feat = None - return 'success' if tr else 'fail' + assert tr ############################################################################### # Write a feature without a geometry, and verify that it works OK. -def ogr_shape_4(): +def test_ogr_shape_4(): if gdaltest.shape_ds is None: - return 'skip' + pytest.skip() ###################################################################### # Create feature without geometry. @@ -154,26 +150,21 @@ def ogr_shape_4(): gdaltest.shape_lyr.SetAttributeFilter("PRFEDEA = 'nulled'") feat_read = gdaltest.shape_lyr.GetNextFeature() - if feat_read is None: - gdaltest.post_reason('Didnt get feature with null geometry back.') - return 'fail' + assert feat_read is not None, 'Didnt get feature with null geometry back.' if feat_read.GetGeometryRef() is not None: - print(feat_read.GetGeometryRef()) print(feat_read.GetGeometryRef().ExportToWkt()) - gdaltest.post_reason('Didnt get null geometry as expected.') - return 'fail' - - return 'success' + pytest.fail('Didnt get null geometry as expected.') + ############################################################################### # Test ExecuteSQL() results layers without geometry. -def ogr_shape_5(): +def test_ogr_shape_5(): if gdaltest.shape_ds is None: - return 'skip' + pytest.skip() expect = [179, 173, 172, 171, 170, 169, 168, 166, 165, 158, None] @@ -183,16 +174,16 @@ def ogr_shape_5(): gdaltest.shape_ds.ReleaseResultSet(sql_lyr) - return 'success' if tr else 'fail' + assert tr ############################################################################### # Test ExecuteSQL() results layers with geometry. -def ogr_shape_6(): +def test_ogr_shape_6(): if gdaltest.shape_ds is None: - return 'skip' + pytest.skip() sql_lyr = gdaltest.shape_ds.ExecuteSQL( "select * from tpoly where prfedea = '35043413'") @@ -206,16 +197,16 @@ def ogr_shape_6(): gdaltest.shape_ds.ReleaseResultSet(sql_lyr) - return 'success' if tr else 'fail' + assert tr ############################################################################### # Test spatial filtering. -def ogr_shape_7(): +def test_ogr_shape_7(): if gdaltest.shape_ds is None: - return 'skip' + pytest.skip() gdaltest.shape_lyr.SetAttributeFilter(None) @@ -229,23 +220,21 @@ def ogr_shape_7(): gdaltest.shape_lyr.SetSpatialFilter(None) - return 'success' if tr else 'fail' + assert tr ############################################################################### # Create spatial index, and verify we get the same results. -def ogr_shape_8(): +def test_ogr_shape_8(): if gdaltest.shape_ds is None: - return 'skip' + pytest.skip() gdaltest.shape_lyr.SetAttributeFilter(None) gdaltest.shape_ds.ExecuteSQL('CREATE SPATIAL INDEX ON tpoly') - if not os.access('tmp/tpoly.qix', os.F_OK): - gdaltest.post_reason('tpoly.qix not created') - return 'fail' + assert os.access('tmp/tpoly.qix', os.F_OK), 'tpoly.qix not created' geom = ogr.CreateGeometryFromWkt( 'LINESTRING(479505 4763195,480526 4762819)') @@ -257,28 +246,23 @@ def ogr_shape_8(): gdaltest.shape_lyr.SetSpatialFilter(None) - if not tr: - return 'fail' + assert tr # Test recreating while already existing gdaltest.shape_ds.ExecuteSQL('CREATE SPATIAL INDEX ON tpoly') gdaltest.shape_ds.ExecuteSQL('DROP SPATIAL INDEX ON tpoly') - if os.access('tmp/tpoly.qix', os.F_OK): - gdaltest.post_reason('tpoly.qix not deleted') - return 'fail' - - return 'success' + assert not os.access('tmp/tpoly.qix', os.F_OK), 'tpoly.qix not deleted' ############################################################################### # Test that we don't return a polygon if we are "inside" but non-overlapping. -def ogr_shape_9(): +def test_ogr_shape_9(): if gdaltest.shape_ds is None: - return 'skip' + pytest.skip() gdaltest.shape_ds = None gdaltest.shape_ds = ogr.Open('data/testpoly.shp') @@ -287,35 +271,35 @@ def ogr_shape_9(): gdaltest.shape_lyr.SetSpatialFilterRect(-10, -130, 10, -110) if ogrtest.have_geos() and gdaltest.shape_lyr.GetFeatureCount() == 0: - return 'success' + return if not ogrtest.have_geos() and gdaltest.shape_lyr.GetFeatureCount() == 1: - return 'success' - return 'fail' + return + pytest.fail() ############################################################################### # Do a fair size query that should pull in a few shapes. -def ogr_shape_10(): +def test_ogr_shape_10(): if gdaltest.shape_ds is None: - return 'skip' + pytest.skip() gdaltest.shape_lyr.SetSpatialFilterRect(-400, 22, -120, 400) tr = ogrtest.check_features_against_list(gdaltest.shape_lyr, 'FID', [0, 4, 8]) - return 'success' if tr else 'fail' + assert tr ############################################################################### # Do a mixed indexed attribute and spatial query. -def ogr_shape_11(): +def test_ogr_shape_11(): if gdaltest.shape_ds is None: - return 'skip' + pytest.skip() gdaltest.shape_lyr.SetAttributeFilter('FID = 5') gdaltest.shape_lyr.SetSpatialFilterRect(-400, 22, -120, 400) @@ -323,8 +307,7 @@ def ogr_shape_11(): tr = ogrtest.check_features_against_list(gdaltest.shape_lyr, 'FID', []) - if not tr: - return 'fail' + assert tr gdaltest.shape_lyr.SetAttributeFilter('FID = 4') gdaltest.shape_lyr.SetSpatialFilterRect(-400, 22, -120, 400) @@ -335,16 +318,16 @@ def ogr_shape_11(): gdaltest.shape_lyr.SetAttributeFilter(None) gdaltest.shape_lyr.SetSpatialFilter(None) - return 'success' if tr else 'fail' + assert tr ############################################################################### # Check that multipolygon of asm.shp is properly returned. -def ogr_shape_12(): +def test_ogr_shape_12(): if gdaltest.shape_ds is None: - return 'skip' + pytest.skip() asm_ds = ogr.Open('data/asm.shp') asm_lyr = asm_ds.GetLayer(0) @@ -352,45 +335,33 @@ def ogr_shape_12(): feat = asm_lyr.GetNextFeature() geom = feat.GetGeometryRef() - if geom.GetCoordinateDimension() != 2: - gdaltest.post_reason('dimension wrong.') - return 'fail' + assert geom.GetCoordinateDimension() == 2, 'dimension wrong.' - if geom.GetGeometryName() != 'MULTIPOLYGON': - gdaltest.post_reason('Geometry of wrong type.') - return 'fail' + assert geom.GetGeometryName() == 'MULTIPOLYGON', 'Geometry of wrong type.' - if geom.GetGeometryCount() != 5: - gdaltest.post_reason('Did not get the expected number of polygons.') - return 'fail' + assert geom.GetGeometryCount() == 5, 'Did not get the expected number of polygons.' counts = [15, 11, 17, 20, 9] for i in range(5): poly = geom.GetGeometryRef(i) - if poly.GetGeometryName() != 'POLYGON': - gdaltest.post_reason('Did not get right type for polygons') - return 'fail' + assert poly.GetGeometryName() == 'POLYGON', \ + 'Did not get right type for polygons' - if poly.GetGeometryCount() != 1: - gdaltest.post_reason('polygon with more than one ring.') - return 'fail' + assert poly.GetGeometryCount() == 1, 'polygon with more than one ring.' pnt_count = poly.GetGeometryRef(0).GetPointCount() - if pnt_count != counts[i]: - gdaltest.post_reason(('Polygon %d has %d points instead of %d.' % - (i, pnt_count, counts[i]))) - return 'fail' - - return 'success' + assert pnt_count == counts[i], ('Polygon %d has %d points instead of %d.' % + (i, pnt_count, counts[i])) + ############################################################################### # Perform a SetFeature() on a couple features, resetting the size. -def ogr_shape_13(): +def test_ogr_shape_13(): if gdaltest.shape_ds is None: - return 'skip' + pytest.skip() gdaltest.shape_ds = None gdaltest.shape_ds = ogr.Open('tmp/tpoly.shp', update=1) @@ -406,9 +377,7 @@ def ogr_shape_13(): 'POLYGON ((0 0, 0 60, 100 60, 100 0, 200 30, 0 0))') feat.SetGeometry(geom) - if gdaltest.shape_lyr.SetFeature(feat) != 0: - gdaltest.post_reason('SetFeature() failed.') - return 'fail' + assert gdaltest.shape_lyr.SetFeature(feat) == 0, 'SetFeature() failed.' ###################################################################### # Update FID 8 (EAS_ID=165), making the polygon smaller. @@ -420,20 +389,16 @@ def ogr_shape_13(): 'POLYGON ((0 0, 0 60, 100 60, 100 0, 0 0))') feat.SetGeometry(geom) - if gdaltest.shape_lyr.SetFeature(feat) != 0: - gdaltest.post_reason('SetFeature() failed.') - return 'fail' - - return 'success' + assert gdaltest.shape_lyr.SetFeature(feat) == 0, 'SetFeature() failed.' ############################################################################### # Verify last changes. -def ogr_shape_14(): +def test_ogr_shape_14(): if gdaltest.shape_ds is None: - return 'skip' + pytest.skip() gdaltest.shape_ds = None gdaltest.shape_ds = ogr.Open('tmp/tpoly.shp', update=1) @@ -444,44 +409,34 @@ def ogr_shape_14(): feat = gdaltest.shape_lyr.GetFeature(9) - if feat.GetField('AREA') != 6000.0: - gdaltest.post_reason('AREA update failed, FID 9.') - return 'fail' + assert feat.GetField('AREA') == 6000.0, 'AREA update failed, FID 9.' - if ogrtest.check_feature_geometry(feat, 'POLYGON ((0 0, 0 60, 100 60, 100 0, 200 30, 0 0))') != 0: - gdaltest.post_reason('Geometry update failed, FID 9.') - return 'fail' + assert ogrtest.check_feature_geometry(feat, 'POLYGON ((0 0, 0 60, 100 60, 100 0, 200 30, 0 0))') == 0, \ + 'Geometry update failed, FID 9.' ###################################################################### # Update FID 8 (EAS_ID=165), making the polygon smaller. feat = gdaltest.shape_lyr.GetFeature(8) - if feat.GetField('AREA') != 7000.0: - gdaltest.post_reason('AREA update failed, FID 8.') - return 'fail' - - if ogrtest.check_feature_geometry(feat, 'POLYGON ((0 0, 0 60, 100 60, 100 0, 0 0))') != 0: - gdaltest.post_reason('Geometry update failed, FID 8.') - return 'fail' + assert feat.GetField('AREA') == 7000.0, 'AREA update failed, FID 8.' - return 'success' + assert ogrtest.check_feature_geometry(feat, 'POLYGON ((0 0, 0 60, 100 60, 100 0, 0 0))') == 0, \ + 'Geometry update failed, FID 8.' ############################################################################### # Delete a feature, and verify reduced count. -def ogr_shape_15(): +def test_ogr_shape_15(): if gdaltest.shape_ds is None: - return 'skip' + pytest.skip() ###################################################################### # Delete FID 9. - if gdaltest.shape_lyr.DeleteFeature(9) != 0: - gdaltest.post_reason('DeleteFeature failed.') - return 'fail' + assert gdaltest.shape_lyr.DeleteFeature(9) == 0, 'DeleteFeature failed.' ###################################################################### # Count features, verifying that none are FID 9. @@ -489,27 +444,21 @@ def ogr_shape_15(): count = 0 feat = gdaltest.shape_lyr.GetNextFeature() while feat is not None: - if feat.GetFID() == 9: - gdaltest.post_reason('Still an FID 9 in dataset.') - return 'fail' + assert feat.GetFID() != 9, 'Still an FID 9 in dataset.' count = count + 1 feat = gdaltest.shape_lyr.GetNextFeature() - if count != 10: - gdaltest.post_reason('Did not get expected FID count.') - return 'fail' - - return 'success' + assert count == 10, 'Did not get expected FID count.' ############################################################################### # Repack and verify a few things. -def ogr_shape_16(): +def test_ogr_shape_16(): if gdaltest.shape_ds is None: - return 'skip' + pytest.skip() gdaltest.shape_ds.ExecuteSQL('REPACK tpoly') @@ -527,26 +476,20 @@ def ogr_shape_16(): count = count + 1 feat = gdaltest.shape_lyr.GetNextFeature() - if count != 10: - gdaltest.post_reason('Did not get expected FID count.') - return 'fail' + assert count == 10, 'Did not get expected FID count.' - if got_9 == 0: - gdaltest.post_reason('Did not get FID 9 as expected.') - return 'fail' + assert got_9 != 0, 'Did not get FID 9 as expected.' feat = gdaltest.shape_lyr.GetFeature(9) - return 'success' - ############################################################################### # Test adding a field to the schema of a populated layer. -def ogr_shape_16_1(): +def test_ogr_shape_16_1(): if gdaltest.shape_ds is None: - return 'skip' + pytest.skip() ###################################################################### # Add a new field. @@ -555,32 +498,24 @@ def ogr_shape_16_1(): result = gdaltest.shape_lyr.CreateField(field_defn) - if result != 0: - gdaltest.post_reason('failed to create new field.') - return 'fail' + assert result == 0, 'failed to create new field.' ###################################################################### # Check at least one feature. feat = gdaltest.shape_lyr.GetFeature(8) - if feat.EAS_ID != 165: - gdaltest.post_reason('Got wrong EAS_ID') - return 'fail' - - if not feat.IsFieldNull('NEWFLD'): - gdaltest.post_reason('Expected NULL NEWFLD value!') - return 'fail' + assert feat.EAS_ID == 165, 'Got wrong EAS_ID' - return 'success' + assert feat.IsFieldNull('NEWFLD'), 'Expected NULL NEWFLD value!' ############################################################################### # Simple test with point shapefile with no associated .dbf -def ogr_shape_17(): +def test_ogr_shape_17(): if gdaltest.shape_ds is None: - return 'skip' + pytest.skip() shutil.copy('data/can_caps.shp', 'tmp/can_caps.shp') shutil.copy('data/can_caps.shx', 'tmp/can_caps.shx') @@ -588,9 +523,8 @@ def ogr_shape_17(): shp_ds = ogr.Open('tmp/can_caps.shp', update=1) shp_lyr = shp_ds.GetLayer(0) - if shp_lyr.GetLayerDefn().GetFieldCount() != 0: - gdaltest.post_reason('Unexpectedly got attribute fields.') - return 'fail' + assert shp_lyr.GetLayerDefn().GetFieldCount() == 0, \ + 'Unexpectedly got attribute fields.' count = 0 while 1: @@ -604,17 +538,12 @@ def ogr_shape_17(): count += 1 - if count != 13: - gdaltest.post_reason('Got wrong number of features.') - return 'fail' + assert count == 13, 'Got wrong number of features.' # Create new feature without a DBF feat = ogr.Feature(shp_lyr.GetLayerDefn()) shp_lyr.CreateFeature(feat) - if feat.GetFID() != 13: - print(feat.GetFID()) - gdaltest.post_reason('Got wrong FID.') - return 'fail' + assert feat.GetFID() == 13, 'Got wrong FID.' shp_lyr = None shp_ds = None @@ -622,22 +551,18 @@ def ogr_shape_17(): os.remove('tmp/can_caps.shp') os.remove('tmp/can_caps.shx') - return 'success' - ############################################################################### # Test reading data/poly.PRJ file with mixed-case file name -def ogr_shape_18(): +def test_ogr_shape_18(): shp_ds = ogr.Open('data/poly.shp') shp_lyr = shp_ds.GetLayer(0) srs_lyr = shp_lyr.GetSpatialRef() - if srs_lyr is None: - gdaltest.post_reason('Missing projection definition.') - return 'fail' + assert srs_lyr is not None, 'Missing projection definition.' # data/poly.shp has arbitrarily assigned EPSG:27700 srs = osr.SpatialReference() @@ -648,17 +573,15 @@ def ogr_shape_18(): print('') print('expected = %s' % srs.ExportToPrettyWkt()) print('existing = %s' % srs_lyr.ExportToPrettyWkt()) - gdaltest.post_reason('Projections differ') - return 'fail' - - return 'success' + pytest.fail('Projections differ') + ############################################################################### # Test polygon formation logic - recognising what rings are inner/outer # and deciding on polygon vs. multipolygon (#1217) -def ogr_shape_19(): +def test_ogr_shape_19(): ds = ogr.Open('data/Stacks.shp') lyr = ds.GetLayer(0) @@ -667,62 +590,51 @@ def ogr_shape_19(): wkt = 'MULTIPOLYGON (((3115478.809630727861077 13939288.008583962917328,3134266.47213465673849 13971973.394036004319787,3176989.101938112173229 13957303.575368551537395,3198607.7820796193555 13921787.172278933227062,3169010.779504936654121 13891675.439224690198898,3120368.749186545144767 13897852.204979406669736,3115478.809630727861077 13939288.008583962917328),(3130405.993537959177047 13935427.529987264424562,3135038.567853996530175 13902742.144535223022103,3167209.22282647760585 13902227.414055664092302,3184452.693891727831215 13922559.267998272553086,3172871.258101634215564 13947781.061496697366238,3144561.081725850701332 13957818.305848112329841,3130405.993537959177047 13935427.529987264424562)),((3143016.890287171583623 13932596.512349685654044,3152282.038919246289879 13947266.331017138436437,3166179.761867358349264 13940060.104303302243352,3172099.162382294889539 13928221.303273428231478,3169268.144744716584682 13916897.23272311501205,3158201.439434182830155 13911235.197447959333658,3144818.446965630631894 13911749.927927518263459,3139928.507409813348204 13916382.502243556082249,3143016.890287171583623 13932596.512349685654044),(3149193.65604188805446 13926677.11183474957943,3150737.84748056717217 13918698.789401574060321,3158458.804673962760717 13919728.250360693782568,3164892.935668459162116 13923331.36371761187911,3163863.474709339439869 13928736.033752989023924,3157171.978475063573569 13935427.529987264424562,3149193.65604188805446 13926677.11183474957943)))' - if ogrtest.check_feature_geometry(feat, wkt, - max_error=0.00000001) != 0: - return 'fail' - - return 'success' + assert (ogrtest.check_feature_geometry(feat, wkt, + max_error=0.00000001) == 0) ############################################################################### # Test empty multipoint, multiline, multipolygon. # From GDAL 1.6.0, the expected behaviour is to return a feature with a NULL geometry -def ogr_shape_20(): +def test_ogr_shape_20(): if gdaltest.shape_ds is None: - return 'skip' + pytest.skip() ds = ogr.Open('data/emptymultipoint.shp') lyr = ds.GetLayer(0) lyr.ResetReading() feat = lyr.GetNextFeature() - if feat is None: - return 'fail' - if feat.GetGeometryRef() is not None: - return 'fail' + assert feat is not None + assert feat.GetGeometryRef() is None ds = ogr.Open('data/emptymultiline.shp') lyr = ds.GetLayer(0) lyr.ResetReading() feat = lyr.GetNextFeature() - if feat is None: - return 'fail' - if feat.GetGeometryRef() is not None: - return 'fail' + assert feat is not None + assert feat.GetGeometryRef() is None ds = ogr.Open('data/emptymultipoly.shp') lyr = ds.GetLayer(0) lyr.ResetReading() feat = lyr.GetNextFeature() - if feat is None: - return 'fail' - if feat.GetGeometryRef() is not None: - return 'fail' - - return 'success' + assert feat is not None + assert feat.GetGeometryRef() is None ############################################################################### # Test robutness towards broken/unfriendly shapefiles -def ogr_shape_21(): +def test_ogr_shape_21(): if gdaltest.shape_ds is None: - return 'skip' + pytest.skip() files = ['data/buggypoint.shp', 'data/buggymultipoint.shp', @@ -737,8 +649,7 @@ def ogr_shape_21(): feat = lyr.GetNextFeature() gdal.PopErrorHandler() - if feat.GetGeometryRef() is not None: - return 'fail' + assert feat.GetGeometryRef() is None # Test fix for #3665 lyr.ResetReading() @@ -748,19 +659,17 @@ def ogr_shape_21(): feat = lyr.GetNextFeature() gdal.PopErrorHandler() - if feat is not None and feat.GetGeometryRef() is not None: - return 'fail' - - return 'success' + assert feat is None or feat.GetGeometryRef() is None + ############################################################################### # Test writing and reading all handled data types -def ogr_shape_22(): +def test_ogr_shape_22(): if gdaltest.shape_ds is None: - return 'skip' + pytest.skip() ####################################################### # Create memory Layer @@ -792,13 +701,10 @@ def ogr_shape_22(): gdaltest.shape_ds = ogr.GetDriverByName('ESRI Shapefile').Open('tmp', update=1) gdaltest.shape_lyr = gdaltest.shape_ds.GetLayerByName('datatypes') feat_read = gdaltest.shape_lyr.GetNextFeature() - if feat_read.GetField('REAL') != 1.2 or \ - feat_read.GetField('INTEGER') != 3 or \ - feat_read.GetField('STRING') != 'aString' or \ - feat_read.GetFieldAsString('DATE') != '2005/10/12': - return 'fail' - - return 'success' + assert (feat_read.GetField('REAL') == 1.2 and \ + feat_read.GetField('INTEGER') == 3 and \ + feat_read.GetField('STRING') == 'aString' and \ + feat_read.GetFieldAsString('DATE') == '2005/10/12') ############################################################################### @@ -834,19 +740,15 @@ def ogr_shape_23_write_valid_and_invalid(layer_name, wkt, invalid_wkt, wkbType, gdaltest.shape_ds = ogr.GetDriverByName('ESRI Shapefile').Open('tmp', update=1) read_lyr = gdaltest.shape_ds.GetLayerByName(layer_name) - if read_lyr.GetFeatureCount() != 1: - return 'fail' + assert read_lyr.GetFeatureCount() == 1, layer_name feat_read = read_lyr.GetNextFeature() if isEmpty and feat_read.GetGeometryRef() is None: - return 'success' + return - if ogrtest.check_feature_geometry(feat_read, ogr.CreateGeometryFromWkt(wkt), - max_error=0.000000001) != 0: - print(feat_read.GetGeometryRef().ExportToWkt()) - return 'fail' - - return 'success' + assert (ogrtest.check_feature_geometry(feat_read, ogr.CreateGeometryFromWkt(wkt), + max_error=0.000000001) == 0), \ + feat_read.GetGeometryRef().ExportToWkt() def ogr_shape_23_write_geom(layer_name, geom, expected_geom, wkbType): @@ -872,31 +774,25 @@ def ogr_shape_23_write_geom(layer_name, geom, expected_geom, wkbType): gdaltest.shape_ds = ogr.GetDriverByName('ESRI Shapefile').Open('tmp', update=1) read_lyr = gdaltest.shape_ds.GetLayerByName(layer_name) - if read_lyr.GetFeatureCount() != 1: - return 'fail' + assert read_lyr.GetFeatureCount() == 1 feat_read = read_lyr.GetNextFeature() if expected_geom is None: - if feat_read.GetGeometryRef() is not None: - print(feat_read.GetGeometryRef().ExportToWkt()) - return 'fail' - return 'success' - - if ogrtest.check_feature_geometry(feat_read, expected_geom, - max_error=0.000000001) != 0: - print(feat_read.GetGeometryRef().ExportToWkt()) - return 'fail' + assert feat_read.GetGeometryRef() is None, feat_read.GetGeometryRef().ExportToWkt() + return - return 'success' + assert (ogrtest.check_feature_geometry(feat_read, expected_geom, + max_error=0.000000001) == 0), \ + feat_read.GetGeometryRef().ExportToWkt() ############################################################################### # Test writing and reading all handled geometry types -def ogr_shape_23(): +def test_ogr_shape_23(): if gdaltest.shape_ds is None: - return 'skip' + pytest.skip() test_geom_array = [ ('points', 'POINT(0 1)', 'LINESTRING(0 1)', ogr.wkbPoint), @@ -926,13 +822,9 @@ def ogr_shape_23(): # Write a feature in a new layer (geometry type unset at layer creation) for item in test_geom_array: - if ogr_shape_23_write_valid_and_invalid(item[0], item[1], item[2], ogr.wkbUnknown, 0) != 'success': - gdaltest.post_reason('Test for layer %s failed' % item[0]) - return 'fail' + ogr_shape_23_write_valid_and_invalid(item[0], item[1], item[2], ogr.wkbUnknown, 0) for item in test_empty_geom_array: - if ogr_shape_23_write_valid_and_invalid(item[0], item[1], item[2], ogr.wkbUnknown, 1) != 'success': - gdaltest.post_reason('Test for layer %s failed' % item[0]) - return 'fail' + ogr_shape_23_write_valid_and_invalid(item[0], item[1], item[2], ogr.wkbUnknown, 1) ####################################################### # Same test but use the wkb type when creating the layer @@ -943,13 +835,9 @@ def ogr_shape_23(): gdaltest.shape_ds = shape_drv.CreateDataSource('tmp') for item in test_geom_array: - if ogr_shape_23_write_valid_and_invalid(item[0], item[1], item[2], item[3], 0) != 'success': - gdaltest.post_reason('(2) Test for layer %s failed' % item[0]) - return 'fail' + ogr_shape_23_write_valid_and_invalid(item[0], item[1], item[2], item[3], 0) for item in test_empty_geom_array: - if ogr_shape_23_write_valid_and_invalid(item[0], item[1], item[2], item[3], 1) != 'success': - gdaltest.post_reason('(2) Test for layer %s failed' % item[0]) - return 'fail' + ogr_shape_23_write_valid_and_invalid(item[0], item[1], item[2], item[3], 1) ####################################################### # Test writing of a geometrycollection @@ -977,10 +865,9 @@ def ogr_shape_23(): read_lyr = gdaltest.shape_ds.GetLayerByName(layer_name) feat_read = read_lyr.GetNextFeature() - if ogrtest.check_feature_geometry(feat_read, ogr.CreateGeometryFromWkt('MULTIPOLYGON(((0 0 0,0 10,10 10,0 0),(0.25 0.5,1 1,0.5 1,0.25 0.5)),((100 0,100 10,110 10,100 0),(100.25 0.5,100.5 1,100 1,100.25 0.5)))'), - max_error=0.000000001) != 0: - print(feat_read.GetGeometryRef().ExportToWkt()) - return 'fail' + assert (ogrtest.check_feature_geometry(feat_read, ogr.CreateGeometryFromWkt('MULTIPOLYGON(((0 0 0,0 10,10 10,0 0),(0.25 0.5,1 1,0.5 1,0.25 0.5)),((100 0,100 10,110 10,100 0),(100.25 0.5,100.5 1,100 1,100.25 0.5)))'), + max_error=0.000000001) == 0), \ + feat_read.GetGeometryRef().ExportToWkt() ####################################################### # Test writing of a multipoint with an empty point inside @@ -989,9 +876,7 @@ def ogr_shape_23(): geom = ogr.CreateGeometryFromWkt(wkt) geom.AddGeometry(ogr.Geometry(type=ogr.wkbPoint)) - if ogr_shape_23_write_geom(layer_name, geom, ogr.CreateGeometryFromWkt(geom.ExportToWkt()), ogr.wkbUnknown) != 'success': - gdaltest.post_reason('Test for layer %s failed' % layer_name) - return 'fail' + ogr_shape_23_write_geom(layer_name, geom, ogr.CreateGeometryFromWkt(geom.ExportToWkt()), ogr.wkbUnknown) ####################################################### # Test writing of a multilinestring with an empty linestring inside @@ -1000,9 +885,7 @@ def ogr_shape_23(): geom = ogr.CreateGeometryFromWkt(wkt) geom.AddGeometry(ogr.Geometry(type=ogr.wkbLineString)) - if ogr_shape_23_write_geom(layer_name, geom, ogr.CreateGeometryFromWkt(geom.ExportToWkt()), ogr.wkbUnknown) != 'success': - gdaltest.post_reason('Test for layer %s failed' % layer_name) - return 'fail' + ogr_shape_23_write_geom(layer_name, geom, ogr.CreateGeometryFromWkt(geom.ExportToWkt()), ogr.wkbUnknown) ####################################################### # Test writing of a polygon with an empty external ring @@ -1017,9 +900,7 @@ def ogr_shape_23(): ring.AddPoint_2D(0, 0) geom.AddGeometry(ring) - if ogr_shape_23_write_geom(layer_name, geom, None, ogr.wkbUnknown) != 'success': - gdaltest.post_reason('Test for layer %s failed' % layer_name) - return 'fail' + ogr_shape_23_write_geom(layer_name, geom, None, ogr.wkbUnknown) ####################################################### # Test writing of a polygon with an empty external ring @@ -1028,9 +909,7 @@ def ogr_shape_23(): geom = ogr.CreateGeometryFromWkt(wkt) geom.AddGeometry(ogr.Geometry(type=ogr.wkbLinearRing)) - if ogr_shape_23_write_geom(layer_name, geom, ogr.CreateGeometryFromWkt(geom.ExportToWkt()), ogr.wkbUnknown) != 'success': - gdaltest.post_reason('Test for layer %s failed' % layer_name) - return 'fail' + ogr_shape_23_write_geom(layer_name, geom, ogr.CreateGeometryFromWkt(geom.ExportToWkt()), ogr.wkbUnknown) ####################################################### # Test writing of a multipolygon with an empty polygon and a polygon with an empty external ring @@ -1042,44 +921,34 @@ def ogr_shape_23(): poly.AddGeometry(ogr.Geometry(type=ogr.wkbLinearRing)) geom.AddGeometry(poly) - if ogr_shape_23_write_geom(layer_name, geom, ogr.CreateGeometryFromWkt(geom.ExportToWkt()), ogr.wkbUnknown) != 'success': - gdaltest.post_reason('Test for layer %s failed' % layer_name) - return 'fail' - - return 'success' + ogr_shape_23_write_geom(layer_name, geom, ogr.CreateGeometryFromWkt(geom.ExportToWkt()), ogr.wkbUnknown) ############################################################################### # Test reading a polygon whose outer and the inner ring touches at one point (#2589) -def ogr_shape_24(): +def test_ogr_shape_24(): if gdaltest.shape_ds is None: - return 'skip' + pytest.skip() layer_name = 'touchingrings' wkt = 'MULTIPOLYGON(((0 0,0 10,10 10,0 0), (0 0,1 1,0 1,0 0)), ((100 100,100 200,200 200,200 100,100 100)))' geom = ogr.CreateGeometryFromWkt(wkt) - if ogr_shape_23_write_geom(layer_name, geom, ogr.CreateGeometryFromWkt(geom.ExportToWkt()), ogr.wkbUnknown) != 'success': - gdaltest.post_reason('Test for layer %s failed' % layer_name) - return 'fail' - - return 'success' + ogr_shape_23_write_geom(layer_name, geom, ogr.CreateGeometryFromWkt(geom.ExportToWkt()), ogr.wkbUnknown) ############################################################################### # Test reading a multipolygon with one part inside the bounding box of the other # part, but not inside it, and sharing the same first point... (#2589) -def ogr_shape_25(): +def test_ogr_shape_25(): layer_name = 'touchingrings2' wkt = 'MULTIPOLYGON(((10 5, 5 5,5 0,0 0,0 10,10 10,10 5)),((10 5,10 0,5 0,5 4.9,10 5)), ((100 100,100 200,200 200,200 100,100 100)))' geom = ogr.CreateGeometryFromWkt(wkt) - if ogr_shape_23_write_geom(layer_name, geom, ogr.CreateGeometryFromWkt(geom.ExportToWkt()), ogr.wkbUnknown) != 'success': - gdaltest.post_reason('Test for layer %s failed' % layer_name) - return 'fail' + ogr_shape_23_write_geom(layer_name, geom, ogr.CreateGeometryFromWkt(geom.ExportToWkt()), ogr.wkbUnknown) # Same test, but use OGR_ORGANIZE_POLYGONS=DEFAULT to avoid relying only on the winding order layer_name = 'touchingrings3' @@ -1087,64 +956,47 @@ def ogr_shape_25(): geom = ogr.CreateGeometryFromWkt(wkt) gdal.SetConfigOption('OGR_ORGANIZE_POLYGONS', 'DEFAULT') - ret = ogr_shape_23_write_geom(layer_name, geom, ogr.CreateGeometryFromWkt(geom.ExportToWkt()), ogr.wkbUnknown) + ogr_shape_23_write_geom(layer_name, geom, ogr.CreateGeometryFromWkt(geom.ExportToWkt()), ogr.wkbUnknown) gdal.SetConfigOption('OGR_ORGANIZE_POLYGONS', '') - if ret != 'success': - gdaltest.post_reason('Test for layer %s failed' % layer_name) - return 'fail' - - return 'success' ############################################################################### # Test a polygon made of one outer ring and two inner rings (special case # in organizePolygons() -def ogr_shape_26(): +def test_ogr_shape_26(): layer_name = 'oneouterring' wkt = 'POLYGON ((100 100,100 200,200 200,200 100,100 100),(110 110,120 110,120 120,110 120,110 110),(130 110,140 110,140 120,130 120,130 110))' geom = ogr.CreateGeometryFromWkt(wkt) - ret = ogr_shape_23_write_geom(layer_name, geom, ogr.CreateGeometryFromWkt(geom.ExportToWkt()), ogr.wkbUnknown) - if ret != 'success': - gdaltest.post_reason('Test for layer %s failed' % layer_name) - return 'fail' - - return 'success' + ogr_shape_23_write_geom(layer_name, geom, ogr.CreateGeometryFromWkt(geom.ExportToWkt()), ogr.wkbUnknown) ############################################################################### # Test alternate date formatting (#2746) -def ogr_shape_27(): - - result = 'success' - +def test_ogr_shape_27(): ds = ogr.Open('data/water_main_dist.dbf') lyr = ds.GetLayer(0) feat = lyr.GetNextFeature() - if feat.installe_1 != '1989/04/25': - print(feat.installe_1) - gdaltest.post_reason('got wrong date result!') - result = 'fail' + assert feat.installe_1 == '1989/04/25', 'got wrong date result!' feat = None lyr = None ds = None - return result ############################################################################### # Test reading a 3 GB .DBF (#3011) -def ogr_shape_28(): +def test_ogr_shape_28(): # Determine if the filesystem supports sparse files (we don't want to create a real 3 GB # file ! if not gdaltest.filesystem_supports_sparse_files('tmp'): - return 'skip' + pytest.skip() for filename in ('tmp/hugedbf.dbf', 'tmp/hugedbf.shp', 'tmp/hugedbf.shx'): try: @@ -1184,16 +1036,12 @@ def ogr_shape_28(): f.close() ds = ogr.Open('tmp/hugedbf.dbf', update=1) - if ds is None: - gdaltest.post_reason('Cannot open tmp/hugedbf.dbf') - return 'fail' + assert ds is not None, 'Cannot open tmp/hugedbf.dbf' # Check that the hand-written value can be read back lyr = ds.GetLayer(0) feat = lyr.GetFeature(23900000) - if feat.GetFieldAsString(0) != 'value_over_2GB': - print(feat.GetFieldAsString(0)) - return 'fail' + assert feat.GetFieldAsString(0) == 'value_over_2GB' # Update with a new value feat.SetField(0, 'updated_value') @@ -1206,13 +1054,10 @@ def ogr_shape_28(): gdal.PushErrorHandler('CPLQuietErrorHandler') ret = lyr.CreateFeature(feat) gdal.PopErrorHandler() - if ret != 0: - gdaltest.post_reason('failure') - return 'fail' + assert ret == 0 feat = None - if gdal.GetLastErrorMsg().find('2GB file size limit reached') < 0: - gdaltest.post_reason('did not find expected warning') - return 'fail' + assert gdal.GetLastErrorMsg().find('2GB file size limit reached') >= 0, \ + 'did not find expected warning' ds = None @@ -1222,9 +1067,7 @@ def ogr_shape_28(): gdal.SetConfigOption('SHAPE_2GB_LIMIT', None) lyr = ds.GetLayer(0) feat = lyr.GetFeature(23900000) - if feat.GetFieldAsString(0) != 'updated_value': - print(feat.GetFieldAsString(0)) - return 'fail' + assert feat.GetFieldAsString(0) == 'updated_value' feat = None # Test creating a feature over 2 GB file limit -> should fail @@ -1233,23 +1076,18 @@ def ogr_shape_28(): gdal.PushErrorHandler('CPLQuietErrorHandler') ret = lyr.CreateFeature(feat) gdal.PopErrorHandler() - if ret == 0: - gdaltest.post_reason('failure') - return 'fail' + assert ret != 0 feat = None - if gdal.GetLastErrorMsg().find('2GB file size limit reached') < 0: - gdaltest.post_reason('did not find expected warning') - return 'fail' + assert gdal.GetLastErrorMsg().find('2GB file size limit reached') >= 0, \ + 'did not find expected warning' ds = None - return 'success' - ############################################################################### # Test that REPACK doesn't change extension case (#3293) -def ogr_shape_29(): +def test_ogr_shape_29(): os.mkdir('tmp/UPPERCASE') shutil.copy('data/poly.shp', 'tmp/UPPERCASE/UPPERCASE.SHP') @@ -1267,29 +1105,19 @@ def ogr_shape_29(): lst = gdal.ReadDir('tmp/UPPERCASE') - if len(lst) != 6: - print(lst) - return 'fail' + assert len(lst) == 6 for filename in lst: - if filename not in ['.', '..', 'UPPERCASE.SHP', 'UPPERCASE.SHX', 'UPPERCASE.DBF', 'UPPERCASE.CPG']: - gdaltest.post_reason('fail') - print(lst) - print(filename) - return 'fail' - if filename.find('packed') >= 0: - gdaltest.post_reason('fail') - print(lst) - print(filename) - return 'fail' - - return 'success' + assert filename in ['.', '..', 'UPPERCASE.SHP', 'UPPERCASE.SHX', 'UPPERCASE.DBF', 'UPPERCASE.CPG'], \ + lst + assert filename.find('packed') < 0, lst + ############################################################################### # Test that REPACK doesn't change extension case (#3293) -def ogr_shape_30(): +def test_ogr_shape_30(): os.mkdir('tmp/lowercase') shutil.copy('data/poly.shp', 'tmp/lowercase/lowercase.shp') @@ -1304,26 +1132,21 @@ def ogr_shape_30(): lst = gdal.ReadDir('tmp/lowercase') - if len(lst) != 5: - print(lst) - return 'fail' + assert len(lst) == 5 for filename in lst: - if filename not in ['.', '..', 'lowercase.shp', 'lowercase.shx', 'lowercase.dbf']: - print(lst) - return 'fail' - - return 'success' + assert filename in ['.', '..', 'lowercase.shp', 'lowercase.shx', 'lowercase.dbf'], lst + ############################################################################### # Test truncation of long and duplicate field names. # FIXME: Empty field names are allowed now! -def ogr_shape_31(): +def test_ogr_shape_31(): if gdaltest.shape_ds is None: - return 'skip' + pytest.skip() fields = [('a', ogr.OFTReal), ('A', ogr.OFTInteger), @@ -1384,9 +1207,7 @@ def ogr_shape_31(): print('Expected ', expected_fields[i], ',but got', layer_defn.GetFieldDefn(i).GetNameRef()) error_occurred = True - if error_occurred: - return 'fail' - return 'success' + assert not error_occurred ############################################################################### # Test creating a nearly 4GB (2^32 Bytes) .shp (#3236) @@ -1394,13 +1215,13 @@ def ogr_shape_31(): # Assuming 2^32 is the max value for unsigned int. -def ogr_shape_32(): +def test_ogr_shape_32(): # This test takes a few minutes and disk space. Hence, skipped by default. # To run this test, make sure that the directory BigFilePath points to has # 4.5 GB space available or give a new directory that does and delete the # directory afterwards. - return 'skip' # pylint: disable=unreachable + pytest.skip() # pylint: disable=unreachable # pylint: disable=unreachable from decimal import Decimal @@ -1427,9 +1248,7 @@ def ogr_shape_32(): dst_feat = ogr.Feature(feature_def=gdaltest.shape_lyr.GetLayerDefn()) dst_feat.SetGeometry(geom) ret = gdaltest.shape_lyr.CreateFeature(dst_feat) - if ret != 0 and n < 22845570: - print('File limit reached before 4GB!') - return 'fail' + assert ret == 0 or n >= 22845570, 'File limit reached before 4GB!' if (n % 22846) == 0: sys.stdout.write('\r%.1f%% ' % (n / Decimal('228460.0'))) @@ -1445,40 +1264,33 @@ def ogr_shape_32(): for i in [0, 1, read_lyr.GetFeatureCount() - 1]: feat_read = read_lyr.GetFeature(i) - if feat_read is None: - print('Could not retrieve geometry at FID', i) - return 'fail' - if ogrtest.check_feature_geometry(feat_read, ogr.CreateGeometryFromWkt('POLYGON((0 0,0 10,10 10,0 0),(0.25 0.5,1 1.1,0.5 1,0.25 0.5))'), - max_error=0.000000001) != 0: - print('Wrong geometry encountered at FID', i, ':', (feat_read.GetGeometryRef().ExportToWkt())) - return 'fail' - - return 'success' + assert feat_read is not None, ('Could not retrieve geometry at FID', i) + assert (ogrtest.check_feature_geometry(feat_read, ogr.CreateGeometryFromWkt('POLYGON((0 0,0 10,10 10,0 0),(0.25 0.5,1 1.1,0.5 1,0.25 0.5))'), + max_error=0.000000001) == 0), \ + ('Wrong geometry encountered at FID', i, ':', (feat_read.GetGeometryRef().ExportToWkt())) + ############################################################################### # Check that we can detect correct winding order even with polygons with big # coordinate offset (#3356) -def ogr_shape_33(): +def test_ogr_shape_33(): ds = ogr.Open('data/bigoffset.shp') lyr = ds.GetLayer(0) feat_read = lyr.GetNextFeature() - if ogrtest.check_feature_geometry(feat_read, ogr.CreateGeometryFromWkt('MULTIPOLYGON( ((0 0,0 1,1 1,1 0,0 0)),((100000000000 100000000000,100000000000 100000000001,100000000001 100000000001,100000000001 100000000000,100000000000 100000000000)) )'), - max_error=0.000000001) != 0: - print('Wrong geometry : %s' % feat_read.GetGeometryRef().ExportToWkt()) - return 'fail' - - return 'success' + assert (ogrtest.check_feature_geometry(feat_read, ogr.CreateGeometryFromWkt('MULTIPOLYGON( ((0 0,0 1,1 1,1 0,0 0)),((100000000000 100000000000,100000000000 100000000001,100000000001 100000000001,100000000001 100000000000,100000000000 100000000000)) )'), + max_error=0.000000001) == 0), \ + ('Wrong geometry : %s' % feat_read.GetGeometryRef().ExportToWkt()) ############################################################################### # Check that we can write correct winding order even with polygons with big # coordinate offset (#33XX) -def ogr_shape_34(): +def test_ogr_shape_34(): ds = ogr.GetDriverByName('ESRI Shapefile').CreateDataSource('tmp/bigoffset.shp') lyr = ds.CreateLayer('bigoffset') @@ -1493,18 +1305,15 @@ def ogr_shape_34(): lyr = ds.GetLayer(0) feat_read = lyr.GetNextFeature() - if ogrtest.check_feature_geometry(feat_read, ogr.CreateGeometryFromWkt('MULTIPOLYGON( ((0 0,0 1,1 1,1 0,0 0)),((100000000000 100000000000,100000000000 100000000001,100000000001 100000000001,100000000001 100000000000,100000000000 100000000000)) )'), - max_error=0.000000001) != 0: - print('Wrong geometry : %s' % feat_read.GetGeometryRef().ExportToWkt()) - return 'fail' - - return 'success' + assert (ogrtest.check_feature_geometry(feat_read, ogr.CreateGeometryFromWkt('MULTIPOLYGON( ((0 0,0 1,1 1,1 0,0 0)),((100000000000 100000000000,100000000000 100000000001,100000000001 100000000001,100000000001 100000000000,100000000000 100000000000)) )'), + max_error=0.000000001) == 0), \ + ('Wrong geometry : %s' % feat_read.GetGeometryRef().ExportToWkt()) ############################################################################### # Check that we can read & write a VSI*L dataset -def ogr_shape_35(): +def test_ogr_shape_35(): ds = ogr.GetDriverByName('ESRI Shapefile').CreateDataSource('/vsimem/test35.shp') srs = osr.SpatialReference() @@ -1520,123 +1329,97 @@ def ogr_shape_35(): ds = ogr.Open('/vsimem/test35.shp') lyr = ds.GetLayer(0) srs_read = lyr.GetSpatialRef() - if srs_read.ExportToWkt() != srs.ExportToWkt(): - gdaltest.post_reason('did not get expected SRS') - print(srs_read) - return 'fail' + assert srs_read.ExportToWkt() == srs.ExportToWkt(), 'did not get expected SRS' feat_read = lyr.GetNextFeature() - if ogrtest.check_feature_geometry(feat_read, ogr.CreateGeometryFromWkt('POINT(0 1)'), - max_error=0.000000001) != 0: - print('Wrong geometry : %s' % feat_read.GetGeometryRef().ExportToWkt()) - return 'fail' - - return 'success' + assert (ogrtest.check_feature_geometry(feat_read, ogr.CreateGeometryFromWkt('POINT(0 1)'), + max_error=0.000000001) == 0), \ + ('Wrong geometry : %s' % feat_read.GetGeometryRef().ExportToWkt()) ############################################################################### # Check that we can read from the root of a .ZIP file -def ogr_shape_36(): +def test_ogr_shape_36(): ds = ogr.Open('/vsizip/data/poly.zip') - if ds is None: - return 'fail' + assert ds is not None lyr = ds.GetLayer(0) srs = lyr.GetSpatialRef() wkt = srs.ExportToWkt() - if wkt.find('OSGB') == -1: - gdaltest.post_reason('did not get expected SRS') - return 'fail' + assert wkt.find('OSGB') != -1, 'did not get expected SRS' feat_read = lyr.GetFeature(9) - if ogrtest.check_feature_geometry(feat_read, ogr.CreateGeometryFromWkt('POLYGON ((479750.6875 4764702.0,479658.59375 4764670.0,479640.09375 4764721.0,479735.90625 4764752.0,479750.6875 4764702.0))'), - max_error=0.000000001) != 0: - print('Wrong geometry : %s' % feat_read.GetGeometryRef().ExportToWkt()) - return 'fail' - - return 'success' + assert (ogrtest.check_feature_geometry(feat_read, ogr.CreateGeometryFromWkt('POLYGON ((479750.6875 4764702.0,479658.59375 4764670.0,479640.09375 4764721.0,479735.90625 4764752.0,479750.6875 4764702.0))'), + max_error=0.000000001) == 0), \ + ('Wrong geometry : %s' % feat_read.GetGeometryRef().ExportToWkt()) ############################################################################### # Check that we can read from the root of a .tar.gz file -def ogr_shape_37(): +def test_ogr_shape_37(): ds = ogr.Open('/vsitar/data/poly.tar.gz') - if ds is None: - return 'fail' + assert ds is not None lyr = ds.GetLayer(0) srs = lyr.GetSpatialRef() wkt = srs.ExportToWkt() - if wkt.find('OSGB') == -1: - gdaltest.post_reason('did not get expected SRS') - return 'fail' + assert wkt.find('OSGB') != -1, 'did not get expected SRS' for i in range(10): feat_read = lyr.GetNextFeature() if i == 9: - if ogrtest.check_feature_geometry(feat_read, ogr.CreateGeometryFromWkt('POLYGON ((479750.6875 4764702.0,479658.59375 4764670.0,479640.09375 4764721.0,479735.90625 4764752.0,479750.6875 4764702.0))'), - max_error=0.000000001) != 0: - print('Wrong geometry : %s' % feat_read.GetGeometryRef().ExportToWkt()) - return 'fail' + assert (ogrtest.check_feature_geometry(feat_read, ogr.CreateGeometryFromWkt('POLYGON ((479750.6875 4764702.0,479658.59375 4764670.0,479640.09375 4764721.0,479735.90625 4764752.0,479750.6875 4764702.0))'), + max_error=0.000000001) == 0), \ + ('Wrong geometry : %s' % feat_read.GetGeometryRef().ExportToWkt()) lyr.ResetReading() feat_read = lyr.GetFeature(9) - if ogrtest.check_feature_geometry(feat_read, ogr.CreateGeometryFromWkt('POLYGON ((479750.6875 4764702.0,479658.59375 4764670.0,479640.09375 4764721.0,479735.90625 4764752.0,479750.6875 4764702.0))'), - max_error=0.000000001) != 0: - print('Wrong geometry : %s' % feat_read.GetGeometryRef().ExportToWkt()) - return 'fail' + assert (ogrtest.check_feature_geometry(feat_read, ogr.CreateGeometryFromWkt('POLYGON ((479750.6875 4764702.0,479658.59375 4764670.0,479640.09375 4764721.0,479735.90625 4764752.0,479750.6875 4764702.0))'), + max_error=0.000000001) == 0), \ + ('Wrong geometry : %s' % feat_read.GetGeometryRef().ExportToWkt()) ds = None gdal.Unlink('data/poly.tar.gz.properties') - return 'success' - ############################################################################### # Check that we can read from a .tar file -def ogr_shape_37_bis(): +def test_ogr_shape_37_bis(): ds = ogr.Open('/vsitar/data/poly.tar') - if ds is None: - return 'fail' + assert ds is not None lyr = ds.GetLayer(0) srs = lyr.GetSpatialRef() wkt = srs.ExportToWkt() - if wkt.find('OSGB') == -1: - gdaltest.post_reason('did not get expected SRS') - return 'fail' + assert wkt.find('OSGB') != -1, 'did not get expected SRS' for i in range(10): feat_read = lyr.GetNextFeature() if i == 9: - if ogrtest.check_feature_geometry(feat_read, ogr.CreateGeometryFromWkt('POLYGON ((479750.6875 4764702.0,479658.59375 4764670.0,479640.09375 4764721.0,479735.90625 4764752.0,479750.6875 4764702.0))'), - max_error=0.000000001) != 0: - print('Wrong geometry : %s' % feat_read.GetGeometryRef().ExportToWkt()) - return 'fail' + assert (ogrtest.check_feature_geometry(feat_read, ogr.CreateGeometryFromWkt('POLYGON ((479750.6875 4764702.0,479658.59375 4764670.0,479640.09375 4764721.0,479735.90625 4764752.0,479750.6875 4764702.0))'), + max_error=0.000000001) == 0), \ + ('Wrong geometry : %s' % feat_read.GetGeometryRef().ExportToWkt()) lyr.ResetReading() feat_read = lyr.GetFeature(9) - if ogrtest.check_feature_geometry(feat_read, ogr.CreateGeometryFromWkt('POLYGON ((479750.6875 4764702.0,479658.59375 4764670.0,479640.09375 4764721.0,479735.90625 4764752.0,479750.6875 4764702.0))'), - max_error=0.000000001) != 0: - print('Wrong geometry : %s' % feat_read.GetGeometryRef().ExportToWkt()) - return 'fail' - - return 'success' + assert (ogrtest.check_feature_geometry(feat_read, ogr.CreateGeometryFromWkt('POLYGON ((479750.6875 4764702.0,479658.59375 4764670.0,479640.09375 4764721.0,479735.90625 4764752.0,479750.6875 4764702.0))'), + max_error=0.000000001) == 0), \ + ('Wrong geometry : %s' % feat_read.GetGeometryRef().ExportToWkt()) ############################################################################### # Check that we cannot create duplicated layers -def ogr_shape_38(): +def test_ogr_shape_38(): ds = ogr.Open('/vsimem/', update=1) gdal.PushErrorHandler('CPLQuietErrorHandler') @@ -1644,38 +1427,31 @@ def ogr_shape_38(): gdal.PopErrorHandler() ds = None - if lyr is not None: - gdaltest.post_reason('should not have created a new layer') - return 'fail' - - return 'success' + assert lyr is None, 'should not have created a new layer' ############################################################################### # Check that we can detect correct winding order even with polygons with big # coordinate offset (#3356) -def ogr_shape_39(): +def test_ogr_shape_39(): ds = ogr.Open('data/multipatch.shp') lyr = ds.GetLayer(0) feat_read = lyr.GetNextFeature() - if ogrtest.check_feature_geometry(feat_read, ogr.CreateGeometryFromWkt('GEOMETRYCOLLECTION (TIN (((5 4 10,0 0 5,10 0 5,5 4 10)),((5 4 10,10 0 5,10 8 5,5 4 10)),((5 4 10,10 8 5,0 8 5,5 4 10)),((5 4 10,0 8 5,0 0 5,5 4 10))),TIN (((10 0 5,10 0 0,10 8 5,10 0 5)),((10 0 0,10 8 5,10 8 0,10 0 0)),((10 8 5,10 8 0,0 8 5,10 8 5)),((10 8 0,0 8 5,0 8 0,10 8 0)),((0 8 5,0 8 0,0 0 5,0 8 5)),((0 8 0,0 0 5,0 0 0,0 8 0))),MULTIPOLYGON (((0 0 0,0 0 5,10 0 5,10 0 0,6 0 0,6 0 3,4 0 3,4 0 0,0 0 0),(1 0 2,3 0 2,3 0 4,1 0 4,1 0 2),(7 0 2,9 0 2,9 0 4,7 0 4,7 0 2))))'), - max_error=0.000000001) != 0: - print('Wrong geometry : %s' % feat_read.GetGeometryRef().ExportToWkt()) - return 'fail' - - return 'success' + assert (ogrtest.check_feature_geometry(feat_read, ogr.CreateGeometryFromWkt('GEOMETRYCOLLECTION (TIN (((5 4 10,0 0 5,10 0 5,5 4 10)),((5 4 10,10 0 5,10 8 5,5 4 10)),((5 4 10,10 8 5,0 8 5,5 4 10)),((5 4 10,0 8 5,0 0 5,5 4 10))),TIN (((10 0 5,10 0 0,10 8 5,10 0 5)),((10 0 0,10 8 5,10 8 0,10 0 0)),((10 8 5,10 8 0,0 8 5,10 8 5)),((10 8 0,0 8 5,0 8 0,10 8 0)),((0 8 5,0 8 0,0 0 5,0 8 5)),((0 8 0,0 0 5,0 0 0,0 8 0))),MULTIPOLYGON (((0 0 0,0 0 5,10 0 5,10 0 0,6 0 0,6 0 3,4 0 3,4 0 0,0 0 0),(1 0 2,3 0 2,3 0 4,1 0 4,1 0 2),(7 0 2,9 0 2,9 0 4,7 0 4,7 0 2))))'), + max_error=0.000000001) == 0), \ + ('Wrong geometry : %s' % feat_read.GetGeometryRef().ExportToWkt()) ############################################################################### # Make some changes to a shapefile and check the index files. qix, sbn & sbx -def ogr_shape_40(): +def test_ogr_shape_40(): if gdaltest.shape_ds is None: - return 'skip' + pytest.skip() datafiles = ('gjpoint.dbf', 'gjpoint.shp', 'gjpoint.shx') indexfiles = ('gjpoint.sbn', 'gjpoint.sbx', 'gjpoint.qix') @@ -1694,14 +1470,10 @@ def ogr_shape_40(): geom = ogr.CreateGeometryFromWkt('POINT (99 1)') feat.SetGeometry(geom) for f in indexfiles: - if not os.path.exists(os.path.join('tmp', f)): - print('SetFeature(): ' + f) - return 'fail' + assert os.path.exists(os.path.join('tmp', f)), ('SetFeature(): ' + f) gdaltest.shape_lyr.SetFeature(feat) for f in indexfiles: - if os.path.exists(os.path.join('tmp', f)): - print('SetFeature(): ' + f) - return 'fail' + assert not os.path.exists(os.path.join('tmp', f)), ('SetFeature(): ' + f) # Check if adding a feature removes the indices for i in range(2): @@ -1719,14 +1491,10 @@ def ogr_shape_40(): feat.SetFID(1) for f in indexfiles: - if not os.path.exists(os.path.join('tmp', f)): - print('CreateFeature(): ' + f) - return 'fail' + assert os.path.exists(os.path.join('tmp', f)), ('CreateFeature(): ' + f) gdaltest.shape_lyr.CreateFeature(feat) for f in indexfiles: - if os.path.exists(os.path.join('tmp', f)): - print('CreateFeature(): ' + f) - return 'fail' + assert not os.path.exists(os.path.join('tmp', f)), ('CreateFeature(): ' + f) # Check if deleting a feature removes the indices for i in range(2): @@ -1737,28 +1505,21 @@ def ogr_shape_40(): gdaltest.shape_ds.ExecuteSQL('CREATE SPATIAL INDEX ON gjpoint') for f in indexfiles: - if not os.path.exists(os.path.join('tmp', f)): - print('DeleteFeature(): ' + f) - return 'fail' - if gdaltest.shape_lyr.DeleteFeature(0) != 0: - gdaltest.post_reason('DeleteFeature failed.') - return 'fail' + assert os.path.exists(os.path.join('tmp', f)), ('DeleteFeature(): ' + f) + assert gdaltest.shape_lyr.DeleteFeature(0) == 0, 'DeleteFeature failed.' for f in indexfiles: - if os.path.exists(os.path.join('tmp', f)): - print('DeleteFeature(): ' + f) - return 'fail' - - return 'success' + assert not os.path.exists(os.path.join('tmp', f)), ('DeleteFeature(): ' + f) + ############################################################################### # Run test_ogrsf -def ogr_shape_41(): +def test_ogr_shape_41(): import test_cli_utilities if test_cli_utilities.get_test_ogrsf_path() is None: - return 'skip' + pytest.skip() shutil.copy('data/poly.shp', 'tmp/poly.shp') shutil.copy('data/poly.shx', 'tmp/poly.shx') @@ -1770,21 +1531,17 @@ def ogr_shape_41(): os.remove('tmp/poly.shx') os.remove('tmp/poly.dbf') - if ret.find('INFO') == -1 or ret.find('ERROR') != -1: - print(ret) - return 'fail' - - return 'success' + assert ret.find('INFO') != -1 and ret.find('ERROR') == -1 ############################################################################### # Run test_ogrsf with -sql -def ogr_shape_42(): +def test_ogr_shape_42(): import test_cli_utilities if test_cli_utilities.get_test_ogrsf_path() is None: - return 'skip' + pytest.skip() shutil.copy('data/poly.shp', 'tmp/poly.shp') shutil.copy('data/poly.shx', 'tmp/poly.shx') @@ -1796,46 +1553,34 @@ def ogr_shape_42(): os.remove('tmp/poly.shx') os.remove('tmp/poly.dbf') - if ret.find('INFO') == -1 or ret.find('ERROR') != -1: - print(ret) - return 'fail' - - return 'success' + assert ret.find('INFO') != -1 and ret.find('ERROR') == -1 ############################################################################### # Test /vsizip//vsicurl/ -def ogr_shape_43(): +def test_ogr_shape_43(): drv = gdal.GetDriverByName('HTTP') if drv is None: - return 'skip' + pytest.skip() conn = gdaltest.gdalurlopen('https://raw.githubusercontent.com/OSGeo/gdal/master/autotest/ogr/data/poly.zip') if conn is None: - print('cannot open URL') - return 'skip' + pytest.skip('cannot open URL') conn.close() ds = ogr.Open('/vsizip//vsicurl/https://raw.githubusercontent.com/OSGeo/gdal/master/autotest/ogr/data/poly.zip') - if ds is None: - return 'fail' + assert ds is not None lyr = ds.GetLayer(0) srs = lyr.GetSpatialRef() wkt = srs.ExportToWkt() - if wkt.find('OSGB') == -1: - gdaltest.post_reason('did not get expected SRS') - return 'fail' + assert wkt.find('OSGB') != -1, 'did not get expected SRS' f = lyr.GetNextFeature() - if f is None: - gdaltest.post_reason('did not get expected feature') - return 'fail' - - return 'success' + assert f is not None, 'did not get expected feature' ############################################################################### # Test /vsicurl/ on a directory @@ -1845,38 +1590,30 @@ def ogr_shape_44_DISABLED(): drv = gdal.GetDriverByName('HTTP') if drv is None: - return 'skip' + pytest.skip() conn = gdaltest.gdalurlopen('https://raw.githubusercontent.com/OSGeo/gdal/master/autotest/ogr/data/poly.zip') if conn is None: - print('cannot open URL') - return 'skip' + pytest.skip('cannot open URL') conn.close() ds = ogr.Open('/vsicurl/https://raw.githubusercontent.com/OSGeo/gdal/master/autotest/ogr/data/testshp') - if ds is None: - return 'fail' + assert ds is not None lyr = ds.GetLayer(0) srs = lyr.GetSpatialRef() wkt = srs.ExportToWkt() - if wkt.find('OSGB') == -1: - gdaltest.post_reason('did not get expected SRS') - return 'fail' + assert wkt.find('OSGB') != -1, 'did not get expected SRS' f = lyr.GetNextFeature() - if f is None: - gdaltest.post_reason('did not get expected feature') - return 'fail' - - return 'success' + assert f is not None, 'did not get expected feature' ############################################################################### # Test ignored fields works ok on a shapefile. -def ogr_shape_45(): +def test_ogr_shape_45(): shp_ds = ogr.Open('data/poly.shp') shp_layer = shp_ds.GetLayer(0) @@ -1884,64 +1621,41 @@ def ogr_shape_45(): feat = shp_layer.GetNextFeature() - if feat.IsFieldSet('AREA'): - gdaltest.post_reason('got area despite request to ignore it.') - return 'fail' + assert not feat.IsFieldSet('AREA'), 'got area despite request to ignore it.' - if feat.GetFieldAsInteger('EAS_ID') != 168: - gdaltest.post_reason('missing or wrong eas_id') - return 'fail' + assert feat.GetFieldAsInteger('EAS_ID') == 168, 'missing or wrong eas_id' wkt = 'POLYGON ((479819.84375 4765180.5,479690.1875 4765259.5,479647.0 4765369.5,479730.375 4765400.5,480039.03125 4765539.5,480035.34375 4765558.5,480159.78125 4765610.5,480202.28125 4765482.0,480365.0 4765015.5,480389.6875 4764950.0,480133.96875 4764856.5,480080.28125 4764979.5,480082.96875 4765049.5,480088.8125 4765139.5,480059.90625 4765239.5,480019.71875 4765319.5,479980.21875 4765409.5,479909.875 4765370.0,479859.875 4765270.0,479819.84375 4765180.5))' - if ogrtest.check_feature_geometry(feat, wkt, - max_error=0.00000001) != 0: - return 'fail' + assert (ogrtest.check_feature_geometry(feat, wkt, + max_error=0.00000001) == 0) fd = shp_layer.GetLayerDefn() fld = fd.GetFieldDefn(0) # area - if not fld.IsIgnored(): - gdaltest.post_reason('AREA unexpectedly not marked as ignored.') - return 'fail' + assert fld.IsIgnored(), 'AREA unexpectedly not marked as ignored.' fld = fd.GetFieldDefn(1) # eas_id - if fld.IsIgnored(): - gdaltest.post_reason('EASI unexpectedly marked as ignored.') - return 'fail' + assert not fld.IsIgnored(), 'EASI unexpectedly marked as ignored.' - if fd.IsGeometryIgnored(): - gdaltest.post_reason('geometry unexpectedly ignored.') - return 'fail' + assert not fd.IsGeometryIgnored(), 'geometry unexpectedly ignored.' - if fd.IsStyleIgnored(): - gdaltest.post_reason('style unexpectedly ignored.') - return 'fail' + assert not fd.IsStyleIgnored(), 'style unexpectedly ignored.' fd.SetGeometryIgnored(1) - if not fd.IsGeometryIgnored(): - gdaltest.post_reason('geometry unexpectedly not ignored.') - return 'fail' + assert fd.IsGeometryIgnored(), 'geometry unexpectedly not ignored.' feat = shp_layer.GetNextFeature() - if feat.GetGeometryRef() is not None: - gdaltest.post_reason('Unexpectedly got a geometry on feature 2.') - return 'fail' + assert feat.GetGeometryRef() is None, 'Unexpectedly got a geometry on feature 2.' - if feat.IsFieldSet('AREA'): - gdaltest.post_reason('got area despite request to ignore it.') - return 'fail' + assert not feat.IsFieldSet('AREA'), 'got area despite request to ignore it.' - if feat.GetFieldAsInteger('EAS_ID') != 179: - gdaltest.post_reason('missing or wrong eas_id') - return 'fail' + assert feat.GetFieldAsInteger('EAS_ID') == 179, 'missing or wrong eas_id' feat = None shp_layer = None shp_ds = None - return 'success' - ############################################################################### # This is a very weird use case : the user creates/open a datasource # made of a single shapefile 'foo.shp' and wants to add a new layer @@ -1949,7 +1663,7 @@ def ogr_shape_45(): # directory as 'foo.shp' -def ogr_shape_46(): +def test_ogr_shape_46(): ds = ogr.GetDriverByName('ESRI Shapefile').CreateDataSource('/vsimem/ogr_shape_46.shp') ds.CreateLayer('you_can_put_here_what_you_want_i_dont_care') @@ -1957,45 +1671,37 @@ def ogr_shape_46(): ds = None ds = ogr.Open('/vsimem/ogr_shape_46.shp') - if ds.GetLayerCount() != 1: - return 'fail' + assert ds.GetLayerCount() == 1 ds = None ds = ogr.Open('/vsimem/this_one_i_care_46.shp') - if ds.GetLayerCount() != 1: - return 'fail' + assert ds.GetLayerCount() == 1 ds = None - return 'success' - ############################################################################### # Test that we can open a symlink whose pointed filename isn't a real # file, but a filename that OGR recognizes -def ogr_shape_47(): +def test_ogr_shape_47(): if not gdaltest.support_symlink(): - return 'skip' + pytest.skip() gdal.Unlink('tmp/poly.zip') os.symlink('/vsizip/data/poly.zip', 'tmp/poly.zip') ds = ogr.Open('tmp/poly.zip') - if ds is None: - gdaltest.post_reason('tmp/polyzip symlink does not open.') - return 'fail' + assert ds is not None, 'tmp/polyzip symlink does not open.' ds = None os.remove('tmp/poly.zip') - return 'success' - ############################################################################### # Test RECOMPUTE EXTENT ON (#4027) -def ogr_shape_48(): +def test_ogr_shape_48(): ds = ogr.GetDriverByName('ESRI Shapefile').CreateDataSource('/vsimem/ogr_shape_48.shp') lyr = ds.CreateLayer('ogr_shape_48') @@ -2007,24 +1713,21 @@ def ogr_shape_48(): lyr.SetFeature(feat) extent = lyr.GetExtent() if extent != (1, 3, 2, 4): - gdaltest.post_reason('did not get expected extent (1)') print(lyr.GetExtent()) - return 'fail' + pytest.fail('did not get expected extent (1)') ds.ExecuteSQL('RECOMPUTE EXTENT ON ogr_shape_48') extent = lyr.GetExtent() if extent != (3, 3, 4, 4): - gdaltest.post_reason('did not get expected extent (2)') print(lyr.GetExtent()) - return 'fail' + pytest.fail('did not get expected extent (2)') ds = None ds = ogr.Open('/vsimem/ogr_shape_48.shp') lyr = ds.GetLayer(0) extent = lyr.GetExtent() if extent != (3, 3, 4, 4): - gdaltest.post_reason('did not get expected extent (3)') print(lyr.GetExtent()) - return 'fail' + pytest.fail('did not get expected extent (3)') ds = None ogr.GetDriverByName('ESRI Shapefile').DeleteDataSource('/vsimem/ogr_shape_48.shp') @@ -2040,9 +1743,8 @@ def ogr_shape_48(): ds.ExecuteSQL('RECOMPUTE EXTENT ON ogr_shape_48') extent = lyr.GetExtent() if extent != (0, 1, 0, 1): - gdaltest.post_reason('did not get expected extent (4)') print(lyr.GetExtent()) - return 'fail' + pytest.fail('did not get expected extent (4)') ds = None ogr.GetDriverByName('ESRI Shapefile').DeleteDataSource('/vsimem/ogr_shape_48.shp') @@ -2058,19 +1760,16 @@ def ogr_shape_48(): # FIXME: when we have a GetExtent3D extent = lyr.GetExtent() if extent != (0, 1, 0, 1): - gdaltest.post_reason('did not get expected extent (4)') print(lyr.GetExtent()) - return 'fail' + pytest.fail('did not get expected extent (4)') ds = None ogr.GetDriverByName('ESRI Shapefile').DeleteDataSource('/vsimem/ogr_shape_48.shp') - return 'success' - ############################################################################### # Test that we can read at an LDID/87 file and recode to UTF-8. -def ogr_shape_49(): +def test_ogr_shape_49(): ds = ogr.Open('data/facility_surface_dd.dbf') lyr = ds.GetLayer(0) @@ -2086,32 +1785,26 @@ def ogr_shape_49(): exec("gdaltest.exp_name = u'OSEBERG S\u00D8R'") gdaltest.exp_name = gdaltest.exp_name.encode('utf-8') - if name != gdaltest.exp_name: - gdaltest.post_reason('Did not get expected name, encoding problems?') - return 'fail' - - return 'success' + assert name == gdaltest.exp_name, 'Did not get expected name, encoding problems?' ############################################################################### # Test that we can read encoded field names -def ogr_shape_50(): +def test_ogr_shape_50(): ds = ogr.Open('data/chinese.dbf') if ds is None: - return 'skip' + pytest.skip() lyr = ds.GetLayer(0) reconv_possible = lyr.TestCapability(ogr.OLCStringsAsUTF8) == 1 if gdal.GetLastErrorMsg().find('Recode from CP936 to UTF-8 not supported, treated as ISO-8859-1 to UTF-8.') != -1: - if reconv_possible: - gdaltest.post_reason('Recode failed, but TestCapability(OLCStringsAsUTF8) returns TRUE') - return 'fail' + assert not reconv_possible, \ + 'Recode failed, but TestCapability(OLCStringsAsUTF8) returns TRUE' - gdaltest.post_reason('skipping test: iconv support needed') - return 'skip' + pytest.skip('skipping test: iconv support needed') # Setup the utf-8 string. if sys.version_info >= (3, 0, 0): @@ -2120,25 +1813,19 @@ def ogr_shape_50(): exec("gdaltest.fieldname = u'\u4e2d\u56fd'") gdaltest.fieldname = gdaltest.fieldname.encode('utf-8') - if lyr.GetLayerDefn().GetFieldIndex(gdaltest.fieldname) != 0: - print(lyr.GetLayerDefn().GetFieldDefn(0).GetNameRef()) - return 'fail' + assert lyr.GetLayerDefn().GetFieldIndex(gdaltest.fieldname) == 0, \ + lyr.GetLayerDefn().GetFieldDefn(0).GetNameRef() - if not reconv_possible: - gdaltest.post_reason('TestCapability(OLCStringsAsUTF8) should return TRUE') - return 'fail' - - return 'success' + assert reconv_possible, 'TestCapability(OLCStringsAsUTF8) should return TRUE' ############################################################################### # Test that we can add a field when there's no dbf file initially -def ogr_shape_51(): +def test_ogr_shape_51(): if int(gdal.VersionInfo('VERSION_NUM')) < 1900: - gdaltest.post_reason('would crash') - return 'skip' + pytest.skip('would crash') ds = ogr.GetDriverByName('ESRI Shapefile').CreateDataSource('/vsimem/ogr_shape_51.shp') lyr = ds.CreateLayer('ogr_shape_51') @@ -2165,23 +1852,15 @@ def ogr_shape_51(): ogr.GetDriverByName('ESRI Shapefile').DeleteDataSource('/vsimem/ogr_shape_51.shp') - if field_count != 1: - gdaltest.post_reason('did not get expected field count') - print(field_count) - return 'fail' - - if value != 'bar': - gdaltest.post_reason('did not get expected value') - print(value) - return 'fail' + assert field_count == 1, 'did not get expected field count' - return 'success' + assert value == 'bar', 'did not get expected value' ############################################################################### # Test fix for #3356 -def ogr_shape_52(): +def test_ogr_shape_52(): expected_geom = ogr.CreateGeometryFromWkt('MULTIPOLYGON (((175.524709766699999 -40.17203475,175.524757883299998 -40.172050566700001,175.52480505 -40.1720663,175.524858766699992 -40.172091433299997,175.524913916700001 -40.172112966699999,175.524966049999989 -40.172136933300003,175.525030633299991 -40.17216185,175.5250873 -40.17218215,175.52515168330001 -40.1722011,175.525217666700001 -40.172221216700002,175.525269416700013 -40.172234466699997,175.5253165 -40.1722478,175.52535415 -40.1722577667,175.52538385 -40.17226365,175.525436816699994 -40.1722814333,175.525507016700004 -40.17229905,175.525594783299994 -40.172322033299999,175.525669933300009 -40.172339533299997,175.52574 -40.17235335,175.525807566699996 -40.1723672,175.52585005 -40.17237395,175.52588115 -40.172378683300003,175.525969816700012 -40.172388633300002,175.526057266700008 -40.1724020833,175.52723455 -40.17253515,175.527275583299996 -40.1725388,175.527324533300003 -40.17254675,175.527394866700007 -40.172552766700001,175.527473066699997 -40.172561616700001,175.527576666700014 -40.172572916699998,175.527678333300003 -40.172584266699999,175.527787883299993 -40.17259845,175.52789345 -40.172609716700002,175.527953933300012 -40.17261295,175.528028083300001 -40.1726174,175.52809835 -40.1726219333,175.528151650000012 -40.172625833300003,175.528190349999988 -40.17262725,175.528230900000011 -40.172631183299998,175.5282776 -40.1726338,175.528322800000012 -40.172637633299999,175.5283648 -40.17263915,175.5284115 -40.172641766700004,175.528452133299993 -40.17264435,175.528492133300006 -40.172646033299998,175.52856465 -40.17264805,175.528621733300014 -40.1726492,175.52868035 -40.172650333299998,175.528751333299994 -40.172652383299997,175.528814566699992 -40.1726534,175.528883933299994 -40.172653116699998,175.528939383300013 -40.17265195,175.529002566700001 -40.1726518,175.529070350000012 -40.172650366699997,175.529136633299998 -40.17265015,175.529193616700013 -40.17264895,175.529250616700011 -40.172647733300003,175.529313800000011 -40.172647583299998,175.529376783299995 -40.172647016699997,175.52895773329999 -40.172694633299997,175.528450866700013 -40.172752216699998,175.52835635 -40.172753466700001,175.52741181670001 -40.1727757333,175.52685245 -40.172532333299998,175.52627245 -40.172501266700003,175.5262405167 -40.172502816700003,175.5258356 -40.172522816700003,175.5256125 -40.172533833300001,175.525424433300003 -40.172543116699998,175.524834133300004 -40.1725533,175.524739033299994 -40.172414983300001,175.5247128 -40.17207405,175.524709766699999 -40.17203475)),((175.531267916699989 -40.17286525,175.5312654 -40.172863283300003,175.531252849999987 -40.172853516700002,175.531054566699993 -40.172822366699997,175.530193283300008 -40.172687333299997,175.529890266699994 -40.1726398,175.529916116700008 -40.172639383300002,175.529972483300014 -40.172639216699999,175.53002885 -40.1726398,175.530085183300002 -40.17264115,175.530141500000013 -40.17264325,175.530197733300014 -40.172646133299999,175.530253916699991 -40.172649766699998,175.530309983299986 -40.172654166699999,175.53036595 -40.172659333299997,175.5304218 -40.17266525,175.53047748329999 -40.172671916699997,175.530533016699991 -40.17267935,175.5305883833 -40.1726875333,175.530643533300008 -40.172696466700003,175.530722333299991 -40.172710633299999,175.530800633300004 -40.1727263167,175.5308541 -40.17273795,175.5309073 -40.1727503,175.530960216700009 -40.172763366700003,175.531012816700013 -40.172777133300002,175.5310651 -40.1727916,175.53111705 -40.172806766699999,175.531168650000012 -40.172822633300001,175.531219883299997 -40.172839183299999,175.531270733300005 -40.1728564,175.531267916699989 -40.17286525)))') @@ -2189,10 +1868,9 @@ def ogr_shape_52(): lyr = ds.GetLayer(0) feat = lyr.GetNextFeature() - if ogrtest.check_feature_geometry(feat, expected_geom, - max_error=0.000000001) != 0: - gdaltest.post_reason('failed reading geom') - return 'fail' + assert (ogrtest.check_feature_geometry(feat, expected_geom, + max_error=0.000000001) == 0), \ + 'failed reading geom' ds = None @@ -2207,29 +1885,24 @@ def ogr_shape_52(): lyr = ds.GetLayer(0) feat = lyr.GetNextFeature() - if ogrtest.check_feature_geometry(feat, expected_geom, - max_error=0.000000001) != 0: - gdaltest.post_reason('failed writing and reading back geom') - return 'fail' + assert (ogrtest.check_feature_geometry(feat, expected_geom, + max_error=0.000000001) == 0), \ + 'failed writing and reading back geom' ds = None - return 'success' - ############################################################################### # Test various expected error cases -def ogr_shape_53(): +def test_ogr_shape_53(): ds = ogr.GetDriverByName('ESRI Shapefile').CreateDataSource('/vsimem/ogr_shape_53.shp') lyr = ds.CreateLayer('ogr_shape_53') # Test ReorderFields() when there are no fields ret = lyr.ReorderFields([]) - if ret != 0: - gdaltest.post_reason('failed') - return 'fail' + assert ret == 0 # Test REPACK when there are no features gdal.ErrorReset() @@ -2237,9 +1910,7 @@ def ogr_shape_53(): ret = ds.ExecuteSQL("REPACK ogr_shape_53") gdal.PopErrorHandler() # Should work without any error - if gdal.GetLastErrorMsg() != '': - gdaltest.post_reason('failed') - return 'fail' + assert gdal.GetLastErrorMsg() == '' # Create a field fd = ogr.FieldDefn("foo", ogr.OFTString) @@ -2250,9 +1921,7 @@ def ogr_shape_53(): gdal.PushErrorHandler('CPLQuietErrorHandler') feat = lyr.GetFeature(-1) gdal.PopErrorHandler() - if feat is not None or gdal.GetLastErrorMsg() == '': - gdaltest.post_reason('failed') - return 'fail' + assert feat is None and gdal.GetLastErrorMsg() != '' # SetFeature() on a invalid FID gdal.ErrorReset() @@ -2261,9 +1930,7 @@ def ogr_shape_53(): ret = lyr.SetFeature(feat) feat = None gdal.PopErrorHandler() - if ret == 0: - gdaltest.post_reason('failed') - return 'fail' + assert ret != 0 # SetFeature() on a invalid FID gdal.ErrorReset() @@ -2273,54 +1940,42 @@ def ogr_shape_53(): ret = lyr.SetFeature(feat) feat = None gdal.PopErrorHandler() - if ret == 0: - gdaltest.post_reason('failed') - return 'fail' + assert ret != 0 # DeleteFeature() on a invalid FID gdal.ErrorReset() gdal.PushErrorHandler('CPLQuietErrorHandler') ret = lyr.DeleteFeature(-1) gdal.PopErrorHandler() - if ret == 0: - gdaltest.post_reason('failed') - return 'fail' + assert ret != 0 feat = ogr.Feature(lyr.GetLayerDefn()) lyr.CreateFeature(feat) feat = None ret = lyr.DeleteFeature(0) - if ret != 0: - gdaltest.post_reason('failed') - return 'fail' + assert ret == 0 # Try deleting an already deleted feature gdal.ErrorReset() gdal.PushErrorHandler('CPLQuietErrorHandler') ret = lyr.DeleteFeature(0) gdal.PopErrorHandler() - if ret == 0: - gdaltest.post_reason('failed') - return 'fail' + assert ret != 0 # Test DeleteField() on a invalid index gdal.ErrorReset() gdal.PushErrorHandler('CPLQuietErrorHandler') ret = lyr.DeleteField(-1) gdal.PopErrorHandler() - if ret == 0 or gdal.GetLastErrorMsg() == '': - gdaltest.post_reason('failed') - return 'fail' + assert not (ret == 0 or gdal.GetLastErrorMsg() == '') # Test ReorderFields() with invalid permutation gdal.ErrorReset() gdal.PushErrorHandler('CPLQuietErrorHandler') ret = lyr.ReorderFields([1]) gdal.PopErrorHandler() - if ret == 0 or gdal.GetLastErrorMsg() == '': - gdaltest.post_reason('failed') - return 'fail' + assert not (ret == 0 or gdal.GetLastErrorMsg() == '') # Test AlterFieldDefn() on a invalid index gdal.ErrorReset() @@ -2328,9 +1983,7 @@ def ogr_shape_53(): fd = ogr.FieldDefn("foo2", ogr.OFTString) ret = lyr.AlterFieldDefn(-1, fd, 0) gdal.PopErrorHandler() - if ret == 0 or gdal.GetLastErrorMsg() == '': - gdaltest.post_reason('failed') - return 'fail' + assert not (ret == 0 or gdal.GetLastErrorMsg() == '') # Test AlterFieldDefn() when attempting to convert from OFTString to something else gdal.ErrorReset() @@ -2338,18 +1991,14 @@ def ogr_shape_53(): fd = ogr.FieldDefn("foo", ogr.OFTInteger) ret = lyr.AlterFieldDefn(0, fd, ogr.ALTER_TYPE_FLAG) gdal.PopErrorHandler() - if ret == 0 or gdal.GetLastErrorMsg() == '': - gdaltest.post_reason('failed') - return 'fail' + assert not (ret == 0 or gdal.GetLastErrorMsg() == '') # Test DROP SPATIAL INDEX ON layer without index gdal.ErrorReset() gdal.PushErrorHandler('CPLQuietErrorHandler') ret = ds.ExecuteSQL("DROP SPATIAL INDEX ON ogr_shape_53") gdal.PopErrorHandler() - if gdal.GetLastErrorMsg() == '': - gdaltest.post_reason('failed') - return 'fail' + assert gdal.GetLastErrorMsg() != '' # Re-create a feature feat = ogr.Feature(lyr.GetLayerDefn()) @@ -2363,24 +2012,12 @@ def ogr_shape_53(): ds = ogr.Open('/vsimem/ogr_shape_53.shp') lyr = ds.GetLayer(0) - if lyr.TestCapability(ogr.OLCSequentialWrite) != 0: - gdaltest.post_reason('failed') - return 'fail' - if lyr.TestCapability(ogr.OLCDeleteFeature) != 0: - gdaltest.post_reason('failed') - return 'fail' - if lyr.TestCapability(ogr.OLCCreateField) != 0: - gdaltest.post_reason('failed') - return 'fail' - if lyr.TestCapability(ogr.OLCDeleteField) != 0: - gdaltest.post_reason('failed') - return 'fail' - if lyr.TestCapability(ogr.OLCReorderFields) != 0: - gdaltest.post_reason('failed') - return 'fail' - if lyr.TestCapability(ogr.OLCAlterFieldDefn) != 0: - gdaltest.post_reason('failed') - return 'fail' + assert lyr.TestCapability(ogr.OLCSequentialWrite) == 0 + assert lyr.TestCapability(ogr.OLCDeleteFeature) == 0 + assert lyr.TestCapability(ogr.OLCCreateField) == 0 + assert lyr.TestCapability(ogr.OLCDeleteField) == 0 + assert lyr.TestCapability(ogr.OLCReorderFields) == 0 + assert lyr.TestCapability(ogr.OLCAlterFieldDefn) == 0 # Test CreateField() fd = ogr.FieldDefn("bar", ogr.OFTString) @@ -2389,27 +2026,21 @@ def ogr_shape_53(): gdal.PushErrorHandler('CPLQuietErrorHandler') ret = lyr.CreateField(fd) gdal.PopErrorHandler() - if ret == 0 or gdal.GetLastErrorMsg() == '': - gdaltest.post_reason('failed') - return 'fail' + assert not (ret == 0 or gdal.GetLastErrorMsg() == '') # Test ReorderFields() gdal.ErrorReset() gdal.PushErrorHandler('CPLQuietErrorHandler') ret = lyr.ReorderFields([0]) gdal.PopErrorHandler() - if ret == 0 or gdal.GetLastErrorMsg() == '': - gdaltest.post_reason('failed') - return 'fail' + assert not (ret == 0 or gdal.GetLastErrorMsg() == '') # Test DeleteField() gdal.ErrorReset() gdal.PushErrorHandler('CPLQuietErrorHandler') ret = lyr.DeleteField(0) gdal.PopErrorHandler() - if ret == 0 or gdal.GetLastErrorMsg() == '': - gdaltest.post_reason('failed') - return 'fail' + assert not (ret == 0 or gdal.GetLastErrorMsg() == '') # Test AlterFieldDefn() gdal.ErrorReset() @@ -2417,9 +2048,7 @@ def ogr_shape_53(): fd = ogr.FieldDefn("foo2", ogr.OFTString) ret = lyr.AlterFieldDefn(0, fd, 0) gdal.PopErrorHandler() - if ret == 0 or gdal.GetLastErrorMsg() == '': - gdaltest.post_reason('failed') - return 'fail' + assert not (ret == 0 or gdal.GetLastErrorMsg() == '') # Test CreateFeature() feat = ogr.Feature(lyr.GetLayerDefn()) @@ -2428,18 +2057,14 @@ def ogr_shape_53(): gdal.PushErrorHandler('CPLQuietErrorHandler') ret = lyr.CreateFeature(feat) gdal.PopErrorHandler() - if ret == 0 or gdal.GetLastErrorMsg() == '': - gdaltest.post_reason('failed') - return 'fail' + assert not (ret == 0 or gdal.GetLastErrorMsg() == '') # Test DeleteFeature() gdal.ErrorReset() gdal.PushErrorHandler('CPLQuietErrorHandler') ret = lyr.DeleteFeature(0) gdal.PopErrorHandler() - if ret == 0 or gdal.GetLastErrorMsg() == '': - gdaltest.post_reason('failed') - return 'fail' + assert not (ret == 0 or gdal.GetLastErrorMsg() == '') # Test SetFeature() feat = lyr.GetNextFeature() @@ -2448,27 +2073,21 @@ def ogr_shape_53(): gdal.PushErrorHandler('CPLQuietErrorHandler') ret = lyr.SetFeature(feat) gdal.PopErrorHandler() - if ret == 0 or gdal.GetLastErrorMsg() == '': - gdaltest.post_reason('failed') - return 'fail' + assert not (ret == 0 or gdal.GetLastErrorMsg() == '') # Test REPACK gdal.ErrorReset() gdal.PushErrorHandler('CPLQuietErrorHandler') ret = ds.ExecuteSQL("REPACK ogr_shape_53") gdal.PopErrorHandler() - if gdal.GetLastErrorMsg() == '': - gdaltest.post_reason('failed') - return 'fail' + assert gdal.GetLastErrorMsg() != '' # Test RECOMPUTE EXTENT ON gdal.ErrorReset() gdal.PushErrorHandler('CPLQuietErrorHandler') ret = ds.ExecuteSQL("RECOMPUTE EXTENT ON ogr_shape_53") gdal.PopErrorHandler() - if gdal.GetLastErrorMsg() == '': - gdaltest.post_reason('failed') - return 'fail' + assert gdal.GetLastErrorMsg() != '' feat = None lyr = None @@ -2483,9 +2102,7 @@ def ogr_shape_53(): gdal.PushErrorHandler('CPLQuietErrorHandler') ret = lyr.DeleteFeature(0) gdal.PopErrorHandler() - if ret == 0 or gdal.GetLastErrorMsg() == '': - gdaltest.post_reason('failed') - return 'fail' + assert not (ret == 0 or gdal.GetLastErrorMsg() == '') # Test REPACK ds.ExecuteSQL("REPACK ogr_shape_53") @@ -2506,15 +2123,11 @@ def ogr_shape_53(): gdal.PushErrorHandler('CPLQuietErrorHandler') ret = ds.ExecuteSQL("RECOMPUTE EXTENT ON ogr_shape_53") gdal.PopErrorHandler() - if gdal.GetLastErrorMsg() == '': - gdaltest.post_reason('failed') - return 'fail' + assert gdal.GetLastErrorMsg() != '' lyr = None ds = None - return 'success' - ############################################################################### # Test accessing a shape datasource with hundreds of layers (#4306) @@ -2532,27 +2145,20 @@ def ogr_shape_54_create_layer(ds, layer_index): def ogr_shape_54_test_layer(ds, layer_index): lyr = ds.GetLayerByName('layer%03d' % layer_index) - if lyr is None: - gdaltest.post_reason('failed for layer %d' % layer_index) - return 'fail' + assert lyr is not None, ('failed for layer %d' % layer_index) lyr.ResetReading() feat = lyr.GetNextFeature() - if feat is None: - gdaltest.post_reason('failed for layer %d' % layer_index) - return 'fail' - if feat.GetField(0) != 'val%d' % layer_index: - gdaltest.post_reason('failed for layer %d' % layer_index) - return 'fail' + assert feat is not None, ('failed for layer %d' % layer_index) + assert feat.GetField(0) == 'val%d' % layer_index, \ + ('failed for layer %d' % layer_index) if (layer_index % 2) == 0: - if feat.GetGeometryRef() is None or \ - feat.GetGeometryRef().ExportToWkt() != 'POINT (%d %d)' % (layer_index, layer_index + 1): - gdaltest.post_reason('failed for layer %d' % layer_index) - return 'fail' - - return 'success' + assert (feat.GetGeometryRef() is not None and \ + feat.GetGeometryRef().ExportToWkt() == 'POINT (%d %d)' % (layer_index, layer_index + 1)), \ + ('failed for layer %d' % layer_index) + -def ogr_shape_54(): +def test_ogr_shape_54(): shape_drv = ogr.GetDriverByName('ESRI Shapefile') ds_name = '/vsimem/ogr_shape_54' @@ -2570,32 +2176,16 @@ def ogr_shape_54(): # Test access to the N layers in sequence ds = ogr.Open(ds_name) for i in range(N): - ret = ogr_shape_54_test_layer(ds, i) - if ret != 'success': - return ret + ogr_shape_54_test_layer(ds, i) # Now some 'random' access - ret = ogr_shape_54_test_layer(ds, N - 1 - LRUListSize) - if ret != 'success': - return ret - ret = ogr_shape_54_test_layer(ds, N - LRUListSize / 2) - if ret != 'success': - return ret - ret = ogr_shape_54_test_layer(ds, N - LRUListSize / 4) - if ret != 'success': - return ret - ret = ogr_shape_54_test_layer(ds, 0) - if ret != 'success': - return ret - ret = ogr_shape_54_test_layer(ds, 0) - if ret != 'success': - return ret - ret = ogr_shape_54_test_layer(ds, 2) - if ret != 'success': - return ret - ret = ogr_shape_54_test_layer(ds, 1) - if ret != 'success': - return ret + ogr_shape_54_test_layer(ds, N - 1 - LRUListSize) + ogr_shape_54_test_layer(ds, N - LRUListSize / 2) + ogr_shape_54_test_layer(ds, N - LRUListSize / 4) + ogr_shape_54_test_layer(ds, 0) + ogr_shape_54_test_layer(ds, 0) + ogr_shape_54_test_layer(ds, 2) + ogr_shape_54_test_layer(ds, 1) ds = None # Test adding a new layer @@ -2605,31 +2195,21 @@ def ogr_shape_54(): # Test accessing the new layer ds = ogr.Open(ds_name) - ret = ogr_shape_54_test_layer(ds, N) - if ret != 'success': - return ret + ogr_shape_54_test_layer(ds, N) ds = None # Test deleting layers ds = ogr.Open(ds_name, update=1) for i in range(N): - ret = ogr_shape_54_test_layer(ds, i) - if ret != 'success': - return ret + ogr_shape_54_test_layer(ds, i) for i in range(N - LRUListSize + 1, N): ds.ExecuteSQL('DROP TABLE layer%03d' % i) - ret = ogr_shape_54_test_layer(ds, N - LRUListSize) - if ret != 'success': - return ret + ogr_shape_54_test_layer(ds, N - LRUListSize) ogr_shape_54_create_layer(ds, N + 2) for i in range(0, N - LRUListSize + 1): ds.ExecuteSQL('DROP TABLE layer%03d' % i) - ret = ogr_shape_54_test_layer(ds, N) - if ret != 'success': - return ret - ret = ogr_shape_54_test_layer(ds, N + 2) - if ret != 'success': - return ret + ogr_shape_54_test_layer(ds, N) + ogr_shape_54_test_layer(ds, N + 2) ds = None # Destroy and recreate datasource @@ -2655,9 +2235,7 @@ def ogr_shape_54(): lyr.ResetReading() lyr.GetNextFeature() gdal.PopErrorHandler() - if gdal.GetLastErrorMsg() == '': - gdaltest.post_reason('failed') - return 'fail' + assert gdal.GetLastErrorMsg() != '' gdal.ErrorReset() ideletedlayer = 1 @@ -2675,13 +2253,11 @@ def ogr_shape_54(): ds = None - return 'success' - ############################################################################### # Test that we cannot add more fields that the maximum allowed -def ogr_shape_55(): +def test_ogr_shape_55(): shape_drv = ogr.GetDriverByName('ESRI Shapefile') ds_name = '/vsimem/ogr_shape_55' ds = shape_drv.CreateDataSource(ds_name) @@ -2696,20 +2272,15 @@ def ogr_shape_55(): ret = lyr.CreateField(ogr.FieldDefn('foo%d' % i, ogr.OFTInteger)) if i == 255: gdal.PopErrorHandler() - if gdal.GetLastErrorMsg() == '': - gdaltest.post_reason('expecting a warning for 256th field added') - return 'fail' - if ret != 0: - gdaltest.post_reason('failed creating field foo%d' % i) - return 'fail' + assert gdal.GetLastErrorMsg() != '', \ + 'expecting a warning for 256th field added' + assert ret == 0, ('failed creating field foo%d' % i) i = max_field_count gdal.PushErrorHandler('CPLQuietErrorHandler') ret = lyr.CreateField(ogr.FieldDefn('foo%d' % i, ogr.OFTInteger)) gdal.PopErrorHandler() - if ret == 0: - gdaltest.post_reason('should have failed creating field foo%d' % i) - return 'fail' + assert ret != 0, ('should have failed creating field foo%d' % i) feat = ogr.Feature(lyr.GetLayerDefn()) for i in range(max_field_count): @@ -2723,13 +2294,11 @@ def ogr_shape_55(): ds = None - return 'success' - ############################################################################### # Test that we cannot add more fields that the maximum allowed record length -def ogr_shape_56(): +def test_ogr_shape_56(): shape_drv = ogr.GetDriverByName('ESRI Shapefile') ds_name = '/vsimem/ogr_shape_56' ds = shape_drv.CreateDataSource(ds_name) @@ -2744,20 +2313,15 @@ def ogr_shape_56(): ret = lyr.CreateField(ogr.FieldDefn('foo%d' % i, ogr.OFTString)) if i == 255: gdal.PopErrorHandler() - if gdal.GetLastErrorMsg() == '': - gdaltest.post_reason('expecting a warning for 256th field added') - return 'fail' - if ret != 0: - gdaltest.post_reason('failed creating field foo%d' % i) - return 'fail' + assert gdal.GetLastErrorMsg() != '', \ + 'expecting a warning for 256th field added' + assert ret == 0, ('failed creating field foo%d' % i) i = max_field_count gdal.PushErrorHandler('CPLQuietErrorHandler') ret = lyr.CreateField(ogr.FieldDefn('foo%d' % i, ogr.OFTString)) gdal.PopErrorHandler() - if ret == 0: - gdaltest.post_reason('should have failed creating field foo%d' % i) - return 'fail' + assert ret != 0, ('should have failed creating field foo%d' % i) feat = ogr.Feature(lyr.GetLayerDefn()) for i in range(max_field_count): @@ -2771,13 +2335,11 @@ def ogr_shape_56(): ds = None - return 'success' - ############################################################################### # Test that we emit a warning if the truncation of a field value occurs -def ogr_shape_57(): +def test_ogr_shape_57(): shape_drv = ogr.GetDriverByName('ESRI Shapefile') ds_name = '/vsimem/ogr_shape_57' ds = shape_drv.CreateDataSource(ds_name) @@ -2791,9 +2353,7 @@ def ogr_shape_57(): lyr.CreateField(field_defn) gdal.PopErrorHandler() # print(gdal.GetLastErrorMsg()) - if gdal.GetLastErrorMsg() == '': - gdaltest.post_reason('expecting a warning') - return 'fail' + assert gdal.GetLastErrorMsg() != '', 'expecting a warning' feat = ogr.Feature(lyr.GetLayerDefn()) feat.SetField(0, '0123456789' * 27) @@ -2803,19 +2363,15 @@ def ogr_shape_57(): lyr.CreateFeature(feat) gdal.PopErrorHandler() # print(gdal.GetLastErrorMsg()) - if gdal.GetLastErrorMsg() == '': - gdaltest.post_reason('expecting a warning') - return 'fail' + assert gdal.GetLastErrorMsg() != '', 'expecting a warning' ds = None - return 'success' - ############################################################################### # Test creating and reading back all geometry types -def ogr_shape_58(): +def test_ogr_shape_58(): shape_drv = ogr.GetDriverByName('ESRI Shapefile') ds_name = '/vsimem/ogr_shape_58' ds = shape_drv.CreateDataSource(ds_name) @@ -2856,60 +2412,44 @@ def ogr_shape_58(): lyr.ResetReading() feat = lyr.GetNextFeature() geom_read = feat.GetGeometryRef() - if geom_read.ExportToWkt() != wkt: - gdaltest.post_reason( - 'did not get expected geom for field %s' % layer_name) - print(geom_read.ExportToWkt()) - return 'fail' + assert geom_read.ExportToWkt() == wkt, \ + ('did not get expected geom for field %s' % layer_name) ds = None - return 'success' - ############################################################################### # Test reading a shape with XYM geometries -def ogr_shape_59(): +def test_ogr_shape_59(): if gdaltest.shape_ds is None: - return 'skip' + pytest.skip() shp_ds = ogr.Open('data/testpointm.shp') if shp_ds is None: - return 'skip' + pytest.skip() shp_lyr = shp_ds.GetLayer(0) feat = shp_lyr.GetNextFeature() geom = feat.GetGeometryRef() - if geom.GetGeometryName() != 'POINT': - print(geom.GetGeometryName()) - gdaltest.post_reason('Geometry of wrong type.') - return 'fail' + assert geom.GetGeometryName() == 'POINT', 'Geometry of wrong type.' - if geom.GetCoordinateDimension() != 2: - gdaltest.post_reason('dimension wrong.') - return 'fail' + assert geom.GetCoordinateDimension() == 2, 'dimension wrong.' if geom.GetPointZM(0) != (1.0, 2.0, 0.0, 3.0): print(geom.GetPoint(0)) - gdaltest.post_reason('Did not get right point result.') - return 'fail' + pytest.fail('Did not get right point result.') shp_ds = ogr.Open('data/arcm_with_m.shp') shp_lyr = shp_ds.GetLayer(0) feat = shp_lyr.GetNextFeature() geom = feat.GetGeometryRef() - if geom.ExportToIsoWkt() != 'LINESTRING M (0 0 10,1 1 20)': - print(geom.ExportToIsoWkt()) - gdaltest.post_reason('fail') - return 'fail' + assert geom.ExportToIsoWkt() == 'LINESTRING M (0 0 10,1 1 20)' feat = shp_lyr.GetNextFeature() geom = feat.GetGeometryRef() - if geom.ExportToIsoWkt() != 'MULTILINESTRING M ((0 0 10,1 1 20),(2 2 30,3 3 40))': - gdaltest.post_reason('fail') - return 'fail' + assert geom.ExportToIsoWkt() == 'MULTILINESTRING M ((0 0 10,1 1 20),(2 2 30,3 3 40))' geom = None feat = None @@ -2917,61 +2457,44 @@ def ogr_shape_59(): shp_lyr = shp_ds.GetLayer(0) feat = shp_lyr.GetNextFeature() geom = feat.GetGeometryRef() - if geom.ExportToIsoWkt() != 'POLYGON M ((0 0 10,0 1 20,1 1 30,0 0 40))': - print(geom.ExportToIsoWkt()) - gdaltest.post_reason('fail') - return 'fail' + assert geom.ExportToIsoWkt() == 'POLYGON M ((0 0 10,0 1 20,1 1 30,0 0 40))' feat = shp_lyr.GetNextFeature() geom = feat.GetGeometryRef() - if geom.ExportToIsoWkt() != 'POLYGON M ((0 0 10,0 1 20,1 1 30,0 0 40),(0.25 0.25 50,0.75 0.75 60,0.25 0.75 70,0.25 0.25 80))': - print(geom.ExportToIsoWkt()) - gdaltest.post_reason('fail') - return 'fail' + assert geom.ExportToIsoWkt() == 'POLYGON M ((0 0 10,0 1 20,1 1 30,0 0 40),(0.25 0.25 50,0.75 0.75 60,0.25 0.75 70,0.25 0.25 80))' geom = None feat = None - return 'success' - ############################################################################### # Test reading a shape with XYZM geometries -def ogr_shape_60(): +def test_ogr_shape_60(): if gdaltest.shape_ds is None: - return 'skip' + pytest.skip() shp_ds = ogr.Open('data/testpointzm.shp') if shp_ds is None: - return 'skip' + pytest.skip() shp_lyr = shp_ds.GetLayer(0) feat = shp_lyr.GetNextFeature() geom = feat.GetGeometryRef() - if geom.GetGeometryName() != 'POINT': - gdaltest.post_reason('Geometry of wrong type.') - return 'fail' + assert geom.GetGeometryName() == 'POINT', 'Geometry of wrong type.' - if geom.GetCoordinateDimension() != 3: - gdaltest.post_reason('dimension wrong.') - return 'fail' + assert geom.GetCoordinateDimension() == 3, 'dimension wrong.' - if geom.GetPoint(0) != (1.0, 2.0, 3.0): - print(geom.GetPoint(0)) - gdaltest.post_reason('Did not get right point result.') - return 'fail' + assert geom.GetPoint(0) == (1.0, 2.0, 3.0), 'Did not get right point result.' geom = None feat = None - return 'success' - ############################################################################### # Test field auto-growing -def ogr_shape_61(): +def test_ogr_shape_61(): shape_drv = ogr.GetDriverByName('ESRI Shapefile') ds_name = '/vsimem/ogr_shape_61' ds = shape_drv.CreateDataSource(ds_name) @@ -2990,10 +2513,7 @@ def ogr_shape_61(): feat = None field_defn = lyr.GetLayerDefn().GetFieldDefn(0) - if field_defn.GetWidth() != 80: - gdaltest.post_reason('did not get initial field size') - print(field_defn.GetWidth()) - return 'fail' + assert field_defn.GetWidth() == 80, 'did not get initial field size' feat = ogr.Feature(lyr.GetLayerDefn()) feat.SetField(0, '0123456789' * 9) @@ -3002,46 +2522,29 @@ def ogr_shape_61(): feat = None field_defn = lyr.GetLayerDefn().GetFieldDefn(0) - if field_defn.GetWidth() != 90: - gdaltest.post_reason('did not extend field') - print(field_defn.GetWidth()) - return 'fail' + assert field_defn.GetWidth() == 90, 'did not extend field' field_defn = lyr.GetLayerDefn().GetFieldDefn(1) - if field_defn.GetWidth() != 2: - gdaltest.post_reason('did not extend field') - print(field_defn.GetWidth()) - return 'fail' + assert field_defn.GetWidth() == 2, 'did not extend field' ds = None ds = ogr.Open(ds_name) lyr = ds.GetLayer(0) field_defn = lyr.GetLayerDefn().GetFieldDefn(0) - if field_defn.GetWidth() != 90: - gdaltest.post_reason('did not get expected field size') - print(field_defn.GetWidth()) - return 'fail' + assert field_defn.GetWidth() == 90, 'did not get expected field size' feat = lyr.GetFeature(1) val = feat.GetFieldAsString(0) - if val != '0123456789' * 9: - gdaltest.post_reason('did not get expected field value') - print(val) - return 'fail' + assert val == '0123456789' * 9, 'did not get expected field value' val = feat.GetFieldAsInteger(1) - if val != 34: - gdaltest.post_reason('did not get expected field value') - print(val) - return 'fail' - - return 'success' + assert val == 34, 'did not get expected field value' ############################################################################### # Test field resizing -def ogr_shape_62(): +def test_ogr_shape_62(): shape_drv = ogr.GetDriverByName('ESRI Shapefile') ds_name = '/vsimem/ogr_shape_62' ds = shape_drv.CreateDataSource(ds_name) @@ -3074,10 +2577,7 @@ def ogr_shape_62(): # Check field_defn = lyr.GetLayerDefn().GetFieldDefn(0) - if field_defn.GetWidth() != 4: - gdaltest.post_reason('did not get expected field size') - print(field_defn.GetWidth()) - return 'fail' + assert field_defn.GetWidth() == 4, 'did not get expected field size' # Reopen file ds = ogr.Open(ds_name, update=1) @@ -3091,37 +2591,25 @@ def ogr_shape_62(): for expected_value in values: feat = lyr.GetNextFeature() got_val = feat.GetFieldAsString(0) - if got_val != expected_value: - gdaltest.post_reason('did not get expected value') - print(got_val) - return 'fail' + assert got_val == expected_value, 'did not get expected value' got_val = feat.GetFieldAsInteger(2) - if got_val != 12: - gdaltest.post_reason('did not get expected value') - print(got_val) - return 'fail' + assert got_val == 12, 'did not get expected value' ds = None - return 'success' - ############################################################################### # More testing of recoding -def ogr_shape_63(): +def test_ogr_shape_63(): ds = ogr.GetDriverByName('ESRI Shapefile').CreateDataSource('/vsimem/ogr_shape_63.dbf') lyr = ds.CreateLayer('ogr_shape_63', geom_type=ogr.wkbNone) gdaltest.fieldname = '\xc3\xa9' - if lyr.CreateField(ogr.FieldDefn(gdaltest.fieldname, ogr.OFTString)) != 0: - gdaltest.post_reason('failed') - return 'fail' + assert lyr.CreateField(ogr.FieldDefn(gdaltest.fieldname, ogr.OFTString)) == 0 gdaltest.fieldname = '\xc3\xa9\xc3\xa9' - if lyr.AlterFieldDefn(0, ogr.FieldDefn(gdaltest.fieldname, ogr.OFTString), ogr.ALTER_NAME_FLAG) != 0: - gdaltest.post_reason('failed') - return 'fail' + assert lyr.AlterFieldDefn(0, ogr.FieldDefn(gdaltest.fieldname, ogr.OFTString), ogr.ALTER_NAME_FLAG) == 0 chinese_str = struct.pack('B' * 6, 229, 144, 141, 231, 167, 176) if sys.version_info >= (3, 0, 0): @@ -3131,29 +2619,20 @@ def ogr_shape_63(): ret = lyr.AlterFieldDefn(0, ogr.FieldDefn(chinese_str, ogr.OFTString), ogr.ALTER_NAME_FLAG) gdal.PopErrorHandler() - if ret == 0: - gdaltest.post_reason('failed') - return 'fail' + assert ret != 0 gdal.PushErrorHandler('CPLQuietErrorHandler') ret = lyr.CreateField(ogr.FieldDefn(chinese_str, ogr.OFTString)) gdal.PopErrorHandler() - if ret == 0: - gdaltest.post_reason('failed') - return 'fail' + assert ret != 0 ds = None ds = ogr.Open('/vsimem/ogr_shape_63.dbf') lyr = ds.GetLayer(0) - if lyr.TestCapability(ogr.OLCStringsAsUTF8) != 1: - gdaltest.post_reason('failed') - return 'fail' - if lyr.GetLayerDefn().GetFieldDefn(0).GetName() != gdaltest.fieldname: - gdaltest.post_reason('failed') - print(gdaltest.fieldname) - return 'fail' + assert lyr.TestCapability(ogr.OLCStringsAsUTF8) == 1 + assert lyr.GetLayerDefn().GetFieldDefn(0).GetName() == gdaltest.fieldname ds = None # Set an invalid encoding @@ -3162,28 +2641,22 @@ def ogr_shape_63(): ds = ogr.Open('/vsimem/ogr_shape_63.dbf') lyr = ds.GetLayer(0) # TestCapability(OLCStringsAsUTF8) should return FALSE - if lyr.TestCapability(ogr.OLCStringsAsUTF8) != 0: - gdaltest.post_reason('failed') - return 'fail' + assert lyr.TestCapability(ogr.OLCStringsAsUTF8) == 0 ds = None gdal.Unlink('/vsimem/ogr_shape_63.dbf') gdal.Unlink('/vsimem/ogr_shape_63.cpg') - return 'success' - ############################################################################### # Test creating layers whose name include dot character -def ogr_shape_64(): +def test_ogr_shape_64(): ds = ogr.GetDriverByName('ESRI Shapefile').CreateDataSource('/vsimem/ogr_shape_64') lyr = ds.CreateLayer('a.b') - if lyr.GetName() != 'a.b': - gdaltest.post_reason('failed') - return 'fail' + assert lyr.GetName() == 'a.b' lyr.CreateField(ogr.FieldDefn('foo', ogr.OFTString)) feat = ogr.Feature(lyr.GetLayerDefn()) feat.SetField('foo', 'bar') @@ -3191,26 +2664,20 @@ def ogr_shape_64(): feat = None lyr = ds.CreateLayer('a.c') - if lyr.GetName() != 'a.c': - gdaltest.post_reason('failed') - return 'fail' + assert lyr.GetName() == 'a.c' # Test that we cannot create a duplicate layer gdal.PushErrorHandler('CPLQuietErrorHandler') lyr = ds.CreateLayer('a.b') gdal.PopErrorHandler() - if lyr is not None: - gdaltest.post_reason('failed') - return 'fail' + assert lyr is None ds = None ds = ogr.Open('/vsimem/ogr_shape_64/a.b.shp') lyr = ds.GetLayer(0) feat = lyr.GetNextFeature() - if feat.GetFieldAsString('foo') != 'bar': - gdaltest.post_reason('failed') - return 'fail' + assert feat.GetFieldAsString('foo') == 'bar' ds = None gdal.Unlink('/vsimem/ogr_shape_64/a.b.shp') @@ -3221,13 +2688,11 @@ def ogr_shape_64(): gdal.Unlink('/vsimem/ogr_shape_64/a.c.dbf') gdal.Unlink('/vsimem/ogr_shape_64') - return 'success' - ############################################################################### # Test reading a DBF with a 'nan' as a numeric value (#4799) -def ogr_shape_65(): +def test_ogr_shape_65(): ds = ogr.Open('data/nan.dbf') lyr = ds.GetLayer(0) @@ -3236,60 +2701,46 @@ def ogr_shape_65(): feat = None ds = None - if not gdaltest.isnan(val): - print(val) - return 'fail' - - return 'success' + assert gdaltest.isnan(val) ############################################################################### # Test failures when creating files and datasources -def ogr_shape_66(): +def test_ogr_shape_66(): ds = ogr.GetDriverByName('ESRI Shapefile').CreateDataSource('/i_dont_exist/bar.dbf') gdal.PushErrorHandler('CPLQuietErrorHandler') lyr = ds.CreateLayer('bar', geom_type=ogr.wkbNone) gdal.PopErrorHandler() - if lyr is not None: - gdaltest.post_reason('fail') - return 'fail' + assert lyr is None ds = None ds = ogr.GetDriverByName('ESRI Shapefile').CreateDataSource('/i_dont_exist/bar.shp') gdal.PushErrorHandler('CPLQuietErrorHandler') lyr = ds.CreateLayer('bar', geom_type=ogr.wkbPoint) gdal.PopErrorHandler() - if lyr is not None: - gdaltest.post_reason('fail') - return 'fail' + assert lyr is None ds = None gdal.PushErrorHandler('CPLQuietErrorHandler') ds = ogr.GetDriverByName('ESRI Shapefile').CreateDataSource('/i_dont_exist/bar') gdal.PopErrorHandler() - if ds is not None: - gdaltest.post_reason('fail') - return 'fail' + assert ds is None f = open('tmp/foo', 'wb') f.close() gdal.PushErrorHandler('CPLQuietErrorHandler') ds = ogr.GetDriverByName('ESRI Shapefile').CreateDataSource('tmp/foo') gdal.PopErrorHandler() - if ds is not None: - gdaltest.post_reason('fail') - return 'fail' + assert ds is None os.unlink('tmp/foo') - return 'success' - ############################################################################### # Test opening an empty .sbn spatial index -def ogr_shape_67(): +def test_ogr_shape_67(): shutil.copy('data/emptyshapefilewithsbn.shp', 'tmp/emptyshapefilewithsbn.shp') shutil.copy('data/emptyshapefilewithsbn.shx', 'tmp/emptyshapefilewithsbn.shx') @@ -3300,26 +2751,21 @@ def ogr_shape_67(): ds.ExecuteSQL('DROP SPATIAL INDEX ON emptyshapefilewithsbn') ds = None - try: + with pytest.raises(OSError): os.stat('tmp/emptyshapefilewithsbn.sbn') - return 'fail' - except OSError: - pass + os.unlink('tmp/emptyshapefilewithsbn.shp') os.unlink('tmp/emptyshapefilewithsbn.shx') - return 'success' - ############################################################################### # Test opening a shape datasource with files with mixed case and then REPACK -def ogr_shape_68(): +def test_ogr_shape_68(): if sys.platform == 'darwin': - print("Fails on MacOSX. Not sure why.") - return 'skip' + pytest.skip("Fails on MacOSX. Not sure why.") for i in range(2): if i == 1 and sys.platform != 'win32': @@ -3339,9 +2785,8 @@ def ogr_shape_68(): expected_layer_count = 1 else: expected_layer_count = 2 - if ds.GetLayerCount() != expected_layer_count: - gdaltest.post_reason('expected %d layers, got %d' % (expected_layer_count, ds.GetLayerCount())) - return 'fail' + assert ds.GetLayerCount() == expected_layer_count, \ + ('expected %d layers, got %d' % (expected_layer_count, ds.GetLayerCount())) if i == 1: lyr = ds.GetLayerByName('mixedcase') else: @@ -3353,23 +2798,15 @@ def ogr_shape_68(): ds.ExecuteSQL('REPACK MIXEDCASE') if sys.platform == 'win32': - if lyr.GetGeomType() != ogr.wkbPolygon: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.GetGeomType() == ogr.wkbPolygon else: - if lyr.GetGeomType() != ogr.wkbNone: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.GetGeomType() == ogr.wkbNone lyr = ds.GetLayerByName('mixedcase') - if lyr.GetGeomType() != ogr.wkbPolygon: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.GetGeomType() == ogr.wkbPolygon gdal.PushErrorHandler('CPLQuietErrorHandler') ret = lyr.DeleteFeature(0) gdal.PopErrorHandler() - if ret == 0: - gdaltest.post_reason('expected failure on DeleteFeature()') - return 'fail' + assert ret != 0, 'expected failure on DeleteFeature()' # gdal.ErrorReset() # gdal.PushErrorHandler('CPLQuietErrorHandler') ds.ExecuteSQL('REPACK mixedcase') @@ -3388,32 +2825,21 @@ def ogr_shape_68(): new_shx_size = os.stat('tmp/mixedcase/mixedcase.shx').st_size new_dbf_size = os.stat('tmp/mixedcase/MIXEDCASE.DBF').st_size - if new_dbf_size == ori_dbf_size: - gdaltest.post_reason('fail') - return 'fail' + assert new_dbf_size != ori_dbf_size if sys.platform == 'win32': - if new_shp_size == ori_shp_size: - gdaltest.post_reason('fail') - return 'fail' - if new_shx_size == ori_shx_size: - gdaltest.post_reason('fail') - return 'fail' + assert new_shp_size != ori_shp_size + assert new_shx_size != ori_shx_size else: - if new_shp_size != ori_shp_size: - gdaltest.post_reason('fail') - return 'fail' - if new_shx_size != ori_shx_size: - gdaltest.post_reason('fail') - return 'fail' - - return 'success' + assert new_shp_size == ori_shp_size + assert new_shx_size == ori_shx_size + ############################################################################### # Test fix for #5135 (creating a field of type Integer with a big width) -def ogr_shape_69(): +def test_ogr_shape_69(): ds = ogr.GetDriverByName('ESRI Shapefile').CreateDataSource('/vsimem/ogr_shape_69.shp') lyr = ds.CreateLayer('ogr_shape_69') @@ -3428,26 +2854,22 @@ def ogr_shape_69(): ds = ogr.Open('/vsimem/ogr_shape_69.shp') lyr = ds.GetLayer(0) - if lyr.GetLayerDefn().GetFieldDefn(0).GetType() != ogr.OFTReal: - return 'fail' + assert lyr.GetLayerDefn().GetFieldDefn(0).GetType() == ogr.OFTReal feat = lyr.GetNextFeature() - if feat.GetField(0) != 123456: - return 'fail' + assert feat.GetField(0) == 123456 ds = None ogr.GetDriverByName('ESRI Shapefile').DeleteDataSource('/vsimem/ogr_shape_69.shp') - return 'success' - ############################################################################### # Test fix for https://github.com/OSGeo/gdal/pull/17 # (shapefile opened twice on Windows) -def ogr_shape_70(): +def test_ogr_shape_70(): if sys.platform != 'win32': - return 'skip' + pytest.skip() ds = ogr.GetDriverByName('ESRI Shapefile').CreateDataSource('tmp/ogr_shape_70.shp') lyr = ds.CreateLayer('ogr_shape_70') @@ -3476,23 +2898,19 @@ def ogr_shape_70(): ogr.GetDriverByName('ESRI Shapefile').DeleteDataSource('tmp/ogr_shape_70.shp') - if errmsg == '': - return 'fail' - - return 'success' + assert errmsg != '' ############################################################################### # Test heterogeneous file permissions on .shp and .dbf. -def ogr_shape_71(): +def test_ogr_shape_71(): if sys.platform.find('linux') != 0: - return 'skip' + pytest.skip() if os.getuid() == 0: - print('running as root... skipping') - return 'skip' + pytest.skip('running as root... skipping') import stat shutil.copy('data/poly.shp', 'tmp/ogr_shape_71.shp') @@ -3508,21 +2926,18 @@ def ogr_shape_71(): ogr.GetDriverByName('ESRI Shapefile').DeleteDataSource('tmp/ogr_shape_71.shp') - if not ok: - return 'fail' - - return 'success' + assert ok ############################################################################### # Test shapefile size limit -def ogr_shape_72(): +def test_ogr_shape_72(): # Determine if the filesystem supports sparse files (we don't want to create a real 3 GB # file ! if gdaltest.filesystem_supports_sparse_files('tmp') is False: - return 'skip' + pytest.skip() ds = ogr.GetDriverByName('ESRI Shapefile').CreateDataSource('tmp/ogr_shape_72.shp') lyr = ds.CreateLayer('2gb', geom_type=ogr.wkbPoint) @@ -3544,9 +2959,7 @@ def ogr_shape_72(): gdal.PushErrorHandler('CPLQuietErrorHandler') ret = lyr.CreateFeature(feat) gdal.PopErrorHandler() - if ret == 0: - gdaltest.post_reason('fail') - return 'fail' + assert ret != 0 ds = None f = open('tmp/ogr_shape_72.shp', 'rb+') @@ -3565,9 +2978,7 @@ def ogr_shape_72(): gdal.PushErrorHandler('CPLQuietErrorHandler') ret = lyr.CreateFeature(feat) gdal.PopErrorHandler() - if ret == 0: - gdaltest.post_reason('fail') - return 'fail' + assert ret != 0 ds = None # Test creating a feature over 2 GB file limit -> should succeed with warning @@ -3579,30 +2990,23 @@ def ogr_shape_72(): gdal.PushErrorHandler('CPLQuietErrorHandler') ret = lyr.CreateFeature(feat) gdal.PopErrorHandler() - if ret != 0: - gdaltest.post_reason('fail') - return 'fail' - if gdal.GetLastErrorMsg().find('2GB file size limit reached') < 0: - gdaltest.post_reason('did not find expected warning') - return 'fail' + assert ret == 0 + assert gdal.GetLastErrorMsg().find('2GB file size limit reached') >= 0, \ + 'did not find expected warning' ds = None ds = ogr.Open('tmp/ogr_shape_72.shp') lyr = ds.GetLayer(0) feat = lyr.GetFeature(1) - if feat.GetGeometryRef().ExportToWkt() != 'POINT (7 8)': - gdaltest.post_reason('fail') - return 'fail' + assert feat.GetGeometryRef().ExportToWkt() == 'POINT (7 8)' ds = None - return 'success' - ############################################################################### # Test that isClockwise() works correctly on a degenerated ring that passes # twice by the same point (#5342) -def ogr_shape_73(): +def test_ogr_shape_73(): ds = ogr.GetDriverByName('ESRI Shapefile').CreateDataSource('/vsimem/ogr_shape_73.shp') lyr = ds.CreateLayer('ogr_shape_73', geom_type=ogr.wkbPolygon) @@ -3623,17 +3027,15 @@ def ogr_shape_73(): got_geom = feat.GetGeometryRef() if geom.ExportToWkt() != got_geom.ExportToWkt(): feat.DumpReadable() - return 'fail' + pytest.fail() ds = None - return 'success' - ############################################################################### # Test organizePolygons() in OGR_ORGANIZE_POLYGONS=DEFAULT mode when # two outer rings are touching, by the first vertex of one. -def ogr_shape_74(): +def test_ogr_shape_74(): ds = ogr.GetDriverByName('ESRI Shapefile').CreateDataSource('/vsimem/ogr_shape_74.shp') lyr = ds.CreateLayer('ogr_shape_74', geom_type=ogr.wkbPolygon) @@ -3649,9 +3051,8 @@ def ogr_shape_74(): feat = lyr.GetNextFeature() got_geom = feat.GetGeometryRef() if geom.ExportToWkt() != got_geom.ExportToWkt(): - gdaltest.post_reason('fail') feat.DumpReadable() - return 'fail' + pytest.fail() lyr.ResetReading() gdal.SetConfigOption('OGR_ORGANIZE_POLYGONS', 'DEFAULT') @@ -3659,85 +3060,62 @@ def ogr_shape_74(): gdal.SetConfigOption('OGR_ORGANIZE_POLYGONS', None) got_geom = feat.GetGeometryRef() if geom.ExportToWkt() != got_geom.ExportToWkt(): - gdaltest.post_reason('fail') feat.DumpReadable() - return 'fail' + pytest.fail() ds = None - return 'success' - ############################################################################### # Test GetFileList() -def ogr_shape_75(): +def test_ogr_shape_75(): ds = gdal.OpenEx('data/poly.shp') - if ds.GetFileList() != ['data/poly.shp', 'data/poly.shx', 'data/poly.dbf', 'data/poly.PRJ'] and \ - ds.GetFileList() != ['data/poly.shp', 'data/poly.shx', 'data/poly.dbf', 'data/poly.prj']: - gdaltest.post_reason('fail') - print(ds.GetFileList()) - return 'fail' + assert (ds.GetFileList() == ['data/poly.shp', 'data/poly.shx', 'data/poly.dbf', 'data/poly.PRJ'] or \ + ds.GetFileList() == ['data/poly.shp', 'data/poly.shx', 'data/poly.dbf', 'data/poly.prj']) ds = None ds = gdal.OpenEx('data/idlink.dbf') - if ds.GetFileList() != ['data/idlink.dbf']: - gdaltest.post_reason('fail') - print(ds.GetFileList()) - return 'fail' + assert ds.GetFileList() == ['data/idlink.dbf'] ds = None ds = gdal.OpenEx('data/testpoly.shp') - if ds.GetFileList() != ['data/testpoly.shp', 'data/testpoly.shx', 'data/testpoly.dbf', 'data/testpoly.qix']: - gdaltest.post_reason('fail') - print(ds.GetFileList()) - return 'fail' + assert ds.GetFileList() == ['data/testpoly.shp', 'data/testpoly.shx', 'data/testpoly.dbf', 'data/testpoly.qix'] ds = None ds = gdal.OpenEx('data/emptyshapefilewithsbn.shx') - if ds.GetFileList() != ['data/emptyshapefilewithsbn.shp', 'data/emptyshapefilewithsbn.shx', 'data/emptyshapefilewithsbn.sbn', 'data/emptyshapefilewithsbn.sbx']: - gdaltest.post_reason('fail') - print(ds.GetFileList()) - return 'fail' + assert ds.GetFileList() == ['data/emptyshapefilewithsbn.shp', 'data/emptyshapefilewithsbn.shx', 'data/emptyshapefilewithsbn.sbn', 'data/emptyshapefilewithsbn.sbx'] ds = None - return 'success' - ############################################################################### # Test opening shapefile whose .prj has a UTF-8 BOM marker -def ogr_shape_76(): +def test_ogr_shape_76(): ds = ogr.Open('data/prjwithutf8bom.shp') lyr = ds.GetLayer(0) sr = lyr.GetSpatialRef() - if sr.ExportToWkt().find('GEOGCS["NAD83"') != 0: - return 'fail' - - return 'success' + assert sr.ExportToWkt().find('GEOGCS["NAD83"') == 0 ############################################################################### # Test opening shapefile whose .shx doesn't follow the official shapefile spec (#5608) -def ogr_shape_77(): +def test_ogr_shape_77(): ds = ogr.Open('data/nonconformant_shx_ticket5608.shp') lyr = ds.GetLayer(0) feat = lyr.GetNextFeature() geom = feat.GetGeometryRef() - if geom.ExportToWkt() != 'LINESTRING (0 1,2 3)': - return 'fail' - - return 'success' + assert geom.ExportToWkt() == 'LINESTRING (0 1,2 3)' ############################################################################### # Test writing integer values through double fields, and cases of truncation or # loss of precision (#5625) -def ogr_shape_78(): +def test_ogr_shape_78(): ds = ogr.GetDriverByName('ESRI Shapefile').CreateDataSource('/vsimem/ogr_shape_78.dbf') lyr = ds.CreateLayer('ogr_shape_78') @@ -3756,9 +3134,7 @@ def ogr_shape_78(): f = ogr.Feature(lyr.GetLayerDefn()) f.SetField('dblfield', (2**53) * 1.0) lyr.CreateFeature(f) - if gdal.GetLastErrorMsg() != '': - gdaltest.post_reason('got unexpected error/warning') - return 'fail' + assert gdal.GetLastErrorMsg() == '', 'got unexpected error/warning' # Field width too small gdal.ErrorReset() @@ -3767,9 +3143,7 @@ def ogr_shape_78(): gdal.PushErrorHandler('CPLQuietErrorHandler') lyr.CreateFeature(f) gdal.PopErrorHandler() - if gdal.GetLastErrorMsg() == '': - gdaltest.post_reason('did not get expected error/warning') - return 'fail' + assert gdal.GetLastErrorMsg() != '', 'did not get expected error/warning' # Likely precision loss gdal.ErrorReset() @@ -3778,9 +3152,7 @@ def ogr_shape_78(): gdal.PushErrorHandler('CPLQuietErrorHandler') lyr.CreateFeature(f) gdal.PopErrorHandler() - if gdal.GetLastErrorMsg() == '': - gdaltest.post_reason('did not get expected error/warning') - return 'fail' + assert gdal.GetLastErrorMsg() != '', 'did not get expected error/warning' gdal.ErrorReset() ds = None @@ -3789,18 +3161,15 @@ def ogr_shape_78(): lyr = ds.GetLayer(0) f = lyr.GetNextFeature() if f.GetField('dblfield') != 9007199254740992.: - gdaltest.post_reason('did not get expected value') f.DumpReadable() - return 'fail' + pytest.fail('did not get expected value') ds = None - return 'success' - ############################################################################### # Test adding a field after creating features with 0 field -def ogr_shape_79(): +def test_ogr_shape_79(): ds = ogr.GetDriverByName('ESRI Shapefile').CreateDataSource('/vsimem/ogr_shape_79.dbf') lyr = ds.CreateLayer('ogr_shape_79') @@ -3823,34 +3192,26 @@ def ogr_shape_79(): ds = ogr.Open('/vsimem/ogr_shape_79.dbf') lyr = ds.GetLayer(0) - if lyr.GetLayerDefn().GetFieldCount() != 2: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.GetLayerDefn().GetFieldCount() == 2 ds = None - return 'success' - ############################################################################### # Test reading a shape with invalid extent (nan values) (#5702) -def ogr_shape_80(): +def test_ogr_shape_80(): ds = ogr.Open('data/extentnan.shp') lyr = ds.GetLayer(0) extent = lyr.GetExtent() - if extent is not None and extent[0] != extent[0]: - gdaltest.post_reason('fail') - print(extent) - return 'fail' + assert extent is None or extent[0] == extent[0] ds = None - return 'success' ############################################################################### # Test REPACK after SetFeature() and geometry change (#XXXX) -def ogr_shape_81(): +def test_ogr_shape_81(): ds = ogr.GetDriverByName('ESRI Shapefile').CreateDataSource('/vsimem/ogr_shape_81.shp') lyr = ds.CreateLayer('ogr_shape_81') @@ -3876,9 +3237,7 @@ def ogr_shape_81(): # Should be a no-op ds.ExecuteSQL('REPACK ogr_shape_81') size_after = gdal.VSIStatL('/vsimem/ogr_shape_81.shp').size - if size_after != size_before: - gdaltest.post_reason('fail') - return 'fail' + assert size_after == size_before f = lyr.GetNextFeature() f.SetGeometry(ogr.CreateGeometryFromWkt('LINESTRING(2 2,3 3)')) @@ -3887,55 +3246,43 @@ def ogr_shape_81(): # Should be a no-op ds.ExecuteSQL('REPACK ogr_shape_81') size_after = gdal.VSIStatL('/vsimem/ogr_shape_81.shp').size - if size_after != size_before: - gdaltest.post_reason('fail') - return 'fail' + assert size_after == size_before # Writes a longer geometry. So .shp will be extended f.SetGeometry(ogr.CreateGeometryFromWkt('LINESTRING(2 2,3 3,4 4)')) lyr.SetFeature(f) size_after = gdal.VSIStatL('/vsimem/ogr_shape_81.shp').size - if size_after == size_before: - gdaltest.post_reason('fail') - return 'fail' + assert size_after != size_before # Should do something size_before = size_after ds.ExecuteSQL('REPACK ogr_shape_81') size_after = gdal.VSIStatL('/vsimem/ogr_shape_81.shp').size - if size_after == size_before: - gdaltest.post_reason('fail') - return 'fail' + assert size_after != size_before # Writes a shorter geometry, so .shp should not change size. size_before = size_after f.SetGeometry(ogr.CreateGeometryFromWkt('LINESTRING(3 3,4 4)')) lyr.SetFeature(f) size_after = gdal.VSIStatL('/vsimem/ogr_shape_81.shp').size - if size_after != size_before: - gdaltest.post_reason('fail') - return 'fail' + assert size_after == size_before size_before = size_after # Should do something ds.ExecuteSQL('REPACK ogr_shape_81') size_after = gdal.VSIStatL('/vsimem/ogr_shape_81.shp').size - if size_after == size_before: - gdaltest.post_reason('fail') - return 'fail' + assert size_after != size_before ds = None - return 'success' - ############################################################################### # Test string length more than 254 bytes in UTF-8 encoding cut to 254 bytes -def ogr_shape_82(): +def test_ogr_shape_82(): if gdaltest.shape_ds is None: - return 'skip' + pytest.skip() # create ogrlayer to test cut long strings with UTF-8 encoding gdaltest.shape_lyr = gdaltest.shape_ds.CreateLayer('test_utf_cut', geom_type=ogr.wkbPoint, options=['ENCODING=UTF-8']) @@ -3946,9 +3293,7 @@ def ogr_shape_82(): result = gdaltest.shape_lyr.CreateField(field_defn) - if result != 0: - gdaltest.post_reason('failed to create new field.') - return 'fail' + assert result == 0, 'failed to create new field.' # Insert feature with long string in Russian. Shoe repair ad. feat = ogr.Feature(feature_def=gdaltest.shape_lyr.GetLayerDefn()) @@ -3992,48 +3337,34 @@ def ogr_shape_82(): # Read strings and compare with correct values. feat = gdaltest.shape_lyr.GetFeature(0) # rus - if feat.cut_field != result_rus: - gdaltest.post_reason('Wrong rus string cut') - return 'fail' + assert feat.cut_field == result_rus, 'Wrong rus string cut' feat = gdaltest.shape_lyr.GetFeature(1) # en - if feat.cut_field != result_en: - gdaltest.post_reason('Wrong en string cut') - print(feat.cut_field) - print(result_en) - return 'fail' - - return 'success' + assert feat.cut_field == result_en, 'Wrong en string cut' ############################################################################### # Test behaviour with curve geometries -def ogr_shape_83(): +def test_ogr_shape_83(): ds = ogr.GetDriverByName('ESRI Shapefile').CreateDataSource('/vsimem/ogr_shape_83.shp') lyr = ds.CreateLayer('ogr_shape_83', geom_type=ogr.wkbCurvePolygon) - if lyr.GetGeomType() != ogr.wkbPolygon: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.GetGeomType() == ogr.wkbPolygon f = ogr.Feature(lyr.GetLayerDefn()) f.SetGeometry(ogr.CreateGeometryFromWkt('CURVEPOLYGON((0 0,0 1,1 1,1 0,0 0))')) lyr.CreateFeature(f) f = None f = lyr.GetFeature(0) - if f.GetGeometryRef().GetGeometryType() != ogr.wkbPolygon: - gdaltest.post_reason('fail') - return 'fail' + assert f.GetGeometryRef().GetGeometryType() == ogr.wkbPolygon ds = None - return 'success' - ############################################################################### # Test SPATIAL_INDEX creation option -def ogr_shape_84(): +def test_ogr_shape_84(): ds = ogr.GetDriverByName('ESRI Shapefile').CreateDataSource('/vsimem/ogr_shape_84.shp') lyr = ds.CreateLayer('ogr_shape_84', options=['SPATIAL_INDEX=YES']) @@ -4043,17 +3374,13 @@ def ogr_shape_84(): f = None ds = None - if gdal.VSIStatL('/vsimem/ogr_shape_84.qix') is None: - gdaltest.post_reason('fail') - return 'fail' - - return 'success' + assert gdal.VSIStatL('/vsimem/ogr_shape_84.qix') is not None ############################################################################### # Test Integer64 -def ogr_shape_85(): +def test_ogr_shape_85(): ds = ogr.GetDriverByName('ESRI Shapefile').CreateDataSource('/vsimem/ogr_shape_85.shp') lyr = ds.CreateLayer('ogr_shape_85') @@ -4068,16 +3395,10 @@ def ogr_shape_85(): ds = ogr.Open('/vsimem/ogr_shape_85.shp', update=1) lyr = ds.GetLayer(0) - if lyr.GetLayerDefn().GetFieldDefn(0).GetType() != ogr.OFTInteger: - gdaltest.post_reason('failure') - return 'fail' - if lyr.GetLayerDefn().GetFieldDefn(1).GetType() != ogr.OFTInteger64: - gdaltest.post_reason('failure') - return 'fail' + assert lyr.GetLayerDefn().GetFieldDefn(0).GetType() == ogr.OFTInteger + assert lyr.GetLayerDefn().GetFieldDefn(1).GetType() == ogr.OFTInteger64 f = lyr.GetNextFeature() - if f.GetField(0) != 123456789 or f.GetField(1) != 123456789012345678: - gdaltest.post_reason('failure') - return 'fail' + assert f.GetField(0) == 123456789 and f.GetField(1) == 123456789012345678 # Passing from 9 to 10 figures causes "promotion" to Integer64 f.SetField(0, 2000000000) # Passing from 18 to 19 figures causes "promotion" to Real @@ -4087,31 +3408,19 @@ def ogr_shape_85(): ds = ogr.Open('/vsimem/ogr_shape_85.shp') lyr = ds.GetLayer(0) - if lyr.GetLayerDefn().GetFieldDefn(0).GetType() != ogr.OFTInteger64: - gdaltest.post_reason('failure') - return 'fail' - if lyr.GetLayerDefn().GetFieldDefn(1).GetType() != ogr.OFTReal: - gdaltest.post_reason('failure') - return 'fail' + assert lyr.GetLayerDefn().GetFieldDefn(0).GetType() == ogr.OFTInteger64 + assert lyr.GetLayerDefn().GetFieldDefn(1).GetType() == ogr.OFTReal f = lyr.GetNextFeature() - if f.GetField(0) != 2000000000 or f.GetField(1) != 9000000000000000000: - gdaltest.post_reason('failure') - return 'fail' + assert f.GetField(0) == 2000000000 and f.GetField(1) == 9000000000000000000 ds = None # Test open option ADJUST_TYPE ds = gdal.OpenEx('/vsimem/ogr_shape_85.shp', gdal.OF_VECTOR, open_options=['ADJUST_TYPE=YES']) lyr = ds.GetLayer(0) - if lyr.GetLayerDefn().GetFieldDefn(0).GetType() != ogr.OFTInteger: - gdaltest.post_reason('failure') - return 'fail' - if lyr.GetLayerDefn().GetFieldDefn(1).GetType() != ogr.OFTInteger64: - gdaltest.post_reason('failure') - return 'fail' + assert lyr.GetLayerDefn().GetFieldDefn(0).GetType() == ogr.OFTInteger + assert lyr.GetLayerDefn().GetFieldDefn(1).GetType() == ogr.OFTInteger64 f = lyr.GetNextFeature() - if f.GetField(0) != 2000000000 or f.GetField(1) != 9000000000000000000: - gdaltest.post_reason('failure') - return 'fail' + assert f.GetField(0) == 2000000000 and f.GetField(1) == 9000000000000000000 ds = None ogr.GetDriverByName('ESRI Shapefile').DeleteDataSource('/vsimem/ogr_shape_85.shp') @@ -4124,62 +3433,48 @@ def ogr_shape_85(): lyr.CreateFeature(f) fd = ogr.FieldDefn("foo", ogr.OFTInteger64) ret = lyr.AlterFieldDefn(0, fd, ogr.ALTER_TYPE_FLAG) - if ret != 0: - gdaltest.post_reason('failure') - return 'fail' + assert ret == 0 f.SetField(0, 123456789012345678) lyr.SetFeature(f) ds = None ds = ogr.Open('/vsimem/ogr_shape_85.shp', update=1) lyr = ds.GetLayer(0) - if lyr.GetLayerDefn().GetFieldDefn(0).GetType() != ogr.OFTInteger64: - gdaltest.post_reason('failure') - return 'fail' + assert lyr.GetLayerDefn().GetFieldDefn(0).GetType() == ogr.OFTInteger64 f = lyr.GetNextFeature() - if f.GetField(0) != 123456789012345678: - gdaltest.post_reason('failure') - return 'fail' + assert f.GetField(0) == 123456789012345678 ds = None - return 'success' - ############################################################################### # Robustness: test reading a non-conformant shapefile that mixes different shape type # OGR can not produce such a file (unless patched) -def ogr_shape_86(): +def test_ogr_shape_86(): ds = ogr.Open('data/mixed_shape_type_non_conformant.shp') sql_lyr = ds.ExecuteSQL("select count(distinct ogr_geometry) from mixed_shape_type_non_conformant") f = sql_lyr.GetNextFeature() val = f.GetField(0) ds.ReleaseResultSet(sql_lyr) - if val != 6: - return 'fail' - - return 'success' + assert val == 6 ############################################################################### # Check we accept opening standalone .dbf files with weird header lengths (#6035) -def ogr_shape_87(): +def test_ogr_shape_87(): ds = ogr.Open('data/weird_header_length.dbf') lyr = ds.GetLayer(0) f = lyr.GetNextFeature() - if f.GetField(0) != 1: - return 'fail' - - return 'success' + assert f.GetField(0) == 1 ############################################################################### # Test REPACK after SetFeature() and geometry change, without DBF -def ogr_shape_88(): +def test_ogr_shape_88(): ds = ogr.GetDriverByName('ESRI Shapefile').CreateDataSource('/vsimem/ogr_shape_88.shp') lyr = ds.CreateLayer('ogr_shape_88') @@ -4201,13 +3496,11 @@ def ogr_shape_88(): ds = None - return 'success' - ############################################################################### # Test reading geometry bigger than 10 MB -def ogr_shape_89(): +def test_ogr_shape_89(): ds = ogr.GetDriverByName('ESRI Shapefile').CreateDataSource('/vsimem/ogr_shape_89.shp') lyr = ds.CreateLayer('ogr_shape_89') @@ -4232,9 +3525,7 @@ def ogr_shape_89(): lyr = ds.GetLayer(0) with gdaltest.error_handler(): f = lyr.GetNextFeature() - if f is not None and f.GetGeometryRef() is not None: - gdaltest.post_reason('fail') - return 'fail' + assert f is None or f.GetGeometryRef() is None ds = None f = gdal.VSIFOpenL('/vsimem/ogr_shape_89.shp', 'rb+') @@ -4246,19 +3537,15 @@ def ogr_shape_89(): lyr = ds.GetLayer(0) f = lyr.GetNextFeature() g = f.GetGeometryRef() - if g.GetPointCount() != 2: - gdaltest.post_reason('fail') - return 'fail' + assert g.GetPointCount() == 2 ds = None - return 'success' - ############################################################################### # Test reading a lot of geometries -def ogr_shape_90(): +def test_ogr_shape_90(): ds = ogr.GetDriverByName('ESRI Shapefile').CreateDataSource('/vsimem/ogr_shape_90.shp') lyr = ds.CreateLayer('ogr_shape_90') @@ -4279,8 +3566,7 @@ def ogr_shape_90(): ds = ogr.Open('/vsimem/ogr_shape_90.shp') lyr = ds.GetLayer(0) - if lyr.GetFeatureCount() != 1: - return 'fail' + assert lyr.GetFeatureCount() == 1 # Now it is consistent f = gdal.VSIFOpenL('/vsimem/ogr_shape_90.shx', 'rb+') @@ -4290,18 +3576,15 @@ def ogr_shape_90(): ds = ogr.Open('/vsimem/ogr_shape_90.shp') lyr = ds.GetLayer(0) - if lyr.GetFeatureCount() != 1024 * 1024: - return 'fail' + assert lyr.GetFeatureCount() == 1024 * 1024 ds = None - return 'success' - ############################################################################### # Test reading XYM geometries but with missing M array (#6317) -def ogr_shape_91(): +def test_ogr_shape_91(): ds = ogr.Open('data/arcm_without_m.shp') lyr = ds.GetLayer(0) @@ -4313,47 +3596,36 @@ def ogr_shape_91(): for _ in lyr: pass - return 'success' - + ############################################################################### # Test reading multipoint Z geometries without M -def ogr_shape_92(): +def test_ogr_shape_92(): ds = ogr.Open('data/multipointz_without_m.shp') lyr = ds.GetLayer(0) f = lyr.GetNextFeature() wkt = f.GetGeometryRef().ExportToIsoWkt() - if wkt != 'MULTIPOINT Z ((0 1 2),(3 4 5))': - gdaltest.post_reason('fail') - print(wkt) - return 'fail' - - return 'success' + assert wkt == 'MULTIPOINT Z ((0 1 2),(3 4 5))' ############################################################################### # Test reading point Z geometries without M -def ogr_shape_93(): +def test_ogr_shape_93(): ds = ogr.Open('data/pointz_without_m.shp') lyr = ds.GetLayer(0) f = lyr.GetNextFeature() wkt = f.GetGeometryRef().ExportToIsoWkt() - if wkt != 'POINT Z (1 2 3)': - gdaltest.post_reason('fail') - print(wkt) - return 'fail' - - return 'success' + assert wkt == 'POINT Z (1 2 3)' ############################################################################### # Test SHPT creation option / CreateLayer(geom_type = xxx) -def ogr_shape_94(): +def test_ogr_shape_94(): tests = [["POINT", ogr.wkbPoint, "POINT (1 2)"], ["POINTM", ogr.wkbPointM, "POINT M (1 2 3)"], @@ -4395,10 +3667,8 @@ def ogr_shape_94(): else: lyr = ds.CreateLayer('ogr_shape_94', geom_type=geom_type) test_lyr_geom_type = ogr.GT_Flatten(geom_type) != ogr.wkbMultiLineString and ogr.GT_Flatten(geom_type) != ogr.wkbMultiPolygon - if test_lyr_geom_type and lyr.GetGeomType() != geom_type: - gdaltest.post_reason('fail') - print(i, shpt, geom_type, wkt, lyr.GetGeomType()) - return 'fail' + assert not test_lyr_geom_type or lyr.GetGeomType() == geom_type, \ + (i, shpt, geom_type, wkt, lyr.GetGeomType()) f = ogr.Feature(lyr.GetLayerDefn()) f.SetGeometry(ogr.CreateGeometryFromWkt(wkt)) lyr.CreateFeature(f) @@ -4406,75 +3676,51 @@ def ogr_shape_94(): ds = None ds = ogr.Open('/vsimem/ogr_shape_94.shp') lyr = ds.GetLayer(0) - if test_lyr_geom_type and lyr.GetGeomType() != geom_type: - gdaltest.post_reason('fail') - print(shpt, geom_type, wkt, lyr.GetGeomType()) - return 'fail' + assert not test_lyr_geom_type or lyr.GetGeomType() == geom_type, \ + (shpt, geom_type, wkt, lyr.GetGeomType()) f = lyr.GetNextFeature() if f.GetGeometryRef().ExportToIsoWkt() != wkt: if expected_fail: print('FIXME!:', i, shpt, geom_type, wkt, f.GetGeometryRef().ExportToIsoWkt()) else: - gdaltest.post_reason('fail') - print(i, shpt, geom_type, wkt, f.GetGeometryRef().ExportToIsoWkt()) - return 'fail' + pytest.fail(i, shpt, geom_type, wkt, f.GetGeometryRef().ExportToIsoWkt()) ds = None ogr.GetDriverByName('ESRI Shapefile').DeleteDataSource('/vsimem/ogr_shape_94.shp') - return 'success' - + ############################################################################### # Test demoting of ZM to Z when the M values are nodata -def ogr_shape_95(): +def test_ogr_shape_95(): ds = gdal.OpenEx('data/pointzm_with_all_nodata_m.shp') lyr = ds.GetLayer(0) - if lyr.GetGeomType() != ogr.wkbPoint25D: - gdaltest.post_reason('fail') - print(lyr.GetGeomType()) - return 'fail' + assert lyr.GetGeomType() == ogr.wkbPoint25D f = lyr.GetNextFeature() - if f.GetGeometryRef().ExportToIsoWkt() != 'POINT Z (1 2 3)': - gdaltest.post_reason('fail') - print(lyr.GetGeomType()) - return 'fail' + assert f.GetGeometryRef().ExportToIsoWkt() == 'POINT Z (1 2 3)', lyr.GetGeomType() ds = gdal.OpenEx('data/pointzm_with_all_nodata_m.shp', open_options=['ADJUST_GEOM_TYPE=NO']) lyr = ds.GetLayer(0) - if lyr.GetGeomType() != ogr.wkbPointZM: - gdaltest.post_reason('fail') - print(lyr.GetGeomType()) - return 'fail' + assert lyr.GetGeomType() == ogr.wkbPointZM f = lyr.GetNextFeature() - if ogrtest.check_feature_geometry(f, ogr.CreateGeometryFromWkt('POINT ZM (1 2 3 -1.79769313486232e+308)')) != 0: - gdaltest.post_reason('fail') - print(f.GetGeometryRef().ExportToIsoWkt()) - return 'fail' + assert ogrtest.check_feature_geometry(f, ogr.CreateGeometryFromWkt('POINT ZM (1 2 3 -1.79769313486232e+308)')) == 0, \ + f.GetGeometryRef().ExportToIsoWkt() # The shape with a non nodata M is the second one ds = gdal.OpenEx('data/pointzm_with_one_valid_m.shp', open_options=['ADJUST_GEOM_TYPE=FIRST_SHAPE']) lyr = ds.GetLayer(0) - if lyr.GetGeomType() != ogr.wkbPoint25D: - gdaltest.post_reason('fail') - print(lyr.GetGeomType()) - return 'fail' + assert lyr.GetGeomType() == ogr.wkbPoint25D ds = gdal.OpenEx('data/pointzm_with_one_valid_m.shp', open_options=['ADJUST_GEOM_TYPE=ALL_SHAPES']) lyr = ds.GetLayer(0) - if lyr.GetGeomType() != ogr.wkbPointZM: - gdaltest.post_reason('fail') - print(lyr.GetGeomType()) - return 'fail' - - return 'success' + assert lyr.GetGeomType() == ogr.wkbPointZM ############################################################################### # Test updating a XYM shapefile (#6331) -def ogr_shape_96(): +def test_ogr_shape_96(): ds = ogr.GetDriverByName('ESRI Shapefile').CreateDataSource('/vsimem/ogr_shape_96.shp') lyr = ds.CreateLayer('ogr_shape_96') @@ -4486,10 +3732,7 @@ def ogr_shape_96(): ds = ogr.Open('/vsimem/ogr_shape_96.shp', update=1) lyr = ds.GetLayer(0) f = lyr.GetNextFeature() - if f.GetGeometryRef().ExportToIsoWkt() != 'POINT M (1 2 3)': - gdaltest.post_reason('fail') - print(f.GetGeometryRef().ExportToIsoWkt()) - return 'fail' + assert f.GetGeometryRef().ExportToIsoWkt() == 'POINT M (1 2 3)' f.SetGeometry(ogr.CreateGeometryFromWkt('POINT M (1 2 4)')) lyr.SetFeature(f) ds = None @@ -4497,21 +3740,16 @@ def ogr_shape_96(): ds = ogr.Open('/vsimem/ogr_shape_96.shp') lyr = ds.GetLayer(0) f = lyr.GetNextFeature() - if f.GetGeometryRef().ExportToIsoWkt() != 'POINT M (1 2 4)': - gdaltest.post_reason('fail') - print(f.GetGeometryRef().ExportToIsoWkt()) - return 'fail' + assert f.GetGeometryRef().ExportToIsoWkt() == 'POINT M (1 2 4)' ds = None ogr.GetDriverByName('ESRI Shapefile').DeleteDataSource('/vsimem/ogr_shape_96.shp') - return 'success' - ############################################################################### # Test updating a XYZM shapefile -def ogr_shape_97(): +def test_ogr_shape_97(): ds = ogr.GetDriverByName('ESRI Shapefile').CreateDataSource('/vsimem/ogr_shape_97.shp') lyr = ds.CreateLayer('ogr_shape_97') @@ -4523,10 +3761,7 @@ def ogr_shape_97(): ds = ogr.Open('/vsimem/ogr_shape_97.shp', update=1) lyr = ds.GetLayer(0) f = lyr.GetNextFeature() - if f.GetGeometryRef().ExportToIsoWkt() != 'POINT ZM (1 2 3 4)': - gdaltest.post_reason('fail') - print(f.GetGeometryRef().ExportToIsoWkt()) - return 'fail' + assert f.GetGeometryRef().ExportToIsoWkt() == 'POINT ZM (1 2 3 4)' f.SetGeometry(ogr.CreateGeometryFromWkt('POINT ZM (1 2 5 6)')) lyr.SetFeature(f) ds = None @@ -4534,24 +3769,19 @@ def ogr_shape_97(): ds = ogr.Open('/vsimem/ogr_shape_97.shp') lyr = ds.GetLayer(0) f = lyr.GetNextFeature() - if f.GetGeometryRef().ExportToIsoWkt() != 'POINT ZM (1 2 5 6)': - gdaltest.post_reason('fail') - print(f.GetGeometryRef().ExportToIsoWkt()) - return 'fail' + assert f.GetGeometryRef().ExportToIsoWkt() == 'POINT ZM (1 2 5 6)' ds = None ogr.GetDriverByName('ESRI Shapefile').DeleteDataSource('/vsimem/ogr_shape_97.shp') - return 'success' - ############################################################################### # Test restore function when .shx file is missing -def ogr_shape_98(): +def test_ogr_shape_98(): if gdaltest.shape_ds is None: - return 'skip' + pytest.skip() gdal.SetConfigOption('SHAPE_RESTORE_SHX', 'TRUE') shutil.copy('data/can_caps.shp', 'tmp/can_caps.shp') @@ -4559,9 +3789,7 @@ def ogr_shape_98(): shp_ds = ogr.Open('tmp/can_caps.shp', update=1) shp_lyr = shp_ds.GetLayer(0) - if shp_lyr.GetFeatureCount() != 13: - gdaltest.post_reason('Got wrong number of features.') - return 'fail' + assert shp_lyr.GetFeatureCount() == 13, 'Got wrong number of features.' shp_lyr = None shp_ds = None @@ -4574,17 +3802,13 @@ def ogr_shape_98(): os.remove('tmp/can_caps.shp') os.remove('tmp/can_caps.shx') - if ref_shx != got_shx: - gdaltest.post_reason('Rebuilt shx is different from original shx.') - return 'fail' - - return 'success' + assert ref_shx == got_shx, 'Rebuilt shx is different from original shx.' ############################################################################### # Import TOWGS84 from EPSG when possible (#6485) -def ogr_shape_99(): +def test_ogr_shape_99(): ds = ogr.GetDriverByName('ESRI Shapefile').CreateDataSource('/vsimem/ogr_shape_99.shp') lyr = ds.CreateLayer('ogr_shape_99') @@ -4620,20 +3844,15 @@ def ogr_shape_99(): AUTHORITY["EPSG","21781"]]""" ds = None - if got_wkt != expected_wkt: - gdaltest.post_reason('Projections differ') - print(got_wkt) - return 'fail' + assert got_wkt == expected_wkt, 'Projections differ' ogr.GetDriverByName('ESRI Shapefile').DeleteDataSource('/vsimem/ogr_shape_99.shp') - return 'success' - ############################################################################### # Test REPACK with both implementations -def ogr_shape_100(): +def test_ogr_shape_100(): old_val = gdal.GetConfigOption('OGR_SHAPE_PACK_IN_PLACE') @@ -4671,46 +3890,26 @@ def ogr_shape_100(): gdal.SetConfigOption('OGR_SHAPE_PACK_IN_PLACE', old_val) - if gdal.GetLastErrorMsg() != '': - gdaltest.post_reason('fail') - print(variant) - return 'fail' + assert gdal.GetLastErrorMsg() == '', variant for ext in ['dbf', 'shp', 'shx', 'cpg']: - if gdal.VSIStatL('tmp/ogr_shape_100_packed.' + ext) is not None: - gdaltest.post_reason('fail') - print(variant) - print(ext) - return 'fail' + assert gdal.VSIStatL('tmp/ogr_shape_100_packed.' + ext) is None, variant f = lyr.GetFeature(0) if f['foo'] != '2' or f.GetGeometryRef().ExportToWkt() != 'LINESTRING (1 1,2 2,3 3)': - gdaltest.post_reason('fail') - print(variant) f.DumpReadable() - return 'fail' + pytest.fail(variant) with gdaltest.error_handler(): f = lyr.GetFeature(1) - if f is not None: - gdaltest.post_reason('fail') - print(variant) - return 'fail' + assert f is None, variant lyr.ResetReading() - if lyr.GetFeatureCount() != 1: - gdaltest.post_reason('fail') - print(variant) - return 'fail' + assert lyr.GetFeatureCount() == 1, variant f = lyr.GetNextFeature() if f['foo'] != '2' or f.GetGeometryRef().ExportToWkt() != 'LINESTRING (1 1,2 2,3 3)': - gdaltest.post_reason('fail') - print(variant) f.DumpReadable() - return 'fail' + pytest.fail(variant) f = lyr.GetNextFeature() - if f is not None: - gdaltest.post_reason('fail') - print(variant) - return 'fail' + assert f is None, variant f = ogr.Feature(lyr.GetLayerDefn()) f.SetGeometry(ogr.CreateGeometryFromWkt('LINESTRING (3 3,4 4,5 5,6 6)')) f.SetField('foo', '3') @@ -4720,38 +3919,27 @@ def ogr_shape_100(): ds = ogr.Open('tmp/ogr_shape_100.shp') lyr = ds.GetLayer(0) - if lyr.GetFeatureCount() != 2: - gdaltest.post_reason('fail') - print(variant) - return 'fail' + assert lyr.GetFeatureCount() == 2, variant f = lyr.GetNextFeature() if f['foo'] != '2' or f.GetGeometryRef().ExportToWkt() != 'LINESTRING (1 1,2 2,3 3)': - gdaltest.post_reason('fail') - print(variant) f.DumpReadable() - return 'fail' + pytest.fail(variant) f = lyr.GetNextFeature() if f['foo'] != '3' or f.GetGeometryRef().ExportToWkt() != 'LINESTRING (3 3,4 4,5 5,6 6)': - gdaltest.post_reason('fail') - print(variant) f.DumpReadable() - return 'fail' + pytest.fail(variant) f = lyr.GetNextFeature() - if f is not None: - gdaltest.post_reason('fail') - print(variant) - return 'fail' + assert f is None, variant ds = None ogr.GetDriverByName('ESRI Shapefile').DeleteDataSource('tmp/ogr_shape_100.shp') - return 'success' - + ############################################################################### # Test auto repack -def ogr_shape_101(): +def test_ogr_shape_101(): for i in range(2): @@ -4774,30 +3962,19 @@ def ogr_shape_101(): ds = None else: ds.SyncToDisk() - if lyr.GetFeatureCount() != 1: - gdaltest.post_reason('fail') - print(i) - return 'fail' + assert lyr.GetFeatureCount() == 1, i # No-op ds.ExecuteSQL('REPACK ogr_shape_101') ds_read = ogr.Open('/vsimem/ogr_shape_101.shp') lyr = ds_read.GetLayer(0) - if lyr.GetFeatureCount() != 1: - gdaltest.post_reason('fail') - print(i) - return 'fail' + assert lyr.GetFeatureCount() == 1, i f = lyr.GetNextFeature() if f.GetFID() != 0 or f['foo'] != '2' or f.GetGeometryRef().ExportToWkt() != 'LINESTRING (1 1,2 2,3 3)': - gdaltest.post_reason('fail') - print(i) f.DumpReadable() - return 'fail' + pytest.fail(i) f = lyr.GetNextFeature() - if f is not None: - gdaltest.post_reason('fail') - print(i) - return 'fail' + assert f is None, i ds = None ds_read = None @@ -4818,21 +3995,13 @@ def ogr_shape_101(): ds = ogr.Open('/vsimem/ogr_shape_101.shp') lyr = ds.GetLayer(0) - if lyr.GetFeatureCount() != 1: - gdaltest.post_reason('fail') - print(i) - return 'fail' + assert lyr.GetFeatureCount() == 1, i f = lyr.GetNextFeature() if f.GetFID() != 0 or f['foo'] != '3' or f.GetGeometryRef().ExportToWkt() != 'LINESTRING (3 3,4 4,5 5,6 6)': - gdaltest.post_reason('fail') - print(i) f.DumpReadable() - return 'fail' + pytest.fail(i) f = lyr.GetNextFeature() - if f is not None: - gdaltest.post_reason('fail') - print(i) - return 'fail' + assert f is None, i ds = None # Test disabling auto-repack on update @@ -4848,28 +4017,22 @@ def ogr_shape_101(): ds = ogr.Open('/vsimem/ogr_shape_101.shp') lyr = ds.GetLayer(0) - if lyr.GetFeatureCount() != 2: - gdaltest.post_reason('fail') - print(i) - return 'fail' + assert lyr.GetFeatureCount() == 2, i f = lyr.GetNextFeature() if f.GetFID() != 1 or f['foo'] != '4': - gdaltest.post_reason('fail') - print(i) f.DumpReadable() - return 'fail' + pytest.fail(i) ds = None ogr.GetDriverByName('ESRI Shapefile').DeleteDataSource('/vsimem/ogr_shape_101.shp') - return 'success' - + ############################################################################### # Test reading invalid .prj -def ogr_shape_102(): +def test_ogr_shape_102(): ds = ogr.GetDriverByName('ESRI Shapefile').CreateDataSource('/vsimem/ogr_shape_102.shp') lyr = ds.CreateLayer('ogr_shape_102', geom_type=ogr.wkbPoint) @@ -4881,8 +4044,6 @@ def ogr_shape_102(): ds = None ogr.GetDriverByName('ESRI Shapefile').DeleteDataSource('/vsimem/ogr_shape_102.shp') - return 'success' - ############################################################################### # Test handling of EOF character @@ -4910,7 +4071,7 @@ def check_EOF(filename, expected=True): return True -def ogr_shape_103(): +def test_ogr_shape_103(): filename = '/vsimem/ogr_shape_103.dbf' @@ -4925,10 +4086,7 @@ def ogr_shape_103(): lyr = ds.CreateLayer('ogr_shape_103', geom_type=ogr.wkbNone, options=options) ds = None - if not check_EOF(filename, expected=expected): - gdaltest.post_reason('fail') - print(options) - return 'fail' + assert check_EOF(filename, expected=expected), options # Add field ds = gdal.OpenEx(filename, gdal.OF_UPDATE, open_options=options) @@ -4936,9 +4094,7 @@ def ogr_shape_103(): lyr.CreateField(ogr.FieldDefn('foo', ogr.OFTString)) ds = None - if not check_EOF(filename, expected=expected): - gdaltest.post_reason('fail') - return 'fail' + assert check_EOF(filename, expected=expected) # Add record ds = gdal.OpenEx(filename, gdal.OF_UPDATE, open_options=options) @@ -4946,9 +4102,7 @@ def ogr_shape_103(): lyr.CreateFeature(ogr.Feature(lyr.GetLayerDefn())) ds = None - if not check_EOF(filename, expected=expected): - gdaltest.post_reason('fail') - return 'fail' + assert check_EOF(filename, expected=expected) # Add another field ds = gdal.OpenEx(filename, gdal.OF_UPDATE, open_options=options) @@ -4956,9 +4110,7 @@ def ogr_shape_103(): lyr.CreateField(ogr.FieldDefn('foo2', ogr.OFTString)) ds = None - if not check_EOF(filename, expected=expected): - gdaltest.post_reason('fail') - return 'fail' + assert check_EOF(filename, expected=expected) # Grow a field ds = gdal.OpenEx(filename, gdal.OF_UPDATE, open_options=options) @@ -4969,9 +4121,7 @@ def ogr_shape_103(): lyr.AlterFieldDefn(0, fd, ogr.ALTER_ALL_FLAG) ds = None - if not check_EOF(filename, expected=expected): - gdaltest.post_reason('fail') - return 'fail' + assert check_EOF(filename, expected=expected) # Reorder fields ds = gdal.OpenEx(filename, gdal.OF_UPDATE, open_options=options) @@ -4979,9 +4129,7 @@ def ogr_shape_103(): lyr.ReorderFields([1, 0]) ds = None - if not check_EOF(filename, expected=expected): - gdaltest.post_reason('fail') - return 'fail' + assert check_EOF(filename, expected=expected) # Shrink a field ds = gdal.OpenEx(filename, gdal.OF_UPDATE, open_options=options) @@ -4992,9 +4140,7 @@ def ogr_shape_103(): lyr.AlterFieldDefn(0, fd, ogr.ALTER_ALL_FLAG) ds = None - if not check_EOF(filename, expected=expected): - gdaltest.post_reason('fail') - return 'fail' + assert check_EOF(filename, expected=expected) # Remove a field ds = gdal.OpenEx(filename, gdal.OF_UPDATE, open_options=options) @@ -5002,9 +4148,7 @@ def ogr_shape_103(): lyr.DeleteField(0) ds = None - if not check_EOF(filename, expected=expected): - gdaltest.post_reason('fail') - return 'fail' + assert check_EOF(filename, expected=expected) ogr.GetDriverByName('ESRI Shapefile').DeleteDataSource(filename) @@ -5014,9 +4158,7 @@ def ogr_shape_103(): lyr.CreateField(ogr.FieldDefn('foo', ogr.OFTString)) ds = None - if not check_EOF(filename, expected=expected): - gdaltest.post_reason('fail') - return 'fail' + assert check_EOF(filename, expected=expected) ogr.GetDriverByName('ESRI Shapefile').DeleteDataSource(filename) # Create file with two records @@ -5027,9 +4169,7 @@ def ogr_shape_103(): lyr.CreateFeature(ogr.Feature(lyr.GetLayerDefn())) ds = None - if not check_EOF(filename, expected=expected): - gdaltest.post_reason('fail') - return 'fail' + assert check_EOF(filename, expected=expected) # Test editing a record that is not the last one ds = gdal.OpenEx(filename, gdal.OF_UPDATE, open_options=options) @@ -5037,9 +4177,7 @@ def ogr_shape_103(): lyr.SetFeature(lyr.GetNextFeature()) ds = None - if not check_EOF(filename, expected=expected): - gdaltest.post_reason('fail') - return 'fail' + assert check_EOF(filename, expected=expected) # Test editing the last record ds = gdal.OpenEx(filename, gdal.OF_UPDATE, open_options=options) @@ -5048,9 +4186,7 @@ def ogr_shape_103(): lyr.SetFeature(lyr.GetNextFeature()) ds = None - if not check_EOF(filename, expected=expected): - gdaltest.post_reason('fail') - return 'fail' + assert check_EOF(filename, expected=expected) ogr.GetDriverByName('ESRI Shapefile').DeleteDataSource(filename) @@ -5065,9 +4201,7 @@ def ogr_shape_103(): lyr.CreateFeature(ogr.Feature(lyr.GetLayerDefn())) ds.FlushCache() - if not check_EOF(filename): - gdaltest.post_reason('fail') - return 'fail' + assert check_EOF(filename) ds = None ogr.GetDriverByName('ESRI Shapefile').DeleteDataSource(filename) @@ -5085,19 +4219,15 @@ def ogr_shape_103(): ds = None # To document our current behaviour. Could make sense to be changed. - if not check_EOF(filename, expected=False): - gdaltest.post_reason('fail') - return 'fail' + assert check_EOF(filename, expected=False) ogr.GetDriverByName('ESRI Shapefile').DeleteDataSource(filename) - return 'success' - ############################################################################### # Test writing MULTIPATCH -def ogr_shape_104(): +def test_ogr_shape_104(): for (wkt, lyr_type, options, expected_wkt) in \ [['TIN Z (((0 0 0,0 1 2,1 1 3,0 0 0)))', ogr.wkbUnknown, [], None], @@ -5130,39 +4260,30 @@ def ogr_shape_104(): lyr = ds.GetLayer(0) f = lyr.GetNextFeature() if f.GetGeometryRef().ExportToIsoWkt() != expected_wkt: - gdaltest.post_reason('fail') - print(wkt, lyr_type, options) f.DumpReadable() - return 'fail' + pytest.fail(wkt, lyr_type, options) ds = None ogr.GetDriverByName('ESRI Shapefile').DeleteDataSource(filename) - return 'success' - + ############################################################################### # Test reading .dbf with substantial padding after last field definition. -def ogr_shape_105(): +def test_ogr_shape_105(): ds = ogr.Open('data/padding_after_field_defns.dbf') lyr = ds.GetLayer(0) - if lyr.GetLayerDefn().GetFieldCount() != 2: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.GetLayerDefn().GetFieldCount() == 2 f = lyr.GetNextFeature() - if f['id'] != '1' or f['foo'] != '2': - gdaltest.post_reason('fail') - return 'fail' - - return 'success' + assert f['id'] == '1' and f['foo'] == '2' ############################################################################### # Test that rewriting the last shape reuses the space it took. (#6787) -def ogr_shape_106(): +def test_ogr_shape_106(): shape_drv = ogr.GetDriverByName('ESRI Shapefile') ds = shape_drv.CreateDataSource('/vsimem/ogr_shape_106.shp') @@ -5174,10 +4295,7 @@ def ogr_shape_106(): ds = None size = gdal.VSIStatL('/vsimem/ogr_shape_106.shp').size - if size != 188: - gdaltest.post_reason('fail') - print(size) - return 'fail' + assert size == 188 ds = ogr.Open('/vsimem/ogr_shape_106.shp', update=1) lyr = ds.GetLayer(0) @@ -5188,15 +4306,10 @@ def ogr_shape_106(): ds = None size = gdal.VSIStatL('/vsimem/ogr_shape_106.shp').size - if size != 188 + 2 * 8: - gdaltest.post_reason('fail') - print(size) - return 'fail' + assert size == 188 + 2 * 8 shape_drv.DeleteDataSource('/vsimem/ogr_shape_106.shp') - return 'success' - ############################################################################### # Compare to VSI*L file @@ -5239,7 +4352,7 @@ def is_same(filename1, filename2, verbose=True): # Test that multiple edition of the last shape works properly (#7031) -def ogr_shape_107(): +def test_ogr_shape_107(): layer_name = 'ogr_shape_107' filename = '/vsimem/' + layer_name + '.shp' @@ -5269,20 +4382,16 @@ def ogr_shape_107(): lyr = ds.GetLayer(0) f = lyr.GetNextFeature() if f.GetGeometryRef().ExportToWkt() != 'LINESTRING (1 2,3 4)': - gdaltest.post_reason('fail') f.DumpReadable() - return'fail' + pytest.fail() f = lyr.GetNextFeature() if f.GetGeometryRef().ExportToWkt() != 'LINESTRING (5 6)': - gdaltest.post_reason('fail') f.DumpReadable() - return'fail' + pytest.fail() ds = None gdal.VectorTranslate(copy_filename, filename) - if not is_same(copy_filename, filename): - gdaltest.post_reason('fail') - return'fail' + assert is_same(copy_filename, filename) shape_drv.DeleteDataSource(copy_filename) shape_drv.DeleteDataSource(filename) @@ -5305,44 +4414,34 @@ def ogr_shape_107(): lyr = ds.GetLayer(0) f = lyr.GetNextFeature() if f.GetGeometryRef().ExportToWkt() != 'LINESTRING (1 2,3 4)': - gdaltest.post_reason('fail') f.DumpReadable() - return'fail' + pytest.fail() ds = None gdal.VectorTranslate(copy_filename, filename) - if not is_same(copy_filename, filename): - gdaltest.post_reason('fail') - return'fail' + assert is_same(copy_filename, filename) shape_drv.DeleteDataSource(copy_filename) shape_drv.DeleteDataSource(filename) - return 'success' - ############################################################################### # Test spatial + attribute filter -def ogr_shape_108(): +def test_ogr_shape_108(): ds = ogr.Open('data/poly.shp') lyr = ds.GetLayer(0) lyr.SetSpatialFilterRect(479750.6875, 4764702.0, 479750.6875, 4764702.0) expected_fc = lyr.GetFeatureCount() lyr.SetAttributeFilter("1=1") - if lyr.GetFeatureCount() != expected_fc: - gdaltest.post_reason('fail') - print(lyr.GetFeatureCount(), expected_fc) - return'fail' - - return 'success' + assert lyr.GetFeatureCount() == expected_fc ############################################################################### # Test writing invalid polygon -def ogr_shape_109(): +def test_ogr_shape_109(): layer_name = 'ogr_shape_109' filename = '/vsimem/' + layer_name + '.shp' @@ -5359,13 +4458,11 @@ def ogr_shape_109(): ds = None shape_drv.DeleteDataSource(filename) - return 'success' - ############################################################################### -def ogr_shape_110_write_invalid_multipatch(): +def test_ogr_shape_110_write_invalid_multipatch(): layer_name = 'ogr_shape_110' filename = '/vsimem/' + layer_name + '.shp' @@ -5381,13 +4478,11 @@ def ogr_shape_110_write_invalid_multipatch(): ds = None shape_drv.DeleteDataSource(filename) - return 'success' - ############################################################################### -def ogr_shape_111_delete_field_no_record(): +def test_ogr_shape_111_delete_field_no_record(): layer_name = 'ogr_shape_111_delete_field_no_record' filename = '/vsimem/' + layer_name + '.shp' @@ -5405,21 +4500,18 @@ def ogr_shape_111_delete_field_no_record(): ds = ogr.Open(filename) lyr = ds.GetLayer(0) - if lyr.GetLayerDefn().GetFieldDefn(0).GetName() != 'field_1': - return 'fail' + assert lyr.GetLayerDefn().GetFieldDefn(0).GetName() == 'field_1' ds = None shape_drv.DeleteDataSource(filename) - return 'success' - ############################################################################### -def ogr_shape_cleanup(): +def test_ogr_shape_cleanup(): if gdaltest.shape_ds is None: - return 'skip' + pytest.skip() gdaltest.shape_ds = None @@ -5453,132 +4545,3 @@ def ogr_shape_cleanup(): shape_drv.DeleteDataSource('/vsimem/ogr_shape_90.shp') if os.path.exists('tmp/ogr_shape_100.shp'): shape_drv.DeleteDataSource('tmp/ogr_shape_100.shp') - - return 'success' - - -gdaltest_list = [ - ogr_shape_1, - ogr_shape_2, - ogr_shape_3, - ogr_shape_4, - ogr_shape_5, - ogr_shape_6, - ogr_shape_7, - ogr_shape_8, - ogr_shape_9, - ogr_shape_10, - ogr_shape_11, - ogr_shape_12, - ogr_shape_13, - ogr_shape_14, - ogr_shape_15, - ogr_shape_16, - ogr_shape_16_1, - ogr_shape_17, - ogr_shape_18, - ogr_shape_19, - ogr_shape_20, - ogr_shape_21, - ogr_shape_22, - ogr_shape_23, - ogr_shape_24, - ogr_shape_25, - ogr_shape_26, - ogr_shape_27, - ogr_shape_28, - ogr_shape_29, - ogr_shape_30, - ogr_shape_31, - ogr_shape_32, - ogr_shape_33, - ogr_shape_34, - ogr_shape_35, - ogr_shape_36, - ogr_shape_37, - ogr_shape_37_bis, - ogr_shape_38, - ogr_shape_39, - ogr_shape_40, - ogr_shape_41, - ogr_shape_42, - ogr_shape_43, - # ogr_shape_44, - ogr_shape_45, - ogr_shape_46, - ogr_shape_47, - ogr_shape_48, - ogr_shape_49, - ogr_shape_50, - ogr_shape_51, - ogr_shape_52, - ogr_shape_53, - ogr_shape_54, - ogr_shape_55, - ogr_shape_56, - ogr_shape_57, - ogr_shape_58, - ogr_shape_59, - ogr_shape_60, - ogr_shape_61, - ogr_shape_62, - ogr_shape_63, - ogr_shape_64, - ogr_shape_65, - ogr_shape_66, - ogr_shape_67, - ogr_shape_68, - ogr_shape_69, - ogr_shape_70, - ogr_shape_71, - ogr_shape_72, - ogr_shape_73, - ogr_shape_74, - ogr_shape_75, - ogr_shape_76, - ogr_shape_77, - ogr_shape_78, - ogr_shape_79, - ogr_shape_80, - ogr_shape_81, - ogr_shape_82, - ogr_shape_83, - ogr_shape_84, - ogr_shape_85, - ogr_shape_86, - ogr_shape_87, - ogr_shape_88, - ogr_shape_89, - ogr_shape_90, - ogr_shape_91, - ogr_shape_92, - ogr_shape_93, - ogr_shape_94, - ogr_shape_95, - ogr_shape_96, - ogr_shape_97, - ogr_shape_98, - ogr_shape_99, - ogr_shape_100, - ogr_shape_101, - ogr_shape_102, - ogr_shape_103, - ogr_shape_104, - ogr_shape_105, - ogr_shape_106, - ogr_shape_107, - ogr_shape_108, - ogr_shape_109, - ogr_shape_110_write_invalid_multipatch, - ogr_shape_111_delete_field_no_record, - ogr_shape_cleanup] - -# gdaltest_list = [ ogr_shape_107 ] - -if __name__ == '__main__': - - gdaltest.setup_run('ogr_shape') - - gdaltest.run_tests(gdaltest_list) - - sys.exit(gdaltest.summarize()) diff --git a/autotest/ogr/ogr_shape_qix.py b/autotest/ogr/ogr_shape_qix.py index 5a9a20203619..b32b53dfd5e3 100755 --- a/autotest/ogr/ogr_shape_qix.py +++ b/autotest/ogr/ogr_shape_qix.py @@ -29,12 +29,9 @@ # DEALINGS IN THE SOFTWARE. ############################################################################### -import sys import random -sys.path.append('../pymod') -import gdaltest from osgeo import ogr ############################################################################### @@ -61,9 +58,8 @@ def check_qix_non_overlapping_geoms(lyr): lyr.ResetReading() feat = lyr.GetNextFeature() got_geom = feat.GetGeometryRef() - if got_geom.Equals(geom) == 0: - gdaltest.post_reason('expected %s. got %s' % (geom.ExportToWkt(), got_geom.ExportToWkt())) - return 'fail' + assert got_geom.Equals(geom) != 0, \ + ('expected %s. got %s' % (geom.ExportToWkt(), got_geom.ExportToWkt())) # Get all geoms in a single gulp. We do not use exactly the extent bounds, because # there is an optimization in the shapefile driver to skip the spatial index in that @@ -71,11 +67,7 @@ def check_qix_non_overlapping_geoms(lyr): lyr.SetSpatialFilterRect(extents[0] + 0.001, extents[2] + 0.001, extents[1] - 0.001, extents[3] - 0.001) lyr.ResetReading() fc = lyr.GetFeatureCount() - if fc != fc_ref: - gdaltest.post_reason('expected %d. got %d' % (fc_ref, fc)) - return 'fail' - - return 'success' + assert fc == fc_ref, ('expected %d. got %d' % (fc_ref, fc)) ############################################################################### @@ -88,7 +80,7 @@ def build_rectangle_from_point(x, y, radius=0.1): # Test geoms on a 10x10 grid -def ogr_shape_qix_1(): +def test_ogr_shape_qix_1(): shape_drv = ogr.GetDriverByName('ESRI Shapefile') ds = shape_drv.CreateDataSource('/vsimem/ogr_shape_qix.shp') @@ -117,7 +109,7 @@ def ogr_shape_qix_1(): # Test geoms on a 100x100 grid -def ogr_shape_qix_2(): +def test_ogr_shape_qix_2(): shape_drv = ogr.GetDriverByName('ESRI Shapefile') ds = shape_drv.CreateDataSource('/vsimem/ogr_shape_qix.shp') @@ -146,7 +138,7 @@ def ogr_shape_qix_2(): # Test 2 separated regions of 10x10 geoms -def ogr_shape_qix_3(): +def test_ogr_shape_qix_3(): shape_drv = ogr.GetDriverByName('ESRI Shapefile') ds = shape_drv.CreateDataSource('/vsimem/ogr_shape_qix.shp') @@ -208,9 +200,7 @@ def check_qix_random_geoms(lyr): found_geom = True else: feat = lyr.GetNextFeature() - if not found_geom: - gdaltest.post_reason('did not find geometry for %s' % (geom.ExportToWkt())) - return 'fail' + assert found_geom, ('did not find geometry for %s' % (geom.ExportToWkt())) # Get all geoms in a single gulp. We do not use exactly the extent bounds, because # there is an optimization in the shapefile driver to skip the spatial index in that @@ -218,11 +208,7 @@ def check_qix_random_geoms(lyr): lyr.SetSpatialFilterRect(extents[0] + 0.001, extents[2] + 0.001, extents[1] - 0.001, extents[3] - 0.001) lyr.ResetReading() fc = lyr.GetFeatureCount() - if fc != fc_ref: - gdaltest.post_reason('expected %d. got %d' % (fc_ref, fc)) - return 'fail' - - return 'success' + assert fc == fc_ref, ('expected %d. got %d' % (fc_ref, fc)) ############################################################################### @@ -235,7 +221,7 @@ def build_rectangle(x1, y1, x2, y2): # Test random geometries -def ogr_shape_qix_4(): +def test_ogr_shape_qix_4(): shape_drv = ogr.GetDriverByName('ESRI Shapefile') ds = shape_drv.CreateDataSource('/vsimem/ogr_shape_qix.shp') @@ -273,17 +259,4 @@ def ogr_shape_qix_4(): return ret -gdaltest_list = [ - ogr_shape_qix_1, - ogr_shape_qix_2, - ogr_shape_qix_3, - ogr_shape_qix_4, -] - -if __name__ == '__main__': - - gdaltest.setup_run('ogr_shape_qix') - - gdaltest.run_tests(gdaltest_list) - sys.exit(gdaltest.summarize()) diff --git a/autotest/ogr/ogr_shape_sbn.py b/autotest/ogr/ogr_shape_sbn.py index b76eecdd2a1b..8c5fe8894ffa 100755 --- a/autotest/ogr/ogr_shape_sbn.py +++ b/autotest/ogr/ogr_shape_sbn.py @@ -29,13 +29,12 @@ # DEALINGS IN THE SOFTWARE. ############################################################################### -import sys import os -sys.path.append('../pymod') import gdaltest from osgeo import ogr +import pytest ############################################################################### # @@ -67,9 +66,7 @@ def search_all_features(lyr): found_geom = True else: feat = lyr.GetNextFeature() - if not found_geom: - gdaltest.post_reason('did not find geometry for %s' % (geom.ExportToWkt())) - return 'fail' + assert found_geom, ('did not find geometry for %s' % (geom.ExportToWkt())) # Get all geoms in a single gulp. We do not use exactly the extent bounds, because # there is an optimization in the shapefile driver to skip the spatial index in that @@ -98,20 +95,16 @@ def search_all_features(lyr): lyr.ResetReading() fc = fc + lyr.GetFeatureCount() - if fc != fc_ref: - gdaltest.post_reason('layer %s: expected %d. got %d' % (lyr.GetName(), fc_ref, fc)) - return 'fail' - - return 'success' + assert fc == fc_ref, ('layer %s: expected %d. got %d' % (lyr.GetName(), fc_ref, fc)) ############################################################################### # Test -def ogr_shape_sbn_1(): +def test_ogr_shape_sbn_1(): if not gdaltest.download_file('http://pubs.usgs.gov/sim/3194/contents/Cochiti_shapefiles.zip', 'Cochiti_shapefiles.zip'): - return 'skip' + pytest.skip() try: os.stat('tmp/cache/CochitiDamShapeFiles/CochitiBoundary.shp') @@ -121,39 +114,25 @@ def ogr_shape_sbn_1(): try: os.stat('tmp/cache/CochitiDamShapeFiles/CochitiBoundary.shp') except OSError: - return 'skip' + pytest.skip() except OSError: - return 'skip' + pytest.skip() ds = ogr.Open('tmp/cache/CochitiDamShapeFiles') for i in range(ds.GetLayerCount()): lyr = ds.GetLayer(i) - ret = search_all_features(lyr) - if ret != 'success': - return ret - - return 'success' + search_all_features(lyr) + ############################################################################### # Test -def ogr_shape_sbn_2(): +def test_ogr_shape_sbn_2(): ds = ogr.Open('data/CoHI_GCS12.shp') lyr = ds.GetLayer(0) return search_all_features(lyr) -gdaltest_list = [ - ogr_shape_sbn_1, - ogr_shape_sbn_2, -] - -if __name__ == '__main__': - - gdaltest.setup_run('ogr_shape_sbn') - - gdaltest.run_tests(gdaltest_list) - sys.exit(gdaltest.summarize()) diff --git a/autotest/ogr/ogr_sosi.py b/autotest/ogr/ogr_sosi.py index a9dba25b82aa..496f4051c16e 100755 --- a/autotest/ogr/ogr_sosi.py +++ b/autotest/ogr/ogr_sosi.py @@ -29,44 +29,30 @@ # DEALINGS IN THE SOFTWARE. ############################################################################### -import sys from osgeo import ogr -sys.path.append('../pymod') import gdaltest +import pytest ############################################################################### -def ogr_sosi_1(): +def test_ogr_sosi_1(): if ogr.GetDriverByName('SOSI') is None: - return 'skip' + pytest.skip() if not gdaltest.download_file('http://trac.osgeo.org/gdal/raw-attachment/ticket/3638/20BygnAnlegg.SOS', '20BygnAnlegg.SOS'): - return 'skip' + pytest.skip() import test_cli_utilities if test_cli_utilities.get_test_ogrsf_path() is None: - return 'skip' + pytest.skip() ret = gdaltest.runexternal(test_cli_utilities.get_test_ogrsf_path() + ' -ro tmp/cache/20BygnAnlegg.SOS') - if ret.find('INFO') == -1 or ret.find('ERROR') != -1: - print(ret) - return 'fail' + assert ret.find('INFO') != -1 and ret.find('ERROR') == -1 - return 'success' -gdaltest_list = [ - ogr_sosi_1] - -if __name__ == '__main__': - - gdaltest.setup_run('ogr_sosi') - - gdaltest.run_tests(gdaltest_list) - - sys.exit(gdaltest.summarize()) diff --git a/autotest/ogr/ogr_sql_rfc28.py b/autotest/ogr/ogr_sql_rfc28.py index 65f7318b3593..1c1142996c32 100755 --- a/autotest/ogr/ogr_sql_rfc28.py +++ b/autotest/ogr/ogr_sql_rfc28.py @@ -30,240 +30,216 @@ # DEALINGS IN THE SOFTWARE. ############################################################################### -import sys -sys.path.append('../pymod') from osgeo import gdal from osgeo import ogr import gdaltest import ogrtest +import pytest ############################################################################### # Test an expression with a left side value and right side column and an \ # expression for the value. -def ogr_rfc28_1(): +def test_ogr_rfc28_1(): gdaltest.ds = ogr.Open('data') gdaltest.lyr = gdaltest.ds.GetLayerByName('poly') gdaltest.lyr.SetAttributeFilter('160+7 > eas_id') count = gdaltest.lyr.GetFeatureCount() - if count != 3: - gdaltest.post_reason('Got wrong count with GetFeatureCount() - %d, expecting 3' % count) - return 'fail' - - return 'success' + assert count == 3, \ + ('Got wrong count with GetFeatureCount() - %d, expecting 3' % count) ############################################################################### # Test CONCAT operator in the context of a WHERE clause. -def ogr_rfc28_2(): +def test_ogr_rfc28_2(): gdaltest.lyr.SetAttributeFilter("CONCAT('x',PRFEDEA) = 'x35043423'") count = gdaltest.lyr.GetFeatureCount() - if count != 1: - gdaltest.post_reason('Got wrong count with GetFeatureCount() - %d, expecting 1' % count) - return 'fail' + assert count == 1, \ + ('Got wrong count with GetFeatureCount() - %d, expecting 1' % count) gdaltest.lyr.SetAttributeFilter('') - return 'success' ############################################################################### # Test '+' operator on strings. -def ogr_rfc28_3(): +def test_ogr_rfc28_3(): gdaltest.lyr.SetAttributeFilter("'x'+PRFEDEA = 'x35043423'") count = gdaltest.lyr.GetFeatureCount() - if count != 1: - gdaltest.post_reason('Got wrong count with GetFeatureCount() - %d, expecting 1' % count) - return 'fail' + assert count == 1, \ + ('Got wrong count with GetFeatureCount() - %d, expecting 1' % count) gdaltest.lyr.SetAttributeFilter('') - return 'success' ############################################################################### # Test '%' operator. -def ogr_rfc28_4(): +def test_ogr_rfc28_4(): gdaltest.lyr.SetAttributeFilter("EAS_ID % 5 = 1") count = gdaltest.lyr.GetFeatureCount() - if count != 2: - gdaltest.post_reason('Got wrong count with GetFeatureCount() - %d, expecting 2' % count) - return 'fail' + assert count == 2, \ + ('Got wrong count with GetFeatureCount() - %d, expecting 2' % count) gdaltest.lyr.SetAttributeFilter('') - return 'success' ############################################################################### # Test '%' operator. -def ogr_rfc28_5(): +def test_ogr_rfc28_5(): gdaltest.lyr.SetAttributeFilter("EAS_ID % 5 = 1") count = gdaltest.lyr.GetFeatureCount() - if count != 2: - gdaltest.post_reason('Got wrong count with GetFeatureCount() - %d, expecting 2' % count) - return 'fail' + assert count == 2, \ + ('Got wrong count with GetFeatureCount() - %d, expecting 2' % count) gdaltest.lyr.SetAttributeFilter('') - return 'success' ############################################################################### # Test support for a quoted field name. -def ogr_rfc28_6(): +def test_ogr_rfc28_6(): gdaltest.lyr.SetAttributeFilter("\"EAS_ID\" = 166") count = gdaltest.lyr.GetFeatureCount() - if count != 1: - gdaltest.post_reason('Got wrong count with GetFeatureCount() - %d, expecting 1' % count) - return 'fail' + assert count == 1, \ + ('Got wrong count with GetFeatureCount() - %d, expecting 1' % count) gdaltest.lyr.SetAttributeFilter('') - return 'success' ############################################################################### # test with distinguished name for field in where clause. -def ogr_rfc28_7_wrong_quoting(): +def test_ogr_rfc28_7_wrong_quoting(): with gdaltest.error_handler(): ql = gdaltest.ds.ExecuteSQL("select eas_id from idlink where \"idlink.eas_id\" = 166") count = ql.GetFeatureCount() - if count != 1: - gdaltest.post_reason('Got wrong count with GetFeatureCount() - %d, expecting 1' % count) - return 'fail' + assert count == 1, \ + ('Got wrong count with GetFeatureCount() - %d, expecting 1' % count) gdaltest.ds.ReleaseResultSet(ql) - return 'success' -def ogr_rfc28_7_good_quoting(): +def test_ogr_rfc28_7_good_quoting(): ql = gdaltest.ds.ExecuteSQL("select eas_id from idlink where idlink.eas_id = 166") count = ql.GetFeatureCount() - if count != 1: - gdaltest.post_reason('Got wrong count with GetFeatureCount() - %d, expecting 1' % count) - return 'fail' + assert count == 1, \ + ('Got wrong count with GetFeatureCount() - %d, expecting 1' % count) gdaltest.ds.ReleaseResultSet(ql) - return 'success' ############################################################################### # test with distinguished name for field in target columns. -def ogr_rfc28_8_wrong_quoting(): +def test_ogr_rfc28_8_wrong_quoting(): with gdaltest.error_handler(): ql = gdaltest.ds.ExecuteSQL("select \"idlink.eas_id\" from idlink where \"idlink.eas_id\" = 166") count = ql.GetFeatureCount() - if count != 1: - gdaltest.post_reason('Got wrong count with GetFeatureCount() - %d, expecting 1' % count) - return 'fail' + assert count == 1, \ + ('Got wrong count with GetFeatureCount() - %d, expecting 1' % count) expect = [166] tr = ogrtest.check_features_against_list(ql, 'idlink.eas_id', expect) gdaltest.ds.ReleaseResultSet(ql) - return 'success' if tr else 'fail' + assert tr -def ogr_rfc28_8_good_quoting(): +def test_ogr_rfc28_8_good_quoting(): ql = gdaltest.ds.ExecuteSQL("select idlink.eas_id from idlink where idlink.eas_id = 166") count = ql.GetFeatureCount() - if count != 1: - gdaltest.post_reason('Got wrong count with GetFeatureCount() - %d, expecting 1' % count) - return 'fail' + assert count == 1, \ + ('Got wrong count with GetFeatureCount() - %d, expecting 1' % count) expect = [166] tr = ogrtest.check_features_against_list(ql, 'idlink.eas_id', expect) gdaltest.ds.ReleaseResultSet(ql) - return 'success' if tr else 'fail' + assert tr ############################################################################### # Test with quoted funky (non-identifier) name. -def ogr_rfc28_9(): +def test_ogr_rfc28_9(): ds = ogr.Open('data/oddname.csv') lyr = ds.GetLayer(0) lyr.SetAttributeFilter("\"Funky @Name\" = '32'") count = lyr.GetFeatureCount() - if count != 1: - gdaltest.post_reason('Got wrong count with GetFeatureCount() - %d, expecting 1' % count) - return 'fail' + assert count == 1, \ + ('Got wrong count with GetFeatureCount() - %d, expecting 1' % count) expect = ['8902'] tr = ogrtest.check_features_against_list(lyr, 'PRIME_MERIDIAN_CODE', expect) - return 'success' if tr else 'fail' + assert tr # TODO: unparse quoting? ############################################################################### # test quoted names for funky columns in SELECT WHERE (confirm unparse quoting) -def ogr_rfc28_10(): +def test_ogr_rfc28_10(): ds = ogr.Open('data/oddname.csv') lyr = ds.ExecuteSQL("SELECT * from oddname where \"Funky @Name\" = '32'") count = lyr.GetFeatureCount() - if count != 1: - gdaltest.post_reason('Got wrong count with GetFeatureCount() - %d, expecting 1' % count) - return 'fail' + assert count == 1, \ + ('Got wrong count with GetFeatureCount() - %d, expecting 1' % count) expect = ['8902'] tr = ogrtest.check_features_against_list(lyr, 'PRIME_MERIDIAN_CODE', expect) ds.ReleaseResultSet(lyr) - return 'success' if tr else 'fail' + assert tr ############################################################################### # test quoted funky names in output columns list. -def ogr_rfc28_11(): +def test_ogr_rfc28_11(): ds = ogr.Open('data/oddname.csv') lyr = ds.ExecuteSQL("SELECT \"Funky @Name\" from oddname where prime_meridian_code = '8902'") count = lyr.GetFeatureCount() - if count != 1: - gdaltest.post_reason('Got wrong count with GetFeatureCount() - %d, expecting 1' % count) - return 'fail' + assert count == 1, \ + ('Got wrong count with GetFeatureCount() - %d, expecting 1' % count) expect = ['32'] tr = ogrtest.check_features_against_list(lyr, 'Funky @Name', expect) ds.ReleaseResultSet(lyr) - return 'success' if tr else 'fail' + assert tr ############################################################################### # test selecting fixed string fields. -def ogr_rfc28_12(): +def test_ogr_rfc28_12(): lyr = gdaltest.ds.ExecuteSQL("SELECT 'constant string', 'other' as abc, eas_id from idlink where eas_id = 165") count = lyr.GetFeatureCount() - if count != 1: - gdaltest.post_reason('Got wrong count with GetFeatureCount() - %d, expecting 1' % count) - return 'fail' + assert count == 1, \ + ('Got wrong count with GetFeatureCount() - %d, expecting 1' % count) expect = ['other'] tr = ogrtest.check_features_against_list(lyr, 'abc', expect) @@ -280,28 +256,26 @@ def ogr_rfc28_12(): gdaltest.ds.ReleaseResultSet(lyr) - return 'success' if tr else 'fail' + assert tr ############################################################################### # Test SUBSTR operator in the context of a WHERE clause. -def ogr_rfc28_13(): +def test_ogr_rfc28_13(): gdaltest.lyr.SetAttributeFilter("SUBSTR(PRFEDEA,5,4) = '3423'") count = gdaltest.lyr.GetFeatureCount() - if count != 1: - gdaltest.post_reason('Got wrong count with GetFeatureCount() - %d, expecting 1' % count) - return 'fail' + assert count == 1, \ + ('Got wrong count with GetFeatureCount() - %d, expecting 1' % count) gdaltest.lyr.SetAttributeFilter('') - return 'success' ############################################################################### # test selecting fixed string fields. -def ogr_rfc28_14(): +def test_ogr_rfc28_14(): lyr = gdaltest.ds.ExecuteSQL("SELECT SUBSTR(PRFEDEA,4,5) from poly where eas_id in (168,179)") expect = ['43411', '43423'] @@ -309,13 +283,13 @@ def ogr_rfc28_14(): gdaltest.ds.ReleaseResultSet(lyr) - return 'success' if tr else 'fail' + assert tr ############################################################################### # Test CONCAT with more than two arguments. -def ogr_rfc28_15(): +def test_ogr_rfc28_15(): lyr = gdaltest.ds.ExecuteSQL("SELECT CONCAT(PRFEDEA,' ',CAST(EAS_ID AS CHARACTER(3))) from poly where eas_id in (168,179)") expect = ['35043411 168', '35043423 179'] @@ -323,13 +297,13 @@ def ogr_rfc28_15(): gdaltest.ds.ReleaseResultSet(lyr) - return 'success' if tr else 'fail' + assert tr ############################################################################### # Test parse support for negative numbers (#3724) -def ogr_rfc28_16(): +def test_ogr_rfc28_16(): lyr = gdaltest.ds.ExecuteSQL("SELECT -1, 3--1,3*-1,2e-1,3-1 from poly where eas_id = 168") expect = [-1] @@ -353,13 +327,13 @@ def ogr_rfc28_16(): gdaltest.ds.ReleaseResultSet(lyr) - return 'success' if tr else 'fail' + assert tr ############################################################################### # Test evaluation of division - had a problem with type conversion. -def ogr_rfc28_17(): +def test_ogr_rfc28_17(): lyr = gdaltest.ds.ExecuteSQL("SELECT 5/2, 5.0/2.0, 5/2.0, 5.0/2 from poly where eas_id = 168") expect = [2] @@ -379,13 +353,13 @@ def ogr_rfc28_17(): gdaltest.ds.ReleaseResultSet(lyr) - return 'success' if tr else 'fail' + assert tr ############################################################################### # Test some special distinct cases. -def ogr_rfc28_18(): +def test_ogr_rfc28_18(): lyr = gdaltest.ds.ExecuteSQL("SELECT COUNT(distinct id), COUNT(distinct id) as \"xx\" from departs") expect = [1] @@ -397,13 +371,13 @@ def ogr_rfc28_18(): gdaltest.ds.ReleaseResultSet(lyr) - return 'success' if tr else 'fail' + assert tr ############################################################################### # Verify that NOT IN ( list ) works -def ogr_rfc28_19(): +def test_ogr_rfc28_19(): sql_lyr = gdaltest.ds.ExecuteSQL('select * from poly where eas_id not in (158,165)') @@ -411,17 +385,14 @@ def ogr_rfc28_19(): gdaltest.ds.ReleaseResultSet(sql_lyr) - if count != 8: - gdaltest.post_reason('Got wrong count with GetFeatureCount() - %d, expecting 8' % count) - return 'fail' - - return 'success' + assert count == 8, \ + ('Got wrong count with GetFeatureCount() - %d, expecting 8' % count) ############################################################################### # Verify arithmetic operator precedence and unary minus -def ogr_rfc28_20(): +def test_ogr_rfc28_20(): ds = ogr.GetDriverByName("Memory").CreateDataSource("my_ds") lyr = ds.CreateLayer("my_layer") @@ -433,19 +404,16 @@ def ogr_rfc28_20(): sql_lyr = ds.ExecuteSQL('select -intfield + 1 + 2 * 3 + 5 - 3 * 2 from my_layer') feat = sql_lyr.GetNextFeature() - if feat.GetField('FIELD_1') != 4: - return 'fail' + assert feat.GetField('FIELD_1') == 4 ds.ReleaseResultSet(sql_lyr) ds = None - return 'success' - ############################################################################### # Verify that BETWEEN works -def ogr_rfc28_21(): +def test_ogr_rfc28_21(): sql_lyr = gdaltest.ds.ExecuteSQL('select * from poly where eas_id between 165 and 169') @@ -459,17 +427,14 @@ def ogr_rfc28_21(): gdaltest.ds.ReleaseResultSet(sql_lyr) - if count_between != count_ge_and_le: - gdaltest.post_reason('Got wrong count with GetFeatureCount() - %d, expecting %d' % (count_between, count_ge_and_le)) - return 'fail' - - return 'success' + assert count_between == count_ge_and_le, \ + ('Got wrong count with GetFeatureCount() - %d, expecting %d' % (count_between, count_ge_and_le)) ############################################################################### # Verify that NOT BETWEEN works -def ogr_rfc28_22(): +def test_ogr_rfc28_22(): sql_lyr = gdaltest.ds.ExecuteSQL('select * from poly where eas_id not between 165 and 169') @@ -483,17 +448,14 @@ def ogr_rfc28_22(): gdaltest.ds.ReleaseResultSet(sql_lyr) - if count_not_between != count_not_ge_and_le: - gdaltest.post_reason('Got wrong count with GetFeatureCount() - %d, expecting %d' % (count_not_between, count_not_ge_and_le)) - return 'fail' - - return 'success' + assert count_not_between == count_not_ge_and_le, \ + ('Got wrong count with GetFeatureCount() - %d, expecting %d' % (count_not_between, count_not_ge_and_le)) ############################################################################### # Verify that NOT LIKE works -def ogr_rfc28_23(): +def test_ogr_rfc28_23(): sql_lyr = gdaltest.ds.ExecuteSQL("select * from poly where PRFEDEA NOT LIKE '35043413'") @@ -507,17 +469,14 @@ def ogr_rfc28_23(): gdaltest.ds.ReleaseResultSet(sql_lyr) - if count_not_like1 != count_not_like2: - gdaltest.post_reason('Got wrong count with GetFeatureCount() - %d, expecting %d' % (count_not_like1, count_not_like2)) - return 'fail' - - return 'success' + assert count_not_like1 == count_not_like2, \ + ('Got wrong count with GetFeatureCount() - %d, expecting %d' % (count_not_like1, count_not_like2)) ############################################################################### # Verify that NULL works -def ogr_rfc28_24(): +def test_ogr_rfc28_24(): sql_lyr = gdaltest.ds.ExecuteSQL("select *, NULL, NULL as nullstrfield, CAST(null as integer) as nullintfield from poly where NULL IS NULL") @@ -526,33 +485,30 @@ def ogr_rfc28_24(): if feat.IsFieldSet('FIELD_4'): feat.DumpReadable() gdaltest.ds.ReleaseResultSet(sql_lyr) - return 'fail' + pytest.fail() if feat.IsFieldSet('nullstrfield'): feat.DumpReadable() gdaltest.ds.ReleaseResultSet(sql_lyr) - return 'fail' + pytest.fail() if feat.IsFieldSet('nullintfield'): feat.DumpReadable() gdaltest.ds.ReleaseResultSet(sql_lyr) - return 'fail' + pytest.fail() count = sql_lyr.GetFeatureCount() gdaltest.ds.ReleaseResultSet(sql_lyr) - if count != 10: - gdaltest.post_reason('Got wrong count with GetFeatureCount() - %d, expecting %d' % (count, 10)) - return 'fail' - - return 'success' + assert count == 10, \ + ('Got wrong count with GetFeatureCount() - %d, expecting %d' % (count, 10)) ############################################################################### # Verify that LIKE pattern ESCAPE escape_char works -def ogr_rfc28_25(): +def test_ogr_rfc28_25(): sql_lyr = gdaltest.ds.ExecuteSQL("select * from poly where prfedea LIKE 'x35043408' ESCAPE 'x'") @@ -560,17 +516,14 @@ def ogr_rfc28_25(): gdaltest.ds.ReleaseResultSet(sql_lyr) - if count != 1: - gdaltest.post_reason('Got wrong count with GetFeatureCount() - %d, expecting 1' % count) - return 'fail' - - return 'success' + assert count == 1, \ + ('Got wrong count with GetFeatureCount() - %d, expecting 1' % count) ############################################################################### # Test SUBSTR with negative offsets -def ogr_rfc28_26(): +def test_ogr_rfc28_26(): lyr = gdaltest.ds.ExecuteSQL("SELECT SUBSTR(PRFEDEA,-2) from poly where eas_id in (168,179)") expect = ['11', '23'] @@ -578,13 +531,13 @@ def ogr_rfc28_26(): gdaltest.ds.ReleaseResultSet(lyr) - return 'success' if tr else 'fail' + assert tr ############################################################################### # Test that we correctly let floating point values as floating point, and not as integer (#4634)" -def ogr_rfc28_27(): +def test_ogr_rfc28_27(): lyr = gdaltest.ds.ExecuteSQL("SELECT * FROM poly WHERE 4000000000. > 2000000000.") @@ -592,7 +545,7 @@ def ogr_rfc28_27(): gdaltest.ds.ReleaseResultSet(lyr) - return 'success' if count == 10 else 'fail' + assert count == 10 ############################################################################### # Extensive test of the evaluation of arithmetic and logical operators @@ -604,14 +557,11 @@ def ogr_rfc28_28_test(formula, expected_val): got = f.GetField(0) gdaltest.ds.ReleaseResultSet(sql_lyr) - if got != expected_val: - gdaltest.post_reason('bad result for %s : %s' % (formula, str(expected_val))) - return 'fail' - - return 'success' + assert got == expected_val, \ + ('bad result for %s : %s' % (formula, str(expected_val))) -def ogr_rfc28_28(): +def test_ogr_rfc28_28(): operators = ['+', '-', '*', '/', '%'] formulas = [] @@ -690,13 +640,12 @@ def ogr_rfc28_28(): if ret == 'fail': return ret - return 'success' - + ############################################################################### # Test behaviour of binary operations when one operand is a NULL value -def ogr_rfc28_29(): +def test_ogr_rfc28_29(): lyr = gdaltest.ds.ExecuteSQL("select * from idlink where (eas_id + cast(null as integer)) is not null or eas_id = 170 + cast(null as integer) or (eas_id + cast(null as float)) is not null or eas_id = 170.0 + cast(null as float)") @@ -704,13 +653,13 @@ def ogr_rfc28_29(): gdaltest.ds.ReleaseResultSet(lyr) - return 'success' if count == 0 else 'fail' + assert count == 0 ############################################################################### # Test behaviour of binary operations on strings when one operand is a NULL value -def ogr_rfc28_30(): +def test_ogr_rfc28_30(): lyr = gdaltest.ds.ExecuteSQL("select * from idlink2 where F1 <> 'foo' or concat(F1,cast(null as character(32))) is not null") @@ -718,13 +667,13 @@ def ogr_rfc28_30(): gdaltest.ds.ReleaseResultSet(lyr) - return 'success' if count == 0 else 'fail' + assert count == 0 ############################################################################### # Test UNION ALL -def ogr_rfc28_31(): +def test_ogr_rfc28_31(): lyr = gdaltest.ds.ExecuteSQL("select * from idlink union all select * from idlink2") @@ -732,13 +681,13 @@ def ogr_rfc28_31(): gdaltest.ds.ReleaseResultSet(lyr) - return 'success' if count != 6 + 7 else 'fail' + assert count != 6 + 7 ############################################################################### # Test UNION ALL with parenthesis -def ogr_rfc28_32(): +def test_ogr_rfc28_32(): lyr = gdaltest.ds.ExecuteSQL("(select * from idlink) union all (select * from idlink2 order by eas_id)") @@ -746,86 +695,78 @@ def ogr_rfc28_32(): gdaltest.ds.ReleaseResultSet(lyr) - return 'success' if count != 6 + 7 else 'fail' + assert count != 6 + 7 ############################################################################### # Test lack of end-of-string character -def ogr_rfc28_33(): +def test_ogr_rfc28_33(): gdal.PushErrorHandler('CPLQuietErrorHandler') lyr = gdaltest.ds.ExecuteSQL("select * from idlink where name='foo") gdal.PopErrorHandler() - return 'success' if lyr is None else 'fail' + assert lyr is None ############################################################################### # Test wildcard expansion of an unknown table. -def ogr_rfc28_34(): +def test_ogr_rfc28_34(): gdal.PushErrorHandler('CPLQuietErrorHandler') lyr = gdaltest.ds.ExecuteSQL("select foo.* from idlink") gdal.PopErrorHandler() - if gdal.GetLastErrorMsg().find( - 'Table foo not recognised from foo.* definition') != 0: - print(gdal.GetLastErrorMsg()) - return 'fail' + assert (gdal.GetLastErrorMsg().find( + 'Table foo not recognised from foo.* definition') == 0) - return 'success' if lyr is None else 'fail' + assert lyr is None ############################################################################### # Test selecting more than one distinct -def ogr_rfc28_35(): +def test_ogr_rfc28_35(): gdal.PushErrorHandler('CPLQuietErrorHandler') lyr = gdaltest.ds.ExecuteSQL("select distinct eas_id, distinct name from idlink") gdal.PopErrorHandler() - if gdal.GetLastErrorMsg().find('SQL Expression Parsing Error') != 0: - print(gdal.GetLastErrorMsg()) - return 'fail' + assert gdal.GetLastErrorMsg().find('SQL Expression Parsing Error') == 0 - return 'success' if lyr is None else 'fail' + assert lyr is None ############################################################################### # Test selecting more than one distinct -def ogr_rfc28_35_bis(): +def test_ogr_rfc28_35_bis(): gdal.PushErrorHandler('CPLQuietErrorHandler') lyr = gdaltest.ds.ExecuteSQL("select distinct eas_id, name from idlink") gdal.PopErrorHandler() - if gdal.GetLastErrorMsg().find('SELECT DISTINCT not supported on multiple columns') != 0: - print(gdal.GetLastErrorMsg()) - return 'fail' + assert gdal.GetLastErrorMsg().find('SELECT DISTINCT not supported on multiple columns') == 0 - return 'success' if lyr is None else 'fail' + assert lyr is None ############################################################################### # Test selecting more than one distinct -def ogr_rfc28_35_ter(): +def test_ogr_rfc28_35_ter(): gdal.PushErrorHandler('CPLQuietErrorHandler') lyr = gdaltest.ds.ExecuteSQL("select distinct * from idlink") gdal.PopErrorHandler() - if gdal.GetLastErrorMsg().find('SELECT DISTINCT not supported on multiple columns') != 0: - print(gdal.GetLastErrorMsg()) - return 'fail' + assert gdal.GetLastErrorMsg().find('SELECT DISTINCT not supported on multiple columns') == 0 - return 'success' if lyr is None else 'fail' + assert lyr is None ############################################################################### # Test ORDER BY a DISTINCT list by more than one key -def ogr_rfc28_36(): +def test_ogr_rfc28_36(): gdal.ErrorReset() gdal.PushErrorHandler('CPLQuietErrorHandler') @@ -833,17 +774,14 @@ def ogr_rfc28_36(): if lyr is not None: lyr.GetNextFeature() gdal.PopErrorHandler() - if gdal.GetLastErrorMsg().find("Can't ORDER BY a DISTINCT list by more than one key") != 0: - print(gdal.GetLastErrorMsg()) - return 'fail' + assert gdal.GetLastErrorMsg().find("Can't ORDER BY a DISTINCT list by more than one key") == 0 gdaltest.ds.ReleaseResultSet(lyr) - return 'success' ############################################################################### # Test different fields for ORDER BY and DISTINCT -def ogr_rfc28_37(): +def test_ogr_rfc28_37(): gdal.ErrorReset() gdal.PushErrorHandler('CPLQuietErrorHandler') @@ -851,45 +789,34 @@ def ogr_rfc28_37(): if lyr is not None: lyr.GetNextFeature() gdal.PopErrorHandler() - if gdal.GetLastErrorMsg().find("Only selected DISTINCT field can be used for ORDER BY") != 0: - print(gdal.GetLastErrorMsg()) - return 'fail' + assert gdal.GetLastErrorMsg().find("Only selected DISTINCT field can be used for ORDER BY") == 0 gdaltest.ds.ReleaseResultSet(lyr) - return 'success' ############################################################################### # Test invalid SUBSTR -def ogr_rfc28_38(): +def test_ogr_rfc28_38(): gdal.ErrorReset() gdal.PushErrorHandler('CPLQuietErrorHandler') lyr = gdaltest.ds.ExecuteSQL("SELECT SUBSTR(PRFEDEA) from poly") gdal.PopErrorHandler() - if gdal.GetLastErrorMsg().find("Expected 2 or 3 arguments to SUBSTR(), but got 1") != 0: - print(gdal.GetLastErrorMsg()) - return 'fail' - if lyr is not None: - return 'fail' + assert gdal.GetLastErrorMsg().find("Expected 2 or 3 arguments to SUBSTR(), but got 1") == 0 + assert lyr is None gdal.ErrorReset() gdal.PushErrorHandler('CPLQuietErrorHandler') lyr = gdaltest.ds.ExecuteSQL("SELECT SUBSTR(1,2) from poly") gdal.PopErrorHandler() - if gdal.GetLastErrorMsg().find("Wrong argument type for SUBSTR()") != 0: - print(gdal.GetLastErrorMsg()) - return 'fail' - if lyr is not None: - return 'fail' - - return 'success' + assert gdal.GetLastErrorMsg().find("Wrong argument type for SUBSTR()") == 0 + assert lyr is None ############################################################################### # Test COUNT() on a 0-row result -def ogr_rfc28_39(): +def test_ogr_rfc28_39(): lyr = gdaltest.ds.ExecuteSQL("SELECT COUNT(*) from poly where 0 = 1") @@ -897,13 +824,13 @@ def ogr_rfc28_39(): gdaltest.ds.ReleaseResultSet(lyr) - return 'success' if tr else 'fail' + assert tr ############################################################################### # Test MIN(), MAX() and AVG() on a date (#5333) -def ogr_rfc28_40(): +def test_ogr_rfc28_40(): ds = ogr.GetDriverByName('Memory').CreateDataSource('') lyr = ds.CreateLayer('test') @@ -924,21 +851,17 @@ def ogr_rfc28_40(): gdaltest.ds.ReleaseResultSet(lyr) - if not tr: - return 'fail' + assert tr - if not tr2: - return 'fail' + assert tr2 - if not tr3: - return 'fail' - return 'success' + assert tr3 ############################################################################### # Verify that SELECT * works on a layer with a field that has a dot character (#5379) -def ogr_rfc28_41(): +def test_ogr_rfc28_41(): ds = ogr.GetDriverByName("Memory").CreateDataSource("my_ds") lyr = ds.CreateLayer("my_layer") @@ -950,27 +873,21 @@ def ogr_rfc28_41(): sql_lyr = ds.ExecuteSQL('select * from my_layer') feat = sql_lyr.GetNextFeature() - if feat.GetField('a.b') != 2: - gdaltest.post_reason('fail') - return 'fail' + assert feat.GetField('a.b') == 2 ds.ReleaseResultSet(sql_lyr) sql_lyr = ds.ExecuteSQL('select l.* from my_layer l') feat = sql_lyr.GetNextFeature() - if feat.GetField('l.a.b') != 2: - gdaltest.post_reason('fail') - return 'fail' + assert feat.GetField('l.a.b') == 2 ds.ReleaseResultSet(sql_lyr) ds = None - return 'success' - ############################################################################### # Test boolean and int16 support -def ogr_rfc28_42(): +def test_ogr_rfc28_42(): ds = ogr.GetDriverByName('Memory').CreateDataSource('') lyr = ds.CreateLayer('test') @@ -990,73 +907,41 @@ def ogr_rfc28_42(): # To b OR NOT to b... that's the question lyr = ds.ExecuteSQL("SELECT b, NOT b, 1 + b, CAST(1 AS BOOLEAN), b IS NOT NULL, short, 1 + short, CAST(1 + short as SMALLINT) FROM test WHERE b OR NOT b") - if lyr.GetLayerDefn().GetFieldDefn(0).GetSubType() != ogr.OFSTBoolean: - gdaltest.post_reason('fail') - return 'fail' - if lyr.GetLayerDefn().GetFieldDefn(1).GetSubType() != ogr.OFSTBoolean: - gdaltest.post_reason('fail') - return 'fail' - if lyr.GetLayerDefn().GetFieldDefn(2).GetSubType() != ogr.OFSTNone: - gdaltest.post_reason('fail') - return 'fail' - if lyr.GetLayerDefn().GetFieldDefn(3).GetSubType() != ogr.OFSTBoolean: - gdaltest.post_reason('fail') - return 'fail' - if lyr.GetLayerDefn().GetFieldDefn(4).GetSubType() != ogr.OFSTBoolean: - gdaltest.post_reason('fail') - return 'fail' - if lyr.GetLayerDefn().GetFieldDefn(5).GetSubType() != ogr.OFSTInt16: - gdaltest.post_reason('fail') - return 'fail' - if lyr.GetLayerDefn().GetFieldDefn(6).GetSubType() != ogr.OFSTNone: - gdaltest.post_reason('fail') - return 'fail' - if lyr.GetLayerDefn().GetFieldDefn(7).GetSubType() != ogr.OFSTInt16: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.GetLayerDefn().GetFieldDefn(0).GetSubType() == ogr.OFSTBoolean + assert lyr.GetLayerDefn().GetFieldDefn(1).GetSubType() == ogr.OFSTBoolean + assert lyr.GetLayerDefn().GetFieldDefn(2).GetSubType() == ogr.OFSTNone + assert lyr.GetLayerDefn().GetFieldDefn(3).GetSubType() == ogr.OFSTBoolean + assert lyr.GetLayerDefn().GetFieldDefn(4).GetSubType() == ogr.OFSTBoolean + assert lyr.GetLayerDefn().GetFieldDefn(5).GetSubType() == ogr.OFSTInt16 + assert lyr.GetLayerDefn().GetFieldDefn(6).GetSubType() == ogr.OFSTNone + assert lyr.GetLayerDefn().GetFieldDefn(7).GetSubType() == ogr.OFSTInt16 f = lyr.GetNextFeature() if f.GetField('b') != 0 or f.GetField(1) != 1 or f.GetField(2) != 1 or \ f.GetField(3) != 1 or f.GetField(4) != 1 or \ f.GetField(5) != 32000 or f.GetField(6) != 32001 or f.GetField(7) != 32001: - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' + pytest.fail() f = lyr.GetNextFeature() if f.GetField('b') != 1 or f.GetField(1) != 0 or f.GetField(2) != 2 or f.GetField(3) != 1 or f.GetField(4) != 1: - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' + pytest.fail() gdaltest.ds.ReleaseResultSet(lyr) lyr = ds.ExecuteSQL("SELECT MIN(b), MAX(b), SUM(b) FROM test") - if lyr.GetLayerDefn().GetFieldDefn(0).GetSubType() != ogr.OFSTBoolean: - gdaltest.post_reason('fail') - return 'fail' - if lyr.GetLayerDefn().GetFieldDefn(1).GetSubType() != ogr.OFSTBoolean: - gdaltest.post_reason('fail') - return 'fail' - if lyr.GetLayerDefn().GetFieldDefn(2).GetSubType() != ogr.OFSTNone: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.GetLayerDefn().GetFieldDefn(0).GetSubType() == ogr.OFSTBoolean + assert lyr.GetLayerDefn().GetFieldDefn(1).GetSubType() == ogr.OFSTBoolean + assert lyr.GetLayerDefn().GetFieldDefn(2).GetSubType() == ogr.OFSTNone f = lyr.GetNextFeature() - if f.GetField('MIN_b') != 0: - gdaltest.post_reason('fail') - return 'fail' - if f.GetField('MAX_b') != 1: - gdaltest.post_reason('fail') - return 'fail' - if f.GetField('SUM_b') != 1: - gdaltest.post_reason('fail') - return 'fail' + assert f.GetField('MIN_b') == 0 + assert f.GetField('MAX_b') == 1 + assert f.GetField('SUM_b') == 1 gdaltest.ds.ReleaseResultSet(lyr) - return 'success' - ############################################################################### # Test integer64 support -def ogr_rfc28_43(): +def test_ogr_rfc28_43(): ds = ogr.GetDriverByName('Memory').CreateDataSource('') lyr = ds.CreateLayer('test') @@ -1071,53 +956,42 @@ def ogr_rfc28_43(): lyr = ds.ExecuteSQL("SELECT 1000000000000, myint64, CAST(1 AS bigint), CAST(100000000000 AS bigint), CAST(1 AS numeric(15,0)) FROM test WHERE myint64 < -9999999999 or myint64 > 9999999999") f = lyr.GetNextFeature() - if lyr.GetLayerDefn().GetFieldDefn(2).GetType() != ogr.OFTInteger64: - gdaltest.post_reason('fail') - return 'fail' - if lyr.GetLayerDefn().GetFieldDefn(3).GetType() != ogr.OFTInteger64: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.GetLayerDefn().GetFieldDefn(2).GetType() == ogr.OFTInteger64 + assert lyr.GetLayerDefn().GetFieldDefn(3).GetType() == ogr.OFTInteger64 if f.GetField(0) != 1000000000000 or f.GetField(1) != -1000000000000 or f.GetField(2) != 1 or f.GetField(3) != 100000000000 or f.GetField(4) != 1.0: - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' + pytest.fail() gdaltest.ds.ReleaseResultSet(lyr) lyr = ds.ExecuteSQL("SELECT MIN(myint64), MAX(myint64), SUM(myint64) FROM test") f = lyr.GetNextFeature() if f.GetField('MIN_myint64') != -1000000000000: - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' + pytest.fail() if f.GetField('MAX_myint64') != 100000000000: - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' + pytest.fail() if f.GetField('SUM_myint64') != -1000000000000 + 100000000000: - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' + pytest.fail() gdaltest.ds.ReleaseResultSet(lyr) lyr = ds.ExecuteSQL("SELECT DISTINCT myint64 FROM test ORDER BY myint64") f = lyr.GetNextFeature() if f.GetField('myint64') != -1000000000000: - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' + pytest.fail() f = lyr.GetNextFeature() if f.GetField('myint64') != 100000000000: - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' + pytest.fail() gdaltest.ds.ReleaseResultSet(lyr) - return 'success' ############################################################################### # Test crazy quoting of table and fields -def ogr_rfc28_44(): +def test_ogr_rfc28_44(): ds = ogr.GetDriverByName('Memory').CreateDataSource('') lyr = ds.CreateLayer('lyr.withpoint') @@ -1135,24 +1009,16 @@ def ogr_rfc28_44(): gdal.ErrorReset() lyr = ds.ExecuteSQL("SELECT * FROM \"lyr.withpoint\" WHERE \"field.withpoint\" = 1") - if gdal.GetLastErrorMsg() != '': - gdaltest.post_reason('fail') - return 'fail' + assert gdal.GetLastErrorMsg() == '' f = lyr.GetNextFeature() - if f is None: - gdaltest.post_reason('fail') - return 'fail' + assert f is not None gdaltest.ds.ReleaseResultSet(lyr) gdal.ErrorReset() lyr = ds.ExecuteSQL("SELECT \"lyr.withpoint\".\"field.withpoint\", \"field.withpoint\" FROM \"lyr.withpoint\" WHERE \"lyr.withpoint\".\"field.withpoint\" = 1") - if gdal.GetLastErrorMsg() != '': - gdaltest.post_reason('fail') - return 'fail' + assert gdal.GetLastErrorMsg() == '' f = lyr.GetNextFeature() - if f is None: - gdaltest.post_reason('fail') - return 'fail' + assert f is not None gdaltest.ds.ReleaseResultSet(lyr) # Test our tolerance against lack of necessary quoting @@ -1160,13 +1026,9 @@ def ogr_rfc28_44(): gdal.PushErrorHandler() lyr = ds.ExecuteSQL("SELECT * FROM \"lyr.withpoint\" WHERE field.withpoint = 1") gdal.PopErrorHandler() - if gdal.GetLastErrorMsg() != 'Passed field name field.withpoint should have been surrounded by double quotes. Accepted since there is no ambiguity...': - gdaltest.post_reason('fail') - return 'fail' + assert gdal.GetLastErrorMsg() == 'Passed field name field.withpoint should have been surrounded by double quotes. Accepted since there is no ambiguity...' f = lyr.GetNextFeature() - if f is None: - gdaltest.post_reason('fail') - return 'fail' + assert f is not None gdaltest.ds.ReleaseResultSet(lyr) # Againg, but in a situation where there IS ambiguity @@ -1178,50 +1040,38 @@ def ogr_rfc28_44(): gdal.PushErrorHandler() lyr = ds.ExecuteSQL("SELECT * FROM \"lyr.withpoint\" JOIN field ON \"lyr.withpoint\".foo = field.id WHERE field.withpoint = 1") gdal.PopErrorHandler() - if gdal.GetLastErrorMsg() != '"field"."withpoint" not recognised as an available field.': - gdaltest.post_reason('fail') - return 'fail' - if lyr is not None: - gdaltest.post_reason('fail') - return 'fail' + assert gdal.GetLastErrorMsg() == '"field"."withpoint" not recognised as an available field.' + assert lyr is None # Test our tolerance against unnecessary quoting gdal.ErrorReset() gdal.PushErrorHandler() lyr = ds.ExecuteSQL("SELECT * FROM \"lyr.withpoint\" f WHERE \"f.foo\" = 2") gdal.PopErrorHandler() - if gdal.GetLastErrorMsg() != 'Passed field name f.foo should NOT have been surrounded by double quotes. Accepted since there is no ambiguity...': - gdaltest.post_reason('fail') - return 'fail' + assert gdal.GetLastErrorMsg() == 'Passed field name f.foo should NOT have been surrounded by double quotes. Accepted since there is no ambiguity...' f = lyr.GetNextFeature() - if f is None: - gdaltest.post_reason('fail') - return 'fail' + assert f is not None gdaltest.ds.ReleaseResultSet(lyr) - return 'success' - ############################################################################### # Test 'FROM table_name AS alias' -def ogr_rfc28_45(): +def test_ogr_rfc28_45(): ql = gdaltest.ds.ExecuteSQL("select eas_id from idlink as il where il.eas_id = 166") count = ql.GetFeatureCount() - if count != 1: - gdaltest.post_reason('Got wrong count with GetFeatureCount() - %d, expecting 1' % count) - return 'fail' + assert count == 1, \ + ('Got wrong count with GetFeatureCount() - %d, expecting 1' % count) gdaltest.ds.ReleaseResultSet(ql) - return 'success' ############################################################################### # Test fid special column and 64 bit -def ogr_rfc28_46(): +def test_ogr_rfc28_46(): ds = ogr.GetDriverByName('Memory').CreateDataSource('') lyr = ds.CreateLayer('lyr') @@ -1241,29 +1091,23 @@ def ogr_rfc28_46(): lyr.CreateFeature(feat) lyr.SetAttributeFilter('fid >= 2500000000') - if lyr.GetFeatureCount() != 2: - gdaltest.post_reason('fail') - print(lyr.GetFeatureCount()) - return 'fail' + assert lyr.GetFeatureCount() == 2 lyr.SetAttributeFilter(None) # Explicit cast of fid to bigint needed in SELECT columns sql_lyr = ds.ExecuteSQL('SELECT CAST(fid AS bigint) AS outfid, val FROM lyr WHERE fid >= 2500000000 ORDER BY fid') f = sql_lyr.GetNextFeature() if f.GetFID() != 2500000000 or f['outfid'] != 2500000000 or f['val'] != 2: - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' + pytest.fail() f = sql_lyr.GetNextFeature() if f.GetFID() != 3000000000 or f['outfid'] != 3000000000 or f['val'] != 1: - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' + pytest.fail() f = sql_lyr.GetNextFeature() if f is not None: - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' + pytest.fail() ds.ReleaseResultSet(sql_lyr) # Explicit cast of fid to bigint no longer needed if the layer is declared OLMD_FID64=YES @@ -1271,161 +1115,108 @@ def ogr_rfc28_46(): sql_lyr = ds.ExecuteSQL('SELECT fid AS outfid, val FROM lyr WHERE fid >= 2500000000 ORDER BY fid') f = sql_lyr.GetNextFeature() if f.GetFID() != 2500000000 or f['outfid'] != 2500000000 or f['val'] != 2: - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' + pytest.fail() ds.ReleaseResultSet(sql_lyr) ds = None - return 'success' - ############################################################################### # Test LIMIT and OFFSET -def ogr_rfc28_47(): +def test_ogr_rfc28_47(): lyr = gdaltest.ds.ExecuteSQL("SELECT * FROM POLY LIMIT 0") tr = ogrtest.check_features_against_list(lyr, 'EAS_ID', []) gdaltest.ds.ReleaseResultSet(lyr) - if not tr: - gdaltest.post_reason('fail') - return 'fail' + assert tr lyr = gdaltest.ds.ExecuteSQL("SELECT * FROM POLY LIMIT 1") - if lyr.GetFeatureCount() != 1: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.GetFeatureCount() == 1 tr = ogrtest.check_features_against_list(lyr, 'EAS_ID', [168]) gdaltest.ds.ReleaseResultSet(lyr) - if not tr: - gdaltest.post_reason('fail') - return 'fail' + assert tr lyr = gdaltest.ds.ExecuteSQL("SELECT * FROM POLY ORDER BY EAS_ID LIMIT 1") - if lyr.GetFeatureCount() != 1: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.GetFeatureCount() == 1 tr = ogrtest.check_features_against_list(lyr, 'EAS_ID', [158]) gdaltest.ds.ReleaseResultSet(lyr) - if not tr: - gdaltest.post_reason('fail') - return 'fail' + assert tr lyr = gdaltest.ds.ExecuteSQL("SELECT * FROM POLY ORDER BY PRFEDEA LIMIT 1") - if lyr.GetFeatureCount() != 1: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.GetFeatureCount() == 1 tr = ogrtest.check_features_against_list(lyr, 'PRFEDEA', ['35043369']) gdaltest.ds.ReleaseResultSet(lyr) - if not tr: - gdaltest.post_reason('fail') - return 'fail' + assert tr lyr = gdaltest.ds.ExecuteSQL("SELECT * FROM POLY WHERE 0 ORDER BY EAS_ID LIMIT 1") - if lyr.GetNextFeature() is not None: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.GetNextFeature() is None gdaltest.ds.ReleaseResultSet(lyr) lyr = gdaltest.ds.ExecuteSQL("SELECT * FROM POLY WHERE EAS_ID = 168 LIMIT 11") - if lyr.GetFeatureCount() != 1: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.GetFeatureCount() == 1 tr = ogrtest.check_features_against_list(lyr, 'EAS_ID', [168]) gdaltest.ds.ReleaseResultSet(lyr) - if not tr: - gdaltest.post_reason('fail') - return 'fail' + assert tr lyr = gdaltest.ds.ExecuteSQL("SELECT * FROM POLY WHERE EAS_ID = 168 OFFSET 0") tr = ogrtest.check_features_against_list(lyr, 'EAS_ID', [168]) gdaltest.ds.ReleaseResultSet(lyr) - if not tr: - gdaltest.post_reason('fail') - return 'fail' + assert tr lyr = gdaltest.ds.ExecuteSQL("SELECT * FROM POLY WHERE EAS_ID = 168 OFFSET 1") - if lyr.GetFeatureCount() != 0: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.GetFeatureCount() == 0 tr = ogrtest.check_features_against_list(lyr, 'EAS_ID', []) gdaltest.ds.ReleaseResultSet(lyr) - if not tr: - gdaltest.post_reason('fail') - return 'fail' + assert tr lyr = gdaltest.ds.ExecuteSQL("SELECT * FROM POLY OFFSET 10") - if lyr.GetFeatureCount() != 0: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.GetFeatureCount() == 0 tr = ogrtest.check_features_against_list(lyr, 'EAS_ID', []) gdaltest.ds.ReleaseResultSet(lyr) - if not tr: - gdaltest.post_reason('fail') - return 'fail' + assert tr lyr = gdaltest.ds.ExecuteSQL("SELECT * FROM POLY OFFSET 8") - if lyr.GetFeatureCount() != 2: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.GetFeatureCount() == 2 tr = ogrtest.check_features_against_list(lyr, 'EAS_ID', [165, 170]) gdaltest.ds.ReleaseResultSet(lyr) - if not tr: - gdaltest.post_reason('fail') - return 'fail' + assert tr lyr = gdaltest.ds.ExecuteSQL("SELECT * FROM POLY LIMIT 1 OFFSET 8") - if lyr.GetFeatureCount() != 1: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.GetFeatureCount() == 1 tr = ogrtest.check_features_against_list(lyr, 'EAS_ID', [165]) gdaltest.ds.ReleaseResultSet(lyr) - if not tr: - gdaltest.post_reason('fail') - return 'fail' + assert tr lyr = gdaltest.ds.ExecuteSQL("SELECT * FROM POLY LIMIT 2 OFFSET 8") lyr.SetNextByIndex(1) f = lyr.GetNextFeature() - if f['EAS_ID'] != 170: - gdaltest.post_reason('fail') - return 'fail' + assert f['EAS_ID'] == 170 f = lyr.GetNextFeature() - if f is not None: - gdaltest.post_reason('fail') - return 'fail' + assert f is None gdaltest.ds.ReleaseResultSet(lyr) lyr = gdaltest.ds.ExecuteSQL("SELECT * FROM POLY ORDER BY EAS_ID DESC LIMIT 2") tr = ogrtest.check_features_against_list(lyr, 'EAS_ID', [179, 173]) gdaltest.ds.ReleaseResultSet(lyr) - if not tr: - gdaltest.post_reason('fail') - return 'fail' + assert tr lyr = gdaltest.ds.ExecuteSQL("SELECT * FROM POLY ORDER BY EAS_ID DESC LIMIT 1 OFFSET 1") tr = ogrtest.check_features_against_list(lyr, 'EAS_ID', [173]) gdaltest.ds.ReleaseResultSet(lyr) - if not tr: - gdaltest.post_reason('fail') - return 'fail' + assert tr lyr = gdaltest.ds.ExecuteSQL("SELECT DISTINCT EAS_ID FROM POLY ORDER BY EAS_ID DESC LIMIT 2 OFFSET 3") tr = ogrtest.check_features_against_list(lyr, 'EAS_ID', [171, 170]) gdaltest.ds.ReleaseResultSet(lyr) - if not tr: - gdaltest.post_reason('fail') - return 'fail' - - return 'success' + assert tr ############################################################################### # Test date/datetime comparisons (#6810) -def ogr_rfc28_48(): +def test_ogr_rfc28_48(): ds = ogr.GetDriverByName('Memory').CreateDataSource('') lyr = ds.CreateLayer('lyr') @@ -1436,108 +1227,68 @@ def ogr_rfc28_48(): lyr.CreateFeature(feat) with gdaltest.error_handler(): - if lyr.SetAttributeFilter('dt >= 2500000000') == 0: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.SetAttributeFilter('dt >= 2500000000') != 0 lyr.SetAttributeFilter("dt >= 'a'") with gdaltest.error_handler(): - if lyr.GetFeatureCount() != 0: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.GetFeatureCount() == 0 lyr.SetAttributeFilter("'a' <= dt") with gdaltest.error_handler(): - if lyr.GetFeatureCount() != 0: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.GetFeatureCount() == 0 lyr.SetAttributeFilter("dt BETWEEN dt AND 'a'") with gdaltest.error_handler(): - if lyr.GetFeatureCount() != 0: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.GetFeatureCount() == 0 lyr.SetAttributeFilter("dt >= '2017/02/17 11:06:34'") - if lyr.GetFeatureCount() != 1: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.GetFeatureCount() == 1 lyr.SetAttributeFilter("dt >= '2017/02/17'") - if lyr.GetFeatureCount() != 1: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.GetFeatureCount() == 1 lyr.SetAttributeFilter("dt >= '2017/02/17 11:06:35'") - if lyr.GetFeatureCount() != 0: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.GetFeatureCount() == 0 lyr.SetAttributeFilter("dt > '2017/02/17 11:06:33'") - if lyr.GetFeatureCount() != 1: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.GetFeatureCount() == 1 lyr.SetAttributeFilter("dt > '2017/02/17 11:06:34'") - if lyr.GetFeatureCount() != 0: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.GetFeatureCount() == 0 lyr.SetAttributeFilter("dt <= '2017/02/17 11:06:34'") - if lyr.GetFeatureCount() != 1: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.GetFeatureCount() == 1 lyr.SetAttributeFilter("dt <= '2017/02/17 11:06:33'") - if lyr.GetFeatureCount() != 0: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.GetFeatureCount() == 0 lyr.SetAttributeFilter("dt < '2017/02/17 11:06:35'") - if lyr.GetFeatureCount() != 1: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.GetFeatureCount() == 1 lyr.SetAttributeFilter("dt < '2017/02/17 11:06:34'") - if lyr.GetFeatureCount() != 0: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.GetFeatureCount() == 0 lyr.SetAttributeFilter("dt = '2017/02/17 11:06:34'") - if lyr.GetFeatureCount() != 1: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.GetFeatureCount() == 1 lyr.SetAttributeFilter("dt = '2017/02/17 11:06:34.001'") - if lyr.GetFeatureCount() != 0: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.GetFeatureCount() == 0 lyr.SetAttributeFilter("dt BETWEEN dt AND dt") - if lyr.GetFeatureCount() != 1: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.GetFeatureCount() == 1 lyr.SetAttributeFilter("dt BETWEEN '2017/02/17 11:06:33.999' AND '2017/02/17 11:06:34.001'") - if lyr.GetFeatureCount() != 1: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.GetFeatureCount() == 1 lyr.SetAttributeFilter("dt BETWEEN '2017/02/17 11:06:34.001' AND dt") - if lyr.GetFeatureCount() != 0: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.GetFeatureCount() == 0 lyr.SetAttributeFilter("dt BETWEEN dt AND '2017/02/17 11:06:33.999'") - if lyr.GetFeatureCount() != 0: - gdaltest.post_reason('fail') - return 'fail' - - return 'success' + assert lyr.GetFeatureCount() == 0 ############################################################################### -def ogr_rfc28_int_overflows(): +def test_ogr_rfc28_int_overflows(): ds = ogr.GetDriverByName('Memory').CreateDataSource('') lyr = ds.CreateLayer('lyr') @@ -1579,85 +1330,17 @@ def ogr_rfc28_int_overflows(): f = sql_lyr.GetNextFeature() else: f = sql_lyr.GetNextFeature() - if f.GetField(0) != res: - gdaltest.post_reason('fail') - print(sql, res, f.GetField(0)) - return 'fail' + assert f.GetField(0) == res, (sql, res, f.GetField(0)) ds.ReleaseResultSet(sql_lyr) - return 'success' - + ############################################################################### -def ogr_rfc28_cleanup(): +def test_ogr_rfc28_cleanup(): gdaltest.lyr = None gdaltest.ds = None - return 'success' - - -gdaltest_list = [ - ogr_rfc28_1, - ogr_rfc28_2, - ogr_rfc28_3, - ogr_rfc28_4, - ogr_rfc28_5, - ogr_rfc28_6, - ogr_rfc28_7_wrong_quoting, - ogr_rfc28_7_good_quoting, - ogr_rfc28_8_wrong_quoting, - ogr_rfc28_8_good_quoting, - ogr_rfc28_9, - ogr_rfc28_10, - ogr_rfc28_11, - ogr_rfc28_12, - ogr_rfc28_13, - ogr_rfc28_14, - ogr_rfc28_15, - ogr_rfc28_16, - ogr_rfc28_17, - ogr_rfc28_18, - ogr_rfc28_19, - ogr_rfc28_20, - ogr_rfc28_21, - ogr_rfc28_22, - ogr_rfc28_23, - ogr_rfc28_24, - ogr_rfc28_25, - ogr_rfc28_26, - ogr_rfc28_27, - ogr_rfc28_28, - ogr_rfc28_29, - ogr_rfc28_30, - ogr_rfc28_31, - ogr_rfc28_32, - ogr_rfc28_33, - ogr_rfc28_34, - ogr_rfc28_35, - ogr_rfc28_35_bis, - ogr_rfc28_35_ter, - ogr_rfc28_36, - ogr_rfc28_37, - ogr_rfc28_38, - ogr_rfc28_39, - ogr_rfc28_40, - ogr_rfc28_41, - ogr_rfc28_42, - ogr_rfc28_43, - ogr_rfc28_44, - ogr_rfc28_45, - ogr_rfc28_46, - ogr_rfc28_47, - ogr_rfc28_48, - ogr_rfc28_int_overflows, - ogr_rfc28_cleanup] - -if __name__ == '__main__': - - gdaltest.setup_run('ogr_sql_rfc28') - - gdaltest.run_tests(gdaltest_list) - - sys.exit(gdaltest.summarize()) + + diff --git a/autotest/ogr/ogr_sql_sqlite.py b/autotest/ogr/ogr_sql_sqlite.py index 7ff7c6973414..8e1e5fe19239 100755 --- a/autotest/ogr/ogr_sql_sqlite.py +++ b/autotest/ogr/ogr_sql_sqlite.py @@ -34,9 +34,6 @@ except ImportError: from http.server import BaseHTTPRequestHandler -import sys - -sys.path.append('../pymod') from osgeo import ogr from osgeo import osr @@ -44,45 +41,48 @@ import gdaltest import ogrtest import webserver +import pytest + + +@pytest.fixture(autouse=True) +def clear_config_options(): + gdal.SetConfigOption('OGR_GEOCODE_CACHE_FILE', None) + gdal.SetConfigOption('OGR_GEOCODE_APPLICATION', None) + gdal.SetConfigOption('OGR_GEOCODE_EMAIL', None) + gdal.SetConfigOption('OGR_GEOCODE_QUERY_TEMPLATE', None) + gdal.SetConfigOption('OGR_GEOCODE_DELAY', None) + gdal.SetConfigOption('OGR_GEOCODE_SERVICE', None) + gdal.SetConfigOption('OGR_GEOCODE_USERNAME', None) + gdal.SetConfigOption('OGR_GEOCODE_KEY', None) + gdal.SetConfigOption('OGR_SQLITE_DIALECT_USE_SPATIALITE', None) + ############################################################################### # Detect OGR SQLite dialect availability -def ogr_sql_sqlite_available(): - - ogrtest.has_sqlite_dialect = False +@pytest.fixture(autouse=True, scope='module') +def require_ogr_sql_sqlite(): if ogr.GetDriverByName('SQLite') is None: - return False + pytest.skip() # If we have SQLite VFS support, then SQLite dialect should be available ds = ogr.GetDriverByName('SQLite').CreateDataSource('/vsimem/ogr_sql_sqlite_available.db') if ds is None: - return False + pytest.skip() ds = None gdal.Unlink('/vsimem/ogr_sql_sqlite_available.db') ds = ogr.GetDriverByName("Memory").CreateDataSource("my_ds") sql_lyr = ds.ExecuteSQL("SELECT * FROM sqlite_master", dialect='SQLite') ds.ReleaseResultSet(sql_lyr) - if sql_lyr is None: - return 'fail' - ogrtest.has_sqlite_dialect = True - return True + assert sql_lyr is not None ############################################################################### # Tests that don't involve geometry -def ogr_sql_sqlite_1(): - - ret = ogr_sql_sqlite_available() - if ret == 'fail': - gdaltest.post_reason('fail') - return ret - if not ret: - return 'skip' - +def test_ogr_sql_sqlite_1(): ds = ogr.GetDriverByName("Memory").CreateDataSource("my_ds") for geom in [ogr.wkbNone, ogr.wkbUnknown]: lyr = ds.CreateLayer("my_layer", geom_type=geom) @@ -140,9 +140,8 @@ def ogr_sql_sqlite_1(): feat.GetField('datefield') != '2012/08/23' or \ feat.GetField('timefield') != '21:24:00' or \ feat.GetField('from') != 'from_val': - gdaltest.post_reason('failure') feat.DumpReadable() - return 'fail' + pytest.fail() feat = None # Test UPDATE @@ -158,9 +157,8 @@ def ogr_sql_sqlite_1(): feat.GetField('datetimefield') != '2012/08/23 21:24:00' or \ feat.GetField('datefield') != '2012/08/23' or \ feat.GetField('timefield') != '12:34:00': - gdaltest.post_reason('failure') feat.DumpReadable() - return 'fail' + pytest.fail() feat.SetStyleString('cool_style') lyr.SetFeature(feat) @@ -169,24 +167,12 @@ def ogr_sql_sqlite_1(): # Test SELECT sql_lyr = ds.ExecuteSQL("SELECT * FROM my_layer", dialect='SQLite') - if sql_lyr.GetLayerDefn().GetFieldDefn(sql_lyr.GetLayerDefn().GetFieldIndex('boolfield')).GetSubType() != ogr.OFSTBoolean: - gdaltest.post_reason('fail') - return 'fail' - if sql_lyr.GetLayerDefn().GetFieldDefn(sql_lyr.GetLayerDefn().GetFieldIndex('int16field')).GetSubType() != ogr.OFSTInt16: - gdaltest.post_reason('fail') - return 'fail' - if sql_lyr.GetLayerDefn().GetFieldDefn(sql_lyr.GetLayerDefn().GetFieldIndex('float32field')).GetSubType() != ogr.OFSTFloat32: - gdaltest.post_reason('fail') - return 'fail' - if sql_lyr.GetLayerDefn().GetFieldDefn(sql_lyr.GetLayerDefn().GetFieldIndex('intlistfield')).GetType() != ogr.OFTIntegerList: - gdaltest.post_reason('fail') - return 'fail' - if sql_lyr.GetLayerDefn().GetFieldDefn(sql_lyr.GetLayerDefn().GetFieldIndex('doublelistfield')).GetType() != ogr.OFTRealList: - gdaltest.post_reason('fail') - return 'fail' - if sql_lyr.GetLayerDefn().GetFieldDefn(sql_lyr.GetLayerDefn().GetFieldIndex('strlistfield')).GetType() != ogr.OFTStringList: - gdaltest.post_reason('fail') - return 'fail' + assert sql_lyr.GetLayerDefn().GetFieldDefn(sql_lyr.GetLayerDefn().GetFieldIndex('boolfield')).GetSubType() == ogr.OFSTBoolean + assert sql_lyr.GetLayerDefn().GetFieldDefn(sql_lyr.GetLayerDefn().GetFieldIndex('int16field')).GetSubType() == ogr.OFSTInt16 + assert sql_lyr.GetLayerDefn().GetFieldDefn(sql_lyr.GetLayerDefn().GetFieldIndex('float32field')).GetSubType() == ogr.OFSTFloat32 + assert sql_lyr.GetLayerDefn().GetFieldDefn(sql_lyr.GetLayerDefn().GetFieldIndex('intlistfield')).GetType() == ogr.OFTIntegerList + assert sql_lyr.GetLayerDefn().GetFieldDefn(sql_lyr.GetLayerDefn().GetFieldIndex('doublelistfield')).GetType() == ogr.OFTRealList + assert sql_lyr.GetLayerDefn().GetFieldDefn(sql_lyr.GetLayerDefn().GetFieldIndex('strlistfield')).GetType() == ogr.OFTStringList feat = sql_lyr.GetNextFeature() if feat.GetField('intfield') != 2 or \ feat.GetField('int64field') != 234567890123 or \ @@ -203,9 +189,8 @@ def ogr_sql_sqlite_1(): feat.GetField('int64listfield') != [1234567890123456] or \ feat.GetField('doublelistfield') != [1.23] or \ feat.GetField('strlistfield') != ['a']: - gdaltest.post_reason('failure') feat.DumpReadable() - return 'fail' + pytest.fail() feat = None ds.ReleaseResultSet(sql_lyr) @@ -217,9 +202,8 @@ def ogr_sql_sqlite_1(): feat.GetField('doublefield') != 3.45 or \ feat.GetField('strfield') != 'bar' or \ feat.GetStyleString() != 'cool_style': - gdaltest.post_reason('failure') feat.DumpReadable() - return 'fail' + pytest.fail() feat = None ds.ReleaseResultSet(sql_lyr) @@ -238,10 +222,7 @@ def ogr_sql_sqlite_1(): "\"from\" = 'from_val'"]: sql_lyr = ds.ExecuteSQL("SELECT * FROM my_layer WHERE " + cond, dialect='SQLite') feat = sql_lyr.GetNextFeature() - if feat is None: - gdaltest.post_reason('failure') - print(cond) - return 'fail' + assert feat is not None, cond feat = None ds.ReleaseResultSet(sql_lyr) @@ -254,9 +235,7 @@ def ogr_sql_sqlite_1(): "\"from\" = 'other_val'"]: sql_lyr = ds.ExecuteSQL("SELECT * FROM my_layer WHERE " + cond, dialect='SQLite') feat = sql_lyr.GetNextFeature() - if feat is not None: - gdaltest.post_reason('failure') - return 'fail' + assert feat is None feat = None ds.ReleaseResultSet(sql_lyr) @@ -271,9 +250,8 @@ def ogr_sql_sqlite_1(): feat = lyr.GetFeature(1000) if feat.GetField('intfield') != 100: - gdaltest.post_reason('failure') feat.DumpReadable() - return 'fail' + pytest.fail() feat = None # Test DELETE @@ -285,25 +263,19 @@ def ogr_sql_sqlite_1(): lyr.ResetReading() feat = lyr.GetNextFeature() if feat is not None: - gdaltest.post_reason('failure') feat.DumpReadable() - return 'fail' + pytest.fail() feat = None ds.DeleteLayer(0) ds = None - return 'success' - ############################################################################### # Tests that involve geometry (but without needing Spatialite) -def ogr_sql_sqlite_2(): - - if not ogrtest.has_sqlite_dialect: - return 'skip' +def test_ogr_sql_sqlite_2(): ds = ogr.GetDriverByName("Memory").CreateDataSource("my_ds") @@ -337,9 +309,8 @@ def ogr_sql_sqlite_2(): feat.GetField('doublefield') != 3.45 or \ feat.GetField('strfield') != 'bar' or \ feat.GetGeometryRef().ExportToWkt() != 'POINT (0 1)': - gdaltest.post_reason('failure') feat.DumpReadable() - return 'fail' + pytest.fail() feat = None # Test SELECT @@ -349,15 +320,10 @@ def ogr_sql_sqlite_2(): feat.GetField('doublefield') != 3.45 or \ feat.GetField('strfield') != 'bar' or \ feat.GetGeometryRef().ExportToWkt() != 'POINT (0 1)': - gdaltest.post_reason('failure') feat.DumpReadable() - return 'fail' + pytest.fail() got_srs = feat.GetGeometryRef().GetSpatialReference() - if got_srs is None or srs.IsSame(got_srs) == 0: - gdaltest.post_reason('failure') - print(srs) - print(got_srs) - return 'fail' + assert not (got_srs is None or srs.IsSame(got_srs) == 0) feat = None ds.ReleaseResultSet(sql_lyr) @@ -369,15 +335,10 @@ def ogr_sql_sqlite_2(): feat.GetField('strfield') != 'bar' or \ feat.GetStyleString() != 'cool_style' or \ feat.GetGeometryRef().ExportToWkt() != 'POINT (0 1)': - gdaltest.post_reason('failure') feat.DumpReadable() - return 'fail' + pytest.fail() got_srs = feat.GetGeometryRef().GetSpatialReference() - if got_srs is None or srs.IsSame(got_srs) == 0: - gdaltest.post_reason('failure') - print(srs) - print(got_srs) - return 'fail' + assert not (got_srs is None or srs.IsSame(got_srs) == 0) feat = None ds.ReleaseResultSet(sql_lyr) @@ -400,38 +361,24 @@ def ogr_sql_sqlite_2(): sql_lyr = ds.ExecuteSQL("SELECT * FROM my_layer2", dialect='SQLite') layer_srs = sql_lyr.GetSpatialRef() - if layer_srs is None or srs.IsSame(layer_srs) == 0: - gdaltest.post_reason('failure') - print(srs) - print(layer_srs) - return 'fail' + assert not (layer_srs is None or srs.IsSame(layer_srs) == 0) for _ in range(2): feat = sql_lyr.GetNextFeature() if feat.GetGeometryRef().ExportToWkt() != 'POINT (0 1)': - gdaltest.post_reason('failure') feat.DumpReadable() - return 'fail' + pytest.fail() got_srs = feat.GetGeometryRef().GetSpatialReference() - if got_srs is None or srs.IsSame(got_srs) == 0: - gdaltest.post_reason('failure') - print(srs) - print(got_srs) - return 'fail' + assert not (got_srs is None or srs.IsSame(got_srs) == 0) feat = None ds.ReleaseResultSet(sql_lyr) - return 'success' - ############################################################################### # Test that involves a join -def ogr_sql_sqlite_3(): - - if not ogrtest.has_sqlite_dialect: - return 'skip' +def test_ogr_sql_sqlite_3(): ds = ogr.Open('data') @@ -441,30 +388,23 @@ def ogr_sql_sqlite_3(): feat = sql_lyr.GetNextFeature() if feat.GetField('NAME') != '_158_': feat.DumpReadable() - return 'fail' + pytest.fail() geom = feat.GetGeometryRef() p = geom.GetGeometryRef(0).GetPoint_2D(0) if p != (480701.0625, 4764738.0): feat.DumpReadable() - return 'fail' + pytest.fail() ds.ReleaseResultSet(sql_lyr) - if count != 10: - print(count) - return 'fail' + assert count == 10 ds = None - return 'success' - ############################################################################### # Test that involves a self-join (to check that we can open twice the same table) -def ogr_sql_sqlite_4(): - - if not ogrtest.has_sqlite_dialect: - return 'skip' +def test_ogr_sql_sqlite_4(): ds = ogr.Open('data') @@ -472,22 +412,15 @@ def ogr_sql_sqlite_4(): count = sql_lyr.GetFeatureCount() ds.ReleaseResultSet(sql_lyr) - if count != 10: - print(count) - return 'fail' + assert count == 10 ds = None - return 'success' - ############################################################################### # Test that involves spatialite -def ogr_sql_sqlite_5(): - - if not ogrtest.has_sqlite_dialect: - return 'skip' +def test_ogr_sql_sqlite_5(): gdal.PushErrorHandler('CPLQuietErrorHandler') ds = ogr.GetDriverByName('SQLite').CreateDataSource('/vsimem/foo.db', options=['SPATIALITE=YES']) @@ -502,8 +435,7 @@ def ogr_sql_sqlite_5(): gdal.PopErrorHandler() if ogrtest.has_spatialite is False: - print('Spatialite not available') - return 'skip' + pytest.skip('Spatialite not available') ds = ogr.Open('data') @@ -513,51 +445,32 @@ def ogr_sql_sqlite_5(): ds = None - if count != 1: - print(count) - return 'fail' - - return 'success' + assert count == 1 ############################################################################### # If Spatialite available, retry some tests without it, to check that # we are fully compatible with regular SQLite -def ogr_sql_sqlite_6(): - - if not ogrtest.has_sqlite_dialect: - return 'skip' +def test_ogr_sql_sqlite_6(): if ogrtest.has_spatialite is False: - return 'skip' + pytest.skip() gdal.SetConfigOption('OGR_SQLITE_DIALECT_USE_SPATIALITE', 'NO') - ret = ogr_sql_sqlite_1() - if ret != 'success': - return ret - - ret = ogr_sql_sqlite_2() - if ret != 'success': - return ret + test_ogr_sql_sqlite_1() - ret = ogr_sql_sqlite_4() - if ret != 'success': - return ret + test_ogr_sql_sqlite_2() - gdal.SetConfigOption('OGR_SQLITE_DIALECT_USE_SPATIALITE', None) + test_ogr_sql_sqlite_4() - return 'success' ############################################################################### # Test if there's a text column called GEOMETRY already in the table -def ogr_sql_sqlite_7(): - - if not ogrtest.has_sqlite_dialect: - return 'skip' +def test_ogr_sql_sqlite_7(): ds = ogr.GetDriverByName("Memory").CreateDataSource("my_ds") @@ -577,17 +490,14 @@ def ogr_sql_sqlite_7(): # Test SELECT sql_lyr = ds.ExecuteSQL("SELECT * FROM my_layer", dialect='SQLite') - if sql_lyr.GetGeometryColumn() != 'GEOMETRY2': - gdaltest.post_reason('failure') - return 'fail' + assert sql_lyr.GetGeometryColumn() == 'GEOMETRY2' feat = sql_lyr.GetNextFeature() if feat.GetField('intfield') != 1 or \ feat.GetField('geometry') != 'BLA' or \ feat.GetGeometryRef().ExportToWkt() != 'POINT (0 1)': - gdaltest.post_reason('failure') feat.DumpReadable() - return 'fail' + pytest.fail() feat = None ds.ReleaseResultSet(sql_lyr) @@ -595,22 +505,16 @@ def ogr_sql_sqlite_7(): sql_lyr = ds.ExecuteSQL("SELECT GEOMETRY2 FROM my_layer", dialect='SQLite') feat = sql_lyr.GetNextFeature() if feat.GetGeometryRef().ExportToWkt() != 'POINT (0 1)': - gdaltest.post_reason('failure') feat.DumpReadable() - return 'fail' + pytest.fail() feat = None ds.ReleaseResultSet(sql_lyr) - return 'success' - ############################################################################### # Test join with an external datasource -def ogr_sql_sqlite_8(): - - if not ogrtest.has_sqlite_dialect: - return 'skip' +def test_ogr_sql_sqlite_8(): ds = ogr.Open('data') @@ -625,16 +529,13 @@ def ogr_sql_sqlite_8(): ds.ReleaseResultSet(sql_lyr) - return 'success' if tr else 'fail' + assert tr ############################################################################### # Check parsing of sub-selects -def ogr_sql_sqlite_9(): - - if not ogrtest.has_sqlite_dialect: - return 'skip' +def test_ogr_sql_sqlite_9(): ds = ogr.Open('data') @@ -649,16 +550,12 @@ def ogr_sql_sqlite_9(): if cnt != 7: return' fail' - return 'success' ############################################################################### # Test optimized count(*) -def ogr_sql_sqlite_10(): - - if not ogrtest.has_sqlite_dialect: - return 'skip' +def test_ogr_sql_sqlite_10(): ds = ogr.Open('data') @@ -673,16 +570,12 @@ def ogr_sql_sqlite_10(): if cnt != 10: return' fail' - return 'success' ############################################################################### # Test correct parsing of litterals -def ogr_sql_sqlite_11(): - - if not ogrtest.has_sqlite_dialect: - return 'skip' +def test_ogr_sql_sqlite_11(): ds = ogr.GetDriverByName("Memory").CreateDataSource("my_ds") @@ -703,16 +596,12 @@ def ogr_sql_sqlite_11(): if cnt != 1: return' fail' - return 'success' ############################################################################### # Test various error conditions -def ogr_sql_sqlite_12(): - - if not ogrtest.has_sqlite_dialect: - return 'skip' +def test_ogr_sql_sqlite_12(): ds = ogr.GetDriverByName("Memory").CreateDataSource("my_ds") @@ -736,16 +625,11 @@ def ogr_sql_sqlite_12(): ds = None - return 'success' - ############################################################################### # Test ogr_layer_Extent(), ogr_layer_SRID() and ogr_layer_GeometryType() -def ogr_sql_sqlite_13(): - - if not ogrtest.has_sqlite_dialect: - return 'skip' +def test_ogr_sql_sqlite_13(): ds = ogr.GetDriverByName("Memory").CreateDataSource("my_ds") @@ -771,9 +655,7 @@ def ogr_sql_sqlite_13(): geom = feat.GetGeometryRef() ds.ReleaseResultSet(sql_lyr) - if geom is not None: - gdaltest.post_reason('fail') - return 'fail' + assert geom is None # Test on non existing layer gdal.PushErrorHandler('CPLQuietErrorHandler') @@ -783,9 +665,7 @@ def ogr_sql_sqlite_13(): geom = feat.GetGeometryRef() ds.ReleaseResultSet(sql_lyr) - if geom is not None: - gdaltest.post_reason('fail') - return 'fail' + assert geom is None # Test ogr_layer_Extent() sql_lyr = ds.ExecuteSQL("SELECT ogr_layer_Extent('my_layer')", dialect='SQLite') @@ -794,10 +674,7 @@ def ogr_sql_sqlite_13(): feat = None ds.ReleaseResultSet(sql_lyr) - if geom_wkt != 'POLYGON ((0 1,2 1,2 3,0 3,0 1))': - gdaltest.post_reason('fail') - print(geom_wkt) - return 'fail' + assert geom_wkt == 'POLYGON ((0 1,2 1,2 3,0 3,0 1))' # Test ogr_layer_FeatureCount() sql_lyr = ds.ExecuteSQL("SELECT ogr_layer_FeatureCount('my_layer') AS the_count", dialect='SQLite') @@ -806,10 +683,7 @@ def ogr_sql_sqlite_13(): feat = None ds.ReleaseResultSet(sql_lyr) - if count != 1: - gdaltest.post_reason('fail') - print(count) - return 'fail' + assert count == 1 # Test ogr_layer_Extent() on a non spatial layer sql_lyr = ds.ExecuteSQL("SELECT ogr_layer_Extent('non_spatial')", dialect='SQLite') @@ -817,9 +691,7 @@ def ogr_sql_sqlite_13(): geom = feat.GetGeometryRef() ds.ReleaseResultSet(sql_lyr) - if geom is not None: - gdaltest.post_reason('fail') - return 'fail' + assert geom is None # Test ogr_layer_SRID() sql_lyr = ds.ExecuteSQL("SELECT ogr_layer_SRID('my_layer') AS the_srid", dialect='SQLite') @@ -828,10 +700,7 @@ def ogr_sql_sqlite_13(): feat = None ds.ReleaseResultSet(sql_lyr) - if the_srid != 4326: - gdaltest.post_reason('fail') - print(the_srid) - return 'fail' + assert the_srid == 4326 # Test ogr_layer_SRID() on a non spatial layer sql_lyr = ds.ExecuteSQL("SELECT ogr_layer_SRID('non_spatial') AS the_srid", dialect='SQLite') @@ -840,9 +709,7 @@ def ogr_sql_sqlite_13(): feat = None ds.ReleaseResultSet(sql_lyr) - if the_srid is not None: - gdaltest.post_reason('fail') - return 'fail' + assert the_srid is None # Test ogr_layer_GeometryType() sql_lyr = ds.ExecuteSQL("SELECT ogr_layer_GeometryType('my_layer') AS the_geometrytype", dialect='SQLite') @@ -851,10 +718,7 @@ def ogr_sql_sqlite_13(): feat = None ds.ReleaseResultSet(sql_lyr) - if the_geometrytype != 'LINESTRING': - gdaltest.post_reason('fail') - print(the_geometrytype) - return 'fail' + assert the_geometrytype == 'LINESTRING' # Test ogr_layer_GeometryType() on a non spatial layer sql_lyr = ds.ExecuteSQL("SELECT ogr_layer_GeometryType('non_spatial') AS the_geometrytype", dialect='SQLite') @@ -863,9 +727,7 @@ def ogr_sql_sqlite_13(): feat = None ds.ReleaseResultSet(sql_lyr) - if the_geometrytype is not None: - gdaltest.post_reason('fail') - return 'fail' + assert the_geometrytype is None # Test on a external virtual table ds_shape = ogr.GetDriverByName("ESRI Shapefile").CreateDataSource('/vsimem/ogr_sql_sqlite_13.shp') @@ -882,15 +744,10 @@ def ogr_sql_sqlite_13(): ogr.GetDriverByName("ESRI Shapefile").DeleteDataSource('/vsimem/ogr_sql_sqlite_13.shp') - if the_srid_shp != 32631: - gdaltest.post_reason('fail') - print(the_srid_shp) - return 'fail' + assert the_srid_shp == 32631 ds = None - return 'success' - ############################################################################### # @@ -949,27 +806,20 @@ def ogr_sql_sqlite_14_and_15(sql): feat = None feat = sql_lyr.GetNextFeature() - if feat is not None: - return 'fail' + assert feat is None ds.ReleaseResultSet(sql_lyr) - if not (got_one and got_two): - return 'fail' - - return 'success' + assert (got_one and got_two) ############################################################################### # Test 'idx_layername_geometryname' spatial index recognition -def ogr_sql_sqlite_14(): - - if not ogrtest.has_sqlite_dialect: - return 'skip' +def test_ogr_sql_sqlite_14(): if ogrtest.has_spatialite is False: - return 'skip' + pytest.skip() sql = "SELECT intfield, intfield2 FROM my_layer, my_layer2 WHERE " + \ "my_layer2.rowid IN (SELECT pkid FROM idx_my_layer2_geometry WHERE " + \ @@ -982,16 +832,13 @@ def ogr_sql_sqlite_14(): # Test 'SpatialIndex' spatial index recognition -def ogr_sql_sqlite_15(): - - if not ogrtest.has_sqlite_dialect: - return 'skip' +def test_ogr_sql_sqlite_15(): if ogrtest.has_spatialite is False: - return 'skip' + pytest.skip() if int(gdaltest.spatialite_version[0:gdaltest.spatialite_version.find('.')]) < 3: - return 'skip' + pytest.skip() sql = "SELECT intfield, intfield2 FROM my_layer, my_layer2 WHERE " + \ "my_layer2.rowid IN (SELECT ROWID FROM SpatialIndex WHERE f_table_name = 'my_layer2' AND search_frame = my_layer.geometry)" @@ -1266,34 +1113,27 @@ def do_GET(self): ############################################################################### -def ogr_sql_sqlite_start_webserver(): +def test_ogr_sql_sqlite_start_webserver(): ogrtest.webserver_process = None ogrtest.webserver_port = 0 - if not ogrtest.has_sqlite_dialect: - return 'skip' - if gdal.GetDriverByName('HTTP') is None: - return 'skip' + pytest.skip() (ogrtest.webserver_process, ogrtest.webserver_port) = webserver.launch(handler=GeocodingHTTPHandler) if ogrtest.webserver_port == 0: - return 'skip' + pytest.skip() - return 'success' ############################################################################### # Test ogr_geocode() -def ogr_sql_sqlite_16(service=None, template='http://127.0.0.1:%d/geocoding?q=%%s'): - - if not ogrtest.has_sqlite_dialect: - return 'skip' +def test_ogr_sql_sqlite_16(service=None, template='http://127.0.0.1:%d/geocoding?q=%%s'): if ogrtest.webserver_port == 0: - return 'skip' + pytest.skip() gdal.SetConfigOption('OGR_GEOCODE_APPLICATION', 'GDAL/OGR autotest suite') gdal.SetConfigOption('OGR_GEOCODE_EMAIL', 'foo@bar') @@ -1305,8 +1145,6 @@ def ogr_sql_sqlite_16(service=None, template='http://127.0.0.1:%d/geocoding?q=%% elif service == 'BING': gdal.SetConfigOption('OGR_GEOCODE_KEY', 'fakekey') - ret = 'success' - for cache_filename in ['tmp/ogr_geocode_cache.sqlite', 'tmp/ogr_geocode_cache.csv']: gdal.Unlink(cache_filename) @@ -1328,43 +1166,34 @@ def ogr_sql_sqlite_16(service=None, template='http://127.0.0.1:%d/geocoding?q=%% sql_lyr = ds.ExecuteSQL(sql, dialect='SQLite') feat = sql_lyr.GetNextFeature() if feat is None: - gdaltest.post_reason('fail') print(sql) - ret = 'fail' ds.ReleaseResultSet(sql_lyr) - break + pytest.fail() if ((sql == "SELECT ogr_geocode('Paris')" or sql == "SELECT ogr_geocode('Paris', 'geometry')") and feat.GetGeometryRef() is None) or \ (sql == "SELECT ogr_geocode('Paris', '%s')" % name_field and not feat.IsFieldSet(name_field)) or \ (sql == "SELECT ogr_geocode('Paris', 'raw')" and not feat.IsFieldSet('raw')): feat.DumpReadable() - gdaltest.post_reason('fail') print(sql) - ret = 'fail' ds.ReleaseResultSet(sql_lyr) - break + pytest.fail() ds.ReleaseResultSet(sql_lyr) - if ret == 'success': - for sql in ["SELECT ogr_geocode('NonExistingPlace')", "SELECT ogr_geocode('Error')"]: - sql_lyr = ds.ExecuteSQL(sql, dialect='SQLite') - feat = sql_lyr.GetNextFeature() - if feat is None: - gdaltest.post_reason('fail') - ret = 'fail' - ds.ReleaseResultSet(sql_lyr) - break - - if feat.GetGeometryRef() is not None: - feat.DumpReadable() - gdaltest.post_reason('fail') - ret = 'fail' - ds.ReleaseResultSet(sql_lyr) - break + for sql in ["SELECT ogr_geocode('NonExistingPlace')", "SELECT ogr_geocode('Error')"]: + sql_lyr = ds.ExecuteSQL(sql, dialect='SQLite') + feat = sql_lyr.GetNextFeature() + if feat is None: + ds.ReleaseResultSet(sql_lyr) + pytest.fail() + if feat.GetGeometryRef() is not None: + feat.DumpReadable() ds.ReleaseResultSet(sql_lyr) + pytest.fail() + + ds.ReleaseResultSet(sql_lyr) # Test various syntax errors sql_lyr = ds.ExecuteSQL("SELECT ogr_geocode()", dialect='SQLite') @@ -1383,45 +1212,26 @@ def ogr_sql_sqlite_16(service=None, template='http://127.0.0.1:%d/geocoding?q=%% # Check cache existence cache_ds = ogr.Open(cache_filename) - if cache_ds is None: - gdaltest.post_reason('fail') - ret = 'fail' + assert cache_ds is not None if cache_ds.GetDriver().GetName().lower() != cache_filename[cache_filename.find('.') + 1:].lower(): - gdaltest.post_reason('fail') print(cache_ds.GetDriver().GetName()) print(cache_filename) - ret = 'fail' + pytest.fail() cache_ds = None gdal.Unlink(cache_filename) ds = None - if ret != 'success': - break - - gdal.SetConfigOption('OGR_GEOCODE_CACHE_FILE', None) - gdal.SetConfigOption('OGR_GEOCODE_APPLICATION', None) - gdal.SetConfigOption('OGR_GEOCODE_EMAIL', None) - gdal.SetConfigOption('OGR_GEOCODE_QUERY_TEMPLATE', None) - gdal.SetConfigOption('OGR_GEOCODE_DELAY', None) - gdal.SetConfigOption('OGR_GEOCODE_SERVICE', None) - gdal.SetConfigOption('OGR_GEOCODE_USERNAME', None) - gdal.SetConfigOption('OGR_GEOCODE_KEY', None) - - return ret ############################################################################### # Test ogr_geocode_reverse() -def ogr_sql_sqlite_17(service=None, template='http://127.0.0.1:%d/reversegeocoding?lon={lon}&lat={lat}'): - - if not ogrtest.has_sqlite_dialect: - return 'skip' +def test_ogr_sql_sqlite_17(service=None, template='http://127.0.0.1:%d/reversegeocoding?lon={lon}&lat={lat}'): if ogrtest.webserver_port == 0: - return 'skip' + pytest.skip() gdal.SetConfigOption('OGR_GEOCODE_APPLICATION', 'GDAL/OGR autotest suite') gdal.SetConfigOption('OGR_GEOCODE_EMAIL', 'foo@bar') @@ -1433,8 +1243,6 @@ def ogr_sql_sqlite_17(service=None, template='http://127.0.0.1:%d/reversegeocodi elif service == 'BING': gdal.SetConfigOption('OGR_GEOCODE_KEY', 'fakekey') - ret = 'success' - for cache_filename in ['tmp/ogr_geocode_cache.sqlite', 'tmp/ogr_geocode_cache.csv']: gdal.Unlink(cache_filename) @@ -1463,11 +1271,9 @@ def ogr_sql_sqlite_17(service=None, template='http://127.0.0.1:%d/reversegeocodi sql_lyr = ds.ExecuteSQL(sql, dialect='SQLite') feat = sql_lyr.GetNextFeature() if feat is None: - gdaltest.post_reason('fail') print(sql) - ret = 'fail' ds.ReleaseResultSet(sql_lyr) - break + pytest.fail() if sql.find('raw') != -1: field_to_test = 'raw' @@ -1475,11 +1281,9 @@ def ogr_sql_sqlite_17(service=None, template='http://127.0.0.1:%d/reversegeocodi field_to_test = name_field if not feat.IsFieldSet(field_to_test): feat.DumpReadable() - gdaltest.post_reason('fail') print(sql) - ret = 'fail' ds.ReleaseResultSet(sql_lyr) - break + pytest.fail() ds.ReleaseResultSet(sql_lyr) @@ -1507,85 +1311,66 @@ def ogr_sql_sqlite_17(service=None, template='http://127.0.0.1:%d/reversegeocodi # Check cache existence cache_ds = ogr.Open(cache_filename) - if cache_ds is None: - gdaltest.post_reason('fail') - ret = 'fail' + assert cache_ds is not None cache_ds = None gdal.Unlink(cache_filename) ds = None - if ret != 'success': - break - - gdal.SetConfigOption('OGR_GEOCODE_CACHE_FILE', None) - gdal.SetConfigOption('OGR_GEOCODE_APPLICATION', None) - gdal.SetConfigOption('OGR_GEOCODE_EMAIL', None) - gdal.SetConfigOption('OGR_GEOCODE_REVERSE_QUERY_TEMPLATE', None) - gdal.SetConfigOption('OGR_GEOCODE_DELAY', None) - gdal.SetConfigOption('OGR_GEOCODE_SERVICE', None) - gdal.SetConfigOption('OGR_GEOCODE_USERNAME', None) - gdal.SetConfigOption('OGR_GEOCODE_KEY', None) - - return ret - ############################################################################### # Test ogr_geocode() with Yahoo geocoding service -def ogr_sql_sqlite_18(): +def test_ogr_sql_sqlite_18(): - return ogr_sql_sqlite_16('YAHOO', 'http://127.0.0.1:%d/yahoogeocoding?q=%%s') + return test_ogr_sql_sqlite_16('YAHOO', 'http://127.0.0.1:%d/yahoogeocoding?q=%%s') ############################################################################### # Test ogr_geocode_reverse() with Yahoo geocoding service -def ogr_sql_sqlite_19(): +def test_ogr_sql_sqlite_19(): - return ogr_sql_sqlite_17('YAHOO', 'http://127.0.0.1:%d/yahooreversegeocoding?q={lat},{lon}&gflags=R') + return test_ogr_sql_sqlite_17('YAHOO', 'http://127.0.0.1:%d/yahooreversegeocoding?q={lat},{lon}&gflags=R') ############################################################################### # Test ogr_geocode() with GeoNames.org geocoding service -def ogr_sql_sqlite_20(): +def test_ogr_sql_sqlite_20(): - return ogr_sql_sqlite_16('GEONAMES', 'http://127.0.0.1:%d/geonamesgeocoding?q=%%s') + return test_ogr_sql_sqlite_16('GEONAMES', 'http://127.0.0.1:%d/geonamesgeocoding?q=%%s') ############################################################################### # Test ogr_geocode_reverse() with GeoNames.org geocoding service -def ogr_sql_sqlite_21(): +def test_ogr_sql_sqlite_21(): - return ogr_sql_sqlite_17('GEONAMES', 'http://127.0.0.1:%d/geonamesreversegeocoding?lat={lat}&lng={lon}') + return test_ogr_sql_sqlite_17('GEONAMES', 'http://127.0.0.1:%d/geonamesreversegeocoding?lat={lat}&lng={lon}') ############################################################################### # Test ogr_geocode() with Bing geocoding service -def ogr_sql_sqlite_22(): +def test_ogr_sql_sqlite_22(): - return ogr_sql_sqlite_16('BING', 'http://127.0.0.1:%d/binggeocoding?q=%%s') + return test_ogr_sql_sqlite_16('BING', 'http://127.0.0.1:%d/binggeocoding?q=%%s') ############################################################################### # Test ogr_geocode_reverse() with Bing geocoding service -def ogr_sql_sqlite_23(): +def test_ogr_sql_sqlite_23(): - return ogr_sql_sqlite_17('BING', 'http://127.0.0.1:%d/bingreversegeocoding?{lat},{lon}') + return test_ogr_sql_sqlite_17('BING', 'http://127.0.0.1:%d/bingreversegeocoding?{lat},{lon}') ############################################################################### # Test ogr_deflate() and ogr_inflate() -def ogr_sql_sqlite_24(): - - if not ogrtest.has_sqlite_dialect: - return 'skip' +def test_ogr_sql_sqlite_24(): ds = ogr.GetDriverByName("Memory").CreateDataSource("my_ds") @@ -1593,10 +1378,9 @@ def ogr_sql_sqlite_24(): sql_lyr = ds.ExecuteSQL("SELECT CAST(ogr_inflate(ogr_deflate('ab')) AS VARCHAR)", dialect='SQLite') feat = sql_lyr.GetNextFeature() if feat.GetField(0) != 'ab': - gdaltest.post_reason('fail') feat.DumpReadable() ds.ReleaseResultSet(sql_lyr) - return 'fail' + pytest.fail() ds.ReleaseResultSet(sql_lyr) # Big very compressible string @@ -1604,30 +1388,27 @@ def ogr_sql_sqlite_24(): sql_lyr = ds.ExecuteSQL("SELECT CAST(ogr_inflate(ogr_deflate('%s')) AS VARCHAR)" % bigstr, dialect='SQLite') feat = sql_lyr.GetNextFeature() if feat.GetField(0) != bigstr: - gdaltest.post_reason('fail') feat.DumpReadable() ds.ReleaseResultSet(sql_lyr) - return 'fail' + pytest.fail() ds.ReleaseResultSet(sql_lyr) # Blob sql_lyr = ds.ExecuteSQL("SELECT ogr_inflate(ogr_deflate(x'0203', 5))", dialect='SQLite') feat = sql_lyr.GetNextFeature() if feat.GetField(0) != '0203': - gdaltest.post_reason('fail') feat.DumpReadable() ds.ReleaseResultSet(sql_lyr) - return 'fail' + pytest.fail() ds.ReleaseResultSet(sql_lyr) # Test inflating a random binary blob sql_lyr = ds.ExecuteSQL("SELECT ogr_inflate(x'0203')", dialect='SQLite') feat = sql_lyr.GetNextFeature() if not feat.IsFieldNull(0): - gdaltest.post_reason('fail') feat.DumpReadable() ds.ReleaseResultSet(sql_lyr) - return 'fail' + pytest.fail() ds.ReleaseResultSet(sql_lyr) # Error case @@ -1635,18 +1416,16 @@ def ogr_sql_sqlite_24(): sql_lyr = ds.ExecuteSQL("SELECT ogr_deflate()", dialect='SQLite') gdal.PopErrorHandler() if sql_lyr is not None: - gdaltest.post_reason('fail') ds.ReleaseResultSet(sql_lyr) - return 'fail' + pytest.fail() # Error case sql_lyr = ds.ExecuteSQL("SELECT ogr_deflate('a', 'b')", dialect='SQLite') feat = sql_lyr.GetNextFeature() if not feat.IsFieldNull(0): - gdaltest.post_reason('fail') feat.DumpReadable() ds.ReleaseResultSet(sql_lyr) - return 'fail' + pytest.fail() ds.ReleaseResultSet(sql_lyr) # Error case @@ -1654,34 +1433,28 @@ def ogr_sql_sqlite_24(): sql_lyr = ds.ExecuteSQL("SELECT ogr_inflate()", dialect='SQLite') gdal.PopErrorHandler() if sql_lyr is not None: - gdaltest.post_reason('fail') ds.ReleaseResultSet(sql_lyr) - return 'fail' + pytest.fail() # Error case sql_lyr = ds.ExecuteSQL("SELECT ogr_inflate('a')", dialect='SQLite') feat = sql_lyr.GetNextFeature() if not feat.IsFieldNull(0): - gdaltest.post_reason('fail') feat.DumpReadable() ds.ReleaseResultSet(sql_lyr) - return 'fail' + pytest.fail() ds.ReleaseResultSet(sql_lyr) - return 'success' - ############################################################################### -def ogr_sql_sqlite_stop_webserver(): +def test_ogr_sql_sqlite_stop_webserver(): if ogrtest.webserver_port == 0: - return 'skip' + pytest.skip() webserver.server_stop(ogrtest.webserver_process, ogrtest.webserver_port) - return 'success' - ############################################################################### # If Spatialite is NOT available, test some of the minimal spatial functions # implemented. Test it also if spatialite is available, so we have a cross @@ -1701,10 +1474,7 @@ def ogr_sql_sqlite_25_test_errors(ds, fct): return True -def ogr_sql_sqlite_25(): - - if not ogrtest.has_sqlite_dialect: - return 'skip' +def test_ogr_sql_sqlite_25(): # if ogrtest.has_spatialite is True: # return 'skip' @@ -1715,16 +1485,13 @@ def ogr_sql_sqlite_25(): sql_lyr = ds.ExecuteSQL("SELECT ST_GeomFromWKB(ST_AsBinary(ST_GeomFromText(ST_AsText(ST_GeomFromText('POINT (0 1)')),4326)))", dialect='SQLite') feat = sql_lyr.GetNextFeature() if feat.GetGeometryRef().ExportToWkt() != 'POINT (0 1)': - gdaltest.post_reason('fail') feat.DumpReadable() ds.ReleaseResultSet(sql_lyr) - return 'fail' + pytest.fail() ds.ReleaseResultSet(sql_lyr) for fct in ["ST_AsText", "ST_GeomFromText", "ST_AsBinary", "ST_GeomFromWKB"]: - if not ogr_sql_sqlite_25_test_errors(ds, fct): - gdaltest.post_reason('fail with %s' % fct) - return 'fail' + assert ogr_sql_sqlite_25_test_errors(ds, fct), ('fail with %s' % fct) # Test ST_SRID sql_lyr = ds.ExecuteSQL("SELECT ST_SRID(ST_GeomFromText('POINT(0 0)',4326))", dialect='SQLite') @@ -1732,10 +1499,7 @@ def ogr_sql_sqlite_25(): val_sql = feat.GetField(0) ds.ReleaseResultSet(sql_lyr) - if val_sql != 4326: - gdaltest.post_reason('fail') - print(val_sql) - return 'fail' + assert val_sql == 4326 # Test ST_Area sql_lyr = ds.ExecuteSQL("SELECT ST_Area(ST_GeomFromText('%s')), ST_Area(null), ST_Area(x'00')" % 'POLYGON((0 0,0 1,1 1,1 0,0 0))', dialect='SQLite') @@ -1748,31 +1512,17 @@ def ogr_sql_sqlite_25(): geomA = ogr.CreateGeometryFromWkt('POLYGON((0 0,0 1,1 1,1 0,0 0))') val_ogr = geomA.GetArea() - if abs(val_sql - val_ogr) > 1e-5: - gdaltest.post_reason('fail') - print(val_sql) - print(val_ogr) - return 'fail' + assert abs(val_sql - val_ogr) <= 1e-5 - if val1_sql is not None: - gdaltest.post_reason('fail') - print(val1_sql) - return 'fail' + assert val1_sql is None - if val2_sql is not None: - gdaltest.post_reason('fail') - return 'fail' + assert val2_sql is None - return 'success' - -def ogr_sql_sqlite_26(): - - if not ogrtest.has_sqlite_dialect: - return 'skip' +def test_ogr_sql_sqlite_26(): if not ogrtest.have_geos(): - return 'skip' + pytest.skip() # if ogrtest.has_spatialite is True: # return 'skip' @@ -1794,9 +1544,7 @@ def ogr_sql_sqlite_26(): geom = ogr.CreateGeometryFromWkt(geom1_wkt) geom_geos = geom.Buffer(0.1) - if geom_sql.Equals(geom_geos) == 0: - gdaltest.post_reason('fail with %s' % op_str) - return 'fail' + assert geom_sql.Equals(geom_geos) != 0, ('fail with %s' % op_str) for op_str in ["IsEmpty", "IsSimple", "IsValid"]: for wkt in ['POLYGON EMPTY', 'POINT(0 1)', 'POLYGON((0 0,1 1,0 1,1 0,0 0))']: @@ -1810,14 +1558,13 @@ def ogr_sql_sqlite_26(): op = getattr(geom, op_str) b_geos = op() if b_sql != b_geos: - if ogrtest.has_sqlite_dialect and wkt == 'POLYGON EMPTY': + if wkt == 'POLYGON EMPTY': print('difference wit op = %s and wkt = POLYGON EMPTY' % op_str) else: - gdaltest.post_reason('fail with %s' % op_str) print(wkt) print(b_sql) print(b_geos) - return 'fail' + pytest.fail('fail with %s' % op_str) for op_str in ["Intersects", "Equals", "Disjoint", "Touches", "Crosses", "Within", @@ -1836,9 +1583,7 @@ def ogr_sql_sqlite_26(): geomB = ogr.CreateGeometryFromWkt(geomB_wkt) op = getattr(geomA, op_str) b_geos = op(geomB) - if b_sql != b_geos: - gdaltest.post_reason('fail with %s' % op_str) - return 'fail' + assert b_sql == b_geos, ('fail with %s' % op_str) for op_str in ["Intersection", "Difference", "Union", "SymDifference"]: for (geomA_wkt, geomB_wkt) in [(geom1_wkt, geom1_wkt), @@ -1861,15 +1606,12 @@ def ogr_sql_sqlite_26(): # GEOS can return empty geometry collection, while spatialite # does not if geom_geos is not None and geom_geos.IsEmpty() == 0: - gdaltest.post_reason('fail with %s' % op_str) print(geomA_wkt) print(geomB_wkt) print(geom_geos.ExportToWkt()) - return 'fail' + pytest.fail('fail with %s' % op_str) else: - if geom_sql.Equals(geom_geos) == 0: - gdaltest.post_reason('fail with %s' % op_str) - return 'fail' + assert geom_sql.Equals(geom_geos) != 0, ('fail with %s' % op_str) # Error cases op_str = 'Intersects' @@ -1879,9 +1621,7 @@ def ogr_sql_sqlite_26(): b0_sql = feat.GetField(0) b1_sql = feat.GetField(1) ds.ReleaseResultSet(sql_lyr) - if b0_sql > 0 or b1_sql > 0: - gdaltest.post_reason('fail with %s' % op_str) - return 'fail' + assert b0_sql <= 0 and b1_sql <= 0, ('fail with %s' % op_str) op_str = 'Intersection' for val in ['null', "'foo'", "x'00010203'"]: @@ -1889,28 +1629,20 @@ def ogr_sql_sqlite_26(): feat = sql_lyr.GetNextFeature() geom_sql = feat.GetGeometryRef() ds.ReleaseResultSet(sql_lyr) - if geom_sql is not None: - gdaltest.post_reason('fail with %s' % op_str) - return 'fail' + assert geom_sql is None, ('fail with %s' % op_str) sql_lyr = ds.ExecuteSQL("SELECT ST_%s(%s, ST_GeomFromText('%s'))" % (op_str, val, geom1_wkt), dialect='SQLite') feat = sql_lyr.GetNextFeature() geom_sql = feat.GetGeometryRef() ds.ReleaseResultSet(sql_lyr) - if geom_sql is not None: - gdaltest.post_reason('fail with %s' % op_str) - return 'fail' + assert geom_sql is None, ('fail with %s' % op_str) - return 'success' ############################################################################### # Test MIN(), MAX() on a date -def ogr_sql_sqlite_27(): - - if not ogrtest.has_sqlite_dialect: - return 'skip' +def test_ogr_sql_sqlite_27(): ds = ogr.GetDriverByName('Memory').CreateDataSource('') lyr = ds.CreateLayer('test') @@ -1922,34 +1654,23 @@ def ogr_sql_sqlite_27(): feat.SetField(0, '2013/01/01 00:00:00') lyr.CreateFeature(feat) lyr = ds.ExecuteSQL("SELECT MIN(DATE), MAX(DATE) from test", dialect='SQLite') - if lyr.GetLayerDefn().GetFieldDefn(0).GetType() != ogr.OFTDateTime: - gdaltest.post_reason('fail') - return 'fail' - if lyr.GetLayerDefn().GetFieldDefn(1).GetType() != ogr.OFTDateTime: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.GetLayerDefn().GetFieldDefn(0).GetType() == ogr.OFTDateTime + assert lyr.GetLayerDefn().GetFieldDefn(1).GetType() == ogr.OFTDateTime tr = ogrtest.check_features_against_list(lyr, 'MIN(DATE)', ['2013/01/01 00:00:00']) lyr.ResetReading() tr2 = ogrtest.check_features_against_list(lyr, 'MAX(DATE)', ['2013/12/31 23:59:59']) ds.ReleaseResultSet(lyr) - if not tr: - return 'fail' - - if not tr2: - return 'fail' + assert tr - return 'success' + assert tr2 ############################################################################### # Test hstore_get_value() -def ogr_sql_sqlite_28(): - - if not ogrtest.has_sqlite_dialect: - return 'skip' +def test_ogr_sql_sqlite_28(): ds = ogr.GetDriverByName('Memory').CreateDataSource('') @@ -1958,10 +1679,7 @@ def ogr_sql_sqlite_28(): gdal.PushErrorHandler('CPLQuietErrorHandler') sql_lyr = ds.ExecuteSQL(sql, dialect='SQLite') gdal.PopErrorHandler() - if sql_lyr is not None: - gdaltest.post_reason('fail') - print(sql) - return 'fail' + assert sql_lyr is None, sql # Invalid hstore syntax or empty result for sql in ["SELECT hstore_get_value('a', null)", @@ -1972,10 +1690,8 @@ def ogr_sql_sqlite_28(): sql_lyr = ds.ExecuteSQL(sql, dialect='SQLite') f = sql_lyr.GetNextFeature() if not f.IsFieldNull(0): - gdaltest.post_reason('fail') - print(sql) f.DumpReadable() - return 'fail' + pytest.fail(sql) ds.ReleaseResultSet(sql_lyr) # Valid hstore syntax @@ -1983,22 +1699,16 @@ def ogr_sql_sqlite_28(): sql_lyr = ds.ExecuteSQL(sql, dialect='SQLite') f = sql_lyr.GetNextFeature() if f.GetField(0) != expected: - gdaltest.post_reason('fail') - print(sql) f.DumpReadable() - return 'fail' + pytest.fail(sql) ds.ReleaseResultSet(sql_lyr) - return 'success' ############################################################################### # Test compat with curve geometries -def ogr_sql_sqlite_29(): - - if not ogrtest.has_sqlite_dialect: - return 'skip' +def test_ogr_sql_sqlite_29(): ds = ogr.GetDriverByName('Memory').CreateDataSource('') lyr = ds.CreateLayer('test', geom_type=ogr.wkbCircularString) @@ -2013,26 +1723,15 @@ def ogr_sql_sqlite_29(): ds.ReleaseResultSet(sql_lyr) ds = None - if geom_type != ogr.wkbCircularString: - gdaltest.post_reason('fail') - print(geom_type) - return 'fail' - - if got_wkt != 'CIRCULARSTRING (0 0,1 0,0 0)': - gdaltest.post_reason('fail') - print(got_wkt) - return 'fail' + assert geom_type == ogr.wkbCircularString - return 'success' + assert got_wkt == 'CIRCULARSTRING (0 0,1 0,0 0)' ############################################################################### # Test compat with M geometries -def ogr_sql_sqlite_30(): - - if not ogrtest.has_sqlite_dialect: - return 'skip' +def test_ogr_sql_sqlite_30(): ds = ogr.GetDriverByName('Memory').CreateDataSource('') lyr = ds.CreateLayer('testm', geom_type=ogr.wkbLineStringM) @@ -2051,15 +1750,9 @@ def ogr_sql_sqlite_30(): got_wkt = f.GetGeometryRef().ExportToIsoWkt() ds.ReleaseResultSet(sql_lyr) - if geom_type != ogr.wkbLineStringM: - gdaltest.post_reason('fail') - print(geom_type) - return 'fail' + assert geom_type == ogr.wkbLineStringM - if got_wkt != 'LINESTRING M (1 2 3)': - gdaltest.post_reason('fail') - print(got_wkt) - return 'fail' + assert got_wkt == 'LINESTRING M (1 2 3)' sql_lyr = ds.ExecuteSQL('select * from testzm', dialect='SQLite') geom_type = sql_lyr.GetGeomType() @@ -2067,26 +1760,15 @@ def ogr_sql_sqlite_30(): got_wkt = f.GetGeometryRef().ExportToIsoWkt() ds.ReleaseResultSet(sql_lyr) - if geom_type != ogr.wkbLineStringZM: - gdaltest.post_reason('fail') - print(geom_type) - return 'fail' + assert geom_type == ogr.wkbLineStringZM - if got_wkt != 'LINESTRING ZM (1 2 3 4)': - gdaltest.post_reason('fail') - print(got_wkt) - return 'fail' - - return 'success' + assert got_wkt == 'LINESTRING ZM (1 2 3 4)' ############################################################################### # Test filtering complex field name -def ogr_sql_sqlite_31(): - - if not ogrtest.has_sqlite_dialect: - return 'skip' +def test_ogr_sql_sqlite_31(): ds = ogr.GetDriverByName('Memory').CreateDataSource('') lyr = ds.CreateLayer('test') @@ -2101,53 +1783,7 @@ def ogr_sql_sqlite_31(): value = f.GetField(0) ds.ReleaseResultSet(sql_lyr) - if value != 25: - gdaltest.post_reason('fail') - return 'fail' - - return 'success' - - -gdaltest_list = [ - ogr_sql_sqlite_1, - ogr_sql_sqlite_2, - ogr_sql_sqlite_3, - ogr_sql_sqlite_4, - ogr_sql_sqlite_5, - ogr_sql_sqlite_6, - ogr_sql_sqlite_7, - ogr_sql_sqlite_8, - ogr_sql_sqlite_9, - ogr_sql_sqlite_10, - ogr_sql_sqlite_11, - ogr_sql_sqlite_12, - ogr_sql_sqlite_13, - ogr_sql_sqlite_14, - ogr_sql_sqlite_15, - ogr_sql_sqlite_start_webserver, - ogr_sql_sqlite_16, - ogr_sql_sqlite_17, - ogr_sql_sqlite_18, - ogr_sql_sqlite_19, - ogr_sql_sqlite_20, - ogr_sql_sqlite_21, - ogr_sql_sqlite_22, - ogr_sql_sqlite_23, - ogr_sql_sqlite_stop_webserver, - ogr_sql_sqlite_24, - ogr_sql_sqlite_25, - ogr_sql_sqlite_26, - ogr_sql_sqlite_27, - ogr_sql_sqlite_28, - ogr_sql_sqlite_29, - ogr_sql_sqlite_30, - ogr_sql_sqlite_31 -] - -if __name__ == '__main__': - - gdaltest.setup_run('ogr_sql_sqlite') - - gdaltest.run_tests(gdaltest_list) - - sys.exit(gdaltest.summarize()) + assert value == 25 + + + diff --git a/autotest/ogr/ogr_sql_test.py b/autotest/ogr/ogr_sql_test.py index 9b26a5d080de..57106ccc1e4a 100755 --- a/autotest/ogr/ogr_sql_test.py +++ b/autotest/ogr/ogr_sql_test.py @@ -29,41 +29,37 @@ import sys -sys.path.append('../pymod') from osgeo import gdal from osgeo import ogr import gdaltest import ogrtest +import pytest ############################################################################### # Test a simple query with a where clause. -def ogr_sql_1(): +def test_ogr_sql_1(): gdaltest.ds = ogr.Open('data') gdaltest.lyr = gdaltest.ds.GetLayerByName('poly') gdaltest.lyr.SetAttributeFilter('eas_id < 167') count = gdaltest.lyr.GetFeatureCount() - if count != 3: - gdaltest.post_reason('Got wrong count with GetFeatureCount() - %d, expecting 3' % count) - return 'fail' + assert count == 3, \ + ('Got wrong count with GetFeatureCount() - %d, expecting 3' % count) gdaltest.lyr.SetAttributeFilter('') count = gdaltest.lyr.GetFeatureCount() - if count != 10: - gdaltest.post_reason('Got wrong count with GetFeatureCount() - %d, expecting 10' % count) - return 'fail' - - return 'success' + assert count == 10, \ + ('Got wrong count with GetFeatureCount() - %d, expecting 10' % count) ############################################################################### # Test DISTINCT handling -def ogr_sql_2(): +def test_ogr_sql_2(): expect = [168, 169, 166, 158, 165] @@ -73,13 +69,13 @@ def ogr_sql_2(): gdaltest.ds.ReleaseResultSet(sql_lyr) - return 'success' if tr else 'fail' + assert tr ############################################################################### # Test ORDER BY handling -def ogr_sql_3(): +def test_ogr_sql_3(): expect = [158, 165, 166, 168, 169] @@ -89,13 +85,13 @@ def ogr_sql_3(): gdaltest.ds.ReleaseResultSet(sql_lyr) - return 'success' if tr else 'fail' + assert tr ############################################################################### # Test ORDER BY DESC handling -def ogr_sql_3_desc(): +def test_ogr_sql_3_desc(): expect = [169, 168, 166, 165, 158] @@ -105,13 +101,13 @@ def ogr_sql_3_desc(): gdaltest.ds.ReleaseResultSet(sql_lyr) - return 'success' if tr else 'fail' + assert tr ############################################################################### # Test DISTINCT and ORDER BY on strings. -def ogr_sql_4(): +def test_ogr_sql_4(): expect = ['_158_', '_165_', '_166_', '_168_', '_170_', '_171_', '_179_'] @@ -121,45 +117,38 @@ def ogr_sql_4(): gdaltest.ds.ReleaseResultSet(sql_lyr) - return 'success' if tr else 'fail' + assert tr ############################################################################### # Test column functions. -def ogr_sql_5(): +def test_ogr_sql_5(): sql_lyr = gdaltest.ds.ExecuteSQL('select max(eas_id), min(eas_id), avg(eas_id), sum(eas_id), count(eas_id) from idlink') feat = sql_lyr.GetNextFeature() if feat['max_eas_id'] != 179: feat.DumpReadable() - gdaltest.post_reason('fail') - return 'fail' + pytest.fail() if feat['min_eas_id'] != 158: feat.DumpReadable() - gdaltest.post_reason('fail') - return 'fail' + pytest.fail() if abs(feat['avg_eas_id'] - 168.142857142857) > 1e-12: feat.DumpReadable() - gdaltest.post_reason('fail') - return 'fail' + pytest.fail() if feat['count_eas_id'] != 7: feat.DumpReadable() - gdaltest.post_reason('fail') - return 'fail' + pytest.fail() if feat['sum_eas_id'] != 1177: feat.DumpReadable() - gdaltest.post_reason('fail') - return 'fail' + pytest.fail() gdaltest.ds.ReleaseResultSet(sql_lyr) - return 'success' - ############################################################################### # Test simple COUNT() function. -def ogr_sql_6(): +def test_ogr_sql_6(): expect = [10] @@ -169,13 +158,13 @@ def ogr_sql_6(): gdaltest.ds.ReleaseResultSet(sql_lyr) - return 'success' if tr else 'fail' + assert tr ############################################################################### # Verify that selecting the FID works properly. -def ogr_sql_7(): +def test_ogr_sql_7(): expect = [7, 8] @@ -185,13 +174,13 @@ def ogr_sql_7(): gdaltest.ds.ReleaseResultSet(sql_lyr) - return 'success' if tr else 'fail' + assert tr ############################################################################### # Verify that wildcard expansion works properly. -def ogr_sql_8(): +def test_ogr_sql_8(): expect = ['35043369', '35043408'] @@ -201,13 +190,13 @@ def ogr_sql_8(): gdaltest.ds.ReleaseResultSet(sql_lyr) - return 'success' if tr else 'fail' + assert tr ############################################################################### # Verify that quoted table names work. -def ogr_sql_9(): +def test_ogr_sql_9(): expect = ['35043369', '35043408'] @@ -217,13 +206,13 @@ def ogr_sql_9(): gdaltest.ds.ReleaseResultSet(sql_lyr) - return 'success' if tr else 'fail' + assert tr ############################################################################### # Test the ILIKE operator. -def ogr_sql_10(): +def test_ogr_sql_10(): expect = [170] @@ -233,13 +222,13 @@ def ogr_sql_10(): gdaltest.ds.ReleaseResultSet(sql_lyr) - return 'success' if tr else 'fail' + assert tr ############################################################################### # Test MAX() on empty dataset. -def ogr_sql_11(): +def test_ogr_sql_11(): expect = [None] @@ -249,13 +238,13 @@ def ogr_sql_11(): gdaltest.ds.ReleaseResultSet(sql_lyr) - return 'success' if tr else 'fail' + assert tr ############################################################################### # Test DISTINCT on empty dataset. -def ogr_sql_12(): +def test_ogr_sql_12(): expect = [] @@ -265,13 +254,13 @@ def ogr_sql_12(): gdaltest.ds.ReleaseResultSet(sql_lyr) - return 'success' if tr else 'fail' + assert tr ############################################################################### # Verify selection of, and on ogr_geometry. -def ogr_sql_13(): +def test_ogr_sql_13(): expect = ['POLYGON', 'POLYGON', 'POLYGON', 'POLYGON', 'POLYGON', 'POLYGON', 'POLYGON', 'POLYGON', 'POLYGON', 'POLYGON'] @@ -282,13 +271,13 @@ def ogr_sql_13(): gdaltest.ds.ReleaseResultSet(sql_lyr) - return 'success' if tr else 'fail' + assert tr ############################################################################### # Verify selection of, and on ogr_style and ogr_geom_wkt. -def ogr_sql_14(): +def test_ogr_sql_14(): expect = [ 'BRUSH(fc:#000000,bc:#ffffff,id:"mapinfo-brush-1,ogr-brush-1");PEN(w:1px,c:#000000,id:"mapinfo-pen-2,ogr-pen-0")', @@ -302,13 +291,13 @@ def ogr_sql_14(): ds.ReleaseResultSet(sql_lyr) ds = None - return 'success' if tr else 'fail' + assert tr ############################################################################### # Verify that selecting with filtering by FID works properly. -def ogr_sql_15(): +def test_ogr_sql_15(): expect = [7] @@ -318,12 +307,12 @@ def ogr_sql_15(): gdaltest.ds.ReleaseResultSet(sql_lyr) - return 'success' if tr else 'fail' + assert tr ############################################################################### -def ogr_sql_16(): +def test_ogr_sql_16(): expect = [2] @@ -335,13 +324,13 @@ def ogr_sql_16(): ds.ReleaseResultSet(sql_lyr) ds = None - return 'success' if tr else 'fail' + assert tr ############################################################################### # Test the RFC 21 CAST operator. # -def ogr_sql_17(): +def test_ogr_sql_17(): expect = ['1', '2'] @@ -350,10 +339,7 @@ def ogr_sql_17(): fld_def = sql_lyr.GetLayerDefn().GetFieldDefn(0) - if fld_def.GetName() != 'fid': - gdaltest.post_reason('got wrong fid field name') - print(fld_def.GetName()) - return 'fail' + assert fld_def.GetName() == 'fid', 'got wrong fid field name' if fld_def.GetType() != ogr.OFTString: gdaltest.post_reason('got wrong fid field type') @@ -365,10 +351,7 @@ def ogr_sql_17(): fld_def = sql_lyr.GetLayerDefn().GetFieldDefn(1) - if fld_def.GetName() != 'data': - gdaltest.post_reason('got wrong data field name') - print(fld_def.GetName()) - return 'fail' + assert fld_def.GetName() == 'data', 'got wrong data field name' if fld_def.GetType() != ogr.OFTReal: gdaltest.post_reason('got wrong data field type') @@ -387,31 +370,29 @@ def ogr_sql_17(): ds.ReleaseResultSet(sql_lyr) ds = None - return 'success' if tr else 'fail' + assert tr ############################################################################### # Test extended character set -def ogr_sql_18(): +def test_ogr_sql_18(): if sys.version_info >= (3, 0, 0): - return 'skip' + pytest.skip() name = 'data/departs.vrt' ds = ogr.Open(name) - if ds is None: - return 'fail' + assert ds is not None sql = 'select * from D\303\251parts' sql_lyr = ds.ExecuteSQL(sql) if sql_lyr is None: ds = None - return 'fail' + pytest.fail() feat = sql_lyr.GetNextFeature() - if feat is None: - return 'fail' + assert feat is not None feat = None ds.ReleaseResultSet(sql_lyr) @@ -421,37 +402,31 @@ def ogr_sql_18(): sql_lyr = ds.ExecuteSQL(sql) if sql_lyr is None: ds = None - return 'fail' + pytest.fail() feat = sql_lyr.GetNextFeature() - if feat is None: - return 'fail' + assert feat is not None feat = None ds.ReleaseResultSet(sql_lyr) ds = None - return 'success' - ############################################################################### # Test empty request string -def ogr_sql_19(): +def test_ogr_sql_19(): gdal.PushErrorHandler('CPLQuietErrorHandler') sql_lyr = gdaltest.ds.ExecuteSQL('') gdal.PopErrorHandler() - if sql_lyr is not None: - return 'fail' - - return 'success' + assert sql_lyr is None ############################################################################### # Test query "SELECT * from my_layer" on layer without any field (#2788) -def ogr_sql_20(): +def test_ogr_sql_20(): mem_ds = ogr.GetDriverByName("Memory").CreateDataSource("my_ds") mem_lyr = mem_ds.CreateLayer("my_layer") @@ -465,37 +440,30 @@ def ogr_sql_20(): mem_lyr.CreateFeature(feat) sql_lyr = mem_ds.ExecuteSQL("SELECT * from my_layer") - if sql_lyr.GetFeatureCount() != 2: - return 'fail' + assert sql_lyr.GetFeatureCount() == 2 mem_ds.ReleaseResultSet(sql_lyr) mem_ds = None - return 'success' - ############################################################################### # Test query "SELECT *, fid from my_layer" on layer without any field (#2788) -def ogr_sql_21(): +def test_ogr_sql_21(): mem_ds = ogr.GetDriverByName("Memory").CreateDataSource("my_ds") mem_ds.CreateLayer("my_layer") sql_lyr = mem_ds.ExecuteSQL("SELECT *, fid from my_layer") - if sql_lyr.GetLayerDefn().GetFieldCount() != 1: - return 'fail' - if sql_lyr.GetLayerDefn().GetFieldDefn(0).GetName() != 'fid': - return 'fail' + assert sql_lyr.GetLayerDefn().GetFieldCount() == 1 + assert sql_lyr.GetLayerDefn().GetFieldDefn(0).GetName() == 'fid' mem_ds.ReleaseResultSet(sql_lyr) mem_ds = None - return 'success' - ############################################################################### # Test multiple expansion of '*' as in "SELECT *, fid, *, my_layer.* from my_layer" (#2788) -def ogr_sql_22(): +def test_ogr_sql_22(): mem_ds = ogr.GetDriverByName("Memory").CreateDataSource("my_ds") mem_lyr = mem_ds.CreateLayer("my_layer") @@ -506,26 +474,19 @@ def ogr_sql_22(): mem_lyr.CreateFeature(feat) sql_lyr = mem_ds.ExecuteSQL("SELECT *, fid, *, my_layer.* from my_layer") - if sql_lyr.GetLayerDefn().GetFieldCount() != 4: - return 'fail' - if sql_lyr.GetLayerDefn().GetFieldDefn(0).GetName() != 'test': - return 'fail' - if sql_lyr.GetLayerDefn().GetFieldDefn(1).GetName() != 'fid': - return 'fail' - if sql_lyr.GetLayerDefn().GetFieldDefn(2).GetName() != 'test': - return 'fail' - if sql_lyr.GetLayerDefn().GetFieldDefn(3).GetName() != 'my_layer.test': - return 'fail' + assert sql_lyr.GetLayerDefn().GetFieldCount() == 4 + assert sql_lyr.GetLayerDefn().GetFieldDefn(0).GetName() == 'test' + assert sql_lyr.GetLayerDefn().GetFieldDefn(1).GetName() == 'fid' + assert sql_lyr.GetLayerDefn().GetFieldDefn(2).GetName() == 'test' + assert sql_lyr.GetLayerDefn().GetFieldDefn(3).GetName() == 'my_layer.test' mem_ds.ReleaseResultSet(sql_lyr) mem_ds = None - return 'success' - ############################################################################### # Test query "SELECT DISTINCT test from my_layer" (#2788) -def ogr_sql_23(): +def test_ogr_sql_23(): mem_ds = ogr.GetDriverByName("Memory").CreateDataSource("my_ds") mem_lyr = mem_ds.CreateLayer("my_layer") @@ -542,18 +503,15 @@ def ogr_sql_23(): mem_lyr.CreateFeature(feat) sql_lyr = mem_ds.ExecuteSQL("SELECT DISTINCT test from my_layer") - if sql_lyr.GetFeatureCount() != 2: - return 'fail' + assert sql_lyr.GetFeatureCount() == 2 mem_ds.ReleaseResultSet(sql_lyr) mem_ds = None - return 'success' - ############################################################################### # Test that style strings get carried with OGR SQL SELECT results. (#2808) -def ogr_sql_24(): +def test_ogr_sql_24(): result = 'success' @@ -576,7 +534,7 @@ def ogr_sql_24(): # Test for OGR_GEOM_AREA special field (#2949) -def ogr_sql_25(): +def test_ogr_sql_25(): mem_ds = ogr.GetDriverByName("Memory").CreateDataSource("my_ds") mem_lyr = mem_ds.CreateLayer("my_layer") @@ -593,25 +551,20 @@ def ogr_sql_25(): mem_lyr.CreateFeature(feat) sql_lyr = mem_ds.ExecuteSQL("SELECT test, OGR_GEOM_AREA from my_layer WHERE OGR_GEOM_AREA > 0.9") - if sql_lyr.GetFeatureCount() != 1: - return 'fail' + assert sql_lyr.GetFeatureCount() == 1 feat = sql_lyr.GetNextFeature() - if feat.GetFieldAsDouble('OGR_GEOM_AREA') != 1.0: - return 'fail' - if feat.GetFieldAsString('test') != '0': - return 'fail' + assert feat.GetFieldAsDouble('OGR_GEOM_AREA') == 1.0 + assert feat.GetFieldAsString('test') == '0' mem_ds.ReleaseResultSet(sql_lyr) mem_ds = None - return 'success' - ############################################################################### # Test query 'SELECT 'literal_value' AS column_name FROM a_table' # -def ogr_sql_26(): +def test_ogr_sql_26(): mem_ds = ogr.GetDriverByName("Memory").CreateDataSource("my_ds") mem_lyr = mem_ds.CreateLayer("my_layer") @@ -620,19 +573,14 @@ def ogr_sql_26(): mem_lyr.CreateFeature(feat) sql_lyr = mem_ds.ExecuteSQL("SELECT 'literal_value' AS my_column, 'literal_value2' my_column2 FROM my_layer") - if sql_lyr.GetFeatureCount() != 1: - return 'fail' + assert sql_lyr.GetFeatureCount() == 1 feat = sql_lyr.GetNextFeature() - if feat.GetFieldAsString('my_column') != 'literal_value': - return 'fail' - if feat.GetFieldAsString('my_column2') != 'literal_value2': - return 'fail' + assert feat.GetFieldAsString('my_column') == 'literal_value' + assert feat.GetFieldAsString('my_column2') == 'literal_value2' mem_ds.ReleaseResultSet(sql_lyr) mem_ds = None - return 'success' - ############################################################################### ############################################################################### @@ -640,7 +588,7 @@ def ogr_sql_26(): # -def ogr_sql_27(): +def test_ogr_sql_27(): ds = ogr.Open('data/testdatetime.csv') @@ -655,7 +603,7 @@ def ogr_sql_27(): ds.ReleaseResultSet(sql_lyr) ds = None - return 'success' if tr else 'fail' + assert tr ############################################################################### @@ -663,7 +611,7 @@ def ogr_sql_27(): # With RFC 28 new implementation, most of them are directly caught by the generated # code from the grammar -def ogr_sql_28(): +def test_ogr_sql_28(): ds = ogr.GetDriverByName("Memory").CreateDataSource("my_ds") lyr = ds.CreateLayer("my_layer") @@ -679,12 +627,9 @@ def ogr_sql_28(): field_defn = ogr.FieldDefn("strfield2", ogr.OFTString) lyr.CreateField(field_defn) - try: + with pytest.raises(Exception, message='expected error on NULL query'): sql_lyr = ds.ExecuteSQL(None) - gdaltest.post_reason('expected error on NULL query') - return 'fail' - except: - pass + queries = [ '', @@ -823,22 +768,17 @@ def ogr_sql_28(): sql_lyr = ds.ExecuteSQL(query) gdal.PopErrorHandler() if sql_lyr is not None: - gdaltest.post_reason('expected None result on "%s"' % query) ds.ReleaseResultSet(sql_lyr) - return 'fail' - if gdal.GetLastErrorType() == 0: - gdaltest.post_reason('expected error on "%s"' % query) - return 'fail' + pytest.fail('expected None result on "%s"' % query) + assert gdal.GetLastErrorType() != 0, ('expected error on "%s"' % query) ds = None - return 'success' - ############################################################################### # Verify that IS NULL and IS NOT NULL are working -def ogr_sql_29(): +def test_ogr_sql_29(): ds = ogr.GetDriverByName("Memory").CreateDataSource("my_ds") lyr = ds.CreateLayer("my_layer") @@ -866,23 +806,15 @@ def ogr_sql_29(): ds = None - if count_is_null != 1: - gdaltest.post_reason('IS NULL failed') - print(count_is_null) - return 'fail' - - if count_is_not_null != 2: - gdaltest.post_reason('IS NOT NULL failed') - print(count_is_not_null) - return 'fail' + assert count_is_null == 1, 'IS NULL failed' - return 'success' + assert count_is_not_null == 2, 'IS NOT NULL failed' ############################################################################### # Verify a select mixing a count(*) with something else works without errors -def ogr_sql_30(): +def test_ogr_sql_30(): gdal.ErrorReset() @@ -893,16 +825,15 @@ def ogr_sql_30(): gdaltest.ds.ReleaseResultSet(sql_lyr) - if gdal.GetLastErrorMsg() != '': - return 'fail' + assert gdal.GetLastErrorMsg() == '' - return 'success' if val_count == 10 else 'fail' + assert val_count == 10 ############################################################################### # Regression test for #4022 -def ogr_sql_31(): +def test_ogr_sql_31(): gdal.ErrorReset() @@ -913,16 +844,15 @@ def ogr_sql_31(): gdaltest.ds.ReleaseResultSet(sql_lyr) - if gdal.GetLastErrorMsg() != '': - return 'fail' + assert gdal.GetLastErrorMsg() == '' - return 'success' if val is None else 'fail' + assert val is None ############################################################################### # Regression test for #4022 (same as above, but with dialect = 'OGRSQL') -def ogr_sql_32(): +def test_ogr_sql_32(): gdal.ErrorReset() @@ -934,16 +864,15 @@ def ogr_sql_32(): gdaltest.ds.ReleaseResultSet(sql_lyr) - if gdal.GetLastErrorMsg() != '': - return 'fail' + assert gdal.GetLastErrorMsg() == '' - return 'success' if val is None else 'fail' + assert val is None ############################################################################### # Check ALTER TABLE commands -def ogr_sql_33(): +def test_ogr_sql_33(): ds = ogr.GetDriverByName("Memory").CreateDataSource("my_ds") lyr = ds.CreateLayer("my_layer") @@ -952,47 +881,39 @@ def ogr_sql_33(): for extrakeyword in ('COLUMN ', ''): sql = 'ALTER TABLE my_layer ADD %smyfield NUMERIC(20, 8)' % extrakeyword ds.ExecuteSQL(sql) - if lyr.GetLayerDefn().GetFieldIndex('myfield') == -1 or \ - lyr.GetLayerDefn().GetFieldDefn(lyr.GetLayerDefn().GetFieldIndex('myfield')).GetType() != ogr.OFTReal or \ - lyr.GetLayerDefn().GetFieldDefn(lyr.GetLayerDefn().GetFieldIndex('myfield')).GetWidth() != 20 or \ - lyr.GetLayerDefn().GetFieldDefn(lyr.GetLayerDefn().GetFieldIndex('myfield')).GetPrecision() != 8: - gdaltest.post_reason('%s failed' % sql) - return 'fail' + assert (lyr.GetLayerDefn().GetFieldIndex('myfield') != -1 and \ + lyr.GetLayerDefn().GetFieldDefn(lyr.GetLayerDefn().GetFieldIndex('myfield')).GetType() == ogr.OFTReal and \ + lyr.GetLayerDefn().GetFieldDefn(lyr.GetLayerDefn().GetFieldIndex('myfield')).GetWidth() == 20 and \ + lyr.GetLayerDefn().GetFieldDefn(lyr.GetLayerDefn().GetFieldIndex('myfield')).GetPrecision() == 8), \ + ('%s failed' % sql) sql = 'ALTER TABLE my_layer RENAME %smyfield TO "myfield 2"' % extrakeyword ds.ExecuteSQL(sql) - if lyr.GetLayerDefn().GetFieldIndex('myfield') != -1 or \ - lyr.GetLayerDefn().GetFieldIndex('myfield 2') == -1: - gdaltest.post_reason('%s failed' % sql) - return 'fail' + assert (lyr.GetLayerDefn().GetFieldIndex('myfield') == -1 and \ + lyr.GetLayerDefn().GetFieldIndex('myfield 2') != -1), \ + ('%s failed' % sql) sql = 'ALTER TABLE my_layer ALTER %s"myfield 2" TYPE CHARACTER' % extrakeyword ds.ExecuteSQL(sql) - if lyr.GetLayerDefn().GetFieldDefn(lyr.GetLayerDefn().GetFieldIndex('myfield 2')).GetType() != ogr.OFTString: - gdaltest.post_reason('%s failed' % sql) - return 'fail' + assert lyr.GetLayerDefn().GetFieldDefn(lyr.GetLayerDefn().GetFieldIndex('myfield 2')).GetType() == ogr.OFTString, \ + ('%s failed' % sql) sql = 'ALTER TABLE my_layer ALTER %s"myfield 2" TYPE CHARACTER(15)' % extrakeyword ds.ExecuteSQL(sql) - if lyr.GetLayerDefn().GetFieldDefn(lyr.GetLayerDefn().GetFieldIndex('myfield 2')).GetWidth() != 15: - gdaltest.post_reason('%s failed' % sql) - return 'fail' + assert lyr.GetLayerDefn().GetFieldDefn(lyr.GetLayerDefn().GetFieldIndex('myfield 2')).GetWidth() == 15, \ + ('%s failed' % sql) sql = 'ALTER TABLE my_layer DROP %s"myfield 2"' % extrakeyword ds.ExecuteSQL(sql) - if lyr.GetLayerDefn().GetFieldIndex('myfield 2') != -1: - gdaltest.post_reason('%s failed' % sql) - return 'fail' + assert lyr.GetLayerDefn().GetFieldIndex('myfield 2') == -1, ('%s failed' % sql) ds = None - return 'success' - ############################################################################### # Test implicit conversion from string to numeric (#4259) -def ogr_sql_34(): +def test_ogr_sql_34(): sql_lyr = gdaltest.ds.ExecuteSQL("select count(*) from poly where eas_id in ('165')") @@ -1001,23 +922,18 @@ def ogr_sql_34(): gdaltest.ds.ReleaseResultSet(sql_lyr) - if val != 1: - print(val) - return 'fail' + assert val == 1 gdal.PushErrorHandler('CPLQuietErrorHandler') sql_lyr = gdaltest.ds.ExecuteSQL("select count(*) from poly where eas_id in ('a165')") gdal.PopErrorHandler() - if sql_lyr is not None: - return 'fail' - - return 'success' + assert sql_lyr is None ############################################################################### # Test huge SQL queries (#4262) -def ogr_sql_35(): +def test_ogr_sql_35(): cols = "area" for _ in range(10): @@ -1028,13 +944,13 @@ def ogr_sql_35(): gdaltest.ds.ReleaseResultSet(sql_lyr) - return 'success' if count_cols == 1024 else 'fail' + assert count_cols == 1024 ############################################################################### # Test select distinct on null values (#4353) -def ogr_sql_36(): +def test_ogr_sql_36(): ds = ogr.GetDriverByName('Memory').CreateDataSource('ogr_sql_36') lyr = ds.CreateLayer('layer') @@ -1056,41 +972,32 @@ def ogr_sql_36(): sql_lyr = ds.ExecuteSQL("select distinct %s from layer order by %s asc" % (fieldname, fieldname)) feat = sql_lyr.GetNextFeature() if feat.IsFieldSetAndNotNull(0) != 0: - gdaltest.post_reason('fail') - print('field %s' % fieldname) feat.DumpReadable() - return 'fail' + pytest.fail('field %s' % fieldname) feat = sql_lyr.GetNextFeature() if feat.IsFieldSetAndNotNull(0) == 0: - gdaltest.post_reason('fail') - print('field %s' % fieldname) feat.DumpReadable() - return 'fail' + pytest.fail('field %s' % fieldname) ds.ReleaseResultSet(sql_lyr) for fieldname in ['intfield', 'int64field', 'floatfield', 'strfield']: sql_lyr = ds.ExecuteSQL("select distinct %s from layer order by %s desc" % (fieldname, fieldname)) feat = sql_lyr.GetNextFeature() if feat.IsFieldSetAndNotNull(0) == 0: - gdaltest.post_reason('fail') - print('field %s' % fieldname) feat.DumpReadable() - return 'fail' + pytest.fail('field %s' % fieldname) feat = sql_lyr.GetNextFeature() if feat.IsFieldSetAndNotNull(0) != 0: - gdaltest.post_reason('fail') - print('field %s' % fieldname) feat.DumpReadable() - return 'fail' + pytest.fail('field %s' % fieldname) ds.ReleaseResultSet(sql_lyr) - return 'success' - + ############################################################################### # Test select count([distinct] column) with null values (#4354) -def ogr_sql_37(): +def test_ogr_sql_37(): ds = ogr.GetDriverByName('Memory').CreateDataSource('ogr_sql_37') lyr = ds.CreateLayer('layer') @@ -1121,70 +1028,57 @@ def ogr_sql_37(): sql_lyr = ds.ExecuteSQL("select count(%s), count(distinct %s), count(*) from layer" % (fieldname, fieldname)) feat = sql_lyr.GetNextFeature() if feat.GetFieldAsInteger(0) != 2: - gdaltest.post_reason('fail') - print('field %s' % fieldname) feat.DumpReadable() - return 'fail' + pytest.fail('field %s' % fieldname) if feat.GetFieldAsInteger(1) != 1: - gdaltest.post_reason('fail') - print('field %s' % fieldname) feat.DumpReadable() - return 'fail' + pytest.fail('field %s' % fieldname) if feat.GetFieldAsInteger(2) != 4: - gdaltest.post_reason('fail') - print('field %s' % fieldname) feat.DumpReadable() - return 'fail' + pytest.fail('field %s' % fieldname) ds.ReleaseResultSet(sql_lyr) sql_lyr = ds.ExecuteSQL("select avg(intfield) from layer where intfield is null") feat = sql_lyr.GetNextFeature() if feat.IsFieldSetAndNotNull(0) != 0: - gdaltest.post_reason('fail') feat.DumpReadable() - return 'fail' + pytest.fail() ds.ReleaseResultSet(sql_lyr) # Fix crash when first values is null (#4509) sql_lyr = ds.ExecuteSQL("select distinct strfield_first_null from layer") feat = sql_lyr.GetNextFeature() if feat.IsFieldSetAndNotNull('strfield_first_null'): - gdaltest.post_reason('fail') feat.DumpReadable() - return 'fail' + pytest.fail() feat = sql_lyr.GetNextFeature() if feat.GetFieldAsString('strfield_first_null') != 'foo': - gdaltest.post_reason('fail') feat.DumpReadable() - return 'fail' + pytest.fail() ds.ReleaseResultSet(sql_lyr) sql_lyr = ds.ExecuteSQL("select distinct strfield_never_set from layer") feat = sql_lyr.GetNextFeature() if feat.IsFieldSetAndNotNull('strfield_never_set'): - gdaltest.post_reason('fail') feat.DumpReadable() - return 'fail' + pytest.fail() ds.ReleaseResultSet(sql_lyr) sql_lyr = ds.ExecuteSQL("select min(intfield_never_set), max(intfield_never_set), avg(intfield_never_set), sum(intfield_never_set), count(intfield_never_set) from layer") feat = sql_lyr.GetNextFeature() if feat.IsFieldSetAndNotNull(0) or feat.IsFieldSetAndNotNull(1) or feat.IsFieldSetAndNotNull(2) or feat.IsFieldSetAndNotNull(3) or feat.GetField(4) != 0: - gdaltest.post_reason('fail') feat.DumpReadable() - return 'fail' + pytest.fail() ds.ReleaseResultSet(sql_lyr) - return 'success' - ############################################################################### # Test "SELECT MAX(OGR_GEOM_AREA) FROM XXXX" (#4633) -def ogr_sql_38(): +def test_ogr_sql_38(): sql_lyr = gdaltest.ds.ExecuteSQL("SELECT MAX(OGR_GEOM_AREA) FROM poly") @@ -1194,15 +1088,14 @@ def ogr_sql_38(): gdaltest.ds.ReleaseResultSet(sql_lyr) if abs(val - 1634833.39062) < 1e-5: - return 'success' - print(val) - return 'fail' + return + pytest.fail(val) ############################################################################### # Test ORDER BY on a float special field -def ogr_sql_39(): +def test_ogr_sql_39(): sql_lyr = gdaltest.ds.ExecuteSQL("SELECT * FROM poly ORDER BY OGR_GEOM_AREA") @@ -1212,15 +1105,14 @@ def ogr_sql_39(): gdaltest.ds.ReleaseResultSet(sql_lyr) if abs(val - 5268.813) < 1e-5: - return 'success' - print(val) - return 'fail' + return + pytest.fail(val) ############################################################################### # Test ORDER BY on a int special field -def ogr_sql_40(): +def test_ogr_sql_40(): sql_lyr = gdaltest.ds.ExecuteSQL("SELECT * FROM poly ORDER BY FID DESC") @@ -1228,13 +1120,13 @@ def ogr_sql_40(): gdaltest.ds.ReleaseResultSet(sql_lyr) - return 'success' if feat.GetFID() == 9 else 'fail' + assert feat.GetFID() == 9 ############################################################################### # Test ORDER BY on a string special field -def ogr_sql_41(): +def test_ogr_sql_41(): sql_lyr = gdaltest.ds.ExecuteSQL("SELECT * FROM poly ORDER BY OGR_GEOMETRY") @@ -1242,36 +1134,30 @@ def ogr_sql_41(): gdaltest.ds.ReleaseResultSet(sql_lyr) - return 'success' if feat.GetFID() == 0 else 'fail' + assert feat.GetFID() == 0 ############################################################################### # Test comparing to empty string -def ogr_sql_42(): +def test_ogr_sql_42(): lyr = gdaltest.ds.GetLayerByName('poly') lyr.SetAttributeFilter("prfedea <> ''") feat = lyr.GetNextFeature() lyr.SetAttributeFilter(None) - if feat is None: - gdaltest.post_reason('fail') - return 'fail' + assert feat is not None sql_lyr = gdaltest.ds.ExecuteSQL("SELECT * FROM poly WHERE prfedea <> ''") feat = sql_lyr.GetNextFeature() gdaltest.ds.ReleaseResultSet(sql_lyr) - if feat is None: - gdaltest.post_reason('fail') - return 'fail' - - return 'success' + assert feat is not None ############################################################################### # Test escape sequences -def ogr_sql_43(): +def test_ogr_sql_43(): ret = 'success' sql = "SELECT '\"' as a, '\\\'' as b, '\'\'' as c FROM poly" @@ -1289,7 +1175,7 @@ def ogr_sql_43(): # Test hstore_get_value() -def ogr_sql_44(): +def test_ogr_sql_44(): # Invalid parameters for sql in ["SELECT hstore_get_value('a') FROM poly", @@ -1297,10 +1183,7 @@ def ogr_sql_44(): gdal.PushErrorHandler('CPLQuietErrorHandler') sql_lyr = gdaltest.ds.ExecuteSQL(sql) gdal.PopErrorHandler() - if sql_lyr is not None: - gdaltest.post_reason('fail') - print(sql) - return 'fail' + assert sql_lyr is None, sql # Invalid hstore syntax or empty result for sql in ["SELECT hstore_get_value('a', null) FROM poly", @@ -1320,10 +1203,8 @@ def ogr_sql_44(): sql_lyr = gdaltest.ds.ExecuteSQL(sql) f = sql_lyr.GetNextFeature() if f.IsFieldSetAndNotNull(0): - gdaltest.post_reason('fail') - print(sql) f.DumpReadable() - return 'fail' + pytest.fail(sql) gdaltest.ds.ReleaseResultSet(sql_lyr) # Valid hstore syntax @@ -1339,19 +1220,16 @@ def ogr_sql_44(): sql_lyr = gdaltest.ds.ExecuteSQL(sql) f = sql_lyr.GetNextFeature() if f.GetField(0) != expected: - gdaltest.post_reason('fail') - print(sql) f.DumpReadable() - return 'fail' + pytest.fail(sql) gdaltest.ds.ReleaseResultSet(sql_lyr) - return 'success' - + ############################################################################### # Test 64 bit GetFeatureCount() -def ogr_sql_45(): +def test_ogr_sql_45(): ds = ogr.Open("""<OGRVRTDataSource> <OGRVRTLayer name="poly"> @@ -1366,36 +1244,26 @@ def ogr_sql_45(): </OGRVRTDataSource>""") lyr = ds.GetLayer(0) - if lyr.GetFeatureCount() != 1000000000000: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.GetFeatureCount() == 1000000000000 sql_lyr = ds.ExecuteSQL('SELECT COUNT(*) FROM poly') f = sql_lyr.GetNextFeature() - if f.GetField(0) != 1000000000000: - gdaltest.post_reason('fail') - return 'fail' + assert f.GetField(0) == 1000000000000 f = None ds.ReleaseResultSet(sql_lyr) sql_lyr = ds.ExecuteSQL('SELECT COUNT(AREA) FROM poly') - if sql_lyr.GetLayerDefn().GetFieldDefn(0).GetType() != ogr.OFTInteger: - gdaltest.post_reason('fail') - return 'fail' + assert sql_lyr.GetLayerDefn().GetFieldDefn(0).GetType() == ogr.OFTInteger f = sql_lyr.GetNextFeature() - if f.GetField(0) != 10: - gdaltest.post_reason('fail') - return 'fail' + assert f.GetField(0) == 10 f = None ds.ReleaseResultSet(sql_lyr) - return 'success' - ############################################################################### # Test strict SQL quoting -def ogr_sql_46(): +def test_ogr_sql_46(): ds = ogr.GetDriverByName('Memory').CreateDataSource('test') lyr = ds.CreateLayer('test') @@ -1414,62 +1282,48 @@ def ogr_sql_46(): sql_lyr = ds.ExecuteSQL("select id, 'id', \"id\" as id2, id as \"id3\", \"from\" from test where \"from\" = 'from'") feat = sql_lyr.GetNextFeature() if feat.GetField(0) != 3 or feat.GetField(1) != 'id' or feat.GetField(2) != 3 or feat.GetField(3) != 3 or feat.GetField(4) != 'from': - gdaltest.post_reason('fail') feat.DumpReadable() - return 'fail' + pytest.fail() feat = sql_lyr.GetNextFeature() - if feat is not None: - gdaltest.post_reason('fail') - return 'fail' + assert feat is None ds.ReleaseResultSet(sql_lyr) sql_lyr = ds.ExecuteSQL("select max(\"id\"), max(id), count(\"id\"), count(id) from \"test\"") feat = sql_lyr.GetNextFeature() if feat.GetField(0) != 3 or feat.GetField(1) != 3 or feat.GetField(2) != 2 or feat.GetField(3) != 2: - gdaltest.post_reason('fail') feat.DumpReadable() - return 'fail' + pytest.fail() ds.ReleaseResultSet(sql_lyr) # Not accepted gdal.PushErrorHandler() sql_lyr = ds.ExecuteSQL("select * from 'test'") gdal.PopErrorHandler() - if sql_lyr is not None: - gdaltest.post_reason('fail') - return 'fail' + assert sql_lyr is None # Not accepted gdal.PushErrorHandler() sql_lyr = ds.ExecuteSQL("select distinct 'id' from 'test'") gdal.PopErrorHandler() - if sql_lyr is not None: - gdaltest.post_reason('fail') - return 'fail' + assert sql_lyr is None # Not accepted gdal.PushErrorHandler() sql_lyr = ds.ExecuteSQL("select max('id') from 'test'") gdal.PopErrorHandler() - if sql_lyr is not None: - gdaltest.post_reason('fail') - return 'fail' + assert sql_lyr is None # Not accepted gdal.PushErrorHandler() sql_lyr = ds.ExecuteSQL("select id as 'id2' from 'test'") gdal.PopErrorHandler() - if sql_lyr is not None: - gdaltest.post_reason('fail') - return 'fail' - - return 'success' + assert sql_lyr is None ############################################################################### # Test NULL sorting (#6155) -def ogr_sql_47(): +def test_ogr_sql_47(): ds = ogr.Open('data/sort_test.dbf') sql_lyr = ds.ExecuteSQL('SELECT * FROM sort_test ORDER BY text_value') @@ -1479,20 +1333,15 @@ def ogr_sql_47(): new_val = f['text_value'] else: new_val = '' - if new_val < prec_val: - gdaltest.post_reason('fail') - print("new_val = '%s', prec_val = '%s'" % (new_val, prec_val)) - return 'fail' + assert new_val >= prec_val, ("new_val = '%s', prec_val = '%s'" % (new_val, prec_val)) prec_val = new_val ds.ReleaseResultSet(sql_lyr) - return 'success' - ############################################################################### # Test sorting of more than 100 elements -def ogr_sql_48(): +def test_ogr_sql_48(): ds = ogr.GetDriverByName('Memory').CreateDataSource('') lyr = ds.CreateLayer('test', geom_type=ogr.wkbNone) @@ -1508,81 +1357,16 @@ def ogr_sql_48(): i = 1 for f in sql_lyr: if f['int_field'] != i: - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' + pytest.fail() i = i + 1 ds.ReleaseResultSet(sql_lyr) - if i != 1001: - gdaltest.post_reason('fail') - return 'fail' + assert i == 1001 - return 'success' - -def ogr_sql_cleanup(): +def test_ogr_sql_cleanup(): gdaltest.lyr = None gdaltest.ds = None - return 'success' - - -gdaltest_list = [ - ogr_sql_1, - ogr_sql_2, - ogr_sql_3, - ogr_sql_3_desc, - ogr_sql_4, - ogr_sql_5, - ogr_sql_6, - ogr_sql_7, - ogr_sql_8, - ogr_sql_9, - ogr_sql_10, - ogr_sql_11, - ogr_sql_12, - ogr_sql_13, - ogr_sql_14, - ogr_sql_15, - ogr_sql_16, - ogr_sql_17, - ogr_sql_18, - ogr_sql_19, - ogr_sql_20, - ogr_sql_21, - ogr_sql_22, - ogr_sql_23, - ogr_sql_24, - ogr_sql_25, - ogr_sql_26, - ogr_sql_27, - ogr_sql_28, - ogr_sql_29, - ogr_sql_30, - ogr_sql_31, - ogr_sql_32, - ogr_sql_33, - ogr_sql_34, - ogr_sql_35, - ogr_sql_36, - ogr_sql_37, - ogr_sql_38, - ogr_sql_39, - ogr_sql_40, - ogr_sql_41, - ogr_sql_42, - ogr_sql_43, - ogr_sql_44, - ogr_sql_45, - ogr_sql_46, - ogr_sql_47, - ogr_sql_48, - ogr_sql_cleanup] - -if __name__ == '__main__': - - gdaltest.setup_run('ogr_sql_test') - - gdaltest.run_tests(gdaltest_list) - - sys.exit(gdaltest.summarize()) + + diff --git a/autotest/ogr/ogr_sqlite.py b/autotest/ogr/ogr_sqlite.py index 9ee84ebc2430..a51a29410d78 100755 --- a/autotest/ogr/ogr_sqlite.py +++ b/autotest/ogr/ogr_sqlite.py @@ -31,15 +31,8 @@ ############################################################################### import os -import sys import shutil - -# Make sure we run from the directory of the script -if os.path.basename(sys.argv[0]) == os.path.basename(__file__): - if os.path.dirname(sys.argv[0]) != '': - os.chdir(os.path.dirname(sys.argv[0])) - -sys.path.append('../pymod') +import pytest from osgeo import gdal from osgeo import ogr @@ -47,20 +40,56 @@ import gdaltest import ogrtest -run_without_spatialite = True + +pytestmark = [ + pytest.mark.require_driver('SQLite'), +] + ############################################################################### -# Create a fresh database. +# Test if SpatiaLite is available + +@pytest.fixture(autouse=True, scope='module') +def setup(): + gdal.PushErrorHandler('CPLQuietErrorHandler') + ds = ogr.GetDriverByName('SQLite').CreateDataSource('/vsimem/foo.db', options=['SPATIALITE=YES']) + gdaltest.spatialite_version = None + if ds is not None: + sql_lyr = ds.ExecuteSQL("SELECT spatialite_version()") + feat = sql_lyr.GetNextFeature() + gdaltest.spatialite_version = feat.GetFieldAsString(0) + print('Spatialite : %s' % gdaltest.spatialite_version) + ds.ReleaseResultSet(sql_lyr) + ds = None + gdal.Unlink('/vsimem/foo.db') + gdal.PopErrorHandler() -def ogr_sqlite_1(): +@pytest.fixture() +def require_spatialite(setup): + if gdaltest.spatialite_version is None: + pytest.skip('Spatialite not available') + return gdaltest.spatialite_version + +@pytest.fixture(params=['no-spatialite', 'spatialite']) +def with_and_without_spatialite(request): + if request.param == 'spatialite': + return gdaltest.spatialite_version + else: + return None + + +############################################################################### +# Create a fresh database. + + +def test_ogr_sqlite_1(): gdaltest.sl_ds = None - gdaltest.has_spatialite = False sqlite_dr = ogr.GetDriverByName('SQLite') if sqlite_dr is None: - return 'skip' + pytest.skip() try: os.remove('tmp/sqlite_test.db') @@ -74,18 +103,16 @@ def ogr_sqlite_1(): gdaltest.sl_ds = sqlite_dr.CreateDataSource('tmp/sqlite_test.db') - if gdaltest.sl_ds is not None: - return 'success' - return 'fail' + assert gdaltest.sl_ds is not None ############################################################################### # Create table from data/poly.shp -def ogr_sqlite_2(): +def test_ogr_sqlite_2(): if gdaltest.sl_ds is None: - return 'skip' + pytest.skip() gdal.PushErrorHandler('CPLQuietErrorHandler') gdaltest.sl_ds.ExecuteSQL('DELLAYER:tpoly') @@ -95,24 +122,18 @@ def ogr_sqlite_2(): gdal.PushErrorHandler('CPLQuietErrorHandler') lyr = gdaltest.sl_ds.CreateLayer('will_fail', options=['FORMAT=FOO']) gdal.PopErrorHandler() - if lyr is not None: - gdaltest.post_reason('layer creation should have failed') - return 'fail' + assert lyr is None, 'layer creation should have failed' # Test creating a layer with an existing name lyr = gdaltest.sl_ds.CreateLayer('a_layer') gdal.PushErrorHandler('CPLQuietErrorHandler') lyr = gdaltest.sl_ds.CreateLayer('a_layer') gdal.PopErrorHandler() - if lyr is not None: - gdaltest.post_reason('layer creation should have failed') - return 'fail' + assert lyr is None, 'layer creation should have failed' # Test OVERWRITE=YES lyr = gdaltest.sl_ds.CreateLayer('a_layer', options=['FID=my_fid', 'GEOMETRY_NAME=mygeom', 'OVERWRITE=YES']) - if lyr is None: - gdaltest.post_reason('layer creation should have succeeded') - return 'fail' + assert lyr is not None, 'layer creation should have succeeded' ###################################################### # Create Layer @@ -140,9 +161,7 @@ def ogr_sqlite_2(): gdaltest.sl_ds = None gdaltest.sl_ds = ogr.Open('tmp/sqlite_test.db', update=1) gdaltest.sl_lyr = gdaltest.sl_ds.GetLayerByName('tpoly') - if gdaltest.sl_lyr.GetGeometryColumn() != 'GEOMETRY': - gdaltest.post_reason('failure') - return 'fail' + assert gdaltest.sl_lyr.GetGeometryColumn() == 'GEOMETRY' for field_desc in fields: feature_def = gdaltest.sl_lyr.GetLayerDefn() @@ -152,20 +171,12 @@ def ogr_sqlite_2(): (field_desc[0], field_defn.GetFieldTypeName(field_defn.GetType()), field_defn.GetFieldTypeName(field_desc[1]))) field_defn = feature_def.GetFieldDefn(feature_def.GetFieldIndex('fld_boolean')) - if field_defn.GetType() != ogr.OFTInteger or field_defn.GetSubType() != ogr.OFSTBoolean: - gdaltest.post_reason('failure') - return 'fail' + assert field_defn.GetType() == ogr.OFTInteger and field_defn.GetSubType() == ogr.OFSTBoolean field_defn = feature_def.GetFieldDefn(feature_def.GetFieldIndex('INT64')) - if field_defn.GetType() != ogr.OFTInteger64: - gdaltest.post_reason('failure') - return 'fail' + assert field_defn.GetType() == ogr.OFTInteger64 - if gdaltest.sl_ds.GetLayerByName('a_layer').GetGeometryColumn() != 'mygeom': - gdaltest.post_reason('failure') - return 'fail' - if gdaltest.sl_ds.GetLayerByName('a_layer').GetFIDColumn() != 'my_fid': - gdaltest.post_reason('failure') - return 'fail' + assert gdaltest.sl_ds.GetLayerByName('a_layer').GetGeometryColumn() == 'mygeom' + assert gdaltest.sl_ds.GetLayerByName('a_layer').GetFIDColumn() == 'my_fid' ###################################################### # Copy in poly.shp @@ -193,19 +204,15 @@ def ogr_sqlite_2(): gdaltest.sl_lyr.CommitTransaction() - return 'success' - ############################################################################### # Verify that stuff we just wrote is still OK. -def ogr_sqlite_3(): +def test_ogr_sqlite_3(): if gdaltest.sl_ds is None: - return 'skip' + pytest.skip() - if gdaltest.sl_lyr.GetFeatureCount() != 10: - gdaltest.post_reason('GetFeatureCount() returned %d instead of 10' % gdaltest.sl_lyr.GetFeatureCount()) - return 'fail' + assert gdaltest.sl_lyr.GetFeatureCount() == 10 expect = [168, 169, 166, 158, 165] @@ -213,9 +220,7 @@ def ogr_sqlite_3(): tr = ogrtest.check_features_against_list(gdaltest.sl_lyr, 'eas_id', expect) - if gdaltest.sl_lyr.GetFeatureCount() != 5: - gdaltest.post_reason('GetFeatureCount() returned %d instead of 5' % gdaltest.sl_lyr.GetFeatureCount()) - return 'fail' + assert gdaltest.sl_lyr.GetFeatureCount() == 5 gdaltest.sl_lyr.SetAttributeFilter(None) @@ -223,37 +228,32 @@ def ogr_sqlite_3(): orig_feat = gdaltest.poly_feat[i] read_feat = gdaltest.sl_lyr.GetNextFeature() - if read_feat is None: - gdaltest.post_reason('Did not get as many features as expected.') - return 'fail' + assert read_feat is not None, 'Did not get as many features as expected.' - if ogrtest.check_feature_geometry(read_feat, orig_feat.GetGeometryRef(), - max_error=0.001) != 0: - return 'fail' + assert (ogrtest.check_feature_geometry(read_feat, orig_feat.GetGeometryRef(), + max_error=0.001) == 0) for fld in range(3): - if orig_feat.GetField(fld) != read_feat.GetField(fld): - gdaltest.post_reason('Attribute %d does not match' % fld) - return 'fail' + assert orig_feat.GetField(fld) == read_feat.GetField(fld), \ + ('Attribute %d does not match' % fld) if read_feat.GetField('int64') != 1234567890123: - gdaltest.post_reason('failure') read_feat.DumpReadable() - return 'fail' + pytest.fail() gdaltest.poly_feat = None gdaltest.shp_ds = None - return 'success' if tr else 'fail' + assert tr ############################################################################### # Write more features with a bunch of different geometries, and verify the # geometries are still OK. -def ogr_sqlite_4(): +def test_ogr_sqlite_4(): if gdaltest.sl_ds is None: - return 'skip' + pytest.skip() dst_feat = ogr.Feature(feature_def=gdaltest.sl_lyr.GetLayerDefn()) wkt_list = ['10', '2', '1', '3d_1', '4', '5', '6'] @@ -277,46 +277,40 @@ def ogr_sqlite_4(): gdaltest.sl_lyr.SetAttributeFilter("PRFEDEA = '%s'" % item) feat_read = gdaltest.sl_lyr.GetNextFeature() - if feat_read is None: - gdaltest.post_reason('Did not get as many features as expected.') - return 'fail' + assert feat_read is not None, 'Did not get as many features as expected.' - if ogrtest.check_feature_geometry(feat_read, geom) != 0: - return 'fail' + assert ogrtest.check_feature_geometry(feat_read, geom) == 0 - return 'success' ############################################################################### # Test ExecuteSQL() results layers without geometry. -def ogr_sqlite_5(): +def test_ogr_sqlite_5(): if gdaltest.sl_ds is None: - return 'skip' + pytest.skip() expect = [179, 173, 172, 171, 170, 169, 168, 166, 165, 158, None] sql_lyr = gdaltest.sl_ds.ExecuteSQL('select distinct eas_id from tpoly order by eas_id desc') - if sql_lyr.GetFeatureCount() != 11: - gdaltest.post_reason('GetFeatureCount() returned %d instead of 11' % sql_lyr.GetFeatureCount()) - return 'fail' + assert sql_lyr.GetFeatureCount() == 11 tr = ogrtest.check_features_against_list(sql_lyr, 'eas_id', expect) gdaltest.sl_ds.ReleaseResultSet(sql_lyr) - return 'success' if tr else 'fail' + assert tr ############################################################################### # Test ExecuteSQL() results layers with geometry. -def ogr_sqlite_6(): +def test_ogr_sqlite_6(): if gdaltest.sl_ds is None: - return 'skip' + pytest.skip() sql_lyr = gdaltest.sl_ds.ExecuteSQL("select * from tpoly where prfedea = '2'") @@ -329,16 +323,16 @@ def ogr_sqlite_6(): gdaltest.sl_ds.ReleaseResultSet(sql_lyr) - return 'success' if tr else 'fail' + assert tr ############################################################################### # Test spatial filtering. -def ogr_sqlite_7(): +def test_ogr_sqlite_7(): if gdaltest.sl_ds is None: - return 'skip' + pytest.skip() gdaltest.sl_lyr.SetAttributeFilter(None) @@ -347,33 +341,29 @@ def ogr_sqlite_7(): gdaltest.sl_lyr.SetSpatialFilter(geom) geom.Destroy() - if gdaltest.sl_lyr.GetFeatureCount() != 1: - gdaltest.post_reason('GetFeatureCount() returned %d instead of 1' % gdaltest.sl_lyr.GetFeatureCount()) - return 'fail' + assert gdaltest.sl_lyr.GetFeatureCount() == 1 tr = ogrtest.check_features_against_list(gdaltest.sl_lyr, 'eas_id', [158]) gdaltest.sl_lyr.SetAttributeFilter('eas_id = 158') - if gdaltest.sl_lyr.GetFeatureCount() != 1: - gdaltest.post_reason('GetFeatureCount() returned %d instead of 1' % gdaltest.sl_lyr.GetFeatureCount()) - return 'fail' + assert gdaltest.sl_lyr.GetFeatureCount() == 1 gdaltest.sl_lyr.SetAttributeFilter(None) gdaltest.sl_lyr.SetSpatialFilter(None) - return 'success' if tr else 'fail' + assert tr ############################################################################### # Test transactions with rollback. -def ogr_sqlite_8(): +def test_ogr_sqlite_8(): if gdaltest.sl_ds is None: - return 'skip' + pytest.skip() ###################################################################### # Prepare working feature. @@ -397,9 +387,7 @@ def ogr_sqlite_8(): feat_read = gdaltest.sl_lyr.GetNextFeature() gdaltest.sl_lyr.SetAttributeFilter(None) - if feat_read is not None: - gdaltest.post_reason('Unexpectedly got rollbacktest feature.') - return 'fail' + assert feat_read is None, 'Unexpectedly got rollbacktest feature.' ###################################################################### # Create it, and commit the transaction. @@ -415,23 +403,19 @@ def ogr_sqlite_8(): feat_read = gdaltest.sl_lyr.GetNextFeature() gdaltest.sl_lyr.SetAttributeFilter(None) - if feat_read is None: - gdaltest.post_reason('Failed to get committed feature.') - return 'fail' + assert feat_read is not None, 'Failed to get committed feature.' feat_read.Destroy() dst_feat.Destroy() - return 'success' - ############################################################################### # Test SetFeature() -def ogr_sqlite_9(): +def test_ogr_sqlite_9(): if gdaltest.sl_ds is None: - return 'skip' + pytest.skip() ###################################################################### # Read feature with EAS_ID 158. @@ -440,18 +424,14 @@ def ogr_sqlite_9(): feat_read = gdaltest.sl_lyr.GetNextFeature() gdaltest.sl_lyr.SetAttributeFilter(None) - if feat_read is None: - gdaltest.post_reason('did not find eas_id 158!') - return 'fail' + assert feat_read is not None, 'did not find eas_id 158!' ###################################################################### # Modify the PRFEDEA value, and reset it. feat_read.SetField('PRFEDEA', 'SetWorked') err = gdaltest.sl_lyr.SetFeature(feat_read) - if err != 0: - gdaltest.post_reason('SetFeature() reported error %d' % err) - return 'fail' + assert err == 0, ('SetFeature() reported error %d' % err) ###################################################################### # Read feature with EAS_ID 158 and check that PRFEDEA was altered. @@ -460,39 +440,32 @@ def ogr_sqlite_9(): feat_read_2 = gdaltest.sl_lyr.GetNextFeature() gdaltest.sl_lyr.SetAttributeFilter(None) - if feat_read_2 is None: - gdaltest.post_reason('did not find eas_id 158!') - return 'fail' + assert feat_read_2 is not None, 'did not find eas_id 158!' if feat_read_2.GetField('PRFEDEA') != 'SetWorked': feat_read_2.DumpReadable() - gdaltest.post_reason('PRFEDEA apparently not reset as expected.') - return 'fail' + pytest.fail('PRFEDEA apparently not reset as expected.') # Test updating non-existing feature feat_read.SetFID(-10) - if gdaltest.sl_lyr.SetFeature(feat_read) != ogr.OGRERR_NON_EXISTING_FEATURE: - gdaltest.post_reason('Expected failure of SetFeature().') - return 'fail' + assert gdaltest.sl_lyr.SetFeature(feat_read) == ogr.OGRERR_NON_EXISTING_FEATURE, \ + 'Expected failure of SetFeature().' # Test deleting non-existing feature - if gdaltest.sl_lyr.DeleteFeature(-10) != ogr.OGRERR_NON_EXISTING_FEATURE: - gdaltest.post_reason('Expected failure of DeleteFeature().') - return 'fail' + assert gdaltest.sl_lyr.DeleteFeature(-10) == ogr.OGRERR_NON_EXISTING_FEATURE, \ + 'Expected failure of DeleteFeature().' feat_read.Destroy() feat_read_2.Destroy() - return 'success' - ############################################################################### # Test GetFeature() -def ogr_sqlite_10(): +def test_ogr_sqlite_10(): if gdaltest.sl_ds is None: - return 'skip' + pytest.skip() ###################################################################### # Read feature with EAS_ID 158. @@ -501,35 +474,29 @@ def ogr_sqlite_10(): feat_read = gdaltest.sl_lyr.GetNextFeature() gdaltest.sl_lyr.SetAttributeFilter(None) - if feat_read is None: - gdaltest.post_reason('did not find eas_id 158!') - return 'fail' + assert feat_read is not None, 'did not find eas_id 158!' ###################################################################### # Now read the feature by FID. feat_read_2 = gdaltest.sl_lyr.GetFeature(feat_read.GetFID()) - if feat_read_2 is None: - gdaltest.post_reason('did not find FID %d' % feat_read.GetFID()) - return 'fail' + assert feat_read_2 is not None, ('did not find FID %d' % feat_read.GetFID()) if feat_read_2.GetField('PRFEDEA') != feat_read.GetField('PRFEDEA'): feat_read.DumpReadable() feat_read_2.DumpReadable() - gdaltest.post_reason('GetFeature() result seems to not match expected.') - return 'fail' - - return 'success' + pytest.fail('GetFeature() result seems to not match expected.') + ############################################################################### # Test FORMAT=WKB creation option -def ogr_sqlite_11(): +def test_ogr_sqlite_11(): if gdaltest.sl_ds is None: - return 'skip' + pytest.skip() ###################################################### # Create Layer with WKB geometry @@ -551,21 +518,18 @@ def ogr_sqlite_11(): gdaltest.sl_lyr = gdaltest.sl_ds.GetLayerByName('geomwkb') feat_read = gdaltest.sl_lyr.GetNextFeature() - if ogrtest.check_feature_geometry(feat_read, geom, max_error=0.001) != 0: - return 'fail' + assert ogrtest.check_feature_geometry(feat_read, geom, max_error=0.001) == 0 gdaltest.sl_lyr.ResetReading() - return 'success' - ############################################################################### # Test FORMAT=WKT creation option -def ogr_sqlite_12(): +def test_ogr_sqlite_12(): if gdaltest.sl_ds is None: - return 'skip' + pytest.skip() ###################################################### # Create Layer with WKT geometry @@ -587,8 +551,7 @@ def ogr_sqlite_12(): gdaltest.sl_lyr = gdaltest.sl_ds.GetLayerByName('geomwkt') feat_read = gdaltest.sl_lyr.GetNextFeature() - if ogrtest.check_feature_geometry(feat_read, geom, max_error=0.001) != 0: - return 'fail' + assert ogrtest.check_feature_geometry(feat_read, geom, max_error=0.001) == 0 feat_read = None gdaltest.sl_lyr.ResetReading() @@ -596,27 +559,23 @@ def ogr_sqlite_12(): sql_lyr = gdaltest.sl_ds.ExecuteSQL("select * from geomwkt") feat_read = sql_lyr.GetNextFeature() - if ogrtest.check_feature_geometry(feat_read, geom, max_error=0.001) != 0: - return 'fail' + assert ogrtest.check_feature_geometry(feat_read, geom, max_error=0.001) == 0 feat_read = None feat_read = sql_lyr.GetFeature(0) - if ogrtest.check_feature_geometry(feat_read, geom, max_error=0.001) != 0: - return 'fail' + assert ogrtest.check_feature_geometry(feat_read, geom, max_error=0.001) == 0 feat_read = None gdaltest.sl_ds.ReleaseResultSet(sql_lyr) - return 'success' - ############################################################################### # Test SRID support -def ogr_sqlite_13(): +def test_ogr_sqlite_13(): if gdaltest.sl_ds is None: - return 'skip' + pytest.skip() ###################################################### # Create Layer with EPSG:4326 @@ -630,9 +589,7 @@ def ogr_sqlite_13(): gdaltest.sl_ds = ogr.Open('tmp/sqlite_test.db', update=1) gdaltest.sl_lyr = gdaltest.sl_ds.GetLayerByName('wgs84layer') - if not gdaltest.sl_lyr.GetSpatialRef().IsSame(srs): - gdaltest.post_reason('SRS is not the one expected.') - return 'fail' + assert gdaltest.sl_lyr.GetSpatialRef().IsSame(srs), 'SRS is not the one expected.' ###################################################### # Create second layer with very approximative EPSG:4326 @@ -643,20 +600,17 @@ def ogr_sqlite_13(): # Must still be 1 sql_lyr = gdaltest.sl_ds.ExecuteSQL("SELECT COUNT(*) AS count FROM spatial_ref_sys") feat = sql_lyr.GetNextFeature() - if feat.GetFieldAsInteger('count') != 1: - return 'fail' + assert feat.GetFieldAsInteger('count') == 1 gdaltest.sl_ds.ReleaseResultSet(sql_lyr) - return 'success' - ############################################################################### # Test all column types -def ogr_sqlite_14(): +def test_ogr_sqlite_14(): if gdaltest.sl_ds is None: - return 'skip' + pytest.skip() gdaltest.sl_lyr = gdaltest.sl_ds.CreateLayer('testtypes') ogrtest.quick_create_layer_def(gdaltest.sl_lyr, @@ -691,24 +645,21 @@ def ogr_sqlite_14(): gdaltest.sl_lyr.ResetReading() for _ in range(2): feat_read = gdaltest.sl_lyr.GetNextFeature() - if feat_read.GetField('INTEGER') != 1 or \ - feat_read.GetField('FLOAT') != 1.2 or \ - feat_read.GetField('STRING') != 'myString\'a' or \ - feat_read.GetFieldAsString('BLOB') != '0001FF': - return 'fail' + assert (feat_read.GetField('INTEGER') == 1 and \ + feat_read.GetField('FLOAT') == 1.2 and \ + feat_read.GetField('STRING') == 'myString\'a' and \ + feat_read.GetFieldAsString('BLOB') == '0001FF') gdaltest.sl_lyr.ResetReading() - return 'success' - ############################################################################### # Test FORMAT=SPATIALITE layer creation option -def ogr_sqlite_15(): +def test_ogr_sqlite_15(): if gdaltest.sl_ds is None: - return 'skip' + pytest.skip() ###################################################### # Create Layer with SPATIALITE geometry @@ -749,41 +700,34 @@ def ogr_sqlite_15(): gdal.PushErrorHandler('CPLQuietErrorHandler') lyr = gdaltest.sl_ds.CreateLayer('will_fail') gdal.PopErrorHandler() - if lyr is not None: - gdaltest.post_reason('layer creation should have failed') - return 'fail' + assert lyr is None, 'layer creation should have failed' gdaltest.sl_lyr = gdaltest.sl_ds.GetLayerByName('geomspatialite') for geom in geoms: feat_read = gdaltest.sl_lyr.GetNextFeature() - if ogrtest.check_feature_geometry(feat_read, geom, max_error=0.001) != 0: - return 'fail' + assert ogrtest.check_feature_geometry(feat_read, geom, max_error=0.001) == 0 gdaltest.sl_lyr.ResetReading() sql_lyr = gdaltest.sl_ds.ExecuteSQL("select * from geomspatialite") feat_read = sql_lyr.GetNextFeature() - if ogrtest.check_feature_geometry(feat_read, geoms[0], max_error=0.001) != 0: - return 'fail' + assert ogrtest.check_feature_geometry(feat_read, geoms[0], max_error=0.001) == 0 feat_read = sql_lyr.GetFeature(0) - if ogrtest.check_feature_geometry(feat_read, geoms[0], max_error=0.001) != 0: - return 'fail' + assert ogrtest.check_feature_geometry(feat_read, geoms[0], max_error=0.001) == 0 gdaltest.sl_ds.ReleaseResultSet(sql_lyr) - return 'success' - ############################################################################### # Test reading geometries in FGF (FDO Geometry Format) binary representation. -def ogr_sqlite_16(): +def test_ogr_sqlite_16(): if gdaltest.sl_ds is None: - return 'skip' + pytest.skip() ###################################################### # Reopen DB in update @@ -815,63 +759,52 @@ def ogr_sqlite_16(): feat = gdaltest.sl_lyr.GetNextFeature() geom = feat.GetGeometryRef() - if geom.ExportToWkt() != 'POINT (1 2)': - return 'fail' + assert geom.ExportToWkt() == 'POINT (1 2)' feat = gdaltest.sl_lyr.GetNextFeature() geom = feat.GetGeometryRef() - if geom.ExportToWkt() != 'LINESTRING EMPTY': - return 'fail' + assert geom.ExportToWkt() == 'LINESTRING EMPTY' feat = gdaltest.sl_lyr.GetNextFeature() geom = feat.GetGeometryRef() - if geom.ExportToWkt() != 'LINESTRING (1 2,3 4)': - return 'fail' + assert geom.ExportToWkt() == 'LINESTRING (1 2,3 4)' feat = gdaltest.sl_lyr.GetNextFeature() geom = feat.GetGeometryRef() - if geom.ExportToWkt() != 'POLYGON EMPTY': - return 'fail' + assert geom.ExportToWkt() == 'POLYGON EMPTY' feat = gdaltest.sl_lyr.GetNextFeature() geom = feat.GetGeometryRef() - if geom.ExportToWkt() != 'POLYGON ((1 2,3 4))': - return 'fail' + assert geom.ExportToWkt() == 'POLYGON ((1 2,3 4))' feat = gdaltest.sl_lyr.GetNextFeature() geom = feat.GetGeometryRef() - if geom.ExportToWkt() != 'GEOMETRYCOLLECTION EMPTY': - return 'fail' + assert geom.ExportToWkt() == 'GEOMETRYCOLLECTION EMPTY' feat = gdaltest.sl_lyr.GetNextFeature() geom = feat.GetGeometryRef() - if geom.ExportToWkt() != 'GEOMETRYCOLLECTION (POLYGON ((1 2,3 4)),POLYGON ((1 2,3 4)))': - return 'fail' + assert geom.ExportToWkt() == 'GEOMETRYCOLLECTION (POLYGON ((1 2,3 4)),POLYGON ((1 2,3 4)))' feat = gdaltest.sl_lyr.GetNextFeature() geom = feat.GetGeometryRef() - if geom.ExportToWkt() != 'POINT (1 2 3)': - return 'fail' + assert geom.ExportToWkt() == 'POINT (1 2 3)' # Test invalid geometries for _ in range(3): feat = gdaltest.sl_lyr.GetNextFeature() geom = feat.GetGeometryRef() - if geom is not None: - return 'fail' + assert geom is None gdaltest.sl_lyr.ResetReading() - return 'success' - ############################################################################### # Test SPATIALITE dataset creation option -def ogr_sqlite_17(): +def test_ogr_sqlite_17(require_spatialite): if gdaltest.sl_ds is None: - return 'skip' + pytest.skip() ###################################################### # Create dataset with SPATIALITE geometry @@ -879,17 +812,10 @@ def ogr_sqlite_17(): with gdaltest.error_handler(): ds = ogr.GetDriverByName('SQLite').CreateDataSource('tmp/spatialite_test.db', options=['SPATIALITE=YES']) - if not gdaltest.has_spatialite: - if ds is not None: - return 'fail' - return 'success' - gdal.PushErrorHandler('CPLQuietErrorHandler') lyr = ds.CreateLayer('will_fail', options=['FORMAT=WKB']) gdal.PopErrorHandler() - if lyr is not None: - gdaltest.post_reason('layer creation should have failed') - return 'fail' + assert lyr is None, 'layer creation should have failed' srs = osr.SpatialReference() srs.SetFromUserInput("""GEOGCS["GCS_WGS_1984",DATUM["WGS_1984",SPHEROID["WGS_1984",6378137,298.257223563]],PRIMEM["Greenwich",0],UNIT["Degree",0.017453292519943295]]""") @@ -908,29 +834,20 @@ def ogr_sqlite_17(): lyr = ds.GetLayerByName('geomspatialite') feat_read = lyr.GetNextFeature() - if ogrtest.check_feature_geometry(feat_read, geom, max_error=0.001) != 0: - return 'fail' + assert ogrtest.check_feature_geometry(feat_read, geom, max_error=0.001) == 0 srs = lyr.GetSpatialRef() wkt = srs.ExportToWkt() - if wkt.find('4326') == -1: - gdaltest.post_reason('did not identify correctly SRS') - print(wkt) - return 'fail' + assert wkt.find('4326') != -1, 'did not identify correctly SRS' - return 'success' ############################################################################### # Create a layer with a non EPSG SRS into a SPATIALITE DB (#3506) -def ogr_sqlite_18(): - +def test_ogr_sqlite_18(require_spatialite): if gdaltest.sl_ds is None: - return 'skip' - - if not gdaltest.has_spatialite: - return 'skip' + pytest.skip() ds = ogr.Open('tmp/spatialite_test.db', update=1) srs = osr.SpatialReference() @@ -945,39 +862,30 @@ def ogr_sqlite_18(): lyr = ds.GetLayerByName('nonepsgsrs') srs = lyr.GetSpatialRef() wkt = srs.ExportToWkt() - if wkt.find('VanDerGrinten') == -1: - gdaltest.post_reason('did not identify correctly SRS') - print(wkt) - return 'fail' + assert wkt.find('VanDerGrinten') != -1, 'did not identify correctly SRS' sql_lyr = ds.ExecuteSQL("SELECT * FROM spatial_ref_sys ORDER BY srid DESC LIMIT 1") feat = sql_lyr.GetNextFeature() if feat.GetField('auth_name') != 'OGR' or \ feat.GetField('proj4text').find('+proj=vandg') != 0: feat.DumpReadable() - gdaltest.post_reason('fail') - return 'fail' + pytest.fail() gdaltest.sl_ds.ReleaseResultSet(sql_lyr) - return 'success' - ############################################################################### # Create a SpatiaLite DB with INIT_WITH_EPSG=YES -def ogr_sqlite_19(): +def test_ogr_sqlite_19(require_spatialite): if gdaltest.sl_ds is None: - return 'skip' + pytest.skip() if int(gdal.VersionInfo('VERSION_NUM')) < 1800: - return 'skip' - - if not gdaltest.has_spatialite: - return 'skip' + pytest.skip() - if gdaltest.spatialite_version != '2.3.1': - return 'skip' + if require_spatialite != '2.3.1': + pytest.skip() ds = ogr.GetDriverByName('SQLite').CreateDataSource('tmp/spatialite_test_with_epsg.db', options=['SPATIALITE=YES', 'INIT_WITH_EPSG=YES']) @@ -995,27 +903,21 @@ def ogr_sqlite_19(): ds.ReleaseResultSet(sql_lyr) # Currently the injection of the EPSG DB as proj.4 strings adds 3915 entries - if nb_srs < 3915: - gdaltest.post_reason('did not get expected SRS count') - print(nb_srs) - return 'fail' + assert nb_srs >= 3915, 'did not get expected SRS count' - return 'success' ############################################################################### # Create a SpatiaLite DB with INIT_WITH_EPSG=NO -def ogr_sqlite_19_bis(): +def test_ogr_sqlite_19_bis(require_spatialite): if gdaltest.sl_ds is None: - return 'skip' + pytest.skip() - if not gdaltest.has_spatialite: - return 'skip' - - if int(gdaltest.spatialite_version[0:gdaltest.spatialite_version.find('.')]) < 4: - return 'skip' + spatialite_major_ver = int(require_spatialite.split('.')[0]) + if spatialite_major_ver < 4: + pytest.skip() ds = ogr.GetDriverByName('SQLite').CreateDataSource('/vsimem/spatialite_test_without_epsg.db', options=['SPATIALITE=YES', 'INIT_WITH_EPSG=NO']) @@ -1032,23 +934,18 @@ def ogr_sqlite_19_bis(): nb_srs = feat.GetFieldAsInteger(0) ds.ReleaseResultSet(sql_lyr) - if nb_srs != 1: - gdaltest.post_reason('did not get expected SRS count') - print(nb_srs) - return 'fail' + assert nb_srs == 1, 'did not get expected SRS count' gdal.Unlink('/vsimem/spatialite_test_without_epsg.db') - return 'success' - ############################################################################### # Create a regular DB with INIT_WITH_EPSG=YES -def ogr_sqlite_20(): +def test_ogr_sqlite_20(): if gdaltest.sl_ds is None: - return 'skip' + pytest.skip() gdal.Unlink('tmp/non_spatialite_test_with_epsg.db') @@ -1068,135 +965,96 @@ def ogr_sqlite_20(): ds.ReleaseResultSet(sql_lyr) # Currently the injection of the EPSG DB as proj.4 strings adds 3945 entries - if nb_srs < 3945: - gdaltest.post_reason('did not get expected SRS count') - print(nb_srs) - return 'fail' + assert nb_srs >= 3945, 'did not get expected SRS count' - return 'success' ############################################################################### # Test CopyLayer() from a table layer (#3617) -def ogr_sqlite_21(): +def test_ogr_sqlite_21(): if gdaltest.sl_ds is None: - return 'skip' + pytest.skip() src_lyr = gdaltest.sl_ds.GetLayerByName('tpoly') copy_lyr = gdaltest.sl_ds.CopyLayer(src_lyr, 'tpoly_2') src_lyr_count = src_lyr.GetFeatureCount() copy_lyr_count = copy_lyr.GetFeatureCount() - if src_lyr_count != copy_lyr_count: - gdaltest.post_reason('did not get same number of features') - print(src_lyr_count) - print(copy_lyr_count) - return 'fail' - - return 'success' + assert src_lyr_count == copy_lyr_count, 'did not get same number of features' ############################################################################### # Test CopyLayer() from a result layer (#3617) -def ogr_sqlite_22(): +def test_ogr_sqlite_22(): if gdaltest.sl_ds is None: - return 'skip' + pytest.skip() src_lyr = gdaltest.sl_ds.ExecuteSQL('select * from tpoly') copy_lyr = gdaltest.sl_ds.CopyLayer(src_lyr, 'tpoly_3') src_lyr_count = src_lyr.GetFeatureCount() copy_lyr_count = copy_lyr.GetFeatureCount() - if src_lyr_count != copy_lyr_count: - gdaltest.post_reason('did not get same number of features') - print(src_lyr_count) - print(copy_lyr_count) - return 'fail' + assert src_lyr_count == copy_lyr_count, 'did not get same number of features' gdaltest.sl_ds.ReleaseResultSet(src_lyr) - return 'success' - ############################################################################### # Test ignored fields works ok -def ogr_sqlite_23(): +def test_ogr_sqlite_23(): if gdaltest.sl_ds is None: - return 'skip' + pytest.skip() shp_layer = gdaltest.sl_ds.GetLayerByName('tpoly') shp_layer.SetIgnoredFields(['AREA']) feat = shp_layer.GetNextFeature() - if feat.IsFieldSet('AREA'): - gdaltest.post_reason('got area despite request to ignore it.') - return 'fail' + assert not feat.IsFieldSet('AREA'), 'got area despite request to ignore it.' - if feat.GetFieldAsInteger('EAS_ID') != 168: - gdaltest.post_reason('missing or wrong eas_id') - return 'fail' + assert feat.GetFieldAsInteger('EAS_ID') == 168, 'missing or wrong eas_id' wkt = 'POLYGON ((479819.84375 4765180.5,479690.1875 4765259.5,479647.0 4765369.5,479730.375 4765400.5,480039.03125 4765539.5,480035.34375 4765558.5,480159.78125 4765610.5,480202.28125 4765482.0,480365.0 4765015.5,480389.6875 4764950.0,480133.96875 4764856.5,480080.28125 4764979.5,480082.96875 4765049.5,480088.8125 4765139.5,480059.90625 4765239.5,480019.71875 4765319.5,479980.21875 4765409.5,479909.875 4765370.0,479859.875 4765270.0,479819.84375 4765180.5))' - if ogrtest.check_feature_geometry(feat, wkt, - max_error=0.00000001) != 0: - return 'fail' + assert (ogrtest.check_feature_geometry(feat, wkt, + max_error=0.00000001) == 0) fd = shp_layer.GetLayerDefn() fld = fd.GetFieldDefn(0) # area - if not fld.IsIgnored(): - gdaltest.post_reason('AREA unexpectedly not marked as ignored.') - return 'fail' + assert fld.IsIgnored(), 'AREA unexpectedly not marked as ignored.' fld = fd.GetFieldDefn(1) # eas_id - if fld.IsIgnored(): - gdaltest.post_reason('EASI unexpectedly marked as ignored.') - return 'fail' + assert not fld.IsIgnored(), 'EASI unexpectedly marked as ignored.' - if fd.IsGeometryIgnored(): - gdaltest.post_reason('geometry unexpectedly ignored.') - return 'fail' + assert not fd.IsGeometryIgnored(), 'geometry unexpectedly ignored.' - if fd.IsStyleIgnored(): - gdaltest.post_reason('style unexpectedly ignored.') - return 'fail' + assert not fd.IsStyleIgnored(), 'style unexpectedly ignored.' fd.SetGeometryIgnored(1) - if not fd.IsGeometryIgnored(): - gdaltest.post_reason('geometry unexpectedly not ignored.') - return 'fail' + assert fd.IsGeometryIgnored(), 'geometry unexpectedly not ignored.' feat = shp_layer.GetNextFeature() - if feat.GetGeometryRef() is not None: - gdaltest.post_reason('Unexpectedly got a geometry on feature 2.') - return 'fail' + assert feat.GetGeometryRef() is None, 'Unexpectedly got a geometry on feature 2.' - if feat.IsFieldSet('AREA'): - gdaltest.post_reason('got area despite request to ignore it.') - return 'fail' + assert not feat.IsFieldSet('AREA'), 'got area despite request to ignore it.' - if feat.GetFieldAsInteger('EAS_ID') != 179: - gdaltest.post_reason('missing or wrong eas_id') - return 'fail' - - return 'success' + assert feat.GetFieldAsInteger('EAS_ID') == 179, 'missing or wrong eas_id' ############################################################################### # Test that ExecuteSQL() with OGRSQL dialect doesn't forward the where clause to sqlite (#4022) -def ogr_sqlite_24(): +def test_ogr_sqlite_24(): if gdaltest.sl_ds is None: - return 'skip' + pytest.skip() try: os.remove('tmp/test24.sqlite') @@ -1221,54 +1079,43 @@ def ogr_sqlite_24(): lyr = ds.ExecuteSQL('select OGR_GEOMETRY from test') gdal.PopErrorHandler() if lyr is not None: - gdaltest.post_reason('this should not work (1)') ds.ReleaseResultSet(lyr) - return 'fail' + pytest.fail('this should not work (1)') lyr = ds.ExecuteSQL('select * from test') lyr.SetAttributeFilter("OGR_GEOMETRY = 'POLYGON'") feat = lyr.GetNextFeature() ds.ReleaseResultSet(lyr) - if feat is None: - gdaltest.post_reason('a feature was expected (2)') - return 'fail' + assert feat is not None, 'a feature was expected (2)' lyr = ds.GetLayerByName('test') lyr.SetAttributeFilter("OGR_GEOMETRY = 'POLYGON'") gdal.PushErrorHandler('CPLQuietErrorHandler') feat = lyr.GetNextFeature() gdal.PopErrorHandler() - if feat is not None: - gdaltest.post_reason('a feature was not expected (3)') - return 'fail' + assert feat is None, 'a feature was not expected (3)' lyr = ds.ExecuteSQL('select OGR_GEOMETRY from test', dialect='OGRSQL') lyr.SetAttributeFilter("OGR_GEOMETRY = 'POLYGON'") feat = lyr.GetNextFeature() ds.ReleaseResultSet(lyr) - if feat is None: - gdaltest.post_reason('a feature was expected (4)') - return 'fail' + assert feat is not None, 'a feature was expected (4)' lyr = ds.ExecuteSQL("select OGR_GEOMETRY from test WHERE OGR_GEOMETRY = 'POLYGON'", dialect='OGRSQL') feat = lyr.GetNextFeature() ds.ReleaseResultSet(lyr) - if feat is None: - gdaltest.post_reason('a feature was expected (5)') - return 'fail' + assert feat is not None, 'a feature was expected (5)' ds = None - return 'success' - ############################################################################### # Test opening a /vsicurl/ DB -def ogr_sqlite_25(): +def test_ogr_sqlite_25(): if gdaltest.sl_ds is None: - return 'skip' + pytest.skip() sql_lyr = gdaltest.sl_ds.ExecuteSQL("SELECT sqlite_version()") feat = sql_lyr.GetNextFeature() @@ -1280,14 +1127,14 @@ def ogr_sqlite_25(): drv = gdal.GetDriverByName('HTTP') if drv is None: - return 'skip' + pytest.skip() # Check that we have SQLite VFS support gdal.PushErrorHandler('CPLQuietErrorHandler') ds = ogr.GetDriverByName('SQLite').CreateDataSource('/vsimem/ogr_sqlite_25.db') gdal.PopErrorHandler() if ds is None: - return 'skip' + pytest.skip() ds = None gdal.Unlink('/vsimem/ogr_sqlite_25.db') @@ -1296,60 +1143,47 @@ def ogr_sqlite_25(): gdal.SetConfigOption('GDAL_HTTP_TIMEOUT', None) if ds is None: if gdaltest.gdalurlopen('http://download.osgeo.org/gdal/data/sqlite3/polygon.db', timeout=4) is None: - print('cannot open URL') - return 'skip' - return 'fail' + pytest.skip('cannot open URL') + pytest.fail() lyr = ds.GetLayerByName('polygon') - if lyr is None: - gdaltest.post_reason('failed') - return 'fail' + assert lyr is not None - if lyr.GetLayerDefn().GetFieldCount() == 0: - gdaltest.post_reason('failed') - return 'fail' - - return 'success' + assert lyr.GetLayerDefn().GetFieldCount() != 0 ############################################################################### # Test creating a :memory: DB -def ogr_sqlite_26(): +def test_ogr_sqlite_26(): if gdaltest.sl_ds is None: - return 'skip' + pytest.skip() ds = ogr.GetDriverByName('SQLite').CreateDataSource(':memory:') sql_lyr = ds.ExecuteSQL('select count(*) from geometry_columns') - if sql_lyr is None: - gdaltest.post_reason('expected existing geometry_columns') - return 'fail' + assert sql_lyr is not None, 'expected existing geometry_columns' count = sql_lyr.GetFeatureCount() ds.ReleaseResultSet(sql_lyr) ds = None - if count != 1: - gdaltest.post_reason('expected existing geometry_columns') - return 'fail' - - return 'success' + assert count == 1, 'expected existing geometry_columns' ############################################################################### # Run test_ogrsf -def ogr_sqlite_27(): +def test_ogr_sqlite_27(): if gdaltest.sl_ds is None: - return 'skip' + pytest.skip() import test_cli_utilities if test_cli_utilities.get_ogr2ogr_path() is None: - return 'skip' + pytest.skip() if test_cli_utilities.get_test_ogrsf_path() is None: - return 'skip' + pytest.skip() gdaltest.runexternal(test_cli_utilities.get_ogr2ogr_path() + ' -f SQLite tmp/ogr_sqlite_27.sqlite data/poly.shp --config OGR_SQLITE_SYNCHRONOUS OFF') @@ -1372,79 +1206,58 @@ def ogr_sqlite_27(): if pos != -1: ret = ret[0:pos] - if ret.find('INFO') == -1 or ret.find('ERROR') != -1: - gdaltest.post_reason('failed') - print(ret) - return 'fail' + assert ret.find('INFO') != -1 and ret.find('ERROR') == -1 # Test on a result SQL layer ret = gdaltest.runexternal(test_cli_utilities.get_test_ogrsf_path() + ' -ro tmp/ogr_sqlite_27.sqlite -sql "SELECT * FROM poly"') - if ret.find('INFO') == -1 or ret.find('ERROR') != -1: - gdaltest.post_reason('failed') - print(ret) - return 'fail' - - return 'success' + assert ret.find('INFO') != -1 and ret.find('ERROR') == -1 ############################################################################### # Run test_ogrsf on a spatialite enabled DB -def ogr_sqlite_28(): +def test_ogr_sqlite_28(): if gdaltest.sl_ds is None: - return 'skip' + pytest.skip() import test_cli_utilities if test_cli_utilities.get_test_ogrsf_path() is None: - return 'skip' + pytest.skip() # Test with a Spatialite 3.0 DB shutil.copy('data/poly_spatialite.sqlite', 'tmp/poly_spatialite.sqlite') ret = gdaltest.runexternal(test_cli_utilities.get_test_ogrsf_path() + ' tmp/poly_spatialite.sqlite') os.unlink('tmp/poly_spatialite.sqlite') - if ret.find('INFO') == -1 or ret.find('ERROR') != -1: - gdaltest.post_reason('failed') - print(ret) - return 'fail' + assert ret.find('INFO') != -1 and ret.find('ERROR') == -1 # Test on a result SQL layer ret = gdaltest.runexternal(test_cli_utilities.get_test_ogrsf_path() + ' -ro data/poly_spatialite.sqlite -sql "SELECT * FROM poly"') - if ret.find('INFO') == -1 or ret.find('ERROR') != -1: - gdaltest.post_reason('failed') - print(ret) - return 'fail' + assert ret.find('INFO') != -1 and ret.find('ERROR') == -1 # Test with a Spatialite 4.0 DB shutil.copy('data/poly_spatialite4.sqlite', 'tmp/poly_spatialite4.sqlite') ret = gdaltest.runexternal(test_cli_utilities.get_test_ogrsf_path() + ' tmp/poly_spatialite4.sqlite') os.unlink('tmp/poly_spatialite4.sqlite') - if ret.find('INFO') == -1 or ret.find('ERROR') != -1: - gdaltest.post_reason('failed') - print(ret) - return 'fail' + assert ret.find('INFO') != -1 and ret.find('ERROR') == -1 # Generic test ret = gdaltest.runexternal(test_cli_utilities.get_test_ogrsf_path() + ' -driver SQLite -dsco SPATIALITE=YES') - if ret.find('INFO') == -1 or ret.find('ERROR') != -1: - print(ret) - return 'fail' - - return 'success' + assert ret.find('INFO') != -1 and ret.find('ERROR') == -1 ############################################################################### # Test CreateFeature() with empty feature -def ogr_sqlite_29(): +def test_ogr_sqlite_29(): if gdaltest.sl_ds is None: - return 'skip' + pytest.skip() try: os.remove('tmp/ogr_sqlite_29.sqlite') @@ -1454,67 +1267,35 @@ def ogr_sqlite_29(): lyr = ds.CreateLayer('test') feat = ogr.Feature(lyr.GetLayerDefn()) - if lyr.CreateFeature(feat) != 0: - return 'fail' + assert lyr.CreateFeature(feat) == 0 ds = None - return 'success' - ############################################################################### # Test ExecuteSQL() with empty result set (#4684) -def ogr_sqlite_30(): +def test_ogr_sqlite_30(): if gdaltest.sl_ds is None: - return 'skip' + pytest.skip() sql_lyr = gdaltest.sl_ds.ExecuteSQL('SELECT * FROM tpoly WHERE eas_id = 12345') if sql_lyr is None: - return 'skip' + pytest.skip() # Test fix added in r24768 feat = sql_lyr.GetNextFeature() - if feat is not None: - return 'fail' + assert feat is None gdaltest.sl_ds.ReleaseResultSet(sql_lyr) - return 'success' - -############################################################################### -# Test if SpatiaLite is available - - -def ogr_spatialite_1(): - - if gdaltest.sl_ds is None: - return 'skip' - - gdal.PushErrorHandler('CPLQuietErrorHandler') - sql_lyr = gdaltest.sl_ds.ExecuteSQL("SELECT spatialite_version()") - gdal.PopErrorHandler() - if sql_lyr is None: - res = 'skip' - else: - feat = sql_lyr.GetNextFeature() - print('Spatialite : %s' % feat.GetFieldAsString(0)) - gdaltest.spatialite_version = feat.GetFieldAsString(0) - gdaltest.has_spatialite = True - gdaltest.sl_ds.ReleaseResultSet(sql_lyr) - res = 'success' - - return res ############################################################################### # Test spatial filter when SpatiaLite is available -def ogr_spatialite_2(): - - if not gdaltest.has_spatialite: - return 'skip' +def test_ogr_spatialite_2(require_spatialite): ds = ogr.Open('tmp/spatialite_test.db', update=1) srs = osr.SpatialReference() @@ -1547,134 +1328,85 @@ def ogr_spatialite_2(): lyr = ds.GetLayerByName('test_spatialfilter') extent = lyr.GetExtent() - if extent != (0.0, 9.0, 0.0, 9.0): - gdaltest.post_reason('got bad extent') - print(extent) - return 'fail' + assert extent == (0.0, 9.0, 0.0, 9.0), 'got bad extent' # Test caching extent = lyr.GetExtent() - if extent != (0.0, 9.0, 0.0, 9.0): - gdaltest.post_reason('got bad extent') - print(extent) - return 'fail' + assert extent == (0.0, 9.0, 0.0, 9.0), 'got bad extent' geom = ogr.CreateGeometryFromWkt( 'POLYGON((2 2,2 8,8 8,8 2,2 2))') lyr.SetSpatialFilter(geom) - if lyr.TestCapability(ogr.OLCFastFeatureCount) is False: - gdaltest.post_reason('OLCFastFeatureCount failed') - return 'fail' - if lyr.TestCapability(ogr.OLCFastSpatialFilter) is False: - gdaltest.post_reason('OLCFastSpatialFilter failed') - return 'fail' + assert lyr.TestCapability(ogr.OLCFastFeatureCount) is not False, \ + 'OLCFastFeatureCount failed' + assert lyr.TestCapability(ogr.OLCFastSpatialFilter) is not False, \ + 'OLCFastSpatialFilter failed' - if lyr.GetFeatureCount() != 50: - gdaltest.post_reason('did not get expected feature count') - print(lyr.GetFeatureCount()) - return 'fail' + assert lyr.GetFeatureCount() == 50, 'did not get expected feature count' # Test spatial filter with a SQL result layer without WHERE clause sql_lyr = ds.ExecuteSQL("SELECT * FROM 'test_spatialfilter'") extent = sql_lyr.GetExtent() - if extent != (0.0, 9.0, 0.0, 9.0): - gdaltest.post_reason('got bad extent') - print(extent) - return 'fail' + assert extent == (0.0, 9.0, 0.0, 9.0), 'got bad extent' # Test caching extent = sql_lyr.GetExtent() - if extent != (0.0, 9.0, 0.0, 9.0): - gdaltest.post_reason('got bad extent') - print(extent) - return 'fail' - - if sql_lyr.TestCapability(ogr.OLCFastSpatialFilter) is False: - gdaltest.post_reason('OLCFastSpatialFilter failed') - return 'fail' + assert extent == (0.0, 9.0, 0.0, 9.0), 'got bad extent' + + assert sql_lyr.TestCapability(ogr.OLCFastSpatialFilter) is not False, \ + 'OLCFastSpatialFilter failed' sql_lyr.SetSpatialFilter(geom) - if sql_lyr.TestCapability(ogr.OLCFastSpatialFilter) is False: - gdaltest.post_reason('OLCFastSpatialFilter failed') - return 'fail' - if sql_lyr.GetFeatureCount() != 50: - gdaltest.post_reason('did not get expected feature count') - print(sql_lyr.GetFeatureCount()) - return 'fail' + assert sql_lyr.TestCapability(ogr.OLCFastSpatialFilter) is not False, \ + 'OLCFastSpatialFilter failed' + assert sql_lyr.GetFeatureCount() == 50, 'did not get expected feature count' ds.ReleaseResultSet(sql_lyr) # Test spatial filter with a SQL result layer with WHERE clause sql_lyr = ds.ExecuteSQL('SELECT * FROM test_spatialfilter WHERE 1=1') - if sql_lyr.TestCapability(ogr.OLCFastSpatialFilter) is False: - gdaltest.post_reason('OLCFastSpatialFilter failed') - return 'fail' + assert sql_lyr.TestCapability(ogr.OLCFastSpatialFilter) is not False, \ + 'OLCFastSpatialFilter failed' sql_lyr.SetSpatialFilter(geom) - if sql_lyr.TestCapability(ogr.OLCFastSpatialFilter) is False: - gdaltest.post_reason('OLCFastSpatialFilter failed') - return 'fail' - if sql_lyr.GetFeatureCount() != 50: - gdaltest.post_reason('did not get expected feature count') - print(sql_lyr.GetFeatureCount()) - return 'fail' + assert sql_lyr.TestCapability(ogr.OLCFastSpatialFilter) is not False, \ + 'OLCFastSpatialFilter failed' + assert sql_lyr.GetFeatureCount() == 50, 'did not get expected feature count' ds.ReleaseResultSet(sql_lyr) # Test spatial filter with a SQL result layer with ORDER BY clause sql_lyr = ds.ExecuteSQL('SELECT * FROM test_spatialfilter ORDER BY intcol') extent = sql_lyr.GetExtent() - if extent != (0.0, 9.0, 0.0, 9.0): - gdaltest.post_reason('got bad extent') - print(extent) - return 'fail' + assert extent == (0.0, 9.0, 0.0, 9.0), 'got bad extent' # Test caching extent = sql_lyr.GetExtent() - if extent != (0.0, 9.0, 0.0, 9.0): - gdaltest.post_reason('got bad extent') - print(extent) - return 'fail' - - if sql_lyr.TestCapability(ogr.OLCFastSpatialFilter) is False: - gdaltest.post_reason('OLCFastSpatialFilter failed') - return 'fail' + assert extent == (0.0, 9.0, 0.0, 9.0), 'got bad extent' + + assert sql_lyr.TestCapability(ogr.OLCFastSpatialFilter) is not False, \ + 'OLCFastSpatialFilter failed' sql_lyr.SetSpatialFilter(geom) - if sql_lyr.TestCapability(ogr.OLCFastSpatialFilter) is False: - gdaltest.post_reason('OLCFastSpatialFilter failed') - return 'fail' - if sql_lyr.GetFeatureCount() != 50: - gdaltest.post_reason('did not get expected feature count') - print(sql_lyr.GetFeatureCount()) - return 'fail' + assert sql_lyr.TestCapability(ogr.OLCFastSpatialFilter) is not False, \ + 'OLCFastSpatialFilter failed' + assert sql_lyr.GetFeatureCount() == 50, 'did not get expected feature count' ds.ReleaseResultSet(sql_lyr) # Test spatial filter with a SQL result layer with WHERE and ORDER BY clause sql_lyr = ds.ExecuteSQL('SELECT * FROM test_spatialfilter WHERE 1 = 1 ORDER BY intcol') extent = sql_lyr.GetExtent() - if extent != (0.0, 9.0, 0.0, 9.0): - gdaltest.post_reason('got bad extent') - print(extent) - return 'fail' + assert extent == (0.0, 9.0, 0.0, 9.0), 'got bad extent' # Test caching extent = sql_lyr.GetExtent() - if extent != (0.0, 9.0, 0.0, 9.0): - gdaltest.post_reason('got bad extent') - print(extent) - return 'fail' - - if sql_lyr.TestCapability(ogr.OLCFastSpatialFilter) is False: - gdaltest.post_reason('OLCFastSpatialFilter failed') - return 'fail' + assert extent == (0.0, 9.0, 0.0, 9.0), 'got bad extent' + + assert sql_lyr.TestCapability(ogr.OLCFastSpatialFilter) is not False, \ + 'OLCFastSpatialFilter failed' sql_lyr.SetSpatialFilter(geom) - if sql_lyr.TestCapability(ogr.OLCFastSpatialFilter) is False: - gdaltest.post_reason('OLCFastSpatialFilter failed') - return 'fail' - if sql_lyr.GetFeatureCount() != 50: - gdaltest.post_reason('did not get expected feature count') - print(sql_lyr.GetFeatureCount()) - return 'fail' + assert sql_lyr.TestCapability(ogr.OLCFastSpatialFilter) is not False, \ + 'OLCFastSpatialFilter failed' + assert sql_lyr.GetFeatureCount() == 50, 'did not get expected feature count' ds.ReleaseResultSet(sql_lyr) # Remove spatial index @@ -1686,9 +1418,7 @@ def ogr_spatialite_2(): ret = feat.GetFieldAsInteger(0) ds.ReleaseResultSet(sql_lyr) - if ret != 1: - gdaltest.post_reason('DisableSpatialIndex failed') - return 'fail' + assert ret == 1, 'DisableSpatialIndex failed' ds.ExecuteSQL("VACUUM") @@ -1703,27 +1433,18 @@ def ogr_spatialite_2(): lyr.SetSpatialFilter(geom) geom.Destroy() - if lyr.TestCapability(ogr.OLCFastFeatureCount) is True: - return 'fail' - if lyr.TestCapability(ogr.OLCFastSpatialFilter) is True: - return 'fail' + assert lyr.TestCapability(ogr.OLCFastFeatureCount) is not True + assert lyr.TestCapability(ogr.OLCFastSpatialFilter) is not True - if lyr.GetFeatureCount() != 50: - print(lyr.GetFeatureCount()) - return 'fail' + assert lyr.GetFeatureCount() == 50 ds.Destroy() - return 'success' - ############################################################################### # Test VirtualShape feature of SpatiaLite -def ogr_spatialite_3(): - - if not gdaltest.has_spatialite: - return 'skip' +def test_ogr_spatialite_3(require_spatialite): ds = ogr.Open('tmp/spatialite_test.db', update=1) ds.ExecuteSQL('CREATE VIRTUAL TABLE testpoly USING VirtualShape(data/testpoly, CP1252, -1)') @@ -1731,8 +1452,7 @@ def ogr_spatialite_3(): ds = ogr.Open('tmp/spatialite_test.db') lyr = ds.GetLayerByName('testpoly') - if lyr is None: - return 'fail' + assert lyr is not None lyr.SetSpatialFilterRect(-400, 22, -120, 400) @@ -1741,16 +1461,13 @@ def ogr_spatialite_3(): ds.Destroy() - return 'success' if tr else 'fail' + assert tr ############################################################################### # Test updating a spatialite DB (#3471 and #3474) -def ogr_spatialite_4(): - - if not gdaltest.has_spatialite: - return 'skip' +def test_ogr_spatialite_4(require_spatialite): ds = ogr.Open('tmp/spatialite_test.db', update=1) @@ -1768,9 +1485,7 @@ def ogr_spatialite_4(): lyr = ds.ExecuteSQL('SELECT * FROM geomspatialite') feat = lyr.GetNextFeature() geom = feat.GetGeometryRef() - if geom is None or geom.ExportToWkt() != 'POINT (0 1)': - print(geom) - return 'fail' + assert geom is not None and geom.ExportToWkt() == 'POINT (0 1)' feat.Destroy() ds.ReleaseResultSet(lyr) @@ -1779,9 +1494,8 @@ def ogr_spatialite_4(): nb_sqlite_master_objects_after = lyr.GetFeatureCount() ds.ReleaseResultSet(lyr) - if nb_sqlite_master_objects_before != nb_sqlite_master_objects_after: - print('nb_sqlite_master_objects_before=%d, nb_sqlite_master_objects_after=%d' % (nb_sqlite_master_objects_before, nb_sqlite_master_objects_after)) - return 'fail' + assert nb_sqlite_master_objects_before == nb_sqlite_master_objects_after, \ + ('nb_sqlite_master_objects_before=%d, nb_sqlite_master_objects_after=%d' % (nb_sqlite_master_objects_before, nb_sqlite_master_objects_after)) # Add new feature lyr = ds.GetLayerByName('geomspatialite') @@ -1795,20 +1509,23 @@ def ogr_spatialite_4(): nb_idx_after = lyr.GetFeatureCount() ds.ReleaseResultSet(lyr) - if nb_idx_before + 1 != nb_idx_after: - print('nb_idx_before=%d, nb_idx_after=%d' % (nb_idx_before, nb_idx_after)) - return 'fail' + assert nb_idx_before + 1 == nb_idx_after, \ + ('nb_idx_before=%d, nb_idx_after=%d' % (nb_idx_before, nb_idx_after)) - return 'success' ############################################################################### # Test writing and reading back spatialite geometries (#4092) +# Test writing and reading back spatialite geometries in compressed form -def ogr_spatialite_5(bUseComprGeom=False): - - if not gdaltest.has_spatialite: - return 'skip' +@pytest.mark.parametrize( + 'bUseComprGeom', + [False, True], + ids=['dont-compress-geometries', 'compress-geometries'] +) +def test_ogr_spatialite_5(require_spatialite, bUseComprGeom): + if bUseComprGeom and require_spatialite == '2.3.1': + pytest.skip() try: os.remove('tmp/ogr_spatialite_5.sqlite') @@ -1893,21 +1610,16 @@ def ogr_spatialite_5(bUseComprGeom=False): for wkt in geometries: geom = ogr.CreateGeometryFromWkt(wkt) lyr = ds.GetLayer(num_layer) - if lyr.GetGeomType() != geom.GetGeometryType(): - gdaltest.post_reason('got %d, expected %d' % (lyr.GetGeomType(), geom.GetGeometryType())) - return 'fail' + assert lyr.GetGeomType() == geom.GetGeometryType() feat = lyr.GetNextFeature() got_wkt = feat.GetGeometryRef().ExportToIsoWkt() # Spatialite < 2.4 only supports 2D geometries if gdaltest.spatialite_version == '2.3.1' and (geom.GetGeometryType() & ogr.wkb25DBit) != 0: geom.SetCoordinateDimension(2) expected_wkt = geom.ExportToIsoWkt() - if got_wkt != expected_wkt: - gdaltest.post_reason('got %s, expected %s' % (got_wkt, expected_wkt)) - return 'fail' + assert got_wkt == expected_wkt elif got_wkt != wkt: - gdaltest.post_reason('got %s, expected %s' % (got_wkt, wkt)) - return 'fail' + pytest.fail('got %s, expected %s' % (got_wkt, wkt)) num_layer = num_layer + 1 @@ -1920,50 +1632,29 @@ def ogr_spatialite_5(bUseComprGeom=False): val = feat.GetFieldAsInteger(0) if wkt != 'LINESTRING (1 2)': if val != 1: - gdaltest.post_reason('did not get expected compressed geometry') print(wkt) print(val) ds.ReleaseResultSet(sql_lyr) - return 'fail' + pytest.fail('did not get expected compressed geometry') else: if val != 0: - print(wkt) print(val) ds.ReleaseResultSet(sql_lyr) - return 'fail' + pytest.fail(wkt) feat = None ds.ReleaseResultSet(sql_lyr) num_layer = num_layer + 1 ds = None - return 'success' - - -############################################################################### -# Test writing and reading back spatialite geometries in compressed form - -def ogr_spatialite_compressed_geom_5(): - - if not gdaltest.has_spatialite: - return 'skip' - - if gdaltest.spatialite_version == '2.3.1': - return 'skip' - - return ogr_spatialite_5(bUseComprGeom=True) ############################################################################### # Test spatialite spatial views -def ogr_spatialite_6(): - - if not gdaltest.has_spatialite: - return 'skip' - - if gdaltest.spatialite_version.find('2.3') == 0: - return 'skip' +def test_ogr_spatialite_6(require_spatialite): + if gdaltest.spatialite_version.startswith('2.3'): + pytest.skip() try: os.remove('tmp/ogr_spatialite_6.sqlite') @@ -2036,47 +1727,28 @@ def ogr_spatialite_6(): ds = ogr.Open('tmp/ogr_spatialite_6.sqlite') lyr = ds.GetLayerByName(layername) view_lyr = ds.GetLayerByName(viewname) - if view_lyr.GetFIDColumn() != pkid_single: - gdaltest.post_reason('failed') - print(view_lyr.GetGeometryColumn()) - return 'fail' - if view_lyr.GetGeometryColumn() != thegeom_single: - gdaltest.post_reason('failed') - print(view_lyr.GetGeometryColumn()) - return 'fail' - if view_lyr.GetLayerDefn().GetFieldDefn(0).GetName() != "int'col": - gdaltest.post_reason('failed') - print(view_lyr.GetLayerDefn().GetFieldDefn(0).GetName()) - return 'fail' - if view_lyr.GetGeomType() != lyr.GetGeomType(): - gdaltest.post_reason('failed') - return 'fail' - if view_lyr.GetFeatureCount() != lyr.GetFeatureCount(): - gdaltest.post_reason('failed') - return 'fail' - if view_lyr.GetSpatialRef().IsSame(lyr.GetSpatialRef()) != 1: - gdaltest.post_reason('failed') - return 'fail' + assert view_lyr.GetFIDColumn() == pkid_single, view_lyr.GetGeometryColumn() + assert view_lyr.GetGeometryColumn() == thegeom_single + assert view_lyr.GetLayerDefn().GetFieldDefn(0).GetName() == "int'col" + assert view_lyr.GetGeomType() == lyr.GetGeomType() + assert view_lyr.GetFeatureCount() == lyr.GetFeatureCount() + assert view_lyr.GetSpatialRef().IsSame(lyr.GetSpatialRef()) == 1 feat = view_lyr.GetFeature(3) if feat.GetFieldAsInteger(0) != 34: - gdaltest.post_reason('failed') feat.DumpReadable() - return 'fail' + pytest.fail() if feat.GetFieldAsDouble(1) != 56.78: - gdaltest.post_reason('failed') feat.DumpReadable() - return 'fail' + pytest.fail() view_lyr.SetAttributeFilter('"int\'col" = 34') view_lyr.SetSpatialFilterRect(2.5, 49.5, 3.5, 50.5) feat = view_lyr.GetNextFeature() if feat.GetFID() != 3: - gdaltest.post_reason('failed') feat.DumpReadable() - return 'fail' + pytest.fail() if feat.GetGeometryRef().ExportToWkt() != 'POINT (3 50)': - gdaltest.post_reason('failed') feat.DumpReadable() - return 'fail' + pytest.fail() ds = None # Remove spatial index @@ -2093,54 +1765,33 @@ def ogr_spatialite_6(): view_lyr.SetSpatialFilterRect(2.5, 49.5, 3.5, 50.5) feat = view_lyr.GetNextFeature() if feat.GetFID() != 3: - gdaltest.post_reason('failed') feat.DumpReadable() - return 'fail' + pytest.fail() ds = None - return 'success' - ############################################################################### # Test VirtualShape:xxx.shp -def ogr_spatialite_7(): - - if not gdaltest.has_spatialite: - return 'skip' - +def test_ogr_spatialite_7(require_spatialite): ds = ogr.Open('VirtualShape:data/poly.shp') - if ds is None: - gdaltest.post_reason('failed') - return 'fail' + assert ds is not None lyr = ds.GetLayerByName('poly') - if lyr is None: - gdaltest.post_reason('failed') - return 'fail' + assert lyr is not None - if lyr.GetGeomType() != ogr.wkbPolygon: - gdaltest.post_reason('failed') - return 'fail' + assert lyr.GetGeomType() == ogr.wkbPolygon f = lyr.GetNextFeature() - if f.GetGeometryRef() is None: - gdaltest.post_reason('failed') - return 'fail' - - return 'success' + assert f.GetGeometryRef() is not None ############################################################################### # Test tables with multiple geometry columns (#4768) -def ogr_spatialite_8(): - - if not gdaltest.has_spatialite: - return 'skip' - - if gdaltest.spatialite_version.find('2.3') == 0: - return 'skip' +def test_ogr_spatialite_8(require_spatialite): + if require_spatialite.find('2.3') == 0: + pytest.skip() try: os.remove('tmp/ogr_spatialite_8.sqlite') @@ -2166,9 +1817,8 @@ def ogr_spatialite_8(): f = lyr.GetNextFeature() if f.GetGeomFieldRef('geom1').ExportToWkt() != 'POINT (0 -1)' or \ f.GetGeomFieldRef('geom2').ExportToWkt() != 'LINESTRING (0 -1,2 3)': - gdaltest.post_reason('failed') f.DumpReadable() - return 'fail' + pytest.fail() f.SetGeomFieldDirectly(0, ogr.CreateGeometryFromWkt('POINT(0 1)')) f.SetGeomFieldDirectly(1, ogr.CreateGeometryFromWkt('LINESTRING(0 1,2 3)')) lyr.SetFeature(f) @@ -2193,157 +1843,102 @@ def ogr_spatialite_8(): lyr = ds.GetLayerByName('test(geom1)') view_lyr = ds.GetLayerByName('view_test_geom1') - if lyr.GetLayerDefn().GetFieldCount() != 1: - gdaltest.post_reason('failed') - return 'fail' - if view_lyr.GetLayerDefn().GetFieldCount() != 1: - gdaltest.post_reason('failed') - return 'fail' - if lyr.GetGeometryColumn() != 'geom1': - gdaltest.post_reason('failed') - return 'fail' - if view_lyr.GetGeometryColumn() != 'renamed_geom1': - gdaltest.post_reason('failed') - return 'fail' - if lyr.GetGeomType() != ogr.wkbPoint: - gdaltest.post_reason('failed') - return 'fail' - if view_lyr.GetGeomType() != lyr.GetGeomType(): - gdaltest.post_reason('failed') - return 'fail' - if view_lyr.GetFeatureCount() != lyr.GetFeatureCount(): - gdaltest.post_reason('failed') - return 'fail' + assert lyr.GetLayerDefn().GetFieldCount() == 1 + assert view_lyr.GetLayerDefn().GetFieldCount() == 1 + assert lyr.GetGeometryColumn() == 'geom1' + assert view_lyr.GetGeometryColumn() == 'renamed_geom1' + assert lyr.GetGeomType() == ogr.wkbPoint + assert view_lyr.GetGeomType() == lyr.GetGeomType() + assert view_lyr.GetFeatureCount() == lyr.GetFeatureCount() feat = view_lyr.GetFeature(1) if feat.GetFieldAsString(0) != 'bar': - gdaltest.post_reason('failed') feat.DumpReadable() - return 'fail' + pytest.fail() feat = None view_lyr.SetSpatialFilterRect(-1, -1, 10, 10) feat = view_lyr.GetNextFeature() if feat.GetFID() != 1: - gdaltest.post_reason('failed') feat.DumpReadable() - return 'fail' + pytest.fail() if feat.GetGeometryRef().ExportToWkt() != 'POINT (0 1)': - gdaltest.post_reason('failed') feat.DumpReadable() - return 'fail' + pytest.fail() feat = None lyr = ds.GetLayerByName('test(geom2)') view_lyr = ds.GetLayerByName('view_test_geom2') - if lyr.GetLayerDefn().GetFieldCount() != 1: - gdaltest.post_reason('failed') - return 'fail' - if view_lyr.GetLayerDefn().GetFieldCount() != 1: - gdaltest.post_reason('failed') - return 'fail' - if lyr.GetGeometryColumn() != 'geom2': - gdaltest.post_reason('failed') - return 'fail' - if view_lyr.GetGeometryColumn() != 'renamed_geom2': - gdaltest.post_reason('failed') - return 'fail' - if lyr.GetGeomType() != ogr.wkbLineString: - gdaltest.post_reason('failed') - return 'fail' - if view_lyr.GetGeomType() != lyr.GetGeomType(): - gdaltest.post_reason('failed') - return 'fail' - if view_lyr.GetFeatureCount() != lyr.GetFeatureCount(): - gdaltest.post_reason('failed') - return 'fail' + assert lyr.GetLayerDefn().GetFieldCount() == 1 + assert view_lyr.GetLayerDefn().GetFieldCount() == 1 + assert lyr.GetGeometryColumn() == 'geom2' + assert view_lyr.GetGeometryColumn() == 'renamed_geom2' + assert lyr.GetGeomType() == ogr.wkbLineString + assert view_lyr.GetGeomType() == lyr.GetGeomType() + assert view_lyr.GetFeatureCount() == lyr.GetFeatureCount() feat = view_lyr.GetFeature(1) if feat.GetFieldAsString(0) != 'bar': - gdaltest.post_reason('failed') feat.DumpReadable() - return 'fail' + pytest.fail() feat = None view_lyr.SetSpatialFilterRect(-1, -1, 10, 10) feat = view_lyr.GetNextFeature() if feat.GetFID() != 1: - gdaltest.post_reason('failed') feat.DumpReadable() - return 'fail' + pytest.fail() if feat.GetGeometryRef().ExportToWkt() != 'LINESTRING (0 1,2 3)': - gdaltest.post_reason('failed') feat.DumpReadable() - return 'fail' + pytest.fail() feat = None sql_lyr = ds.ExecuteSQL('SELECT foo, geom2 FROM test') sql_lyr.SetSpatialFilterRect(-1, -1, 10, 10) feat = sql_lyr.GetNextFeature() if feat.GetGeometryRef().ExportToWkt() != 'LINESTRING (0 1,2 3)': - gdaltest.post_reason('failed') feat.DumpReadable() - return 'fail' + pytest.fail() feat = None ds.ReleaseResultSet(sql_lyr) with gdaltest.error_handler(): lyr = ds.GetLayerByName('invalid_layer_name(geom1)') - if lyr is not None: - gdaltest.post_reason('failed') - return 'fail' + assert lyr is None lyr = ds.GetLayerByName('test') - if lyr.GetLayerDefn().GetFieldCount() != 1: - gdaltest.post_reason('failed') - return 'fail' - if lyr.GetLayerDefn().GetGeomFieldCount() != 2: - gdaltest.post_reason('failed') - return 'fail' - if lyr.GetLayerDefn().GetGeomFieldDefn(0).GetName() != 'geom1': - gdaltest.post_reason('failed') - return 'fail' - if lyr.GetLayerDefn().GetGeomFieldDefn(1).GetName() != 'geom2': - gdaltest.post_reason('failed') - return 'fail' - if lyr.GetLayerDefn().GetGeomFieldDefn(0).GetType() != ogr.wkbPoint: - gdaltest.post_reason('failed') - return 'fail' - if lyr.GetLayerDefn().GetGeomFieldDefn(1).GetType() != ogr.wkbLineString: - gdaltest.post_reason('failed') - return 'fail' + assert lyr.GetLayerDefn().GetFieldCount() == 1 + assert lyr.GetLayerDefn().GetGeomFieldCount() == 2 + assert lyr.GetLayerDefn().GetGeomFieldDefn(0).GetName() == 'geom1' + assert lyr.GetLayerDefn().GetGeomFieldDefn(1).GetName() == 'geom2' + assert lyr.GetLayerDefn().GetGeomFieldDefn(0).GetType() == ogr.wkbPoint + assert lyr.GetLayerDefn().GetGeomFieldDefn(1).GetType() == ogr.wkbLineString lyr.SetSpatialFilterRect(-1, -1, 10, 10) feat = lyr.GetNextFeature() if feat.GetFID() != 1: - gdaltest.post_reason('failed') feat.DumpReadable() - return 'fail' + pytest.fail() if feat.GetGeomFieldRef(0).ExportToWkt() != 'POINT (0 1)': - gdaltest.post_reason('failed') feat.DumpReadable() - return 'fail' + pytest.fail() if feat.GetGeomFieldRef(1).ExportToWkt() != 'LINESTRING (0 1,2 3)': - gdaltest.post_reason('failed') feat.DumpReadable() - return 'fail' + pytest.fail() feat = None lyr.SetSpatialFilterRect(1, -1, -1, 10, 10) feat = lyr.GetNextFeature() if feat.GetFID() != 1: - gdaltest.post_reason('failed') feat.DumpReadable() - return 'fail' + pytest.fail() feat = None ds = None - return 'success' - ############################################################################### # Test tables with multiple geometry columns (#4768) -def ogr_sqlite_31(): +def test_ogr_sqlite_31(): if gdaltest.sl_ds is None: - return 'skip' + pytest.skip() try: os.remove('tmp/ogr_sqlite_31.sqlite') @@ -2371,61 +1966,43 @@ def ogr_sqlite_31(): ds = ogr.Open('tmp/ogr_sqlite_31.sqlite') lyr = ds.GetLayerByName('test(geom1)') - if lyr.GetLayerDefn().GetFieldCount() != 1: - gdaltest.post_reason('failed') - return 'fail' - if lyr.GetGeometryColumn() != 'geom1': - gdaltest.post_reason('failed') - return 'fail' - if lyr.GetGeomType() != ogr.wkbPoint: - gdaltest.post_reason('failed') - return 'fail' + assert lyr.GetLayerDefn().GetFieldCount() == 1 + assert lyr.GetGeometryColumn() == 'geom1' + assert lyr.GetGeomType() == ogr.wkbPoint lyr.SetSpatialFilterRect(-1, -1, 10, 10) feat = lyr.GetNextFeature() if feat.GetFID() != 1: - gdaltest.post_reason('failed') feat.DumpReadable() - return 'fail' + pytest.fail() if feat.GetGeometryRef().ExportToWkt() != 'POINT (0 1)': - gdaltest.post_reason('failed') feat.DumpReadable() - return 'fail' + pytest.fail() feat = None lyr = ds.GetLayerByName('test(geom2)') - if lyr.GetLayerDefn().GetFieldCount() != 1: - gdaltest.post_reason('failed') - return 'fail' - if lyr.GetGeometryColumn() != 'geom2': - gdaltest.post_reason('failed') - return 'fail' - if lyr.GetGeomType() != ogr.wkbLineString: - gdaltest.post_reason('failed') - return 'fail' + assert lyr.GetLayerDefn().GetFieldCount() == 1 + assert lyr.GetGeometryColumn() == 'geom2' + assert lyr.GetGeomType() == ogr.wkbLineString lyr.SetSpatialFilterRect(-1, -1, 10, 10) feat = lyr.GetNextFeature() if feat.GetFID() != 1: - gdaltest.post_reason('failed') feat.DumpReadable() - return 'fail' + pytest.fail() if feat.GetGeometryRef().ExportToWkt() != 'LINESTRING (0 1,2 3)': - gdaltest.post_reason('failed') feat.DumpReadable() - return 'fail' + pytest.fail() feat = None ds = None - return 'success' - ############################################################################### # Test datetime support -def ogr_sqlite_32(): +def test_ogr_sqlite_32(): if gdaltest.sl_ds is None: - return 'skip' + pytest.skip() try: os.remove('tmp/ogr_sqlite_32.sqlite') @@ -2452,168 +2029,132 @@ def ogr_sqlite_32(): ds = ogr.Open('tmp/ogr_sqlite_32.sqlite') lyr = ds.GetLayer(0) - if lyr.GetLayerDefn().GetFieldDefn(0).GetType() != ogr.OFTDateTime: - gdaltest.post_reason('fail') - return 'fail' - if lyr.GetLayerDefn().GetFieldDefn(1).GetType() != ogr.OFTDate: - gdaltest.post_reason('fail') - return 'fail' - if lyr.GetLayerDefn().GetFieldDefn(2).GetType() != ogr.OFTTime: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.GetLayerDefn().GetFieldDefn(0).GetType() == ogr.OFTDateTime + assert lyr.GetLayerDefn().GetFieldDefn(1).GetType() == ogr.OFTDate + assert lyr.GetLayerDefn().GetFieldDefn(2).GetType() == ogr.OFTTime feat = lyr.GetNextFeature() if feat.GetField('datetimefield') != '2012/08/23 21:24:00' or \ feat.GetField('datefield') != '2012/08/23' or \ feat.GetField('timefield') != '21:24:00': - gdaltest.post_reason('failure') feat.DumpReadable() - return 'fail' + pytest.fail() feat = None ds = None - return 'success' - ############################################################################### # Test SRID layer creation option -def ogr_sqlite_33(): - +def test_ogr_sqlite_33(with_and_without_spatialite): if gdaltest.sl_ds is None: - return 'skip' - - for i in range(2): - try: - os.remove('tmp/ogr_sqlite_33.sqlite') - except OSError: - pass - if i == 0: - options = [] - else: - if not gdaltest.has_spatialite: - return 'success' - if gdaltest.spatialite_version.find('2.3') == 0: - return 'success' - options = ['SPATIALITE=YES'] - - ds = ogr.GetDriverByName('SQLite').CreateDataSource('tmp/ogr_sqlite_33.sqlite', options=options) - - if i == 0: - # To make sure that the entry is added in spatial_ref_sys - srs = osr.SpatialReference() - srs.ImportFromEPSG(4326) - lyr = ds.CreateLayer('test1', srs=srs) - - # Test with existing entry - lyr = ds.CreateLayer('test2', options=['SRID=4326']) - - # Test with non-existing entry - gdal.PushErrorHandler('CPLQuietErrorHandler') - lyr = ds.CreateLayer('test3', options=['SRID=123456']) - gdal.PopErrorHandler() - ds = None - - ds = ogr.Open('tmp/ogr_sqlite_33.sqlite') - lyr = ds.GetLayerByName('test2') - srs = lyr.GetSpatialRef() - if srs.ExportToWkt().find('4326') == -1: - gdaltest.post_reason('failure') - print(i) - return 'fail' - - # 123456 should be referenced in geometry_columns... - sql_lyr = ds.ExecuteSQL('SELECT * from geometry_columns WHERE srid=123456') - feat = sql_lyr.GetNextFeature() - is_none = feat is None - feat = None - ds.ReleaseResultSet(sql_lyr) + pytest.skip() - if is_none: - gdaltest.post_reason('failure') - print(i) - return 'fail' + try: + os.remove('tmp/ogr_sqlite_33.sqlite') + except OSError: + pass + if not with_and_without_spatialite: + options = [] + else: + if gdaltest.spatialite_version.find('2.3') == 0: + return + options = ['SPATIALITE=YES'] - # ... but not in spatial_ref_sys - sql_lyr = ds.ExecuteSQL('SELECT * from spatial_ref_sys WHERE srid=123456') - feat = sql_lyr.GetNextFeature() - is_none = feat is None - feat = None - ds.ReleaseResultSet(sql_lyr) + ds = ogr.GetDriverByName('SQLite').CreateDataSource('tmp/ogr_sqlite_33.sqlite', options=options) + + if not with_and_without_spatialite: + # To make sure that the entry is added in spatial_ref_sys + srs = osr.SpatialReference() + srs.ImportFromEPSG(4326) + lyr = ds.CreateLayer('test1', srs=srs) + + # Test with existing entry + lyr = ds.CreateLayer('test2', options=['SRID=4326']) + + # Test with non-existing entry + gdal.PushErrorHandler('CPLQuietErrorHandler') + lyr = ds.CreateLayer('test3', options=['SRID=123456']) + gdal.PopErrorHandler() + ds = None + + ds = ogr.Open('tmp/ogr_sqlite_33.sqlite') + lyr = ds.GetLayerByName('test2') + srs = lyr.GetSpatialRef() + if srs.ExportToWkt().find('4326') == -1: + pytest.fail('failure') + + # 123456 should be referenced in geometry_columns... + sql_lyr = ds.ExecuteSQL('SELECT * from geometry_columns WHERE srid=123456') + feat = sql_lyr.GetNextFeature() + is_none = feat is None + feat = None + ds.ReleaseResultSet(sql_lyr) + + assert not is_none - if not is_none: - gdaltest.post_reason('failure') - print(i) - return 'fail' + # ... but not in spatial_ref_sys + sql_lyr = ds.ExecuteSQL('SELECT * from spatial_ref_sys WHERE srid=123456') + feat = sql_lyr.GetNextFeature() + is_none = feat is None + feat = None + ds.ReleaseResultSet(sql_lyr) - ds = None + assert is_none - return 'success' ############################################################################### # Test REGEXP support (#4823) -def ogr_sqlite_34(): +def test_ogr_sqlite_34(): if gdaltest.sl_ds is None: - return 'skip' + pytest.skip() gdal.PushErrorHandler('CPLQuietErrorHandler') sql_lyr = gdaltest.sl_ds.ExecuteSQL("SELECT 'a' REGEXP 'a'") gdal.PopErrorHandler() if sql_lyr is None: - return 'skip' + pytest.skip() feat = sql_lyr.GetNextFeature() val = feat.GetField(0) gdaltest.sl_ds.ReleaseResultSet(sql_lyr) - if val != 1: - gdaltest.post_reason('failure') - return 'fail' + assert val == 1 # Evaluates to FALSE sql_lyr = gdaltest.sl_ds.ExecuteSQL("SELECT 'b' REGEXP 'a'") feat = sql_lyr.GetNextFeature() val = feat.GetField(0) gdaltest.sl_ds.ReleaseResultSet(sql_lyr) - if val != 0: - gdaltest.post_reason('failure') - return 'fail' + assert val == 0 # NULL left-member sql_lyr = gdaltest.sl_ds.ExecuteSQL("SELECT NULL REGEXP 'a'") feat = sql_lyr.GetNextFeature() val = feat.GetField(0) gdaltest.sl_ds.ReleaseResultSet(sql_lyr) - if val != 0: - gdaltest.post_reason('failure') - return 'fail' + assert val == 0 # NULL regexp gdal.PushErrorHandler('CPLQuietErrorHandler') sql_lyr = gdaltest.sl_ds.ExecuteSQL("SELECT 'a' REGEXP NULL") gdal.PopErrorHandler() - if sql_lyr is not None: - gdaltest.post_reason('failure') - return 'fail' + assert sql_lyr is None # Invalid regexp gdal.PushErrorHandler('CPLQuietErrorHandler') sql_lyr = gdaltest.sl_ds.ExecuteSQL("SELECT 'a' REGEXP '['") gdal.PopErrorHandler() - if sql_lyr is not None: - gdaltest.post_reason('failure') - return 'fail' + assert sql_lyr is None # Adds another pattern sql_lyr = gdaltest.sl_ds.ExecuteSQL("SELECT 'b' REGEXP 'b'") feat = sql_lyr.GetNextFeature() val = feat.GetField(0) gdaltest.sl_ds.ReleaseResultSet(sql_lyr) - if val != 1: - gdaltest.post_reason('failure') - return 'fail' + assert val == 1 # Test cache for _ in range(2): @@ -2623,21 +2164,21 @@ def ogr_sqlite_34(): feat = sql_lyr.GetNextFeature() val = feat.GetField(0) gdaltest.sl_ds.ReleaseResultSet(sql_lyr) - if val != 1: - return 'fail' + assert val == 1 - return 'success' ############################################################################### # Test SetAttributeFilter() on SQL result layer -def ogr_sqlite_35(): +def test_ogr_sqlite_35(with_and_without_spatialite): if gdaltest.sl_ds is None: - return 'skip' + pytest.skip() - if gdaltest.has_spatialite and gdaltest.spatialite_version.find('2.3') < 0: + if with_and_without_spatialite: + if gdaltest.spatialite_version.find('2.3') >= 0: + pytest.skip() options = ['SPATIALITE=YES'] else: options = [] @@ -2671,68 +2212,54 @@ def ogr_sqlite_35(): sql_lyr.SetAttributeFilter("foo = 'bar'") sql_lyr.ResetReading() feat = sql_lyr.GetNextFeature() - if feat is None: - gdaltest.post_reason('failure') - return 'fail' + assert feat is not None feat = None sql_lyr.SetAttributeFilter("foo = 'baz'") sql_lyr.ResetReading() feat = sql_lyr.GetNextFeature() - if feat is not None: - gdaltest.post_reason('failure') - return 'fail' + assert feat is None feat = None sql_lyr.SetAttributeFilter(None) sql_lyr.ResetReading() feat = sql_lyr.GetNextFeature() - if feat is None: - gdaltest.post_reason('failure') - return 'fail' + assert feat is not None feat = None sql_lyr.SetSpatialFilterRect(0, 0, 2, 2) sql_lyr.SetAttributeFilter("foo = 'bar'") sql_lyr.ResetReading() feat = sql_lyr.GetNextFeature() - if feat is None: - gdaltest.post_reason('failure') - return 'fail' + assert feat is not None feat = None sql_lyr.SetSpatialFilterRect(1.5, 1.5, 2, 2) sql_lyr.SetAttributeFilter("foo = 'bar'") sql_lyr.ResetReading() feat = sql_lyr.GetNextFeature() - if feat is not None: - gdaltest.post_reason('failure') - return 'fail' + assert feat is None feat = None sql_lyr.SetSpatialFilterRect(0, 0, 2, 2) sql_lyr.SetAttributeFilter(None) sql_lyr.ResetReading() feat = sql_lyr.GetNextFeature() - if feat is None: - gdaltest.post_reason('failure') - return 'fail' + assert feat is not None feat = None ds.ReleaseResultSet(sql_lyr) ds = None - return 'success' - ############################################################################### # Test FID64 support -def ogr_sqlite_36(): +def test_ogr_sqlite_36(): if gdaltest.sl_ds is None: - return 'skip' + pytest.skip() try: os.remove('tmp/ogr_sqlite_36.sqlite') @@ -2754,24 +2281,18 @@ def ogr_sqlite_36(): ds = ogr.Open('tmp/ogr_sqlite_36.sqlite') lyr = ds.GetLayer(0) - if lyr.GetMetadataItem(ogr.OLMD_FID64) is None: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.GetMetadataItem(ogr.OLMD_FID64) is not None f = lyr.GetNextFeature() - if f.GetFID() != 1234567890123: - gdaltest.post_reason('failure') - return 'fail' - - return 'success' + assert f.GetFID() == 1234567890123 ############################################################################### # Test not nullable fields -def ogr_sqlite_37(): +def test_ogr_sqlite_37(): if gdaltest.sl_ds is None: - return 'skip' + pytest.skip() try: os.remove('tmp/ogr_sqlite_37.sqlite') @@ -2802,9 +2323,7 @@ def ogr_sqlite_37(): gdal.PushErrorHandler() ret = lyr.CreateFeature(f) gdal.PopErrorHandler() - if ret == 0: - gdaltest.post_reason('fail') - return 'fail' + assert ret != 0 f = None # Error case: missing non-nullable field @@ -2813,36 +2332,24 @@ def ogr_sqlite_37(): gdal.PushErrorHandler() ret = lyr.CreateFeature(f) gdal.PopErrorHandler() - if ret == 0: - gdaltest.post_reason('fail') - return 'fail' + assert ret != 0 f = None ds = None ds = ogr.Open('tmp/ogr_sqlite_37.sqlite', update=1) lyr = ds.GetLayerByName('test') - if lyr.GetLayerDefn().GetFieldDefn(lyr.GetLayerDefn().GetFieldIndex('field_not_nullable')).IsNullable() != 0: - gdaltest.post_reason('fail') - return 'fail' - if lyr.GetLayerDefn().GetFieldDefn(lyr.GetLayerDefn().GetFieldIndex('field_nullable')).IsNullable() != 1: - gdaltest.post_reason('fail') - return 'fail' - if lyr.GetLayerDefn().GetGeomFieldDefn(lyr.GetLayerDefn().GetGeomFieldIndex('geomfield_not_nullable')).IsNullable() != 0: - gdaltest.post_reason('fail') - return 'fail' - if lyr.GetLayerDefn().GetGeomFieldDefn(lyr.GetLayerDefn().GetGeomFieldIndex('geomfield_nullable')).IsNullable() != 1: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.GetLayerDefn().GetFieldDefn(lyr.GetLayerDefn().GetFieldIndex('field_not_nullable')).IsNullable() == 0 + assert lyr.GetLayerDefn().GetFieldDefn(lyr.GetLayerDefn().GetFieldIndex('field_nullable')).IsNullable() == 1 + assert lyr.GetLayerDefn().GetGeomFieldDefn(lyr.GetLayerDefn().GetGeomFieldIndex('geomfield_not_nullable')).IsNullable() == 0 + assert lyr.GetLayerDefn().GetGeomFieldDefn(lyr.GetLayerDefn().GetGeomFieldIndex('geomfield_nullable')).IsNullable() == 1 # Turn not null into nullable src_fd = lyr.GetLayerDefn().GetFieldDefn(lyr.GetLayerDefn().GetFieldIndex('field_not_nullable')) fd = ogr.FieldDefn('now_nullable', src_fd.GetType()) fd.SetNullable(1) lyr.AlterFieldDefn(lyr.GetLayerDefn().GetFieldIndex('field_not_nullable'), fd, ogr.ALTER_ALL_FLAG) - if lyr.GetLayerDefn().GetFieldDefn(lyr.GetLayerDefn().GetFieldIndex('now_nullable')).IsNullable() != 1: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.GetLayerDefn().GetFieldDefn(lyr.GetLayerDefn().GetFieldIndex('now_nullable')).IsNullable() == 1 # Turn nullable into not null, but remove NULL values first ds.ExecuteSQL("UPDATE test SET field_nullable = '' WHERE field_nullable IS NULL") @@ -2851,38 +2358,26 @@ def ogr_sqlite_37(): fd.SetName('now_not_nullable') fd.SetNullable(0) lyr.AlterFieldDefn(lyr.GetLayerDefn().GetFieldIndex('field_nullable'), fd, ogr.ALTER_ALL_FLAG) - if lyr.GetLayerDefn().GetFieldDefn(lyr.GetLayerDefn().GetFieldIndex('now_not_nullable')).IsNullable() != 0: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.GetLayerDefn().GetFieldDefn(lyr.GetLayerDefn().GetFieldIndex('now_not_nullable')).IsNullable() == 0 ds = None ds = ogr.Open('tmp/ogr_sqlite_37.sqlite') lyr = ds.GetLayerByName('test') - if lyr.GetLayerDefn().GetFieldDefn(lyr.GetLayerDefn().GetFieldIndex('now_not_nullable')).IsNullable() != 0: - gdaltest.post_reason('fail') - return 'fail' - if lyr.GetLayerDefn().GetFieldDefn(lyr.GetLayerDefn().GetFieldIndex('now_nullable')).IsNullable() != 1: - gdaltest.post_reason('fail') - return 'fail' - if lyr.GetLayerDefn().GetGeomFieldDefn(lyr.GetLayerDefn().GetGeomFieldIndex('geomfield_not_nullable')).IsNullable() != 0: - gdaltest.post_reason('fail') - return 'fail' - if lyr.GetLayerDefn().GetGeomFieldDefn(lyr.GetLayerDefn().GetGeomFieldIndex('geomfield_nullable')).IsNullable() != 1: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.GetLayerDefn().GetFieldDefn(lyr.GetLayerDefn().GetFieldIndex('now_not_nullable')).IsNullable() == 0 + assert lyr.GetLayerDefn().GetFieldDefn(lyr.GetLayerDefn().GetFieldIndex('now_nullable')).IsNullable() == 1 + assert lyr.GetLayerDefn().GetGeomFieldDefn(lyr.GetLayerDefn().GetGeomFieldIndex('geomfield_not_nullable')).IsNullable() == 0 + assert lyr.GetLayerDefn().GetGeomFieldDefn(lyr.GetLayerDefn().GetGeomFieldIndex('geomfield_nullable')).IsNullable() == 1 ds = None - return 'success' - ############################################################################### # Test default values -def ogr_sqlite_38(): +def test_ogr_sqlite_38(): if gdaltest.sl_ds is None: - return 'skip' + pytest.skip() try: os.remove('tmp/ogr_sqlite_38.sqlite') @@ -2937,39 +2432,16 @@ def ogr_sqlite_38(): ds = ogr.Open('tmp/ogr_sqlite_38.sqlite', update=1) lyr = ds.GetLayerByName('test') - if lyr.GetLayerDefn().GetFieldDefn(lyr.GetLayerDefn().GetFieldIndex('field_string')).GetDefault() != "'a''b'": - gdaltest.post_reason('fail') - return 'fail' - if lyr.GetLayerDefn().GetFieldDefn(lyr.GetLayerDefn().GetFieldIndex('field_int')).GetDefault() != '123': - gdaltest.post_reason('fail') - return 'fail' - if lyr.GetLayerDefn().GetFieldDefn(lyr.GetLayerDefn().GetFieldIndex('field_real')).GetDefault() != '1.23': - gdaltest.post_reason('fail') - return 'fail' - if lyr.GetLayerDefn().GetFieldDefn(lyr.GetLayerDefn().GetFieldIndex('field_nodefault')).GetDefault() is not None: - gdaltest.post_reason('fail') - return 'fail' - if lyr.GetLayerDefn().GetFieldDefn(lyr.GetLayerDefn().GetFieldIndex('field_datetime')).GetDefault() != 'CURRENT_TIMESTAMP': - gdaltest.post_reason('fail') - return 'fail' - if lyr.GetLayerDefn().GetFieldDefn(lyr.GetLayerDefn().GetFieldIndex('field_datetime2')).GetDefault() != "'2015/06/30 12:34:56'": - gdaltest.post_reason('fail') - print(lyr.GetLayerDefn().GetFieldDefn(lyr.GetLayerDefn().GetFieldIndex('field_datetime2')).GetDefault()) - return 'fail' - if lyr.GetLayerDefn().GetFieldDefn(lyr.GetLayerDefn().GetFieldIndex('field_datetime3')).GetDefault() != "(strftime('%Y-%m-%dT%H:%M:%fZ','now'))": - gdaltest.post_reason('fail') - print(lyr.GetLayerDefn().GetFieldDefn(lyr.GetLayerDefn().GetFieldIndex('field_datetime3')).GetDefault()) - return 'fail' - if lyr.GetLayerDefn().GetFieldDefn(lyr.GetLayerDefn().GetFieldIndex('field_datetime4')).GetDefault() != "'2015/06/30 12:34:56.123'": - gdaltest.post_reason('fail') - print(lyr.GetLayerDefn().GetFieldDefn(lyr.GetLayerDefn().GetFieldIndex('field_datetime4')).GetDefault()) - return 'fail' - if lyr.GetLayerDefn().GetFieldDefn(lyr.GetLayerDefn().GetFieldIndex('field_date')).GetDefault() != "CURRENT_DATE": - gdaltest.post_reason('fail') - return 'fail' - if lyr.GetLayerDefn().GetFieldDefn(lyr.GetLayerDefn().GetFieldIndex('field_time')).GetDefault() != "CURRENT_TIME": - gdaltest.post_reason('fail') - return 'fail' + assert lyr.GetLayerDefn().GetFieldDefn(lyr.GetLayerDefn().GetFieldIndex('field_string')).GetDefault() == "'a''b'" + assert lyr.GetLayerDefn().GetFieldDefn(lyr.GetLayerDefn().GetFieldIndex('field_int')).GetDefault() == '123' + assert lyr.GetLayerDefn().GetFieldDefn(lyr.GetLayerDefn().GetFieldIndex('field_real')).GetDefault() == '1.23' + assert lyr.GetLayerDefn().GetFieldDefn(lyr.GetLayerDefn().GetFieldIndex('field_nodefault')).GetDefault() is None + assert lyr.GetLayerDefn().GetFieldDefn(lyr.GetLayerDefn().GetFieldIndex('field_datetime')).GetDefault() == 'CURRENT_TIMESTAMP' + assert lyr.GetLayerDefn().GetFieldDefn(lyr.GetLayerDefn().GetFieldIndex('field_datetime2')).GetDefault() == "'2015/06/30 12:34:56'" + assert lyr.GetLayerDefn().GetFieldDefn(lyr.GetLayerDefn().GetFieldIndex('field_datetime3')).GetDefault() == "(strftime('%Y-%m-%dT%H:%M:%fZ','now'))" + assert lyr.GetLayerDefn().GetFieldDefn(lyr.GetLayerDefn().GetFieldIndex('field_datetime4')).GetDefault() == "'2015/06/30 12:34:56.123'" + assert lyr.GetLayerDefn().GetFieldDefn(lyr.GetLayerDefn().GetFieldIndex('field_date')).GetDefault() == "CURRENT_DATE" + assert lyr.GetLayerDefn().GetFieldDefn(lyr.GetLayerDefn().GetFieldIndex('field_time')).GetDefault() == "CURRENT_TIME" f = lyr.GetNextFeature() if f.GetField('field_string') != 'a\'b' or f.GetField('field_int') != 123 or \ f.GetField('field_real') != 1.23 or \ @@ -2978,54 +2450,37 @@ def ogr_sqlite_38(): f.GetField('field_datetime4') != '2015/06/30 12:34:56.123' or \ not f.IsFieldSet('field_datetime3') or \ not f.IsFieldSet('field_date') or not f.IsFieldSet('field_time'): - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' + pytest.fail() # Change DEFAULT value src_fd = lyr.GetLayerDefn().GetFieldDefn(lyr.GetLayerDefn().GetFieldIndex('field_string')) fd = ogr.FieldDefn('field_string', src_fd.GetType()) fd.SetDefault("'c'") lyr.AlterFieldDefn(lyr.GetLayerDefn().GetFieldIndex('field_string'), fd, ogr.ALTER_DEFAULT_FLAG) - if lyr.GetLayerDefn().GetFieldDefn(lyr.GetLayerDefn().GetFieldIndex('field_string')).GetDefault() != "'c'": - gdaltest.post_reason('fail') - print(lyr.GetLayerDefn().GetFieldDefn(lyr.GetLayerDefn().GetFieldIndex('field_string')).GetDefault()) - return 'fail' + assert lyr.GetLayerDefn().GetFieldDefn(lyr.GetLayerDefn().GetFieldIndex('field_string')).GetDefault() == "'c'" # Drop DEFAULT value src_fd = lyr.GetLayerDefn().GetFieldDefn(lyr.GetLayerDefn().GetFieldIndex('field_int')) fd = ogr.FieldDefn('field_int', src_fd.GetType()) fd.SetDefault(None) lyr.AlterFieldDefn(lyr.GetLayerDefn().GetFieldIndex('field_int'), fd, ogr.ALTER_DEFAULT_FLAG) - if lyr.GetLayerDefn().GetFieldDefn(lyr.GetLayerDefn().GetFieldIndex('field_int')).GetDefault() is not None: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.GetLayerDefn().GetFieldDefn(lyr.GetLayerDefn().GetFieldIndex('field_int')).GetDefault() is None ds = None ds = ogr.Open('tmp/ogr_sqlite_38.sqlite', update=1) lyr = ds.GetLayerByName('test') - if lyr.GetLayerDefn().GetFieldDefn(lyr.GetLayerDefn().GetFieldIndex('field_string')).GetDefault() != "'c'": - gdaltest.post_reason('fail') - print(lyr.GetLayerDefn().GetFieldDefn(lyr.GetLayerDefn().GetFieldIndex('field_string')).GetDefault()) - return 'fail' - if lyr.GetLayerDefn().GetFieldDefn(lyr.GetLayerDefn().GetFieldIndex('field_int')).GetDefault() is not None: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.GetLayerDefn().GetFieldDefn(lyr.GetLayerDefn().GetFieldIndex('field_string')).GetDefault() == "'c'" + assert lyr.GetLayerDefn().GetFieldDefn(lyr.GetLayerDefn().GetFieldIndex('field_int')).GetDefault() is None ds = None - return 'success' - ############################################################################### # Test spatial filters with point extent -def ogr_spatialite_9(): - - if not gdaltest.has_spatialite: - return 'skip' - +def test_ogr_spatialite_9(require_spatialite): ds = ogr.GetDriverByName('SQLite').CreateDataSource('/vsimem/ogr_spatialite_9.sqlite', options=['SPATIALITE=YES']) lyr = ds.CreateLayer('point', geom_type=ogr.wkbPoint) feat = ogr.Feature(lyr.GetLayerDefn()) @@ -3034,21 +2489,15 @@ def ogr_spatialite_9(): lyr.SetSpatialFilterRect(1, 2, 1, 2) lyr.ResetReading() feat = lyr.GetNextFeature() - if feat is None: - return 'fail' + assert feat is not None ds = None ogr.GetDriverByName('SQLite').DeleteDataSource('/vsimem/ogr_spatialite_9.sqlite') - return 'success' - ############################################################################### # Test not nullable fields -def ogr_spatialite_10(): - - if not gdaltest.has_spatialite: - return 'skip' +def test_ogr_spatialite_10(require_spatialite): try: os.remove('tmp/ogr_spatialite_10.sqlite') except OSError: @@ -3075,30 +2524,20 @@ def ogr_spatialite_10(): ds = ogr.Open('tmp/ogr_spatialite_10.sqlite') lyr = ds.GetLayerByName('test') - if lyr.GetLayerDefn().GetFieldDefn(lyr.GetLayerDefn().GetFieldIndex('field_not_nullable')).IsNullable() != 0: - gdaltest.post_reason('fail') - return 'fail' - if lyr.GetLayerDefn().GetFieldDefn(lyr.GetLayerDefn().GetFieldIndex('field_nullable')).IsNullable() != 1: - gdaltest.post_reason('fail') - return 'fail' - if lyr.GetLayerDefn().GetGeomFieldDefn(lyr.GetLayerDefn().GetGeomFieldIndex('geomfield_not_nullable')).IsNullable() != 0: - gdaltest.post_reason('fail') - return 'fail' - if lyr.GetLayerDefn().GetGeomFieldDefn(lyr.GetLayerDefn().GetGeomFieldIndex('geomfield_nullable')).IsNullable() != 1: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.GetLayerDefn().GetFieldDefn(lyr.GetLayerDefn().GetFieldIndex('field_not_nullable')).IsNullable() == 0 + assert lyr.GetLayerDefn().GetFieldDefn(lyr.GetLayerDefn().GetFieldIndex('field_nullable')).IsNullable() == 1 + assert lyr.GetLayerDefn().GetGeomFieldDefn(lyr.GetLayerDefn().GetGeomFieldIndex('geomfield_not_nullable')).IsNullable() == 0 + assert lyr.GetLayerDefn().GetGeomFieldDefn(lyr.GetLayerDefn().GetGeomFieldIndex('geomfield_nullable')).IsNullable() == 1 ds = None - return 'success' - ############################################################################### # Test creating a field with the fid name -def ogr_sqlite_39(): +def test_ogr_sqlite_39(): if gdaltest.sl_ds is None: - return 'skip' + pytest.skip() ds = ogr.GetDriverByName('SQLite').CreateDataSource('/vsimem/ogr_sqlite_39.sqlite') lyr = ds.CreateLayer('test', geom_type=ogr.wkbNone, options=['FID=myfid']) @@ -3107,14 +2546,10 @@ def ogr_sqlite_39(): gdal.PushErrorHandler() ret = lyr.CreateField(ogr.FieldDefn('myfid', ogr.OFTString)) gdal.PopErrorHandler() - if ret == 0: - gdaltest.post_reason('fail') - return 'fail' + assert ret != 0 ret = lyr.CreateField(ogr.FieldDefn('myfid', ogr.OFTInteger)) - if ret != 0: - gdaltest.post_reason('fail') - return 'fail' + assert ret == 0 lyr.CreateField(ogr.FieldDefn('str2', ogr.OFTString)) feat = ogr.Feature(lyr.GetLayerDefn()) @@ -3122,33 +2557,23 @@ def ogr_sqlite_39(): feat.SetField('myfid', 10) feat.SetField('str2', 'second string') ret = lyr.CreateFeature(feat) - if ret != 0: - gdaltest.post_reason('fail') - return 'fail' - if feat.GetFID() != 10: - gdaltest.post_reason('fail') - return 'fail' + assert ret == 0 + assert feat.GetFID() == 10 feat = ogr.Feature(lyr.GetLayerDefn()) feat.SetField('str2', 'second string') ret = lyr.CreateFeature(feat) - if ret != 0: - gdaltest.post_reason('fail') - return 'fail' + assert ret == 0 if feat.GetFID() < 0: - gdaltest.post_reason('fail') feat.DumpReadable() - return 'fail' + pytest.fail() if feat.GetField('myfid') != feat.GetFID(): - gdaltest.post_reason('fail') feat.DumpReadable() - return 'fail' + pytest.fail() feat.SetField('str', 'foo') ret = lyr.SetFeature(feat) - if ret != 0: - gdaltest.post_reason('fail') - return 'fail' + assert ret == 0 feat = ogr.Feature(lyr.GetLayerDefn()) feat.SetFID(1) @@ -3156,150 +2581,107 @@ def ogr_sqlite_39(): gdal.PushErrorHandler() ret = lyr.CreateFeature(feat) gdal.PopErrorHandler() - if ret == 0: - gdaltest.post_reason('fail') - return 'fail' + assert ret != 0 gdal.PushErrorHandler() ret = lyr.SetFeature(feat) gdal.PopErrorHandler() - if ret == 0: - gdaltest.post_reason('fail') - return 'fail' + assert ret != 0 feat.UnsetField('myfid') gdal.PushErrorHandler() ret = lyr.SetFeature(feat) gdal.PopErrorHandler() - if ret == 0: - gdaltest.post_reason('fail') - return 'fail' + assert ret != 0 lyr.ResetReading() f = lyr.GetNextFeature() if f.GetFID() != 10 or f.GetField('str') != 'first string' or f.GetField('str2') != 'second string' or f.GetField('myfid') != 10: - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' + pytest.fail() f = None ds = None ogr.GetDriverByName('SQLite').DeleteDataSource('/vsimem/ogr_sqlite_39.sqlite') - return 'success' - ############################################################################### # Test dataset transactions -def ogr_sqlite_40(): +def test_ogr_sqlite_40(with_and_without_spatialite): if gdaltest.sl_ds is None: - return 'skip' + pytest.skip() - if gdaltest.has_spatialite: + if with_and_without_spatialite: options = ['SPATIALITE=YES'] else: options = [] ds = ogr.GetDriverByName('SQLite').CreateDataSource('/vsimem/ogr_sqlite_40.sqlite', options=options) - if ds.TestCapability(ogr.ODsCTransactions) != 1: - gdaltest.post_reason('fail') - return 'fail' + assert ds.TestCapability(ogr.ODsCTransactions) == 1 ret = ds.StartTransaction() - if ret != 0: - gdaltest.post_reason('fail') - return 'fail' + assert ret == 0 gdal.PushErrorHandler() ret = ds.StartTransaction() gdal.PopErrorHandler() - if ret == 0: - gdaltest.post_reason('fail') - return 'fail' + assert ret != 0 lyr = ds.CreateLayer('test', geom_type=ogr.wkbPoint) lyr.CreateField(ogr.FieldDefn('foo', ogr.OFTString)) ret = ds.RollbackTransaction() - if ret != 0: - gdaltest.post_reason('fail') - return 'fail' + assert ret == 0 gdal.PushErrorHandler() ret = ds.RollbackTransaction() gdal.PopErrorHandler() - if ret == 0: - gdaltest.post_reason('fail') - return 'fail' + assert ret != 0 ds = None ds = ogr.Open('/vsimem/ogr_sqlite_40.sqlite', update=1) - if ds.GetLayerCount() != 0: - gdaltest.post_reason('fail') - return 'fail' + assert ds.GetLayerCount() == 0 ret = ds.StartTransaction() - if ret != 0: - gdaltest.post_reason('fail') - return 'fail' + assert ret == 0 gdal.PushErrorHandler() ret = ds.StartTransaction() gdal.PopErrorHandler() - if ret == 0: - gdaltest.post_reason('fail') - return 'fail' + assert ret != 0 lyr = ds.CreateLayer('test', geom_type=ogr.wkbPoint) lyr.CreateField(ogr.FieldDefn('foo', ogr.OFTString)) ret = ds.CommitTransaction() - if ret != 0: - gdaltest.post_reason('fail') - return 'fail' + assert ret == 0 gdal.PushErrorHandler() ret = ds.CommitTransaction() gdal.PopErrorHandler() - if ret == 0: - gdaltest.post_reason('fail') - return 'fail' + assert ret != 0 ds = None ds = ogr.Open('/vsimem/ogr_sqlite_40.sqlite', update=1) - if ds.GetLayerCount() != 1: - gdaltest.post_reason('fail') - return 'fail' + assert ds.GetLayerCount() == 1 lyr = ds.GetLayerByName('test') ds.StartTransaction() lyr.CreateFeature(ogr.Feature(lyr.GetLayerDefn())) lyr.ResetReading() f = lyr.GetNextFeature() - if f is None: - gdaltest.post_reason('fail') - return 'fail' - if lyr.GetFeatureCount() != 1: - gdaltest.post_reason('fail') - return 'fail' + assert f is not None + assert lyr.GetFeatureCount() == 1 ds.RollbackTransaction() - if lyr.GetFeatureCount() != 0: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.GetFeatureCount() == 0 ds.StartTransaction() lyr.CreateFeature(ogr.Feature(lyr.GetLayerDefn())) lyr.CreateFeature(ogr.Feature(lyr.GetLayerDefn())) lyr.ResetReading() f = lyr.GetNextFeature() - if f is None or f.GetFID() != 1: - gdaltest.post_reason('fail') - return 'fail' + assert f is not None and f.GetFID() == 1 ds.CommitTransaction() # the cursor is still valid after CommitTransaction(), which isn't the case for other backends such as PG ! f = lyr.GetNextFeature() - if f is None or f.GetFID() != 2: - gdaltest.post_reason('fail') - return 'fail' - if lyr.GetFeatureCount() != 2: - gdaltest.post_reason('fail') - return 'fail' + assert f is not None and f.GetFID() == 2 + assert lyr.GetFeatureCount() == 2 ds.StartTransaction() lyr = ds.CreateLayer('test2', geom_type=ogr.wkbPoint) @@ -3309,18 +2691,14 @@ def ogr_sqlite_40(): f.SetGeometryDirectly(ogr.CreateGeometryFromWkt('POINT(0 0)')) ret = lyr.CreateFeature(f) ds.CommitTransaction() - if ret != 0: - gdaltest.post_reason('fail') - return 'fail' + assert ret == 0 ds.StartTransaction() f = ogr.Feature(lyr.GetLayerDefn()) f.SetGeometryDirectly(ogr.CreateGeometryFromWkt('POINT(0 0)')) ret = lyr.CreateFeature(f) ds.CommitTransaction() - if ret != 0: - gdaltest.post_reason('fail') - return 'fail' + assert ret == 0 ds.StartTransaction() lyr = ds.CreateLayer('test3', geom_type=ogr.wkbPoint) @@ -3341,24 +2719,20 @@ def ogr_sqlite_40(): f.SetGeometryDirectly(ogr.CreateGeometryFromWkt('POINT(0 0)')) ret = lyr.CreateFeature(f) ds.CommitTransaction() - if ret != 0: - gdaltest.post_reason('fail') - return 'fail' + assert ret == 0 ds = None ogr.GetDriverByName('SQLite').DeleteDataSource('/vsimem/ogr_sqlite_40.sqlite') - return 'success' - ############################################################################### # Test reading dates from Julian day floating point representation -def ogr_sqlite_41(): +def test_ogr_sqlite_41(): if gdaltest.sl_ds is None: - return 'skip' + pytest.skip() ds = ogr.GetDriverByName('SQLite').CreateDataSource('/vsimem/ogr_sqlite_41.sqlite', options=['METADATA=NO']) ds.ExecuteSQL('CREATE TABLE test(a_date DATETIME);') ds.ExecuteSQL("INSERT INTO test(a_date) VALUES (strftime('%J', '2015-04-30 12:34:56'))") @@ -3367,24 +2741,20 @@ def ogr_sqlite_41(): ds = ogr.Open('/vsimem/ogr_sqlite_41.sqlite') lyr = ds.GetLayer(0) f = lyr.GetNextFeature() - if f['a_date'] != '2015/04/30 12:34:56': - gdaltest.post_reason('fail') - return 'fail' + assert f['a_date'] == '2015/04/30 12:34:56' ds = None ogr.GetDriverByName('SQLite').DeleteDataSource('/vsimem/ogr_sqlite_41.sqlite') - return 'success' - ############################################################################### # Test ExecuteSQL() heuristics (#6107) -def ogr_sqlite_42(): +def test_ogr_sqlite_42(): if gdaltest.sl_ds is None: - return 'skip' + pytest.skip() ds = ogr.GetDriverByName('SQLite').CreateDataSource('/vsimem/ogr_sqlite_42.sqlite') lyr = ds.CreateLayer("aab") @@ -3397,17 +2767,13 @@ def ogr_sqlite_42(): sql_lyr = ds.ExecuteSQL('SELECT id FROM aab') sql_lyr.SetAttributeFilter('id = 1') f = sql_lyr.GetNextFeature() - if f is None: - gdaltest.post_reason('fail') - return 'fail' + assert f is not None ds.ReleaseResultSet(sql_lyr) sql_lyr = ds.ExecuteSQL('SELECT id FROM "aab"') sql_lyr.SetAttributeFilter('id = 1') f = sql_lyr.GetNextFeature() - if f is None: - gdaltest.post_reason('fail') - return 'fail' + assert f is not None ds.ReleaseResultSet(sql_lyr) lyr = ds.CreateLayer('with"quotes') @@ -3420,54 +2786,45 @@ def ogr_sqlite_42(): sql_lyr = ds.ExecuteSQL('SELECT id FROM "with""quotes"') sql_lyr.SetAttributeFilter('id = 1') f = sql_lyr.GetNextFeature() - if f is None: - gdaltest.post_reason('fail') - return 'fail' + assert f is not None ds.ReleaseResultSet(sql_lyr) # Too complex to analyze sql_lyr = ds.ExecuteSQL('SELECT id FROM "with""quotes" UNION ALL SELECT id FROM aab') sql_lyr.SetAttributeFilter('id = 1') f = sql_lyr.GetNextFeature() - if f is None: - gdaltest.post_reason('fail') - return 'fail' + assert f is not None ds.ReleaseResultSet(sql_lyr) ds = None ogr.GetDriverByName('SQLite').DeleteDataSource('/vsimem/ogr_sqlite_42.sqlite') - return 'success' - ############################################################################### # Test file:foo?mode=memory&cache=shared (#6150) -def ogr_sqlite_43(): +def test_ogr_sqlite_43(): if gdaltest.sl_ds is None: - return 'skip' + pytest.skip() # Only available since sqlite 3.8.0 version = ogrtest.sqlite_version.split('.') if not (len(version) >= 3 and int(version[0]) * 10000 + int(version[1]) * 100 + int(version[2]) >= 30800): - return 'skip' + pytest.skip() ds = ogr.Open('file:foo?mode=memory&cache=shared') - if ds is None: - return 'fail' - - return 'success' + assert ds is not None ############################################################################### # Test reading/writing StringList, etc.. -def ogr_sqlite_44(): +def test_ogr_sqlite_44(): if gdaltest.sl_ds is None: - return 'skip' + pytest.skip() gdal.FileFromMemBuffer('/vsimem/ogr_sqlite_44.csvt', 'JsonStringList,JsonIntegerList,JsonInteger64List,JsonRealList,WKT') gdal.FileFromMemBuffer('/vsimem/ogr_sqlite_44.csv', @@ -3479,25 +2836,17 @@ def ogr_sqlite_44(): gdal.VectorTranslate('/vsimem/ogr_sqlite_44_out.csv', '/vsimem/ogr_sqlite_44.sqlite', format='CSV', layerCreationOptions=['CREATE_CSVT=YES', 'LINEFORMAT=LF']) f = gdal.VSIFOpenL('/vsimem/ogr_sqlite_44_out.csv', 'rb') - if f is None: - gdaltest.post_reason('fail') - return 'fail' + assert f is not None data = gdal.VSIFReadL(1, 10000, f).decode('ascii') gdal.VSIFCloseL(f) - if data.find('stringlist,intlist,int64list,reallist,wkt\n"[ ""a"", """" ]",[ 1 ],[ 1234567890123 ],[ 0.125') != 0: - gdaltest.post_reason('fail') - print(data) - return 'fail' + assert data.find('stringlist,intlist,int64list,reallist,wkt\n"[ ""a"", """" ]",[ 1 ],[ 1234567890123 ],[ 0.125') == 0 f = gdal.VSIFOpenL('/vsimem/ogr_sqlite_44_out.csvt', 'rb') data = gdal.VSIFReadL(1, 10000, f).decode('ascii') gdal.VSIFCloseL(f) - if data.find('JSonStringList,JSonIntegerList,JSonInteger64List,JSonRealList') != 0: - gdaltest.post_reason('fail') - print(data) - return 'fail' + assert data.find('JSonStringList,JSonIntegerList,JSonInteger64List,JSonRealList') == 0 gdal.Unlink('/vsimem/ogr_sqlite_44.csv') gdal.Unlink('/vsimem/ogr_sqlite_44.csvt') @@ -3505,58 +2854,44 @@ def ogr_sqlite_44(): gdal.Unlink('/vsimem/ogr_sqlite_44_out.csv') gdal.Unlink('/vsimem/ogr_sqlite_44_out.csvt') - return 'success' - ############################################################################### # Test WAL and opening in read-only (#6776) -def ogr_sqlite_45(): +def test_ogr_sqlite_45(): if gdaltest.sl_ds is None: - return 'skip' + pytest.skip() # Only available since sqlite 3.7.0 version = ogrtest.sqlite_version.split('.') if not (len(version) >= 3 and int(version[0]) * 10000 + int(version[1]) * 100 + int(version[2]) >= 30700): - return 'skip' + pytest.skip() ds = ogr.GetDriverByName('SQLite').CreateDataSource('tmp/ogr_sqlite_45.db') sql_lyr = ds.ExecuteSQL('PRAGMA journal_mode = WAL') ds.ReleaseResultSet(sql_lyr) sql_lyr = ds.ExecuteSQL('SELECT * FROM sqlite_master') ds.ReleaseResultSet(sql_lyr) - if not os.path.exists('tmp/ogr_sqlite_45.db-wal'): - gdaltest.post_reason('fail') - return 'fail' + assert os.path.exists('tmp/ogr_sqlite_45.db-wal') shutil.copy('tmp/ogr_sqlite_45.db', 'tmp/ogr_sqlite_45_bis.db') shutil.copy('tmp/ogr_sqlite_45.db-shm', 'tmp/ogr_sqlite_45_bis.db-shm') shutil.copy('tmp/ogr_sqlite_45.db-wal', 'tmp/ogr_sqlite_45_bis.db-wal') ds = None - if os.path.exists('tmp/ogr_sqlite_45.db-wal'): - gdaltest.post_reason('fail') - return 'fail' + assert not os.path.exists('tmp/ogr_sqlite_45.db-wal') ds = ogr.Open('tmp/ogr_sqlite_45_bis.db') ds = None - if os.path.exists('tmp/ogr_sqlite_45_bis.db-wal'): - gdaltest.post_reason('fail') - return 'fail' + assert not os.path.exists('tmp/ogr_sqlite_45_bis.db-wal') gdal.Unlink('tmp/ogr_sqlite_45.db') gdal.Unlink('tmp/ogr_sqlite_45_bis.db') - return 'success' - ############################################################################### # Test creating unsupported geometry types -def ogr_spatialite_11(): - - if not gdaltest.has_spatialite: - return 'skip' - +def test_ogr_spatialite_11(require_spatialite): ds = ogr.GetDriverByName('SQLite').CreateDataSource('/vsimem/ogr_spatialite_11.sqlite', options=['SPATIALITE=YES']) # Will be converted to LineString @@ -3568,44 +2903,32 @@ def ogr_spatialite_11(): lyr = ds.CreateLayer('test2', geom_type=ogr.wkbNone) with gdaltest.error_handler(): res = lyr.CreateGeomField(ogr.GeomFieldDefn('foo', ogr.wkbCurvePolygon)) - if res == 0: - gdaltest.post_reason('fail') - return 'fail' + assert res != 0 ds = None gdal.Unlink('/vsimem/ogr_spatialite_11.sqlite') - return 'success' - ############################################################################### # Test opening a .sql file -def ogr_spatialite_12(): - - if not gdaltest.has_spatialite: - return 'skip' - +def test_ogr_spatialite_12(require_spatialite): if gdal.GetDriverByName('SQLite').GetMetadataItem("ENABLE_SQL_SQLITE_FORMAT") != 'YES': - return 'skip' + pytest.skip() ds = ogr.Open('data/poly_spatialite.sqlite.sql') lyr = ds.GetLayer(0) f = lyr.GetNextFeature() - if f is None: - gdaltest.post_reason('fail') - return 'fail' - - return 'success' + assert f is not None ############################################################################### -def ogr_sqlite_iterate_and_update(): +def test_ogr_sqlite_iterate_and_update(): if gdaltest.sl_ds is None: - return 'skip' + pytest.skip() filename = "/vsimem/ogr_sqlite_iterate_and_update.db" ds = ogr.GetDriverByName('SQLite').CreateDataSource(filename) @@ -3623,21 +2946,19 @@ def ogr_sqlite_iterate_and_update(): lyr.SetFeature(f) lyr.ResetReading() for f in lyr: - if not f['strfield'].endswith('_updated'): - return 'fail' + assert f['strfield'].endswith('_updated') ds = None gdal.Unlink(filename) - return 'success' ############################################################################### # -def ogr_sqlite_cleanup(): +def test_ogr_sqlite_cleanup(): if gdaltest.sl_ds is None: - return 'skip' + pytest.skip() gdaltest.sl_ds.ExecuteSQL('DELLAYER:tpoly') gdaltest.sl_ds.ExecuteSQL('DELLAYER:tpoly_2') @@ -3653,193 +2974,3 @@ def ogr_sqlite_cleanup(): gdaltest.sl_ds = None gdaltest.shp_ds = None - - try: - os.remove('tmp/sqlite_test.db') - except OSError: - pass - - try: - os.remove('tmp/spatialite_test.db') - except OSError: - pass - - try: - os.remove('tmp/spatialite_test_with_epsg.db') - except OSError: - pass - - try: - os.remove('tmp/non_spatialite_test_with_epsg.db') - except OSError: - pass - try: - os.remove('tmp/test24.sqlite') - except OSError: - pass - - try: - os.remove('tmp/ogr_spatialite_5.sqlite') - except OSError: - pass - - try: - os.remove('tmp/ogr_spatialite_6.sqlite') - except OSError: - pass - - try: - os.remove('tmp/ogr_sqlite_27.sqlite') - except OSError: - pass - - try: - os.remove('tmp/ogr_sqlite_29.sqlite') - except OSError: - pass - - try: - os.remove('tmp/ogr_spatialite_8.sqlite') - except OSError: - pass - - try: - os.remove('tmp/ogr_sqlite_31.sqlite') - except OSError: - pass - - try: - os.remove('tmp/ogr_sqlite_32.sqlite') - except OSError: - pass - - try: - os.remove('tmp/ogr_sqlite_33.sqlite') - except OSError: - pass - - try: - os.remove('tmp/ogr_sqlite_35.sqlite') - except OSError: - pass - - try: - os.remove('tmp/ogr_sqlite_36.sqlite') - except OSError: - pass - - try: - os.remove('tmp/ogr_sqlite_37.sqlite') - except OSError: - pass - - try: - os.remove('tmp/ogr_sqlite_38.sqlite') - except OSError: - pass - try: - os.remove('tmp/ogr_spatialite_10.sqlite') - except OSError: - pass - return 'success' - -############################################################################### -# Ask to run again tests in a new python process without libspatialite loaded - - -def ogr_sqlite_without_spatialite(): - - if not gdaltest.has_spatialite or not run_without_spatialite: - return 'skip' - - import test_py_scripts - ret = test_py_scripts.run_py_script_as_external_script('.', 'ogr_sqlite', ' -without_spatialite', display_live_on_parent_stdout=True) - - if ret.find('Failed: 0') == -1: - return 'fail' - - return 'success' - - -gdaltest_list = [ - ogr_sqlite_1, - ogr_sqlite_2, - ogr_sqlite_3, - ogr_sqlite_4, - ogr_sqlite_5, - ogr_sqlite_6, - ogr_sqlite_7, - ogr_sqlite_8, - ogr_sqlite_9, - ogr_sqlite_10, - ogr_sqlite_11, - ogr_sqlite_12, - ogr_sqlite_13, - ogr_sqlite_14, - ogr_sqlite_15, - ogr_sqlite_16, - ogr_sqlite_20, - ogr_sqlite_21, - ogr_sqlite_22, - ogr_sqlite_23, - ogr_sqlite_24, - ogr_sqlite_25, - ogr_sqlite_26, - ogr_sqlite_27, - ogr_sqlite_28, - ogr_sqlite_29, - ogr_sqlite_30, - ogr_spatialite_1, - ogr_sqlite_17, - ogr_sqlite_18, - ogr_sqlite_19, - ogr_sqlite_19_bis, - ogr_spatialite_2, - ogr_spatialite_3, - ogr_spatialite_4, - ogr_spatialite_5, - ogr_spatialite_compressed_geom_5, - ogr_spatialite_6, - ogr_spatialite_7, - ogr_spatialite_8, - ogr_sqlite_31, - ogr_sqlite_32, - ogr_sqlite_33, - ogr_sqlite_34, - ogr_sqlite_35, - ogr_sqlite_36, - ogr_sqlite_37, - ogr_sqlite_38, - ogr_spatialite_9, - ogr_spatialite_10, - ogr_sqlite_39, - ogr_sqlite_40, - ogr_sqlite_41, - ogr_sqlite_42, - ogr_sqlite_43, - ogr_sqlite_44, - ogr_sqlite_45, - ogr_sqlite_iterate_and_update, - ogr_spatialite_11, - ogr_spatialite_12, - ogr_sqlite_cleanup, - ogr_sqlite_without_spatialite, -] - -disabled_gdaltest_list = [ - ogr_sqlite_1, - ogr_sqlite_45, - ogr_sqlite_cleanup, -] - -if __name__ == '__main__': - - if len(sys.argv) >= 2 and sys.argv[1] == '-without_spatialite': - run_without_spatialite = False - gdal.SetConfigOption('SPATIALITE_LOAD', 'NO') - - gdaltest.setup_run('ogr_sqlite') - - gdaltest.run_tests(gdaltest_list) - - sys.exit(gdaltest.summarize()) diff --git a/autotest/ogr/ogr_style.py b/autotest/ogr/ogr_style.py index 2253db38a0f6..fb3390230c6a 100755 --- a/autotest/ogr/ogr_style.py +++ b/autotest/ogr/ogr_style.py @@ -29,11 +29,8 @@ # DEALINGS IN THE SOFTWARE. ############################################################################### -import sys -sys.path.append('../pymod') -import gdaltest from osgeo import ogr from osgeo import gdal @@ -42,113 +39,69 @@ # -def ogr_style_styletable(): +def test_ogr_style_styletable(): style_table = ogr.StyleTable() style_table.AddStyle("style1_normal", 'SYMBOL(id:"http://style1_normal",c:#67452301)') gdal.PushErrorHandler('CPLQuietErrorHandler') ret = style_table.SaveStyleTable('/nonexistingdir/nonexistingfile') gdal.PopErrorHandler() - if ret != 0: - gdaltest.post_reason('failure') - print(ret) - return 'fail' - if style_table.SaveStyleTable("/vsimem/out.txt") != 1: - gdaltest.post_reason('failure') - return 'fail' + assert ret == 0 + assert style_table.SaveStyleTable("/vsimem/out.txt") == 1 style_table = None style_table = ogr.StyleTable() gdal.PushErrorHandler('CPLQuietErrorHandler') ret = style_table.LoadStyleTable('/nonexistent') gdal.PopErrorHandler() - if ret != 0: - gdaltest.post_reason('failure') - return 'fail' - if style_table.LoadStyleTable('/vsimem/out.txt') != 1: - gdaltest.post_reason('failure') - return 'fail' + assert ret == 0 + assert style_table.LoadStyleTable('/vsimem/out.txt') == 1 gdal.Unlink('/vsimem/out.txt') gdal.PushErrorHandler('CPLQuietErrorHandler') ret = style_table.Find("non_existing_style") gdal.PopErrorHandler() - if ret is not None: - gdaltest.post_reason('failure') - return 'fail' + assert ret is None - if style_table.Find("style1_normal") != 'SYMBOL(id:"http://style1_normal",c:#67452301)': - gdaltest.post_reason('failure') - return 'fail' + assert style_table.Find("style1_normal") == 'SYMBOL(id:"http://style1_normal",c:#67452301)' style = style_table.GetNextStyle() - if style != 'SYMBOL(id:"http://style1_normal",c:#67452301)': - gdaltest.post_reason('failure') - return 'fail' + assert style == 'SYMBOL(id:"http://style1_normal",c:#67452301)' style_name = style_table.GetLastStyleName() - if style_name != 'style1_normal': - gdaltest.post_reason('failure') - return 'fail' + assert style_name == 'style1_normal' style = style_table.GetNextStyle() - if style is not None: - gdaltest.post_reason('failure') - return 'fail' + assert style is None style_table.ResetStyleStringReading() style = style_table.GetNextStyle() - if style is None: - gdaltest.post_reason('failure') - return 'fail' + assert style is not None # GetStyleTable()/SetStyleTable() on data source ds = ogr.GetDriverByName('Memory').CreateDataSource('') - if ds.GetStyleTable() is not None: - gdaltest.post_reason('failure') - return 'fail' + assert ds.GetStyleTable() is None ds.SetStyleTable(None) - if ds.GetStyleTable() is not None: - gdaltest.post_reason('failure') - return 'fail' + assert ds.GetStyleTable() is None ds.SetStyleTable(style_table) style_table2 = ds.GetStyleTable() style = style_table2.GetNextStyle() - if style != 'SYMBOL(id:"http://style1_normal",c:#67452301)': - gdaltest.post_reason('failure') - return 'fail' + assert style == 'SYMBOL(id:"http://style1_normal",c:#67452301)' # GetStyleTable()/SetStyleTable() on layer lyr = ds.CreateLayer('foo') - if lyr.GetStyleTable() is not None: - gdaltest.post_reason('failure') - return 'fail' + assert lyr.GetStyleTable() is None lyr.SetStyleTable(None) - if lyr.GetStyleTable() is not None: - gdaltest.post_reason('failure') - return 'fail' + assert lyr.GetStyleTable() is None lyr.SetStyleTable(style_table) style_table2 = lyr.GetStyleTable() style = style_table2.GetNextStyle() - if style != 'SYMBOL(id:"http://style1_normal",c:#67452301)': - gdaltest.post_reason('failure') - return 'fail' + assert style == 'SYMBOL(id:"http://style1_normal",c:#67452301)' ds = None - return 'success' - ############################################################################### # Build tests runner -gdaltest_list = [ - ogr_style_styletable] - -if __name__ == '__main__': - - gdaltest.setup_run('ogr_style') - - gdaltest.run_tests(gdaltest_list) - sys.exit(gdaltest.summarize()) diff --git a/autotest/ogr/ogr_sua.py b/autotest/ogr/ogr_sua.py index d93eb801b479..7101f2c807b1 100755 --- a/autotest/ogr/ogr_sua.py +++ b/autotest/ogr/ogr_sua.py @@ -28,57 +28,39 @@ # DEALINGS IN THE SOFTWARE. ############################################################################### -import sys -sys.path.append('../pymod') -import gdaltest import ogrtest from osgeo import ogr +import pytest ############################################################################### # Basic test -def ogr_sua_1(): +def test_ogr_sua_1(): ds = ogr.Open('data/za.sua') - if ds is None: - gdaltest.post_reason('cannot open dataset') - return 'fail' + assert ds is not None, 'cannot open dataset' lyr = ds.GetLayer(0) - if lyr is None: - gdaltest.post_reason('cannot find layer') - return 'fail' + assert lyr is not None, 'cannot find layer' feat = lyr.GetNextFeature() geom = feat.GetGeometryRef() if ogrtest.check_feature_geometry(feat, 'POLYGON ((24.760277777777777 -28.466666666666683,24.766895312434809 -28.46671727367243,24.773510850527718 -28.466869079419723,24.780122395865373 -28.467122038103,24.786727953485673 -28.467476073394735,24.793325530310469 -28.467931078467672,24.799913135516679 -28.468486916026166,24.806488781187785 -28.469143418346533,24.813050482985464 -28.469900387326192,24.819596260561802 -28.47075759454188,24.826124138325216 -28.47171478131645,24.832632145879771 -28.472771658795054,24.839118318703743 -28.47392790802968,24.845580698630823 -28.475183180072875,24.852017334528803 -28.476537096080108,24.858426282776776 -28.47798924742105,24.86480560789666 -28.479539195799475,24.871153383126547 -28.481186473381939,24.877467690931773 -28.482930582935339,24.883746623625481 -28.48477099797276,24.889988283903538 -28.486707162908274,24.896190785431472 -28.48873849322014,24.902352253349676 -28.490864375622735,24.908470824878808 -28.493084168246597,24.914544649847166 -28.495397200827426,24.920571891246279 -28.497802774903008,24.926550725747585 -28.500300164018839,24.932479344288705 -28.502888613941764,24.938355952571698 -28.505567342882131,24.944178771610126 -28.508335541723795,24.949946038264724 -28.511192374262492,24.955656005751909 -28.514136977452182,24.961306944165695 -28.517168461659423,24.966897141013046 -28.520285910925423,24.972424901704478 -28.523488383236369,24.977888550056022 -28.526774910801166,24.983286428814758 -28.530144500336959,24.988616900132001 -28.533596133362522,24.99387834606733 -28.537128766498796,24.999069169069763 -28.540741331777156,25.004187792453038 -28.544432736955102,25.009232660883608 -28.548201865839104,25.014202240830937 -28.552047578614662,25.019095021044684 -28.555968712183585,25.02390951301135 -28.559964080508252,25.028644251401499 -28.564032474962829,25.033297794511821 -28.568172664691346,25.037868724701763 -28.572383396972441,25.042355648839958 -28.576663397590849,25.046757198702647 -28.581011371215411,25.051072031428639 -28.585426001783489,25.055298829890791 -28.589905952891769,25.059436303127992 -28.594449868193294,25.063483186732412 -28.599056371800572,25.067438243238151 -28.603724068694731,25.071300262513763 -28.608451545140568,25.075068062113562 -28.613237369107495,25.078740487674832 -28.618080090695855,25.082316413248837 -28.622978242569175,25.085794741684015 -28.627930340391472,25.089174404927817 -28.632934883270281,25.092454364404489 -28.637990354204419,25.095633611313403 -28.643095220537134,25.098711166955503 -28.64824793441413,25.10168608305365 -28.653446933246229,25.104557442038406 -28.658690640176914,25.107324357344936 -28.663977464554407,25.109985973715663 -28.669305802407834,25.112541467439499 -28.674674036928209,25.114990046654459 -28.680080538952993,25.117330951578985 -28.685523667455101,25.119563454781961 -28.691001770035456,25.121686861395737 -28.696513183419484,25.123700509365641 -28.702056233957038,25.125603769666306 -28.707629238125719,25.127396046506441 -28.713230503037792,25.129076777527761 -28.718858326949757,25.130645434008265 -28.724510999775319,25.13210152102771 -28.730186803601043,25.133444577652867 -28.735884013204668,25.134674177090211 -28.741600896576003,25.135789926836566 -28.7473357154403,25.136791468828061 -28.753086725783632,25.137678479562659 -28.758852178380579,25.138450670228519 -28.764630319323757,25.139107786806342 -28.770419390555091,25.139649610175514 -28.776217630398676,25.140075956205322 -28.782023274095195,25.140386675823155 -28.787834554337508,25.140581655100206 -28.793649701807396,25.140660815291394 -28.799466945713419,25.140624112899374 -28.805284514329315,25.140471539698027 -28.811100635533307,25.140203122769478 -28.816913537347659,25.139818924509857 -28.822721448478802,25.139319042644907 -28.828522598857376,25.138703610206345 -28.834315220178425,25.137972795537667 -28.840097546441314,25.137126802248048 -28.845867814489324,25.136165869182687 -28.85162426454886,25.135090270371048 -28.857365140767754,25.133900314962272 -28.863088691752992,25.132596347160835 -28.868793171107171,25.131178746139458 -28.874476837963954,25.129647925945786 -28.880137957522209,25.128004335404732 -28.885774801578492,25.126248457993494 -28.891385649057952,25.124380811721167 -28.896968786543397,25.122401948989488 -28.902522508802292,25.120312456446726 -28.908045119311723,25.118112954838665 -28.913534930780742,25.11580409880861 -28.918990265670601,25.113386576755399 -28.924409456711885,25.110861110617904 -28.92979084741917,25.108228455676212 -28.935132792602516,25.105489400347579 -28.940433658875676,25.102644765960211 -28.94569182516129,25.099695406505884 -28.950905683192275,25.096642208420011 -28.956073638009698,25.093486090307582 -28.961194108456937,25.090228002679709 -28.96626552766962,25.086868927687608 -28.97128634356163,25.083409878829617 -28.976255019306763,25.079851900655964 -28.981170033815886,25.076196068457499 -28.986029882209536,25.072443487959553 -28.990833076285767,25.068595294982366 -28.995578144983043,25.064652655115509 -29.000263634838049,25.060616763368554 -29.004888110438372,25.05648884380911 -29.009450154869668,25.052270149197888 -29.013948370157522,25.04796196062637 -29.018381377703292,25.043565587113235 -29.022747818714564,25.039082365218423 -29.027046354629377,25.034513658643014 -29.031275667534388,25.029860857809823 -29.035434460576823,25.025125379446433 -29.039521458370103,25.020308666156058 -29.043535407392909,25.015412185972465 -29.047475076381517,25.010437431908937 -29.051339256715593,25.005385921523313 -29.055126762796746,25.000259196426232 -29.05883643242025,24.995058821820685 -29.062467127139698,24.98978638601983 -29.066017732624076,24.984443499974287 -29.069487159007593,24.979031796736475 -29.072874341232009,24.973552930996892 -29.076178239381264,24.96800857854516 -29.079397839008323,24.962400435777845 -29.082532151454132,24.95673021914298 -29.085580214158654,24.950999664626245 -29.088541090963787,24.945210527202558 -29.09141387240804,24.939364580306272 -29.094197676012925,24.933463615254794 -29.096891646561062,24.927509440705947 -29.09949495636549,24.921503882088025 -29.102006805530834,24.915448781031092 -29.104426422205322,24.909345994796006 -29.10675306282441,24.90319739567629 -29.108986012345341,24.897004870446018 -29.11112458447279,24.890770319697953 -29.113168121875631,24.884495657344228 -29.115115996394422,24.878182809944395 -29.116967609239822,24.871833716110423 -29.11872239118189,24.865450325918069 -29.120379802729857,24.859034600277788 -29.121939334302667,24.852588510335149 -29.123400506390141,24.846114036796582 -29.124762869704583,24.83961316938128 -29.1260260053228,24.8330879061436 -29.127189524818803,24.826540252848378 -29.128253070386421,24.819972222345168 -29.129216314952828,24.813385833911177 -29.1300789622818,24.806783112687896 -29.130840747067623,24.800166088946376 -29.131501435018961,24.793536797471898 -29.132060822933184,24.786897276912615 -29.132518738760538,24.780249569276663 -29.132875041658693,24.773595719053805 -29.133129622037345,24.766937772515039 -29.133282401592936,24.760277777777777 -29.13333333333334,24.753617783040514 -29.133282401592936,24.746959836501748 -29.133129622037345,24.740305986278891 -29.132875041658693,24.733658278642938 -29.132518738760538,24.727018758083656 -29.132060822933184,24.720389466609177 -29.131501435018961,24.713772442867658 -29.130840747067623,24.707169721644377 -29.1300789622818,24.700583333210385 -29.129216314952828,24.694015302707175 -29.128253070386421,24.687467649411953 -29.127189524818803,24.680942386174273 -29.1260260053228,24.674441518758972 -29.124762869704583,24.667967045220404 -29.123400506390141,24.661520955277766 -29.121939334302667,24.655105229637485 -29.120379802729857,24.64872183944513 -29.11872239118189,24.642372745611159 -29.116967609239822,24.636059898211325 -29.115115996394422,24.6297852358576 -29.113168121875631,24.623550685109535 -29.11112458447279,24.617358159879263 -29.108986012345341,24.611209560759548 -29.10675306282441,24.605106774524462 -29.104426422205322,24.599051673467528 -29.102006805530834,24.593046114849606 -29.09949495636549,24.587091940300759 -29.096891646561062,24.581190975249282 -29.094197676012925,24.575345028352995 -29.09141387240804,24.569555890929308 -29.088541090963787,24.563825336412574 -29.085580214158654,24.558155119777709 -29.082532151454132,24.552546977010394 -29.079397839008323,24.547002624558662 -29.076178239381264,24.541523758819078 -29.072874341232009,24.536112055581267 -29.069487159007593,24.530769169535724 -29.066017732624076,24.525496733734869 -29.062467127139698,24.520296359129322 -29.05883643242025,24.51516963403224 -29.055126762796746,24.510118123646617 -29.051339256715593,24.505143369583088 -29.047475076381517,24.500246889399495 -29.043535407392909,24.495430176109121 -29.039521458370103,24.490694697745731 -29.035434460576823,24.486041896912539 -29.031275667534388,24.48147319033713 -29.027046354629377,24.476989968442318 -29.022747818714564,24.472593594929183 -29.018381377703292,24.468285406357666 -29.013948370157522,24.464066711746444 -29.009450154869668,24.459938792187 -29.004888110438372,24.455902900440044 -29.000263634838049,24.451960260573188 -28.995578144983043,24.448112067596 -28.990833076285767,24.444359487098055 -28.986029882209536,24.44070365489959 -28.981170033815886,24.437145676725937 -28.976255019306763,24.433686627867946 -28.97128634356163,24.430327552875845 -28.96626552766962,24.427069465247971 -28.961194108456937,24.423913347135542 -28.956073638009698,24.42086014904967 -28.950905683192275,24.417910789595343 -28.94569182516129,24.415066155207974 -28.940433658875676,24.412327099879342 -28.935132792602516,24.409694444937649 -28.92979084741917,24.407168978800154 -28.924409456711885,24.404751456746943 -28.918990265670601,24.402442600716888 -28.913534930780742,24.400243099108827 -28.908045119311723,24.398153606566066 -28.902522508802292,24.396174743834386 -28.896968786543397,24.394307097562059 -28.891385649057952,24.392551220150821 -28.885774801578492,24.390907629609767 -28.880137957522209,24.389376809416095 -28.874476837963954,24.387959208394719 -28.868793171107171,24.386655240593281 -28.863088691752992,24.385465285184505 -28.857365140767754,24.384389686372867 -28.85162426454886,24.383428753306539 -28.845867814489324,24.382582760017886 -28.840097546441314,24.381851945350171 -28.834315220178425,24.381236512910647 -28.828522598857376,24.380736631045696 -28.822721448478802,24.380352432786076 -28.816913537347659,24.380084015857527 -28.811100635533307,24.379931442656179 -28.805284514329315,24.379894740264159 -28.799466945713419,24.379973900455347 -28.793649701807396,24.380168879732398 -28.787834554337508,24.380479599350231 -28.782023274095195,24.380905945380039 -28.776217630398676,24.381447768749211 -28.770419390555091,24.382104885327035 -28.764630319323757,24.382877075992894 -28.758852178380579,24.383764086727492 -28.753086725783632,24.384765628718988 -28.7473357154403,24.385881378465342 -28.741600896576003,24.387110977902687 -28.735884013204668,24.388454034527843 -28.730186803601043,24.389910121547288 -28.724510999775319,24.391478778027793 -28.718858326949757,24.393159509049113 -28.713230503037792,24.394951785889248 -28.707629238125719,24.396855046189913 -28.702056233957038,24.398868694159816 -28.696513183419484,24.400992100773593 -28.691001770035456,24.403224603976568 -28.685523667455101,24.405565508901095 -28.680080538952993,24.408014088116055 -28.674674036928209,24.410569581839891 -28.669305802407834,24.413231198210617 -28.663977464554407,24.415998113517148 -28.658690640176914,24.418869472501903 -28.653446933246229,24.42184438860005 -28.64824793441413,24.424921944242151 -28.643095220537134,24.428101191151065 -28.637990354204419,24.431381150627736 -28.632934883270281,24.434760813871538 -28.627930340391472,24.438239142306717 -28.622978242569175,24.441815067880722 -28.618080090695855,24.445487493441991 -28.613237369107495,24.449255293041791 -28.608451545140568,24.453117312317403 -28.603724068694731,24.457072368823141 -28.599056371800572,24.461119252427562 -28.594449868193294,24.465256725664762 -28.589905952891769,24.469483524126915 -28.585426001783489,24.473798356852907 -28.581011371215411,24.478199906715595 -28.576663397590849,24.48268683085379 -28.572383396972441,24.487257761043733 -28.568172664691346,24.491911304154055 -28.564032474962829,24.496646042544203 -28.559964080508252,24.501460534510869 -28.555968712183585,24.506353314724617 -28.552047578614662,24.511322894671945 -28.548201865839104,24.516367763102515 -28.544432736955102,24.52148638648579 -28.540741331777156,24.526677209488223 -28.537128766498796,24.531938655423552 -28.533596133362522,24.537269126740796 -28.530144500336959,24.542667005499531 -28.526774910801166,24.548130653851075 -28.523488383236369,24.553658414542507 -28.520285910925423,24.559248611389858 -28.517168461659423,24.564899549803645 -28.514136977452182,24.57060951729083 -28.511192374262492,24.576376783945427 -28.508335541723795,24.582199602983856 -28.505567342882131,24.588076211266849 -28.502888613941764,24.594004829807968 -28.500300164018839,24.599983664309274 -28.497802774903008,24.606010905708388 -28.495397200827426,24.612084730676745 -28.493084168246597,24.618203302205877 -28.490864375622735,24.624364770124082 -28.48873849322014,24.630567271652016 -28.486707162908274,24.636808931930073 -28.48477099797276,24.64308786462378 -28.482930582935339,24.649402172429006 -28.481186473381939,24.655749947658894 -28.479539195799475,24.662129272778778 -28.47798924742105,24.668538221026751 -28.476537096080108,24.674974856924731 -28.475183180072875,24.68143723685181 -28.47392790802968,24.687923409675783 -28.472771658795054,24.694431417230337 -28.47171478131645,24.700959294993751 -28.47075759454188,24.70750507257009 -28.469900387326192,24.714066774367769 -28.469143418346533,24.720642420038875 -28.468486916026166,24.727230025245085 -28.467931078467672,24.73382760206988 -28.467476073394735,24.740433159690181 -28.467122038103,24.747044705027836 -28.466869079419723,24.753660243120745 -28.46671727367243,24.760277777777777 -28.466666666666683))', max_error=0.0000001) != 0: print('did not get expected first geom') - print(geom.ExportToWkt()) - return 'fail' + pytest.fail(geom.ExportToWkt()) feat = lyr.GetNextFeature() geom = feat.GetGeometryRef() if ogrtest.check_feature_geometry(feat, 'POLYGON ((25.324444444444445 -28.735,25.324444444444445 -28.735,25.324444444444747 -28.735,25.3256844012835 -28.743637219488093,25.326752458414518 -28.752292221672775,25.327648242989319 -28.760962374913134,25.328371434292126 -28.769645042225264,25.328921763884399 -28.778337582080368,25.329299015739096 -28.787037349205164,25.329503026367707 -28.795741695383924,25.329533684919237 -28.804447970262672,25.329390933266499 -28.813153522154423,25.329074766083266 -28.821855698846022,25.328585230899417 -28.830551848405761,25.32792242813515 -28.839239319991876,25.327086511130251 -28.847915464661341,25.326077686158602 -28.856577636179196,25.324896212403537 -28.865223191827752,25.323542401945843 -28.873849493215474,25.322016619719491 -28.882453907085591,25.320319283456154 -28.891033806123644,25.31845086360034 -28.899586569764509,25.316411883234647 -28.908109584997732,25.314202917960664 -28.916600247171544,25.311824595781452 -28.925055960795305,25.309277596961152 -28.933474140339584,25.306562653857945 -28.941852211034359,25.303680550768494 -28.950187609664397,25.300632123720742 -28.958477785362163,25.29741826027432 -28.966720200397404,25.294039899300181 -28.974912330963704,25.290498030727949 -28.983051667961448,25.286793695305345 -28.991135717776984,25.282927984310767 -28.999162003057677,25.278902039273312 -29.007128063482853,25.274717051653134 -29.015031456530025,25.270374262533323 -29.022869758236496,25.265874962270246 -29.030640563955714,25.26122049013696 -29.038341489108532,25.256412233959036 -29.045970169928736,25.251451629715206 -29.053524264202991,25.246340161140221 -29.06100145200449,25.241079359298173 -29.068399436420506,25.23567080214746 -29.075715944273327,25.230116114090873 -29.082948726834402,25.224416965497046 -29.090095560531509,25.218575072228933 -29.097154247648504,25.212592195130505 -29.10412261701785,25.206470139518853 -29.110998524705039,25.200210754651753 -29.11777985468531,25.193815933175109 -29.124464519512046,25.187287610571182 -29.131050460976667,25.180627764570215 -29.137535650759972,25.173838414570472 -29.143918091074411,25.166921621027861 -29.150195815297337,25.159879484826497 -29.156366888594846,25.152714146662561 -29.162429408536127,25.145427786377269 -29.168381505697866,25.138022622300941 -29.174221344258754,25.130500910584292 -29.179947122583698,25.122864944495355 -29.185557073797725,25.115117053723321 -29.191049466349057,25.107259603657024 -29.196422604561548,25.099294994669837 -29.201674829175872,25.091225661355146 -29.206804517879718,25.083054071794677 -29.211810085826329,25.074782726776942 -29.216689986141546,25.066414159022649 -29.221442710419112,25.057950932399795 -29.226066789203841,25.049395641117307 -29.230560792462668,25.040750908918767 -29.234923330043529,25.032019388244304 -29.239153052121523,25.023203759421683 -29.243248649632577,25.014306729794193 -29.247208854694165,25.005331032890854 -29.251032441013166,24.996279427553059 -29.254718224280467,24.987154697052485 -29.258265062552468,24.977959648227149 -29.261671856618946,24.96869711057434 -29.264937550357544,24.959369935370919 -29.268061131074475,24.949980994740844 -29.271041629831515,24.940533180755306 -29.273878121758855,24.931029404524764 -29.276569726354225,24.921472595226302 -29.27911560776748,24.911865699212655 -29.281514975071246,24.902211679051732 -29.283767082516917,24.892513512561873 -29.285871229776419,24.882774191884664 -29.287826762169175,24.872996722502361 -29.289633070874672,24.863184122310912 -29.291289593130031,24.853339420578315 -29.292795812413047,24.843465657046142 -29.294151258610142,24.833565880890973 -29.295355508169479,24.823643149820615 -29.296408184238985,24.813700528987738 -29.297308956789578,24.803741090085058 -29.298057542722887,24.793767910343536 -29.298653705964284,24.783784071443542 -29.299097257540382,24.773792658660838 -29.299388055641543,24.763796759952577 -29.299526005669037,24.753799464358973 -29.299511060267122,24.743803861918728 -29.299343219339562,24.733813042177051 -29.299022530051275,24.723830092997549 -29.298549086814461,24.713858099961822 -29.297923031259401,24.703900145183407 -29.297144552190304,24.693959306309406 -29.296213885525674,24.684038655567267 -29.295131314223482,24.674141258801942 -29.293897168191322,24.664270174416327 -29.292511824181247,24.65442845241142 -29.290975705669538,24.644619133445421 -29.289289282721541,24.634845247808041 -29.287453071841185,24.625109814448344 -29.285467635805958,24.615415840038214 -29.283333583486638,24.605766317960285 -29.281051569652291,24.596164227391593 -29.278622294760709,24.586612532310763 -29.276046504733856,24.577114180572615 -29.273324990718947,24.567672102945274 -29.270458588834956,24.558289212193195 -29.267448179904818,24.548968402128249 -29.264294689173013,24.539712546687348 -29.260999086009392,24.530524499021816 -29.257562383598525,24.521407090592227 -29.253985638615347,24.512363130253711 -29.250269950886775,24.503395403389867 -29.246416463039765,24.494506670979664 -29.242426360135497,24.485699668772813 -29.238300869290413,24.476977106411617 -29.234041259283813,24.468341666547062 -29.229648840152166,24.459796004019395 -29.225124962770508,24.451342745027716 -29.220471018421009,24.442984486277584 -29.215688438348721,24.434723794192617 -29.210778693304832,24.426563204089472 -29.205743293077461,24.418505219398092 -29.200583786010426,24.410552310879975 -29.195301758509814,24.402706915859742 -29.189898834538667,24.394971437455574 -29.184376675100097,24.387348243856902 -29.178736977708979,24.379839667567335 -29.172981475852069,24.372448004707099 -29.167111938437387,24.365175514288836 -29.161130169232337,24.358024417543742 -29.155038006291477,24.350996897226008 -29.14883732137352,24.34409509694385 -29.142530019348044,24.337321120532131 -29.136118037592439,24.33067703138671 -29.129603345378626,24.324164851854118 -29.122987943250237,24.317786562621645 -29.116273862390543,24.311544102121797 -29.109463163980905,24.30543936594934 -29.10255793855049,24.2994742062996 -29.095560305316994,24.293650431416442 -29.088472411518978,24.287969805061284 -29.081296431740057,24.282434045985305 -29.074034567224615,24.277044827435564 -29.06668904518618,24.271803776659787 -29.059262118107824,24.266712474439807 -29.051756063035484,24.261772454629462 -29.044173180864007,24.256985203708833 -29.036515795616396,24.252352160375441 -29.02878625371649,24.247874715121878 -29.02098692325518,24.24355420984503 -29.013120193250629,24.239391937478619 -29.00518847290239,24.235389141624353 -28.997194190840176,24.231547016208346 -28.989139794367077,24.227866705162754 -28.981027748697628,24.224349302108447 -28.972860536191234,24.220995850059293 -28.964640655580638,24.217807341153009 -28.956370621196328,24.214784716384329 -28.948052962186651,24.211928865360008 -28.939690221734097,24.209240626079428 -28.931284956268058,24.206720784716541 -28.92283973467417,24.204370075425757 -28.914357137500531,24.202189180171864 -28.905839756161143,24.200178728561479 -28.897290192136808,24.198339297705129 -28.888711056173534,24.196671412087511 -28.880104967479028,24.195175543457147 -28.871474552917306,24.19385211072877 -28.862822446201619,24.192701479915275 -28.854151287086367,24.19172396405807 -28.845463720557575,24.190919823186178 -28.836762396022849,24.190289264288399 -28.828049966500572,24.189832441300496 -28.819329087808967,24.189549455112285 -28.810602417754893,24.189440353583787 -28.801872615323049,24.189505131591886 -28.793142339865469,24.189743731066635 -28.784414250291647,24.190156041080773 -28.775691004259812,24.190741897919008 -28.766975257369026,24.191501085191938 -28.758269662353158,24.192433333936325 -28.74957686827598,24.193538322762858 -28.740899519728529,24.194815678001433 -28.732240256028561,24.196264973852333 -28.723601710422116,24.197885732583238 -28.714986509287982,24.19967742470579 -28.706397271344827,24.201639469198703 -28.697836606861372,24.203771233721888 -28.68930711687004,24.206072034858177 -28.680811392383887,24.208541138376447 -28.672352013617413,24.211177759476751 -28.663931549211355,24.213981063100391 -28.655552555461597,24.2169501642021 -28.647217575552503,24.220084128082078 -28.638929138794964,24.223381970696099 -28.630689759869227,24.226842659002589 -28.622501938072631,24.230465111308209 -28.614368156572979,24.234248197645979 -28.606290881666965,24.238190740140944 -28.598272562044642,24.242291513417509 -28.590315628059457,24.246549244988177 -28.582422491004635,24.250962615689375 -28.574595542395741,24.255530260106084 -28.566837153259698,24.260250767015116 -28.559149673430525,24.265122679844414 -28.551535430851899,24.270144497143669 -28.543996730886917,24.275314673058389 -28.536535855634881,24.280631617835351 -28.529155063255686,24.286093698316382 -28.521856587301826,24.291699238459888 -28.514642636057971,24.297446519871226 -28.507515391888845,24.303333782336477 -28.500477010594921,24.309359224380383 -28.493529620776712,24.31552100381996 -28.486675323207294,24.321817238338735 -28.479916190213615,24.328246006069861 -28.473254265066558,24.334805346194791 -28.466691561380145,24.341493259533799 -28.4602300625194,24.348307709170513 -28.453871721018132,24.355246621064914 -28.447618458005579,24.362307884696193 -28.441472162642967,24.369489353694416 -28.435434691569711,24.376788846495483 -28.429507868359337,24.384204147000045 -28.423693482985684,24.391733005249641 -28.417993291298984,24.399373138086929 -28.412409014512306,24.407122229850941 -28.406942338698542,24.414977933080777 -28.401594914297746,24.422937869201576 -28.396368355635119,24.430999629236783 -28.391264240449956,24.43916077453795 -28.38628410943538,24.447418837487788 -28.381429465788997,24.455771322249223 -28.37670177477483,24.464215705504113 -28.372102463296528,24.472749437186824 -28.367632919481679,24.481369941250147 -28.363294492277845,24.490074616410581 -28.359088491059879,24.498860836925523 -28.355016185249198,24.50772595334951 -28.351078803944461,24.516667293338532 -28.347277535564402,24.525682162385579 -28.343613527502299,24.534767844672221 -28.340087885792698,24.543921603800779 -28.336701674789964,24.553140683623202 -28.333455916859251,24.562422309051517 -28.330351592079595,24.57176368682665 -28.327389637959214,24.581162006386851 -28.324570949163544,24.590614440635008 -28.3218963772552,24.60011814677102 -28.31936673044703,24.609670267145127 -28.316982773367286,24.619267930032869 -28.314745226837644,24.628908250528362 -28.312654767663972,24.63858833131291 -28.310712028439568,24.648305263544835 -28.308917597361543,24.658056127663254 -28.30727201805972,24.667837994267057 -28.305775789438641,24.677647924917796 -28.304429365532272,24.687482973026292 -28.303233155371913,24.697340184664604 -28.302187522866816,24.707216599457116 -28.301292786698056,24.717109251382755 -28.300549220225193,24.727015169673113 -28.299957051406295,24.736931379690652 -28.299516462730722,24.746854903656409 -28.299227591165192,24.756782761632255 -28.29909052811297,24.766711972434599 -28.299105319386072,24.776639554240347 -28.299271965190698,24.786562525734769 -28.299590420125625,24.796477906700915 -28.300060593194004,24.806382719171182 -28.300682347828001,24.816273988013755 -28.301455501926711,24.826148741958701 -28.302379827907302,24.836004014361414 -28.303455052768882,24.845836844098478 -28.304680858169917,24.855644276402057 -28.306056880518398,24.865423363765725 -28.307582711075085,24.875171166708189 -28.309257896070051,24.884884754678925 -28.311081936831783,24.894561206900327 -28.313054289929653,24.904197613154185 -28.315174367329107,24.913791074742456 -28.317441536559656,24.92333870518836 -28.31985512089615,24.932837631161526 -28.322414399552244,24.93611111111111 -28.323333333333334,24.93611111111111 -28.323333333333334,24.74 -28.466111111111111,24.74 -28.466111111111111,24.740000000006798 -28.466111111112809,24.746632430249097 -28.465871637044913,24.753268187622954 -28.465733642679226,24.759905272118928 -28.465697157550323,24.766541673734942 -28.465762180560702,24.77317539772077 -28.4659286799847,24.779804440348542 -28.466196593481584,24.786426802076775 -28.466565828117496,24.793040485511163 -28.467036260396483,24.799643496136763 -28.467607736300309,24.806233842740653 -28.468280071337446,24.812809538018556 -28.46905305060092,24.819368599277652 -28.469926428834924,24.825909048903572 -28.470899930510456,24.832428914991102 -28.471973249910022,24.838926231930369 -28.473146051220724,24.845399040894488 -28.474417968636757,24.85184539057164 -28.475788606470175,24.85826333757198 -28.477257539270838,24.864650947139452 -28.478824311954796,24.871006293602161 -28.480488439941709,24.877327461036565 -28.482249409300493,24.883612543751585 -28.484106676904105,24.889859646912562 -28.486059670592425,24.896066887037229 -28.488107789344113,24.902232392611545 -28.490250403456642,24.908354304611503 -28.492486854734935,24.91443077703882 -28.494816456688355,24.920459977479492 -28.49723849473618,24.926440087661302 -28.499752226420981,24.932369303955355 -28.502356881630817,24.938245837939125 -28.505051662829032,24.944067916906295 -28.50783574529251,24.949833784410384 -28.510708277357907,24.955541700766702 -28.51366838067581,24.961189943568936 -28.516715150472848,24.966776808222054 -28.519847655821607,24.972300608432882 -28.523064939918342,24.9777596767074 -28.526366020368442,24.983152364848348 -28.529749889479419,24.988477044467242 -28.533215514561434,24.993732107439818 -28.536761838235364,24.998915966414472 -28.540387778748141,25.004027055264203 -28.544092230295462,25.009063829563729 -28.547874063351784,25.014024767071181 -28.551732125007007,25.018908368153632 -28.555665239310756,25.023713156252619 -28.559672207623251,25.028437678344208 -28.563751808972938,25.033080505346668 -28.567902800421166,25.03764023257828 -28.572123917433132,25.042115480170764 -28.576413874255621,25.046504893485697 -28.580771364301086,25.050807143534044 -28.585195060537998,25.055020927375441 -28.589683615887409,25.059144968510566 -28.594235663625824,25.063178017286948 -28.598849817793635,25.067118851257888 -28.603524673609968,25.070966275578758 -28.608258807892824,25.074719123363518 -28.61305077948515,25.078376256041661 -28.617899129686265,25.081936563715608 -28.622802382688874,25.085398965501863 -28.627759046021239,25.088762409872622 -28.632767610994421,25.092025874965881 -28.637826553154852,25.095188368924873 -28.642934332741433,25.098248930184742 -28.648089395147835,25.101206627805809 -28.653290171388974,25.104060561732403 -28.658535078572456,25.106809863101081 -28.663822520374055,25.109453694502864 -28.669150887517645,25.111991250254196 -28.674518558259152,25.114421756659766 -28.679923898874449,25.116744472249401 -28.685365264151244,25.118958688020527 -28.690840997884379,25.121063727672666 -28.696349433375019,25.123058947821914 -28.701888893932889,25.124943738219745 -28.707457693382054,25.126717521933593 -28.713054136569667,25.128379755560044 -28.718676519877718,25.129929929402699 -28.724323131737549,25.131367567623556 -28.729992253147103,25.132692228430109 -28.735682158190684,25.13390350421783 -28.741391114561011,25.135001021699754 -28.747117384083495,25.135984442057644 -28.752859223242652,25.136853461048599 -28.75861488371028,25.137607809118133 -28.764382612875551,25.138247251504847 -28.770160654376411,25.138771588331661 -28.775947248632733,25.139180654678363 -28.781740633380437,25.139474320653182 -28.787539044207037,25.139652491459525 -28.793340715087666,25.139715107429993 -28.79914387892245,25.139662144076386 -28.804946768074032,25.139493612107152 -28.810747614905807,25.139444444444443 -28.811944444444446,25.139444444444443 -28.811944444444446,25.324444444444445 -28.735))', max_error=0.0000001) != 0: print('did not get expected second geom') - print(geom.ExportToWkt()) - return 'fail' + pytest.fail(geom.ExportToWkt()) - return 'success' + -gdaltest_list = [ - ogr_sua_1] - -if __name__ == '__main__': - - gdaltest.setup_run('ogr_sua') - - gdaltest.run_tests(gdaltest_list) - - sys.exit(gdaltest.summarize()) diff --git a/autotest/ogr/ogr_svg.py b/autotest/ogr/ogr_svg.py index 5fdf3f0c1cab..a0e085136252 100755 --- a/autotest/ogr/ogr_svg.py +++ b/autotest/ogr/ogr_svg.py @@ -28,16 +28,15 @@ # DEALINGS IN THE SOFTWARE. ############################################################################### -import sys -sys.path.append('../pymod') import gdaltest import ogrtest from osgeo import ogr +import pytest -def ogr_svg_init(): +def test_ogr_svg_init(): gdaltest.svg_ds = None gdaltest.svg_ds = ogr.Open('data/test.svg') @@ -48,86 +47,62 @@ def ogr_svg_init(): gdaltest.have_svg = 1 if not gdaltest.have_svg: - return 'skip' + pytest.skip() - if gdaltest.svg_ds.GetLayerCount() != 3: - gdaltest.post_reason('wrong number of layers') - return 'fail' - - return 'success' + assert gdaltest.svg_ds.GetLayerCount() == 3, 'wrong number of layers' ############################################################################### # Test -def ogr_svg_1(): +def test_ogr_svg_1(): if not gdaltest.have_svg: - return 'skip' + pytest.skip() - if gdaltest.svg_ds is None: - return 'fail' + assert gdaltest.svg_ds is not None lyr = gdaltest.svg_ds.GetLayerByName('points') - if lyr.GetFeatureCount() != 1: - gdaltest.post_reason('wrong number of features') - return 'fail' + assert lyr.GetFeatureCount() == 1, 'wrong number of features' feat = lyr.GetNextFeature() if feat.GetFieldAsString('building') != 'yes': feat.DumpReadable() - return 'fail' + pytest.fail() if ogrtest.check_feature_geometry(feat, 'POINT (-13610535.695141600444913 4561593.930507560260594)', max_error=0.0001) != 0: feat.DumpReadable() - return 'fail' + pytest.fail() lyr = gdaltest.svg_ds.GetLayerByName('lines') - if lyr.GetFeatureCount() != 1: - gdaltest.post_reason('wrong number of features') - return 'fail' + assert lyr.GetFeatureCount() == 1, 'wrong number of features' feat = lyr.GetNextFeature() if ogrtest.check_feature_geometry(feat, 'LINESTRING (-13609855.59 4561479.26,-13609856.21 4561474.27,-13609860.03 4561468.87,-13609865.74 4561465.69,-13609869.54 4561465.06)', max_error=0.0001) != 0: feat.DumpReadable() - return 'fail' + pytest.fail() lyr = gdaltest.svg_ds.GetLayerByName('polygons') - if lyr.GetFeatureCount() != 1: - gdaltest.post_reason('wrong number of features') - return 'fail' + assert lyr.GetFeatureCount() == 1, 'wrong number of features' feat = lyr.GetNextFeature() if ogrtest.check_feature_geometry(feat, 'POLYGON ((-13610027.72 4562403.66,-13609661.58 4562462.95,-13609671.33 4562516.4,-13609676.11 4562532.65,-13609692.36 4562552.71,-13609711.46 4562609.08,-13609721.97 4562634.89,-13609727.7 4562650.16,-13609727.7 4562666.41,-13609716.23 4562699.85,-13609698.09 4562758.14,-13609697.13 4562771.51,-13609706.68 4562811.64,-13609720.06 4562843.18,-13609723.88 4562863.23,-13609725.8 4562891.91,-13609721.02 4562919.61,-13609713.37 4562938.72,-13609701.91 4562954.97,-13609688.53 4562968.34,-13609668.47 4562979.8,-13609614.96 4562993.17,-13609589.16 4563005.6,-13609552.85 4563037.14,-13609530.88 4563053.37,-13609474.5 4563076.3,-13609487.81 4563109.75,-13609491.89 4563149.38,-13609478.48 4563157.66,-13609467.67 4563171.31,-13609462.25 4563189.21,-13609420.46 4563189.32,-13609401.89 4563191.92,-13609395.2 4563201.47,-13609287.23 4563264.53,-13609303.48 4563291.29,-13609330.23 4563313.26,-13609339.78 4563326.63,-13609342.66 4563340.96,-13609344.56 4563458.48,-13609341.7 4563482.38,-13609322.59 4563518.68,-13609304.43 4563574.1,-13609290.1 4563592.26,-13609289.15 4563615.19,-13609290.1 4563655.32,-13609287.23 4563675.38,-13609271.95 4563703.09,-13609263.35 4563739.4,-13609258.57 4563762.32,-13609250.73 4563760.48,-13609226.84 4563718.43,-13609214.42 4563688.81,-13609204.87 4563661.1,-13609191.49 4563641.03,-13609170.47 4563629.56,-13609137.03 4563632.44,-13609109.32 4563648.68,-13609097.85 4563676.39,-13609100.72 4563712.7,-13609102.63 4563800.59,-13609116.0 4563819.7,-13609156.13 4563850.28,-13609151.55 4563861.7,-13609044.54 4563885.58,-13609057.92 4563945.78,-13609058.88 4563959.15,-13609031.17 4563987.81,-13609014.93 4563969.66,-13608988.17 4563981.13,-13608918.43 4563946.74,-13608834.46 4563870.62,-13608756.43 4563811.52,-13608716.02 4563488.23,-13608439.74 4563228.22,-13608483.69 4563167.08,-13608471.27 4563156.56,-13608461.72 4563132.68,-13608457.89 4563102.1,-13608460.76 4563077.26,-13608464.58 4563054.33,-13608444.52 4563044.78,-13608428.02 4562925.57,-13608408.91 4562672.38,-13608471.97 4562671.42,-13608514.96 4562653.27,-13608586.63 4562653.27,-13608728.76 4562628.85,-13609304.17 4562530.01,-13609354.81 4562401.98,-13609349.2 4562281.92,-13609401.52 4562278.13,-13609426.46 4562253.26,-13609385.39 4562165.98,-13609374.88 4561992.09,-13609361.7 4561946.97,-13609413.36 4561935.48,-13609402.85 4561884.85,-13609429.6 4561890.57,-13609487.88 4561880.07,-13609495.53 4561931.65,-13609442.02 4561942.18,-13609454.44 4562017.65,-13609601.59 4561997.59,-13609881.1 4561949.97,-13609858.97 4561817.17,-13609878.07 4561814.31,-13609891.08 4561883.51,-13609912.1 4561880.63,-13609918.79 4561924.59,-13609922.03 4561942.33,-13609949.37 4561938.35,-13609971.5 4562072.19,-13610108.74 4562049.23,-13610117.33 4562098.92,-13610151.73 4562094.14,-13610154.59 4562109.42,-13610224.34 4562097.96,-13610222.43 4562079.81,-13610381.03 4562053.05,-13610401.1 4562051.15,-13610386.77 4561907.82,-13610286.45 4561921.2,-13610210.01 4561869.6,-13610188.04 4561873.42,-13610173.7 4561778.84,-13610177.52 4561770.24,-13610184.21 4561764.51,-13610403.97 4561729.15,-13610429.77 4561711.0,-13610442.18 4561704.31,-13610574.04 4561683.29,-13610579.77 4561748.26,-13610620.86 4561745.4,-13610652.39 4562062.61,-13610802.4 4562037.77,-13610765.13 4561654.62,-13610860.68 4561641.25,-13610892.21 4562001.46,-13610848.26 4562007.19,-13610850.37 4562027.78,-13610870.24 4562264.22,-13610821.87 4562270.93,-13610819.96 4562245.14,-13610749.26 4562250.86,-13610754.03 4562306.29,-13610861.04 4562285.26,-13610864.69 4562319.19,-13610873.3 4562318.24,-13610882.85 4562463.47,-13610835.12 4562470.5,-13610816.0 4562473.37,-13610816.96 4562481.96,-13610737.66 4562493.43,-13610746.26 4562564.13,-13610782.56 4562558.4,-13610784.48 4562580.38,-13610826.52 4562575.6,-13610828.43 4562590.89,-13610845.63 4562588.98,-13610891.49 4562583.24,-13610895.3 4562621.46,-13610829.38 4562629.11,-13610844.67 4562786.76,-13610613.45 4562823.06,-13610570.46 4562334.82,-13610699.56 4562312.97,-13610695.75 4562293.86,-13610689.66 4562256.58,-13610543.47 4562263.26,-13610548.25 4562316.77,-13610487.1 4562326.32,-13610483.27 4562297.66,-13610443.14 4562303.38,-13610446.97 4562333.96,-13610027.72 4562403.66))', max_error=0.0001) != 0: feat.DumpReadable() - return 'fail' - - return 'success' + pytest.fail() + ############################################################################### # -def ogr_svg_cleanup(): +def test_ogr_svg_cleanup(): gdaltest.svg_ds = None - return 'success' - - -gdaltest_list = [ - ogr_svg_init, - ogr_svg_1, - ogr_svg_cleanup] - -if __name__ == '__main__': - gdaltest.setup_run('ogr_svg') - gdaltest.run_tests(gdaltest_list) - sys.exit(gdaltest.summarize()) diff --git a/autotest/ogr/ogr_sxf.py b/autotest/ogr/ogr_sxf.py index 121ed6beb3e8..d104d4a9cf48 100755 --- a/autotest/ogr/ogr_sxf.py +++ b/autotest/ogr/ogr_sxf.py @@ -26,18 +26,17 @@ # Boston, MA 02111-1307, USA. ############################################################################### -import sys -sys.path.append('../pymod') import gdaltest from osgeo import ogr +import pytest ############################################################################### # Open SXF datasource. -def ogr_sxf_1(): +def test_ogr_sxf_1(): gdaltest.sxf_ds = None with gdaltest.error_handler(): @@ -45,50 +44,33 @@ def ogr_sxf_1(): gdaltest.sxf_ds = ogr.Open('data/100_test.sxf') if gdaltest.sxf_ds is not None: - return 'success' - return 'fail' + return + pytest.fail() ############################################################################### # Run test_ogrsf -def ogr_sxf_2(): +def test_ogr_sxf_2(): import test_cli_utilities if test_cli_utilities.get_test_ogrsf_path() is None: - return 'skip' + pytest.skip() ret = gdaltest.runexternal(test_cli_utilities.get_test_ogrsf_path() + ' data/100_test.sxf') - if ret.find('INFO') == -1 or ret.find('ERROR') != -1: - print(ret) - return 'fail' - - return 'success' + assert ret.find('INFO') != -1 and ret.find('ERROR') == -1 ############################################################################### # -def ogr_sxf_cleanup(): +def test_ogr_sxf_cleanup(): if gdaltest.sxf_ds is None: - return 'skip' + pytest.skip() gdaltest.sxf_ds = None - return 'success' - - -gdaltest_list = [ - ogr_sxf_1, - ogr_sxf_2, - ogr_sxf_cleanup] - -if __name__ == '__main__': - - gdaltest.setup_run('ogr_sxf') - gdaltest.run_tests(gdaltest_list) - sys.exit(gdaltest.summarize()) diff --git a/autotest/ogr/ogr_tiger.py b/autotest/ogr/ogr_tiger.py index 8280944e63bc..474fd9b7f60f 100755 --- a/autotest/ogr/ogr_tiger.py +++ b/autotest/ogr/ogr_tiger.py @@ -29,25 +29,24 @@ ############################################################################### import os -import sys import shutil from osgeo import gdal from osgeo import ogr -sys.path.append('../pymod') import gdaltest import ogrtest +import pytest ############################################################################### -def ogr_tiger_1(): +def test_ogr_tiger_1(): ogrtest.tiger_ds = None if not gdaltest.download_file('http://www2.census.gov/geo/tiger/tiger2006se/AL/TGR01001.ZIP', 'TGR01001.ZIP'): - return 'skip' + pytest.skip() try: os.stat('tmp/cache/TGR01001/TGR01001.MET') @@ -61,79 +60,64 @@ def ogr_tiger_1(): try: os.stat('tmp/cache/TGR01001/TGR01001.MET') except OSError: - return 'skip' + pytest.skip() except: - return 'skip' + pytest.skip() ogrtest.tiger_ds = ogr.Open('tmp/cache/TGR01001') - if ogrtest.tiger_ds is None: - gdaltest.post_reason('fail') - return 'fail' + assert ogrtest.tiger_ds is not None ogrtest.tiger_ds = None # also test opening with a filename (#4443) ogrtest.tiger_ds = ogr.Open('tmp/cache/TGR01001/TGR01001.RT1') - if ogrtest.tiger_ds is None: - gdaltest.post_reason('fail') - return 'fail' + assert ogrtest.tiger_ds is not None # Check a few features. cc_layer = ogrtest.tiger_ds.GetLayerByName('CompleteChain') - if cc_layer.GetFeatureCount() != 19289: - gdaltest.post_reason('wrong cc feature count') - return 'fail' + assert cc_layer.GetFeatureCount() == 19289, 'wrong cc feature count' feat = cc_layer.GetNextFeature() feat = cc_layer.GetNextFeature() feat = cc_layer.GetNextFeature() - if feat.TLID != 2833200 or feat.FRIADDL is not None or feat.BLOCKL != 5000: - gdaltest.post_reason('wrong attribute on cc feature.') - return 'fail' + assert feat.TLID == 2833200 and feat.FRIADDL is None and feat.BLOCKL == 5000, \ + 'wrong attribute on cc feature.' - if ogrtest.check_feature_geometry(feat, 'LINESTRING (-86.4402 32.504137,-86.440313 32.504009,-86.440434 32.503884,-86.440491 32.503805,-86.44053 32.503757,-86.440578 32.503641,-86.440593 32.503515,-86.440588 32.503252,-86.440596 32.50298)', max_error=0.000001) != 0: - return 'fail' + assert ogrtest.check_feature_geometry(feat, 'LINESTRING (-86.4402 32.504137,-86.440313 32.504009,-86.440434 32.503884,-86.440491 32.503805,-86.44053 32.503757,-86.440578 32.503641,-86.440593 32.503515,-86.440588 32.503252,-86.440596 32.50298)', max_error=0.000001) == 0 feat = ogrtest.tiger_ds.GetLayerByName('TLIDRange').GetNextFeature() - if feat.MODULE != 'TGR01001' or feat.TLMINID != 2822718: - gdaltest.post_reason('got wrong TLIDRange attributes') - return 'fail' - - return 'success' + assert feat.MODULE == 'TGR01001' and feat.TLMINID == 2822718, \ + 'got wrong TLIDRange attributes' ############################################################################### # Run test_ogrsf -def ogr_tiger_2(): +def test_ogr_tiger_2(): if ogrtest.tiger_ds is None: - return 'skip' + pytest.skip() import test_cli_utilities if test_cli_utilities.get_test_ogrsf_path() is None: - return 'skip' + pytest.skip() ret = gdaltest.runexternal(test_cli_utilities.get_test_ogrsf_path() + ' -ro tmp/cache/TGR01001') - if ret.find('INFO') == -1 or ret.find('ERROR') != -1: - print(ret) - return 'fail' - - return 'success' + assert ret.find('INFO') != -1 and ret.find('ERROR') == -1 ############################################################################### # Test TIGER writing -def ogr_tiger_3(): +def test_ogr_tiger_3(): if ogrtest.tiger_ds is None: - return 'skip' + pytest.skip() import test_cli_utilities if test_cli_utilities.get_ogr2ogr_path() is None: - return 'skip' + pytest.skip() try: shutil.rmtree('tmp/outtiger') @@ -176,10 +160,10 @@ def ogr_tiger_3(): # Load into a /vsimem instance to test virtualization. -def ogr_tiger_4(): +def test_ogr_tiger_4(): if ogrtest.tiger_ds is None: - return 'skip' + pytest.skip() # load all the files into memory. for filename in gdal.ReadDir('tmp/cache/TGR01001'): @@ -195,38 +179,29 @@ def ogr_tiger_4(): # Try reading. ogrtest.tiger_ds = ogr.Open('/vsimem/tigertest/TGR01001.RT1') - if ogrtest.tiger_ds is None: - gdaltest.post_reason('fail to open.') - return 'fail' + assert ogrtest.tiger_ds is not None, 'fail to open.' ogrtest.tiger_ds = None # also test opening with a filename (#4443) ogrtest.tiger_ds = ogr.Open('tmp/cache/TGR01001/TGR01001.RT1') - if ogrtest.tiger_ds is None: - gdaltest.post_reason('fail') - return 'fail' + assert ogrtest.tiger_ds is not None # Check a few features. cc_layer = ogrtest.tiger_ds.GetLayerByName('CompleteChain') - if cc_layer.GetFeatureCount() != 19289: - gdaltest.post_reason('wrong cc feature count') - return 'fail' + assert cc_layer.GetFeatureCount() == 19289, 'wrong cc feature count' feat = cc_layer.GetNextFeature() feat = cc_layer.GetNextFeature() feat = cc_layer.GetNextFeature() - if feat.TLID != 2833200 or feat.FRIADDL is not None or feat.BLOCKL != 5000: - gdaltest.post_reason('wrong attribute on cc feature.') - return 'fail' + assert feat.TLID == 2833200 and feat.FRIADDL is None and feat.BLOCKL == 5000, \ + 'wrong attribute on cc feature.' - if ogrtest.check_feature_geometry(feat, 'LINESTRING (-86.4402 32.504137,-86.440313 32.504009,-86.440434 32.503884,-86.440491 32.503805,-86.44053 32.503757,-86.440578 32.503641,-86.440593 32.503515,-86.440588 32.503252,-86.440596 32.50298)', max_error=0.000001) != 0: - return 'fail' + assert ogrtest.check_feature_geometry(feat, 'LINESTRING (-86.4402 32.504137,-86.440313 32.504009,-86.440434 32.503884,-86.440491 32.503805,-86.44053 32.503757,-86.440578 32.503641,-86.440593 32.503515,-86.440588 32.503252,-86.440596 32.50298)', max_error=0.000001) == 0 feat = ogrtest.tiger_ds.GetLayerByName('TLIDRange').GetNextFeature() - if feat.MODULE != 'TGR01001' or feat.TLMINID != 2822718: - gdaltest.post_reason('got wrong TLIDRange attributes') - return 'fail' + assert feat.MODULE == 'TGR01001' and feat.TLMINID == 2822718, \ + 'got wrong TLIDRange attributes' # Try to recover memory from /vsimem. for filename in gdal.ReadDir('tmp/cache/TGR01001'): @@ -236,31 +211,16 @@ def ogr_tiger_4(): gdal.Unlink('/vsimem/tigertest/' + filename) - return 'success' - + ############################################################################### -def ogr_tiger_cleanup(): +def test_ogr_tiger_cleanup(): if ogrtest.tiger_ds is None: - return 'skip' + pytest.skip() ogrtest.tiger_ds = None - return 'success' - - -gdaltest_list = [ - ogr_tiger_1, - ogr_tiger_2, - ogr_tiger_3, - ogr_tiger_4, - ogr_tiger_cleanup] - -if __name__ == '__main__': - gdaltest.setup_run('ogr_tiger') - gdaltest.run_tests(gdaltest_list) - sys.exit(gdaltest.summarize()) diff --git a/autotest/ogr/ogr_vdv.py b/autotest/ogr/ogr_vdv.py index 4818e2ff3fe9..dc435b2a1349 100755 --- a/autotest/ogr/ogr_vdv.py +++ b/autotest/ogr/ogr_vdv.py @@ -32,120 +32,106 @@ import shutil import sys -sys.path.append('../pymod') import gdaltest import ogrtest from osgeo import gdal from osgeo import ogr +import pytest ############################################################################### # Basic test of .idf file -def ogr_idf_1(): +def test_ogr_idf_1(): ds = ogr.Open('data/test.idf') lyr = ds.GetLayer(0) f = lyr.GetNextFeature() if f['NODE_ID'] != 1 or f['foo'] != 'U' or f.GetGeometryRef().ExportToWkt() != 'POINT (2 49)': - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' + pytest.fail() lyr = ds.GetLayer(1) f = lyr.GetNextFeature() if f.GetGeometryRef().ExportToWkt() != 'LINESTRING (2 49,2.5 49.5,2.7 49.7,3 50)': - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' + pytest.fail() lyr = ds.GetLayer(2) f = lyr.GetNextFeature() if f.GetGeometryRef().ExportToWkt() != 'POINT (2.5 49.5)': - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' + pytest.fail() lyr = ds.GetLayer(3) f = lyr.GetNextFeature() if f['FOO'] != 1: - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' - - return 'success' + pytest.fail() + ############################################################################### # -def ogr_idf_1_with_temp_sqlite_db(): +def test_ogr_idf_1_with_temp_sqlite_db(): if ogr.GetDriverByName('SQLite') is None: - return 'skip' + pytest.skip() with gdaltest.config_option('OGR_IDF_TEMP_DB_THRESHOLD', '0'): - return ogr_idf_1() + return test_ogr_idf_1() ############################################################################### # Basic test of .idf file -def ogr_idf_3d(): +def test_ogr_idf_3d(): ds = ogr.Open('data/test_3d.idf') lyr = ds.GetLayer(0) f = lyr.GetNextFeature() if f['NODE_ID'] != 1 or f['foo'] != 'U' or f.GetGeometryRef().ExportToWkt() != 'POINT (2 49 10)': - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' + pytest.fail() lyr = ds.GetLayer(1) f = lyr.GetNextFeature() if f.GetGeometryRef().ExportToWkt() != 'LINESTRING (2 49 10,2.5 49.5 10,2.7 49.7 20,3 50 20)': - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' + pytest.fail() lyr = ds.GetLayer(2) f = lyr.GetNextFeature() if f.GetGeometryRef().ExportToWkt() != 'POINT (2.5 49.5 10)': - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' + pytest.fail() lyr = ds.GetLayer(3) f = lyr.GetNextFeature() if f['FOO'] != 1: - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' - - return 'success' + pytest.fail() + ############################################################################### # Run test_ogrsf on .idf -def ogr_idf_2(): +def test_ogr_idf_2(): import test_cli_utilities if test_cli_utilities.get_test_ogrsf_path() is None: - return 'skip' + pytest.skip() ret = gdaltest.runexternal(test_cli_utilities.get_test_ogrsf_path() + ' -ro data/test.idf') - if ret.find('INFO') == -1 or ret.find('ERROR') != -1: - print(ret) - return 'fail' - - return 'success' + assert ret.find('INFO') != -1 and ret.find('ERROR') == -1 ############################################################################### # Create a VDV file -def ogr_vdv_1(filename='tmp/test.x10', dsco=None, lco=None): +def test_ogr_vdv_1(filename='tmp/test.x10', dsco=None, lco=None): dsco = [] if dsco is None else dsco lco = [] if lco is None else lco @@ -195,13 +181,11 @@ def ogr_vdv_1(filename='tmp/test.x10', dsco=None, lco=None): ds.CreateLayer('empty2', options=lco) ds = None - return 'success' - ############################################################################### # Read it -def ogr_vdv_2(src_filename='tmp/test.x10'): +def test_ogr_vdv_2(src_filename='tmp/test.x10'): out_filename = '/vsimem/vdv/ogr_vdv_2.x10' gdal.Unlink(out_filename) @@ -260,70 +244,57 @@ def ogr_vdv_2(src_filename='tmp/test.x10'): got = gdal.VSIFReadL(1, 10000, f).decode('latin1') gdal.VSIFCloseL(f) - if got != expected: - gdaltest.post_reason('fail') - print(got) - return 'fail' + assert got == expected gdal.Unlink(out_filename) - return 'success' - ############################################################################### # Run test_ogrsf on it -def ogr_vdv_3(): +def test_ogr_vdv_3(): import test_cli_utilities if test_cli_utilities.get_test_ogrsf_path() is None: - return 'skip' + pytest.skip() ret = gdaltest.runexternal(test_cli_utilities.get_test_ogrsf_path() + ' -ro tmp/test.x10') - if ret.find('INFO') == -1 or ret.find('ERROR') != -1: - print(ret) - return 'fail' - - return 'success' + assert ret.find('INFO') != -1 and ret.find('ERROR') == -1 ############################################################################### # Create a VDV directory -def ogr_vdv_4(): - return ogr_vdv_1(filename='tmp/test_x10', dsco=['SINGLE_FILE=NO'], lco=['EXTENSION=txt']) +def test_ogr_vdv_4(): + return test_ogr_vdv_1(filename='tmp/test_x10', dsco=['SINGLE_FILE=NO'], lco=['EXTENSION=txt']) ############################################################################### # Read it -def ogr_vdv_5(): - return ogr_vdv_2(src_filename='tmp/test_x10') +def test_ogr_vdv_5(): + return test_ogr_vdv_2(src_filename='tmp/test_x10') ############################################################################### # Run test_ogrsf on it -def ogr_vdv_6(): +def test_ogr_vdv_6(): import test_cli_utilities if test_cli_utilities.get_test_ogrsf_path() is None: - return 'skip' + pytest.skip() ret = gdaltest.runexternal(test_cli_utilities.get_test_ogrsf_path() + ' -ro tmp/test_x10') - if ret.find('INFO') == -1 or ret.find('ERROR') != -1: - print(ret) - return 'fail' - - return 'success' + assert ret.find('INFO') != -1 and ret.find('ERROR') == -1 ############################################################################### # Run VDV452 -def ogr_vdv_7(): +def test_ogr_vdv_7(): tests = [('VDV-452', 'STOP', 'POINT_LONGITUDE', 'POINT_LATITUDE'), ('VDV-452-ENGLISH', 'STOP', 'POINT_LONGITUDE', 'POINT_LATITUDE'), @@ -349,9 +320,8 @@ def ogr_vdv_7(): if f[longname] != -1234556789 or \ f[latname] != -234556789 or \ ogrtest.check_feature_geometry(f, 'POINT (-123.765774722222 -23.7657747222222)') != 0: - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' + pytest.fail() ds = None gdal.Unlink('/vsimem/vdv/ogr_vdv_7.x10') @@ -365,15 +335,11 @@ def ogr_vdv_7(): gdal.PushErrorHandler() lyr = ds.CreateLayer('UNKNOWN', options=['PROFILE=' + profile, 'PROFILE_STRICT=' + str(strict)]) gdal.PopErrorHandler() - if gdal.GetLastErrorMsg() == '': - gdaltest.post_reason('fail') - return 'fail' + assert gdal.GetLastErrorMsg() != '' if strict and lyr is not None: - gdaltest.post_reason('fail') - return 'fail' + pytest.fail() elif not strict and lyr is None: - gdaltest.post_reason('fail') - return 'fail' + pytest.fail() if profile == 'VDV-452-GERMAN': lyr_name = 'REC_ORT' @@ -384,41 +350,32 @@ def ogr_vdv_7(): gdal.PushErrorHandler() ret = lyr.CreateField(ogr.FieldDefn('UNKNOWN')) gdal.PopErrorHandler() - if gdal.GetLastErrorMsg() == '': - gdaltest.post_reason('fail') - return 'fail' + assert gdal.GetLastErrorMsg() != '' if strict and ret == 0: - gdaltest.post_reason('fail') - return 'fail' + pytest.fail() elif not strict and ret != 0: - gdaltest.post_reason('fail') - return 'fail' + pytest.fail() ds = None gdal.Unlink('/vsimem/vdv/ogr_vdv_7.x10') - return 'success' - + ############################################################################### # Test a few error cases -def ogr_vdv_8(): +def test_ogr_vdv_8(): gdal.PushErrorHandler() ds = ogr.GetDriverByName('VDV').CreateDataSource('/does/not_exist') gdal.PopErrorHandler() - if ds is not None: - gdaltest.post_reason('fail') - return 'fail' + assert ds is None gdal.PushErrorHandler() ds = ogr.GetDriverByName('VDV').CreateDataSource('/does/not_exist', options=['SINGLE_FILE=FALSE']) gdal.PopErrorHandler() - if ds is not None: - gdaltest.post_reason('fail') - return 'fail' + assert ds is None # Add layer in non writable directory if sys.platform.startswith('linux'): @@ -441,9 +398,7 @@ def ogr_vdv_8(): os.chmod('tmp/ogr_vdv_8', 493) ds = None shutil.rmtree('tmp/ogr_vdv_8') - if lyr is not None: - gdaltest.post_reason('fail') - return 'fail' + assert lyr is None out_filename = '/vsimem/vdv/ogr_vdv_8.x10' ds = ogr.GetDriverByName('VDV').CreateDataSource(out_filename) @@ -452,21 +407,13 @@ def ogr_vdv_8(): gdal.PushErrorHandler() ds2 = ogr.GetDriverByName('VDV').CreateDataSource(out_filename) gdal.PopErrorHandler() - if ds2 is not None: - gdaltest.post_reason('fail') - return 'fail' + assert ds2 is None - if ds.TestCapability(ogr.ODsCCreateLayer) != 1: - gdaltest.post_reason('fail') - return 'fail' + assert ds.TestCapability(ogr.ODsCCreateLayer) == 1 lyr1 = ds.CreateLayer("lyr1") - if lyr1.TestCapability(ogr.OLCSequentialWrite) != 1: - gdaltest.post_reason('fail') - return 'fail' - if lyr1.TestCapability(ogr.OLCCreateField) != 1: - gdaltest.post_reason('fail') - return 'fail' + assert lyr1.TestCapability(ogr.OLCSequentialWrite) == 1 + assert lyr1.TestCapability(ogr.OLCCreateField) == 1 lyr1.ResetReading() @@ -477,36 +424,26 @@ def ogr_vdv_8(): lyr1.CreateFeature(ogr.Feature(lyr1.GetLayerDefn())) # Layer structure is now frozen - if lyr1.TestCapability(ogr.OLCCreateField) != 0: - gdaltest.post_reason('fail') - return 'fail' + assert lyr1.TestCapability(ogr.OLCCreateField) == 0 gdal.PushErrorHandler() ret = lyr1.CreateField(ogr.FieldDefn('not_allowed')) gdal.PopErrorHandler() - if ret == 0: - gdaltest.post_reason('fail') - return 'fail' + assert ret != 0 lyr2 = ds.CreateLayer("lyr2") lyr2.CreateFeature(ogr.Feature(lyr2.GetLayerDefn())) # Test interleaved writing - if lyr1.TestCapability(ogr.OLCSequentialWrite) != 0: - gdaltest.post_reason('fail') - return 'fail' + assert lyr1.TestCapability(ogr.OLCSequentialWrite) == 0 gdal.PushErrorHandler() ret = lyr1.CreateFeature(ogr.Feature(lyr1.GetLayerDefn())) gdal.PopErrorHandler() - if ret == 0: - gdaltest.post_reason('fail') - return 'fail' + assert ret != 0 - if lyr1.GetFeatureCount() != 1: - gdaltest.post_reason('fail') - return 'fail' + assert lyr1.GetFeatureCount() == 1 ds = None @@ -537,25 +474,18 @@ def ogr_vdv_8(): got = gdal.VSIFReadL(1, 10000, f).decode('latin1') gdal.VSIFCloseL(f) - if got != expected: - gdaltest.post_reason('fail') - print(got) - return 'fail' + assert got == expected # Test we are robust against missing end; ds = ogr.Open(out_filename) for i in range(2): lyr = ds.GetLayer(i) - if lyr.GetFeatureCount() != 1: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.GetFeatureCount() == 1 lyr.ResetReading() fc = 0 for f in lyr: fc += 1 - if fc != 1: - gdaltest.post_reason('fail') - return 'fail' + assert fc == 1 lyr = None ds = None @@ -574,20 +504,15 @@ def ogr_vdv_8(): got = gdal.VSIFReadL(1, 10000, f).decode('latin1') gdal.VSIFCloseL(f) - if got != expected: - gdaltest.post_reason('fail') - print(got) - return 'fail' + assert got == expected gdal.Unlink(out_filename) - return 'success' - ############################################################################### # Cleanup -def ogr_vdv_cleanup(): +def test_ogr_vdv_cleanup(): gdal.Unlink('tmp/test.x10') gdal.Unlink('/vsimem/vdv/ogr_vdv_2.x10') @@ -599,29 +524,6 @@ def ogr_vdv_cleanup(): gdal.Unlink('tmp/test_x10/' + f) gdal.Rmdir('tmp/test_x10') - return 'success' - - -gdaltest_list = [ - ogr_idf_1, - ogr_idf_1_with_temp_sqlite_db, - ogr_idf_3d, - ogr_idf_2, - ogr_vdv_1, - ogr_vdv_2, - ogr_vdv_3, - ogr_vdv_4, - ogr_vdv_5, - ogr_vdv_6, - ogr_vdv_7, - ogr_vdv_8, - ogr_vdv_cleanup] - - -if __name__ == '__main__': - gdaltest.setup_run('ogr_vdv') - gdaltest.run_tests(gdaltest_list) - sys.exit(gdaltest.summarize()) diff --git a/autotest/ogr/ogr_vfk.py b/autotest/ogr/ogr_vfk.py index efbca365f2b9..3ab6a8dcdc34 100755 --- a/autotest/ogr/ogr_vfk.py +++ b/autotest/ogr/ogr_vfk.py @@ -31,24 +31,23 @@ ############################################################################### import os -import sys -sys.path.append('../pymod') import gdaltest from osgeo import gdal from osgeo import ogr +import pytest ############################################################################### # Open file, check number of layers, get first layer, # check number of fields and features -def ogr_vfk_1(): +def test_ogr_vfk_1(): gdaltest.vfk_drv = ogr.GetDriverByName('VFK') if gdaltest.vfk_drv is None: - return 'skip' + pytest.skip() try: os.remove('data/bylany.vfk.db') @@ -57,81 +56,63 @@ def ogr_vfk_1(): gdaltest.vfk_ds = ogr.Open('data/bylany.vfk') - if gdaltest.vfk_ds is None: - return 'fail' + assert gdaltest.vfk_ds is not None - if gdaltest.vfk_ds.GetLayerCount() != 61: - gdaltest.post_reason('expected exactly 61 layers!') - return 'fail' + assert gdaltest.vfk_ds.GetLayerCount() == 61, 'expected exactly 61 layers!' gdaltest.vfk_layer_par = gdaltest.vfk_ds.GetLayer(0) - if gdaltest.vfk_layer_par is None: - gdaltest.post_reason('cannot get first layer') - return 'fail' + assert gdaltest.vfk_layer_par is not None, 'cannot get first layer' - if gdaltest.vfk_layer_par.GetName() != 'PAR': - gdaltest.post_reason('did not get expected layer name "PAR"') - return 'fail' + assert gdaltest.vfk_layer_par.GetName() == 'PAR', \ + 'did not get expected layer name "PAR"' defn = gdaltest.vfk_layer_par.GetLayerDefn() - if defn.GetFieldCount() != 28: - gdaltest.post_reason('did not get expected number of fields, got %d' % defn.GetFieldCount()) - return 'fail' + assert defn.GetFieldCount() == 28, \ + ('did not get expected number of fields, got %d' % defn.GetFieldCount()) fc = gdaltest.vfk_layer_par.GetFeatureCount() - if fc != 1: - gdaltest.post_reason('did not get expected feature count, got %d' % fc) - return 'fail' - - return 'success' + assert fc == 1, ('did not get expected feature count, got %d' % fc) ############################################################################### # Read the first feature from layer 'PAR', check envelope -def ogr_vfk_2(): +def test_ogr_vfk_2(): if gdaltest.vfk_drv is None: - return 'skip' + pytest.skip() gdaltest.vfk_layer_par.ResetReading() feat = gdaltest.vfk_layer_par.GetNextFeature() - if feat.GetFID() != 1: - gdaltest.post_reason('did not get expected fid for feature 1') - return 'fail' + assert feat.GetFID() == 1, 'did not get expected fid for feature 1' geom = feat.GetGeometryRef() - if geom.GetGeometryType() != ogr.wkbPolygon: - gdaltest.post_reason('did not get expected geometry type.') - return 'fail' + assert geom.GetGeometryType() == ogr.wkbPolygon, \ + 'did not get expected geometry type.' envelope = geom.GetEnvelope() area = (envelope[1] - envelope[0]) * (envelope[3] - envelope[2]) exp_area = 2010.5 - if area < exp_area - 0.5 or area > exp_area + 0.5: - gdaltest.post_reason('envelope area not as expected, got %g.' % area) - return 'fail' - - return 'success' + assert area >= exp_area - 0.5 and area <= exp_area + 0.5, \ + ('envelope area not as expected, got %g.' % area) ############################################################################### # Read features from layer 'SOBR', test attribute query -def ogr_vfk_3(): +def test_ogr_vfk_3(): if gdaltest.vfk_drv is None: - return 'skip' + pytest.skip() gdaltest.vfk_layer_sobr = gdaltest.vfk_ds.GetLayer(43) - if gdaltest.vfk_layer_sobr.GetName() != 'SOBR': - gdaltest.post_reason('did not get expected layer name "SOBR"') - return 'fail' + assert gdaltest.vfk_layer_sobr.GetName() == 'SOBR', \ + 'did not get expected layer name "SOBR"' gdaltest.vfk_layer_sobr.SetAttributeFilter("CISLO_BODU = '55'") @@ -143,110 +124,84 @@ def ogr_vfk_3(): feat = gdaltest.vfk_layer_sobr.GetNextFeature() count += 1 - if count != 1: - gdaltest.post_reason('did not get expected number of features, got %d' % count) - return 'fail' - - return 'success' + assert count == 1, ('did not get expected number of features, got %d' % count) ############################################################################### # Read features from layer 'SBP', test random access, check length -def ogr_vfk_4(): +def test_ogr_vfk_4(): if gdaltest.vfk_drv is None: - return 'skip' + pytest.skip() gdaltest.vfk_layer_sbp = gdaltest.vfk_ds.GetLayerByName('SBP') - if not gdaltest.vfk_layer_sbp: - gdaltest.post_reason('did not get expected layer name "SBP"') - return 'fail' + assert gdaltest.vfk_layer_sbp, 'did not get expected layer name "SBP"' feat = gdaltest.vfk_layer_sbp.GetFeature(5) length = int(feat.geometry().Length()) - if length != 10: - gdaltest.post_reason('did not get expected length, got %d' % length) - return 'fail' - - return 'success' + assert length == 10, ('did not get expected length, got %d' % length) ############################################################################### # Read features from layer 'HP', check geometry type -def ogr_vfk_5(): +def test_ogr_vfk_5(): if gdaltest.vfk_drv is None: - return 'skip' + pytest.skip() gdaltest.vfk_layer_hp = gdaltest.vfk_ds.GetLayerByName('HP') - if not gdaltest.vfk_layer_hp != 'HP': - gdaltest.post_reason('did not get expected layer name "HP"') - return 'fail' + assert gdaltest.vfk_layer_hp != 'HP', 'did not get expected layer name "HP"' geom_type = gdaltest.vfk_layer_hp.GetGeomType() - if geom_type != ogr.wkbLineString: - gdaltest.post_reason('did not get expected geometry type, got %d' % geom_type) - return 'fail' - - return 'success' + assert geom_type == ogr.wkbLineString, \ + ('did not get expected geometry type, got %d' % geom_type) ############################################################################### # Re-Open file (test .db persistence) -def ogr_vfk_6(): +def test_ogr_vfk_6(): if gdaltest.vfk_drv is None: - return 'skip' + pytest.skip() gdaltest.vfk_layer_par = None gdaltest.vfk_layer_sobr = None gdaltest.vfk_ds = None gdaltest.vfk_ds = ogr.Open('data/bylany.vfk') - if gdaltest.vfk_ds is None: - return 'fail' + assert gdaltest.vfk_ds is not None - if gdaltest.vfk_ds.GetLayerCount() != 61: - gdaltest.post_reason('expected exactly 61 layers!') - return 'fail' + assert gdaltest.vfk_ds.GetLayerCount() == 61, 'expected exactly 61 layers!' gdaltest.vfk_layer_par = gdaltest.vfk_ds.GetLayer(0) - if gdaltest.vfk_layer_par is None: - gdaltest.post_reason('cannot get first layer') - return 'fail' + assert gdaltest.vfk_layer_par is not None, 'cannot get first layer' - if gdaltest.vfk_layer_par.GetName() != 'PAR': - gdaltest.post_reason('did not get expected layer name "PAR"') - return 'fail' + assert gdaltest.vfk_layer_par.GetName() == 'PAR', \ + 'did not get expected layer name "PAR"' defn = gdaltest.vfk_layer_par.GetLayerDefn() - if defn.GetFieldCount() != 28: - gdaltest.post_reason('did not get expected number of fields, got %d' % defn.GetFieldCount()) - return 'fail' + assert defn.GetFieldCount() == 28, \ + ('did not get expected number of fields, got %d' % defn.GetFieldCount()) fc = gdaltest.vfk_layer_par.GetFeatureCount() - if fc != 1: - gdaltest.post_reason('did not get expected feature count, got %d' % fc) - return 'fail' - - return 'success' + assert fc == 1, ('did not get expected feature count, got %d' % fc) ############################################################################### # Read PAR layer, check data types (Integer64 new in GDAL 2.2) -def ogr_vfk_7(): +def test_ogr_vfk_7(): if gdaltest.vfk_drv is None: - return 'skip' + pytest.skip() defn = gdaltest.vfk_layer_par.GetLayerDefn() @@ -255,20 +210,18 @@ def ogr_vfk_7(): (2, "DATUM_VZNIKU", ogr.OFTString), (22, "CENA_NEMOVITOSTI", ogr.OFTReal)): col = defn.GetFieldDefn(idx) - if col.GetName() != name or col.GetType() != ctype: - gdaltest.post_reason("PAR: '{}' column name/type mismatch".format(name)) - return 'fail' - - return 'success' + assert col.GetName() == name and col.GetType() == ctype, \ + "PAR: '{}' column name/type mismatch".format(name) + ############################################################################### # Open DB file as datasource (new in GDAL 2.2) -def ogr_vfk_8(): +def test_ogr_vfk_8(): if gdaltest.vfk_drv is None: - return 'skip' + pytest.skip() # open by SQLite driver first vfk_ds_db = ogr.Open('data/bylany.db') @@ -281,22 +234,19 @@ def ogr_vfk_8(): count2 = vfk_ds_db.GetLayerCount() vfk_ds_db = None - if count1 != count2: - gdaltest.post_reason('layer count differs when opening DB by SQLite and VFK drivers') - return 'fail' + assert count1 == count2, \ + 'layer count differs when opening DB by SQLite and VFK drivers' del os.environ['OGR_VFK_DB_READ'] - return 'success' - ############################################################################### # Open datasource with SUPPRESS_GEOMETRY open option (new in GDAL 2.3) -def ogr_vfk_9(): +def test_ogr_vfk_9(): if gdaltest.vfk_drv is None: - return 'skip' + pytest.skip() # open with suppressing geometry vfk_ds = None @@ -304,28 +254,23 @@ def ogr_vfk_9(): vfk_layer_par = vfk_ds.GetLayerByName('PAR') - if not vfk_layer_par != 'PAR': - gdaltest.post_reason('did not get expected layer name "PAR"') - return 'fail' + assert vfk_layer_par != 'PAR', 'did not get expected layer name "PAR"' geom_type = vfk_layer_par.GetGeomType() vfk_layer_par = None vfk_ds = None - if geom_type != ogr.wkbNone: - gdaltest.post_reason('did not get expected geometry type, got %d' % geom_type) - return 'fail' - - return 'success' + assert geom_type == ogr.wkbNone, \ + ('did not get expected geometry type, got %d' % geom_type) ############################################################################### # Open datasource with FILE_FIELD open option (new in GDAL 2.4) -def ogr_vfk_10(): +def test_ogr_vfk_10(): if gdaltest.vfk_drv is None: - return 'skip' + pytest.skip() # open with suppressing geometry vfk_ds = None @@ -333,9 +278,7 @@ def ogr_vfk_10(): vfk_layer_par = vfk_ds.GetLayerByName('PAR') - if not vfk_layer_par != 'PAR': - gdaltest.post_reason('did not get expected layer name "PAR"') - return 'fail' + assert vfk_layer_par != 'PAR', 'did not get expected layer name "PAR"' vfk_layer_par.ResetReading() feat = vfk_layer_par.GetNextFeature() @@ -343,17 +286,13 @@ def ogr_vfk_10(): vfk_layer_par = None vfk_ds = None - if file_field != 'bylany.vfk': - gdaltest.post_reason('did not get expected file field value') - return 'fail' - - return 'success' + assert file_field == 'bylany.vfk', 'did not get expected file field value' ############################################################################### # Read PAR layer, check sequential feature access consistency -def ogr_vfk_11(): +def test_ogr_vfk_11(): def count_features(): gdaltest.vfk_layer_par.ResetReading() count = 0 @@ -366,26 +305,24 @@ def count_features(): return count if gdaltest.vfk_drv is None: - return 'skip' + pytest.skip() count = gdaltest.vfk_layer_par.GetFeatureCount() for i in range(2): # perform check twice, mix with random access if count != count_features(): feat = gdaltest.vfk_layer_par.GetFeature(i) - gdaltest.post_reason('did not get expected number of features') feat.DumpReadable() - return 'fail' - - return 'success' + pytest.fail('did not get expected number of features') + ############################################################################### # cleanup -def ogr_vfk_cleanup(): +def test_ogr_vfk_cleanup(): if gdaltest.vfk_drv is None: - return 'skip' + pytest.skip() gdaltest.vfk_layer_par = None gdaltest.vfk_layer_hp = None @@ -397,29 +334,9 @@ def ogr_vfk_cleanup(): except OSError: pass - return 'success' - + ############################################################################### # -gdaltest_list = [ - ogr_vfk_1, - ogr_vfk_2, - ogr_vfk_3, - ogr_vfk_4, - ogr_vfk_5, - ogr_vfk_6, - ogr_vfk_7, - ogr_vfk_8, - ogr_vfk_9, - ogr_vfk_10, - ogr_vfk_11, - ogr_vfk_cleanup] - -if __name__ == '__main__': - gdaltest.setup_run('ogr_vfk') - - gdaltest.run_tests(gdaltest_list) - sys.exit(gdaltest.summarize()) diff --git a/autotest/ogr/ogr_virtualogr.py b/autotest/ogr/ogr_virtualogr.py index 9cc9dbacf2b3..ca0f5aa0ac59 100755 --- a/autotest/ogr/ogr_virtualogr.py +++ b/autotest/ogr/ogr_virtualogr.py @@ -31,16 +31,21 @@ import sys -sys.path.append('../pymod') from osgeo import ogr from osgeo import gdal import gdaltest -import ogrtest +import pytest + +# Linter says this isn't used, but it actually is via pytest magic :) +from ogr.ogr_sql_sqlite import require_ogr_sql_sqlite # noqa ############################################################################### +pytestmark = pytest.mark.usefixtures('require_ogr_sql_sqlite') + + def ogr_virtualogr_run_sql(sql_statement): ds = ogr.GetDriverByName('SQLite').CreateDataSource(':memory:') @@ -70,86 +75,47 @@ def ogr_virtualogr_run_sql(sql_statement): # Basic tests -def ogr_virtualogr_1(): - - import ogr_sql_sqlite - if not ogr_sql_sqlite.ogr_sql_sqlite_available(): - return 'skip' - +def test_ogr_virtualogr_1(): # Invalid syntax - if ogr_virtualogr_run_sql("CREATE VIRTUAL TABLE poly USING VirtualOGR()"): - gdaltest.post_reason('failed') - return 'fail' + assert not ogr_virtualogr_run_sql("CREATE VIRTUAL TABLE poly USING VirtualOGR()") # Nonexistent dataset - if ogr_virtualogr_run_sql("CREATE VIRTUAL TABLE poly USING VirtualOGR('foo')"): - gdaltest.post_reason('failed') - return 'fail' + assert not ogr_virtualogr_run_sql("CREATE VIRTUAL TABLE poly USING VirtualOGR('foo')") # Dataset with 0 layer - if ogr_virtualogr_run_sql("CREATE VIRTUAL TABLE poly USING VirtualOGR('<OGRVRTDataSource></OGRVRTDataSource>')"): - gdaltest.post_reason('failed') - return 'fail' + assert not ogr_virtualogr_run_sql("CREATE VIRTUAL TABLE poly USING VirtualOGR('<OGRVRTDataSource></OGRVRTDataSource>')") # Dataset with more than 1 layer - if ogr_virtualogr_run_sql("CREATE VIRTUAL TABLE poly USING VirtualOGR('data')"): - gdaltest.post_reason('failed') - return 'fail' + assert not ogr_virtualogr_run_sql("CREATE VIRTUAL TABLE poly USING VirtualOGR('data')") - if not ogr_virtualogr_run_sql("CREATE VIRTUAL TABLE poly USING VirtualOGR('data/poly.shp')"): - gdaltest.post_reason('failed') - return 'fail' + assert ogr_virtualogr_run_sql("CREATE VIRTUAL TABLE poly USING VirtualOGR('data/poly.shp')") - if not ogr_virtualogr_run_sql("CREATE VIRTUAL TABLE poly USING VirtualOGR('data/poly.shp', 0)"): - gdaltest.post_reason('failed') - return 'fail' + assert ogr_virtualogr_run_sql("CREATE VIRTUAL TABLE poly USING VirtualOGR('data/poly.shp', 0)") - if not ogr_virtualogr_run_sql("CREATE VIRTUAL TABLE poly USING VirtualOGR('data/poly.shp', 1)"): - gdaltest.post_reason('failed') - return 'fail' + assert ogr_virtualogr_run_sql("CREATE VIRTUAL TABLE poly USING VirtualOGR('data/poly.shp', 1)") # Invalid value for update_mode - if ogr_virtualogr_run_sql("CREATE VIRTUAL TABLE poly USING VirtualOGR('data/poly.shp', 'foo')"): - gdaltest.post_reason('failed') - return 'fail' + assert not ogr_virtualogr_run_sql("CREATE VIRTUAL TABLE poly USING VirtualOGR('data/poly.shp', 'foo')") # Nonexistent layer - if ogr_virtualogr_run_sql("CREATE VIRTUAL TABLE poly USING VirtualOGR('data/poly.shp', 0, 'foo')"): - gdaltest.post_reason('failed') - return 'fail' + assert not ogr_virtualogr_run_sql("CREATE VIRTUAL TABLE poly USING VirtualOGR('data/poly.shp', 0, 'foo')") - if not ogr_virtualogr_run_sql("CREATE VIRTUAL TABLE poly USING VirtualOGR('data/poly.shp', 0, 'poly')"): - gdaltest.post_reason('failed') - return 'fail' + assert ogr_virtualogr_run_sql("CREATE VIRTUAL TABLE poly USING VirtualOGR('data/poly.shp', 0, 'poly')") - if not ogr_virtualogr_run_sql("CREATE VIRTUAL TABLE poly USING VirtualOGR('data/poly.shp', 0, 'poly', 0)"): - gdaltest.post_reason('failed') - return 'fail' + assert ogr_virtualogr_run_sql("CREATE VIRTUAL TABLE poly USING VirtualOGR('data/poly.shp', 0, 'poly', 0)") - if not ogr_virtualogr_run_sql("CREATE VIRTUAL TABLE poly USING VirtualOGR('data/poly.shp', 0, 'poly', 1)"): - gdaltest.post_reason('failed') - return 'fail' + assert ogr_virtualogr_run_sql("CREATE VIRTUAL TABLE poly USING VirtualOGR('data/poly.shp', 0, 'poly', 1)") - if not ogr_virtualogr_run_sql("CREATE VIRTUAL TABLE poly USING VirtualOGR('data/poly.shp', 0, 'poly', 1, 1)"): - gdaltest.post_reason('failed') - return 'fail' + assert ogr_virtualogr_run_sql("CREATE VIRTUAL TABLE poly USING VirtualOGR('data/poly.shp', 0, 'poly', 1, 1)") # Too many arguments - if ogr_virtualogr_run_sql("CREATE VIRTUAL TABLE poly USING VirtualOGR('data/poly.shp', 0, 'poly', 1, 1, bla)"): - gdaltest.post_reason('failed') - return 'fail' - - return 'success' + assert not ogr_virtualogr_run_sql("CREATE VIRTUAL TABLE poly USING VirtualOGR('data/poly.shp', 0, 'poly', 1, 1, bla)") ############################################################################### # Test detection of suspicious use of VirtualOGR -def ogr_virtualogr_2(): - - if not ogrtest.has_sqlite_dialect: - return 'skip' - +def test_ogr_virtualogr_2(): ds = ogr.GetDriverByName('SQLite').CreateDataSource('/vsimem/ogr_virtualogr_2.db') ds.ExecuteSQL("CREATE VIRTUAL TABLE foo USING VirtualOGR('data/poly.shp')") ds.ExecuteSQL("CREATE TABLE spy_table (spy_content VARCHAR)") @@ -159,9 +125,7 @@ def ogr_virtualogr_2(): # Check that foo isn't listed ds = ogr.Open('/vsimem/ogr_virtualogr_2.db') for i in range(ds.GetLayerCount()): - if ds.GetLayer(i).GetName() == 'foo': - gdaltest.post_reason('fail') - return 'fail' + assert ds.GetLayer(i).GetName() != 'foo' ds = None # Check that it is listed if OGR_SQLITE_LIST_VIRTUAL_OGR=YES @@ -172,9 +136,7 @@ def ogr_virtualogr_2(): for i in range(ds.GetLayerCount()): if ds.GetLayer(i).GetName() == 'foo': found = True - if not found: - gdaltest.post_reason('fail') - return 'fail' + assert found ds = None # Add suspicious trigger @@ -187,9 +149,7 @@ def ogr_virtualogr_2(): gdal.ErrorReset() ds = ogr.Open('/vsimem/ogr_virtualogr_2.db') for i in range(ds.GetLayerCount()): - if ds.GetLayer(i).GetName() == 'foo': - gdaltest.post_reason('fail') - return 'fail' + assert ds.GetLayer(i).GetName() != 'foo' # An error will be triggered at the time the trigger is used gdal.PushErrorHandler('CPLQuietErrorHandler') ds.ExecuteSQL("INSERT INTO regular_table (bar) VALUES ('bar')") @@ -199,8 +159,7 @@ def ogr_virtualogr_2(): if did_not_get_error: gdal.Unlink('/vsimem/ogr_virtualogr_2.db') - gdaltest.post_reason('expected a failure') - return 'fail' + pytest.fail('expected a failure') gdal.ErrorReset() gdal.PushErrorHandler('CPLQuietErrorHandler') @@ -211,32 +170,23 @@ def ogr_virtualogr_2(): if gdal.GetLastErrorMsg() == '': ds = None gdal.Unlink('/vsimem/ogr_virtualogr_2.db') - gdaltest.post_reason('expected an error message') - return 'fail' + pytest.fail('expected an error message') did_not_get_error = gdal.GetLastErrorMsg() == '' ds = None gdal.Unlink('/vsimem/ogr_virtualogr_2.db') - if did_not_get_error: - gdaltest.post_reason('expected a failure') - return 'fail' - - return 'success' + assert not did_not_get_error, 'expected a failure' ############################################################################### # Test GDAL as a SQLite3 dynamically loaded extension -def ogr_virtualogr_3(): - - if not ogrtest.has_sqlite_dialect: - return 'skip' - +def test_ogr_virtualogr_3(): # Find path of libgdal libgdal_name = gdaltest.find_lib('gdal') if libgdal_name is None: - return 'skip' + pytest.skip() print('Found ' + libgdal_name) # Find path of libsqlite3 or libspatialite @@ -244,7 +194,7 @@ def ogr_virtualogr_3(): if libsqlite_name is None: libsqlite_name = gdaltest.find_lib('spatialite') if libsqlite_name is None: - return 'skip' + pytest.skip() print('Found ' + libsqlite_name) python_exe = sys.executable @@ -256,22 +206,14 @@ def ogr_virtualogr_3(): ret = gdaltest.runexternal(python_exe + ' ogr_as_sqlite_extension.py "%s" "%s"' % (libsqlite_name, libgdal_name), check_memleak=False) if ret.find('skip') == 0: - return 'skip' - if ret.find(gdal.VersionInfo('RELEASE_NAME')) < 0: - gdaltest.post_reason('fail : %s' % ret) - return 'fail' - - return 'success' + pytest.skip() + assert gdal.VersionInfo('RELEASE_NAME') in ret ############################################################################### # Test ogr_datasource_load_layers() -def ogr_virtualogr_4(): - - if not ogrtest.has_sqlite_dialect: - return 'skip' - +def test_ogr_virtualogr_4(): ds = ogr.GetDriverByName('SQLite').CreateDataSource('/vsimem/ogr_virtualogr_4.db') sql_lyr = ds.ExecuteSQL("SELECT ogr_datasource_load_layers('data/poly.shp')") ds.ReleaseResultSet(sql_lyr) @@ -285,9 +227,7 @@ def ogr_virtualogr_4(): ds = None gdal.Unlink('/vsimem/ogr_virtualogr_4.db') - if ret != 10: - gdaltest.post_reason('fail') - return 'fail' + assert ret == 10 ds = ogr.GetDriverByName('SQLite').CreateDataSource('/vsimem/ogr_virtualogr_4.db') sql_lyr = ds.ExecuteSQL("SELECT ogr_datasource_load_layers('data/poly.shp', 0)") @@ -298,9 +238,7 @@ def ogr_virtualogr_4(): ds = None gdal.Unlink('/vsimem/ogr_virtualogr_4.db') - if ret != 10: - gdaltest.post_reason('fail') - return 'fail' + assert ret == 10 ds = ogr.GetDriverByName('SQLite').CreateDataSource('/vsimem/ogr_virtualogr_4.db') sql_lyr = ds.ExecuteSQL("SELECT ogr_datasource_load_layers('data/poly.shp', 0, 'prefix')") @@ -311,9 +249,7 @@ def ogr_virtualogr_4(): ds = None gdal.Unlink('/vsimem/ogr_virtualogr_4.db') - if ret != 10: - gdaltest.post_reason('fail') - return 'fail' + assert ret == 10 # Various error conditions ds = ogr.GetDriverByName('SQLite').CreateDataSource('/vsimem/ogr_virtualogr_4.db') @@ -330,16 +266,11 @@ def ogr_virtualogr_4(): ds = None gdal.Unlink('/vsimem/ogr_virtualogr_4.db') - return 'success' - ############################################################################### # Test failed CREATE VIRTUAL TABLE USING VirtualOGR -def ogr_virtualogr_5(): - - if not ogrtest.has_sqlite_dialect: - return 'skip' +def test_ogr_virtualogr_5(): # Create a CSV with duplicate column name fp = gdal.VSIFOpenL('/vsimem/ogr_virtualogr_5.csv', 'wt') @@ -353,27 +284,10 @@ def ogr_virtualogr_5(): gdal.PushErrorHandler('CPLQuietErrorHandler') sql_lyr = ds.ExecuteSQL("CREATE VIRTUAL TABLE lyr2 USING VirtualOGR('/vsimem/ogr_virtualogr_5.csv')", dialect='SQLITE') gdal.PopErrorHandler() - if sql_lyr is not None: - return 'fail' + assert sql_lyr is None ds = None gdal.Unlink('/vsimem/ogr_virtualogr_5.csv') - return 'success' - - -gdaltest_list = [ - ogr_virtualogr_1, - ogr_virtualogr_2, - ogr_virtualogr_3, - ogr_virtualogr_4, - ogr_virtualogr_5, -] - -if __name__ == '__main__': - - gdaltest.setup_run('ogr_virtualogr') - gdaltest.run_tests(gdaltest_list) - sys.exit(gdaltest.summarize()) diff --git a/autotest/ogr/ogr_vrt.py b/autotest/ogr/ogr_vrt.py index 555e72073928..72ba66dd1c18 100755 --- a/autotest/ogr/ogr_vrt.py +++ b/autotest/ogr/ogr_vrt.py @@ -28,9 +28,7 @@ ############################################################################### import os -import sys -sys.path.append('../pymod') import gdaltest import ogrtest @@ -38,20 +36,21 @@ from osgeo import osr from osgeo import gdal import test_cli_utilities +import pytest ############################################################################### # Open VRT datasource. -def ogr_vrt_1(): +def test_ogr_vrt_1(): with gdaltest.error_handler(): # Complains about dummySrcDataSource as expected. gdaltest.vrt_ds = ogr.Open('data/vrt_test.vrt') if gdaltest.vrt_ds is not None: - return 'success' - return 'fail' + return + pytest.fail() ############################################################################### # Verify the geometries, in the "test2" layer based on x,y,z columns. @@ -59,45 +58,33 @@ def ogr_vrt_1(): # Also tests FID-copied-from-source. -def ogr_vrt_2(): +def test_ogr_vrt_2(): if gdaltest.vrt_ds is None: - return 'skip' + pytest.skip() lyr = gdaltest.vrt_ds.GetLayerByName('test2') extent = lyr.GetExtent() - if extent != (12.5, 100.0, 17.0, 200.0): - gdaltest.post_reason('wrong extent') - print(extent) - return 'fail' + assert extent == (12.5, 100.0, 17.0, 200.0), 'wrong extent' expect = ['First', 'Second'] tr = ogrtest.check_features_against_list(lyr, 'other', expect) - if not tr: - return 'fail' + assert tr lyr.ResetReading() feat = lyr.GetNextFeature() - if ogrtest.check_feature_geometry(feat, 'POINT(12.5 17 1.2)', - max_error=0.000000001) != 0: - return 'fail' + assert (ogrtest.check_feature_geometry(feat, 'POINT(12.5 17 1.2)', + max_error=0.000000001) == 0) - if feat.GetFID() != 0: - gdaltest.post_reason('Unexpected fid') - return 'fail' + assert feat.GetFID() == 0, 'Unexpected fid' feat = lyr.GetNextFeature() - if ogrtest.check_feature_geometry(feat, 'POINT(100 200)', - max_error=0.000000001) != 0: - return 'fail' + assert (ogrtest.check_feature_geometry(feat, 'POINT(100 200)', + max_error=0.000000001) == 0) - if feat.GetFID() != 1: - gdaltest.post_reason('Unexpected fid') - return 'fail' - - return 'success' + assert feat.GetFID() == 1, 'Unexpected fid' ############################################################################### # Same test on layer 3 derived from WKT column. @@ -105,47 +92,38 @@ def ogr_vrt_2(): # Also tests FID-from-attribute. -def ogr_vrt_3(): +def test_ogr_vrt_3(): if gdaltest.vrt_ds is None: - return 'skip' + pytest.skip() lyr = gdaltest.vrt_ds.GetLayerByName('test3') expect = ['First', 'Second'] tr = ogrtest.check_features_against_list(lyr, 'other', expect) - if not tr: - return 'fail' + assert tr lyr.ResetReading() feat = lyr.GetNextFeature() - if ogrtest.check_feature_geometry(feat, 'POINT(12.5 17 1.2)', - max_error=0.000000001) != 0: - return 'fail' + assert (ogrtest.check_feature_geometry(feat, 'POINT(12.5 17 1.2)', + max_error=0.000000001) == 0) - if feat.GetFID() != 1: - gdaltest.post_reason('Unexpected fid') - return 'fail' + assert feat.GetFID() == 1, 'Unexpected fid' feat = lyr.GetNextFeature() - if ogrtest.check_feature_geometry(feat, 'POINT(100 200)', - max_error=0.000000001) != 0: - return 'fail' - - if feat.GetFID() != 2: - gdaltest.post_reason('Unexpected fid') - return 'fail' + assert (ogrtest.check_feature_geometry(feat, 'POINT(100 200)', + max_error=0.000000001) == 0) - return 'success' + assert feat.GetFID() == 2, 'Unexpected fid' ############################################################################### # Test a spatial query. -def ogr_vrt_4(): +def test_ogr_vrt_4(): if gdaltest.vrt_ds is None: - return 'skip' + pytest.skip() lyr = gdaltest.vrt_ds.GetLayerByName('test3') lyr.ResetReading() @@ -155,25 +133,21 @@ def ogr_vrt_4(): expect = ['Second'] tr = ogrtest.check_features_against_list(lyr, 'other', expect) - if not tr: - return 'fail' + assert tr lyr.ResetReading() feat = lyr.GetNextFeature() - if ogrtest.check_feature_geometry(feat, 'POINT(100 200)', - max_error=0.000000001) != 0: - return 'fail' + assert (ogrtest.check_feature_geometry(feat, 'POINT(100 200)', + max_error=0.000000001) == 0) lyr.SetSpatialFilter(None) - return 'success' - ############################################################################### # Test an attribute query. -def ogr_vrt_5(): +def test_ogr_vrt_5(): lyr = gdaltest.vrt_ds.GetLayerByName('test3') lyr.ResetReading() @@ -183,77 +157,60 @@ def ogr_vrt_5(): expect = ['First'] tr = ogrtest.check_features_against_list(lyr, 'other', expect) - if not tr: - return 'fail' + assert tr lyr.ResetReading() feat = lyr.GetNextFeature() - if ogrtest.check_feature_geometry(feat, 'POINT(12.5 17 1.2)', - max_error=0.000000001) != 0: - return 'fail' + assert (ogrtest.check_feature_geometry(feat, 'POINT(12.5 17 1.2)', + max_error=0.000000001) == 0) lyr.SetAttributeFilter(None) - return 'success' - ############################################################################### # Test GetFeature() on layer with FID coming from a column. -def ogr_vrt_6(): +def test_ogr_vrt_6(): if gdaltest.vrt_ds is None: - return 'skip' + pytest.skip() lyr = gdaltest.vrt_ds.GetLayerByName('test3') lyr.ResetReading() feat = lyr.GetFeature(2) - if feat.GetField('other') != 'Second': - gdaltest.post_reason('GetFeature() did not work properly.') - return 'fail' - - return 'success' + assert feat.GetField('other') == 'Second', 'GetFeature() did not work properly.' ############################################################################### # Same as test 3, but on the result of an SQL query. # -def ogr_vrt_7(): +def test_ogr_vrt_7(): if gdaltest.vrt_ds is None: - return 'skip' + pytest.skip() lyr = gdaltest.vrt_ds.GetLayerByName('test4') expect = ['First', 'Second'] tr = ogrtest.check_features_against_list(lyr, 'other', expect) - if not tr: - return 'fail' + assert tr lyr.ResetReading() feat = lyr.GetNextFeature() - if ogrtest.check_feature_geometry(feat, 'POINT(12.5 17 1.2)', - max_error=0.000000001) != 0: - return 'fail' + assert (ogrtest.check_feature_geometry(feat, 'POINT(12.5 17 1.2)', + max_error=0.000000001) == 0) - if feat.GetFID() != 1: - gdaltest.post_reason('Unexpected fid') - return 'fail' + assert feat.GetFID() == 1, 'Unexpected fid' feat = lyr.GetNextFeature() - if ogrtest.check_feature_geometry(feat, 'POINT(100 200)', - max_error=0.000000001) != 0: - return 'fail' - - if feat.GetFID() != 2: - gdaltest.post_reason('Unexpected fid') - return 'fail' + assert (ogrtest.check_feature_geometry(feat, 'POINT(100 200)', + max_error=0.000000001) == 0) - return 'success' + assert feat.GetFID() == 2, 'Unexpected fid' ############################################################################### # Similar test, but now we put the whole VRT contents directly into the @@ -261,9 +218,9 @@ def ogr_vrt_7(): # -def ogr_vrt_8(): +def test_ogr_vrt_8(): if gdaltest.vrt_ds is None: - return 'skip' + pytest.skip() vrt_xml = '<OGRVRTDataSource><OGRVRTLayer name="test4"><SrcDataSource relativeToVRT="0">data/flat.dbf</SrcDataSource><SrcSQL>SELECT * FROM flat</SrcSQL><FID>fid</FID><GeometryType>wkbPoint</GeometryType><GeometryField encoding="PointFromColumns" x="x" y="y" z="z"/></OGRVRTLayer></OGRVRTDataSource>' ds = ogr.Open(vrt_xml) @@ -272,73 +229,57 @@ def ogr_vrt_8(): expect = ['First', 'Second'] tr = ogrtest.check_features_against_list(lyr, 'other', expect) - if not tr: - return 'fail' + assert tr lyr.ResetReading() feat = lyr.GetNextFeature() - if ogrtest.check_feature_geometry(feat, 'POINT(12.5 17 1.2)', - max_error=0.000000001) != 0: - return 'fail' + assert (ogrtest.check_feature_geometry(feat, 'POINT(12.5 17 1.2)', + max_error=0.000000001) == 0) - if feat.GetFID() != 1: - gdaltest.post_reason('Unexpected fid') - return 'fail' + assert feat.GetFID() == 1, 'Unexpected fid' feat = lyr.GetNextFeature() - if ogrtest.check_feature_geometry(feat, 'POINT(100 200)', - max_error=0.000000001) != 0: - return 'fail' - - if feat.GetFID() != 2: - gdaltest.post_reason('Unexpected fid') - return 'fail' + assert (ogrtest.check_feature_geometry(feat, 'POINT(100 200)', + max_error=0.000000001) == 0) - return 'success' + assert feat.GetFID() == 2, 'Unexpected fid' ############################################################################### # Test that attribute filters are passed through to an underlying layer. -def ogr_vrt_9(): +def test_ogr_vrt_9(): if gdaltest.vrt_ds is None: - return 'skip' + pytest.skip() lyr = gdaltest.vrt_ds.GetLayerByName('test3') lyr.SetAttributeFilter("other = 'Second'") lyr.ResetReading() feat = lyr.GetNextFeature() - if feat.GetField('other') != 'Second': - gdaltest.post_reason('attribute filter did not work.') - return 'fail' + assert feat.GetField('other') == 'Second', 'attribute filter did not work.' sub_ds = ogr.OpenShared('data/flat.dbf') sub_layer = sub_ds.GetLayerByName('flat') sub_layer.ResetReading() - if sub_layer.GetFeatureCount() != 1: - print(sub_layer.GetFeatureCount()) - gdaltest.post_reason('attribute filter not passed to sublayer.') - return 'fail' + assert sub_layer.GetFeatureCount() == 1, 'attribute filter not passed to sublayer.' lyr.SetAttributeFilter(None) sub_ds.Release() sub_ds = None - return 'success' - ############################################################################### # Test capabilities # -def ogr_vrt_10(): +def test_ogr_vrt_10(): if gdaltest.vrt_ds is None: - return 'skip' + pytest.skip() vrt_xml = '<OGRVRTDataSource><OGRVRTLayer name="test"><SrcDataSource relativeToVRT="0">data/testpoly.shp</SrcDataSource><SrcLayer>testpoly</SrcLayer></OGRVRTLayer></OGRVRTDataSource>' vrt_ds = ogr.Open(vrt_xml) @@ -346,23 +287,18 @@ def ogr_vrt_10(): src_ds = ogr.Open('data/testpoly.shp') src_lyr = src_ds.GetLayer(0) - if vrt_lyr.TestCapability(ogr.OLCFastFeatureCount) != src_lyr.TestCapability(ogr.OLCFastFeatureCount): - return 'fail' - if vrt_lyr.TestCapability(ogr.OLCFastGetExtent) != src_lyr.TestCapability(ogr.OLCFastGetExtent): - return 'fail' - if vrt_lyr.TestCapability(ogr.OLCRandomRead) != src_lyr.TestCapability(ogr.OLCRandomRead): - return 'fail' - - return 'success' + assert vrt_lyr.TestCapability(ogr.OLCFastFeatureCount) == src_lyr.TestCapability(ogr.OLCFastFeatureCount) + assert vrt_lyr.TestCapability(ogr.OLCFastGetExtent) == src_lyr.TestCapability(ogr.OLCFastGetExtent) + assert vrt_lyr.TestCapability(ogr.OLCRandomRead) == src_lyr.TestCapability(ogr.OLCRandomRead) ############################################################################### # Test VRT write capabilities with PointFromColumns geometries # Test also the reportGeomSrcColumn attribute -def ogr_vrt_11(): +def test_ogr_vrt_11(): if gdaltest.vrt_ds is None: - return 'skip' + pytest.skip() f = open('tmp/test.csv', 'wb') f.write('x,val1,y,val2,style\n'.encode('ascii')) @@ -387,22 +323,14 @@ def ogr_vrt_11(): vrt_lyr = vrt_ds.GetLayerByName('test') # Only val1, val2, style attributes should be reported - if vrt_lyr.GetLayerDefn().GetFieldCount() != 3: - gdaltest.post_reason('failure') - print(vrt_lyr.GetLayerDefn().GetFieldCount()) - return 'fail' - if vrt_lyr.GetLayerDefn().GetFieldDefn(0).GetNameRef() != 'val1': - gdaltest.post_reason('failure') - return 'fail' - if vrt_lyr.GetLayerDefn().GetFieldDefn(1).GetNameRef() != 'val2': - gdaltest.post_reason('failure') - return 'fail' + assert vrt_lyr.GetLayerDefn().GetFieldCount() == 3 + assert vrt_lyr.GetLayerDefn().GetFieldDefn(0).GetNameRef() == 'val1' + assert vrt_lyr.GetLayerDefn().GetFieldDefn(1).GetNameRef() == 'val2' feat = vrt_lyr.GetNextFeature() if feat.GetStyleString() != 'PEN(c:#FF0000,w:5pt,p:"2px 1pt")': - gdaltest.post_reason('failure') feat.DumpReadable() - return 'fail' + pytest.fail() feat = ogr.Feature(vrt_lyr.GetLayerDefn()) geom = ogr.CreateGeometryFromWkt('POINT (3 50)') @@ -414,12 +342,9 @@ def ogr_vrt_11(): feat = vrt_lyr.GetFeature(2) geom = feat.GetGeometryRef() if geom.ExportToWkt() != 'POINT (3 50)': - gdaltest.post_reason('failure') feat.DumpReadable() - return 'fail' - if feat.GetFieldAsString('val1') != 'val21': - gdaltest.post_reason('failure') - return 'fail' + pytest.fail() + assert feat.GetFieldAsString('val1') == 'val21' # The x and y fields are considered as string by default, so spatial # filter cannot be turned into attribute filter @@ -427,12 +352,8 @@ def ogr_vrt_11(): vrt_lyr.SetSpatialFilterRect(0, 40, 10, 49.5) ret = vrt_lyr.GetFeatureCount() gdal.PopErrorHandler() - if gdal.GetLastErrorMsg().find('not declared as numeric fields') == -1: - gdaltest.post_reason('failure') - return 'fail' - if ret != 1: - gdaltest.post_reason('failure') - return 'fail' + assert gdal.GetLastErrorMsg().find('not declared as numeric fields') != -1 + assert ret == 1 vrt_ds = None @@ -444,37 +365,27 @@ def ogr_vrt_11(): vrt_ds = ogr.Open(vrt_xml, update=1) vrt_lyr = vrt_ds.GetLayerByName('test') vrt_lyr.SetSpatialFilterRect(0, 40, 10, 49.5) - if vrt_lyr.GetFeatureCount() != 1: - gdaltest.post_reason('failure') - return 'fail' - if gdal.GetLastErrorMsg() != '': - gdaltest.post_reason('failure') - return 'fail' + assert vrt_lyr.GetFeatureCount() == 1 + assert gdal.GetLastErrorMsg() == '' vrt_lyr.SetAttributeFilter("1 = 1") - if vrt_lyr.GetFeatureCount() != 1: - gdaltest.post_reason('failure') - return 'fail' + assert vrt_lyr.GetFeatureCount() == 1 vrt_lyr.SetAttributeFilter("1 = 0") - if vrt_lyr.GetFeatureCount() != 0: - gdaltest.post_reason('failure') - return 'fail' + assert vrt_lyr.GetFeatureCount() == 0 vrt_ds = None os.remove('tmp/test.csv') os.remove('tmp/test.csvt') - return 'success' - ############################################################################### # Test VRT write capabilities with WKT geometries -def ogr_vrt_12(): +def test_ogr_vrt_12(): if gdaltest.vrt_ds is None: - return 'skip' + pytest.skip() f = open('tmp/test.csv', 'wb') f.write('wkt_geom,val1,val2\n'.encode('ascii')) @@ -501,24 +412,20 @@ def ogr_vrt_12(): vrt_lyr.ResetReading() feat = vrt_lyr.GetFeature(2) geom = feat.GetGeometryRef() - if geom.ExportToWkt() != 'POINT (3 50)': - return 'fail' - if feat.GetFieldAsString('val1') != 'val21': - return 'fail' + assert geom.ExportToWkt() == 'POINT (3 50)' + assert feat.GetFieldAsString('val1') == 'val21' vrt_ds = None os.remove('tmp/test.csv') - return 'success' - ############################################################################### # Test VRT write capabilities with WKB geometries -def ogr_vrt_13(): +def test_ogr_vrt_13(): if gdaltest.vrt_ds is None: - return 'skip' + pytest.skip() f = open('tmp/test.csv', 'wb') f.write('wkb_geom,val1,val2\n'.encode('ascii')) @@ -544,24 +451,20 @@ def ogr_vrt_13(): vrt_lyr.ResetReading() feat = vrt_lyr.GetFeature(1) geom = feat.GetGeometryRef() - if geom.ExportToWkt() != 'POINT (3 50)': - return 'fail' - if feat.GetFieldAsString('val1') != 'val21': - return 'fail' + assert geom.ExportToWkt() == 'POINT (3 50)' + assert feat.GetFieldAsString('val1') == 'val21' vrt_ds = None os.remove('tmp/test.csv') - return 'success' - ############################################################################### # Test SrcRegion element for VGS_Direct -def ogr_vrt_14(): +def test_ogr_vrt_14(): if gdaltest.vrt_ds is None: - return 'skip' + pytest.skip() gdal.PushErrorHandler('CPLQuietErrorHandler') try: @@ -608,63 +511,46 @@ def ogr_vrt_14(): vrt_ds = ogr.Open(vrt_xml) vrt_lyr = vrt_ds.GetLayerByName('mytest') - if vrt_lyr.TestCapability(ogr.OLCFastSpatialFilter) != 1: - gdaltest.post_reason('Fast filter not set.') - return 'fail' + assert vrt_lyr.TestCapability(ogr.OLCFastSpatialFilter) == 1, 'Fast filter not set.' extent = vrt_lyr.GetExtent() - if extent != (2.0, 2.0, 49.0, 49.0): - gdaltest.post_reason('wrong extent') - print(extent) - return 'fail' + assert extent == (2.0, 2.0, 49.0, 49.0), 'wrong extent' - if vrt_lyr.GetFeatureCount() != 1: - gdaltest.post_reason('Feature count not one as expected.') - return 'fail' + assert vrt_lyr.GetFeatureCount() == 1, 'Feature count not one as expected.' feat = vrt_lyr.GetNextFeature() - if feat.GetFID() != 2: - gdaltest.post_reason('did not get fid 2.') - return 'fail' + assert feat.GetFID() == 2, 'did not get fid 2.' geom = feat.GetGeometryRef() - if geom.ExportToWkt() != 'POINT (2 49)': - gdaltest.post_reason('did not get expected point geometry.') - return 'fail' + assert geom.ExportToWkt() == 'POINT (2 49)', 'did not get expected point geometry.' vrt_lyr.SetSpatialFilterRect(1, 41, 3, 49.5) if vrt_lyr.GetFeatureCount() != 1: if gdal.GetLastErrorMsg().find('GEOS support not enabled') != -1: vrt_ds = None ogr.GetDriverByName('ESRI Shapefile').DeleteDataSource('tmp/test.shp') - return 'skip' + pytest.skip() print(vrt_lyr.GetFeatureCount()) - gdaltest.post_reason('did not get one feature on rect spatial filter.') - return 'fail' + pytest.fail('did not get one feature on rect spatial filter.') vrt_lyr.SetSpatialFilterRect(1, 41, 3, 48.5) - if vrt_lyr.GetFeatureCount() != 0: - gdaltest.post_reason('Did not get expected zero feature count.') - return 'fail' + assert vrt_lyr.GetFeatureCount() == 0, 'Did not get expected zero feature count.' vrt_lyr.SetSpatialFilter(None) - if vrt_lyr.GetFeatureCount() != 1: - gdaltest.post_reason('Did not get expected one feature count with no filter.') - return 'fail' + assert vrt_lyr.GetFeatureCount() == 1, \ + 'Did not get expected one feature count with no filter.' vrt_ds = None ogr.GetDriverByName('ESRI Shapefile').DeleteDataSource('tmp/test.shp') - return 'success' - ############################################################################### # Test SrcRegion element for VGS_WKT -def ogr_vrt_15(): +def test_ogr_vrt_15(): if gdaltest.vrt_ds is None: - return 'skip' + pytest.skip() f = open('tmp/test.csv', 'wb') f.write('wkt_geom,val1,val2\n'.encode('ascii')) @@ -686,45 +572,36 @@ def ogr_vrt_15(): vrt_ds = ogr.Open(vrt_xml) vrt_lyr = vrt_ds.GetLayerByName('test') - if vrt_lyr.TestCapability(ogr.OLCFastSpatialFilter) != 0: - return 'fail' + assert vrt_lyr.TestCapability(ogr.OLCFastSpatialFilter) == 0 - if vrt_lyr.GetFeatureCount() != 1: - return 'fail' + assert vrt_lyr.GetFeatureCount() == 1 feat = vrt_lyr.GetNextFeature() - if feat.GetFID() != 3: - return 'fail' + assert feat.GetFID() == 3 geom = feat.GetGeometryRef() - if geom.ExportToWkt() != 'POINT (2 49)': - return 'fail' + assert geom.ExportToWkt() == 'POINT (2 49)' vrt_lyr.SetSpatialFilterRect(1, 41, 3, 49.5) - if vrt_lyr.GetFeatureCount() != 1: - return 'fail' + assert vrt_lyr.GetFeatureCount() == 1 vrt_lyr.SetSpatialFilterRect(1, 41, 3, 48.5) - if vrt_lyr.GetFeatureCount() != 0: - return 'fail' + assert vrt_lyr.GetFeatureCount() == 0 vrt_lyr.SetSpatialFilter(None) - if vrt_lyr.GetFeatureCount() != 1: - return 'fail' + assert vrt_lyr.GetFeatureCount() == 1 vrt_ds = None os.remove('tmp/test.csv') - return 'success' - ############################################################################### # Test SrcRegion element for VGS_PointFromColumns -def ogr_vrt_16(): +def test_ogr_vrt_16(): if gdaltest.vrt_ds is None: - return 'skip' + pytest.skip() f = open('tmp/test.csvt', 'wb') f.write('Real,Real,String,String\n'.encode('ascii')) @@ -750,19 +627,15 @@ def ogr_vrt_16(): vrt_ds = ogr.Open(vrt_xml) vrt_lyr = vrt_ds.GetLayerByName('test') - if vrt_lyr.TestCapability(ogr.OLCFastSpatialFilter) != 0: - return 'fail' + assert vrt_lyr.TestCapability(ogr.OLCFastSpatialFilter) == 0 - if vrt_lyr.GetFeatureCount() != 1: - return 'fail' + assert vrt_lyr.GetFeatureCount() == 1 feat = vrt_lyr.GetNextFeature() - if feat.GetFID() != 3: - return 'fail' + assert feat.GetFID() == 3 geom = feat.GetGeometryRef() - if geom.ExportToWkt() != 'POINT (2 49)': - return 'fail' + assert geom.ExportToWkt() == 'POINT (2 49)' vrt_lyr.SetSpatialFilterRect(1, 41, 3, 49.5) if vrt_lyr.GetFeatureCount() != 1: @@ -770,32 +643,28 @@ def ogr_vrt_16(): vrt_ds = None os.remove('tmp/test.csv') os.remove('tmp/test.csvt') - return 'skip' - return 'fail' + pytest.skip() + pytest.fail() vrt_lyr.SetSpatialFilterRect(1, 41, 3, 48.5) - if vrt_lyr.GetFeatureCount() != 0: - return 'fail' + assert vrt_lyr.GetFeatureCount() == 0 vrt_lyr.SetSpatialFilter(None) - if vrt_lyr.GetFeatureCount() != 1: - return 'fail' + assert vrt_lyr.GetFeatureCount() == 1 vrt_ds = None os.remove('tmp/test.csv') os.remove('tmp/test.csvt') - return 'success' - ############################################################################### # Test explicit field definitions. -def ogr_vrt_17(): +def test_ogr_vrt_17(): if gdaltest.vrt_ds is None: - return 'skip' + pytest.skip() vrt_xml = """ <OGRVRTDataSource> @@ -812,59 +681,38 @@ def ogr_vrt_17(): vrt_ds = ogr.Open(vrt_xml) vrt_lyr = vrt_ds.GetLayerByName('test') - if vrt_lyr.GetLayerDefn().GetFieldCount() != 4: - gdaltest.post_reason('unexpected field count.') - return 'fail' + assert vrt_lyr.GetLayerDefn().GetFieldCount() == 4, 'unexpected field count.' flddef = vrt_lyr.GetLayerDefn().GetFieldDefn(0) - if flddef.GetName() != 'pm_code' \ - or flddef.GetType() != ogr.OFTInteger \ - or flddef.GetWidth() != 4 \ - or flddef.GetPrecision() != 0: - gdaltest.post_reason('pm_code field definition wrong.') - return 'fail' + assert flddef.GetName() == 'pm_code' and flddef.GetType() == ogr.OFTInteger and flddef.GetWidth() == 4 and flddef.GetPrecision() == 0, \ + 'pm_code field definition wrong.' flddef = vrt_lyr.GetLayerDefn().GetFieldDefn(1) - if flddef.GetName() != 'prime_meridian_name' \ - or flddef.GetType() != ogr.OFTString \ - or flddef.GetWidth() != 24 \ - or flddef.GetPrecision() != 0: - gdaltest.post_reason('prime_meridian_name field definition wrong.') - return 'fail' + assert flddef.GetName() == 'prime_meridian_name' and flddef.GetType() == ogr.OFTString and flddef.GetWidth() == 24 and flddef.GetPrecision() == 0, \ + 'prime_meridian_name field definition wrong.' flddef = vrt_lyr.GetLayerDefn().GetFieldDefn(2) - if flddef.GetName() != 'new_col' \ - or flddef.GetType() != ogr.OFTReal \ - or flddef.GetWidth() != 12 \ - or flddef.GetPrecision() != 3: - gdaltest.post_reason('new_col field definition wrong.') - return 'fail' + assert flddef.GetName() == 'new_col' and flddef.GetType() == ogr.OFTReal and flddef.GetWidth() == 12 and flddef.GetPrecision() == 3, \ + 'new_col field definition wrong.' flddef = vrt_lyr.GetLayerDefn().GetFieldDefn(3) - if flddef.GetName() != 'DEPRECATED' \ - or flddef.GetType() != ogr.OFTInteger \ - or flddef.GetSubType() != ogr.OFSTBoolean: - gdaltest.post_reason('DEPRECATED field definition wrong.') - return 'fail' + assert flddef.GetName() == 'DEPRECATED' and flddef.GetType() == ogr.OFTInteger and flddef.GetSubType() == ogr.OFSTBoolean, \ + 'DEPRECATED field definition wrong.' feat = vrt_lyr.GetNextFeature() - if feat.GetField(0) != 8901 or feat.GetField(1) != "Greenwich" \ - or feat.GetField(2) is not None: - gdaltest.post_reason('did not get expected field value(s).') - return 'fail' - - return 'success' + assert feat.GetField(0) == 8901 and feat.GetField(1) == "Greenwich" and feat.GetField(2) is None, \ + 'did not get expected field value(s).' ############################################################################### # Test that attribute filters are *not* passed to sublayer by default # when explicit fields are defined. -def ogr_vrt_18(): +def test_ogr_vrt_18(): if gdaltest.vrt_ds is None: - return 'skip' + pytest.skip() vrt_xml = """ <OGRVRTDataSource> @@ -883,59 +731,47 @@ def ogr_vrt_18(): feat = vrt_lyr.GetNextFeature() - if feat.GetField(0) != 8904: - gdaltest.post_reason('Attribute filter not working properly') - return 'fail' - - return 'success' + assert feat.GetField(0) == 8904, 'Attribute filter not working properly' ############################################################################### # Run test_ogrsf (optimized path) -def ogr_vrt_19_optimized(): +def test_ogr_vrt_19_optimized(): if gdaltest.vrt_ds is None: - return 'skip' + pytest.skip() if test_cli_utilities.get_test_ogrsf_path() is None: - return 'skip' + pytest.skip() ret = gdaltest.runexternal(test_cli_utilities.get_test_ogrsf_path() + ' -ro data/poly_vrt.vrt') - if ret.find('INFO') == -1 or ret.find('ERROR') != -1: - print(ret) - return 'fail' - - return 'success' + assert ret.find('INFO') != -1 and ret.find('ERROR') == -1 ############################################################################### # Run test_ogrsf (non optimized path) -def ogr_vrt_19_nonoptimized(): +def test_ogr_vrt_19_nonoptimized(): if gdaltest.vrt_ds is None: - return 'skip' + pytest.skip() if test_cli_utilities.get_test_ogrsf_path() is None: - return 'skip' + pytest.skip() ret = gdaltest.runexternal(test_cli_utilities.get_test_ogrsf_path() + ' -ro data/poly_nonoptimized_vrt.vrt') - if ret.find('INFO') == -1 or ret.find('ERROR') != -1: - print(ret) - return 'fail' - - return 'success' + assert ret.find('INFO') != -1 and ret.find('ERROR') == -1 ############################################################################### # Test VGS_Direct -def ogr_vrt_20(): +def test_ogr_vrt_20(): if gdaltest.vrt_ds is None: - return 'skip' + pytest.skip() gdal.PushErrorHandler('CPLQuietErrorHandler') try: @@ -981,64 +817,44 @@ def ogr_vrt_20(): vrt_ds = ogr.Open(vrt_xml, update=1) vrt_lyr = vrt_ds.GetLayerByName('mytest') - if vrt_lyr.TestCapability(ogr.OLCFastFeatureCount) != 1: - gdaltest.post_reason('Fast feature count not set.') - return 'fail' + assert vrt_lyr.TestCapability(ogr.OLCFastFeatureCount) == 1, \ + 'Fast feature count not set.' - if vrt_lyr.TestCapability(ogr.OLCFastSpatialFilter) != 1: - gdaltest.post_reason('Fast filter not set.') - return 'fail' + assert vrt_lyr.TestCapability(ogr.OLCFastSpatialFilter) == 1, 'Fast filter not set.' - if vrt_lyr.TestCapability(ogr.OLCFastGetExtent) != 1: - gdaltest.post_reason('Fast extent not set.') - return 'fail' + assert vrt_lyr.TestCapability(ogr.OLCFastGetExtent) == 1, 'Fast extent not set.' extent = vrt_lyr.GetExtent() - if extent != (-10.0, 2.0, 45.0, 49.0): - gdaltest.post_reason('wrong extent') - print(extent) - return 'fail' + assert extent == (-10.0, 2.0, 45.0, 49.0), 'wrong extent' - if vrt_lyr.GetFeatureCount() != 4: - gdaltest.post_reason('Feature count not 4 as expected.') - return 'fail' + assert vrt_lyr.GetFeatureCount() == 4, 'Feature count not 4 as expected.' vrt_lyr.SetSpatialFilterRect(1, 48.5, 3, 49.5) if vrt_lyr.GetFeatureCount() != 1: if gdal.GetLastErrorMsg().find('GEOS support not enabled') != -1: vrt_ds = None ogr.GetDriverByName('ESRI Shapefile').DeleteDataSource('tmp/test.shp') - return 'skip' + pytest.skip() print(vrt_lyr.GetFeatureCount()) - gdaltest.post_reason('did not get one feature on rect spatial filter.') - return 'fail' + pytest.fail('did not get one feature on rect spatial filter.') - if vrt_lyr.TestCapability(ogr.OLCFastFeatureCount) != 1: - gdaltest.post_reason('Fast feature count not set.') - return 'fail' + assert vrt_lyr.TestCapability(ogr.OLCFastFeatureCount) == 1, \ + 'Fast feature count not set.' - if vrt_lyr.TestCapability(ogr.OLCFastGetExtent) != 1: - gdaltest.post_reason('Fast extent not set.') - return 'fail' + assert vrt_lyr.TestCapability(ogr.OLCFastGetExtent) == 1, 'Fast extent not set.' extent = vrt_lyr.GetExtent() # the shapefile driver currently doesn't change the extent even in the # presence of a spatial filter, so that could change in the future - if extent != (-10.0, 2.0, 45.0, 49.0): - gdaltest.post_reason('wrong extent') - print(extent) - return 'fail' + assert extent == (-10.0, 2.0, 45.0, 49.0), 'wrong extent' vrt_lyr.SetSpatialFilterRect(1, 48, 3, 48.5) - if vrt_lyr.GetFeatureCount() != 0: - gdaltest.post_reason('Did not get expected zero feature count.') - return 'fail' + assert vrt_lyr.GetFeatureCount() == 0, 'Did not get expected zero feature count.' vrt_lyr.SetSpatialFilter(None) - if vrt_lyr.GetFeatureCount() != 4: - gdaltest.post_reason('Feature count not 4 as expected with no filter.') - return 'fail' + assert vrt_lyr.GetFeatureCount() == 4, \ + 'Feature count not 4 as expected with no filter.' vrt_lyr.ResetReading() feat = vrt_lyr.GetNextFeature() @@ -1050,15 +866,12 @@ def ogr_vrt_20(): feat = vrt_lyr.GetNextFeature() if feat.GetGeometryRef() is None or \ feat.GetGeometryRef().ExportToWkt() != 'POINT (1 2)': - gdaltest.post_reason('fail') feat.DumpReadable() - return 'fail' + pytest.fail() vrt_ds = None ogr.GetDriverByName('ESRI Shapefile').DeleteDataSource('tmp/test.shp') - return 'success' - ############################################################################### # Test lazy initialization with valid layer @@ -1066,27 +879,21 @@ def ogr_vrt_20(): def ogr_vrt_21_internal(): if gdaltest.vrt_ds is None: - return 'skip' + pytest.skip() ds = ogr.Open('data/vrt_test.vrt') lyr = ds.GetLayerByName('test3') - if lyr.GetName() != 'test3': - gdaltest.post_reason('fail') - return 'fail' + assert lyr.GetName() == 'test3' ds = None ds = ogr.Open('data/vrt_test.vrt') lyr = ds.GetLayerByName('test3') - if lyr.GetGeomType() != ogr.wkbPoint: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.GetGeomType() == ogr.wkbPoint ds = None ds = ogr.Open('data/vrt_test.vrt') lyr = ds.GetLayerByName('test3') - if lyr.GetSpatialRef().ExportToWkt().find('84') == -1: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.GetSpatialRef().ExportToWkt().find('84') != -1 ds = None ds = ogr.Open('data/vrt_test.vrt') @@ -1096,44 +903,32 @@ def ogr_vrt_21_internal(): ds = ogr.Open('data/vrt_test.vrt') lyr = ds.GetLayerByName('test3') - if lyr.GetNextFeature() is None: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.GetNextFeature() is not None ds = None ds = ogr.Open('data/vrt_test.vrt') lyr = ds.GetLayerByName('test3') - if lyr.GetFeature(1) is None: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.GetFeature(1) is not None ds = None ds = ogr.Open('data/vrt_test.vrt') lyr = ds.GetLayerByName('test3') - if lyr.GetFeatureCount() == 0: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.GetFeatureCount() != 0 ds = None ds = ogr.Open('data/vrt_test.vrt') lyr = ds.GetLayerByName('test3') - if lyr.SetNextByIndex(1) != 0: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.SetNextByIndex(1) == 0 ds = None ds = ogr.Open('data/vrt_test.vrt') lyr = ds.GetLayerByName('test3') - if lyr.GetLayerDefn().GetFieldCount() == 0: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.GetLayerDefn().GetFieldCount() != 0 ds = None ds = ogr.Open('data/vrt_test.vrt') lyr = ds.GetLayerByName('test3') - if lyr.SetAttributeFilter('') != 0: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.SetAttributeFilter('') == 0 ds = None ds = ogr.Open('data/vrt_test.vrt') @@ -1143,23 +938,17 @@ def ogr_vrt_21_internal(): ds = ogr.Open('data/vrt_test.vrt') lyr = ds.GetLayerByName('test3') - if lyr.TestCapability(ogr.OLCFastFeatureCount) != 1: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.TestCapability(ogr.OLCFastFeatureCount) == 1 ds = None ds = ogr.Open('data/vrt_test.vrt') lyr = ds.GetLayerByName('test3') - if lyr.GetExtent() is None: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.GetExtent() is not None ds = None ds = ogr.Open('data/vrt_test.vrt') lyr = ds.GetLayerByName('test3') - if lyr.GetFIDColumn() != 'fid': - gdaltest.post_reason('fail') - return 'fail' + assert lyr.GetFIDColumn() == 'fid' ds = None feature_defn = ogr.FeatureDefn() @@ -1184,10 +973,8 @@ def ogr_vrt_21_internal(): lyr.SyncToDisk() ds = None - return 'success' - -def ogr_vrt_21(): +def test_ogr_vrt_21(): gdal.PushErrorHandler('CPLQuietErrorHandler') try: ret = ogr_vrt_21_internal() @@ -1203,24 +990,21 @@ def ogr_vrt_21(): def ogr_vrt_22_internal(): if gdaltest.vrt_ds is None: - return 'skip' + pytest.skip() ds = ogr.Open('data/vrt_test.vrt') lyr = ds.GetLayerByName('test5') - if lyr.GetName() != 'test5': - return 'fail' + assert lyr.GetName() == 'test5' ds = None ds = ogr.Open('data/vrt_test.vrt') lyr = ds.GetLayerByName('test5') - if lyr.GetGeomType() != ogr.wkbPoint: - return 'fail' + assert lyr.GetGeomType() == ogr.wkbPoint ds = None ds = ogr.Open('data/vrt_test.vrt') lyr = ds.GetLayerByName('test5') - if lyr.GetSpatialRef().ExportToWkt().find('84') == -1: - return 'fail' + assert lyr.GetSpatialRef().ExportToWkt().find('84') != -1 ds = None ds = ogr.Open('data/vrt_test.vrt') @@ -1230,38 +1014,32 @@ def ogr_vrt_22_internal(): ds = ogr.Open('data/vrt_test.vrt') lyr = ds.GetLayerByName('test5') - if lyr.GetNextFeature() is not None: - return 'fail' + assert lyr.GetNextFeature() is None ds = None ds = ogr.Open('data/vrt_test.vrt') lyr = ds.GetLayerByName('test5') - if lyr.GetFeature(1) is not None: - return 'fail' + assert lyr.GetFeature(1) is None ds = None ds = ogr.Open('data/vrt_test.vrt') lyr = ds.GetLayerByName('test5') - if lyr.GetFeatureCount() != 0: - return 'fail' + assert lyr.GetFeatureCount() == 0 ds = None ds = ogr.Open('data/vrt_test.vrt') lyr = ds.GetLayerByName('test5') - if lyr.SetNextByIndex(1) == 0: - return 'fail' + assert lyr.SetNextByIndex(1) != 0 ds = None ds = ogr.Open('data/vrt_test.vrt') lyr = ds.GetLayerByName('test5') - if lyr.GetLayerDefn().GetFieldCount() != 0: - return 'fail' + assert lyr.GetLayerDefn().GetFieldCount() == 0 ds = None ds = ogr.Open('data/vrt_test.vrt') lyr = ds.GetLayerByName('test5') - if lyr.SetAttributeFilter('') == 0: - return 'fail' + assert lyr.SetAttributeFilter('') != 0 ds = None ds = ogr.Open('data/vrt_test.vrt') @@ -1271,14 +1049,12 @@ def ogr_vrt_22_internal(): ds = ogr.Open('data/vrt_test.vrt') lyr = ds.GetLayerByName('test5') - if lyr.TestCapability(ogr.OLCFastFeatureCount) != 0: - return 'fail' + assert lyr.TestCapability(ogr.OLCFastFeatureCount) == 0 ds = None ds = ogr.Open('data/vrt_test.vrt') lyr = ds.GetLayerByName('test5') - if lyr.GetFIDColumn() != '': - return 'fail' + assert lyr.GetFIDColumn() == '' ds = None ds = ogr.Open('data/vrt_test.vrt') @@ -1323,10 +1099,8 @@ def ogr_vrt_22_internal(): lyr.RollbackTransaction() ds = None - return 'success' - -def ogr_vrt_22(): +def test_ogr_vrt_22(): gdal.PushErrorHandler('CPLQuietErrorHandler') try: ret = ogr_vrt_22_internal() @@ -1339,11 +1113,10 @@ def ogr_vrt_22(): # Test anti-recursion mechanism -def ogr_vrt_23(shared_ds_flag=''): +def test_ogr_vrt_23(shared_ds_flag=''): if int(gdal.VersionInfo('VERSION_NUM')) < 1900: - gdaltest.post_reason('would crash') - return 'skip' + pytest.skip('would crash') rec1 = """<OGRVRTDataSource> <OGRVRTLayer name="rec1"> @@ -1363,32 +1136,25 @@ def ogr_vrt_23(shared_ds_flag=''): gdal.FileFromMemBuffer('/vsimem/rec2.vrt', rec2) ds = ogr.Open('/vsimem/rec1.vrt') - if ds is None: - return 'fail' + assert ds is not None gdal.ErrorReset() gdal.PushErrorHandler('CPLQuietErrorHandler') ds.GetLayer(0).GetLayerDefn() ds.GetLayer(0).GetFeatureCount() gdal.PopErrorHandler() - if gdal.GetLastErrorMsg() == '': - gdaltest.post_reason('error expected !') - return 'fail' + assert gdal.GetLastErrorMsg() != '', 'error expected !' gdal.Unlink('/vsimem/rec1.vrt') gdal.Unlink('/vsimem/rec2.vrt') - return 'success' - ############################################################################### # Test anti-recursion mechanism on shared DS -def ogr_vrt_24(): +def test_ogr_vrt_24(): - ret = ogr_vrt_23(' shared="1"') - if ret != 'success': - return ret + test_ogr_vrt_23(' shared="1"') rec1 = """<OGRVRTDataSource> <OGRVRTLayer name="test"> @@ -1406,28 +1172,23 @@ def ogr_vrt_24(): gdal.FileFromMemBuffer('/vsimem/rec2.vrt', rec2) ds = ogr.Open('/vsimem/rec1.vrt') - if ds is None: - return 'fail' + assert ds is not None gdal.ErrorReset() gdal.PushErrorHandler('CPLQuietErrorHandler') ds.GetLayer(0).GetLayerDefn() ds.GetLayer(0).GetFeatureCount() gdal.PopErrorHandler() - if gdal.GetLastErrorMsg() == '': - gdaltest.post_reason('error expected !') - return 'fail' + assert gdal.GetLastErrorMsg() != '', 'error expected !' gdal.Unlink('/vsimem/rec1.vrt') gdal.Unlink('/vsimem/rec2.vrt') - return 'success' - ############################################################################### # Test GetFIDColumn() -def ogr_vrt_25(): +def test_ogr_vrt_25(): with gdaltest.error_handler(): ds = ogr.Open('data/vrt_test.vrt') @@ -1435,49 +1196,35 @@ def ogr_vrt_25(): # test3 layer just declares fid, and implicit fields (so all source # fields are taken as VRT fields), we can report the fid column lyr = ds.GetLayerByName('test3') - if lyr.GetFIDColumn() != 'fid': - gdaltest.post_reason('fail') - print(lyr.GetFIDColumn()) - return 'fail' + assert lyr.GetFIDColumn() == 'fid' # test6 layer declares fid, and explicit fields without the fid lyr = ds.GetLayerByName('test6') - if lyr.GetFIDColumn() != 'fid': - gdaltest.post_reason('fail') - print(lyr.GetFIDColumn()) - return 'fail' + assert lyr.GetFIDColumn() == 'fid' # test7 layer just declares fid with an external visible name lyr = ds.GetLayerByName('test7') - if lyr.GetFIDColumn() != 'bar': - gdaltest.post_reason('fail') - print(lyr.GetFIDColumn()) - return 'fail' + assert lyr.GetFIDColumn() == 'bar' # test2 layer does not declare fid, and source layer has no fid column # so nothing to report lyr = ds.GetLayerByName('test2') - if lyr.GetFIDColumn() != '': - gdaltest.post_reason('fail') - print(lyr.GetFIDColumn()) - return 'fail' + assert lyr.GetFIDColumn() == '' ds = None - return 'success' - ############################################################################### # Test transaction support -def ogr_vrt_26(): +def test_ogr_vrt_26(): if ogr.GetDriverByName('SQLite') is None: - return 'skip' + pytest.skip() sqlite_ds = ogr.GetDriverByName('SQLite').CreateDataSource('/vsimem/ogr_vrt_26.db') if sqlite_ds is None: - return 'skip' + pytest.skip() lyr = sqlite_ds.CreateLayer('test') lyr.CreateField(ogr.FieldDefn('foo', ogr.OFTString)) @@ -1491,9 +1238,7 @@ def ogr_vrt_26(): </OGRVRTDataSource>""", update=1) lyr = vrt_ds.GetLayer(0) - if lyr.TestCapability(ogr.OLCTransactions) == 0: - gdaltest.post_reason('failed') - return 'fail' + assert lyr.TestCapability(ogr.OLCTransactions) != 0 lyr.StartTransaction() feat = ogr.Feature(lyr.GetLayerDefn()) @@ -1501,15 +1246,11 @@ def ogr_vrt_26(): lyr.CreateFeature(feat) feat = None - if lyr.GetFeatureCount() != 1: - gdaltest.post_reason('failed') - return 'fail' + assert lyr.GetFeatureCount() == 1 lyr.RollbackTransaction() - if lyr.GetFeatureCount() != 0: - gdaltest.post_reason('failed') - return 'fail' + assert lyr.GetFeatureCount() == 0 lyr.StartTransaction() feat = ogr.Feature(lyr.GetLayerDefn()) @@ -1518,9 +1259,7 @@ def ogr_vrt_26(): feat = None lyr.CommitTransaction() - if lyr.GetFeatureCount() != 1: - gdaltest.post_reason('failed') - return 'fail' + assert lyr.GetFeatureCount() == 1 vrt_ds = None @@ -1528,13 +1267,11 @@ def ogr_vrt_26(): ogr.GetDriverByName('SQLite').DeleteDataSource('/vsimem/ogr_vrt_26.db') - return 'success' - ############################################################################### # Test shapebin geometry -def ogr_vrt_27(): +def test_ogr_vrt_27(): csv = """dummy,shapebin "dummy","01000000000000000000F03F0000000000000040" @@ -1552,8 +1289,7 @@ def ogr_vrt_27(): </OGRVRTLayer> </OGRVRTDataSource>""") - if ds is None: - return 'fail' + assert ds is not None lyr = ds.GetLayer(0) @@ -1562,8 +1298,7 @@ def ogr_vrt_27(): feat = lyr.GetNextFeature() i = 0 while feat is not None: - if ogrtest.check_feature_geometry(feat, wkt_list[i]) != 0: - return 'fail' + assert ogrtest.check_feature_geometry(feat, wkt_list[i]) == 0 feat = lyr.GetNextFeature() i = i + 1 @@ -1571,30 +1306,25 @@ def ogr_vrt_27(): gdal.Unlink('/vsimem/ogr_vrt_27.csv') - return 'success' - ############################################################################### # Invalid VRT testing -def ogr_vrt_28(): +def test_ogr_vrt_28(): with gdaltest.error_handler(): ds = ogr.Open("<OGRVRTDataSource></foo>") - if ds is not None: - return 'fail' + assert ds is None gdal.FileFromMemBuffer('/vsimem/ogr_vrt_28_invalid.vrt', "<bla><OGRVRTDataSource></OGRVRTDataSource></bla>") with gdaltest.error_handler(): ds = ogr.Open("/vsimem/ogr_vrt_28_invalid.vrt") - if ds is not None: - return 'fail' + assert ds is None gdal.Unlink("/vsimem/ogr_vrt_28_invalid.vrt") with gdaltest.error_handler(): ds = ogr.Open("data/invalid.vrt") - if ds is None: - return 'fail' + assert ds is not None for i in range(ds.GetLayerCount()): gdal.ErrorReset() @@ -1602,40 +1332,31 @@ def ogr_vrt_28(): lyr = ds.GetLayer(i) lyr.GetNextFeature() gdal.PopErrorHandler() - if gdal.GetLastErrorMsg() == '': - gdaltest.post_reason('expected failure for layer %d of datasource %s' % (i, ds.GetName())) - return 'fail' + assert gdal.GetLastErrorMsg() != '', \ + ('expected failure for layer %d of datasource %s' % (i, ds.GetName())) ds = None gdal.PushErrorHandler('CPLQuietErrorHandler') ogr.Open("<OGRVRTDataSource><OGRVRTLayer/></OGRVRTDataSource>") gdal.PopErrorHandler() - if gdal.GetLastErrorMsg() == '': - gdaltest.post_reason('expected error message on datasource opening') - return 'fail' + assert gdal.GetLastErrorMsg() != '', 'expected error message on datasource opening' gdal.PushErrorHandler('CPLQuietErrorHandler') ds = ogr.Open("data/invalid2.vrt") gdal.PopErrorHandler() - if gdal.GetLastErrorMsg() == '': - gdaltest.post_reason('expected error message on datasource opening') - return 'fail' + assert gdal.GetLastErrorMsg() != '', 'expected error message on datasource opening' gdal.PushErrorHandler('CPLQuietErrorHandler') ds = ogr.Open("data/invalid3.vrt") gdal.PopErrorHandler() - if gdal.GetLastErrorMsg() == '': - gdaltest.post_reason('expected error message on datasource opening') - return 'fail' - - return 'success' + assert gdal.GetLastErrorMsg() != '', 'expected error message on datasource opening' ############################################################################### # Test OGRVRTWarpedLayer -def ogr_vrt_29(): +def test_ogr_vrt_29(): gdal.Unlink('tmp/ogr_vrt_29.shp') gdal.Unlink('tmp/ogr_vrt_29.shx') @@ -1669,9 +1390,7 @@ def ogr_vrt_29(): </OGRVRTWarpedLayer> </OGRVRTDataSource>""") gdal.PopErrorHandler() - if gdal.GetLastErrorMsg() == '': - gdaltest.post_reason('fail') - return 'fail' + assert gdal.GetLastErrorMsg() != '' # Non-spatial layer gdal.PushErrorHandler('CPLQuietErrorHandler') @@ -1684,9 +1403,7 @@ def ogr_vrt_29(): </OGRVRTWarpedLayer> </OGRVRTDataSource>""") gdal.PopErrorHandler() - if gdal.GetLastErrorMsg() == '': - gdaltest.post_reason('fail') - return 'fail' + assert gdal.GetLastErrorMsg() != '' # Missing TargetSRS gdal.PushErrorHandler('CPLQuietErrorHandler') @@ -1698,9 +1415,7 @@ def ogr_vrt_29(): </OGRVRTWarpedLayer> </OGRVRTDataSource>""") gdal.PopErrorHandler() - if gdal.GetLastErrorMsg() == '': - gdaltest.post_reason('fail') - return 'fail' + assert gdal.GetLastErrorMsg() != '' # Invalid TargetSRS gdal.PushErrorHandler('CPLQuietErrorHandler') @@ -1713,9 +1428,7 @@ def ogr_vrt_29(): </OGRVRTWarpedLayer> </OGRVRTDataSource>""") gdal.PopErrorHandler() - if gdal.GetLastErrorMsg() == '': - gdaltest.post_reason('fail') - return 'fail' + assert gdal.GetLastErrorMsg() != '' # Invalid SrcSRS gdal.PushErrorHandler('CPLQuietErrorHandler') @@ -1729,9 +1442,7 @@ def ogr_vrt_29(): </OGRVRTWarpedLayer> </OGRVRTDataSource>""") gdal.PopErrorHandler() - if gdal.GetLastErrorMsg() == '': - gdaltest.post_reason('fail') - return 'fail' + assert gdal.GetLastErrorMsg() != '' # TargetSRS == source SRS ds = ogr.Open("""<OGRVRTDataSource> @@ -1760,9 +1471,7 @@ def ogr_vrt_29(): </OGRVRTDataSource>""") lyr = ds.GetLayer(0) bb = lyr.GetExtent() - if bb != (426857, 485608, 5427475, 5516874): - gdaltest.post_reason('fail') - return 'fail' + assert bb == (426857, 485608, 5427475, 5516874) ds = None f = open('tmp/ogr_vrt_29.vrt', 'wt') @@ -1782,37 +1491,26 @@ def ogr_vrt_29(): sr = lyr.GetSpatialRef() got_wkt = sr.ExportToWkt() - if got_wkt.find('32631') == -1: - gdaltest.post_reason('did not get expected WKT') - print(got_wkt) - return 'fail' + assert got_wkt.find('32631') != -1, 'did not get expected WKT' bb = lyr.GetExtent() expected_bb = (426857.98771727527, 485607.2165091355, 5427475.0501426803, 5516873.8591036052) for i in range(4): - if abs(bb[i] - expected_bb[i]) > 1: - gdaltest.post_reason('did not get expected extent') - print(bb) - return 'fail' + assert abs(bb[i] - expected_bb[i]) <= 1, 'did not get expected extent' feat = lyr.GetNextFeature() if ogrtest.check_feature_geometry(feat, 'POINT(426857.987717275274917 5427937.523466162383556)') != 0: - gdaltest.post_reason('fail') feat.DumpReadable() - return 'fail' + pytest.fail() feat = lyr.GetNextFeature() feat.SetGeometry(None) - if lyr.SetFeature(feat) != 0: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.SetFeature(feat) == 0 feat.SetGeometry(ogr.CreateGeometryFromWkt('POINT(500000 0)')) - if lyr.SetFeature(feat) != 0: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.SetFeature(feat) == 0 feat = None lyr.SetSpatialFilterRect(499999, -1, 500001, 1) @@ -1820,24 +1518,19 @@ def ogr_vrt_29(): feat = lyr.GetNextFeature() if ogrtest.check_feature_geometry(feat, 'POINT(500000 0)') != 0: - gdaltest.post_reason('fail') feat.DumpReadable() - return 'fail' + pytest.fail() feat = None feat = ogr.Feature(lyr.GetLayerDefn()) feat.SetField('id', -99) feat.SetGeometry(ogr.CreateGeometryFromWkt('POINT(500000 0)')) - if lyr.CreateFeature(feat) != 0: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.CreateFeature(feat) == 0 feat = None feat = ogr.Feature(lyr.GetLayerDefn()) feat.SetField('id', -100) - if lyr.CreateFeature(feat) != 0: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.CreateFeature(feat) == 0 feat = None ds = None @@ -1849,18 +1542,14 @@ def ogr_vrt_29(): gdal.PushErrorHandler('CPLQuietErrorHandler') ret = lyr.DeleteFeature(1) gdal.PopErrorHandler() - if ret == 0: - gdaltest.post_reason('fail') - return 'fail' + assert ret != 0 feat = lyr.GetNextFeature() feat.SetGeometry(ogr.CreateGeometryFromWkt('POINT(500000 0)')) gdal.PushErrorHandler('CPLQuietErrorHandler') ret = lyr.SetFeature(feat) gdal.PopErrorHandler() - if ret == 0: - gdaltest.post_reason('fail') - return 'fail' + assert ret != 0 feat = None feat = ogr.Feature(lyr.GetLayerDefn()) @@ -1868,9 +1557,7 @@ def ogr_vrt_29(): gdal.PushErrorHandler('CPLQuietErrorHandler') ret = lyr.CreateFeature(feat) gdal.PopErrorHandler() - if ret == 0: - gdaltest.post_reason('fail') - return 'fail' + assert ret != 0 feat = None ds = None @@ -1882,25 +1569,22 @@ def ogr_vrt_29(): feat = lyr.GetNextFeature() feat = lyr.GetNextFeature() if ogrtest.check_feature_geometry(feat, 'POINT(3.0 0.0)') != 0: - gdaltest.post_reason('fail') feat.DumpReadable() - return 'fail' + pytest.fail() lyr.SetAttributeFilter('id = -99') lyr.ResetReading() feat = lyr.GetNextFeature() if ogrtest.check_feature_geometry(feat, 'POINT(3.0 0.0)') != 0: - gdaltest.post_reason('fail') feat.DumpReadable() - return 'fail' + pytest.fail() lyr.SetAttributeFilter('id = -100') lyr.ResetReading() feat = lyr.GetNextFeature() if feat.GetGeometryRef() is not None: - gdaltest.post_reason('fail') feat.DumpReadable() - return 'fail' + pytest.fail() feat = ogr.Feature(lyr.GetLayerDefn()) feat.SetField(0, 1000) @@ -1921,17 +1605,15 @@ def ogr_vrt_29(): gdal.PopErrorHandler() fid = feat.GetFID() if feat.GetGeometryRef() is not None: - gdaltest.post_reason('fail') feat.DumpReadable() - return 'fail' + pytest.fail() gdal.PushErrorHandler('CPLQuietErrorHandler') feat = lyr.GetFeature(fid) gdal.PopErrorHandler() if feat.GetGeometryRef() is not None: - gdaltest.post_reason('fail') feat.DumpReadable() - return 'fail' + pytest.fail() feat = None lyr.DeleteFeature(fid) @@ -1957,9 +1639,7 @@ def ogr_vrt_29(): gdal.PushErrorHandler('CPLQuietErrorHandler') ret = lyr.SetFeature(feat) gdal.PopErrorHandler() - if ret == 0: - gdaltest.post_reason('fail') - return 'fail' + assert ret != 0 feat = None feat = ogr.Feature(lyr.GetLayerDefn()) @@ -1967,9 +1647,7 @@ def ogr_vrt_29(): gdal.PushErrorHandler('CPLQuietErrorHandler') ret = lyr.CreateFeature(feat) gdal.PopErrorHandler() - if ret == 0: - gdaltest.post_reason('fail') - return 'fail' + assert ret != 0 feat = None ds = None @@ -1985,10 +1663,7 @@ def ogr_vrt_29(): ret = gdaltest.runexternal(test_cli_utilities.get_test_ogrsf_path() + ' -ro tmp/ogr_vrt_29.vrt') - if ret.find('INFO') == -1 or ret.find('ERROR') != -1: - gdaltest.post_reason('fail') - print(ret) - return 'fail' + assert ret.find('INFO') != -1 and ret.find('ERROR') == -1 gdal.Unlink('tmp/ogr_vrt_29.shp') gdal.Unlink('tmp/ogr_vrt_29.shx') @@ -1997,13 +1672,11 @@ def ogr_vrt_29(): os.unlink('tmp/ogr_vrt_29.vrt') os.unlink('tmp/ogr_vrt_29_2.vrt') - return 'success' - ############################################################################### # Test OGRVRTUnionLayer -def ogr_vrt_30(): +def test_ogr_vrt_30(): for filename in ['tmp/ogr_vrt_30_1.shp', 'tmp/ogr_vrt_30_1.shx', @@ -2079,122 +1752,79 @@ def ogr_vrt_30(): if check == 0: sr = lyr.GetSpatialRef() got_wkt = sr.ExportToWkt() - if got_wkt.find('GEOGCS["WGS 84"') == -1: - gdaltest.post_reason('did not get expected WKT') - print(got_wkt) - return 'fail' + assert got_wkt.find('GEOGCS["WGS 84"') != -1, 'did not get expected WKT' elif check == 1: bb = lyr.GetExtent() expected_bb = (2.0, 4.7999999999999998, 49.0, 49.799999999999997) for i in range(4): - if abs(bb[i] - expected_bb[i]) > 1: - gdaltest.post_reason('did not get expected extent') - print(bb) - return 'fail' + assert abs(bb[i] - expected_bb[i]) <= 1, 'did not get expected extent' elif check == 2: feat_count = lyr.GetFeatureCount() - if feat_count != 2 * 5 * 5: - gdaltest.post_reason('did not get expected feature count') - print(feat_count) - return 'fail' + assert feat_count == 2 * 5 * 5, 'did not get expected feature count' elif check == 3: - if lyr.GetLayerDefn().GetFieldCount() != 3: - gdaltest.post_reason('did not get expected field count') - return 'fail' - if lyr.GetLayerDefn().GetFieldDefn(1).GetType() != ogr.OFTInteger64: - gdaltest.post_reason('did not get expected field type') - return 'fail' + assert lyr.GetLayerDefn().GetFieldCount() == 3, 'did not get expected field count' + assert lyr.GetLayerDefn().GetFieldDefn(1).GetType() == ogr.OFTInteger64, \ + 'did not get expected field type' elif check == 4: feat = lyr.GetNextFeature() i = 0 while feat is not None: if i < 5 * 5: - if feat.GetFID() != i: - gdaltest.post_reason('did not get expected value') - print(feat.GetFID()) - return 'fail' - if feat.GetFieldAsInteger("id1") != i: - gdaltest.post_reason('did not get expected value') - return 'fail' - if feat.GetFieldAsInteger("id2") != 100 + i: - gdaltest.post_reason('did not get expected value') - return 'fail' - if feat.IsFieldSet("id3"): - gdaltest.post_reason('did not get expected value') - return 'fail' + assert feat.GetFID() == i, 'did not get expected value' + assert feat.GetFieldAsInteger("id1") == i, \ + 'did not get expected value' + assert feat.GetFieldAsInteger("id2") == 100 + i, \ + 'did not get expected value' + assert not feat.IsFieldSet("id3"), 'did not get expected value' if ogrtest.check_feature_geometry(feat, 'POINT(%f %f)' % (2 + int(i / 5) / 5.0, 49 + int(i % 5) / 5.0)) != 0: - gdaltest.post_reason('did not get expected value') feat.DumpReadable() - return 'fail' + pytest.fail('did not get expected value') else: - if feat.GetFID() != i: - gdaltest.post_reason('did not get expected value') - print(feat.GetFID()) - return 'fail' - if feat.IsFieldSet("id1"): - gdaltest.post_reason('did not get expected value') - return 'fail' - if feat.GetFieldAsInteger("id2") != 200 + i - 5 * 5: - gdaltest.post_reason('did not get expected value') - return 'fail' - if feat.GetFieldAsInteger("id3") != 300 + i - 5 * 5: - gdaltest.post_reason('did not get expected value') - return 'fail' - if ogrtest.check_feature_geometry(feat, 'POINT(%f %f)' % (4 + int((i - 5 * 5) / 5) / 5.0, 49 + int((i - 5 * 5) % 5) / 5.0)) != 0: - gdaltest.post_reason('did not get expected value') - return 'fail' + assert feat.GetFID() == i, 'did not get expected value' + assert not feat.IsFieldSet("id1"), 'did not get expected value' + assert feat.GetFieldAsInteger("id2") == 200 + i - 5 * 5, \ + 'did not get expected value' + assert feat.GetFieldAsInteger("id3") == 300 + i - 5 * 5, \ + 'did not get expected value' + assert ogrtest.check_feature_geometry(feat, 'POINT(%f %f)' % (4 + int((i - 5 * 5) / 5) / 5.0, 49 + int((i - 5 * 5) % 5) / 5.0)) == 0, \ + 'did not get expected value' i = i + 1 feat = lyr.GetNextFeature() elif check == 5: - if lyr.GetGeomType() != ogr.wkbPoint: - gdaltest.post_reason('did not get expected geom type') - return 'fail' + assert lyr.GetGeomType() == ogr.wkbPoint, 'did not get expected geom type' elif check == 6: - if lyr.TestCapability(ogr.OLCFastFeatureCount) != 1: - gdaltest.post_reason('did not get expected capability') - return 'fail' + assert lyr.TestCapability(ogr.OLCFastFeatureCount) == 1, \ + 'did not get expected capability' - if lyr.TestCapability(ogr.OLCFastGetExtent) != 1: - gdaltest.post_reason('did not get expected capability') - return 'fail' + assert lyr.TestCapability(ogr.OLCFastGetExtent) == 1, \ + 'did not get expected capability' - if lyr.TestCapability(ogr.OLCFastSpatialFilter) != 1: - gdaltest.post_reason('did not get expected capability') - return 'fail' + assert lyr.TestCapability(ogr.OLCFastSpatialFilter) == 1, \ + 'did not get expected capability' - if lyr.TestCapability(ogr.OLCStringsAsUTF8) != 1: - gdaltest.post_reason('did not get expected capability') - return 'fail' + assert lyr.TestCapability(ogr.OLCStringsAsUTF8) == 1, \ + 'did not get expected capability' - if lyr.TestCapability(ogr.OLCIgnoreFields) != 1: - gdaltest.post_reason('did not get expected capability') - return 'fail' + assert lyr.TestCapability(ogr.OLCIgnoreFields) == 1, \ + 'did not get expected capability' - if lyr.TestCapability(ogr.OLCRandomWrite) != 0: - gdaltest.post_reason('did not get expected capability') - return 'fail' + assert lyr.TestCapability(ogr.OLCRandomWrite) == 0, \ + 'did not get expected capability' - if lyr.TestCapability(ogr.OLCSequentialWrite) != 0: - gdaltest.post_reason('did not get expected capability') - return 'fail' + assert lyr.TestCapability(ogr.OLCSequentialWrite) == 0, \ + 'did not get expected capability' elif check == 7: lyr.SetSpatialFilterRect(2.49, 49.29, 4.49, 49.69) - if lyr.GetFeatureCount() != 10: - print(lyr.GetFeatureCount()) - gdaltest.post_reason('did not get expected feature count') - return 'fail' + assert lyr.GetFeatureCount() == 10, 'did not get expected feature count' elif check == 8: lyr.SetAttributeFilter('id1 = 0') - if lyr.GetFeatureCount() != 1: - print(lyr.GetFeatureCount()) - gdaltest.post_reason('did not get expected feature count') - return 'fail' + assert lyr.GetFeatureCount() == 1, 'did not get expected feature count' elif check == 9: # CreateFeature() should fail @@ -2203,9 +1833,7 @@ def ogr_vrt_30(): gdal.PushErrorHandler('CPLQuietErrorHandler') ret = lyr.CreateFeature(feat) gdal.PopErrorHandler() - if ret == 0: - gdaltest.post_reason('should have failed') - return 'fail' + assert ret != 0, 'should have failed' feat = None # SetFeature() should fail @@ -2215,9 +1843,7 @@ def ogr_vrt_30(): gdal.PushErrorHandler('CPLQuietErrorHandler') ret = lyr.SetFeature(feat) gdal.PopErrorHandler() - if ret == 0: - gdaltest.post_reason('should have failed') - return 'fail' + assert ret != 0, 'should have failed' feat = None # Test feature existence : should fail @@ -2225,9 +1851,7 @@ def ogr_vrt_30(): lyr.ResetReading() feat = lyr.GetNextFeature() - if feat is not None: - gdaltest.post_reason('should have failed') - return 'fail' + assert feat is None, 'should have failed' ds = None @@ -2236,17 +1860,11 @@ def ogr_vrt_30(): ret = gdaltest.runexternal(test_cli_utilities.get_test_ogrsf_path() + ' -ro tmp/ogr_vrt_30.vrt --config OGR_VRT_MAX_OPENED 1') - if ret.find('INFO') == -1 or ret.find('ERROR') != -1: - gdaltest.post_reason('fail') - print(ret) - return 'fail' + assert ret.find('INFO') != -1 and ret.find('ERROR') == -1 ret = gdaltest.runexternal(test_cli_utilities.get_test_ogrsf_path() + ' tmp/ogr_vrt_30.vrt') - if ret.find('INFO') == -1 or ret.find('ERROR') != -1: - gdaltest.post_reason('fail') - print(ret) - return 'fail' + assert ret.find('INFO') != -1 and ret.find('ERROR') == -1 # Test various optional attributes f = open('tmp/ogr_vrt_30.vrt', 'wt') @@ -2279,101 +1897,70 @@ def ogr_vrt_30(): if check == 0: sr = lyr.GetSpatialRef() got_wkt = sr.ExportToWkt() - if got_wkt.find('WGS 72') == -1: - gdaltest.post_reason('did not get expected WKT') - print(got_wkt) - return 'fail' + assert got_wkt.find('WGS 72') != -1, 'did not get expected WKT' elif check == 1: bb = lyr.GetExtent() expected_bb = (-180.0, 180.0, -90.0, 90.0) for i in range(4): - if abs(bb[i] - expected_bb[i]) > 1: - gdaltest.post_reason('did not get expected extent') - print(bb) - return 'fail' + assert abs(bb[i] - expected_bb[i]) <= 1, 'did not get expected extent' elif check == 2: - if lyr.GetFeatureCount() != 100: - gdaltest.post_reason('did not get expected feature count') - return 'fail' + assert lyr.GetFeatureCount() == 100, 'did not get expected feature count' elif check == 3: - if lyr.GetLayerDefn().GetFieldCount() != 2: - gdaltest.post_reason('did not get expected field count') - return 'fail' + assert lyr.GetLayerDefn().GetFieldCount() == 2, 'did not get expected field count' elif check == 4: feat = lyr.GetNextFeature() i = 0 while feat is not None: if i < 5 * 5: - if feat.GetFID() != i: - gdaltest.post_reason('did not get expected value') - print(feat.GetFID()) - return 'fail' - if feat.GetFieldAsString("source_layer") != 'ogr_vrt_30_1': - gdaltest.post_reason('did not get expected value') - return 'fail' - if feat.GetFieldAsInteger("id2") != 100 + i: - gdaltest.post_reason('did not get expected value') - return 'fail' + assert feat.GetFID() == i, 'did not get expected value' + assert feat.GetFieldAsString("source_layer") == 'ogr_vrt_30_1', \ + 'did not get expected value' + assert feat.GetFieldAsInteger("id2") == 100 + i, \ + 'did not get expected value' else: - if feat.GetFID() != i - 5 * 5: - gdaltest.post_reason('did not get expected value') - print(feat.GetFID()) - return 'fail' - if feat.GetFieldAsString("source_layer") != 'ogr_vrt_30_2': - gdaltest.post_reason('did not get expected value') - return 'fail' - if feat.GetFieldAsInteger("id2") != 200 + i - 5 * 5: - gdaltest.post_reason('did not get expected value') - return 'fail' + assert feat.GetFID() == i - 5 * 5, 'did not get expected value' + assert feat.GetFieldAsString("source_layer") == 'ogr_vrt_30_2', \ + 'did not get expected value' + assert feat.GetFieldAsInteger("id2") == 200 + i - 5 * 5, \ + 'did not get expected value' i = i + 1 feat = lyr.GetNextFeature() elif check == 5: - if lyr.GetGeomType() != ogr.wkbPoint25D: - gdaltest.post_reason('did not get expected geom type') - return 'fail' + assert lyr.GetGeomType() == ogr.wkbPoint25D, 'did not get expected geom type' elif check == 6: - if lyr.TestCapability(ogr.OLCFastFeatureCount) != 1: - gdaltest.post_reason('did not get expected capability') - return 'fail' + assert lyr.TestCapability(ogr.OLCFastFeatureCount) == 1, \ + 'did not get expected capability' - if lyr.TestCapability(ogr.OLCFastGetExtent) != 1: - gdaltest.post_reason('did not get expected capability') - return 'fail' + assert lyr.TestCapability(ogr.OLCFastGetExtent) == 1, \ + 'did not get expected capability' - if lyr.TestCapability(ogr.OLCFastSpatialFilter) != 1: - gdaltest.post_reason('did not get expected capability') - return 'fail' + assert lyr.TestCapability(ogr.OLCFastSpatialFilter) == 1, \ + 'did not get expected capability' - if lyr.TestCapability(ogr.OLCStringsAsUTF8) != 1: - gdaltest.post_reason('did not get expected capability') - return 'fail' + assert lyr.TestCapability(ogr.OLCStringsAsUTF8) == 1, \ + 'did not get expected capability' - if lyr.TestCapability(ogr.OLCIgnoreFields) != 1: - gdaltest.post_reason('did not get expected capability') - return 'fail' + assert lyr.TestCapability(ogr.OLCIgnoreFields) == 1, \ + 'did not get expected capability' - if lyr.TestCapability(ogr.OLCRandomWrite) != 1: - gdaltest.post_reason('did not get expected capability') - return 'fail' + assert lyr.TestCapability(ogr.OLCRandomWrite) == 1, \ + 'did not get expected capability' - if lyr.TestCapability(ogr.OLCSequentialWrite) != 1: - gdaltest.post_reason('did not get expected capability') - return 'fail' + assert lyr.TestCapability(ogr.OLCSequentialWrite) == 1, \ + 'did not get expected capability' elif check == 7: lyr.SetSpatialFilterRect(2.49, 49.29, 4.49, 49.69) - if lyr.GetFeatureCount() != 10: - gdaltest.post_reason('did not get expected feature count') - return 'fail' + assert lyr.GetFeatureCount() == 10, 'did not get expected feature count' elif check == 8: # invalid source_layer name with CreateFeature() @@ -2383,9 +1970,7 @@ def ogr_vrt_30(): gdal.PushErrorHandler('CPLQuietErrorHandler') ret = lyr.CreateFeature(feat) gdal.PopErrorHandler() - if ret == 0: - gdaltest.post_reason('should have failed') - return 'fail' + assert ret != 0, 'should have failed' feat = None # unset source_layer name with CreateFeature() @@ -2394,9 +1979,7 @@ def ogr_vrt_30(): gdal.PushErrorHandler('CPLQuietErrorHandler') ret = lyr.CreateFeature(feat) gdal.PopErrorHandler() - if ret == 0: - gdaltest.post_reason('should have failed') - return 'fail' + assert ret != 0, 'should have failed' feat = None # FID set with CreateFeature() @@ -2407,42 +1990,32 @@ def ogr_vrt_30(): gdal.PushErrorHandler('CPLQuietErrorHandler') ret = lyr.CreateFeature(feat) gdal.PopErrorHandler() - if ret == 0: - gdaltest.post_reason('should have failed') - return 'fail' + assert ret != 0, 'should have failed' feat = None # CreateFeature() OK feat = ogr.Feature(lyr.GetLayerDefn()) feat.SetField('source_layer', 'ogr_vrt_30_2') feat.SetField('id2', 12345) - if lyr.CreateFeature(feat) != 0: - gdaltest.post_reason('should have succeeded') - return 'fail' + assert lyr.CreateFeature(feat) == 0, 'should have succeeded' # SetFeature() OK feat.SetField('id2', 45321) - if lyr.SetFeature(feat) != 0: - gdaltest.post_reason('should have succeeded') - return 'fail' + assert lyr.SetFeature(feat) == 0, 'should have succeeded' # invalid source_layer name with SetFeature() feat.SetField('source_layer', 'random_name') gdal.PushErrorHandler('CPLQuietErrorHandler') ret = lyr.SetFeature(feat) gdal.PopErrorHandler() - if ret == 0: - gdaltest.post_reason('should have failed') - return 'fail' + assert ret != 0, 'should have failed' # unset source_layer name with SetFeature() feat.UnsetField('source_layer') gdal.PushErrorHandler('CPLQuietErrorHandler') ret = lyr.SetFeature(feat) gdal.PopErrorHandler() - if ret == 0: - gdaltest.post_reason('should have failed') - return 'fail' + assert ret != 0, 'should have failed' # FID unset with SetFeature() feat = ogr.Feature(lyr.GetLayerDefn()) @@ -2451,43 +2024,33 @@ def ogr_vrt_30(): gdal.PushErrorHandler('CPLQuietErrorHandler') ret = lyr.SetFeature(feat) gdal.PopErrorHandler() - if ret == 0: - gdaltest.post_reason('should have failed') - return 'fail' + assert ret != 0, 'should have failed' feat = None # Test feature existence (with passthru) lyr.SetAttributeFilter('id2 = 45321 AND OGR_GEOMETRY IS NULL') - if lyr.TestCapability(ogr.OLCFastFeatureCount) != 1: - gdaltest.post_reason('should have returned 1') - return 'fail' + assert lyr.TestCapability(ogr.OLCFastFeatureCount) == 1, \ + 'should have returned 1' lyr.ResetReading() feat = lyr.GetNextFeature() - if feat is None: - gdaltest.post_reason('should have succeeded') - return 'fail' + assert feat is not None, 'should have succeeded' # Test feature existence (without passthru) lyr.SetAttributeFilter("id2 = 45321 AND OGR_GEOMETRY IS NULL AND source_layer = 'ogr_vrt_30_2'") - if lyr.TestCapability(ogr.OLCFastFeatureCount) != 0: - gdaltest.post_reason('should have returned 0') - return 'fail' + assert lyr.TestCapability(ogr.OLCFastFeatureCount) == 0, \ + 'should have returned 0' lyr.ResetReading() feat = lyr.GetNextFeature() - if feat is None: - gdaltest.post_reason('should have succeeded') - return 'fail' + assert feat is not None, 'should have succeeded' # Test SyncToDisk() - if lyr.SyncToDisk() != 0: - gdaltest.post_reason('should have succeeded') - return 'fail' + assert lyr.SyncToDisk() == 0, 'should have succeeded' ds = None @@ -2504,13 +2067,11 @@ def ogr_vrt_30(): gdal.Unlink(filename) os.unlink('tmp/ogr_vrt_30.vrt') - return 'success' - ############################################################################### # Test anti-recursion mechanism with union layer -def ogr_vrt_31(shared_ds_flag=''): +def test_ogr_vrt_31(shared_ds_flag=''): rec1 = """<OGRVRTDataSource> <OGRVRTUnionLayer name="rec1"> @@ -2538,36 +2099,31 @@ def ogr_vrt_31(shared_ds_flag=''): gdal.FileFromMemBuffer('/vsimem/rec2.vrt', rec2) ds = ogr.Open('/vsimem/rec1.vrt') - if ds is None: - return 'fail' + assert ds is not None gdal.ErrorReset() gdal.PushErrorHandler('CPLQuietErrorHandler') ds.GetLayer(0).GetLayerDefn() ds.GetLayer(0).GetFeatureCount() gdal.PopErrorHandler() - if gdal.GetLastErrorMsg() == '': - gdaltest.post_reason('error expected !') - return 'fail' + assert gdal.GetLastErrorMsg() != '', 'error expected !' gdal.Unlink('/vsimem/rec1.vrt') gdal.Unlink('/vsimem/rec2.vrt') - return 'success' - ############################################################################### # Test anti-recursion mechanism on shared DS -def ogr_vrt_32(): +def test_ogr_vrt_32(): - return ogr_vrt_31(' shared="1"') + return test_ogr_vrt_31(' shared="1"') ############################################################################### # Test multi-geometry support -def ogr_vrt_33(): +def test_ogr_vrt_33(): try: import shutil @@ -2632,34 +2188,22 @@ def ogr_vrt_33(): lyr = ds.GetLayer(0) for j in range(5): if j == 0: - if lyr.GetGeomType() != ogr.wkbPoint: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.GetGeomType() == ogr.wkbPoint elif j == 1: - if lyr.GetSpatialRef().ExportToWkt().find('GEOGCS') != 0: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.GetSpatialRef().ExportToWkt().find('GEOGCS') == 0 elif j == 2: - if lyr.GetLayerDefn().GetGeomFieldDefn(1).GetType() != ogr.wkbPolygon: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.GetLayerDefn().GetGeomFieldDefn(1).GetType() == ogr.wkbPolygon elif j == 3: - if lyr.GetExtent(geom_field=1) != (0, 1, 0, 1): - gdaltest.post_reason('fail') - return 'fail' + assert lyr.GetExtent(geom_field=1) == (0, 1, 0, 1) elif j == 4: - if lyr.GetLayerDefn().GetGeomFieldDefn(1).GetSpatialRef().ExportToWkt().find('PROJCS') != 0: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.GetLayerDefn().GetGeomFieldDefn(1).GetSpatialRef().ExportToWkt().find('PROJCS') == 0 feat = lyr.GetNextFeature() if feat.GetGeomFieldRef(0).ExportToWkt() != 'POINT (1 2)': - gdaltest.post_reason('fail') feat.DumpReadable() - return 'fail' + pytest.fail() if feat.GetGeomFieldRef(1).ExportToWkt() != 'POLYGON ((0 0,0 1,1 1,1 0,0 0))': - gdaltest.post_reason('fail') feat.DumpReadable() - return 'fail' + pytest.fail() if test_cli_utilities.get_test_ogrsf_path() is not None: f = open('tmp/ogr_vrt_33.vrt', 'wb') @@ -2668,10 +2212,7 @@ def ogr_vrt_33(): ret = gdaltest.runexternal(test_cli_utilities.get_test_ogrsf_path() + ' -ro tmp/ogr_vrt_33.vrt') os.unlink('tmp/ogr_vrt_33.vrt') - if ret.find('INFO') == -1 or ret.find('ERROR') != -1: - gdaltest.post_reason('fail') - print(ret) - return 'fail' + assert ret.find('INFO') != -1 and ret.find('ERROR') == -1 if ogrtest.have_geos(): # Select only second field and change various attributes @@ -2693,38 +2234,22 @@ def ogr_vrt_33(): ds = ogr.Open(ds_str) lyr = ds.GetLayer(0) if i == 0: - if lyr.GetGeomType() != ogr.wkbPolygon25D: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.GetGeomType() == ogr.wkbPolygon25D elif i == 1: - if lyr.GetSpatialRef().ExportToWkt().find('+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') - return 'fail' + assert lyr.GetSpatialRef().ExportToWkt().find('+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 elif i == 2: - if lyr.GetGeometryColumn() != 'foo': - gdaltest.post_reason('fail') - return 'fail' + assert lyr.GetGeometryColumn() == 'foo' elif i == 3: - if lyr.TestCapability(ogr.OLCFastGetExtent) != 1: - gdaltest.post_reason('fail') - return 'fail' - if lyr.GetExtent(geom_field=0) != (1, 3, 2, 4): - gdaltest.post_reason('fail') - print(lyr.GetExtent(geom_field=0)) - return 'fail' + assert lyr.TestCapability(ogr.OLCFastGetExtent) == 1 + assert lyr.GetExtent(geom_field=0) == (1, 3, 2, 4) elif i == 4: - if lyr.TestCapability(ogr.OLCFastFeatureCount) != 0: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.TestCapability(ogr.OLCFastFeatureCount) == 0 elif i == 5: - if lyr.GetLayerDefn().GetGeomFieldCount() != 1: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.GetLayerDefn().GetGeomFieldCount() == 1 feat = lyr.GetNextFeature() if feat.GetGeomFieldRef(0).ExportToWkt() != 'POLYGON ((0.5 1.0,1 1,1.0 0.5,0.5 0.5,0.5 1.0))': - gdaltest.post_reason('fail') feat.DumpReadable() - return 'fail' + pytest.fail() if test_cli_utilities.get_test_ogrsf_path() is not None: f = open('tmp/ogr_vrt_33.vrt', 'wb') @@ -2733,10 +2258,7 @@ def ogr_vrt_33(): ret = gdaltest.runexternal(test_cli_utilities.get_test_ogrsf_path() + ' -ro tmp/ogr_vrt_33.vrt') os.unlink('tmp/ogr_vrt_33.vrt') - if ret.find('INFO') == -1 or ret.find('ERROR') != -1: - gdaltest.post_reason('fail') - print(ret) - return 'fail' + assert ret.find('INFO') != -1 and ret.find('ERROR') == -1 # No geometry fields ds_str = """<OGRVRTDataSource> @@ -2749,26 +2271,19 @@ def ogr_vrt_33(): ds = ogr.Open(ds_str) lyr = ds.GetLayer(0) if i == 0: - if lyr.GetGeomType() != ogr.wkbNone: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.GetGeomType() == ogr.wkbNone elif i == 1: - if lyr.GetSpatialRef() is not None: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.GetSpatialRef() is None elif i == 2: lyr.TestCapability(ogr.OLCFastFeatureCount) lyr.TestCapability(ogr.OLCFastGetExtent) lyr.TestCapability(ogr.OLCFastSpatialFilter) elif i == 3: - if lyr.GetLayerDefn().GetGeomFieldCount() != 0: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.GetLayerDefn().GetGeomFieldCount() == 0 feat = lyr.GetNextFeature() if feat.GetGeomFieldRef(0) is not None: - gdaltest.post_reason('fail') feat.DumpReadable() - return 'fail' + pytest.fail() if test_cli_utilities.get_test_ogrsf_path() is not None: f = open('tmp/ogr_vrt_33.vrt', 'wb') @@ -2777,10 +2292,7 @@ def ogr_vrt_33(): ret = gdaltest.runexternal(test_cli_utilities.get_test_ogrsf_path() + ' -ro tmp/ogr_vrt_33.vrt') os.unlink('tmp/ogr_vrt_33.vrt') - if ret.find('INFO') == -1 or ret.find('ERROR') != -1: - gdaltest.post_reason('fail') - print(ret) - return 'fail' + assert ret.find('INFO') != -1 and ret.find('ERROR') == -1 ds_str = """<OGRVRTDataSource> <OGRVRTLayer name="test"> @@ -2794,49 +2306,35 @@ def ogr_vrt_33(): """ ds = ogr.Open(ds_str) lyr = ds.GetLayer(0) - if lyr.GetLayerDefn().GetGeomFieldDefn(1).GetType() != ogr.wkbPoint: - gdaltest.post_reason('fail') - return 'fail' - if lyr.GetLayerDefn().GetGeomFieldDefn(1).GetSpatialRef().ExportToWkt().find('4326') < 0: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.GetLayerDefn().GetGeomFieldDefn(1).GetType() == ogr.wkbPoint + assert lyr.GetLayerDefn().GetGeomFieldDefn(1).GetSpatialRef().ExportToWkt().find('4326') >= 0 feat = lyr.GetNextFeature() if feat.GetGeomFieldRef(0).ExportToWkt() != 'POINT (1 2)': - gdaltest.post_reason('fail') feat.DumpReadable() - return 'fail' + pytest.fail() if feat.GetGeomFieldRef(1).ExportToWkt() != 'POINT (-1 -2)': - gdaltest.post_reason('fail') feat.DumpReadable() - return 'fail' + pytest.fail() lyr.SetSpatialFilterRect(1, 0, 0, 0, 0) - if lyr.GetFeatureCount() != 0: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.GetFeatureCount() == 0 lyr.SetSpatialFilterRect(1, -1.1, -2.1, -0.9, -1.9) - if lyr.GetFeatureCount() != 1: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.GetFeatureCount() == 1 lyr.SetSpatialFilter(1, None) - if lyr.GetFeatureCount() != 1: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.GetFeatureCount() == 1 lyr.SetIgnoredFields(['geom__WKT_EPSG_4326_POINT']) lyr.ResetReading() feat = lyr.GetNextFeature() if feat.GetGeomFieldRef(0) is not None or \ feat.GetGeomFieldRef(1).ExportToWkt() != 'POINT (-1 -2)': - gdaltest.post_reason('fail') feat.DumpReadable() - return 'fail' + pytest.fail() lyr.SetIgnoredFields(['foo']) lyr.ResetReading() feat = lyr.GetNextFeature() if feat.GetGeomFieldRef(1) is not None or \ feat.GetGeomFieldRef(0).ExportToWkt() != 'POINT (1 2)': - gdaltest.post_reason('fail') feat.DumpReadable() - return 'fail' + pytest.fail() if test_cli_utilities.get_test_ogrsf_path() is not None: f = open('tmp/ogr_vrt_33.vrt', 'wb') @@ -2845,10 +2343,7 @@ def ogr_vrt_33(): ret = gdaltest.runexternal(test_cli_utilities.get_test_ogrsf_path() + ' -ro tmp/ogr_vrt_33.vrt') os.unlink('tmp/ogr_vrt_33.vrt') - if ret.find('INFO') == -1 or ret.find('ERROR') != -1: - gdaltest.post_reason('fail') - print(ret) - return 'fail' + assert ret.find('INFO') != -1 and ret.find('ERROR') == -1 # Warped layer without explicit WarpedGeomFieldName ds_str = """<OGRVRTDataSource> @@ -2861,16 +2356,13 @@ def ogr_vrt_33(): </OGRVRTDataSource>""" ds = ogr.Open(ds_str) lyr = ds.GetLayer(0) - if lyr.GetSpatialRef().ExportToWkt().find('32631') < 0: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.GetSpatialRef().ExportToWkt().find('32631') >= 0 feat = lyr.GetNextFeature() if feat.GetGeomFieldRef(0).ExportToWkt().find('POINT') < 0 or \ feat.GetGeomFieldRef(0).ExportToWkt() == 'POINT (1 2)' or \ feat.GetGeomFieldRef(1).ExportToWkt() != 'POLYGON ((0 0,0 1,1 1,1 0,0 0))': - gdaltest.post_reason('fail') feat.DumpReadable() - return 'fail' + pytest.fail() # Warped layer with explicit WarpedGeomFieldName (that is the first field) ds_str = """<OGRVRTDataSource> @@ -2884,16 +2376,13 @@ def ogr_vrt_33(): </OGRVRTDataSource>""" ds = ogr.Open(ds_str) lyr = ds.GetLayer(0) - if lyr.GetSpatialRef().ExportToWkt().find('32631') < 0: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.GetSpatialRef().ExportToWkt().find('32631') >= 0 feat = lyr.GetNextFeature() if feat.GetGeomFieldRef(0).ExportToWkt().find('POINT') < 0 or \ feat.GetGeomFieldRef(0).ExportToWkt() == 'POINT (1 2)' or \ feat.GetGeomFieldRef(1).ExportToWkt() != 'POLYGON ((0 0,0 1,1 1,1 0,0 0))': - gdaltest.post_reason('fail') feat.DumpReadable() - return 'fail' + pytest.fail() # Warped layer with explicit WarpedGeomFieldName (that does NOT exist) ds_str = """<OGRVRTDataSource> @@ -2908,9 +2397,7 @@ def ogr_vrt_33(): gdal.PushErrorHandler('CPLQuietErrorHandler') ogr.Open(ds_str) gdal.PopErrorHandler() - if gdal.GetLastErrorMsg() == '': - gdaltest.post_reason('fail') - return 'fail' + assert gdal.GetLastErrorMsg() != '' # Warped layer with explicit WarpedGeomFieldName (that is the second field) ds_str = """<OGRVRTDataSource> @@ -2924,16 +2411,13 @@ def ogr_vrt_33(): </OGRVRTDataSource>""" ds = ogr.Open(ds_str) lyr = ds.GetLayer(0) - if lyr.GetLayerDefn().GetGeomFieldDefn(1).GetSpatialRef().ExportToWkt().find('4326') < 0: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.GetLayerDefn().GetGeomFieldDefn(1).GetSpatialRef().ExportToWkt().find('4326') >= 0 feat = lyr.GetNextFeature() if feat.GetGeomFieldRef(1).ExportToWkt().find('POLYGON') < 0 or \ feat.GetGeomFieldRef(1).ExportToWkt() == 'POLYGON ((0 0,0 1,1 1,1 0,0 0))' or \ feat.GetGeomFieldRef(0).ExportToWkt() != 'POINT (1 2)': - gdaltest.post_reason('fail') feat.DumpReadable() - return 'fail' + pytest.fail() # UnionLayer with default union strategy @@ -2953,36 +2437,26 @@ def ogr_vrt_33(): ['geom__WKT_EPSG_32632_POLYGON', ogr.wkbPolygon, '32632'], ['geom__WKT_EPSG_4326_LINESTRING', ogr.wkbLineString, '4326'], ['geom__WKT_EPSG_32631_POINT', ogr.wkbPoint, '32631']] - if lyr.GetLayerDefn().GetGeomFieldCount() != len(geom_fields): - gdaltest.post_reason('fail') - return 'fail' + assert lyr.GetLayerDefn().GetGeomFieldCount() == len(geom_fields) for i, geom_field in enumerate(geom_fields): - if lyr.GetLayerDefn().GetGeomFieldDefn(i).GetName() != geom_field[0]: - gdaltest.post_reason('fail') - return 'fail' - if lyr.GetLayerDefn().GetGeomFieldDefn(i).GetType() != geom_field[1]: - gdaltest.post_reason('fail') - return 'fail' - if lyr.GetLayerDefn().GetGeomFieldDefn(i).GetSpatialRef().ExportToWkt().find(geom_field[2]) < 0: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.GetLayerDefn().GetGeomFieldDefn(i).GetName() == geom_field[0] + assert lyr.GetLayerDefn().GetGeomFieldDefn(i).GetType() == geom_field[1] + assert lyr.GetLayerDefn().GetGeomFieldDefn(i).GetSpatialRef().ExportToWkt().find(geom_field[2]) >= 0 feat = lyr.GetNextFeature() if feat.GetGeomFieldRef(0).ExportToWkt() != 'POINT (1 2)' or \ feat.GetGeomFieldRef(1).ExportToWkt() != 'POLYGON ((0 0,0 1,1 1,1 0,0 0))' or \ feat.GetGeomFieldRef(2) is not None or \ feat.GetGeomFieldRef(3) is not None: - gdaltest.post_reason('fail') feat.DumpReadable() - return 'fail' + pytest.fail() feat = lyr.GetNextFeature() if feat.GetGeomFieldRef(0).ExportToWkt() != 'POINT (3 4)' or \ feat.GetGeomFieldRef(1).ExportToWkt() != 'POLYGON ((1 1,1 2,2 2,2 1,1 1))' or \ feat.GetGeomFieldRef(2) is not None or \ feat.GetGeomFieldRef(3).ExportToWkt() != 'POINT (5 6)': - gdaltest.post_reason('fail') feat.DumpReadable() - return 'fail' + pytest.fail() ds = None @@ -2993,10 +2467,7 @@ def ogr_vrt_33(): ret = gdaltest.runexternal(test_cli_utilities.get_test_ogrsf_path() + ' -ro tmp/ogr_vrt_33.vrt') os.unlink('tmp/ogr_vrt_33.vrt') - if ret.find('INFO') == -1 or ret.find('ERROR') != -1: - gdaltest.post_reason('fail') - print(ret) - return 'fail' + assert ret.find('INFO') != -1 and ret.find('ERROR') == -1 # UnionLayer with intersection strategy @@ -3015,32 +2486,22 @@ def ogr_vrt_33(): lyr = ds.GetLayer(0) geom_fields = [['geom__WKT_EPSG_4326_POINT', ogr.wkbPoint, '4326'], ['geom__WKT_EPSG_32632_POLYGON', ogr.wkbPolygon, '32632']] - if lyr.GetLayerDefn().GetGeomFieldCount() != len(geom_fields): - gdaltest.post_reason('fail') - return 'fail' + assert lyr.GetLayerDefn().GetGeomFieldCount() == len(geom_fields) for i, geom_field in enumerate(geom_fields): - if lyr.GetLayerDefn().GetGeomFieldDefn(i).GetName() != geom_field[0]: - gdaltest.post_reason('fail') - return 'fail' - if lyr.GetLayerDefn().GetGeomFieldDefn(i).GetType() != geom_field[1]: - gdaltest.post_reason('fail') - return 'fail' - if lyr.GetLayerDefn().GetGeomFieldDefn(i).GetSpatialRef().ExportToWkt().find(geom_field[2]) < 0: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.GetLayerDefn().GetGeomFieldDefn(i).GetName() == geom_field[0] + assert lyr.GetLayerDefn().GetGeomFieldDefn(i).GetType() == geom_field[1] + assert lyr.GetLayerDefn().GetGeomFieldDefn(i).GetSpatialRef().ExportToWkt().find(geom_field[2]) >= 0 feat = lyr.GetNextFeature() if feat.GetGeomFieldRef(0).ExportToWkt() != 'POINT (1 2)' or \ feat.GetGeomFieldRef(1).ExportToWkt() != 'POLYGON ((0 0,0 1,1 1,1 0,0 0))': - gdaltest.post_reason('fail') feat.DumpReadable() - return 'fail' + pytest.fail() feat = lyr.GetNextFeature() if feat.GetGeomFieldRef(0).ExportToWkt() != 'POINT (3 4)' or \ feat.GetGeomFieldRef(1).ExportToWkt() != 'POLYGON ((1 1,1 2,2 2,2 1,1 1))': - gdaltest.post_reason('fail') feat.DumpReadable() - return 'fail' + pytest.fail() ds = None @@ -3051,10 +2512,7 @@ def ogr_vrt_33(): ret = gdaltest.runexternal(test_cli_utilities.get_test_ogrsf_path() + ' -ro tmp/ogr_vrt_33.vrt') os.unlink('tmp/ogr_vrt_33.vrt') - if ret.find('INFO') == -1 or ret.find('ERROR') != -1: - gdaltest.post_reason('fail') - print(ret) - return 'fail' + assert ret.find('INFO') != -1 and ret.find('ERROR') == -1 # UnionLayer with FirstLayer strategy @@ -3074,32 +2532,22 @@ def ogr_vrt_33(): geom_fields = [['geom__WKT_EPSG_4326_POINT', ogr.wkbPoint, '4326'], ['geom__WKT_EPSG_32632_POLYGON', ogr.wkbPolygon, '32632'], ['geom__WKT_EPSG_4326_LINESTRING', ogr.wkbLineString, '4326']] - if lyr.GetLayerDefn().GetGeomFieldCount() != len(geom_fields): - gdaltest.post_reason('fail') - return 'fail' + assert lyr.GetLayerDefn().GetGeomFieldCount() == len(geom_fields) for i, geom_field in enumerate(geom_fields): - if lyr.GetLayerDefn().GetGeomFieldDefn(i).GetName() != geom_field[0]: - gdaltest.post_reason('fail') - return 'fail' - if lyr.GetLayerDefn().GetGeomFieldDefn(i).GetType() != geom_field[1]: - gdaltest.post_reason('fail') - return 'fail' - if lyr.GetLayerDefn().GetGeomFieldDefn(i).GetSpatialRef().ExportToWkt().find(geom_field[2]) < 0: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.GetLayerDefn().GetGeomFieldDefn(i).GetName() == geom_field[0] + assert lyr.GetLayerDefn().GetGeomFieldDefn(i).GetType() == geom_field[1] + assert lyr.GetLayerDefn().GetGeomFieldDefn(i).GetSpatialRef().ExportToWkt().find(geom_field[2]) >= 0 feat = lyr.GetNextFeature() if feat.GetGeomFieldRef(0).ExportToWkt() != 'POINT (1 2)' or \ feat.GetGeomFieldRef(1).ExportToWkt() != 'POLYGON ((0 0,0 1,1 1,1 0,0 0))': - gdaltest.post_reason('fail') feat.DumpReadable() - return 'fail' + pytest.fail() feat = lyr.GetNextFeature() if feat.GetGeomFieldRef(0).ExportToWkt() != 'POINT (3 4)' or \ feat.GetGeomFieldRef(1).ExportToWkt() != 'POLYGON ((1 1,1 2,2 2,2 1,1 1))': - gdaltest.post_reason('fail') feat.DumpReadable() - return 'fail' + pytest.fail() ds = None @@ -3110,10 +2558,7 @@ def ogr_vrt_33(): ret = gdaltest.runexternal(test_cli_utilities.get_test_ogrsf_path() + ' -ro tmp/ogr_vrt_33.vrt') os.unlink('tmp/ogr_vrt_33.vrt') - if ret.find('INFO') == -1 or ret.find('ERROR') != -1: - gdaltest.post_reason('fail') - print(ret) - return 'fail' + assert ret.find('INFO') != -1 and ret.find('ERROR') == -1 # UnionLayer with explicit fields but without further information @@ -3133,28 +2578,16 @@ def ogr_vrt_33(): lyr = ds.GetLayer(0) geom_fields = [['geom__WKT_EPSG_32632_POLYGON', ogr.wkbPolygon, '32632'], ['geom__WKT_EPSG_4326_POINT', ogr.wkbPoint, '4326']] - if lyr.GetLayerDefn().GetGeomFieldCount() != len(geom_fields): - gdaltest.post_reason('fail') - return 'fail' + assert lyr.GetLayerDefn().GetGeomFieldCount() == len(geom_fields) for i, geom_field in enumerate(geom_fields): - if lyr.GetLayerDefn().GetGeomFieldDefn(i).GetName() != geom_field[0]: - gdaltest.post_reason('fail') - return 'fail' - if lyr.GetLayerDefn().GetGeomFieldDefn(i).GetType() != geom_field[1]: - print(i) - print(lyr.GetLayerDefn().GetGeomFieldDefn(i).GetType()) - print(geom_field[1]) - gdaltest.post_reason('fail') - return 'fail' - if lyr.GetLayerDefn().GetGeomFieldDefn(i).GetSpatialRef().ExportToWkt().find(geom_field[2]) < 0: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.GetLayerDefn().GetGeomFieldDefn(i).GetName() == geom_field[0] + assert lyr.GetLayerDefn().GetGeomFieldDefn(i).GetType() == geom_field[1] + assert lyr.GetLayerDefn().GetGeomFieldDefn(i).GetSpatialRef().ExportToWkt().find(geom_field[2]) >= 0 feat = lyr.GetNextFeature() if feat.GetGeomFieldRef(0).ExportToWkt() != 'POLYGON ((0 0,0 1,1 1,1 0,0 0))' or \ feat.GetGeomFieldRef(1).ExportToWkt() != 'POINT (1 2)': - gdaltest.post_reason('fail') feat.DumpReadable() - return 'fail' + pytest.fail() ds = None @@ -3165,10 +2598,7 @@ def ogr_vrt_33(): ret = gdaltest.runexternal(test_cli_utilities.get_test_ogrsf_path() + ' -ro tmp/ogr_vrt_33.vrt') os.unlink('tmp/ogr_vrt_33.vrt') - if ret.find('INFO') == -1 or ret.find('ERROR') != -1: - gdaltest.post_reason('fail') - print(ret) - return 'fail' + assert ret.find('INFO') != -1 and ret.find('ERROR') == -1 # UnionLayer with explicit fields with extra information @@ -3196,34 +2626,19 @@ def ogr_vrt_33(): lyr = ds.GetLayer(0) geom_fields = [['geom__WKT_EPSG_32632_POLYGON', ogr.wkbPolygon25D, '32632'], ['geom__WKT_EPSG_4326_POINT', ogr.wkbPoint, '4322']] - if lyr.GetLayerDefn().GetGeomFieldCount() != len(geom_fields): - gdaltest.post_reason('fail') - return 'fail' + assert lyr.GetLayerDefn().GetGeomFieldCount() == len(geom_fields) bb = lyr.GetExtent(geom_field=1) - if bb != (1, 3, 2, 4): - gdaltest.post_reason('fail') - print(bb) - return 'fail' + assert bb == (1, 3, 2, 4) for i, geom_field in enumerate(geom_fields): - if lyr.GetLayerDefn().GetGeomFieldDefn(i).GetName() != geom_field[0]: - gdaltest.post_reason('fail') - return 'fail' - if lyr.GetLayerDefn().GetGeomFieldDefn(i).GetType() != geom_field[1]: - print(i) - print(lyr.GetLayerDefn().GetGeomFieldDefn(i).GetType()) - print(geom_field[1]) - gdaltest.post_reason('fail') - return 'fail' - if lyr.GetLayerDefn().GetGeomFieldDefn(i).GetSpatialRef().ExportToWkt().find(geom_field[2]) < 0: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.GetLayerDefn().GetGeomFieldDefn(i).GetName() == geom_field[0] + assert lyr.GetLayerDefn().GetGeomFieldDefn(i).GetType() == geom_field[1] + assert lyr.GetLayerDefn().GetGeomFieldDefn(i).GetSpatialRef().ExportToWkt().find(geom_field[2]) >= 0 feat = lyr.GetNextFeature() if feat.GetGeomFieldRef(0).ExportToWkt() != 'POLYGON ((0 0,0 1,1 1,1 0,0 0))' or \ feat.GetGeomFieldRef(1).ExportToWkt().find('POINT (') != 0 or \ feat.GetGeomFieldRef(1).ExportToWkt() == 'POINT (1 2)': - gdaltest.post_reason('fail') feat.DumpReadable() - return 'fail' + pytest.fail() ds = None if test_cli_utilities.get_test_ogrsf_path() is not None: @@ -3233,10 +2648,7 @@ def ogr_vrt_33(): ret = gdaltest.runexternal(test_cli_utilities.get_test_ogrsf_path() + ' -ro tmp/ogr_vrt_33.vrt') os.unlink('tmp/ogr_vrt_33.vrt') - if ret.find('INFO') == -1 or ret.find('ERROR') != -1: - gdaltest.post_reason('fail') - print(ret) - return 'fail' + assert ret.find('INFO') != -1 and ret.find('ERROR') == -1 # UnionLayer with geometry fields disabled @@ -3253,18 +2665,11 @@ def ogr_vrt_33(): </OGRVRTDataSource>""" ds = ogr.Open(ds_str) lyr = ds.GetLayer(0) - if lyr.GetLayerDefn().GetGeomFieldCount() != 0: - print(lyr.GetLayerDefn().GetGeomFieldCount()) - gdaltest.post_reason('fail') - return 'fail' - if lyr.GetLayerDefn().GetFieldCount() != 6: - print(lyr.GetLayerDefn().GetGeomFieldCount()) - gdaltest.post_reason('fail') - return 'fail' + assert lyr.GetLayerDefn().GetGeomFieldCount() == 0 + assert lyr.GetLayerDefn().GetFieldCount() == 6, \ + lyr.GetLayerDefn().GetGeomFieldCount() feat = lyr.GetNextFeature() - if feat is None: - gdaltest.post_reason('fail') - return 'fail' + assert feat is not None ds = None @@ -3275,10 +2680,7 @@ def ogr_vrt_33(): ret = gdaltest.runexternal(test_cli_utilities.get_test_ogrsf_path() + ' -ro tmp/ogr_vrt_33.vrt') os.unlink('tmp/ogr_vrt_33.vrt') - if ret.find('INFO') == -1 or ret.find('ERROR') != -1: - gdaltest.post_reason('fail') - print(ret) - return 'fail' + assert ret.find('INFO') != -1 and ret.find('ERROR') == -1 ds = ogr.Open('tmp/ogr_vrt_33') sql_lyr = ds.ExecuteSQL('SELECT * FROM test UNION ALL SELECT * FROM test2') @@ -3286,48 +2688,36 @@ def ogr_vrt_33(): ['geom__WKT_EPSG_32632_POLYGON', ogr.wkbPolygon, '32632'], ['geom__WKT_EPSG_4326_LINESTRING', ogr.wkbLineString, '4326'], ['geom__WKT_EPSG_32631_POINT', ogr.wkbPoint, '32631']] - if sql_lyr.GetLayerDefn().GetGeomFieldCount() != len(geom_fields): - gdaltest.post_reason('fail') - return 'fail' + assert sql_lyr.GetLayerDefn().GetGeomFieldCount() == len(geom_fields) for i, geom_field in enumerate(geom_fields): - if sql_lyr.GetLayerDefn().GetGeomFieldDefn(i).GetName() != geom_field[0]: - gdaltest.post_reason('fail') - return 'fail' - if sql_lyr.GetLayerDefn().GetGeomFieldDefn(i).GetType() != geom_field[1]: - gdaltest.post_reason('fail') - return 'fail' - if sql_lyr.GetLayerDefn().GetGeomFieldDefn(i).GetSpatialRef().ExportToWkt().find(geom_field[2]) < 0: - gdaltest.post_reason('fail') - return 'fail' + assert sql_lyr.GetLayerDefn().GetGeomFieldDefn(i).GetName() == geom_field[0] + assert sql_lyr.GetLayerDefn().GetGeomFieldDefn(i).GetType() == geom_field[1] + assert sql_lyr.GetLayerDefn().GetGeomFieldDefn(i).GetSpatialRef().ExportToWkt().find(geom_field[2]) >= 0 feat = sql_lyr.GetNextFeature() if feat.GetGeomFieldRef(0).ExportToWkt() != 'POINT (1 2)' or \ feat.GetGeomFieldRef(1).ExportToWkt() != 'POLYGON ((0 0,0 1,1 1,1 0,0 0))' or \ feat.GetGeomFieldRef(2) is not None or \ feat.GetGeomFieldRef(3) is not None: - gdaltest.post_reason('fail') feat.DumpReadable() - return 'fail' + pytest.fail() feat = sql_lyr.GetNextFeature() if feat.GetGeomFieldRef(0).ExportToWkt() != 'POINT (3 4)' or \ feat.GetGeomFieldRef(1).ExportToWkt() != 'POLYGON ((1 1,1 2,2 2,2 1,1 1))' or \ feat.GetGeomFieldRef(2) is not None or \ feat.GetGeomFieldRef(3).ExportToWkt() != 'POINT (5 6)': - gdaltest.post_reason('fail') feat.DumpReadable() - return 'fail' + pytest.fail() ds.ReleaseResultSet(sql_lyr) ds = None - return 'success' - ############################################################################### # Test SetIgnoredFields() with with PointFromColumns geometries -def ogr_vrt_34(): +def test_ogr_vrt_34(): if gdaltest.vrt_ds is None: - return 'skip' + pytest.skip() f = open('tmp/test.csv', 'wb') f.write('x,y\n'.encode('ascii')) @@ -3356,20 +2746,18 @@ def ogr_vrt_34(): f = lyr.GetNextFeature() if f.GetGeometryRef().ExportToWkt() != 'POINT (2 49)': f.DumpReadable() - return 'fail' + pytest.fail() ds = None os.unlink('tmp/test.csv') - return 'success' - ############################################################################### # Test nullable fields -def ogr_vrt_35(): +def test_ogr_vrt_35(): if gdaltest.vrt_ds is None: - return 'skip' + pytest.skip() f = open('tmp/test.csv', 'wb') f.write('c1,c2,WKT,WKT2\n'.encode('ascii')) @@ -3397,18 +2785,10 @@ def ogr_vrt_35(): ds = ogr.Open('tmp/test.vrt') lyr = ds.GetLayerByName('test') - if lyr.GetLayerDefn().GetFieldDefn(0).IsNullable() != 0: - gdaltest.post_reason('fail') - return 'fail' - if lyr.GetLayerDefn().GetFieldDefn(1).IsNullable() != 1: - gdaltest.post_reason('fail') - return 'fail' - if lyr.GetLayerDefn().GetGeomFieldDefn(0).IsNullable() != 0: - gdaltest.post_reason('fail') - return 'fail' - if lyr.GetLayerDefn().GetGeomFieldDefn(1).IsNullable() != 1: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.GetLayerDefn().GetFieldDefn(0).IsNullable() == 0 + assert lyr.GetLayerDefn().GetFieldDefn(1).IsNullable() == 1 + assert lyr.GetLayerDefn().GetGeomFieldDefn(0).IsNullable() == 0 + assert lyr.GetLayerDefn().GetGeomFieldDefn(1).IsNullable() == 1 ds = None # Implicit nullable @@ -3423,33 +2803,23 @@ def ogr_vrt_35(): ds = ogr.Open('tmp/test2.vrt') lyr = ds.GetLayerByName('test') - if lyr.GetLayerDefn().GetFieldDefn(0).IsNullable() != 0: - gdaltest.post_reason('fail') - return 'fail' - if lyr.GetLayerDefn().GetFieldDefn(1).IsNullable() != 1: - gdaltest.post_reason('fail') - return 'fail' - if lyr.GetLayerDefn().GetGeomFieldDefn(0).IsNullable() != 0: - gdaltest.post_reason('fail') - return 'fail' - if lyr.GetLayerDefn().GetGeomFieldDefn(1).IsNullable() != 1: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.GetLayerDefn().GetFieldDefn(0).IsNullable() == 0 + assert lyr.GetLayerDefn().GetFieldDefn(1).IsNullable() == 1 + assert lyr.GetLayerDefn().GetGeomFieldDefn(0).IsNullable() == 0 + assert lyr.GetLayerDefn().GetGeomFieldDefn(1).IsNullable() == 1 ds = None os.unlink('tmp/test.csv') os.unlink('tmp/test.vrt') os.unlink('tmp/test2.vrt') - return 'success' - ############################################################################### # Test editing direct geometries -def ogr_vrt_36(): +def test_ogr_vrt_36(): if gdaltest.vrt_ds is None: - return 'skip' + pytest.skip() ds = ogr.GetDriverByName('ESRI Shapefile').CreateDataSource('/vsimem/ogr_vrt_36.shp') lyr = ds.CreateLayer('ogr_vrt_36', geom_type=ogr.wkbPoint) @@ -3480,47 +2850,38 @@ def ogr_vrt_36(): lyr = ds.GetLayer(0) f = lyr.GetNextFeature() if f['id'] != '1': - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' + pytest.fail() ds = None ogr.GetDriverByName('ESRI Shapefile').DeleteDataSource('/vsimem/ogr_vrt_36.shp') gdal.Unlink('/vsimem/ogr_vrt_36.vrt') - return 'success' - ############################################################################### # Test implict non-spatial layers (#6336) -def ogr_vrt_37(): +def test_ogr_vrt_37(): with gdaltest.error_handler(): ds = ogr.Open('data/vrt_test.vrt') lyr = ds.GetLayerByName('test6') - if lyr.GetGeomType() != ogr.wkbNone: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.GetGeomType() == ogr.wkbNone with gdaltest.error_handler(): ds = ogr.Open('data/vrt_test.vrt') lyr = ds.GetLayerByName('test6') - if lyr.GetLayerDefn().GetGeomFieldCount() != 0: - gdaltest.post_reason('fail') - return 'fail' - - return 'success' + assert lyr.GetLayerDefn().GetGeomFieldCount() == 0 ############################################################################### # Test reading geometry type -def ogr_vrt_38(): +def test_ogr_vrt_38(): if gdaltest.vrt_ds is None: - return 'skip' + pytest.skip() types = [['Point', ogr.wkbPoint], ['LineString', ogr.wkbLineString], @@ -3560,22 +2921,18 @@ def ogr_vrt_38(): ds = ogr.Open('/vsimem/ogr_vrt_38.vrt', update=1) lyr = ds.GetLayer(0) - if lyr.GetGeomType() != expected_geom_type: - gdaltest.post_reason('failure') - print(type_str, qualifier, lyr.GetGeomType()) - return 'fail' + assert lyr.GetGeomType() == expected_geom_type, \ + (type_str, qualifier, lyr.GetGeomType()) gdal.Unlink('/vsimem/ogr_vrt_38.vrt') - return 'success' - ############################################################################### # Test that attribute filtering works with <FID> -def ogr_vrt_39(): +def test_ogr_vrt_39(): if gdaltest.vrt_ds is None: - return 'skip' + pytest.skip() gdal.FileFromMemBuffer('/vsimem/ogr_vrt_39.csv', """my_fid,val @@ -3602,24 +2959,21 @@ def ogr_vrt_39(): lyr.SetAttributeFilter('fid = 25') f = lyr.GetNextFeature() if f['val'] != 2: - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' + pytest.fail() ds = None gdal.Unlink('/vsimem/ogr_vrt_39.csv') gdal.Unlink('/vsimem/ogr_vrt_39.csvt') gdal.Unlink('/vsimem/ogr_vrt_39.vrt') - return 'success' - ############################################################################### # Test PointZM support with encoding="PointFromColumns" -def ogr_vrt_40(): +def test_ogr_vrt_40(): if gdaltest.vrt_ds is None: - return 'skip' + pytest.skip() gdal.FileFromMemBuffer('/vsimem/ogr_vrt_40.csv', """id,x,y,z,m @@ -3638,27 +2992,21 @@ def ogr_vrt_40(): ds = ogr.Open('/vsimem/ogr_vrt_40.vrt') lyr = ds.GetLayer(0) - if lyr.GetGeomType() != ogr.wkbPointZM: - gdaltest.post_reason('fail') - print(lyr.GetGeomType()) - return 'fail' + assert lyr.GetGeomType() == ogr.wkbPointZM f = lyr.GetNextFeature() if f.GetGeometryRef().ExportToIsoWkt() != 'POINT ZM (1 2 3 4)': - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' + pytest.fail() ds = None gdal.Unlink('/vsimem/ogr_vrt_40.csv') gdal.Unlink('/vsimem/ogr_vrt_40.vrt') - return 'success' - ############################################################################### # Test GetExtent() on erroneous definition -def ogr_vrt_41(): +def test_ogr_vrt_41(): ds = ogr.Open("""<OGRVRTDataSource> <OGRVRTLayer name="test"> @@ -3669,16 +3017,15 @@ def ogr_vrt_41(): with gdaltest.error_handler(): lyr.GetExtent() - return 'success' - + ############################################################################### # -def ogr_vrt_cleanup(): +def test_ogr_vrt_cleanup(): if gdaltest.vrt_ds is None: - return 'skip' + pytest.skip() gdal.Unlink('/vsimem/rec1.vrt') gdal.Unlink('/vsimem/rec2.vrt') @@ -3696,58 +3043,5 @@ def ogr_vrt_cleanup(): gdaltest.vrt_ds = None - return 'success' - - -gdaltest_list = [ - ogr_vrt_1, - ogr_vrt_2, - ogr_vrt_3, - ogr_vrt_4, - ogr_vrt_5, - ogr_vrt_6, - ogr_vrt_7, - ogr_vrt_8, - ogr_vrt_9, - ogr_vrt_10, - ogr_vrt_11, - ogr_vrt_12, - ogr_vrt_13, - ogr_vrt_14, - ogr_vrt_15, - ogr_vrt_16, - ogr_vrt_17, - ogr_vrt_18, - ogr_vrt_19_optimized, - ogr_vrt_19_nonoptimized, - ogr_vrt_20, - ogr_vrt_21, - ogr_vrt_22, - ogr_vrt_23, - ogr_vrt_24, - ogr_vrt_25, - ogr_vrt_26, - ogr_vrt_27, - ogr_vrt_28, - ogr_vrt_29, - ogr_vrt_30, - ogr_vrt_31, - ogr_vrt_32, - ogr_vrt_33, - ogr_vrt_34, - ogr_vrt_35, - ogr_vrt_36, - ogr_vrt_37, - ogr_vrt_38, - ogr_vrt_39, - ogr_vrt_40, - ogr_vrt_41, - ogr_vrt_cleanup] - -if __name__ == '__main__': - - gdaltest.setup_run('ogr_vrt') - - gdaltest.run_tests(gdaltest_list) - - sys.exit(gdaltest.summarize()) + + diff --git a/autotest/ogr/ogr_wasp.py b/autotest/ogr/ogr_wasp.py index ee7d06ea713b..56189c7254ba 100755 --- a/autotest/ogr/ogr_wasp.py +++ b/autotest/ogr/ogr_wasp.py @@ -29,22 +29,21 @@ # DEALINGS IN THE SOFTWARE. ############################################################################### -import sys import math -sys.path.append('../pymod') import gdaltest import ogrtest from osgeo import gdal from osgeo import ogr from osgeo import osr +import pytest ############################################################################### # Create wasp datasource -def ogr_wasp_create_ds(): +def test_ogr_wasp_create_ds(): wasp_drv = ogr.GetDriverByName('WAsP') wasp_drv.DeleteDataSource('tmp.map') @@ -52,17 +51,16 @@ def ogr_wasp_create_ds(): gdaltest.wasp_ds = wasp_drv.CreateDataSource('tmp.map') if gdaltest.wasp_ds is not None: - return 'success' - return 'fail' + return + pytest.fail() ############################################################################### # Create elevation .map from linestrings z -def ogr_wasp_elevation_from_linestring_z(): +def test_ogr_wasp_elevation_from_linestring_z(): - if ogr_wasp_create_ds() != 'success': - return 'skip' + test_ogr_wasp_create_ds() ref = osr.SpatialReference() ref.ImportFromProj4('+proj=lcc +lat_1=46.8 +lat_0=46.8 +lon_0=0 +k_0=0.99987742 +x_0=600000 +y_0=2200000 +a=6378249.2 +b=6356514.999978254 +pm=2.337229167 +units=m +no_defs') @@ -71,9 +69,7 @@ def ogr_wasp_elevation_from_linestring_z(): ref, geom_type=ogr.wkbLineString25D) - if layer is None: - gdaltest.post_reason('unable to create layer') - return 'fail' + assert layer is not None, 'unable to create layer' dfn = ogr.FeatureDefn() @@ -84,9 +80,7 @@ def ogr_wasp_elevation_from_linestring_z(): line.AddPoint(i, 0.5, i) line.AddPoint(i, 1, i) feat.SetGeometry(line) - if layer.CreateFeature(feat) != 0: - gdaltest.post_reason('unable to create feature') - return 'fail' + assert layer.CreateFeature(feat) == 0, 'unable to create feature' del gdaltest.wasp_ds del layer @@ -99,31 +93,22 @@ def ogr_wasp_elevation_from_linestring_z(): for line in f: if not i % 2: [h, n] = line.split() - if int(n) != 3: - gdaltest.post_reason('number of points should be 3 and is %s' % n) - return 'fail' + assert int(n) == 3, ('number of points should be 3 and is %s' % n) - if float(h) != j: - gdaltest.post_reason('altitude should be %d and is %s' % (j, h)) - return 'fail' + assert float(h) == j, ('altitude should be %d and is %s' % (j, h)) j += 1 i += 1 - if j != 10: - gdaltest.post_reason('nb of feature should be 10 and is %d' % j) - return 'fail' - - return 'success' + assert j == 10, ('nb of feature should be 10 and is %d' % j) ############################################################################### # Create elevation .map from linestrings z with simplification -def ogr_wasp_elevation_from_linestring_z_toler(): +def test_ogr_wasp_elevation_from_linestring_z_toler(): - if ogr_wasp_create_ds() != 'success': - return 'skip' + test_ogr_wasp_create_ds() ref = osr.SpatialReference() ref.ImportFromProj4('+proj=lcc +lat_1=46.8 +lat_0=46.8 +lon_0=0 +k_0=0.99987742 +x_0=600000 +y_0=2200000 +a=6378249.2 +b=6356514.999978254 +pm=2.337229167 +units=m +no_defs') @@ -137,9 +122,7 @@ def ogr_wasp_elevation_from_linestring_z_toler(): if not ogrtest.have_geos(): gdal.PopErrorHandler() - if layer is None: - gdaltest.post_reason('unable to create layer') - return 'fail' + assert layer is not None, 'unable to create layer' dfn = ogr.FeatureDefn() @@ -150,9 +133,7 @@ def ogr_wasp_elevation_from_linestring_z_toler(): line.AddPoint(i, 0.5, i) line.AddPoint(i, 1, i) feat.SetGeometry(line) - if layer.CreateFeature(feat) != 0: - gdaltest.post_reason('unable to create feature') - return 'fail' + assert layer.CreateFeature(feat) == 0, 'unable to create feature' del gdaltest.wasp_ds del layer @@ -167,41 +148,30 @@ def ogr_wasp_elevation_from_linestring_z_toler(): [h, n] = line.split() if int(n) != 2: if ogrtest.have_geos(): - gdaltest.post_reason('number of points should be 2 and is %s' % n) - return 'fail' + pytest.fail('number of points should be 2 and is %s' % n) elif int(n) != 3: - gdaltest.post_reason('number of points should be 3 and is %s' % n) - return 'fail' + pytest.fail('number of points should be 3 and is %s' % n) - if float(h) != j: - gdaltest.post_reason('altitude should be %d and is %s' % (j, h)) - return 'fail' + assert float(h) == j, ('altitude should be %d and is %s' % (j, h)) j += 1 i += 1 - if j != 10: - gdaltest.post_reason('nb of feature should be 10 and is %d' % j) - return 'fail' - - return 'success' + assert j == 10, ('nb of feature should be 10 and is %d' % j) ############################################################################### # Create elevation .map from linestrings field -def ogr_wasp_elevation_from_linestring_field(): +def test_ogr_wasp_elevation_from_linestring_field(): - if ogr_wasp_create_ds() != 'success': - return 'skip' + test_ogr_wasp_create_ds() layer = gdaltest.wasp_ds.CreateLayer('mylayer', options=['WASP_FIELDS=elevation'], geom_type=ogr.wkbLineString) - if layer is None: - gdaltest.post_reason('unable to create layer') - return 'fail' + assert layer is not None, 'unable to create layer' layer.CreateField(ogr.FieldDefn('elevation', ogr.OFTReal)) @@ -213,9 +183,7 @@ def ogr_wasp_elevation_from_linestring_field(): line.AddPoint(i, 0.5) line.AddPoint(i, 1) feat.SetGeometry(line) - if layer.CreateFeature(feat) != 0: - gdaltest.post_reason('unable to create feature') - return 'fail' + assert layer.CreateFeature(feat) == 0, 'unable to create feature' del gdaltest.wasp_ds del layer @@ -228,35 +196,27 @@ def ogr_wasp_elevation_from_linestring_field(): for line in f: if not i % 2: [h, n] = line.split() - if int(n) != 3: - gdaltest.post_reason('number of points should be 3 and is %s' % n) - return 'fail' + assert int(n) == 3, ('number of points should be 3 and is %s' % n) - if float(h) != j: - gdaltest.post_reason('altitude should be %d and is %s' % (j, h)) - return 'fail' + assert float(h) == j, ('altitude should be %d and is %s' % (j, h)) j += 1 i += 1 - return 'success' - + ############################################################################### # Create roughness .map from linestrings fields -def ogr_wasp_roughness_from_linestring_fields(): +def test_ogr_wasp_roughness_from_linestring_fields(): - if ogr_wasp_create_ds() != 'success': - return 'skip' + test_ogr_wasp_create_ds() layer = gdaltest.wasp_ds.CreateLayer('mylayer', options=['WASP_FIELDS=z_left,z_right'], geom_type=ogr.wkbLineString) - if layer is None: - gdaltest.post_reason('unable to create layer') - return 'fail' + assert layer is not None, 'unable to create layer' layer.CreateField(ogr.FieldDefn('dummy', ogr.OFTString)) layer.CreateField(ogr.FieldDefn('z_left', ogr.OFTReal)) @@ -272,9 +232,7 @@ def ogr_wasp_roughness_from_linestring_fields(): line.AddPoint(i, 0.5) line.AddPoint(i, 1) feat.SetGeometry(line) - if layer.CreateFeature(feat) != 0: - gdaltest.post_reason('unable to create feature %d' % i) - return 'fail' + assert layer.CreateFeature(feat) == 0, ('unable to create feature %d' % i) del gdaltest.wasp_ds del layer @@ -287,31 +245,23 @@ def ogr_wasp_roughness_from_linestring_fields(): for line in f: if not i % 2: [l, r, n] = line.split() - if int(n) != 3: - gdaltest.post_reason('number of points should be 3 and is %s' % n) - return 'fail' + assert int(n) == 3, ('number of points should be 3 and is %s' % n) - if float(r) != j or float(l) != j - 1: - gdaltest.post_reason('roughness should be %d and %d and is %s and %s' % (j - 1, j, l, r)) - return 'fail' + assert float(r) == j and float(l) == j - 1, \ + ('roughness should be %d and %d and is %s and %s' % (j - 1, j, l, r)) j += 1 i += 1 - if j != 10: - gdaltest.post_reason('nb of feature should be 10 and is %d' % j) - return 'fail' - - return 'success' + assert j == 10, ('nb of feature should be 10 and is %d' % j) ############################################################################### # Create .map from polygons z -def ogr_wasp_roughness_from_polygon_z(): +def test_ogr_wasp_roughness_from_polygon_z(): - if ogr_wasp_create_ds() != 'success': - return 'skip' + test_ogr_wasp_create_ds() if not ogrtest.have_geos(): gdal.PushErrorHandler('CPLQuietErrorHandler') @@ -321,10 +271,8 @@ def ogr_wasp_roughness_from_polygon_z(): gdal.PopErrorHandler() if layer is None: - if ogrtest.have_geos(): - gdaltest.post_reason('unable to create layer') - return 'fail' - return 'success' + assert not ogrtest.have_geos(), 'unable to create layer' + return dfn = ogr.FeatureDefn() @@ -338,9 +286,7 @@ def ogr_wasp_roughness_from_polygon_z(): poly = ogr.Geometry(type=ogr.wkbPolygon25D) poly.AddGeometry(ring) feat.SetGeometry(poly) - if layer.CreateFeature(feat) != 0: - gdaltest.post_reason('unable to create feature') - return 'fail' + assert layer.CreateFeature(feat) == 0, 'unable to create feature' del gdaltest.wasp_ds del layer @@ -354,9 +300,7 @@ def ogr_wasp_roughness_from_polygon_z(): for line in f: if not i % 2: [l, r, n] = [v for v in line.split()] - if int(n) != 2: - gdaltest.post_reason('number of points should be 2 and is %d' % int(n)) - return 'fail' + assert int(n) == 2, ('number of points should be 2 and is %d' % int(n)) if float(r) > float(l): res.add((float(l), float(r))) else: @@ -364,24 +308,18 @@ def ogr_wasp_roughness_from_polygon_z(): j += 1 i += 1 - if j != 6: - gdaltest.post_reason('there should be 6 boundaries and there are %d' % j) - return 'fail' + assert j == 6, ('there should be 6 boundaries and there are %d' % j) - if res != set([(0, 1), (0, 5), (1, 2), (2, 3), (3, 4), (4, 5)]): - print(res) - gdaltest.post_reason('wrong values f=in boundaries') - return 'fail' - return 'success' + assert res == set([(0, 1), (0, 5), (1, 2), (2, 3), (3, 4), (4, 5)]), \ + 'wrong values f=in boundaries' ############################################################################### # Create .map from polygons field -def ogr_wasp_roughness_from_polygon_field(): +def test_ogr_wasp_roughness_from_polygon_field(): - if ogr_wasp_create_ds() != 'success': - return 'skip' + test_ogr_wasp_create_ds() if not ogrtest.have_geos(): gdal.PushErrorHandler('CPLQuietErrorHandler') @@ -392,10 +330,8 @@ def ogr_wasp_roughness_from_polygon_field(): gdal.PopErrorHandler() if layer is None: - if ogrtest.have_geos(): - gdaltest.post_reason('unable to create layer') - return 'fail' - return 'success' + assert not ogrtest.have_geos(), 'unable to create layer' + return layer.CreateField(ogr.FieldDefn('roughness', ogr.OFTReal)) layer.CreateField(ogr.FieldDefn('dummy', ogr.OFTString)) @@ -411,9 +347,7 @@ def ogr_wasp_roughness_from_polygon_field(): poly = ogr.Geometry(type=ogr.wkbPolygon) poly.AddGeometry(ring) feat.SetGeometry(poly) - if layer.CreateFeature(feat) != 0: - gdaltest.post_reason('unable to create feature') - return 'fail' + assert layer.CreateFeature(feat) == 0, 'unable to create feature' del gdaltest.wasp_ds del layer @@ -427,9 +361,7 @@ def ogr_wasp_roughness_from_polygon_field(): for line in f: if not i % 2: [l, r, n] = [v for v in line.split()] - if int(n) != 2: - gdaltest.post_reason('number of points should be 2 and is %d' % int(n)) - return 'fail' + assert int(n) == 2, ('number of points should be 2 and is %d' % int(n)) if float(r) > float(l): res.add((float(l), float(r))) else: @@ -437,15 +369,10 @@ def ogr_wasp_roughness_from_polygon_field(): j += 1 i += 1 - if j != 6: - gdaltest.post_reason('there should be 6 boundaries and there are %d' % j) - return 'fail' + assert j == 6, ('there should be 6 boundaries and there are %d' % j) - if res != set([(0, 1), (0, 5), (1, 2), (2, 3), (3, 4), (4, 5)]): - print(res) - gdaltest.post_reason('wrong values f=in boundaries') - return 'fail' - return 'success' + assert res == set([(0, 1), (0, 5), (1, 2), (2, 3), (3, 4), (4, 5)]), \ + 'wrong values f=in boundaries' ############################################################################### # Test merging of linestrings @@ -453,10 +380,9 @@ def ogr_wasp_roughness_from_polygon_field(): # a continuing line (pichart map) -def ogr_wasp_merge(): +def test_ogr_wasp_merge(): - if ogr_wasp_create_ds() != 'success': - return 'skip' + test_ogr_wasp_create_ds() if not ogrtest.have_geos(): gdal.PushErrorHandler('CPLQuietErrorHandler') @@ -466,10 +392,8 @@ def ogr_wasp_merge(): gdal.PopErrorHandler() if layer is None: - if ogrtest.have_geos(): - gdaltest.post_reason('unable to create layer') - return 'fail' - return 'success' + assert not ogrtest.have_geos(), 'unable to create layer' + return dfn = ogr.FeatureDefn() @@ -484,9 +408,7 @@ def ogr_wasp_merge(): poly = ogr.Geometry(type=ogr.wkbPolygon25D) poly.AddGeometry(ring) feat.SetGeometry(poly) - if layer.CreateFeature(feat) != 0: - gdaltest.post_reason('unable to create feature') - return 'fail' + assert layer.CreateFeature(feat) == 0, 'unable to create feature' del gdaltest.wasp_ds del layer @@ -500,9 +422,8 @@ def ogr_wasp_merge(): for line in f: if not i % 2: [l, r, n] = [v for v in line.split()] - if int(n) != 2: - gdaltest.post_reason('number of points should be 2 and is %d (unwanted merge ?)' % int(n)) - return 'fail' + assert int(n) == 2, \ + ('number of points should be 2 and is %d (unwanted merge ?)' % int(n)) if float(r) > float(l): res.append((float(l), float(r))) else: @@ -510,29 +431,21 @@ def ogr_wasp_merge(): j += 1 i += 1 - if j != 6: - gdaltest.post_reason('there should be 6 boundaries and there are %d' % j) - return 'fail' + assert j == 6, ('there should be 6 boundaries and there are %d' % j) - if res != [(0, 1)] * 6: - print(res) - gdaltest.post_reason('wrong values f=in boundaries') - return 'fail' - return 'success' + assert res == [(0, 1)] * 6, 'wrong values f=in boundaries' ############################################################################### # Read map file -def ogr_wasp_reading(): - if ogr_wasp_elevation_from_linestring_z() != 'success': - return 'skip' +def test_ogr_wasp_reading(): + test_ogr_wasp_elevation_from_linestring_z() gdaltest.wasp_ds = None ds = ogr.Open('tmp.map') - if ds is None or ds.GetLayerCount() != 1: - return 'fail' + assert ds is not None and ds.GetLayerCount() == 1 layer = ds.GetLayer(0) feat = layer.GetNextFeature() @@ -542,40 +455,15 @@ def ogr_wasp_reading(): feat = layer.GetNextFeature() i += 1 - if i != 10: - return 'fail' - return 'success' + assert i == 10 ############################################################################### # Cleanup -def ogr_wasp_cleanup(): +def test_ogr_wasp_cleanup(): wasp_drv = ogr.GetDriverByName('WAsP') wasp_drv.DeleteDataSource('tmp.map') - return 'success' - - -gdaltest_list = [ - ogr_wasp_create_ds, - ogr_wasp_elevation_from_linestring_z, - ogr_wasp_elevation_from_linestring_z_toler, - ogr_wasp_elevation_from_linestring_field, - ogr_wasp_roughness_from_linestring_fields, - ogr_wasp_roughness_from_polygon_z, - ogr_wasp_roughness_from_polygon_field, - ogr_wasp_merge, - ogr_wasp_reading, - ogr_wasp_cleanup -] - -if __name__ == '__main__': - gdal.PushErrorHandler('CPLQuietErrorHandler') - ogrtest.have_geos() - gdal.PopErrorHandler() - gdaltest.setup_run('ogr_wasp') - gdaltest.run_tests(gdaltest_list) - sys.exit(gdaltest.summarize()) diff --git a/autotest/ogr/ogr_wfs.py b/autotest/ogr/ogr_wfs.py index 3f2c72899aa1..2968d0c95bc8 100755 --- a/autotest/ogr/ogr_wfs.py +++ b/autotest/ogr/ogr_wfs.py @@ -35,9 +35,8 @@ from http.server import BaseHTTPRequestHandler import os -import sys -sys.path.append('../pymod') +import pytest import gdaltest import ogrtest @@ -45,19 +44,19 @@ from osgeo import osr from osgeo import gdal import webserver +from osr import osr_ct ############################################################################### # Test underlying OGR drivers # -def ogr_wfs_init(): +pytestmark = pytest.mark.require_driver('WFS') - gdaltest.wfs_drv = None +@pytest.fixture(autouse=True, scope='module') +def ogr_wfs_init(): gdaltest.wfs_drv = ogr.GetDriverByName('WFS') - if gdaltest.wfs_drv is None: - return 'skip' gdaltest.geoserver_wfs = None gdaltest.deegree_wfs = None @@ -67,291 +66,229 @@ def ogr_wfs_init(): if gml_ds is None: gdaltest.wfs_drv = None if gdal.GetLastErrorMsg().find('Xerces') != -1: - return 'skip' - gdaltest.post_reason('failed to open test file.') - return 'skip' + pytest.skip() + pytest.skip('failed to open test file.') + + +@pytest.fixture( + params=['NO', None], + scope='module', + ids=['without-streaming', 'with-streaming'] +) +def with_and_without_streaming(request): + with gdaltest.config_option('OGR_WFS_USE_STREAMING', request.param): + yield - return 'success' ############################################################################### # Test reading a MapServer WFS server -def ogr_wfs_mapserver(): +@pytest.mark.skip() +def test_ogr_wfs_mapserver(): if gdaltest.wfs_drv is None: - return 'skip' + pytest.skip() if gdaltest.gdalurlopen('http://www2.dmsolutions.ca/cgi-bin/mswfs_gmap') is None: - print('cannot open URL') - return 'skip' + pytest.skip('cannot open URL') ds = ogr.Open('WFS:http://www2.dmsolutions.ca/cgi-bin/mswfs_gmap') if ds is None: - gdaltest.post_reason('did not managed to open WFS datastore') - return 'skip' + pytest.skip('did not managed to open WFS datastore') - if ds.GetLayerCount() != 2: - gdaltest.post_reason('did not get expected layer count') - print(ds.GetLayerCount()) - return 'fail' + assert ds.GetLayerCount() == 2, 'did not get expected layer count' lyr = ds.GetLayer(0) - if lyr.GetName() != 'park': - gdaltest.post_reason('did not get expected layer name') - print(lyr.GetName()) - return 'fail' + assert lyr.GetName() == 'park', 'did not get expected layer name' sr = lyr.GetSpatialRef() sr2 = osr.SpatialReference() sr2.ImportFromEPSG(42304) - if not sr.IsSame(sr2): - gdaltest.post_reason('did not get expected SRS') - print(sr) - return 'fail' + assert sr.IsSame(sr2), 'did not get expected SRS' feat_count = lyr.GetFeatureCount() - if feat_count != 46: - gdaltest.post_reason('did not get expected feature count') - print(feat_count) - return 'fail' + assert feat_count == 46, 'did not get expected feature count' feat = lyr.GetNextFeature() geom = feat.GetGeometryRef() geom_wkt = geom.ExportToWkt() if geom_wkt.find("POLYGON ((389366.84375 3791519.75") == -1: - gdaltest.post_reason('did not get expected feature') feat.DumpReadable() - return 'fail' - - return 'success' + pytest.fail('did not get expected feature') + ############################################################################### # Test reading a GeoServer WFS server -def ogr_wfs_geoserver(): +@pytest.mark.skip('FIXME: re-enable after adapting test') +def test_ogr_wfs_geoserver(): if gdaltest.wfs_drv is None: - return 'skip' + pytest.skip() if gdaltest.gdalurlopen('http://demo.opengeo.org/geoserver/wfs?TYPENAME=za:za_points&SERVICE=WFS&VERSION=1.1.0&REQUEST=DescribeFeatureType') is None: - print('cannot open URL') gdaltest.geoserver_wfs = False - return 'skip' + pytest.skip('cannot open URL') gdaltest.geoserver_wfs = True ds = ogr.Open('WFS:http://demo.opengeo.org/geoserver/wfs?TYPENAME=za:za_points') - if ds is None: - gdaltest.post_reason('did not managed to open WFS datastore') - return 'fail' + assert ds is not None, 'did not managed to open WFS datastore' - if ds.GetLayerCount() != 1: - gdaltest.post_reason('did not get expected layer count') - print(ds.GetLayerCount()) - return 'fail' + assert ds.GetLayerCount() == 1, 'did not get expected layer count' lyr = ds.GetLayer(0) - if lyr.GetName() != 'za:za_points': - gdaltest.post_reason('did not get expected layer name') - print(lyr.GetName()) - return 'fail' + assert lyr.GetName() == 'za:za_points', 'did not get expected layer name' sr = lyr.GetSpatialRef() sr2 = osr.SpatialReference() sr2.ImportFromEPSG(4326) - if not sr.IsSame(sr2): - gdaltest.post_reason('did not get expected SRS') - print(sr) - return 'fail' + assert sr.IsSame(sr2), 'did not get expected SRS' feat_count = lyr.GetFeatureCount() if feat_count < 14000: if gdal.GetLastErrorMsg().find('The connection attempt failed') != -1: - print('server probably in a broken state') - # Disable it for wfs-t test gdaltest.geoserver_wfs = False - return 'skip' - gdaltest.post_reason('did not get expected feature count') + pytest.skip('server probably in a broken state') print(feat_count) - return 'fail' + pytest.fail('did not get expected feature count') - if not lyr.TestCapability(ogr.OLCFastFeatureCount): - gdaltest.post_reason('did not get OLCFastFeatureCount') - return 'fail' + assert lyr.TestCapability(ogr.OLCFastFeatureCount), 'did not get OLCFastFeatureCount' ds = ogr.Open('WFS:http://demo.opengeo.org/geoserver/wfs?TYPENAME=tiger:poi&MAXFEATURES=10&VERSION=1.1.0') if ds is None: - print('server perhaps overloaded') - return 'skip' + pytest.skip('server perhaps overloaded') lyr = ds.GetLayer(0) gdal.ErrorReset() feat = lyr.GetNextFeature() # This error message is generally the sign of a server in a broken state if feat is None and gdal.GetLastErrorMsg().find('<ows:ExceptionText>org.geoserver.platform.ServiceException') != -1: - print('server probably in a broken state') - # Disable it for wfs-t test gdaltest.geoserver_wfs = False - return 'skip' + pytest.skip('server probably in a broken state') if feat.GetField('NAME') != 'museam' or \ ogrtest.check_feature_geometry(feat, 'POINT (-74.0104611 40.70758763)', max_error=0.000001) != 0: - gdaltest.post_reason('did not get expected feature (1)') feat.DumpReadable() - return 'fail' + pytest.fail('did not get expected feature (1)') # Same with VERSION=1.0.0 ds = ogr.Open('WFS:http://demo.opengeo.org/geoserver/wfs?TYPENAME=tiger:poi&MAXFEATURES=10&VERSION=1.0.0') if ds is None: - print('server perhaps overloaded') - return 'skip' + pytest.skip('server perhaps overloaded') lyr = ds.GetLayer(0) feat = lyr.GetNextFeature() if feat.GetField('NAME') != 'museam' or \ ogrtest.check_feature_geometry(feat, 'POINT (-74.0104611 40.70758763)', max_error=0.000001) != 0: - gdaltest.post_reason('did not get expected feature (2)') feat.DumpReadable() - return 'fail' + pytest.fail('did not get expected feature (2)') # Test attribute filter ds = ogr.Open("WFS:http://demo.opengeo.org/geoserver/wfs?TYPENAME=tiger:poi") if ds is None: - print('server perhaps overloaded') - return 'skip' + pytest.skip('server perhaps overloaded') lyr = ds.GetLayer(0) lyr.SetAttributeFilter("MAINPAGE is not null and NAME >= 'a' and NAME LIKE 'mu%%eam'") feat_count = lyr.GetFeatureCount() - if feat_count != 1: - gdaltest.post_reason('did not get expected feature count after SetAttributeFilter (1)') - print(feat_count) - return 'fail' + assert feat_count == 1, \ + 'did not get expected feature count after SetAttributeFilter (1)' feat = lyr.GetNextFeature() if feat.GetField('gml_id') != 'poi.1': - gdaltest.post_reason('did not get expected feature (3)') feat.DumpReadable() - return 'fail' + pytest.fail('did not get expected feature (3)') if False: # pylint: disable=using-constant-test # This GeoServer version doesn't understand <GmlObjectId> lyr.SetAttributeFilter("gml_id = 'poi.1'") feat_count = lyr.GetFeatureCount() - if feat_count != 1: - gdaltest.post_reason('did not get expected feature count after SetAttributeFilter (2)') - print(feat_count) - return 'fail' + assert feat_count == 1, \ + 'did not get expected feature count after SetAttributeFilter (2)' feat = lyr.GetNextFeature() if feat.GetField('gml_id') != 'poi.1': - gdaltest.post_reason('did not get expected feature (4)') feat.DumpReadable() - return 'fail' - - return 'success' + pytest.fail('did not get expected feature (4)') + ############################################################################### # Test reading a GeoServer WFS server with OUTPUTFORMAT=json -def ogr_wfs_geoserver_json(): +@pytest.mark.skip('FIXME: re-enable after adapting test') +def test_ogr_wfs_geoserver_json(): if gdaltest.wfs_drv is None: - return 'skip' + pytest.skip() if not gdaltest.geoserver_wfs: - return 'skip' + pytest.skip() ds = ogr.Open('WFS:http://demo.opengeo.org/geoserver/wfs?TYPENAME=za:za_points&MAXFEATURES=10&VERSION=1.1.0&OUTPUTFORMAT=json') - if ds is None: - gdaltest.post_reason('did not managed to open WFS datastore') - return 'fail' + assert ds is not None, 'did not managed to open WFS datastore' - if ds.GetLayerCount() != 1: - gdaltest.post_reason('did not get expected layer count') - print(ds.GetLayerCount()) - return 'fail' + assert ds.GetLayerCount() == 1, 'did not get expected layer count' lyr = ds.GetLayer(0) - if lyr.GetName() != 'za:za_points': - gdaltest.post_reason('did not get expected layer name') - print(lyr.GetName()) - return 'fail' + assert lyr.GetName() == 'za:za_points', 'did not get expected layer name' feat_count = lyr.GetFeatureCount() - if feat_count != 10: - gdaltest.post_reason('did not get expected feature count') - print(feat_count) - return 'fail' + assert feat_count == 10, 'did not get expected feature count' - if not lyr.TestCapability(ogr.OLCFastFeatureCount): - gdaltest.post_reason('did not get OLCFastFeatureCount') - return 'fail' + assert lyr.TestCapability(ogr.OLCFastFeatureCount), \ + 'did not get OLCFastFeatureCount' feat = lyr.GetNextFeature() # if feat.GetField('name') != 'Alexander Bay' or \ if ogrtest.check_feature_geometry(feat, 'POINT (16.4827778 -28.5947222)', max_error=0.000000001) != 0: - gdaltest.post_reason('did not get expected feature') feat.DumpReadable() - return 'fail' - - return 'success' + pytest.fail('did not get expected feature') + ############################################################################### # Test reading a GeoServer WFS server with OUTPUTFORMAT=SHAPE-ZIP -def ogr_wfs_geoserver_shapezip(): +@pytest.mark.skip('FIXME: re-enable after adapting test') +def test_ogr_wfs_geoserver_shapezip(): if gdaltest.wfs_drv is None: - return 'skip' + pytest.skip() if not gdaltest.geoserver_wfs: - return 'skip' + pytest.skip() ds = ogr.Open('WFS:http://demo.opengeo.org/geoserver/wfs?TYPENAME=za:za_points&MAXFEATURES=10&VERSION=1.1.0&OUTPUTFORMAT=SHAPE-ZIP') - if ds is None: - gdaltest.post_reason('did not managed to open WFS datastore') - return 'fail' + assert ds is not None, 'did not managed to open WFS datastore' - if ds.GetLayerCount() != 1: - gdaltest.post_reason('did not get expected layer count') - print(ds.GetLayerCount()) - return 'fail' + assert ds.GetLayerCount() == 1, 'did not get expected layer count' lyr = ds.GetLayer(0) - if lyr.GetName() != 'za:za_points': - gdaltest.post_reason('did not get expected layer name') - print(lyr.GetName()) - return 'fail' + assert lyr.GetName() == 'za:za_points', 'did not get expected layer name' feat_count = lyr.GetFeatureCount() - if feat_count != 10: - gdaltest.post_reason('did not get expected feature count') - print(feat_count) - return 'fail' + assert feat_count == 10, 'did not get expected feature count' - if not lyr.TestCapability(ogr.OLCFastFeatureCount): - gdaltest.post_reason('did not get OLCFastFeatureCount') - return 'fail' + assert lyr.TestCapability(ogr.OLCFastFeatureCount), \ + 'did not get OLCFastFeatureCount' feat = lyr.GetNextFeature() # if feat.GetField('name') != 'Alexander Bay' or \ if ogrtest.check_feature_geometry(feat, 'POINT (16.4827778 -28.5947222)', max_error=0.000000001) != 0: - gdaltest.post_reason('did not get expected feature') feat.DumpReadable() - return 'fail' - - return 'success' + pytest.fail('did not get expected feature') + ############################################################################### # Test WFS paging -def ogr_wfs_geoserver_paging(): +@pytest.mark.skip('FIXME: re-enable after adapting test') +def test_ogr_wfs_geoserver_paging(): if gdaltest.wfs_drv is None: - return 'skip' + pytest.skip() if not gdaltest.geoserver_wfs: - return 'skip' + pytest.skip() ds = ogr.Open('WFS:http://demo.opengeo.org/geoserver/wfs?TYPENAME=og:bugsites&VERSION=1.1.0') lyr = ds.GetLayer(0) @@ -365,19 +302,13 @@ def ogr_wfs_geoserver_paging(): ds = ogr.Open('WFS:http://demo.opengeo.org/geoserver/wfs?TYPENAME=og:bugsites&VERSION=1.0.0') gdal.SetConfigOption('OGR_WFS_PAGING_ALLOWED', None) gdal.SetConfigOption('OGR_WFS_PAGE_SIZE', None) - if ds is None: - gdaltest.post_reason('did not managed to open WFS datastore') - return 'fail' + assert ds is not None, 'did not managed to open WFS datastore' lyr = ds.GetLayer(0) feature_count_wfs100 = lyr.GetFeatureCount() ds = None - if feature_count_wfs100 != feature_count_ref: - gdaltest.post_reason('fail') - print(feature_count_wfs100) - print(feature_count_ref) - return 'fail' + assert feature_count_wfs100 == feature_count_ref # Test with WFS 1.1.0 gdal.SetConfigOption('OGR_WFS_PAGING_ALLOWED', 'ON') @@ -385,9 +316,7 @@ def ogr_wfs_geoserver_paging(): ds = ogr.Open('WFS:http://demo.opengeo.org/geoserver/wfs?TYPENAME=og:bugsites&VERSION=1.1.0') gdal.SetConfigOption('OGR_WFS_PAGING_ALLOWED', None) gdal.SetConfigOption('OGR_WFS_PAGE_SIZE', None) - if ds is None: - gdaltest.post_reason('did not managed to open WFS datastore') - return 'fail' + assert ds is not None, 'did not managed to open WFS datastore' lyr = ds.GetLayer(0) feature_count_wfs110 = lyr.GetFeatureCount() @@ -400,62 +329,44 @@ def ogr_wfs_geoserver_paging(): feat = lyr.GetNextFeature() ds = None - if feature_count_wfs110 != feature_count_ref: - gdaltest.post_reason('fail') - print(feature_count_wfs100) - print(feature_count_ref) - return 'fail' + assert feature_count_wfs110 == feature_count_ref, feature_count_wfs100 - if feature_count_wfs110_at_hand != feature_count_ref: - gdaltest.post_reason('fail') - print(feature_count_wfs110_at_hand) - print(feature_count_ref) - return 'fail' - - return 'success' + assert feature_count_wfs110_at_hand == feature_count_ref ############################################################################### # Test reading a Deegree WFS server -def ogr_wfs_deegree(): +@pytest.mark.skip() +def test_ogr_wfs_deegree(): if gdaltest.wfs_drv is None: - return 'skip' + pytest.skip() if gdaltest.gdalurlopen('http://demo.deegree.org:80/utah-workspace') is None: gdaltest.deegree_wfs = False - print('cannot open URL') - return 'skip' + pytest.skip('cannot open URL') gdaltest.deegree_wfs = True ds = ogr.Open("WFS:http://demo.deegree.org:80/utah-workspace/services/wfs?ACCEPTVERSIONS=1.1.0&MAXFEATURES=10") if ds is None: if gdal.GetLastErrorMsg().find('Error returned by server') < 0: gdaltest.deegree_wfs = False - return 'skip' - gdaltest.post_reason('did not managed to open WFS datastore') - return 'fail' + pytest.skip() + pytest.fail('did not managed to open WFS datastore') lyr = ds.GetLayerByName('app:SGID024_Springs') - if lyr.GetName() != 'app:SGID024_Springs': - gdaltest.post_reason('did not get expected layer name') - print(lyr.GetName()) - return 'fail' + assert lyr.GetName() == 'app:SGID024_Springs', 'did not get expected layer name' sr = lyr.GetSpatialRef() sr2 = osr.SpatialReference() sr2.ImportFromEPSG(26912) - if not sr.IsSame(sr2): - gdaltest.post_reason('did not get expected SRS') - print(sr) - return 'fail' + assert sr.IsSame(sr2), 'did not get expected SRS' feat = lyr.GetNextFeature() if feat.GetField('OBJECTID') != 1 or \ ogrtest.check_feature_geometry(feat, 'POINT (558750.703 4402882.05)', max_error=0.000000001) != 0: - gdaltest.post_reason('did not get expected feature') feat.DumpReadable() - return 'fail' + pytest.fail('did not get expected feature') # Test attribute filter ds = ogr.Open("WFS:http://demo.deegree.org:80/utah-workspace/services/wfs?ACCEPTVERSIONS=1.1.0") @@ -465,9 +376,8 @@ def ogr_wfs_deegree(): if feat_count != 12: if gdal.GetLastErrorMsg().find('XML parsing of GML file failed') < 0 and \ gdal.GetLastErrorMsg().find('No suitable driver found') < 0: - gdaltest.post_reason('did not get expected feature count after SetAttributeFilter') print(feat_count) - return 'fail' + pytest.fail('did not get expected feature count after SetAttributeFilter') # Test attribute filter with gml_id # lyr.SetAttributeFilter("gml_id = 'SGID024_Springs30' or gml_id = 'SGID024_Springs100'") @@ -476,30 +386,26 @@ def ogr_wfs_deegree(): # gdaltest.post_reason('did not get expected feature count after SetAttributeFilter (2)') # print(feat_count) # return 'fail' - return 'success' - + ############################################################################### # Run test_ogrsf -def ogr_wfs_test_ogrsf(): +@pytest.mark.skip() +def test_ogr_wfs_test_ogrsf(): if gdaltest.wfs_drv is None: - return 'skip' + pytest.skip() if not gdaltest.deegree_wfs: - return 'skip' + pytest.skip() import test_cli_utilities if test_cli_utilities.get_test_ogrsf_path() is None: - return 'skip' + pytest.skip() ret = gdaltest.runexternal(test_cli_utilities.get_test_ogrsf_path() + ' -ro "WFS:http://demo.deegree.org:80/utah-workspace/services/wfs?ACCEPTVERSIONS=1.1.0&MAXFEATURES=10" app:SGID024_Springs') - if ret.find('INFO') == -1 or ret.find('ERROR') != -1: - print(ret) - return 'fail' - - return 'success' + assert ret.find('INFO') != -1 and ret.find('ERROR') == -1 ############################################################################### @@ -562,65 +468,59 @@ def do_GET(self): # Test reading a local fake WFS server -def ogr_wfs_fake_wfs_server(): +def test_ogr_wfs_fake_wfs_server(): if gdaltest.wfs_drv is None: - return 'skip' + pytest.skip() (process, port) = webserver.launch(handler=WFSHTTPHandler) if port == 0: - return 'skip' + pytest.skip() gdal.SetConfigOption('OGR_WFS_LOAD_MULTIPLE_LAYER_DEFN', 'NO') ds = ogr.Open("WFS:http://127.0.0.1:%d/fakewfs" % port) gdal.SetConfigOption('OGR_WFS_LOAD_MULTIPLE_LAYER_DEFN', None) if ds is None: - gdaltest.post_reason('did not managed to open WFS datastore') webserver.server_stop(process, port) - return 'fail' + pytest.fail('did not managed to open WFS datastore') lyr = ds.GetLayerByName('rijkswegen') if lyr.GetName() != 'rijkswegen': - gdaltest.post_reason('did not get expected layer name') print(lyr.GetName()) webserver.server_stop(process, port) - return 'fail' + pytest.fail('did not get expected layer name') sr = lyr.GetSpatialRef() sr2 = osr.SpatialReference() sr2.ImportFromEPSG(28992) if not sr.IsSame(sr2): - gdaltest.post_reason('did not get expected SRS') print(sr) webserver.server_stop(process, port) - return 'fail' + pytest.fail('did not get expected SRS') feat = lyr.GetNextFeature() if feat.GetField('MPLength') != '33513.' or \ ogrtest.check_feature_geometry(feat, 'MULTICURVE ((154898.65286 568054.62753,160108.36082 566076.78094,164239.254332 563024.70188,170523.31535 561231.219583,172676.42256 559253.37299,175912.80562 557459.89069,180043.699132 553508.779495,183294.491306 552250.182732))', max_error=0.00001) != 0: - gdaltest.post_reason('did not get expected feature') feat.DumpReadable() webserver.server_stop(process, port) - return 'fail' + pytest.fail('did not get expected feature') webserver.server_stop(process, port) - return 'success' - ############################################################################### # Test CreateFeature() / UpdateFeature() / DeleteFeature() (WFS-T) -def ogr_wfs_geoserver_wfst(): +@pytest.mark.skip('FIXME: re-enable after adapting test') +def test_ogr_wfs_geoserver_wfst(): if gdaltest.wfs_drv is None: - return 'skip' + pytest.skip() if not gdaltest.geoserver_wfs: - return 'skip' + pytest.skip() ds = ogr.Open('WFS:http://demo.opengeo.org/geoserver/wfs?VERSION=1.1.0', update=1) - if ds is None: - return 'fail' + assert ds is not None lyr = ds.GetLayerByName('za:za_points') geom = ogr.CreateGeometryFromWkt('POINT(0 89.5)') @@ -631,50 +531,37 @@ def ogr_wfs_geoserver_wfst(): if lyr.CreateFeature(feat) != 0: # Likely a bug in the current GeoServer version ?? if gdal.GetLastErrorMsg().find("No such property 'typeName'") >= 0: - return 'skip' + pytest.skip() - gdaltest.post_reason('cannot create feature') - return 'fail' + pytest.fail('cannot create feature') print('Feature %d created !' % feat.GetFID()) feat.SetField('type', 'type_modified_by_ogr_wfs_8_test') - if lyr.SetFeature(feat) != 0: - gdaltest.post_reason('cannot update feature') - return 'fail' + assert lyr.SetFeature(feat) == 0, 'cannot update feature' print('Feature %d updated !' % feat.GetFID()) - if lyr.DeleteFeature(feat.GetFID()) != 0: - gdaltest.post_reason('could not delete feature') - return 'fail' + assert lyr.DeleteFeature(feat.GetFID()) == 0, 'could not delete feature' print('Feature %d deleted !' % feat.GetFID()) # Test transactions - if lyr.StartTransaction() != 0: - gdaltest.post_reason('CommitTransaction() failed') - return 'fail' + assert lyr.StartTransaction() == 0, 'CommitTransaction() failed' geom = ogr.CreateGeometryFromWkt('POINT(0 89.5)') feat = ogr.Feature(lyr.GetLayerDefn()) feat.SetGeometry(geom) # feat.SetField('name', 'name_set_by_ogr_wfs_8_test') feat.SetField('type', 'type_set_by_ogr_wfs_8_test') - if lyr.CreateFeature(feat) != 0: - gdaltest.post_reason('cannot create feature') - return 'fail' + assert lyr.CreateFeature(feat) == 0, 'cannot create feature' geom = ogr.CreateGeometryFromWkt('POINT(0 89.5)') feat = ogr.Feature(lyr.GetLayerDefn()) feat.SetGeometry(geom) # feat.SetField('name', 'name_set_by_ogr_wfs_8_test_2') feat.SetField('type', 'type_set_by_ogr_wfs_8_test_2') - if lyr.CreateFeature(feat) != 0: - gdaltest.post_reason('cannot create feature') - return 'fail' + assert lyr.CreateFeature(feat) == 0, 'cannot create feature' - if lyr.CommitTransaction() != 0: - gdaltest.post_reason('CommitTransaction() failed') - return 'fail' + assert lyr.CommitTransaction() == 0, 'CommitTransaction() failed' # Retrieve inserted features print('Retrieving created features gml:id') @@ -688,34 +575,26 @@ def ogr_wfs_geoserver_wfst(): count = sql_lyr.GetFeatureCount() ds.ReleaseResultSet(sql_lyr) - if count != 2: - gdaltest.post_reason('did not get expected feature count') - return 'fail' + assert count == 2, 'did not get expected feature count' # Delete a bunch of features print('Deleting created features') sql_lyr = ds.ExecuteSQL("DELETE FROM za:za_points WHERE type = 'type_set_by_ogr_wfs_8_test' OR type = 'type_set_by_ogr_wfs_8_test_2'") ds.ReleaseResultSet(sql_lyr) - return 'success' - ############################################################################### # Test CreateFeature() / UpdateFeature() / DeleteFeature() with expected # failure due to server not allowing insert & delete -def ogr_wfs_deegree_wfst(): - - if gdaltest.wfs_drv is None: - return 'skip' +@pytest.mark.skip() +def test_ogr_wfs_deegree_wfst(): if gdaltest.gdalurlopen('http://testing.deegree.org/deegree-wfs/services') is None: - print('cannot open URL') - return 'skip' + pytest.skip('cannot open URL') ds = ogr.Open('WFS:http://testing.deegree.org/deegree-wfs/services', update=1) - if ds is None: - return 'fail' + assert ds is not None lyr = ds.GetLayerByName('app:CountyBoundaries_edited') geom = ogr.CreateGeometryFromWkt('POINT(2 49)') @@ -741,29 +620,25 @@ def ogr_wfs_deegree_wfst(): if ret != 0: print('expected fail on SetFeature') - return 'success' - + ############################################################################### # Test CreateFeature() / UpdateFeature() / DeleteFeature() on a WFS 1.0.0 server -def ogr_wfs_ionic_wfst(): - - if gdaltest.wfs_drv is None: - return 'skip' +@pytest.mark.skip() +def test_ogr_wfs_ionic_wfst(): if gdaltest.gdalurlopen('http://webservices.ionicsoft.com/ionicweb/wfs/BOSTON_ORA') is None: - print('cannot open URL') gdaltest.ionic_wfs = False - return 'skip' + pytest.skip('cannot open URL') gdaltest.ionic_wfs = True ds = ogr.Open('WFS:http://webservices.ionicsoft.com/ionicweb/wfs/BOSTON_ORA', update=1) if ds is None: if gdal.GetLastErrorMsg().find('HTTP error code : 403') != -1: gdaltest.ionic_wfs = False - return 'skip' - return 'fail' + pytest.skip() + pytest.fail() lyr = ds.GetLayerByName('wfs:BUSINESS') geom = ogr.CreateGeometryFromWkt('POINT(234000 890000)') @@ -773,56 +648,41 @@ def ogr_wfs_ionic_wfst(): feat.SetField('TOTAL_EMPLOYEES', '10') ret = lyr.CreateFeature(feat) - if ret != 0: - print('fail on CreateFeature') - return 'fail' + assert ret == 0, 'fail on CreateFeature' gmlid = feat.GetField('gml_id') ret = lyr.SetFeature(feat) - if ret != 0: - print('fail on SetFeature') - return 'fail' + assert ret == 0, 'fail on SetFeature' ds.ExecuteSQL("DELETE FROM wfs:BUSINESS WHERE gml_id = '%s'" % gmlid) - return 'success' - ############################################################################### # Test ExecuteSQL() where SQL should be turned into PROPERTYNAME and FILTER parameters -def ogr_wfs_ionic_sql(): - - if gdaltest.wfs_drv is None: - return 'skip' +@pytest.mark.skip() +def test_ogr_wfs_ionic_sql(): if not gdaltest.ionic_wfs: - return 'skip' + pytest.skip() ds = ogr.Open('WFS:http://webservices.ionicsoft.com/ionicweb/wfs/BOSTON_ORA') - if ds is None: - return 'fail' + assert ds is not None lyr = ds.ExecuteSQL("SELECT name FROM \"wfs:BUSINESS\" WHERE total_employees = 105") count = lyr.GetFeatureCount() ds.ReleaseResultSet(lyr) - if count != 1: - return 'fail' - - return 'success' + assert count == 1 ############################################################################### # Test opening a datasource from a XML description file # The following test should issue 0 WFS http request -def ogr_wfs_xmldescriptionfile(): - - if gdaltest.wfs_drv is None: - return 'skip' +def test_ogr_wfs_xmldescriptionfile(): ds = ogr.Open('data/testwfs.xml') lyr = ds.GetLayer(0) @@ -830,46 +690,32 @@ def ogr_wfs_xmldescriptionfile(): index = feature_defn.GetFieldIndex('name') sr = lyr.GetSpatialRef() - if index != 1: - print(index) - return 'fail' + assert index == 1 wkt = sr.ExportToWkt() - if wkt.find('WGS 84') == -1: - print(wkt) - return 'fail' + assert wkt.find('WGS 84') != -1 layermetadata = ds.GetLayerByName('WFSLayerMetadata') count_layers = layermetadata.GetFeatureCount() - if count_layers != ds.GetLayerCount(): - gdaltest.post_reason('count_layers != ds.GetLayerCount()') - print(count_layers) - print(ds.GetLayerCount()) - return 'fail' + assert count_layers == ds.GetLayerCount(), 'count_layers != ds.GetLayerCount()' getcapabilitieslayer = ds.GetLayerByName('WFSGetCapabilities') getcapabilitieslayer_feat = getcapabilitieslayer.GetNextFeature() getcapabilitieslayer_content = getcapabilitieslayer_feat.GetFieldAsString(0) - if getcapabilitieslayer_content.find('<WFS_Capabilities') != 0: - gdaltest.post_reason('did not get expected result') - print(getcapabilitieslayer_content) - return 'fail' + assert getcapabilitieslayer_content.find('<WFS_Capabilities') == 0, \ + 'did not get expected result' ds = None - return 'success' - ############################################################################### # Test opening a datasource from a XML description file that has just the URL -def ogr_wfs_xmldescriptionfile_to_be_updated(): - - if gdaltest.wfs_drv is None: - return 'skip' +@pytest.mark.skip('FIXME: re-enable after adapting test') +def test_ogr_wfs_xmldescriptionfile_to_be_updated(): if not gdaltest.geoserver_wfs: - return 'skip' + pytest.skip() f = open('tmp/ogr_wfs_xmldescriptionfile_to_be_updated.xml', 'wt') f.write('<OGRWFSDataSource>\n') @@ -879,119 +725,93 @@ def ogr_wfs_xmldescriptionfile_to_be_updated(): # Should only emit GetCapabilities and serialize it ds = ogr.Open('tmp/ogr_wfs_xmldescriptionfile_to_be_updated.xml') - if ds is None: - return 'fail' + assert ds is not None ds = None f = open('tmp/ogr_wfs_xmldescriptionfile_to_be_updated.xml', 'rt') content = f.read() - if content.find('WFS_Capabilities') == -1: - print(content) - gdaltest.post_reason('XML description file was not filled as expected') - return 'fail' - if content.find('<OGRWFSLayer') != -1: - print(content) - gdaltest.post_reason('XML description file was not filled as expected') - return 'fail' + assert content.find('WFS_Capabilities') != -1, \ + 'XML description file was not filled as expected' + assert content.find('<OGRWFSLayer') == -1, \ + 'XML description file was not filled as expected' f.close() # Should emit DescribeFeatureType and serialize its result ds = ogr.Open('tmp/ogr_wfs_xmldescriptionfile_to_be_updated.xml') - if ds is None: - return 'fail' + assert ds is not None ds.GetLayerByName('za:za_points').GetLayerDefn() ds = None f = open('tmp/ogr_wfs_xmldescriptionfile_to_be_updated.xml', 'rt') content = f.read() - if content.find('<OGRWFSLayer name="za:za_points">') == -1: - print(content) - gdaltest.post_reason('XML description file was not filled as expected') - return 'fail' + assert content.find('<OGRWFSLayer name="za:za_points">') != -1, \ + 'XML description file was not filled as expected' f.close() os.unlink('tmp/ogr_wfs_xmldescriptionfile_to_be_updated.xml') - return 'success' - ############################################################################### # Test opening a datasource directly from a GetCapabilities answer XML file # The following test should issue 0 WFS http request -def ogr_wfs_getcapabilitiesfile(): - - if gdaltest.wfs_drv is None: - return 'skip' +def test_ogr_wfs_getcapabilitiesfile(): ds = ogr.Open('data/getcapabilities_wfs.xml') if ds is None: gdal.Unlink('data/getcapabilities_wfs.gfs') - return 'fail' + pytest.fail() ds = None gdal.Unlink('data/getcapabilities_wfs.gfs') - return 'success' - ############################################################################### # Test opening a datastore which only support GML 3.2.1 output -def ogr_wfs_deegree_gml321(): - - if gdaltest.wfs_drv is None: - return 'skip' +@pytest.mark.skip() +def test_ogr_wfs_deegree_gml321(): ds = ogr.Open('WFS:http://demo.deegree.org:80/inspire-workspace/services/wfs?ACCEPTVERSIONS=1.1.0&MAXFEATURES=10') if ds is None: if gdaltest.gdalurlopen('http://demo.deegree.org:80/inspire-workspace/services/wfs?ACCEPTVERSIONS=1.1.0') is None: - print('cannot open URL') - return 'skip' + pytest.skip('cannot open URL') if gdal.GetLastErrorMsg().find("Unable to determine the subcontroller for request type 'GetCapabilities' and service type 'WFS'") != -1: - return 'skip' - return 'fail' + pytest.skip() + pytest.fail() lyr = ds.GetLayerByName("ad:Address") gdal.ErrorReset() lyr.GetFeatureCount() - if gdal.GetLastErrorMsg() != '': - return 'fail' - - return 'success' + assert gdal.GetLastErrorMsg() == '' ############################################################################### # Test WFS 2.0.0 support -def ogr_wfs_deegree_wfs200(): - - if gdaltest.wfs_drv is None: - return 'skip' +@pytest.mark.skip() +def test_ogr_wfs_deegree_wfs200(): ds = ogr.Open('WFS:http://demo.deegree.org:80/utah-workspace/services/wfs?ACCEPTVERSIONS=2.0.0') if ds is None: if gdaltest.gdalurlopen('http://demo.deegree.org:80/utah-workspace/services/wfs?ACCEPTVERSIONS=2.0.0') is None: - print('cannot open URL') - return 'skip' - return 'fail' + pytest.skip('cannot open URL') + pytest.fail() lyr = ds.GetLayerByName("app:SGID024_Municipalities2004_edited") lyr.SetAttributeFilter('OBJECTID = 5') count = lyr.GetFeatureCount() if count != 1: if gdal.GetLastErrorMsg().find('HTTP error code : 500') < 0: - gdaltest.post_reason("OBJECTID = 5 filter failed") print(count) - return 'fail' + pytest.fail("OBJECTID = 5 filter failed") else: feat = lyr.GetNextFeature() if feat.GetFieldAsInteger('OBJECTID') != 5: - gdaltest.post_reason("OBJECTID = 5 filter failed") feat.DumpReadable() - return 'fail' + pytest.fail("OBJECTID = 5 filter failed") lyr.SetAttributeFilter("gml_id = 'SGID024_MUNICIPALITIES2004_EDITED_5'") count = lyr.GetFeatureCount() @@ -1004,182 +824,140 @@ def ogr_wfs_deegree_wfs200(): else: feat = lyr.GetNextFeature() if feat.GetFieldAsInteger('OBJECTID') != 6: - gdaltest.post_reason("gml_id = 'SGID024_MUNICIPALITIES2004_EDITED_5' filter failed") feat.DumpReadable() - return 'fail' + pytest.fail("gml_id = 'SGID024_MUNICIPALITIES2004_EDITED_5' filter failed") lyr.SetAttributeFilter(None) lyr.SetSpatialFilterRect(-1e8, -1e8, 1e8, 1e8) spatialfiltercount = lyr.GetFeatureCount() lyr.SetSpatialFilter(None) allcount = lyr.GetFeatureCount() - if allcount != spatialfiltercount or allcount == 0: - gdaltest.post_reason('spatialfiltercount != allcount') - print(spatialfiltercount) - print(allcount) - return 'fail' - - return 'success' + assert allcount == spatialfiltercount and allcount != 0, \ + 'spatialfiltercount != allcount' ############################################################################### # Test WFS SORTBY support -def ogr_wfs_deegree_sortby(): - - if gdaltest.wfs_drv is None: - return 'skip' +@pytest.mark.skip() +def test_ogr_wfs_deegree_sortby(): ds = ogr.Open('WFS:http://demo.deegree.org:80/utah-workspace/services/wfs?MAXFEATURES=10&VERSION=1.1.0') if ds is None: if gdaltest.gdalurlopen('http://demo.deegree.org:80/utah-workspace/services/wfs') is None: - print('cannot open URL') - return 'skip' - return 'fail' + pytest.skip('cannot open URL') + pytest.fail() lyr = ds.ExecuteSQL("SELECT * FROM \"app:SGID024_Municipalities2004_edited\" ORDER BY OBJECTID DESC") feat = lyr.GetNextFeature() if feat.GetFieldAsInteger('OBJECTID') != 240: feat.DumpReadable() - return 'fail' + pytest.fail() feat = lyr.GetNextFeature() if feat.GetFieldAsInteger('OBJECTID') != 239: feat.DumpReadable() - return 'fail' + pytest.fail() ds.ReleaseResultSet(lyr) - return 'success' - ############################################################################### def ogr_wfs_get_multiple_layer_defn(url): - if gdaltest.wfs_drv is None: - return 'skip' - if not gdaltest.run_slow_tests(): - return 'skip' + pytest.skip() ds = ogr.Open('WFS:' + url) if ds is None: if gdaltest.gdalurlopen(url) is None: - print('cannot open URL') - return 'skip' - return 'fail' + pytest.skip('cannot open URL') + pytest.fail() # This should be slow only for the first layer for i in range(0, ds.GetLayerCount()): lyr = ds.GetLayer(i) print('Layer %s has %d fields' % (lyr.GetName(), lyr.GetLayerDefn().GetFieldCount())) - return 'success' - + ############################################################################### # Test a ESRI server -def ogr_wfs_esri(): +@pytest.mark.skip() +def test_ogr_wfs_esri(): return ogr_wfs_get_multiple_layer_defn('http://map.ngdc.noaa.gov/wfsconnector/com.esri.wfs.Esrimap/dart_atlantic_f') ############################################################################### # Test a ESRI server -def ogr_wfs_esri_2(): +def test_ogr_wfs_esri_2(): return ogr_wfs_get_multiple_layer_defn('http://sentinel.ga.gov.au/wfsconnector/com.esri.wfs.Esrimap') ############################################################################### # Test a CubeWerx server -def ogr_wfs_cubewerx(): +def test_ogr_wfs_cubewerx(): return ogr_wfs_get_multiple_layer_defn('http://portal.cubewerx.com/cubewerx/cubeserv/cubeserv.cgi?CONFIG=haiti_vgi&DATASTORE=vgi') ############################################################################### # Test a TinyOWS server -def ogr_wfs_tinyows(): +def test_ogr_wfs_tinyows(): return ogr_wfs_get_multiple_layer_defn('http://www.tinyows.org/cgi-bin/tinyows') ############################################################################### # Test a ERDAS Apollo server -def ogr_wfs_erdas_apollo(): +def test_ogr_wfs_erdas_apollo(): return ogr_wfs_get_multiple_layer_defn('http://apollo.erdas.com/erdas-apollo/vector/Cherokee') ############################################################################### # Test a Integraph server -def ogr_wfs_intergraph(): +def test_ogr_wfs_intergraph(): return ogr_wfs_get_multiple_layer_defn('http://ideg.xunta.es/WFS_POL/request.aspx') ############################################################################### # Test a MapInfo server -def ogr_wfs_mapinfo(): +def test_ogr_wfs_mapinfo(): return ogr_wfs_get_multiple_layer_defn('http://www.mapinfo.com/miwfs') -############################################################################### -# Test with OGR_WFS_USE_STREAMING=NO - - -def ogr_wfs_turn_streaming_off(): - gdal.SetConfigOption('OGR_WFS_USE_STREAMING', 'NO') - return 'success' - - -def ogr_wfs_turn_streaming_on(): - gdal.SetConfigOption('OGR_WFS_USE_STREAMING', None) - return 'success' ############################################################################### -def ogr_wfs_vsimem_fail_because_not_enabled(): - - if gdaltest.wfs_drv is None: - return 'skip' +def test_ogr_wfs_vsimem_fail_because_not_enabled(with_and_without_streaming): gdal.PushErrorHandler() ds = ogr.Open('WFS:/vsimem/wfs_endpoint') gdal.PopErrorHandler() - if ds is not None: - return 'fail' - - return 'success' + assert ds is None ############################################################################### -def ogr_wfs_vsimem_fail_because_no_get_capabilities(): - - if gdaltest.wfs_drv is None: - return 'skip' +def test_ogr_wfs_vsimem_fail_because_no_get_capabilities(with_and_without_streaming): gdal.SetConfigOption('CPL_CURL_ENABLE_VSIMEM', 'YES') gdal.PushErrorHandler() ds = ogr.Open('WFS:/vsimem/wfs_endpoint') gdal.PopErrorHandler() - if ds is not None: - return 'fail' - - return 'success' + assert ds is None ############################################################################### -def ogr_wfs_vsimem_fail_because_empty_response(): - - if gdaltest.wfs_drv is None: - return 'skip' +def test_ogr_wfs_vsimem_fail_because_empty_response(with_and_without_streaming): gdal.SetConfigOption('CPL_CURL_ENABLE_VSIMEM', 'YES') @@ -1188,23 +966,13 @@ def ogr_wfs_vsimem_fail_because_empty_response(): gdal.PushErrorHandler() ds = ogr.Open('WFS:/vsimem/wfs_endpoint') gdal.PopErrorHandler() - if ds is not None: - gdaltest.post_reason('fail') - return 'fail' - if gdal.GetLastErrorMsg().find('Empty content returned by server') < 0: - gdaltest.post_reason('fail') - print(gdal.GetLastErrorMsg()) - return 'fail' - - return 'success' + assert ds is None + assert gdal.GetLastErrorMsg().find('Empty content returned by server') >= 0 ############################################################################### -def ogr_wfs_vsimem_fail_because_no_WFS_Capabilities(): - - if gdaltest.wfs_drv is None: - return 'skip' +def test_ogr_wfs_vsimem_fail_because_no_WFS_Capabilities(with_and_without_streaming): gdal.SetConfigOption('CPL_CURL_ENABLE_VSIMEM', 'YES') @@ -1213,23 +981,13 @@ def ogr_wfs_vsimem_fail_because_no_WFS_Capabilities(): gdal.PushErrorHandler() ds = ogr.Open('WFS:/vsimem/wfs_endpoint') gdal.PopErrorHandler() - if ds is not None: - gdaltest.post_reason('fail') - return 'fail' - if gdal.GetLastErrorMsg().find('Cannot find <WFS_Capabilities>') < 0: - gdaltest.post_reason('fail') - print(gdal.GetLastErrorMsg()) - return 'fail' - - return 'success' + assert ds is None + assert gdal.GetLastErrorMsg().find('Cannot find <WFS_Capabilities>') >= 0 ############################################################################### -def ogr_wfs_vsimem_fail_because_exception(): - - if gdaltest.wfs_drv is None: - return 'skip' +def test_ogr_wfs_vsimem_fail_because_exception(with_and_without_streaming): gdal.SetConfigOption('CPL_CURL_ENABLE_VSIMEM', 'YES') @@ -1238,23 +996,13 @@ def ogr_wfs_vsimem_fail_because_exception(): gdal.PushErrorHandler() ds = ogr.Open('WFS:/vsimem/wfs_endpoint') gdal.PopErrorHandler() - if ds is not None: - gdaltest.post_reason('fail') - return 'fail' - if gdal.GetLastErrorMsg().find('Error returned by server : <ServiceExceptionReport/>') < 0: - gdaltest.post_reason('fail') - print(gdal.GetLastErrorMsg()) - return 'fail' - - return 'success' + assert ds is None + assert gdal.GetLastErrorMsg().find('Error returned by server : <ServiceExceptionReport/>') >= 0 ############################################################################### -def ogr_wfs_vsimem_fail_because_invalid_xml_capabilities(): - - if gdaltest.wfs_drv is None: - return 'skip' +def test_ogr_wfs_vsimem_fail_because_invalid_xml_capabilities(with_and_without_streaming): gdal.SetConfigOption('CPL_CURL_ENABLE_VSIMEM', 'YES') @@ -1263,23 +1011,13 @@ def ogr_wfs_vsimem_fail_because_invalid_xml_capabilities(): gdal.PushErrorHandler() ds = ogr.Open('WFS:/vsimem/wfs_endpoint') gdal.PopErrorHandler() - if ds is not None: - gdaltest.post_reason('fail') - return 'fail' - if gdal.GetLastErrorMsg().find('Invalid XML content : <invalid_xml') < 0: - gdaltest.post_reason('fail') - print(gdal.GetLastErrorMsg()) - return 'fail' - - return 'success' + assert ds is None + assert gdal.GetLastErrorMsg().find('Invalid XML content : <invalid_xml') >= 0 ############################################################################### -def ogr_wfs_vsimem_fail_because_missing_featuretypelist(): - - if gdaltest.wfs_drv is None: - return 'skip' +def test_ogr_wfs_vsimem_fail_because_missing_featuretypelist(with_and_without_streaming): gdal.SetConfigOption('CPL_CURL_ENABLE_VSIMEM', 'YES') @@ -1290,23 +1028,13 @@ def ogr_wfs_vsimem_fail_because_missing_featuretypelist(): gdal.PushErrorHandler() ds = ogr.Open('WFS:/vsimem/wfs_endpoint') gdal.PopErrorHandler() - if ds is not None: - gdaltest.post_reason('fail') - return 'fail' - if gdal.GetLastErrorMsg().find('Cannot find <FeatureTypeList>') < 0: - gdaltest.post_reason('fail') - print(gdal.GetLastErrorMsg()) - return 'fail' - - return 'success' + assert ds is None + assert gdal.GetLastErrorMsg().find('Cannot find <FeatureTypeList>') >= 0 ############################################################################### -def ogr_wfs_vsimem_wfs110_open_getcapabilities_file(): - - if gdaltest.wfs_drv is None: - return 'skip' +def test_ogr_wfs_vsimem_wfs110_open_getcapabilities_file(with_and_without_streaming): gdal.FileFromMemBuffer('/vsimem/caps.xml', """<WFS_Capabilities @@ -1315,13 +1043,8 @@ def ogr_wfs_vsimem_wfs110_open_getcapabilities_file(): gdal.PushErrorHandler() ds = ogr.Open('/vsimem/caps.xml') gdal.PopErrorHandler() - if ds is not None: - gdaltest.post_reason('fail') - return 'fail' - if gdal.GetLastErrorMsg().find('Parse error at EOF, not all elements have been closed') < 0: - gdaltest.post_reason('fail') - print(gdal.GetLastErrorMsg()) - return 'fail' + assert ds is None + assert gdal.GetLastErrorMsg().find('Parse error at EOF, not all elements have been closed') >= 0 gdal.FileFromMemBuffer('/vsimem/caps.xml', """<foo><WFS_Capabilities/></foo> @@ -1330,13 +1053,8 @@ def ogr_wfs_vsimem_wfs110_open_getcapabilities_file(): gdal.PushErrorHandler() ds = ogr.Open('/vsimem/caps.xml') gdal.PopErrorHandler() - if ds is not None: - gdaltest.post_reason('fail') - return 'fail' - if gdal.GetLastErrorMsg().find('Cannot find <WFS_Capabilities>') < 0: - gdaltest.post_reason('fail') - print(gdal.GetLastErrorMsg()) - return 'fail' + assert ds is None + assert gdal.GetLastErrorMsg().find('Cannot find <WFS_Capabilities>') >= 0 gdal.FileFromMemBuffer('/vsimem/caps.xml', """<WFS_Capabilities version="1.1.0"> @@ -1352,13 +1070,8 @@ def ogr_wfs_vsimem_wfs110_open_getcapabilities_file(): gdal.PushErrorHandler() ds = ogr.Open('/vsimem/caps.xml') gdal.PopErrorHandler() - if ds is not None: - gdaltest.post_reason('fail') - return 'fail' - if gdal.GetLastErrorMsg().find('Cannot find base URL') < 0: - gdaltest.post_reason('fail') - print(gdal.GetLastErrorMsg()) - return 'fail' + assert ds is None + assert gdal.GetLastErrorMsg().find('Cannot find base URL') >= 0 gdal.FileFromMemBuffer('/vsimem/caps.xml', """<WFS_Capabilities version="1.1.0"> @@ -1380,22 +1093,13 @@ def ogr_wfs_vsimem_wfs110_open_getcapabilities_file(): """) ds = ogr.Open('/vsimem/caps.xml') - if ds is None: - gdaltest.post_reason('fail') - return 'fail' - if ds.GetLayerCount() != 1: - gdaltest.post_reason('fail') - return 'fail' - - return 'success' + assert ds is not None + assert ds.GetLayerCount() == 1 ############################################################################### -def ogr_wfs_vsimem_wfs110_minimal_instance(): - - if gdaltest.wfs_drv is None: - return 'skip' +def test_ogr_wfs_vsimem_wfs110_minimal_instance(with_and_without_streaming): gdal.SetConfigOption('CPL_CURL_ENABLE_VSIMEM', 'YES') @@ -1410,40 +1114,22 @@ def ogr_wfs_vsimem_wfs110_minimal_instance(): </WFS_Capabilities> """) ds = ogr.Open('WFS:/vsimem/wfs_endpoint') - if ds is None: - gdaltest.post_reason('fail') - return 'fail' - if ds.GetLayerCount() != 0: - gdaltest.post_reason('fail') - return 'fail' - - if ds.GetMetadataDomainList() != ['', 'xml:capabilities']: - gdaltest.post_reason('fail') - return 'fail' - if ds.GetMetadata() != {'TITLE': 'LDS Testing'}: - gdaltest.post_reason('fail') - print(ds.GetMetadata()) - return 'fail' - if len(ds.GetMetadata_List("xml:capabilities")) != 1: - gdaltest.post_reason('fail') - return 'fail' + assert ds is not None + assert ds.GetLayerCount() == 0 + + assert ds.GetMetadataDomainList() == ['', 'xml:capabilities'] + assert ds.GetMetadata() == {'TITLE': 'LDS Testing'} + assert len(ds.GetMetadata_List("xml:capabilities")) == 1 gdal.PushErrorHandler() ds = ogr.Open('WFS:/vsimem/wfs_endpoint', update=1) gdal.PopErrorHandler() - if ds is not None: - gdaltest.post_reason('fail') - return 'fail' - - return 'success' + assert ds is None ############################################################################### -def ogr_wfs_vsimem_wfs110_one_layer_missing_describefeaturetype(): - - if gdaltest.wfs_drv is None: - return 'skip' +def test_ogr_wfs_vsimem_wfs110_one_layer_missing_describefeaturetype(with_and_without_streaming): gdal.SetConfigOption('CPL_CURL_ENABLE_VSIMEM', 'YES') @@ -1459,40 +1145,25 @@ def ogr_wfs_vsimem_wfs110_one_layer_missing_describefeaturetype(): </WFS_Capabilities> """) ds = ogr.Open('WFS:/vsimem/wfs_endpoint') - if ds is None: - gdaltest.post_reason('fail') - return 'fail' - if ds.GetLayerCount() != 1: - gdaltest.post_reason('fail') - return 'fail' + assert ds is not None + assert ds.GetLayerCount() == 1 lyr = ds.GetLayer(0) - if lyr.GetName() != 'my_layer': - gdaltest.post_reason('fail') - return 'fail' + assert lyr.GetName() == 'my_layer' # Missing DescribeFeatureType gdal.ErrorReset() gdal.PushErrorHandler() lyr_defn = lyr.GetLayerDefn() gdal.PopErrorHandler() - if gdal.GetLastErrorMsg() == '': - gdaltest.post_reason('fail') - return 'fail' - if lyr_defn.GetFieldCount() != 0: - gdaltest.post_reason('fail') - return 'fail' + assert gdal.GetLastErrorMsg() != '' + assert lyr_defn.GetFieldCount() == 0 lyr_defn = lyr.GetLayerDefn() - return 'success' - ############################################################################### -def ogr_wfs_vsimem_wfs110_one_layer_invalid_describefeaturetype(): - - if gdaltest.wfs_drv is None: - return 'skip' +def test_ogr_wfs_vsimem_wfs110_one_layer_invalid_describefeaturetype(with_and_without_streaming): gdal.SetConfigOption('CPL_CURL_ENABLE_VSIMEM', 'YES') @@ -1507,22 +1178,13 @@ def ogr_wfs_vsimem_wfs110_one_layer_invalid_describefeaturetype(): gdal.PushErrorHandler() lyr_defn = lyr.GetLayerDefn() gdal.PopErrorHandler() - if gdal.GetLastErrorMsg() == '': - gdaltest.post_reason('fail') - return 'fail' - if lyr_defn.GetFieldCount() != 0: - gdaltest.post_reason('fail') - return 'fail' - - return 'success' + assert gdal.GetLastErrorMsg() != '' + assert lyr_defn.GetFieldCount() == 0 ############################################################################### -def ogr_wfs_vsimem_wfs110_one_layer_describefeaturetype_missing_schema(): - - if gdaltest.wfs_drv is None: - return 'skip' +def test_ogr_wfs_vsimem_wfs110_one_layer_describefeaturetype_missing_schema(with_and_without_streaming): gdal.SetConfigOption('CPL_CURL_ENABLE_VSIMEM', 'YES') @@ -1537,22 +1199,13 @@ def ogr_wfs_vsimem_wfs110_one_layer_describefeaturetype_missing_schema(): gdal.PushErrorHandler() lyr_defn = lyr.GetLayerDefn() gdal.PopErrorHandler() - if gdal.GetLastErrorMsg() == '': - gdaltest.post_reason('fail') - return 'fail' - if lyr_defn.GetFieldCount() != 0: - gdaltest.post_reason('fail') - return 'fail' - - return 'success' + assert gdal.GetLastErrorMsg() != '' + assert lyr_defn.GetFieldCount() == 0 ############################################################################### -def ogr_wfs_vsimem_wfs110_one_layer_describefeaturetype(): - - if gdaltest.wfs_drv is None: - return 'skip' +def test_ogr_wfs_vsimem_wfs110_one_layer_describefeaturetype(with_and_without_streaming): gdal.SetConfigOption('CPL_CURL_ENABLE_VSIMEM', 'YES') @@ -1583,55 +1236,38 @@ def ogr_wfs_vsimem_wfs110_one_layer_describefeaturetype(): """) lyr_defn = lyr.GetLayerDefn() - if lyr_defn.GetFieldCount() != 8: - gdaltest.post_reason('fail') - return 'fail' - if lyr_defn.GetGeomFieldCount() != 1: - gdaltest.post_reason('fail') - return 'fail' + assert lyr_defn.GetFieldCount() == 8 + assert lyr_defn.GetGeomFieldCount() == 1 ds = gdal.OpenEx('WFS:/vsimem/wfs_endpoint', open_options=['EXPOSE_GML_ID=NO']) lyr = ds.GetLayer(0) lyr_defn = lyr.GetLayerDefn() - if lyr_defn.GetFieldCount() != 7: - gdaltest.post_reason('fail') - return 'fail' + assert lyr_defn.GetFieldCount() == 7 gdal.SetConfigOption('GML_EXPOSE_GML_ID', 'YES') ds = gdal.OpenEx('WFS:/vsimem/wfs_endpoint', open_options=['EXPOSE_GML_ID=NO']) gdal.SetConfigOption('GML_EXPOSE_GML_ID', None) lyr = ds.GetLayer(0) lyr_defn = lyr.GetLayerDefn() - if lyr_defn.GetFieldCount() != 7: - gdaltest.post_reason('fail') - return 'fail' + assert lyr_defn.GetFieldCount() == 7 gdal.SetConfigOption('GML_EXPOSE_GML_ID', 'NO') ds = gdal.OpenEx('WFS:/vsimem/wfs_endpoint', open_options=['EXPOSE_GML_ID=YES']) gdal.SetConfigOption('GML_EXPOSE_GML_ID', None) lyr = ds.GetLayer(0) lyr_defn = lyr.GetLayerDefn() - if lyr_defn.GetFieldCount() != 8: - gdaltest.post_reason('fail') - return 'fail' + assert lyr_defn.GetFieldCount() == 8 gdal.SetConfigOption('GML_EXPOSE_GML_ID', 'NO') ds = gdal.OpenEx('WFS:/vsimem/wfs_endpoint') gdal.SetConfigOption('GML_EXPOSE_GML_ID', None) lyr = ds.GetLayer(0) lyr_defn = lyr.GetLayerDefn() - if lyr_defn.GetFieldCount() != 7: - gdaltest.post_reason('fail') - return 'fail' - - return 'success' + assert lyr_defn.GetFieldCount() == 7 ############################################################################### -def ogr_wfs_vsimem_wfs110_one_layer_xmldescriptionfile_to_be_updated(): - - if gdaltest.wfs_drv is None: - return 'skip' +def test_ogr_wfs_vsimem_wfs110_one_layer_xmldescriptionfile_to_be_updated(with_and_without_streaming): gdal.SetConfigOption('CPL_CURL_ENABLE_VSIMEM', 'YES') @@ -1642,15 +1278,13 @@ def ogr_wfs_vsimem_wfs110_one_layer_xmldescriptionfile_to_be_updated(): ds = ogr.Open('/vsimem/ogr_wfs_xmldescriptionfile_to_be_updated.xml') lyr = ds.GetLayer(0) - if lyr.GetName() != 'my_layer': - gdaltest.post_reason('fail') - return 'fail' + assert lyr.GetName() == 'my_layer' ds = None f = gdal.VSIFOpenL('/vsimem/ogr_wfs_xmldescriptionfile_to_be_updated.xml', 'rb') data = gdal.VSIFReadL(1, 100000, f).decode('ascii') gdal.VSIFCloseL(f) - if data != """<OGRWFSDataSource> + assert data == """<OGRWFSDataSource> <URL>/vsimem/wfs_endpoint</URL> <WFS_Capabilities version="1.1.0"> <FeatureTypeList> @@ -1661,10 +1295,7 @@ def ogr_wfs_vsimem_wfs110_one_layer_xmldescriptionfile_to_be_updated(): </FeatureTypeList> </WFS_Capabilities> </OGRWFSDataSource> -""": - gdaltest.post_reason('fail') - print(data) - return 'fail' +""" ds = ogr.Open('/vsimem/ogr_wfs_xmldescriptionfile_to_be_updated.xml') lyr = ds.GetLayer(0) @@ -1674,7 +1305,7 @@ def ogr_wfs_vsimem_wfs110_one_layer_xmldescriptionfile_to_be_updated(): f = gdal.VSIFOpenL('/vsimem/ogr_wfs_xmldescriptionfile_to_be_updated.xml', 'rb') data = gdal.VSIFReadL(1, 100000, f).decode('ascii') gdal.VSIFCloseL(f) - if data != """<OGRWFSDataSource> + assert data == """<OGRWFSDataSource> <URL>/vsimem/wfs_endpoint</URL> <WFS_Capabilities version="1.1.0"> <FeatureTypeList> @@ -1707,10 +1338,7 @@ def ogr_wfs_vsimem_wfs110_one_layer_xmldescriptionfile_to_be_updated(): </schema> </OGRWFSLayer> </OGRWFSDataSource> -""": - gdaltest.post_reason('fail') - print(data) - return 'fail' +""" gdal.FileFromMemBuffer('/vsimem/ogr_wfs_xmldescriptionfile_to_be_updated.xml', """<OGRWFSDataSource> @@ -1742,20 +1370,13 @@ def ogr_wfs_vsimem_wfs110_one_layer_xmldescriptionfile_to_be_updated(): ds = ogr.Open('/vsimem/ogr_wfs_xmldescriptionfile_to_be_updated.xml') lyr = ds.GetLayer(0) - if lyr.GetLayerDefn().GetFieldCount() != 2: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.GetLayerDefn().GetFieldCount() == 2 ds = None - return 'success' - ############################################################################### -def ogr_wfs_vsimem_wfs110_one_layer_missing_getfeaturecount_no_hits(): - - if gdaltest.wfs_drv is None: - return 'skip' +def test_ogr_wfs_vsimem_wfs110_one_layer_missing_getfeaturecount_no_hits(with_and_without_streaming): gdal.SetConfigOption('CPL_CURL_ENABLE_VSIMEM', 'YES') @@ -1766,23 +1387,13 @@ def ogr_wfs_vsimem_wfs110_one_layer_missing_getfeaturecount_no_hits(): gdal.PushErrorHandler() count = lyr.GetFeatureCount() gdal.PopErrorHandler() - if gdal.GetLastErrorMsg() == '': - gdaltest.post_reason('fail') - return 'fail' - if count != 0: - gdaltest.post_reason('fail') - print(count) - return 'fail' - - return 'success' + assert gdal.GetLastErrorMsg() != '' + assert count == 0 ############################################################################### -def ogr_wfs_vsimem_wfs110_one_layer_missing_getfeaturecount_with_hits(): - - if gdaltest.wfs_drv is None: - return 'skip' +def test_ogr_wfs_vsimem_wfs110_one_layer_missing_getfeaturecount_with_hits(with_and_without_streaming): gdal.SetConfigOption('CPL_CURL_ENABLE_VSIMEM', 'YES') @@ -1816,23 +1427,13 @@ def ogr_wfs_vsimem_wfs110_one_layer_missing_getfeaturecount_with_hits(): gdal.PushErrorHandler() count = lyr.GetFeatureCount() gdal.PopErrorHandler() - if gdal.GetLastErrorMsg() == '': - gdaltest.post_reason('fail') - return 'fail' - if count != 0: - gdaltest.post_reason('fail') - print(count) - return 'fail' - - return 'success' + assert gdal.GetLastErrorMsg() != '' + assert count == 0 ############################################################################### -def ogr_wfs_vsimem_wfs110_one_layer_invalid_getfeaturecount_with_hits(): - - if gdaltest.wfs_drv is None: - return 'skip' +def test_ogr_wfs_vsimem_wfs110_one_layer_invalid_getfeaturecount_with_hits(with_and_without_streaming): gdal.SetConfigOption('CPL_CURL_ENABLE_VSIMEM', 'YES') @@ -1846,23 +1447,13 @@ def ogr_wfs_vsimem_wfs110_one_layer_invalid_getfeaturecount_with_hits(): gdal.PushErrorHandler() count = lyr.GetFeatureCount() gdal.PopErrorHandler() - if gdal.GetLastErrorMsg() == '': - gdaltest.post_reason('fail') - return 'fail' - if count != 0: - gdaltest.post_reason('fail') - print(count) - return 'fail' - - return 'success' + assert gdal.GetLastErrorMsg() != '' + assert count == 0 ############################################################################### -def ogr_wfs_vsimem_wfs110_one_layer_getfeaturecount_with_hits_missing_FeatureCollection(): - - if gdaltest.wfs_drv is None: - return 'skip' +def test_ogr_wfs_vsimem_wfs110_one_layer_getfeaturecount_with_hits_missing_FeatureCollection(with_and_without_streaming): gdal.SetConfigOption('CPL_CURL_ENABLE_VSIMEM', 'YES') @@ -1876,23 +1467,13 @@ def ogr_wfs_vsimem_wfs110_one_layer_getfeaturecount_with_hits_missing_FeatureCol gdal.PushErrorHandler() count = lyr.GetFeatureCount() gdal.PopErrorHandler() - if gdal.GetLastErrorMsg() == '': - gdaltest.post_reason('fail') - return 'fail' - if count != 0: - gdaltest.post_reason('fail') - print(count) - return 'fail' - - return 'success' + assert gdal.GetLastErrorMsg() != '' + assert count == 0 ############################################################################### -def ogr_wfs_vsimem_wfs110_one_layer_getfeaturecount_with_hits_invalid_xml(): - - if gdaltest.wfs_drv is None: - return 'skip' +def test_ogr_wfs_vsimem_wfs110_one_layer_getfeaturecount_with_hits_invalid_xml(with_and_without_streaming): gdal.SetConfigOption('CPL_CURL_ENABLE_VSIMEM', 'YES') @@ -1906,23 +1487,13 @@ def ogr_wfs_vsimem_wfs110_one_layer_getfeaturecount_with_hits_invalid_xml(): gdal.PushErrorHandler() count = lyr.GetFeatureCount() gdal.PopErrorHandler() - if gdal.GetLastErrorMsg() == '': - gdaltest.post_reason('fail') - return 'fail' - if count != 0: - gdaltest.post_reason('fail') - print(count) - return 'fail' - - return 'success' + assert gdal.GetLastErrorMsg() != '' + assert count == 0 ############################################################################### -def ogr_wfs_vsimem_wfs110_one_layer_getfeaturecount_with_hits_ServiceExceptionReport(): - - if gdaltest.wfs_drv is None: - return 'skip' +def test_ogr_wfs_vsimem_wfs110_one_layer_getfeaturecount_with_hits_ServiceExceptionReport(with_and_without_streaming): gdal.SetConfigOption('CPL_CURL_ENABLE_VSIMEM', 'YES') @@ -1936,22 +1507,12 @@ def ogr_wfs_vsimem_wfs110_one_layer_getfeaturecount_with_hits_ServiceExceptionRe gdal.PushErrorHandler() count = lyr.GetFeatureCount() gdal.PopErrorHandler() - if gdal.GetLastErrorMsg() == '': - gdaltest.post_reason('fail') - return 'fail' - if count != 0: - gdaltest.post_reason('fail') - print(count) - return 'fail' - - return 'success' + assert gdal.GetLastErrorMsg() != '' + assert count == 0 ############################################################################### -def ogr_wfs_vsimem_wfs110_one_layer_getfeaturecount_with_hits_missing_numberOfFeatures(): - - if gdaltest.wfs_drv is None: - return 'skip' +def test_ogr_wfs_vsimem_wfs110_one_layer_getfeaturecount_with_hits_missing_numberOfFeatures(with_and_without_streaming): gdal.SetConfigOption('CPL_CURL_ENABLE_VSIMEM', 'YES') @@ -1965,23 +1526,13 @@ def ogr_wfs_vsimem_wfs110_one_layer_getfeaturecount_with_hits_missing_numberOfFe gdal.PushErrorHandler() count = lyr.GetFeatureCount() gdal.PopErrorHandler() - if gdal.GetLastErrorMsg() == '': - gdaltest.post_reason('fail') - return 'fail' - if count != 0: - gdaltest.post_reason('fail') - print(count) - return 'fail' - - return 'success' + assert gdal.GetLastErrorMsg() != '' + assert count == 0 ############################################################################### -def ogr_wfs_vsimem_wfs110_one_layer_getfeaturecount_with_hits(): - - if gdaltest.wfs_drv is None: - return 'skip' +def test_ogr_wfs_vsimem_wfs110_one_layer_getfeaturecount_with_hits(with_and_without_streaming): gdal.SetConfigOption('CPL_CURL_ENABLE_VSIMEM', 'YES') @@ -2004,20 +1555,12 @@ def ogr_wfs_vsimem_wfs110_one_layer_getfeaturecount_with_hits(): </wfs:FeatureCollection>""") count = lyr.GetFeatureCount() - if count != 1: - gdaltest.post_reason('fail') - print(count) - return 'fail' - - return 'success' + assert count == 1 ############################################################################### -def ogr_wfs_vsimem_wfs110_one_layer_missing_getfeature(): - - if gdaltest.wfs_drv is None: - return 'skip' +def test_ogr_wfs_vsimem_wfs110_one_layer_missing_getfeature(with_and_without_streaming): gdal.SetConfigOption('CPL_CURL_ENABLE_VSIMEM', 'YES') @@ -2028,22 +1571,13 @@ def ogr_wfs_vsimem_wfs110_one_layer_missing_getfeature(): gdal.PushErrorHandler() f = lyr.GetNextFeature() gdal.PopErrorHandler() - if gdal.GetLastErrorMsg() == '': - gdaltest.post_reason('fail') - return 'fail' - if f is not None: - gdaltest.post_reason('fail') - return 'fail' - - return 'success' + assert gdal.GetLastErrorMsg() != '' + assert f is None ############################################################################### -def ogr_wfs_vsimem_wfs110_one_layer_invalid_getfeature(): - - if gdaltest.wfs_drv is None: - return 'skip' +def test_ogr_wfs_vsimem_wfs110_one_layer_invalid_getfeature(with_and_without_streaming): gdal.SetConfigOption('CPL_CURL_ENABLE_VSIMEM', 'YES') @@ -2058,22 +1592,13 @@ def ogr_wfs_vsimem_wfs110_one_layer_invalid_getfeature(): gdal.PushErrorHandler() f = lyr.GetNextFeature() gdal.PopErrorHandler() - if gdal.GetLastErrorMsg() == '': - gdaltest.post_reason('fail') - return 'fail' - if f is not None: - gdaltest.post_reason('fail') - return 'fail' - - return 'success' + assert gdal.GetLastErrorMsg() != '' + assert f is None ############################################################################### -def ogr_wfs_vsimem_wfs110_one_layer_exception_getfeature(): - - if gdaltest.wfs_drv is None: - return 'skip' +def test_ogr_wfs_vsimem_wfs110_one_layer_exception_getfeature(with_and_without_streaming): gdal.SetConfigOption('CPL_CURL_ENABLE_VSIMEM', 'YES') @@ -2088,23 +1613,13 @@ def ogr_wfs_vsimem_wfs110_one_layer_exception_getfeature(): gdal.PushErrorHandler() f = lyr.GetNextFeature() gdal.PopErrorHandler() - if gdal.GetLastErrorMsg().find('Error returned by server') < 0: - gdaltest.post_reason('fail') - print(gdal.GetLastErrorMsg()) - return 'fail' - if f is not None: - gdaltest.post_reason('fail') - return 'fail' - - return 'success' + assert gdal.GetLastErrorMsg().find('Error returned by server') >= 0 + assert f is None ############################################################################### -def ogr_wfs_vsimem_wfs110_one_layer_getfeature(): - - if gdaltest.wfs_drv is None: - return 'skip' +def test_ogr_wfs_vsimem_wfs110_one_layer_getfeature(with_and_without_streaming): gdal.SetConfigOption('CPL_CURL_ENABLE_VSIMEM', 'YES') @@ -2161,46 +1676,31 @@ def ogr_wfs_vsimem_wfs110_one_layer_getfeature(): if f.gml_id != 'my_layer.1' or f.boolean != 1 or f.str != 'str' or f.short != 1 or \ f.int != 123456789 or f.float != 1.2 or f.double != 1.23 or f.dt != '2015-04-17T12:34:56Z' or \ f.GetGeometryRef().ExportToWkt() != 'POINT (2 49)': - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' + pytest.fail() sql_lyr = ds.ExecuteSQL('SELECT * FROM my_layer') f = sql_lyr.GetNextFeature() if f.gml_id != 'my_layer.1': - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' + pytest.fail() ds.ReleaseResultSet(sql_lyr) - return 'success' - ############################################################################### -def ogr_wfs_vsimem_wfs110_one_layer_getextent(): - - if gdaltest.wfs_drv is None: - return 'skip' +def test_ogr_wfs_vsimem_wfs110_one_layer_getextent(with_and_without_streaming): gdal.SetConfigOption('CPL_CURL_ENABLE_VSIMEM', 'YES') ds = ogr.Open('WFS:/vsimem/wfs_endpoint') lyr = ds.GetLayer(0) - if lyr.GetExtent() != (2, 2, 49, 49): - gdaltest.post_reason('fail') - print(lyr.GetExtent()) - return 'fail' - - return 'success' + assert lyr.GetExtent() == (2, 2, 49, 49) ############################################################################### -def ogr_wfs_vsimem_wfs110_one_layer_getextent_without_getfeature(): - - if gdaltest.wfs_drv is None: - return 'skip' +def test_ogr_wfs_vsimem_wfs110_one_layer_getextent_without_getfeature(with_and_without_streaming): gdal.SetConfigOption('CPL_CURL_ENABLE_VSIMEM', 'YES') @@ -2214,23 +1714,13 @@ def ogr_wfs_vsimem_wfs110_one_layer_getextent_without_getfeature(): gdal.PushErrorHandler() extent = lyr.GetExtent() gdal.PopErrorHandler() - if gdal.GetLastErrorMsg() == '': - gdaltest.post_reason('fail') - return 'fail' - if extent != (0, 0, 0, 0): - gdaltest.post_reason('fail') - print(extent) - return 'fail' - - return 'success' + assert gdal.GetLastErrorMsg() != '' + assert extent == (0, 0, 0, 0) ############################################################################### -def ogr_wfs_vsimem_wfs110_one_layer_getextent_optimized(): - - if gdaltest.wfs_drv is None: - return 'skip' +def test_ogr_wfs_vsimem_wfs110_one_layer_getextent_optimized(with_and_without_streaming): gdal.SetConfigOption('CPL_CURL_ENABLE_VSIMEM', 'YES') @@ -2287,30 +1777,19 @@ def ogr_wfs_vsimem_wfs110_one_layer_getextent_optimized(): ds = ogr.Open('WFS:/vsimem/wfs_endpoint') lyr = ds.GetLayer(0) - if lyr.GetExtent() != (-180.0, 180.0, -90.0, 90.0): - gdaltest.post_reason('fail') - print(lyr.GetExtent()) - return 'fail' + assert lyr.GetExtent() == (-180.0, 180.0, -90.0, 90.0) lyr = ds.GetLayer(1) gdal.PushErrorHandler() got_extent = lyr.GetExtent() gdal.PopErrorHandler() - if got_extent != (0.0, 0.0, 0.0, 0.0): - gdaltest.post_reason('fail') - print(got_extent) - return 'fail' + assert got_extent == (0.0, 0.0, 0.0, 0.0) ds = gdal.OpenEx('WFS:/vsimem/wfs_endpoint', open_options=['TRUST_CAPABILITIES_BOUNDS=YES']) lyr = ds.GetLayer(1) - if lyr.GetExtent() != (-170.0, 170.0, -80.0, 80.0): - gdaltest.post_reason('fail') - print(lyr.GetExtent()) - return 'fail' - - sys.path.append('../osr') - import osr_ct - osr_ct.osr_ct_1() + assert lyr.GetExtent() == (-170.0, 170.0, -80.0, 80.0) + + osr_ct.test_osr_ct_1() if gdaltest.have_proj4 == 1: gdal.SetConfigOption('OGR_WFS_TRUST_CAPABILITIES_BOUNDS', 'YES') @@ -2321,20 +1800,13 @@ def ogr_wfs_vsimem_wfs110_one_layer_getextent_optimized(): expected_extent = (-20037508.342789248, 20037508.342789248, -20037508.342789154, 20037508.342789147) got_extent = lyr.GetExtent() for i in range(4): - if abs(expected_extent[i] - got_extent[i]) > 1e-5: - gdaltest.post_reason('fail') - print(got_extent) - return 'fail' - - return 'success' + assert abs(expected_extent[i] - got_extent[i]) <= 1e-5 + ############################################################################### -def ogr_wfs_vsimem_wfs110_one_layer_getfeature_ogr_getfeature(): - - if gdaltest.wfs_drv is None: - return 'skip' +def test_ogr_wfs_vsimem_wfs110_one_layer_getfeature_ogr_getfeature(with_and_without_streaming): gdal.SetConfigOption('CPL_CURL_ENABLE_VSIMEM', 'YES') @@ -2423,19 +1895,14 @@ def ogr_wfs_vsimem_wfs110_one_layer_getfeature_ogr_getfeature(): f = lyr.GetFeature(100) if f.gml_id != 'my_layer.100': - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' - - return 'success' + pytest.fail() + ############################################################################### -def ogr_wfs_vsimem_wfs110_one_layer_filter_gml_id_failed(): - - if gdaltest.wfs_drv is None: - return 'skip' +def test_ogr_wfs_vsimem_wfs110_one_layer_filter_gml_id_failed(with_and_without_streaming): gdal.SetConfigOption('CPL_CURL_ENABLE_VSIMEM', 'YES') @@ -2464,22 +1931,13 @@ def ogr_wfs_vsimem_wfs110_one_layer_filter_gml_id_failed(): gdal.PushErrorHandler() f = lyr.GetNextFeature() gdal.PopErrorHandler() - if gdal.GetLastErrorMsg() == '': - gdaltest.post_reason('fail') - return 'fail' - if f is not None: - gdaltest.post_reason('fail') - return 'fail' - - return 'success' + assert gdal.GetLastErrorMsg() != '' + assert f is None ############################################################################### -def ogr_wfs_vsimem_wfs110_one_layer_filter_gml_id_success(): - - if gdaltest.wfs_drv is None: - return 'skip' +def test_ogr_wfs_vsimem_wfs110_one_layer_filter_gml_id_success(with_and_without_streaming): gdal.SetConfigOption('CPL_CURL_ENABLE_VSIMEM', 'YES') @@ -2521,19 +1979,12 @@ def ogr_wfs_vsimem_wfs110_one_layer_filter_gml_id_success(): lyr.SetAttributeFilter("gml_id = 'my_layer.1' OR gml_id = 'my_layer.1'") f = lyr.GetNextFeature() - if f is None: - gdaltest.post_reason('fail') - return 'fail' - - return 'success' + assert f is not None ############################################################################### -def ogr_wfs_vsimem_wfs110_one_layer_filter(): - - if gdaltest.wfs_drv is None: - return 'skip' +def test_ogr_wfs_vsimem_wfs110_one_layer_filter(with_and_without_streaming): gdal.SetConfigOption('CPL_CURL_ENABLE_VSIMEM', 'YES') @@ -2575,19 +2026,12 @@ def ogr_wfs_vsimem_wfs110_one_layer_filter(): lyr.SetAttributeFilter("(str = 'str' AND short = 1 AND float = 1.2) OR str LIKE 'st%' OR boolean IS NOT NULL OR int > 1 OR int >= 1 or int != 2 or int < 2000000000 or int <= 2000000000") f = lyr.GetNextFeature() - if f is None: - gdaltest.post_reason('fail') - return 'fail' - - return 'success' + assert f is not None ############################################################################### -def ogr_wfs_vsimem_wfs110_one_layer_filter_spatial_ops(): - - if gdaltest.wfs_drv is None: - return 'skip' +def test_ogr_wfs_vsimem_wfs110_one_layer_filter_spatial_ops(with_and_without_streaming): gdal.SetConfigOption('CPL_CURL_ENABLE_VSIMEM', 'YES') @@ -2629,114 +2073,72 @@ def ogr_wfs_vsimem_wfs110_one_layer_filter_spatial_ops(): gdal.PushErrorHandler() ret = lyr.SetAttributeFilter("ST_Intersects(shape)") gdal.PopErrorHandler() - if ret == 0 or gdal.GetLastErrorMsg().find('Wrong number of arguments for ST_Intersects') < 0: - gdaltest.post_reason('fail') - print(gdal.GetLastErrorMsg()) - return 'fail' + assert not (ret == 0 or gdal.GetLastErrorMsg().find('Wrong number of arguments for ST_Intersects') < 0) gdal.PushErrorHandler() ret = lyr.SetAttributeFilter("ST_Intersects(shape, 5)") gdal.PopErrorHandler() - if ret == 0 or gdal.GetLastErrorMsg().find('Wrong field type for argument 2 of ST_Intersects') < 0: - gdaltest.post_reason('fail') - print(gdal.GetLastErrorMsg()) - return 'fail' + assert not (ret == 0 or gdal.GetLastErrorMsg().find('Wrong field type for argument 2 of ST_Intersects') < 0) gdal.PushErrorHandler() ret = lyr.SetAttributeFilter("ST_Intersects(shape, ST_MakeEnvelope(1))") gdal.PopErrorHandler() - if ret == 0 or gdal.GetLastErrorMsg().find('Wrong number of arguments for ST_MakeEnvelope') < 0: - gdaltest.post_reason('fail') - print(gdal.GetLastErrorMsg()) - return 'fail' + assert not (ret == 0 or gdal.GetLastErrorMsg().find('Wrong number of arguments for ST_MakeEnvelope') < 0) gdal.PushErrorHandler() ret = lyr.SetAttributeFilter("ST_Intersects(shape, ST_MakeEnvelope(1,1,1,'a'))") gdal.PopErrorHandler() - if ret == 0 or gdal.GetLastErrorMsg().find('Wrong field type for argument 4 of ST_MakeEnvelope') < 0: - gdaltest.post_reason('fail') - print(gdal.GetLastErrorMsg()) - return 'fail' + assert not (ret == 0 or gdal.GetLastErrorMsg().find('Wrong field type for argument 4 of ST_MakeEnvelope') < 0) gdal.PushErrorHandler() ret = lyr.SetAttributeFilter("ST_Intersects(shape, ST_MakeEnvelope(1,1,1,1,3.5))") gdal.PopErrorHandler() - if ret == 0 or gdal.GetLastErrorMsg().find('Wrong field type for argument 5 of ST_MakeEnvelope') < 0: - gdaltest.post_reason('fail') - print(gdal.GetLastErrorMsg()) - return 'fail' + assert not (ret == 0 or gdal.GetLastErrorMsg().find('Wrong field type for argument 5 of ST_MakeEnvelope') < 0) gdal.PushErrorHandler() ret = lyr.SetAttributeFilter("ST_Intersects(shape, ST_MakeEnvelope(1,1,1,1,'not_a_srs'))") gdal.PopErrorHandler() - if ret == 0 or gdal.GetLastErrorMsg().find('Wrong value for argument 5 of ST_MakeEnvelope') < 0: - gdaltest.post_reason('fail') - print(gdal.GetLastErrorMsg()) - return 'fail' + assert not (ret == 0 or gdal.GetLastErrorMsg().find('Wrong value for argument 5 of ST_MakeEnvelope') < 0) gdal.PushErrorHandler() ret = lyr.SetAttributeFilter("ST_Intersects(shape, ST_MakeEnvelope(1,1,1,1,-5))") gdal.PopErrorHandler() - if ret == 0 or gdal.GetLastErrorMsg().find('Wrong value for argument 5 of ST_MakeEnvelope') < 0: - gdaltest.post_reason('fail') - print(gdal.GetLastErrorMsg()) - return 'fail' + assert not (ret == 0 or gdal.GetLastErrorMsg().find('Wrong value for argument 5 of ST_MakeEnvelope') < 0) gdal.PushErrorHandler() ret = lyr.SetAttributeFilter("ST_Intersects(shape, ST_GeomFromText(1,2,3))") gdal.PopErrorHandler() - if ret == 0 or gdal.GetLastErrorMsg().find('Wrong number of arguments for ST_GeomFromText') < 0: - gdaltest.post_reason('fail') - print(gdal.GetLastErrorMsg()) - return 'fail' + assert not (ret == 0 or gdal.GetLastErrorMsg().find('Wrong number of arguments for ST_GeomFromText') < 0) gdal.PushErrorHandler() ret = lyr.SetAttributeFilter("ST_Intersects(shape, ST_GeomFromText(1))") gdal.PopErrorHandler() - if ret == 0 or gdal.GetLastErrorMsg().find('Wrong field type for argument 1 of ST_GeomFromText') < 0: - gdaltest.post_reason('fail') - print(gdal.GetLastErrorMsg()) - return 'fail' + assert not (ret == 0 or gdal.GetLastErrorMsg().find('Wrong field type for argument 1 of ST_GeomFromText') < 0) gdal.PushErrorHandler() ret = lyr.SetAttributeFilter("ST_Intersects(shape, ST_GeomFromText('INVALID_GEOM'))") gdal.PopErrorHandler() - if ret == 0 or gdal.GetLastErrorMsg().find('Wrong value for argument 1 of ST_GeomFromText') < 0: - gdaltest.post_reason('fail') - print(gdal.GetLastErrorMsg()) - return 'fail' + assert not (ret == 0 or gdal.GetLastErrorMsg().find('Wrong value for argument 1 of ST_GeomFromText') < 0) gdal.PushErrorHandler() ret = lyr.SetAttributeFilter("ST_Intersects(shape, ST_GeomFromText('POINT(0 0)', 'invalid_srs'))") gdal.PopErrorHandler() - if ret == 0 or gdal.GetLastErrorMsg().find('Wrong value for argument 2 of ST_GeomFromText') < 0: - gdaltest.post_reason('fail') - print(gdal.GetLastErrorMsg()) - return 'fail' + assert not (ret == 0 or gdal.GetLastErrorMsg().find('Wrong value for argument 2 of ST_GeomFromText') < 0) gdal.PushErrorHandler() ret = lyr.SetAttributeFilter("ST_DWithin(shape)") gdal.PopErrorHandler() - if ret == 0 or gdal.GetLastErrorMsg().find('Wrong number of arguments for ST_DWithin') < 0: - gdaltest.post_reason('fail') - print(gdal.GetLastErrorMsg()) - return 'fail' + assert not (ret == 0 or gdal.GetLastErrorMsg().find('Wrong number of arguments for ST_DWithin') < 0) gdal.PushErrorHandler() ret = lyr.SetAttributeFilter("ST_DWithin(shape,'a',5)") gdal.PopErrorHandler() - if ret == 0 or gdal.GetLastErrorMsg().find('Wrong field type for argument 2 of ST_DWithin') < 0: - gdaltest.post_reason('fail') - print(gdal.GetLastErrorMsg()) - return 'fail' + assert not (ret == 0 or gdal.GetLastErrorMsg().find('Wrong field type for argument 2 of ST_DWithin') < 0) gdal.PushErrorHandler() ret = lyr.SetAttributeFilter("ST_DWithin(shape,shape,'a')") gdal.PopErrorHandler() - if ret == 0 or gdal.GetLastErrorMsg().find('Wrong field type for argument 3 of ST_DWithin') < 0: - gdaltest.post_reason('fail') - print(gdal.GetLastErrorMsg()) - return 'fail' + assert not (ret == 0 or gdal.GetLastErrorMsg().find('Wrong field type for argument 3 of ST_DWithin') < 0) # Now valid requests gdal.FileFromMemBuffer('/vsimem/wfs_endpoint?SERVICE=WFS&VERSION=1.1.0&REQUEST=GetFeature&TYPENAME=my_layer&FILTER=%3CFilter%20xmlns%3D%22http:%2F%2Fwww.opengis.net%2Fogc%22%20xmlns:gml%3D%22http:%2F%2Fwww.opengis.net%2Fgml%22%3E%3COr%3E%3COr%3E%3COr%3E%3CIntersects%3E%3CPropertyName%3Eshape%3C%2FPropertyName%3E%3Cgml:Envelope%20srsName%3D%22urn:ogc:def:crs:EPSG::4326%22%3E%3Cgml:lowerCorner%3E48.5%201.5%3C%2Fgml:lowerCorner%3E%3Cgml:upperCorner%3E49.5%202.5%3C%2Fgml:upperCorner%3E%3C%2Fgml:Envelope%3E%3C%2FIntersects%3E%3CIntersects%3E%3CPropertyName%3Eshape%3C%2FPropertyName%3E%3Cgml:Envelope%20srsName%3D%22urn:ogc:def:crs:EPSG::4326%22%3E%3Cgml:lowerCorner%3E48.5%201.5%3C%2Fgml:lowerCorner%3E%3Cgml:upperCorner%3E49.5%202.5%3C%2Fgml:upperCorner%3E%3C%2Fgml:Envelope%3E%3C%2FIntersects%3E%3C%2FOr%3E%3CIntersects%3E%3CPropertyName%3Eshape%3C%2FPropertyName%3E%3Cgml:Envelope%20srsName%3D%22EPSG:4326%22%3E%3Cgml:lowerCorner%3E1.5%2048.5%3C%2Fgml:lowerCorner%3E%3Cgml:upperCorner%3E2.5%2049.5%3C%2Fgml:upperCorner%3E%3C%2Fgml:Envelope%3E%3C%2FIntersects%3E%3C%2FOr%3E%3CIntersects%3E%3CPropertyName%3Eshape%3C%2FPropertyName%3E%3Cgml:Envelope%20srsName%3D%22urn:ogc:def:crs:EPSG::32630%22%3E%3Cgml:lowerCorner%3E380000%205370000%3C%2Fgml:lowerCorner%3E%3Cgml:upperCorner%3E470000%205490000%3C%2Fgml:upperCorner%3E%3C%2Fgml:Envelope%3E%3C%2FIntersects%3E%3C%2FOr%3E%3C%2FFilter%3E', @@ -2748,9 +2150,7 @@ def ogr_wfs_vsimem_wfs110_one_layer_filter_spatial_ops(): "ST_Intersects(shape, ST_MakeEnvelope(380000,5370000,470000,5490000,32630))") f = lyr.GetNextFeature() - if f is None: - gdaltest.post_reason('fail') - return 'fail' + assert f is not None gdal.FileFromMemBuffer('/vsimem/wfs_endpoint?SERVICE=WFS&VERSION=1.1.0&REQUEST=GetFeature&TYPENAME=my_layer&FILTER=%3CFilter%20xmlns%3D%22http:%2F%2Fwww.opengis.net%2Fogc%22%20xmlns:gml%3D%22http:%2F%2Fwww.opengis.net%2Fgml%22%3E%3COr%3E%3COr%3E%3CIntersects%3E%3CPropertyName%3Eshape%3C%2FPropertyName%3E%3Cgml:Polygon%20srsName%3D%22urn:ogc:def:crs:EPSG::4326%22%20gml:id%3D%22id1%22%3E%3Cgml:exterior%3E%3Cgml:LinearRing%3E%3Cgml:posList%3E48.5%201.5%2049.5%202.5%2049.5%202.5%2048.5%202.5%2048.5%201.5%3C%2Fgml:posList%3E%3C%2Fgml:LinearRing%3E%3C%2Fgml:exterior%3E%3C%2Fgml:Polygon%3E%3C%2FIntersects%3E%3CIntersects%3E%3CPropertyName%3Eshape%3C%2FPropertyName%3E%3Cgml:Polygon%20srsName%3D%22urn:ogc:def:crs:EPSG::4326%22%20gml:id%3D%22id2%22%3E%3Cgml:exterior%3E%3Cgml:LinearRing%3E%3Cgml:posList%3E48.5%201.5%2049.5%202.5%2049.5%202.5%2048.5%202.5%2048.5%201.5%3C%2Fgml:posList%3E%3C%2Fgml:LinearRing%3E%3C%2Fgml:exterior%3E%3C%2Fgml:Polygon%3E%3C%2FIntersects%3E%3C%2FOr%3E%3CIntersects%3E%3CPropertyName%3Eshape%3C%2FPropertyName%3E%3Cgml:Polygon%20srsName%3D%22EPSG:4326%22%20gml:id%3D%22id3%22%3E%3Cgml:exterior%3E%3Cgml:LinearRing%3E%3Cgml:posList%3E1.5%2048.5%202.5%2049.5%202.5%2049.5%202.5%2048.5%201.5%2048.5%3C%2Fgml:posList%3E%3C%2Fgml:LinearRing%3E%3C%2Fgml:exterior%3E%3C%2Fgml:Polygon%3E%3C%2FIntersects%3E%3C%2FOr%3E%3C%2FFilter%3E', content) @@ -2760,9 +2160,7 @@ def ogr_wfs_vsimem_wfs110_one_layer_filter_spatial_ops(): "ST_Intersects(shape, ST_GeomFromText('POLYGON((1.5 48.5,2.5 49.5,2.5 49.5,2.5 48.5,1.5 48.5)))', 'EPSG:4326'))") f = lyr.GetNextFeature() - if f is None: - gdaltest.post_reason('fail') - return 'fail' + assert f is not None gdal.FileFromMemBuffer('/vsimem/wfs_endpoint?SERVICE=WFS&VERSION=1.1.0&REQUEST=GetFeature&TYPENAME=my_layer&FILTER=%3CFilter%20xmlns%3D%22http:%2F%2Fwww.opengis.net%2Fogc%22%20xmlns:gml%3D%22http:%2F%2Fwww.opengis.net%2Fgml%22%3E%3CDWithin%3E%3CPropertyName%3Eshape%3C%2FPropertyName%3E%3Cgml:Envelope%20srsName%3D%22urn:ogc:def:crs:EPSG::4326%22%3E%3Cgml:lowerCorner%3E48.5%201.5%3C%2Fgml:lowerCorner%3E%3Cgml:upperCorner%3E49.5%202.5%3C%2Fgml:upperCorner%3E%3C%2Fgml:Envelope%3E%3CDistance%20unit%3D%22m%22%3E5%3C%2FDistance%3E%3C%2FDWithin%3E%3C%2FFilter%3E', content) @@ -2770,17 +2168,13 @@ def ogr_wfs_vsimem_wfs110_one_layer_filter_spatial_ops(): lyr.SetAttributeFilter("ST_DWithin(shape,ST_MakeEnvelope(1.5,48.5,2.5,49.5),5)") f = lyr.GetNextFeature() - if f is None: - gdaltest.post_reason('fail') - return 'fail' + assert f is not None sql_lyr = ds.ExecuteSQL("SELECT * FROM my_layer WHERE ST_Intersects(shape, ST_GeomFromText('POLYGON((1.5 48.5,2.5 49.5,2.5 49.5,2.5 48.5,1.5 48.5)))')) OR " + "ST_Intersects(shape, ST_GeomFromText('POLYGON((1.5 48.5,2.5 49.5,2.5 49.5,2.5 48.5,1.5 48.5)))', 4326)) OR " + "ST_Intersects(shape, ST_GeomFromText('POLYGON((1.5 48.5,2.5 49.5,2.5 49.5,2.5 48.5,1.5 48.5)))', 'EPSG:4326'))") f = sql_lyr.GetNextFeature() - if f is None: - gdaltest.post_reason('fail') - return 'fail' + assert f is not None ds.ReleaseResultSet(sql_lyr) # Error case @@ -2788,20 +2182,13 @@ def ogr_wfs_vsimem_wfs110_one_layer_filter_spatial_ops(): gdal.PushErrorHandler() f = sql_lyr.GetNextFeature() gdal.PopErrorHandler() - if f is not None: - gdaltest.post_reason('fail') - return 'fail' + assert f is None ds.ReleaseResultSet(sql_lyr) - return 'success' - ############################################################################### -def ogr_wfs_vsimem_wfs110_one_layer_spatial_filter(): - - if gdaltest.wfs_drv is None: - return 'skip' +def test_ogr_wfs_vsimem_wfs110_one_layer_spatial_filter(with_and_without_streaming): gdal.SetConfigOption('CPL_CURL_ENABLE_VSIMEM', 'YES') @@ -2843,16 +2230,12 @@ def ogr_wfs_vsimem_wfs110_one_layer_spatial_filter(): lyr.SetSpatialFilterRect(1, 48, 3, 50) f = lyr.GetNextFeature() - if f is None: - gdaltest.post_reason('fail') - return 'fail' + assert f is not None if gdal.GetConfigOption('OGR_WFS_USE_STREAMING') == 'NO': lyr.SetSpatialFilterRect(1.5, 48.5, 2.5, 49.5) f = lyr.GetNextFeature() - if f is None: - gdaltest.post_reason('fail') - return 'fail' + assert f is not None lyr.SetSpatialFilter(None) lyr.ResetReading() @@ -2860,19 +2243,13 @@ def ogr_wfs_vsimem_wfs110_one_layer_spatial_filter(): lyr.ResetReading() lyr.SetSpatialFilterRect(1, 48, 3, 50) f = lyr.GetNextFeature() - if f is None: - gdaltest.post_reason('fail') - return 'fail' - - return 'success' + assert f is not None + ############################################################################### -def ogr_wfs_vsimem_wfs110_one_layer_spatial_filter_and_attribute_filter(): - - if gdaltest.wfs_drv is None: - return 'skip' +def test_ogr_wfs_vsimem_wfs110_one_layer_spatial_filter_and_attribute_filter(with_and_without_streaming): gdal.SetConfigOption('CPL_CURL_ENABLE_VSIMEM', 'YES') @@ -2915,19 +2292,12 @@ def ogr_wfs_vsimem_wfs110_one_layer_spatial_filter_and_attribute_filter(): lyr.SetAttributeFilter("str = 'str'") f = lyr.GetNextFeature() - if f is None: - gdaltest.post_reason('fail') - return 'fail' - - return 'success' + assert f is not None ############################################################################### -def ogr_wfs_vsimem_wfs110_insertfeature(): - - if gdaltest.wfs_drv is None: - return 'skip' +def test_ogr_wfs_vsimem_wfs110_insertfeature(with_and_without_streaming): wfs_insert_url = None @@ -3010,9 +2380,7 @@ def ogr_wfs_vsimem_wfs110_insertfeature(): gdal.PushErrorHandler() ret = lyr.CreateFeature(f) gdal.PopErrorHandler() - if ret == 0: - gdaltest.post_reason('fail') - return 'fail' + assert ret != 0 wfs_insert_url = """/vsimem/wfs_endpoint&POSTFIELDS=<?xml version="1.0"?> <wfs:Transaction xmlns:wfs="http://www.opengis.net/wfs" @@ -3033,9 +2401,7 @@ def ogr_wfs_vsimem_wfs110_insertfeature(): gdal.PushErrorHandler() ret = lyr.CreateFeature(f) gdal.PopErrorHandler() - if ret == 0: - gdaltest.post_reason('fail') - return 'fail' + assert ret != 0 gdal.FileFromMemBuffer(wfs_insert_url, "<invalid_xml") @@ -3043,9 +2409,7 @@ def ogr_wfs_vsimem_wfs110_insertfeature(): gdal.PushErrorHandler() ret = lyr.CreateFeature(f) gdal.PopErrorHandler() - if ret == 0: - gdaltest.post_reason('fail') - return 'fail' + assert ret != 0 gdal.FileFromMemBuffer(wfs_insert_url, "<ServiceExceptionReport/>") @@ -3053,10 +2417,7 @@ def ogr_wfs_vsimem_wfs110_insertfeature(): gdal.PushErrorHandler() ret = lyr.CreateFeature(f) gdal.PopErrorHandler() - if ret == 0 or gdal.GetLastErrorMsg().find('Error returned by server') < 0: - gdaltest.post_reason('fail') - print(gdal.GetLastErrorMsg()) - return 'fail' + assert not (ret == 0 or gdal.GetLastErrorMsg().find('Error returned by server') < 0) gdal.FileFromMemBuffer(wfs_insert_url, "<dummy_xml/>") @@ -3064,10 +2425,7 @@ def ogr_wfs_vsimem_wfs110_insertfeature(): gdal.PushErrorHandler() ret = lyr.CreateFeature(f) gdal.PopErrorHandler() - if ret == 0 or gdal.GetLastErrorMsg().find('Cannot find <TransactionResponse>') < 0: - gdaltest.post_reason('fail') - print(gdal.GetLastErrorMsg()) - return 'fail' + assert not (ret == 0 or gdal.GetLastErrorMsg().find('Cannot find <TransactionResponse>') < 0) gdal.FileFromMemBuffer(wfs_insert_url, """<TransactionResponse> @@ -3078,9 +2436,7 @@ def ogr_wfs_vsimem_wfs110_insertfeature(): gdal.PushErrorHandler() ret = lyr.CreateFeature(f) gdal.PopErrorHandler() - if ret == 0: - gdaltest.post_reason('fail') - return 'fail' + assert ret != 0 gdal.FileFromMemBuffer(wfs_insert_url, """<TransactionResponse> @@ -3096,9 +2452,7 @@ def ogr_wfs_vsimem_wfs110_insertfeature(): gdal.PushErrorHandler() ret = lyr.CreateFeature(f) gdal.PopErrorHandler() - if ret == 0: - gdaltest.post_reason('fail') - return 'fail' + assert ret != 0 gdal.FileFromMemBuffer(wfs_insert_url, """<TransactionResponse> @@ -3113,170 +2467,109 @@ def ogr_wfs_vsimem_wfs110_insertfeature(): gdal.PushErrorHandler() sql_lyr = ds.ExecuteSQL('SELECT _LAST_INSERTED_FIDS_ FROM not_existing_layer') gdal.PopErrorHandler() - if sql_lyr is not None: - gdaltest.post_reason('fail') - return 'fail' + assert sql_lyr is None f = ogr.Feature(lyr.GetLayerDefn()) ret = lyr.CreateFeature(f) - if ret != 0: - gdaltest.post_reason('fail') - return 'fail' - if f.GetFID() != 100: - gdaltest.post_reason('fail') - return 'fail' + assert ret == 0 + assert f.GetFID() == 100 sql_lyr = ds.ExecuteSQL('SELECT _LAST_INSERTED_FIDS_ FROM my_layer') got_f = sql_lyr.GetNextFeature() - if got_f is not None: - gdaltest.post_reason('fail') - return 'fail' + assert got_f is None ds.ReleaseResultSet(sql_lyr) gdal.PushErrorHandler() ret = lyr.CreateFeature(f) gdal.PopErrorHandler() - if ret == 0 or gdal.GetLastErrorMsg().find('Cannot insert a feature when gml_id field is already set') < 0: - gdaltest.post_reason('fail') - print(gdal.GetLastErrorMsg()) - return 'fail' + assert not (ret == 0 or gdal.GetLastErrorMsg().find('Cannot insert a feature when gml_id field is already set') < 0) # Empty StartTransaction + CommitTransaction ret = lyr.StartTransaction() - if ret != 0: - gdaltest.post_reason('fail') - return 'fail' + assert ret == 0 ret = lyr.CommitTransaction() - if ret != 0: - gdaltest.post_reason('fail') - return 'fail' + assert ret == 0 # Empty StartTransaction + RollbackTransaction ret = lyr.StartTransaction() - if ret != 0: - gdaltest.post_reason('fail') - return 'fail' + assert ret == 0 ret = lyr.RollbackTransaction() - if ret != 0: - gdaltest.post_reason('fail') - return 'fail' + assert ret == 0 # Isolated CommitTransaction gdal.PushErrorHandler() ret = lyr.CommitTransaction() gdal.PopErrorHandler() - if ret == 0: - gdaltest.post_reason('fail') - return 'fail' + assert ret != 0 # Isolated RollbackTransaction gdal.PushErrorHandler() ret = lyr.RollbackTransaction() gdal.PopErrorHandler() - if ret == 0: - gdaltest.post_reason('fail') - return 'fail' + assert ret != 0 # 2 StartTransaction in a row ret = lyr.StartTransaction() - if ret != 0: - gdaltest.post_reason('fail') - return 'fail' + assert ret == 0 gdal.PushErrorHandler() ret = lyr.StartTransaction() gdal.PopErrorHandler() - if ret == 0: - gdaltest.post_reason('fail') - return 'fail' + assert ret != 0 ret = lyr.RollbackTransaction() - if ret != 0: - gdaltest.post_reason('fail') - return 'fail' + assert ret == 0 # Missing TransactionSummary ret = lyr.StartTransaction() - if ret != 0: - gdaltest.post_reason('fail') - return 'fail' + assert ret == 0 f = ogr.Feature(lyr.GetLayerDefn()) ret = lyr.CreateFeature(f) - if ret != 0: - gdaltest.post_reason('fail') - return 'fail' + assert ret == 0 gdal.PushErrorHandler() ret = lyr.CommitTransaction() gdal.PopErrorHandler() - if ret == 0 or gdal.GetLastErrorMsg().find('Only 0 features were inserted whereas 1 where expected') < 0: - gdaltest.post_reason('fail') - print(gdal.GetLastErrorMsg()) - return 'fail' + assert not (ret == 0 or gdal.GetLastErrorMsg().find('Only 0 features were inserted whereas 1 where expected') < 0) ret = lyr.StartTransaction() - if ret != 0: - gdaltest.post_reason('fail') - return 'fail' + assert ret == 0 f = ogr.Feature(lyr.GetLayerDefn()) ret = lyr.CreateFeature(f) - if ret != 0: - gdaltest.post_reason('fail') - return 'fail' + assert ret == 0 gdal.FileFromMemBuffer(wfs_insert_url, "<invalid_xml") gdal.PushErrorHandler() ret = lyr.CommitTransaction() gdal.PopErrorHandler() - if ret == 0 or gdal.GetLastErrorMsg().find('Invalid XML content') < 0: - gdaltest.post_reason('fail') - print(gdal.GetLastErrorMsg()) - return 'fail' + assert not (ret == 0 or gdal.GetLastErrorMsg().find('Invalid XML content') < 0) ret = lyr.StartTransaction() - if ret != 0: - gdaltest.post_reason('fail') - return 'fail' + assert ret == 0 f = ogr.Feature(lyr.GetLayerDefn()) ret = lyr.CreateFeature(f) - if ret != 0: - gdaltest.post_reason('fail') - return 'fail' + assert ret == 0 gdal.FileFromMemBuffer(wfs_insert_url, "<dummy_xml/>") gdal.PushErrorHandler() ret = lyr.CommitTransaction() gdal.PopErrorHandler() - if ret == 0 or gdal.GetLastErrorMsg().find('Cannot find <TransactionResponse>') < 0: - gdaltest.post_reason('fail') - print(gdal.GetLastErrorMsg()) - return 'fail' + assert not (ret == 0 or gdal.GetLastErrorMsg().find('Cannot find <TransactionResponse>') < 0) ret = lyr.StartTransaction() - if ret != 0: - gdaltest.post_reason('fail') - return 'fail' + assert ret == 0 f = ogr.Feature(lyr.GetLayerDefn()) ret = lyr.CreateFeature(f) - if ret != 0: - gdaltest.post_reason('fail') - return 'fail' + assert ret == 0 gdal.FileFromMemBuffer(wfs_insert_url, "<ServiceExceptionReport/>") gdal.PushErrorHandler() ret = lyr.CommitTransaction() gdal.PopErrorHandler() - if ret == 0 or gdal.GetLastErrorMsg().find('Error returned by server') < 0: - gdaltest.post_reason('fail') - print(gdal.GetLastErrorMsg()) - return 'fail' + assert not (ret == 0 or gdal.GetLastErrorMsg().find('Error returned by server') < 0) ret = lyr.StartTransaction() - if ret != 0: - gdaltest.post_reason('fail') - return 'fail' + assert ret == 0 f = ogr.Feature(lyr.GetLayerDefn()) ret = lyr.CreateFeature(f) - if ret != 0: - gdaltest.post_reason('fail') - return 'fail' + assert ret == 0 gdal.FileFromMemBuffer(wfs_insert_url, """<TransactionResponse> @@ -3286,20 +2579,13 @@ def ogr_wfs_vsimem_wfs110_insertfeature(): gdal.PushErrorHandler() ret = lyr.CommitTransaction() gdal.PopErrorHandler() - if ret == 0 or gdal.GetLastErrorMsg().find('Cannot find node InsertResults') < 0: - gdaltest.post_reason('fail') - print(gdal.GetLastErrorMsg()) - return 'fail' + assert not (ret == 0 or gdal.GetLastErrorMsg().find('Cannot find node InsertResults') < 0) ret = lyr.StartTransaction() - if ret != 0: - gdaltest.post_reason('fail') - return 'fail' + assert ret == 0 f = ogr.Feature(lyr.GetLayerDefn()) ret = lyr.CreateFeature(f) - if ret != 0: - gdaltest.post_reason('fail') - return 'fail' + assert ret == 0 gdal.FileFromMemBuffer(wfs_insert_url, """<TransactionResponse> @@ -3310,20 +2596,13 @@ def ogr_wfs_vsimem_wfs110_insertfeature(): gdal.PushErrorHandler() ret = lyr.CommitTransaction() gdal.PopErrorHandler() - if ret == 0 or gdal.GetLastErrorMsg().find('Inconsistent InsertResults: did not get expected FID count') < 0: - gdaltest.post_reason('fail') - print(gdal.GetLastErrorMsg()) - return 'fail' + assert not (ret == 0 or gdal.GetLastErrorMsg().find('Inconsistent InsertResults: did not get expected FID count') < 0) ret = lyr.StartTransaction() - if ret != 0: - gdaltest.post_reason('fail') - return 'fail' + assert ret == 0 f = ogr.Feature(lyr.GetLayerDefn()) ret = lyr.CreateFeature(f) - if ret != 0: - gdaltest.post_reason('fail') - return 'fail' + assert ret == 0 gdal.FileFromMemBuffer(wfs_insert_url, """<TransactionResponse> @@ -3337,20 +2616,13 @@ def ogr_wfs_vsimem_wfs110_insertfeature(): gdal.PushErrorHandler() ret = lyr.CommitTransaction() gdal.PopErrorHandler() - if ret == 0 or gdal.GetLastErrorMsg().find('Cannot find fid') < 0: - gdaltest.post_reason('fail') - print(gdal.GetLastErrorMsg()) - return 'fail' + assert not (ret == 0 or gdal.GetLastErrorMsg().find('Cannot find fid') < 0) ret = lyr.StartTransaction() - if ret != 0: - gdaltest.post_reason('fail') - return 'fail' + assert ret == 0 f = ogr.Feature(lyr.GetLayerDefn()) ret = lyr.CreateFeature(f) - if ret != 0: - gdaltest.post_reason('fail') - return 'fail' + assert ret == 0 gdal.FileFromMemBuffer(wfs_insert_url, """<TransactionResponse> @@ -3363,15 +2635,11 @@ def ogr_wfs_vsimem_wfs110_insertfeature(): </TransactionResponse> """) ret = lyr.CommitTransaction() - if ret != 0: - gdaltest.post_reason('fail') - return 'fail' + assert ret == 0 sql_lyr = ds.ExecuteSQL('SELECT _LAST_INSERTED_FIDS_ FROM my_layer') f = sql_lyr.GetNextFeature() - if f.gml_id != 'my_layer.100': - gdaltest.post_reason('fail') - return 'fail' + assert f.gml_id == 'my_layer.100' sql_lyr.ResetReading() sql_lyr.SetNextByIndex(0) sql_lyr.GetFeature(0) @@ -3417,22 +2685,15 @@ def ogr_wfs_vsimem_wfs110_insertfeature(): f.SetField('double', 2.34) f.SetGeometry(ogr.CreateGeometryFromWkt('POINT (2 49)')) ret = lyr.CreateFeature(f) - if ret != 0: - gdaltest.post_reason('fail') - return 'fail' + assert ret == 0 gdal.Unlink(wfs_insert_url) wfs_insert_url = None - return 'success' - ############################################################################### -def ogr_wfs_vsimem_wfs110_updatefeature(): - - if gdaltest.wfs_drv is None: - return 'skip' +def test_ogr_wfs_vsimem_wfs110_updatefeature(with_and_without_streaming): wfs_update_url = None @@ -3445,28 +2706,20 @@ def ogr_wfs_vsimem_wfs110_updatefeature(): gdal.PushErrorHandler() ret = lyr.CreateFeature(f) gdal.PopErrorHandler() - if ret == 0: - gdaltest.post_reason('fail') - return 'fail' + assert ret != 0 f = ogr.Feature(lyr.GetLayerDefn()) gdal.PushErrorHandler() ret = lyr.SetFeature(f) gdal.PopErrorHandler() - if ret == 0 or gdal.GetLastErrorMsg().find('Cannot update a feature when gml_id field is not set') < 0: - gdaltest.post_reason('fail') - print(gdal.GetLastErrorMsg()) - return 'fail' + assert not (ret == 0 or gdal.GetLastErrorMsg().find('Cannot update a feature when gml_id field is not set') < 0) f = ogr.Feature(lyr.GetLayerDefn()) f.SetField('gml_id', 'my_layer.1') gdal.PushErrorHandler() ret = lyr.SetFeature(f) gdal.PopErrorHandler() - if ret == 0: - gdaltest.post_reason('fail') - print(gdal.GetLastErrorMsg()) - return 'fail' + assert ret != 0, gdal.GetLastErrorMsg() wfs_update_url = """/vsimem/wfs_endpoint&POSTFIELDS=<?xml version="1.0"?> <wfs:Transaction xmlns:wfs="http://www.opengis.net/wfs" @@ -3513,10 +2766,7 @@ def ogr_wfs_vsimem_wfs110_updatefeature(): gdal.PushErrorHandler() ret = lyr.SetFeature(f) gdal.PopErrorHandler() - if ret == 0 or gdal.GetLastErrorMsg().find('Empty content returned by server') < 0: - gdaltest.post_reason('fail') - print(gdal.GetLastErrorMsg()) - return 'fail' + assert not (ret == 0 or gdal.GetLastErrorMsg().find('Empty content returned by server') < 0) gdal.FileFromMemBuffer(wfs_update_url, "<invalid_xmm") f = ogr.Feature(lyr.GetLayerDefn()) @@ -3524,10 +2774,7 @@ def ogr_wfs_vsimem_wfs110_updatefeature(): gdal.PushErrorHandler() ret = lyr.SetFeature(f) gdal.PopErrorHandler() - if ret == 0 or gdal.GetLastErrorMsg().find('Invalid XML content') < 0: - gdaltest.post_reason('fail') - print(gdal.GetLastErrorMsg()) - return 'fail' + assert not (ret == 0 or gdal.GetLastErrorMsg().find('Invalid XML content') < 0) gdal.FileFromMemBuffer(wfs_update_url, "<ServiceExceptionReport/>") f = ogr.Feature(lyr.GetLayerDefn()) @@ -3535,10 +2782,7 @@ def ogr_wfs_vsimem_wfs110_updatefeature(): gdal.PushErrorHandler() ret = lyr.SetFeature(f) gdal.PopErrorHandler() - if ret == 0 or gdal.GetLastErrorMsg().find('Error returned by server') < 0: - gdaltest.post_reason('fail') - print(gdal.GetLastErrorMsg()) - return 'fail' + assert not (ret == 0 or gdal.GetLastErrorMsg().find('Error returned by server') < 0) gdal.FileFromMemBuffer(wfs_update_url, "<foo/>") f = ogr.Feature(lyr.GetLayerDefn()) @@ -3546,19 +2790,13 @@ def ogr_wfs_vsimem_wfs110_updatefeature(): gdal.PushErrorHandler() ret = lyr.SetFeature(f) gdal.PopErrorHandler() - if ret == 0 or gdal.GetLastErrorMsg().find('Cannot find <TransactionResponse>') < 0: - gdaltest.post_reason('fail') - print(gdal.GetLastErrorMsg()) - return 'fail' + assert not (ret == 0 or gdal.GetLastErrorMsg().find('Cannot find <TransactionResponse>') < 0) gdal.FileFromMemBuffer(wfs_update_url, "<TransactionResponse/>") f = ogr.Feature(lyr.GetLayerDefn()) f.SetField('gml_id', 'my_layer.1') ret = lyr.SetFeature(f) - if ret != 0: - gdaltest.post_reason('fail') - print(gdal.GetLastErrorMsg()) - return 'fail' + assert ret == 0, gdal.GetLastErrorMsg() gdal.Unlink(wfs_update_url) wfs_update_url = """/vsimem/wfs_endpoint&POSTFIELDS=<?xml version="1.0"?> @@ -3612,19 +2850,12 @@ def ogr_wfs_vsimem_wfs110_updatefeature(): f.SetField('double', 2.34) f.SetGeometry(ogr.CreateGeometryFromWkt('POINT (2 49)')) ret = lyr.SetFeature(f) - if ret != 0: - gdaltest.post_reason('fail') - return 'fail' - - return 'success' + assert ret == 0 ############################################################################### -def ogr_wfs_vsimem_wfs110_deletefeature(): - - if gdaltest.wfs_drv is None: - return 'skip' +def test_ogr_wfs_vsimem_wfs110_deletefeature(with_and_without_streaming): wfs_delete_url = None @@ -3636,10 +2867,7 @@ def ogr_wfs_vsimem_wfs110_deletefeature(): gdal.PushErrorHandler() ret = lyr.DeleteFeature(200) gdal.PopErrorHandler() - if ret == 0: - gdaltest.post_reason('fail') - print(gdal.GetLastErrorMsg()) - return 'fail' + assert ret != 0, gdal.GetLastErrorMsg() gdal.FileFromMemBuffer('/vsimem/wfs_endpoint?SERVICE=WFS&VERSION=1.1.0&REQUEST=GetFeature&TYPENAME=my_layer&FILTER=%3CFilter%20xmlns%3D%22http:%2F%2Fwww.opengis.net%2Fogc%22%20xmlns:gml%3D%22http:%2F%2Fwww.opengis.net%2Fgml%22%3E%3CGmlObjectId%20id%3D%22my_layer.200%22%2F%3E%3C%2FFilter%3E', """<wfs:FeatureCollection xmlns:xs="http://www.w3.org/2001/XMLSchema" @@ -3667,10 +2895,7 @@ def ogr_wfs_vsimem_wfs110_deletefeature(): gdal.PushErrorHandler() ret = lyr.DeleteFeature(200) gdal.PopErrorHandler() - if ret == 0: - gdaltest.post_reason('fail') - print(gdal.GetLastErrorMsg()) - return 'fail' + assert ret != 0, gdal.GetLastErrorMsg() ds = ogr.Open('WFS:/vsimem/wfs_endpoint', update=1) lyr = ds.GetLayer(0) @@ -3694,10 +2919,7 @@ def ogr_wfs_vsimem_wfs110_deletefeature(): gdal.PushErrorHandler() ret = lyr.DeleteFeature(200) gdal.PopErrorHandler() - if ret == 0 or gdal.GetLastErrorMsg().find('Empty content returned by server') < 0: - gdaltest.post_reason('fail') - print(gdal.GetLastErrorMsg()) - return 'fail' + assert not (ret == 0 or gdal.GetLastErrorMsg().find('Empty content returned by server') < 0) ds = ogr.Open('WFS:/vsimem/wfs_endpoint', update=1) lyr = ds.GetLayer(0) @@ -3705,10 +2927,7 @@ def ogr_wfs_vsimem_wfs110_deletefeature(): gdal.PushErrorHandler() ret = lyr.DeleteFeature(200) gdal.PopErrorHandler() - if ret == 0 or gdal.GetLastErrorMsg().find('Invalid XML content') < 0: - gdaltest.post_reason('fail') - print(gdal.GetLastErrorMsg()) - return 'fail' + assert not (ret == 0 or gdal.GetLastErrorMsg().find('Invalid XML content') < 0) ds = ogr.Open('WFS:/vsimem/wfs_endpoint', update=1) lyr = ds.GetLayer(0) @@ -3716,19 +2935,13 @@ def ogr_wfs_vsimem_wfs110_deletefeature(): gdal.PushErrorHandler() ret = lyr.DeleteFeature(200) gdal.PopErrorHandler() - if ret == 0 or gdal.GetLastErrorMsg().find('Cannot find <TransactionResponse>') < 0: - gdaltest.post_reason('fail') - print(gdal.GetLastErrorMsg()) - return 'fail' + assert not (ret == 0 or gdal.GetLastErrorMsg().find('Cannot find <TransactionResponse>') < 0) ds = ogr.Open('WFS:/vsimem/wfs_endpoint', update=1) lyr = ds.GetLayer(0) gdal.FileFromMemBuffer(wfs_delete_url, "<TransactionResponse/>") ret = lyr.DeleteFeature(200) - if ret != 0: - gdaltest.post_reason('fail') - print(gdal.GetLastErrorMsg()) - return 'fail' + assert ret == 0, gdal.GetLastErrorMsg() gdal.Unlink(wfs_delete_url) wfs_delete_url = """/vsimem/wfs_endpoint&POSTFIELDS=<?xml version="1.0"?> @@ -3749,65 +2962,42 @@ def ogr_wfs_vsimem_wfs110_deletefeature(): gdal.ErrorReset() sql_lyr = ds.ExecuteSQL("DELETE FROM my_layer WHERE gml_id = 'my_layer.200'") - if gdal.GetLastErrorMsg() != '': - gdaltest.post_reason('fail') - print(gdal.GetLastErrorMsg()) - return 'fail' + assert gdal.GetLastErrorMsg() == '' gdal.ErrorReset() gdal.PushErrorHandler() sql_lyr = ds.ExecuteSQL("DELETE FROM ") gdal.PopErrorHandler() - if gdal.GetLastErrorMsg() == '': - gdaltest.post_reason('fail') - print(gdal.GetLastErrorMsg()) - return 'fail' + assert gdal.GetLastErrorMsg() != '' gdal.ErrorReset() gdal.PushErrorHandler() sql_lyr = ds.ExecuteSQL("DELETE FROM non_existing_layer WHERE truc") gdal.PopErrorHandler() - if gdal.GetLastErrorMsg().find('Unknown layer') < 0: - gdaltest.post_reason('fail') - print(gdal.GetLastErrorMsg()) - return 'fail' + assert gdal.GetLastErrorMsg().find('Unknown layer') >= 0 gdal.ErrorReset() gdal.PushErrorHandler() sql_lyr = ds.ExecuteSQL("DELETE FROM my_layer BLA") gdal.PopErrorHandler() - if gdal.GetLastErrorMsg().find('WHERE clause missing') < 0: - gdaltest.post_reason('fail') - print(gdal.GetLastErrorMsg()) - return 'fail' + assert gdal.GetLastErrorMsg().find('WHERE clause missing') >= 0 gdal.ErrorReset() gdal.PushErrorHandler() sql_lyr = ds.ExecuteSQL("DELETE FROM my_layer WHERE -") gdal.PopErrorHandler() - if gdal.GetLastErrorMsg().find('SQL Expression Parsing Error') < 0: - gdaltest.post_reason('fail') - print(gdal.GetLastErrorMsg()) - return 'fail' + assert gdal.GetLastErrorMsg().find('SQL Expression Parsing Error') >= 0 gdal.ErrorReset() gdal.PushErrorHandler() sql_lyr = ds.ExecuteSQL("DELETE FROM my_layer WHERE ogr_geometry = 'POINT'") gdal.PopErrorHandler() - if sql_lyr is not None or gdal.GetLastErrorMsg() == '': - gdaltest.post_reason('fail') - print(gdal.GetLastErrorMsg()) - return 'fail' - - return 'success' + assert sql_lyr is None and gdal.GetLastErrorMsg() != '' ############################################################################### -def ogr_wfs_vsimem_wfs110_schema_not_understood(): - - if gdaltest.wfs_drv is None: - return 'skip' +def test_ogr_wfs_vsimem_wfs110_schema_not_understood(with_and_without_streaming): gdal.SetConfigOption('CPL_CURL_ENABLE_VSIMEM', 'YES') @@ -3851,9 +3041,7 @@ def ogr_wfs_vsimem_wfs110_schema_not_understood(): gdal.PushErrorHandler() lyr_defn = lyr.GetLayerDefn() gdal.PopErrorHandler() - if lyr_defn.GetFieldCount() != 0: - gdaltest.post_reason('fail') - return 'fail' + assert lyr_defn.GetFieldCount() == 0 ds = ogr.Open('WFS:/vsimem/wfs_endpoint_schema_not_understood') lyr = ds.GetLayer(0) @@ -3893,9 +3081,7 @@ def ogr_wfs_vsimem_wfs110_schema_not_understood(): gdal.FileFromMemBuffer('/vsimem/wfs_endpoint_schema_not_understood?SERVICE=WFS&VERSION=1.1.0&REQUEST=GetFeature&TYPENAME=my_layer&MAXFEATURES=1', content) lyr_defn = lyr.GetLayerDefn() - if lyr_defn.GetFieldCount() != 8: - gdaltest.post_reason('fail') - return 'fail' + assert lyr_defn.GetFieldCount() == 8 gdal.FileFromMemBuffer('/vsimem/wfs_endpoint_schema_not_understood?SERVICE=WFS&VERSION=1.1.0&REQUEST=GetFeature&TYPENAME=my_layer', content) @@ -3903,19 +3089,14 @@ def ogr_wfs_vsimem_wfs110_schema_not_understood(): if f.gml_id != 'my_layer.1' or f.boolean != 1 or f.str != 'str' or f.short != 1 or \ f.int != 123456789 or f.float != 1.2 or f.double != 1.23 or f.dt != '2015-04-17T12:34:56Z' or \ f.GetGeometryRef().ExportToWkt() != 'POINT (2 49)': - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' - - return 'success' + pytest.fail() + ############################################################################### -def ogr_wfs_vsimem_wfs110_multiple_layers(): - - if gdaltest.wfs_drv is None: - return 'skip' +def test_ogr_wfs_vsimem_wfs110_multiple_layers(with_and_without_streaming): gdal.FileFromMemBuffer('/vsimem/wfs110_multiple_layers?SERVICE=WFS&REQUEST=GetCapabilities', """<WFS_Capabilities version="1.1.0"> @@ -3947,9 +3128,7 @@ def ogr_wfs_vsimem_wfs110_multiple_layers(): gdal.PushErrorHandler() lyr_defn = lyr.GetLayerDefn() gdal.PopErrorHandler() - if lyr_defn.GetFieldCount() != 0: - gdaltest.post_reason('fail') - return 'fail' + assert lyr_defn.GetFieldCount() == 0 ds = ogr.Open('WFS:/vsimem/wfs110_multiple_layers') lyr = ds.GetLayer(0) @@ -3959,9 +3138,7 @@ def ogr_wfs_vsimem_wfs110_multiple_layers(): gdal.PushErrorHandler() lyr_defn = lyr.GetLayerDefn() gdal.PopErrorHandler() - if lyr_defn.GetFieldCount() != 0: - gdaltest.post_reason('fail') - return 'fail' + assert lyr_defn.GetFieldCount() == 0 ds = ogr.Open('WFS:/vsimem/wfs110_multiple_layers') lyr = ds.GetLayer(0) @@ -3971,9 +3148,7 @@ def ogr_wfs_vsimem_wfs110_multiple_layers(): gdal.PushErrorHandler() lyr_defn = lyr.GetLayerDefn() gdal.PopErrorHandler() - if lyr_defn.GetFieldCount() != 0: - gdaltest.post_reason('fail') - return 'fail' + assert lyr_defn.GetFieldCount() == 0 ds = ogr.Open('WFS:/vsimem/wfs110_multiple_layers') lyr = ds.GetLayer(0) @@ -3983,9 +3158,7 @@ def ogr_wfs_vsimem_wfs110_multiple_layers(): gdal.PushErrorHandler() lyr_defn = lyr.GetLayerDefn() gdal.PopErrorHandler() - if lyr_defn.GetFieldCount() != 0: - gdaltest.post_reason('fail') - return 'fail' + assert lyr_defn.GetFieldCount() == 0 ds = ogr.Open('WFS:/vsimem/wfs110_multiple_layers') lyr = ds.GetLayer(0) @@ -4017,15 +3190,11 @@ def ogr_wfs_vsimem_wfs110_multiple_layers(): lyr = ds.GetLayer(0) lyr_defn = lyr.GetLayerDefn() - if lyr_defn.GetFieldCount() != 2: - gdaltest.post_reason('fail') - return 'fail' + assert lyr_defn.GetFieldCount() == 2 lyr = ds.GetLayer(1) lyr_defn = lyr.GetLayerDefn() - if lyr_defn.GetFieldCount() != 2: - gdaltest.post_reason('fail') - return 'fail' + assert lyr_defn.GetFieldCount() == 2 ds = ogr.Open('WFS:/vsimem/wfs110_multiple_layers') lyr = ds.GetLayer(0) @@ -4047,9 +3216,7 @@ def ogr_wfs_vsimem_wfs110_multiple_layers(): lyr = ds.GetLayer(0) lyr_defn = lyr.GetLayerDefn() - if lyr_defn.GetFieldCount() != 2: - gdaltest.post_reason('fail') - return 'fail' + assert lyr_defn.GetFieldCount() == 2 gdal.FileFromMemBuffer('/vsimem/wfs110_multiple_layers?SERVICE=WFS&VERSION=1.1.0&REQUEST=DescribeFeatureType&TYPENAME=my_layer2', """<xsd:schema xmlns:foo="http://foo" xmlns:gml="http://www.opengis.net/gml" xmlns:xsd="http://www.w3.org/2001/XMLSchema" elementFormDefault="qualified" targetNamespace="http://foo"> @@ -4068,19 +3235,12 @@ def ogr_wfs_vsimem_wfs110_multiple_layers(): """) lyr = ds.GetLayer(1) lyr_defn = lyr.GetLayerDefn() - if lyr_defn.GetFieldCount() != 2: - gdaltest.post_reason('fail') - return 'fail' - - return 'success' + assert lyr_defn.GetFieldCount() == 2 ############################################################################### -def ogr_wfs_vsimem_wfs110_multiple_layers_same_name_different_ns(): - - if gdaltest.wfs_drv is None: - return 'skip' +def test_ogr_wfs_vsimem_wfs110_multiple_layers_same_name_different_ns(with_and_without_streaming): gdal.FileFromMemBuffer('/vsimem/wfs110_multiple_layers_different_ns?SERVICE=WFS&REQUEST=GetCapabilities', """<WFS_Capabilities version="1.1.0"> @@ -4127,9 +3287,7 @@ def ogr_wfs_vsimem_wfs110_multiple_layers_same_name_different_ns(): lyr = ds.GetLayer(0) lyr_defn = lyr.GetLayerDefn() - if lyr_defn.GetFieldCount() != 2: - gdaltest.post_reason('fail') - return 'fail' + assert lyr_defn.GetFieldCount() == 2 gdal.FileFromMemBuffer('/vsimem/wfs110_multiple_layers_different_ns?SERVICE=WFS&VERSION=1.1.0&REQUEST=GetFeature&TYPENAME=ns1:my_layer', """<wfs:FeatureCollection xmlns:xs="http://www.w3.org/2001/XMLSchema" @@ -4152,9 +3310,7 @@ def ogr_wfs_vsimem_wfs110_multiple_layers_same_name_different_ns(): """) f = lyr.GetNextFeature() - if f is None: - gdaltest.post_reason('fail') - return 'fail' + assert f is not None gdal.FileFromMemBuffer('/vsimem/wfs110_multiple_layers_different_ns?SERVICE=WFS&VERSION=1.1.0&REQUEST=DescribeFeatureType&TYPENAME=ns2:my_layer', """<xsd:schema xmlns:ns2="http://ns2" xmlns:ns2="http://ns2" xmlns:gml="http://www.opengis.net/gml" xmlns:xsd="http://www.w3.org/2001/XMLSchema" elementFormDefault="qualified" targetNamespace="http://foo"> @@ -4174,19 +3330,12 @@ def ogr_wfs_vsimem_wfs110_multiple_layers_same_name_different_ns(): """) lyr = ds.GetLayer(1) lyr_defn = lyr.GetLayerDefn() - if lyr_defn.GetFieldCount() != 3: - gdaltest.post_reason('fail') - return 'fail' - - return 'success' + assert lyr_defn.GetFieldCount() == 3 ############################################################################### -def ogr_wfs_vsimem_wfs200_paging(): - - if gdaltest.wfs_drv is None: - return 'skip' +def test_ogr_wfs_vsimem_wfs200_paging(with_and_without_streaming): gdal.FileFromMemBuffer('/vsimem/wfs200_endpoint_paging?SERVICE=WFS&REQUEST=GetCapabilities', """<WFS_Capabilities version="2.0.0"> @@ -4268,10 +3417,7 @@ def ogr_wfs_vsimem_wfs200_paging(): ds = ogr.Open('WFS:/vsimem/wfs200_endpoint_paging') lyr = ds.GetLayer(0) - if lyr.GetMetadata() != {'ABSTRACT': 'abstract', 'KEYWORD_1': 'keyword', 'TITLE': 'title'}: - gdaltest.post_reason('fail') - print(lyr.GetMetadata()) - return 'fail' + assert lyr.GetMetadata() == {'ABSTRACT': 'abstract', 'KEYWORD_1': 'keyword', 'TITLE': 'title'} gdal.FileFromMemBuffer('/vsimem/wfs200_endpoint_paging?SERVICE=WFS&VERSION=2.0.0&REQUEST=DescribeFeatureType&TYPENAME=my_layer', """<xsd:schema xmlns:foo="http://foo" xmlns:gml="http://www.opengis.net/gml" xmlns:xsd="http://www.w3.org/2001/XMLSchema" elementFormDefault="qualified" targetNamespace="http://foo"> @@ -4353,51 +3499,37 @@ def ogr_wfs_vsimem_wfs200_paging(): """) f = lyr.GetNextFeature() - if f is None: - gdaltest.post_reason('fail') - return 'fail' + assert f is not None if f.gml_id != 'my_layer.1': - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' + pytest.fail() f = lyr.GetNextFeature() - if f is None: - gdaltest.post_reason('fail') - return 'fail' + assert f is not None if f.gml_id != 'my_layer.2': - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' + pytest.fail() f = lyr.GetNextFeature() - if f is None: - gdaltest.post_reason('fail') - return 'fail' + assert f is not None if f.gml_id != 'my_layer.3': - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' + pytest.fail() f = lyr.GetNextFeature() if f is not None: - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' + pytest.fail() # if lyr.GetFeatureCount() != 3: # gdaltest.post_reason('fail') # print(lyr.GetFeatureCount()) # return 'fail' - return 'success' - + ############################################################################### -def ogr_wfs_vsimem_wfs200_json(): - - if gdaltest.wfs_drv is None: - return 'skip' +def test_ogr_wfs_vsimem_wfs200_json(with_and_without_streaming): gdal.FileFromMemBuffer('/vsimem/wfs200_endpoint_json?SERVICE=WFS&REQUEST=GetCapabilities', """<WFS_Capabilities version="2.0.0"> @@ -4516,29 +3648,21 @@ def ogr_wfs_vsimem_wfs200_json(): """) f = lyr.GetNextFeature() - if f is None: - gdaltest.post_reason('fail') - return 'fail' + assert f is not None # We currently invert... A bit weird. See comment in code. Probably inappropriate if f.str != 'str' or f.GetGeometryRef().ExportToWkt() != 'POINT (49 2)': - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' + pytest.fail() f = lyr.GetNextFeature() if f is not None: - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' - - return 'success' + pytest.fail() + ############################################################################### -def ogr_wfs_vsimem_wfs200_multipart(): - - if gdaltest.wfs_drv is None: - return 'skip' +def test_ogr_wfs_vsimem_wfs200_multipart(with_and_without_streaming): gdal.FileFromMemBuffer('/vsimem/wfs200_endpoint_multipart?SERVICE=WFS&REQUEST=GetCapabilities', """<WFS_Capabilities version="2.0.0"> @@ -4601,14 +3725,11 @@ def ogr_wfs_vsimem_wfs200_multipart(): """) f = lyr.GetNextFeature() - if f is None: - gdaltest.post_reason('fail') - return 'fail' + assert f is not None # We currently invert... A bit weird. See comment in code. Probably inappropriate if f.str != 'str' or f.GetGeometryRef().ExportToWkt() != 'POINT (49 2)': - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' + pytest.fail() ds = ogr.Open('WFS:/vsimem/wfs200_endpoint_multipart?OUTPUTFORMAT=multipart') lyr = ds.GetLayer(0) @@ -4635,9 +3756,7 @@ def ogr_wfs_vsimem_wfs200_multipart(): """) f = lyr.GetNextFeature() - if f is None: - gdaltest.post_reason('fail') - return 'fail' + assert f is not None ds = ogr.Open('WFS:/vsimem/wfs200_endpoint_multipart?OUTPUTFORMAT=multipart') lyr = ds.GetLayer(0) @@ -4658,24 +3777,17 @@ def ogr_wfs_vsimem_wfs200_multipart(): --my_boundary-- """) f = lyr.GetNextFeature() - if f is None: - gdaltest.post_reason('fail') - return 'fail' + assert f is not None # We currently invert... A bit weird. See comment in code. Probably inappropriate if f.str != 'str' or f.GetGeometryRef().ExportToWkt() != 'POINT (49 2)': - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' - - return 'success' + pytest.fail() + ############################################################################### -def ogr_wfs_vsimem_wfs200_join(): - - if gdaltest.wfs_drv is None: - return 'skip' +def test_ogr_wfs_vsimem_wfs200_join(with_and_without_streaming): gdal.FileFromMemBuffer('/vsimem/wfs200_endpoint_join?SERVICE=WFS&REQUEST=GetCapabilities', """<WFS_Capabilities version="2.0.0"> @@ -4750,9 +3862,7 @@ def ogr_wfs_vsimem_wfs200_join(): gdal.PushErrorHandler() f = sql_lyr.GetNextFeature() gdal.PopErrorHandler() - if f is not None: - gdaltest.post_reason('fail') - return 'fail' + assert f is None ds.ReleaseResultSet(sql_lyr) @@ -4765,10 +3875,7 @@ def ogr_wfs_vsimem_wfs200_join(): gdal.PushErrorHandler() f = sql_lyr.GetNextFeature() gdal.PopErrorHandler() - if f is not None or gdal.GetLastErrorMsg().find('Empty content returned by server') < 0: - gdaltest.post_reason('fail') - print(gdal.GetLastErrorMsg()) - return 'fail' + assert f is None and gdal.GetLastErrorMsg().find('Empty content returned by server') >= 0 ds.ReleaseResultSet(sql_lyr) @@ -4781,10 +3888,7 @@ def ogr_wfs_vsimem_wfs200_join(): gdal.PushErrorHandler() f = sql_lyr.GetNextFeature() gdal.PopErrorHandler() - if f is not None or gdal.GetLastErrorMsg().find('Error returned by server') < 0: - gdaltest.post_reason('fail') - print(gdal.GetLastErrorMsg()) - return 'fail' + assert f is None and gdal.GetLastErrorMsg().find('Error returned by server') >= 0 ds.ReleaseResultSet(sql_lyr) @@ -4797,10 +3901,7 @@ def ogr_wfs_vsimem_wfs200_join(): gdal.PushErrorHandler() f = sql_lyr.GetNextFeature() gdal.PopErrorHandler() - if f is not None or gdal.GetLastErrorMsg().find('Error: cannot parse') < 0: - gdaltest.post_reason('fail') - print(gdal.GetLastErrorMsg()) - return 'fail' + assert f is None and gdal.GetLastErrorMsg().find('Error: cannot parse') >= 0 ds.ReleaseResultSet(sql_lyr) @@ -4813,10 +3914,7 @@ def ogr_wfs_vsimem_wfs200_join(): gdal.PushErrorHandler() f = sql_lyr.GetNextFeature() gdal.PopErrorHandler() - if f is not None or gdal.GetLastErrorMsg().find('Error: cannot parse') < 0: - gdaltest.post_reason('fail') - print(gdal.GetLastErrorMsg()) - return 'fail' + assert f is None and gdal.GetLastErrorMsg().find('Error: cannot parse') >= 0 ds.ReleaseResultSet(sql_lyr) @@ -4901,39 +3999,31 @@ def ogr_wfs_vsimem_wfs200_join(): f['lyr2.gml_id'] != 'lyr2-101' or f['lyr2.str2'] != '123.4' or \ f['lyr1.shape'].ExportToWkt() != 'POINT (2.5 48.5)' or \ f['lyr2.another_shape'].ExportToWkt() != 'POINT (2 49)': - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' + pytest.fail() f = sql_lyr.GetNextFeature() if f['lyr1.gml_id'] != 'lyr1-101' or f['lyr1.str'] != 'foo' or \ f['lyr2.gml_id'] != 'lyr2-102' or f['lyr2.str2'] != 'foo' or \ f['lyr1.shape'].ExportToWkt() != 'POINT (2.5 48.5)' or \ f['lyr2.another_shape'].ExportToWkt() != 'POINT (2 49)': - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' + pytest.fail() f = sql_lyr.GetNextFeature() if f is not None: - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' + pytest.fail() sql_lyr.ResetReading() sql_lyr.ResetReading() f = sql_lyr.GetNextFeature() if f['lyr1.gml_id'] != 'lyr1-100': - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' + pytest.fail() gdal.PushErrorHandler('CPLQuietErrorHandler') fc = sql_lyr.GetFeatureCount() gdal.PopErrorHandler() - if fc != 2: - gdaltest.post_reason('fail') - print(gdal.GetLastErrorMsg()) - print(fc) - return 'fail' + assert fc == 2, gdal.GetLastErrorMsg() # Empty content returned by server gdal.FileFromMemBuffer('/vsimem/wfs200_endpoint_join?SERVICE=WFS&VERSION=2.0.0&REQUEST=GetFeature&TYPENAMES=%28lyr1,lyr2%29&FILTER=%3CFilter%20xmlns%3D%22http:%2F%2Fwww.opengis.net%2Ffes%2F2.0%22%20xmlns:gml%3D%22http:%2F%2Fwww.opengis.net%2Fgml%2F3.2%22%3E%3CPropertyIsEqualTo%3E%3CValueReference%3Elyr1%2Fstr%3C%2FValueReference%3E%3CValueReference%3Elyr2%2Fstr2%3C%2FValueReference%3E%3C%2FPropertyIsEqualTo%3E%3C%2FFilter%3E&RESULTTYPE=hits', @@ -4941,10 +4031,7 @@ def ogr_wfs_vsimem_wfs200_join(): gdal.PushErrorHandler('CPLQuietErrorHandler') fc = sql_lyr.GetFeatureCount() gdal.PopErrorHandler() - if fc != 2: - gdaltest.post_reason('fail') - print(gdal.GetLastErrorMsg()) - return 'fail' + assert fc == 2, gdal.GetLastErrorMsg() # Invalid XML gdal.FileFromMemBuffer('/vsimem/wfs200_endpoint_join?SERVICE=WFS&VERSION=2.0.0&REQUEST=GetFeature&TYPENAMES=%28lyr1,lyr2%29&FILTER=%3CFilter%20xmlns%3D%22http:%2F%2Fwww.opengis.net%2Ffes%2F2.0%22%20xmlns:gml%3D%22http:%2F%2Fwww.opengis.net%2Fgml%2F3.2%22%3E%3CPropertyIsEqualTo%3E%3CValueReference%3Elyr1%2Fstr%3C%2FValueReference%3E%3CValueReference%3Elyr2%2Fstr2%3C%2FValueReference%3E%3C%2FPropertyIsEqualTo%3E%3C%2FFilter%3E&RESULTTYPE=hits', @@ -4952,10 +4039,7 @@ def ogr_wfs_vsimem_wfs200_join(): gdal.PushErrorHandler('CPLQuietErrorHandler') fc = sql_lyr.GetFeatureCount() gdal.PopErrorHandler() - if fc != 2: - gdaltest.post_reason('fail') - print(gdal.GetLastErrorMsg()) - return 'fail' + assert fc == 2, gdal.GetLastErrorMsg() # Server exception gdal.FileFromMemBuffer('/vsimem/wfs200_endpoint_join?SERVICE=WFS&VERSION=2.0.0&REQUEST=GetFeature&TYPENAMES=%28lyr1,lyr2%29&FILTER=%3CFilter%20xmlns%3D%22http:%2F%2Fwww.opengis.net%2Ffes%2F2.0%22%20xmlns:gml%3D%22http:%2F%2Fwww.opengis.net%2Fgml%2F3.2%22%3E%3CPropertyIsEqualTo%3E%3CValueReference%3Elyr1%2Fstr%3C%2FValueReference%3E%3CValueReference%3Elyr2%2Fstr2%3C%2FValueReference%3E%3C%2FPropertyIsEqualTo%3E%3C%2FFilter%3E&RESULTTYPE=hits', @@ -4963,10 +4047,7 @@ def ogr_wfs_vsimem_wfs200_join(): gdal.PushErrorHandler('CPLQuietErrorHandler') fc = sql_lyr.GetFeatureCount() gdal.PopErrorHandler() - if fc != 2: - gdaltest.post_reason('fail') - print(gdal.GetLastErrorMsg()) - return 'fail' + assert fc == 2, gdal.GetLastErrorMsg() # Missing FeatureCollection gdal.FileFromMemBuffer('/vsimem/wfs200_endpoint_join?SERVICE=WFS&VERSION=2.0.0&REQUEST=GetFeature&TYPENAMES=%28lyr1,lyr2%29&FILTER=%3CFilter%20xmlns%3D%22http:%2F%2Fwww.opengis.net%2Ffes%2F2.0%22%20xmlns:gml%3D%22http:%2F%2Fwww.opengis.net%2Fgml%2F3.2%22%3E%3CPropertyIsEqualTo%3E%3CValueReference%3Elyr1%2Fstr%3C%2FValueReference%3E%3CValueReference%3Elyr2%2Fstr2%3C%2FValueReference%3E%3C%2FPropertyIsEqualTo%3E%3C%2FFilter%3E&RESULTTYPE=hits', @@ -4974,10 +4055,7 @@ def ogr_wfs_vsimem_wfs200_join(): gdal.PushErrorHandler('CPLQuietErrorHandler') fc = sql_lyr.GetFeatureCount() gdal.PopErrorHandler() - if fc != 2: - gdaltest.post_reason('fail') - print(gdal.GetLastErrorMsg()) - return 'fail' + assert fc == 2, gdal.GetLastErrorMsg() # Missing FeatureCollection.numberMatched gdal.FileFromMemBuffer('/vsimem/wfs200_endpoint_join?SERVICE=WFS&VERSION=2.0.0&REQUEST=GetFeature&TYPENAMES=%28lyr1,lyr2%29&FILTER=%3CFilter%20xmlns%3D%22http:%2F%2Fwww.opengis.net%2Ffes%2F2.0%22%20xmlns:gml%3D%22http:%2F%2Fwww.opengis.net%2Fgml%2F3.2%22%3E%3CPropertyIsEqualTo%3E%3CValueReference%3Elyr1%2Fstr%3C%2FValueReference%3E%3CValueReference%3Elyr2%2Fstr2%3C%2FValueReference%3E%3C%2FPropertyIsEqualTo%3E%3C%2FFilter%3E&RESULTTYPE=hits', @@ -4985,10 +4063,7 @@ def ogr_wfs_vsimem_wfs200_join(): gdal.PushErrorHandler('CPLQuietErrorHandler') fc = sql_lyr.GetFeatureCount() gdal.PopErrorHandler() - if fc != 2: - gdaltest.post_reason('fail') - print(gdal.GetLastErrorMsg()) - return 'fail' + assert fc == 2, gdal.GetLastErrorMsg() # Valid gdal.FileFromMemBuffer('/vsimem/wfs200_endpoint_join?SERVICE=WFS&VERSION=2.0.0&REQUEST=GetFeature&TYPENAMES=%28lyr1,lyr2%29&FILTER=%3CFilter%20xmlns%3D%22http:%2F%2Fwww.opengis.net%2Ffes%2F2.0%22%20xmlns:gml%3D%22http:%2F%2Fwww.opengis.net%2Fgml%2F3.2%22%3E%3CPropertyIsEqualTo%3E%3CValueReference%3Elyr1%2Fstr%3C%2FValueReference%3E%3CValueReference%3Elyr2%2Fstr2%3C%2FValueReference%3E%3C%2FPropertyIsEqualTo%3E%3C%2FFilter%3E&RESULTTYPE=hits', @@ -5008,10 +4083,7 @@ def ogr_wfs_vsimem_wfs200_join(): gdal.PushErrorHandler('CPLQuietErrorHandler') fc = sql_lyr.GetFeatureCount() gdal.PopErrorHandler() - if fc != 3: - gdaltest.post_reason('fail') - print(gdal.GetLastErrorMsg()) - return 'fail' + assert fc == 3, gdal.GetLastErrorMsg() sql_lyr.TestCapability('foo') sql_lyr.GetLayerDefn() @@ -5036,9 +4108,8 @@ def ogr_wfs_vsimem_wfs200_join(): f['lyr2.gml_id'] != 'lyr2-101' or f['lyr2.str2'] != '123.4' or \ f['lyr1.shape'].ExportToWkt() != 'POINT (2.5 48.5)' or \ f['lyr2.another_shape'].ExportToWkt() != 'POINT (2 49)': - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' + pytest.fail() ds.ReleaseResultSet(sql_lyr) ds = ogr.Open('WFS:/vsimem/wfs200_endpoint_join') @@ -5048,9 +4119,8 @@ def ogr_wfs_vsimem_wfs200_join(): f['lyr2.gml_id'] != 'lyr2-101' or f['lyr2.str2'] != '123.4' or \ f['my_alias1.shape'].ExportToWkt() != 'POINT (2.5 48.5)' or \ f['lyr2.another_shape'].ExportToWkt() != 'POINT (2 49)': - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' + pytest.fail() ds.ReleaseResultSet(sql_lyr) ds = ogr.Open('WFS:/vsimem/wfs200_endpoint_join') @@ -5066,9 +4136,8 @@ def ogr_wfs_vsimem_wfs200_join(): f['str_bigint'] != 123 or \ f['str_float'] != 123.4 or \ f['myshape'].ExportToWkt() != 'POINT (2.5 48.5)': - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' + pytest.fail() ds.ReleaseResultSet(sql_lyr) ds = ogr.Open('WFS:/vsimem/wfs200_endpoint_join') @@ -5111,9 +4180,8 @@ def ogr_wfs_vsimem_wfs200_join(): f['lyr2.gml_id'] != 'lyr2-101' or f['lyr2.str2'] != '123.4' or \ f['lyr1.shape'].ExportToWkt() != 'POINT (2.5 48.5)' or \ f['lyr2.another_shape'].ExportToWkt() != 'POINT (2 49)': - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' + pytest.fail() ds.ReleaseResultSet(sql_lyr) @@ -5122,9 +4190,8 @@ def ogr_wfs_vsimem_wfs200_join(): sql_lyr = ds.ExecuteSQL("SELECT * FROM lyr1 JOIN lyr2 ON lyr1.str = lyr2.str2 WHERE ST_Within(lyr2.another_shape, ST_MakeEnvelope(-180,-90,180,90))") f = sql_lyr.GetNextFeature() if f['lyr1.gml_id'] != 'lyr1-100': - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' + pytest.fail() ds.ReleaseResultSet(sql_lyr) gdal.FileFromMemBuffer('/vsimem/wfs200_endpoint_join?SERVICE=WFS&VERSION=2.0.0&REQUEST=GetFeature&TYPENAMES=%28lyr1,lyr2%29&STARTINDEX=0&COUNT=1&FILTER=%3CFilter%20xmlns%3D%22http:%2F%2Fwww.opengis.net%2Ffes%2F2.0%22%20xmlns:gml%3D%22http:%2F%2Fwww.opengis.net%2Fgml%2F3.2%22%3E%3CPropertyIsEqualTo%3E%3CValueReference%3Elyr1%2Fstr%3C%2FValueReference%3E%3CValueReference%3Elyr2%2Fstr2%3C%2FValueReference%3E%3C%2FPropertyIsEqualTo%3E%3C%2FFilter%3E&SORTBY=str%20DESC', @@ -5132,46 +4199,31 @@ def ogr_wfs_vsimem_wfs200_join(): sql_lyr = ds.ExecuteSQL("SELECT * FROM lyr1 JOIN lyr2 ON lyr1.str = lyr2.str2 ORDER BY lyr1.str DESC") f = sql_lyr.GetNextFeature() if f['lyr1.gml_id'] != 'lyr1-100': - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' + pytest.fail() ds.ReleaseResultSet(sql_lyr) gdal.PushErrorHandler() sql_lyr = ds.ExecuteSQL("SELECT * FROM lyr1 JOIN lyr2 ON lyr1.str = lyr2.str2 WHERE lyr1.OGR_GEOMETRY IS NOT NULL") gdal.PopErrorHandler() - if sql_lyr is not None or gdal.GetLastErrorMsg().find('Unsupported WHERE clause') < 0: - gdaltest.post_reason('fail') - print(gdal.GetLastErrorMsg()) - return 'fail' + assert sql_lyr is None and gdal.GetLastErrorMsg().find('Unsupported WHERE clause') >= 0 gdal.PushErrorHandler() sql_lyr = ds.ExecuteSQL("SELECT * FROM lyr1 JOIN lyr2 ON lyr1.OGR_GEOMETRY IS NOT NULL") gdal.PopErrorHandler() - if sql_lyr is not None or gdal.GetLastErrorMsg().find('Unsupported JOIN clause') < 0: - gdaltest.post_reason('fail') - print(gdal.GetLastErrorMsg()) - return 'fail' + assert sql_lyr is None and gdal.GetLastErrorMsg().find('Unsupported JOIN clause') >= 0 gdal.PushErrorHandler() sql_lyr = ds.ExecuteSQL("SELECT 1 FROM lyr1 JOIN lyr2 ON lyr1.str = lyr2.str2") gdal.PopErrorHandler() - if sql_lyr is not None or gdal.GetLastErrorMsg().find('Only column names supported in column selection') < 0: - gdaltest.post_reason('fail') - print(gdal.GetLastErrorMsg()) - return 'fail' + assert sql_lyr is None and gdal.GetLastErrorMsg().find('Only column names supported in column selection') >= 0 ds = None - return 'success' - ############################################################################### -def ogr_wfs_vsimem_wfs200_join_layer_with_namespace_prefix(): - - if gdaltest.wfs_drv is None: - return 'skip' +def test_ogr_wfs_vsimem_wfs200_join_layer_with_namespace_prefix(with_and_without_streaming): gdal.FileFromMemBuffer('/vsimem/wfs200_endpoint_join?SERVICE=WFS&REQUEST=GetCapabilities', """<WFS_Capabilities version="2.0.0"> @@ -5277,21 +4329,15 @@ def ogr_wfs_vsimem_wfs200_join_layer_with_namespace_prefix(): f['lyr2.gml_id'] != 'lyr2-101' or f['lyr2.str2'] != '123.4' or \ f['lyr1.shape'].ExportToWkt() != 'POINT (2.5 48.5)' or \ f['lyr2.another_shape'].ExportToWkt() != 'POINT (2 49)': - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' + pytest.fail() ds.ReleaseResultSet(sql_lyr) - return 'success' - ############################################################################### -def ogr_wfs_vsimem_wfs200_join_distinct(): - - if gdaltest.wfs_drv is None: - return 'skip' +def test_ogr_wfs_vsimem_wfs200_join_distinct(with_and_without_streaming): gdal.FileFromMemBuffer('/vsimem/wfs200_endpoint_join?SERVICE=WFS&REQUEST=GetCapabilities', """<WFS_Capabilities version="2.0.0"> @@ -5444,124 +4490,20 @@ def ogr_wfs_vsimem_wfs200_join_distinct(): </wfs:member> </wfs:FeatureCollection> """) - if sql_lyr.GetFeatureCount() != 2: - gdaltest.post_reason('fail') - return 'fail' + assert sql_lyr.GetFeatureCount() == 2 ds.ReleaseResultSet(sql_lyr) - return 'success' - ############################################################################### -def ogr_wfs_vsimem_cleanup(): - - if gdaltest.wfs_drv is None: - return 'skip' +def test_ogr_wfs_vsimem_cleanup(with_and_without_streaming): gdal.SetConfigOption('CPL_CURL_ENABLE_VSIMEM', None) for f in gdal.ReadDir('/vsimem/'): gdal.Unlink('/vsimem/' + f) - return 'success' - - -gdaltest_live_list = [ - # ogr_wfs_mapserver, - # ogr_wfs_geoserver, #FIXME: re-enable after adapting test - # ogr_wfs_geoserver_json, #FIXME: re-enable after adapting test - # ogr_wfs_geoserver_shapezip, #FIXME: re-enable after adapting test - # ogr_wfs_geoserver_paging, #FIXME: re-enable after adapting test - # ogr_wfs_deegree, - # ogr_wfs_test_ogrsf, - ogr_wfs_fake_wfs_server, - # ogr_wfs_geoserver_wfst, #FIXME: re-enable after adapting test - # ogr_wfs_deegree_wfst, - # ogr_wfs_ionic_wfst, - # ogr_wfs_ionic_sql, - ogr_wfs_xmldescriptionfile, - # ogr_wfs_xmldescriptionfile_to_be_updated, #FIXME: re-enable after adapting test - ogr_wfs_getcapabilitiesfile, - # ogr_wfs_deegree_gml321, - # ogr_wfs_deegree_wfs200, - # ogr_wfs_deegree_sortby, - # ogr_wfs_esri, - ogr_wfs_esri_2, - ogr_wfs_cubewerx, - ogr_wfs_tinyows, - ogr_wfs_erdas_apollo, - ogr_wfs_intergraph, - ogr_wfs_mapinfo, - ogr_wfs_turn_streaming_off, - # ogr_wfs_deegree, - # ogr_wfs_test_ogrsf, -] - -gdaltest_vsimem_list = [ - ogr_wfs_vsimem_fail_because_not_enabled, - ogr_wfs_vsimem_fail_because_no_get_capabilities, - ogr_wfs_vsimem_fail_because_empty_response, - ogr_wfs_vsimem_fail_because_no_WFS_Capabilities, - ogr_wfs_vsimem_fail_because_exception, - ogr_wfs_vsimem_fail_because_invalid_xml_capabilities, - ogr_wfs_vsimem_fail_because_missing_featuretypelist, - ogr_wfs_vsimem_wfs110_open_getcapabilities_file, - ogr_wfs_vsimem_wfs110_minimal_instance, - ogr_wfs_vsimem_wfs110_one_layer_missing_describefeaturetype, - ogr_wfs_vsimem_wfs110_one_layer_invalid_describefeaturetype, - ogr_wfs_vsimem_wfs110_one_layer_describefeaturetype_missing_schema, - ogr_wfs_vsimem_wfs110_one_layer_describefeaturetype, - ogr_wfs_vsimem_wfs110_one_layer_xmldescriptionfile_to_be_updated, - ogr_wfs_vsimem_wfs110_one_layer_missing_getfeaturecount_no_hits, - ogr_wfs_vsimem_wfs110_one_layer_missing_getfeaturecount_with_hits, - ogr_wfs_vsimem_wfs110_one_layer_invalid_getfeaturecount_with_hits, - ogr_wfs_vsimem_wfs110_one_layer_getfeaturecount_with_hits_missing_FeatureCollection, - ogr_wfs_vsimem_wfs110_one_layer_getfeaturecount_with_hits_invalid_xml, - ogr_wfs_vsimem_wfs110_one_layer_getfeaturecount_with_hits_ServiceExceptionReport, - ogr_wfs_vsimem_wfs110_one_layer_getfeaturecount_with_hits_missing_numberOfFeatures, - ogr_wfs_vsimem_wfs110_one_layer_getfeaturecount_with_hits, - ogr_wfs_vsimem_wfs110_one_layer_missing_getfeature, - ogr_wfs_vsimem_wfs110_one_layer_invalid_getfeature, - ogr_wfs_vsimem_wfs110_one_layer_exception_getfeature, - ogr_wfs_vsimem_wfs110_one_layer_getfeature, - ogr_wfs_vsimem_wfs110_one_layer_getextent, - ogr_wfs_vsimem_wfs110_one_layer_getextent_without_getfeature, - ogr_wfs_vsimem_wfs110_one_layer_getextent_optimized, - ogr_wfs_vsimem_wfs110_one_layer_getfeature_ogr_getfeature, - ogr_wfs_vsimem_wfs110_one_layer_filter_gml_id_failed, - ogr_wfs_vsimem_wfs110_one_layer_filter_gml_id_success, - ogr_wfs_vsimem_wfs110_one_layer_filter, - ogr_wfs_vsimem_wfs110_one_layer_filter_spatial_ops, - ogr_wfs_vsimem_wfs110_one_layer_spatial_filter, - ogr_wfs_vsimem_wfs110_one_layer_spatial_filter_and_attribute_filter, - ogr_wfs_vsimem_wfs110_insertfeature, - ogr_wfs_vsimem_wfs110_updatefeature, - ogr_wfs_vsimem_wfs110_deletefeature, - ogr_wfs_vsimem_wfs110_schema_not_understood, - ogr_wfs_vsimem_wfs110_multiple_layers, - ogr_wfs_vsimem_wfs110_multiple_layers_same_name_different_ns, - ogr_wfs_vsimem_wfs200_paging, - ogr_wfs_vsimem_wfs200_json, - ogr_wfs_vsimem_wfs200_multipart, - ogr_wfs_vsimem_wfs200_join, - ogr_wfs_vsimem_wfs200_join_layer_with_namespace_prefix, - ogr_wfs_vsimem_wfs200_join_distinct, - ogr_wfs_vsimem_cleanup, -] - -gdaltest_list = [ogr_wfs_init] -gdaltest_list += gdaltest_vsimem_list -gdaltest_list += [ogr_wfs_turn_streaming_off] -gdaltest_list += gdaltest_vsimem_list -gdaltest_list += [ogr_wfs_turn_streaming_on] -gdaltest_list += gdaltest_live_list - -if __name__ == '__main__': - - gdaltest.setup_run('ogr_wfs') + - gdaltest.run_tests(gdaltest_list) - sys.exit(gdaltest.summarize()) diff --git a/autotest/ogr/ogr_wfs3.py b/autotest/ogr/ogr_wfs3.py index 5153840f791f..1aebb2008270 100755 --- a/autotest/ogr/ogr_wfs3.py +++ b/autotest/ogr/ogr_wfs3.py @@ -29,50 +29,46 @@ # DEALINGS IN THE SOFTWARE. ############################################################################### -import sys -sys.path.append('../pymod') import gdaltest from osgeo import ogr import webserver +import pytest ############################################################################### # Init # -def ogr_wfs3_init(): +def test_ogr_wfs3_init(): gdaltest.wfs3_drv = ogr.GetDriverByName('WFS3') if gdaltest.wfs3_drv is None: - 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 ogr_wfs3_errors(): +def test_ogr_wfs3_errors(): if gdaltest.wfs3_drv is None: - return 'skip' + pytest.skip() if gdaltest.webserver_port == 0: - return 'skip' + pytest.skip() handler = webserver.SequentialHandler() handler.add('GET', '/wfs3/collections', 404) with webserver.install_http_handler(handler): with gdaltest.error_handler(): ds = ogr.Open('WFS3:http://localhost:%d/wfs3' % gdaltest.webserver_port) - if ds is not None: - gdaltest.post_reason('fail') - return 'fail' + assert ds is None # No Content-Type handler = webserver.SequentialHandler() @@ -80,9 +76,7 @@ def ogr_wfs3_errors(): with webserver.install_http_handler(handler): with gdaltest.error_handler(): ds = ogr.Open('WFS3:http://localhost:%d/wfs3' % gdaltest.webserver_port) - if ds is not None: - gdaltest.post_reason('fail') - return 'fail' + assert ds is None # Unexpected Content-Type handler = webserver.SequentialHandler() @@ -91,9 +85,7 @@ def ogr_wfs3_errors(): with webserver.install_http_handler(handler): with gdaltest.error_handler(): ds = ogr.Open('WFS3:http://localhost:%d/wfs3' % gdaltest.webserver_port) - if ds is not None: - gdaltest.post_reason('fail') - return 'fail' + assert ds is None # Invalid JSON handler = webserver.SequentialHandler() @@ -102,9 +94,7 @@ def ogr_wfs3_errors(): with webserver.install_http_handler(handler): with gdaltest.error_handler(): ds = ogr.Open('WFS3:http://localhost:%d/wfs3' % gdaltest.webserver_port) - if ds is not None: - gdaltest.post_reason('fail') - return 'fail' + assert ds is None # Valid JSON but not collections array handler = webserver.SequentialHandler() @@ -113,9 +103,7 @@ def ogr_wfs3_errors(): with webserver.install_http_handler(handler): with gdaltest.error_handler(): ds = ogr.Open('WFS3:http://localhost:%d/wfs3' % gdaltest.webserver_port) - if ds is not None: - gdaltest.post_reason('fail') - return 'fail' + assert ds is None # Valid JSON but collections is not an array handler = webserver.SequentialHandler() @@ -125,9 +113,7 @@ def ogr_wfs3_errors(): with webserver.install_http_handler(handler): with gdaltest.error_handler(): ds = ogr.Open('WFS3:http://localhost:%d/wfs3' % gdaltest.webserver_port) - if ds is not None: - gdaltest.post_reason('fail') - return 'fail' + assert ds is None handler = webserver.SequentialHandler() handler.add('GET', '/wfs3/collections', 200, @@ -135,30 +121,20 @@ def ogr_wfs3_errors(): '{ "collections" : [ null, {} ] }') with webserver.install_http_handler(handler): ds = ogr.Open('WFS3:http://localhost:%d/wfs3' % gdaltest.webserver_port) - if ds is None: - gdaltest.post_reason('fail') - return 'fail' - if ds.GetLayerCount() != 0: - gdaltest.post_reason('fail') - return 'fail' - if ds.GetLayer(-1) is not None: - gdaltest.post_reason('fail') - return 'fail' - if ds.GetLayer(0) is not None: - gdaltest.post_reason('fail') - return 'fail' - - return 'success' + assert ds is not None + assert ds.GetLayerCount() == 0 + assert ds.GetLayer(-1) is None + assert ds.GetLayer(0) is None ############################################################################### -def ogr_wfs3_empty_layer(): +def test_ogr_wfs3_empty_layer(): if gdaltest.wfs3_drv is None: - return 'skip' + pytest.skip() if gdaltest.webserver_port == 0: - return 'skip' + pytest.skip() handler = webserver.SequentialHandler() handler.add('GET', '/wfs3/collections', 200, @@ -166,37 +142,28 @@ def ogr_wfs3_empty_layer(): '{ "collections" : [ { "name": "foo" }] }') with webserver.install_http_handler(handler): ds = ogr.Open('WFS3:http://localhost:%d/wfs3' % gdaltest.webserver_port) - if ds is None: - gdaltest.post_reason('fail') - return 'fail' - if ds.GetLayerCount() != 1: - gdaltest.post_reason('fail') - return 'fail' + assert ds is not None + assert ds.GetLayerCount() == 1 lyr = ds.GetLayer(0) - if lyr.GetName() != 'foo': - gdaltest.post_reason('fail') - return 'fail' + assert lyr.GetName() == 'foo' handler = webserver.SequentialHandler() handler.add('GET', '/wfs3/collections/foo/items?limit=10', 200, {'Content-Type': 'application/geo+json'}, '{ "type": "FeatureCollection", "features": [] }') with webserver.install_http_handler(handler): - if lyr.GetLayerDefn().GetFieldCount() != 0: - gdaltest.post_reason('fail') - return 'fail' - - return 'success' + assert lyr.GetLayerDefn().GetFieldCount() == 0 + ############################################################################### -def ogr_wfs3_fc_links_next_geojson(): +def test_ogr_wfs3_fc_links_next_geojson(): if gdaltest.wfs3_drv is None: - return 'skip' + pytest.skip() if gdaltest.webserver_port == 0: - return 'skip' + pytest.skip() handler = webserver.SequentialHandler() handler.add('GET', '/wfs3/collections', 200, {'Content-Type': 'application/json'}, @@ -217,9 +184,7 @@ def ogr_wfs3_fc_links_next_geojson(): } ] }""") with webserver.install_http_handler(handler): - if lyr.GetLayerDefn().GetFieldCount() != 1: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.GetLayerDefn().GetFieldCount() == 1 handler = webserver.SequentialHandler() handler.add('GET', '/wfs3/collections/foo/items?limit=10', 200, @@ -239,9 +204,8 @@ def ogr_wfs3_fc_links_next_geojson(): with webserver.install_http_handler(handler): f = lyr.GetNextFeature() if f['foo'] != 'bar': - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' + pytest.fail() handler = webserver.SequentialHandler() handler.add('GET', '/wfs3/foo_next', 200, @@ -258,21 +222,19 @@ def ogr_wfs3_fc_links_next_geojson(): with webserver.install_http_handler(handler): f = lyr.GetNextFeature() if f['foo'] != 'baz': - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' - - return 'success' + pytest.fail() + ############################################################################### -def ogr_wfs3_fc_links_next_headers(): +def test_ogr_wfs3_fc_links_next_headers(): if gdaltest.wfs3_drv is None: - return 'skip' + pytest.skip() if gdaltest.webserver_port == 0: - return 'skip' + pytest.skip() handler = webserver.SequentialHandler() handler.add('GET', '/wfs3/collections', 200, {'Content-Type': 'application/json'}, @@ -293,9 +255,7 @@ def ogr_wfs3_fc_links_next_headers(): } ] }""") with webserver.install_http_handler(handler): - if lyr.GetLayerDefn().GetFieldCount() != 1: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.GetLayerDefn().GetFieldCount() == 1 handler = webserver.SequentialHandler() link_val = '<http://data.example.org/buildings.json>; rel="self"; type="application/geo+json"\r\nLink: <http://localhost:%d/wfs3/foo_next>; rel="next"; type="application/geo+json"' % gdaltest.webserver_port @@ -314,9 +274,8 @@ def ogr_wfs3_fc_links_next_headers(): with webserver.install_http_handler(handler): f = lyr.GetNextFeature() if f['foo'] != 'bar': - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' + pytest.fail() handler = webserver.SequentialHandler() handler.add('GET', '/wfs3/foo_next', 200, @@ -333,21 +292,19 @@ def ogr_wfs3_fc_links_next_headers(): with webserver.install_http_handler(handler): f = lyr.GetNextFeature() if f['foo'] != 'baz': - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' - - return 'success' + pytest.fail() + ############################################################################### -def ogr_wfs3_spatial_filter(): +def test_ogr_wfs3_spatial_filter(): if gdaltest.wfs3_drv is None: - return 'skip' + pytest.skip() if gdaltest.webserver_port == 0: - return 'skip' + pytest.skip() handler = webserver.SequentialHandler() handler.add('GET', '/wfs3/collections', 200, {'Content-Type': 'application/json'}, @@ -360,10 +317,7 @@ def ogr_wfs3_spatial_filter(): with webserver.install_http_handler(handler): ds = ogr.Open('WFS3:http://localhost:%d/wfs3' % gdaltest.webserver_port) lyr = ds.GetLayer(0) - if lyr.GetExtent() != (-10.0, 15.0, 40.0, 50.0): - gdaltest.post_reason('fail') - print(lyr.GetExtent()) - return 'fail' + assert lyr.GetExtent() == (-10.0, 15.0, 40.0, 50.0) handler = webserver.SequentialHandler() handler.add('GET', '/wfs3/collections/foo/items?limit=10', 200, @@ -377,9 +331,7 @@ def ogr_wfs3_spatial_filter(): } ] }""") with webserver.install_http_handler(handler): - if lyr.GetLayerDefn().GetFieldCount() != 1: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.GetLayerDefn().GetFieldCount() == 1 lyr.SetSpatialFilterRect(2, 49, 3, 50) handler = webserver.SequentialHandler() @@ -399,9 +351,7 @@ def ogr_wfs3_spatial_filter(): ] }""") with webserver.install_http_handler(handler): f = lyr.GetNextFeature() - if f is None: - gdaltest.post_reason('fail') - return 'fail' + assert f is not None lyr.SetSpatialFilter(None) lyr.ResetReading() @@ -417,21 +367,17 @@ def ogr_wfs3_spatial_filter(): ] }""") with webserver.install_http_handler(handler): f = lyr.GetNextFeature() - if f is None: - gdaltest.post_reason('fail') - return 'fail' - - return 'success' + assert f is not None ############################################################################### -def ogr_wfs3_get_feature_count(): +def test_ogr_wfs3_get_feature_count(): if gdaltest.wfs3_drv is None: - return 'skip' + pytest.skip() if gdaltest.webserver_port == 0: - return 'skip' + pytest.skip() handler = webserver.SequentialHandler() handler.add('GET', '/wfs3/collections', 200, {'Content-Type': 'application/json'}, @@ -478,30 +424,25 @@ def ogr_wfs3_get_feature_count(): {'Content-Type': 'application/json'}, '{ "numberMatched": 1234 }') with webserver.install_http_handler(handler): - if lyr.GetFeatureCount() != 1234: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.GetFeatureCount() == 1234 handler = webserver.SequentialHandler() handler.add('GET', '/wfs3/collections/foo/items?resultType=hits', 200, {'Content-Type': 'application/json'}, '{ "numberMatched": 1234 }') with webserver.install_http_handler(handler): - if lyr.GetFeatureCount() != 1234: - gdaltest.post_reason('fail') - return 'fail' - - return 'success' + assert lyr.GetFeatureCount() == 1234 + ############################################################################### -def ogr_wfs3_attribute_filter(): +def test_ogr_wfs3_attribute_filter(): if gdaltest.wfs3_drv is None: - return 'skip' + pytest.skip() if gdaltest.webserver_port == 0: - return 'skip' + pytest.skip() handler = webserver.SequentialHandler() handler.add('GET', '/wfs3/collections', 200, {'Content-Type': 'application/json'}, @@ -572,9 +513,7 @@ def ogr_wfs3_attribute_filter(): ] }""") with webserver.install_http_handler(handler): f = lyr.GetNextFeature() - if f is None: - gdaltest.post_reason('fail') - return 'fail' + assert f is not None lyr.ResetReading() lyr.SetAttributeFilter("attr1 = 'foo' OR attr3 = 'bar'") @@ -592,9 +531,7 @@ def ogr_wfs3_attribute_filter(): ] }""") with webserver.install_http_handler(handler): f = lyr.GetNextFeature() - if f is None: - gdaltest.post_reason('fail') - return 'fail' + assert f is not None lyr.ResetReading() lyr.SetAttributeFilter(None) @@ -612,42 +549,19 @@ def ogr_wfs3_attribute_filter(): ] }""") with webserver.install_http_handler(handler): f = lyr.GetNextFeature() - if f is None: - gdaltest.post_reason('fail') - return 'fail' - - return 'success' + assert f is not None ############################################################################### -def ogr_wfs3_cleanup(): +def test_ogr_wfs3_cleanup(): if gdaltest.wfs3_drv is None: - return 'skip' + pytest.skip() if gdaltest.webserver_port != 0: webserver.server_stop(gdaltest.webserver_process, gdaltest.webserver_port) - return 'success' - - -gdaltest_list = [ - ogr_wfs3_init, - ogr_wfs3_errors, - ogr_wfs3_empty_layer, - ogr_wfs3_fc_links_next_geojson, - ogr_wfs3_fc_links_next_headers, - ogr_wfs3_spatial_filter, - ogr_wfs3_get_feature_count, - ogr_wfs3_attribute_filter, - ogr_wfs3_cleanup, -] - -if __name__ == '__main__': - - gdaltest.setup_run('ogr_wfs3') + - gdaltest.run_tests(gdaltest_list) - sys.exit(gdaltest.summarize()) diff --git a/autotest/ogr/ogr_wkbwkt_geom.py b/autotest/ogr/ogr_wkbwkt_geom.py index 456ed2e2e75b..42adcaf04c8f 100755 --- a/autotest/ogr/ogr_wkbwkt_geom.py +++ b/autotest/ogr/ogr_wkbwkt_geom.py @@ -28,9 +28,8 @@ ############################################################################### import os -import sys -sys.path.append('../pymod') +import pytest import gdaltest from osgeo import ogr @@ -39,46 +38,45 @@ ############################################################################### -class wkb_wkt_unit(object): - def __init__(self, unit): - self.unit = unit +@pytest.mark.parametrize( + 'filename', + [ + f for f in os.listdir(os.path.join(os.path.dirname(__file__), 'data/wkb_wkt')) + if f[-4:] == '.wkb' + ] +) +def test_wkbwkt_geom(filename): + raw_wkb = open('data/wkb_wkt/' + filename, 'rb').read() + raw_wkt = open('data/wkb_wkt/' + os.path.splitext(filename)[0] + '.wkt').read() - def wkbwkt_geom(self): - raw_wkb = open('data/wkb_wkt/' + self.unit + '.wkb', 'rb').read() - raw_wkt = open('data/wkb_wkt/' + self.unit + '.wkt').read() + ###################################################################### + # Compare the WKT derived from the WKB file to the WKT provided + # but reformatted (normalized). - ###################################################################### - # Compare the WKT derived from the WKB file to the WKT provided - # but reformatted (normalized). + geom_wkb = ogr.CreateGeometryFromWkb(raw_wkb) + wkb_wkt = geom_wkb.ExportToWkt() - geom_wkb = ogr.CreateGeometryFromWkb(raw_wkb) - wkb_wkt = geom_wkb.ExportToWkt() + geom_wkt = ogr.CreateGeometryFromWkt(raw_wkt) + normal_wkt = geom_wkt.ExportToWkt() - geom_wkt = ogr.CreateGeometryFromWkt(raw_wkt) - normal_wkt = geom_wkt.ExportToWkt() + # print(wkb_wkt) + # print(normal_wkt) + # print(raw_wkt) + assert wkb_wkt == normal_wkt, \ + ('WKT from WKB (%s) does not match clean WKT (%s).' % (wkb_wkt, normal_wkt)) - # print(wkb_wkt) - # print(normal_wkt) - # print(raw_wkt) - if wkb_wkt != normal_wkt: - gdaltest.post_reason('WKT from WKB (%s) does not match clean WKT (%s).' % (wkb_wkt, normal_wkt)) - return 'fail' + ###################################################################### + # Verify that the geometries appear to be the same. This is + # intended to catch problems with the encoding too WKT that might + # cause passes above but that are mistaken. + assert geom_wkb.GetCoordinateDimension() == geom_wkt.GetCoordinateDimension(), \ + 'Coordinate dimension differs!' - ###################################################################### - # Verify that the geometries appear to be the same. This is - # intended to catch problems with the encoding too WKT that might - # cause passes above but that are mistaken. - if geom_wkb.GetCoordinateDimension() != geom_wkt.GetCoordinateDimension(): - gdaltest.post_reason('Coordinate dimension differs!') - return 'fail' + assert geom_wkb.GetGeometryType() == geom_wkt.GetGeometryType(), \ + 'Geometry type differs!' - if geom_wkb.GetGeometryType() != geom_wkt.GetGeometryType(): - gdaltest.post_reason('Geometry type differs!') - return 'fail' - - if geom_wkb.GetGeometryName() != geom_wkt.GetGeometryName(): - gdaltest.post_reason('Geometry name differs!') - return 'fail' + assert geom_wkb.GetGeometryName() == geom_wkt.GetGeometryName(), \ + 'Geometry name differs!' # It turns out this test is too picky about coordinate precision. skip. # if geom_wkb.Equal( geom_wkt ) == 0: @@ -87,41 +85,33 @@ def wkbwkt_geom(self): # print geom_wkt.ExportToWkt() # return 'fail' - geom_wkb.Destroy() - - ###################################################################### - # Convert geometry to WKB and back to verify that WKB encoding is - # working smoothly. + geom_wkb.Destroy() - wkb_xdr = geom_wkt.ExportToWkb(ogr.wkbXDR) - geom_wkb = ogr.CreateGeometryFromWkb(wkb_xdr) + ###################################################################### + # Convert geometry to WKB and back to verify that WKB encoding is + # working smoothly. - if str(geom_wkb) != str(geom_wkt): - print(geom_wkb) - print(geom_wkt) - gdaltest.post_reason('XDR WKB encoding/decoding failure.') - return 'fail' + wkb_xdr = geom_wkt.ExportToWkb(ogr.wkbXDR) + geom_wkb = ogr.CreateGeometryFromWkb(wkb_xdr) - geom_wkb.Destroy() + assert str(geom_wkb) == str(geom_wkt), 'XDR WKB encoding/decoding failure.' - wkb_ndr = geom_wkt.ExportToWkb(ogr.wkbNDR) - geom_wkb = ogr.CreateGeometryFromWkb(wkb_ndr) + geom_wkb.Destroy() - if str(geom_wkb) != str(geom_wkt): - gdaltest.post_reason('NDR WKB encoding/decoding failure.') - return 'fail' + wkb_ndr = geom_wkt.ExportToWkb(ogr.wkbNDR) + geom_wkb = ogr.CreateGeometryFromWkb(wkb_ndr) - geom_wkb.Destroy() + assert str(geom_wkb) == str(geom_wkt), 'NDR WKB encoding/decoding failure.' - geom_wkt.Destroy() + geom_wkb.Destroy() - return 'success' + geom_wkt.Destroy() ############################################################################### # Test geometry with very large exponents of coordinate values. -def ogr_wkbwkt_geom_bigexponents(): +def test_ogr_wkbwkt_geom_bigexponents(): bigx = -1.79769313486e+308 bigy = -1.12345678901e+308 @@ -132,18 +122,13 @@ def ogr_wkbwkt_geom_bigexponents(): expect = 'POINT (-1.79769313486e+308 -1.12345678901e+308 0)' wkt = geom.ExportToWkt() - if str(wkt) != str(expect): - print(wkt) - gdaltest.post_reason('trimming long float numbers failed.') - return 'fail' - - return 'success' + assert str(wkt) == str(expect), 'trimming long float numbers failed.' ############################################################################### # Test importing broken/unhandled WKT. -def ogr_wkbwkt_test_broken_geom(): +def test_ogr_wkbwkt_test_broken_geom(): list_broken = ['POINT', 'POINT UNKNOWN', @@ -373,18 +358,14 @@ def ogr_wkbwkt_test_broken_geom(): gdal.PushErrorHandler('CPLQuietErrorHandler') geom = ogr.CreateGeometryFromWkt(wkt) gdal.PopErrorHandler() - if geom is not None: - gdaltest.post_reason( - 'geom %s instantiated but not expected' % wkt) - return 'fail' - - return 'success' + assert geom is None, ('geom %s instantiated but not expected' % wkt) + ############################################################################### # Test importing WKT SF1.2 -def ogr_wkbwkt_test_import_wkt_sf12(): +def test_ogr_wkbwkt_test_import_wkt_sf12(): list_wkt_tuples = [('POINT EMPTY', 'POINT EMPTY'), ('POINT Z EMPTY', 'POINT EMPTY'), @@ -497,41 +478,32 @@ def ogr_wkbwkt_test_import_wkt_sf12(): for wkt_tuple in list_wkt_tuples: geom = ogr.CreateGeometryFromWkt(wkt_tuple[0]) - if geom is None: - gdaltest.post_reason( - 'could not instantiate geometry %s' % wkt_tuple[0]) - return 'fail' + assert geom is not None, ('could not instantiate geometry %s' % wkt_tuple[0]) out_wkt = geom.ExportToWkt() - if out_wkt != wkt_tuple[1]: - gdaltest.post_reason( - 'in=%s, out=%s, expected=%s.' % (wkt_tuple[0], out_wkt, + assert out_wkt == wkt_tuple[1], \ + ('in=%s, out=%s, expected=%s.' % (wkt_tuple[0], out_wkt, wkt_tuple[1])) - return 'fail' - - return 'success' + ############################################################################### # Test that importing the wkb that would be equivalent to MULTIPOINT(POLYGON((0 0)) # doesn't work -def ogr_wkbwkt_test_import_bad_multipoint_wkb(): +def test_ogr_wkbwkt_test_import_bad_multipoint_wkb(): import struct wkb = struct.pack('B' * 30, 0, 0, 0, 0, 6, 0, 0, 0, 1, 0, 0, 0, 0, 1, 64, 0, 0, 0, 0, 0, 0, 0, 64, 0, 0, 0, 0, 0, 0, 0) gdal.PushErrorHandler('CPLQuietErrorHandler') geom = ogr.CreateGeometryFromWkb(wkb) gdal.PopErrorHandler() - if geom is not None: - return 'fail' - - return 'success' + assert geom is None ############################################################################### # Test WKT -> WKB -> WKT roundtripping for GEOMETRYCOLLECTION -def ogr_wkbwkt_test_geometrycollection_wktwkb(): +def test_ogr_wkbwkt_test_geometrycollection_wktwkb(): wkt_list = ['GEOMETRYCOLLECTION (POINT (0 1))', 'GEOMETRYCOLLECTION (LINESTRING (0 1,2 3))', @@ -551,44 +523,32 @@ def ogr_wkbwkt_test_geometrycollection_wktwkb(): wkb = g.ExportToWkb() g = ogr.CreateGeometryFromWkb(wkb) wkt2 = g.ExportToWkt() - if wkt != wkt2: - gdaltest.post_reason('fail for %s' % wkt) - print(wkt) - print(wkt2) - return 'fail' - - return 'success' + assert wkt == wkt2, ('fail for %s' % wkt) + ############################################################################### # Test that importing too nested WKT doesn't cause stack overflows -def ogr_wkbwkt_test_geometrycollection_wkt_recursion(): +def test_ogr_wkbwkt_test_geometrycollection_wkt_recursion(): wkt = 'GEOMETRYCOLLECTION (' * 31 + 'GEOMETRYCOLLECTION EMPTY' + ')' * 31 geom = ogr.CreateGeometryFromWkt(wkt) - if geom.ExportToWkt() != wkt: - gdaltest.post_reason('expected %s' % wkt) - print(geom.ExportToWkt()) - return 'fail' + assert geom.ExportToWkt() == wkt, ('expected %s' % wkt) wkt = 'GEOMETRYCOLLECTION (' * 32 + 'GEOMETRYCOLLECTION EMPTY' + ')' * 32 gdal.PushErrorHandler('CPLQuietErrorHandler') geom = ogr.CreateGeometryFromWkt(wkt) gdal.PopErrorHandler() - if geom is not None: - gdaltest.post_reason('expected None') - return 'fail' - - return 'success' + assert geom is None, 'expected None' ############################################################################### # Test that importing too nested WKB doesn't cause stack overflows -def ogr_wkbwkt_test_geometrycollection_wkb_recursion(): +def test_ogr_wkbwkt_test_geometrycollection_wkb_recursion(): import struct wkb_repeat = struct.pack('B' * 9, 0, 0, 0, 0, 7, 0, 0, 0, 1) @@ -597,78 +557,56 @@ def ogr_wkbwkt_test_geometrycollection_wkb_recursion(): wkb = wkb_repeat * 31 + wkb_end geom = ogr.CreateGeometryFromWkb(wkb) - if geom is None: - gdaltest.post_reason('expected a geometry') - return 'fail' + assert geom is not None, 'expected a geometry' wkb = struct.pack('B' * 0) + wkb_repeat * 32 + wkb_end gdal.PushErrorHandler('CPLQuietErrorHandler') geom = ogr.CreateGeometryFromWkb(wkb) gdal.PopErrorHandler() - if geom is not None: - gdaltest.post_reason('expected None') - return 'fail' - - return 'success' + assert geom is None, 'expected None' ############################################################################### # Test ISO WKT compliant export of MULTIPOINT -def ogr_wkbwkt_export_wkt_iso_multipoint(): +def test_ogr_wkbwkt_export_wkt_iso_multipoint(): wkt = 'MULTIPOINT ((0 0),(1 1))' g = ogr.CreateGeometryFromWkt(wkt) out_wkt = g.ExportToIsoWkt() - if out_wkt != wkt: - gdaltest.post_reason('fail') - print(out_wkt) - return 'fail' - - return 'success' + assert out_wkt == wkt ############################################################################### # Test exporting WKT with non finite values (#6319) -def ogr_wkt_inf_nan(): +def test_ogr_wkt_inf_nan(): g = ogr.Geometry(ogr.wkbPoint) g.AddPoint(float('inf'), float('-inf'), float('nan')) out_wkt = g.ExportToWkt() - if out_wkt != 'POINT (inf -inf nan)': - gdaltest.post_reason('fail') - print(out_wkt) - return 'fail' - - return 'success' + assert out_wkt == 'POINT (inf -inf nan)' ############################################################################### # Test corrupted WKT -def ogr_wkt_multicurve_compoundcurve_corrupted(): +def test_ogr_wkt_multicurve_compoundcurve_corrupted(): with gdaltest.error_handler(): g = ogr.CreateGeometryFromWkt('MULTICURVE(COMPOUNDCURVE') - if g is not None: - return 'fail' - - return 'success' + assert g is None ############################################################################### # Test corrupted WKT -def ogr_wkt_multipolygon_corrupted(): +def test_ogr_wkt_multipolygon_corrupted(): with gdaltest.error_handler(): g = ogr.CreateGeometryFromWkt('MULTIPOLYGON(POLYGON((N') - if g is not None: - return 'fail' - - return 'success' + assert g is None ############################################################################### # When imported build a list of units based on the files available. @@ -677,30 +615,4 @@ def ogr_wkt_multipolygon_corrupted(): # sys.stdin.readline() -gdaltest_list = [] - -files = os.listdir('data/wkb_wkt') -for filename in files: - if filename[-4:] == '.wkb': - ut = wkb_wkt_unit(filename[:-4]) - gdaltest_list.append((ut.wkbwkt_geom, ut.unit)) - -gdaltest_list.append(ogr_wkbwkt_geom_bigexponents) -gdaltest_list.append(ogr_wkbwkt_test_broken_geom) -gdaltest_list.append(ogr_wkbwkt_test_import_wkt_sf12) -gdaltest_list.append(ogr_wkbwkt_test_import_bad_multipoint_wkb) -gdaltest_list.append(ogr_wkbwkt_test_geometrycollection_wktwkb) -gdaltest_list.append(ogr_wkbwkt_test_geometrycollection_wkt_recursion) -gdaltest_list.append(ogr_wkbwkt_test_geometrycollection_wkb_recursion) -gdaltest_list.append(ogr_wkbwkt_export_wkt_iso_multipoint) -gdaltest_list.append(ogr_wkt_inf_nan) -gdaltest_list.append(ogr_wkt_multicurve_compoundcurve_corrupted) -gdaltest_list.append(ogr_wkt_multipolygon_corrupted) - -if __name__ == '__main__': - - gdaltest.setup_run('ogr_wkbwkt_geom') - - gdaltest.run_tests(gdaltest_list) - sys.exit(gdaltest.summarize()) diff --git a/autotest/ogr/ogr_wktempty.py b/autotest/ogr/ogr_wktempty.py index a683e93c485d..678f5362a3d5 100755 --- a/autotest/ogr/ogr_wktempty.py +++ b/autotest/ogr/ogr_wktempty.py @@ -26,50 +26,12 @@ # Boston, MA 02111-1307, USA. ############################################################################### -import sys -sys.path.append('../pymod') +import pytest -import gdaltest from osgeo import ogr - -class TestWktEmpty(object): - def __init__(self, inString, expectedOutString): - self.inString = inString - self.expectedOutString = expectedOutString - - def isEmpty(self, geom): - try: - ogr.Geometry.IsEmpty - except AttributeError: - return 'skip' - - if not geom.IsEmpty(): - geom.Destroy() - gdaltest.post_reason("IsEmpty returning false for an empty geometry") - return 'fail' - - return 'success' - - def CheckIsEmpty(self): - geom = ogr.CreateGeometryFromWkt(self.inString) - wkt = geom.ExportToWkt() - - if self.expectedOutString != 'POINT EMPTY': - if ogr.CreateGeometryFromWkb(geom.ExportToWkb()).ExportToWkt() != wkt: - return 'fail' - - if wkt == self.expectedOutString: - if self.isEmpty(geom) == 'fail': - return 'fail' - return 'success' - else: - gdaltest.post_reason('WKT is wrong: ' + wkt + '. Expected value is: ' + self.expectedOutString) - return 'fail' - - -empty_wkt_list = [ +wkt_list = [ ('GEOMETRYCOLLECTION(EMPTY)', 'GEOMETRYCOLLECTION EMPTY'), ('MULTIPOLYGON( EMPTY )', 'MULTIPOLYGON EMPTY'), ('MULTILINESTRING(EMPTY)', 'MULTILINESTRING EMPTY'), @@ -88,49 +50,69 @@ def CheckIsEmpty(self): ] -def ogr_wktempty_test_partial_empty_geoms(): +@pytest.mark.parametrize( + "test_input,expected", + wkt_list, + ids=[r[0] for r in wkt_list] +) +def test_empty_wkt(test_input, expected): + geom = ogr.CreateGeometryFromWkt(test_input) + wkt = geom.ExportToWkt() + + if expected != 'POINT EMPTY': + assert ogr.CreateGeometryFromWkb(geom.ExportToWkb()).ExportToWkt() == wkt + + assert wkt == expected + + try: + ogr.Geometry.IsEmpty + except AttributeError: + pytest.skip() + + try: + assert geom.IsEmpty(), "IsEmpty returning false for an empty geometry" + finally: + geom.Destroy() + + +def test_ogr_wktempty_test_partial_empty_geoms(): # Multipoint with a valid point and an empty point wkt = 'MULTIPOINT (1 1)' geom = ogr.CreateGeometryFromWkt(wkt) geom.AddGeometry(ogr.Geometry(type=ogr.wkbPoint)) - if geom.ExportToWkt() != wkt: - gdaltest.post_reason('WKT is wrong: ' + geom.ExportToWkt() + '. Expected value is: ' + wkt) - return 'fail' + assert geom.ExportToWkt() == wkt, \ + ('WKT is wrong: ' + geom.ExportToWkt() + '. Expected value is: ' + wkt) # Multipoint with an empty point and a valid point geom = ogr.CreateGeometryFromWkt('MULTIPOINT EMPTY') geom.AddGeometry(ogr.Geometry(type=ogr.wkbPoint)) geom.AddGeometry(ogr.CreateGeometryFromWkt('POINT (1 1)')) wkt = 'MULTIPOINT (1 1)' - if geom.ExportToWkt() != wkt: - gdaltest.post_reason('WKT is wrong: ' + geom.ExportToWkt() + '. Expected value is: ' + wkt) - return 'fail' + assert geom.ExportToWkt() == wkt, \ + ('WKT is wrong: ' + geom.ExportToWkt() + '. Expected value is: ' + wkt) # Multilinestring with a valid string and an empty linestring wkt = 'MULTILINESTRING ((0 1,2 3,4 5,0 1))' geom = ogr.CreateGeometryFromWkt(wkt) geom.AddGeometry(ogr.Geometry(type=ogr.wkbLineString)) - if geom.ExportToWkt() != wkt: - gdaltest.post_reason('WKT is wrong: ' + geom.ExportToWkt() + '. Expected value is: ' + wkt) - return 'fail' + assert geom.ExportToWkt() == wkt, \ + ('WKT is wrong: ' + geom.ExportToWkt() + '. Expected value is: ' + wkt) # Multilinestring with an empty linestring and a valid linestring geom = ogr.CreateGeometryFromWkt('MULTILINESTRING EMPTY') geom.AddGeometry(ogr.Geometry(type=ogr.wkbLineString)) geom.AddGeometry(ogr.CreateGeometryFromWkt('LINESTRING (0 1,2 3,4 5,0 1)')) wkt = 'MULTILINESTRING ((0 1,2 3,4 5,0 1))' - if geom.ExportToWkt() != wkt: - gdaltest.post_reason('WKT is wrong: ' + geom.ExportToWkt() + '. Expected value is: ' + wkt) - return 'fail' + assert geom.ExportToWkt() == wkt, \ + ('WKT is wrong: ' + geom.ExportToWkt() + '. Expected value is: ' + wkt) # Polygon with a valid external ring and an empty internal ring wkt = 'POLYGON ((100 0,100 10,110 10,100 0))' geom = ogr.CreateGeometryFromWkt(wkt) geom.AddGeometry(ogr.Geometry(type=ogr.wkbLinearRing)) - if geom.ExportToWkt() != wkt: - gdaltest.post_reason('WKT is wrong: ' + geom.ExportToWkt() + '. Expected value is: ' + wkt) - return 'fail' + assert geom.ExportToWkt() == wkt, \ + ('WKT is wrong: ' + geom.ExportToWkt() + '. Expected value is: ' + wkt) # Polygon with an empty external ring and a valid internal ring wkt = 'POLYGON EMPTY' @@ -143,41 +125,23 @@ def ogr_wktempty_test_partial_empty_geoms(): ring.AddPoint_2D(0, 10) ring.AddPoint_2D(0, 0) geom.AddGeometry(ring) - if geom.ExportToWkt() != wkt: - gdaltest.post_reason('WKT is wrong: ' + geom.ExportToWkt() + '. Expected value is: ' + wkt) - return 'fail' + assert geom.ExportToWkt() == wkt, \ + ('WKT is wrong: ' + geom.ExportToWkt() + '. Expected value is: ' + wkt) # Multipolygon with a valid polygon and an empty polygon wkt = 'MULTIPOLYGON (((0 0,0 10,10 10,0 0)))' geom = ogr.CreateGeometryFromWkt(wkt) geom.AddGeometry(ogr.Geometry(type=ogr.wkbPolygon)) - if geom.ExportToWkt() != wkt: - gdaltest.post_reason('WKT is wrong: ' + geom.ExportToWkt() + '. Expected value is: ' + wkt) - return 'fail' + assert geom.ExportToWkt() == wkt, \ + ('WKT is wrong: ' + geom.ExportToWkt() + '. Expected value is: ' + wkt) # Multipolygon with an empty polygon and a valid polygon geom = ogr.CreateGeometryFromWkt('MULTIPOLYGON EMPTY') geom.AddGeometry(ogr.Geometry(type=ogr.wkbPolygon)) geom.AddGeometry(ogr.CreateGeometryFromWkt('POLYGON ((100 0,100 10,110 10,100 0))')) wkt = 'MULTIPOLYGON (((100 0,100 10,110 10,100 0)))' - if geom.ExportToWkt() != wkt: - gdaltest.post_reason('WKT is wrong: ' + geom.ExportToWkt() + '. Expected value is: ' + wkt) - return 'fail' - - return 'success' - - -gdaltest_list = [] - -for item in empty_wkt_list: - ut = TestWktEmpty(item[0], item[1]) - gdaltest_list.append((ut.CheckIsEmpty, item[0])) -gdaltest_list.append(ogr_wktempty_test_partial_empty_geoms) - -if __name__ == '__main__': + assert geom.ExportToWkt() == wkt, \ + ('WKT is wrong: ' + geom.ExportToWkt() + '. Expected value is: ' + wkt) - gdaltest.setup_run('ogr_wktempty') - gdaltest.run_tests(gdaltest_list) - sys.exit(gdaltest.summarize()) diff --git a/autotest/ogr/ogr_xls.py b/autotest/ogr/ogr_xls.py index 0a7cac642657..6ffac6f34b84 100755 --- a/autotest/ogr/ogr_xls.py +++ b/autotest/ogr/ogr_xls.py @@ -29,75 +29,50 @@ # DEALINGS IN THE SOFTWARE. ############################################################################### -import sys -sys.path.append('../pymod') import gdaltest from osgeo import gdal from osgeo import ogr +import pytest ############################################################################### # Basic tests -def ogr_xls_1(): +def test_ogr_xls_1(): drv = ogr.GetDriverByName('XLS') if drv is None: - return 'skip' + pytest.skip() - if drv.TestCapability("foo") != 0: - gdaltest.post_reason('fail') - return 'fail' + assert drv.TestCapability("foo") == 0 ds = ogr.Open('data/test972000xp.xls') - if ds is None: - gdaltest.post_reason('cannot open dataset') - return 'fail' + assert ds is not None, 'cannot open dataset' - if ds.TestCapability("foo") != 0: - gdaltest.post_reason('fail') - return 'fail' + assert ds.TestCapability("foo") == 0 - if ds.GetLayerCount() != 1: - gdaltest.post_reason('bad layer count') - return 'fail' + assert ds.GetLayerCount() == 1, 'bad layer count' lyr = ds.GetLayer(0) - if lyr.GetName() != 'Feuille1': - gdaltest.post_reason('bad layer name') - return 'fail' - - if lyr.GetGeomType() != ogr.wkbNone: - gdaltest.post_reason('bad layer geometry type') - return 'fail' - - if lyr.GetSpatialRef() is not None: - gdaltest.post_reason('bad spatial ref') - return 'fail' - - if lyr.GetFeatureCount() != 3: - gdaltest.post_reason('fail') - print(lyr.GetFeatureCount()) - return 'fail' - - if lyr.TestCapability("foo") != 0: - gdaltest.post_reason('fail') - return 'fail' - - if lyr.GetLayerDefn().GetFieldCount() != 5: - gdaltest.post_reason('fail') - print(lyr.GetLayerDefn().GetFieldCount()) - return 'fail' - - if lyr.GetLayerDefn().GetFieldDefn(0).GetType() != ogr.OFTInteger or \ - lyr.GetLayerDefn().GetFieldDefn(1).GetType() != ogr.OFTReal or \ - lyr.GetLayerDefn().GetFieldDefn(2).GetType() != ogr.OFTString or \ - lyr.GetLayerDefn().GetFieldDefn(3).GetType() != ogr.OFTDate or \ - lyr.GetLayerDefn().GetFieldDefn(4).GetType() != ogr.OFTDateTime: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.GetName() == 'Feuille1', 'bad layer name' + + assert lyr.GetGeomType() == ogr.wkbNone, 'bad layer geometry type' + + assert lyr.GetSpatialRef() is None, 'bad spatial ref' + + assert lyr.GetFeatureCount() == 3 + + assert lyr.TestCapability("foo") == 0 + + assert lyr.GetLayerDefn().GetFieldCount() == 5 + + assert (lyr.GetLayerDefn().GetFieldDefn(0).GetType() == ogr.OFTInteger and \ + lyr.GetLayerDefn().GetFieldDefn(1).GetType() == ogr.OFTReal and \ + lyr.GetLayerDefn().GetFieldDefn(2).GetType() == ogr.OFTString and \ + lyr.GetLayerDefn().GetFieldDefn(3).GetType() == ogr.OFTDate and \ + lyr.GetLayerDefn().GetFieldDefn(4).GetType() == ogr.OFTDateTime) feat = lyr.GetNextFeature() if feat.GetFieldAsInteger(0) != 1 or \ @@ -105,100 +80,69 @@ def ogr_xls_1(): feat.IsFieldSet(2) or \ feat.GetFieldAsString(3) != '1980/01/01' or \ feat.GetFieldAsString(4) != '1980/01/01 00:00:00': - gdaltest.post_reason('fail') feat.DumpReadable() - return 'fail' + pytest.fail() feat = lyr.GetNextFeature() feat = lyr.GetNextFeature() feat = lyr.GetNextFeature() - if feat is not None: - gdaltest.post_reason('fail') - return 'fail' - - return 'success' + assert feat is None ############################################################################### # Test OGR_XLS_HEADERS = DISABLE -def ogr_xls_2(): +def test_ogr_xls_2(): drv = ogr.GetDriverByName('XLS') if drv is None: - return 'skip' + pytest.skip() gdal.SetConfigOption('OGR_XLS_HEADERS', 'DISABLE') ds = ogr.Open('data/test972000xp.xls') lyr = ds.GetLayer(0) - if lyr.GetFeatureCount() != 4: - gdaltest.post_reason('fail') - print(lyr.GetFeatureCount()) - return 'fail' + assert lyr.GetFeatureCount() == 4 gdal.SetConfigOption('OGR_XLS_HEADERS', None) - return 'success' - ############################################################################### # Test OGR_XLS_FIELD_TYPES = STRING -def ogr_xls_3(): +def test_ogr_xls_3(): drv = ogr.GetDriverByName('XLS') if drv is None: - return 'skip' + pytest.skip() gdal.SetConfigOption('OGR_XLS_FIELD_TYPES', 'STRING') ds = ogr.Open('data/test972000xp.xls') lyr = ds.GetLayer(0) - if lyr.GetLayerDefn().GetFieldDefn(0).GetType() != ogr.OFTString: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.GetLayerDefn().GetFieldDefn(0).GetType() == ogr.OFTString gdal.SetConfigOption('OGR_XLS_FIELD_TYPES', None) - return 'success' - ############################################################################### # Run test_ogrsf -def ogr_xls_4(): +def test_ogr_xls_4(): drv = ogr.GetDriverByName('XLS') if drv is None: - return 'skip' + pytest.skip() import test_cli_utilities if test_cli_utilities.get_test_ogrsf_path() is None: - return 'skip' + pytest.skip() ret = gdaltest.runexternal(test_cli_utilities.get_test_ogrsf_path() + ' -ro data/test972000xp.xls') - if ret.find('INFO') == -1 or ret.find('ERROR') != -1: - print(ret) - return 'fail' - - return 'success' - - -gdaltest_list = [ - ogr_xls_1, - ogr_xls_2, - ogr_xls_3, - ogr_xls_4 -] - -if __name__ == '__main__': + assert ret.find('INFO') != -1 and ret.find('ERROR') == -1 - gdaltest.setup_run('ogr_xls') - gdaltest.run_tests(gdaltest_list) - sys.exit(gdaltest.summarize()) diff --git a/autotest/ogr/ogr_xlsx.py b/autotest/ogr/ogr_xlsx.py index 72e403e6e892..5d2167b51e5c 100755 --- a/autotest/ogr/ogr_xlsx.py +++ b/autotest/ogr/ogr_xlsx.py @@ -29,14 +29,13 @@ ############################################################################### import os -import sys import shutil -sys.path.append('../pymod') import gdaltest from osgeo import gdal from osgeo import ogr +import pytest ############################################################################### # Check @@ -44,45 +43,25 @@ def ogr_xlsx_check(ds): - if ds.TestCapability("foo") != 0: - gdaltest.post_reason('fail') - return 'fail' + assert ds.TestCapability("foo") == 0 - if ds.GetLayerCount() != 8: - gdaltest.post_reason('bad layer count') - return 'fail' + assert ds.GetLayerCount() == 8, 'bad layer count' lyr = ds.GetLayer(0) - if lyr.GetName() != 'Feuille1': - gdaltest.post_reason('bad layer name') - return 'fail' + assert lyr.GetName() == 'Feuille1', 'bad layer name' - if lyr.GetGeomType() != ogr.wkbNone: - gdaltest.post_reason('bad layer geometry type') - return 'fail' + assert lyr.GetGeomType() == ogr.wkbNone, 'bad layer geometry type' - if lyr.GetSpatialRef() is not None: - gdaltest.post_reason('bad spatial ref') - return 'fail' + assert lyr.GetSpatialRef() is None, 'bad spatial ref' - if lyr.GetFeatureCount() != 26: - gdaltest.post_reason('fail') - print(lyr.GetFeatureCount()) - return 'fail' + assert lyr.GetFeatureCount() == 26 - if lyr.TestCapability("foo") != 0: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.TestCapability("foo") == 0 lyr = ds.GetLayer(6) - if lyr.GetName() != 'Feuille7': - gdaltest.post_reason('bad layer name') - return 'fail' + assert lyr.GetName() == 'Feuille7', 'bad layer name' - if lyr.GetLayerDefn().GetFieldCount() != 12: - gdaltest.post_reason('fail') - print(lyr.GetLayerDefn().GetFieldCount()) - return 'fail' + assert lyr.GetLayerDefn().GetFieldCount() == 12 type_array = [ogr.OFTString, ogr.OFTInteger, @@ -98,10 +77,7 @@ def ogr_xlsx_check(ds): ogr.OFTDateTime] for i, typ in enumerate(type_array): - if lyr.GetLayerDefn().GetFieldDefn(i).GetType() != typ: - gdaltest.post_reason('fail') - print(i) - return 'fail' + assert lyr.GetLayerDefn().GetFieldDefn(i).GetType() == typ feat = lyr.GetNextFeature() if feat.GetFieldAsString(0) != 'val' or \ @@ -110,36 +86,29 @@ def ogr_xlsx_check(ds): feat.GetFieldAsDouble(3) != 0.52 or \ feat.GetFieldAsString(4) != '2012/01/22' or \ feat.GetFieldAsString(5) != '2012/01/22 18:49:00': - gdaltest.post_reason('fail') feat.DumpReadable() - return 'fail' + pytest.fail() feat = lyr.GetNextFeature() if feat.IsFieldSet(2): - gdaltest.post_reason('fail') feat.DumpReadable() - return 'fail' - - return 'success' + pytest.fail() + ############################################################################### # Basic tests -def ogr_xlsx_1(): +def test_ogr_xlsx_1(): drv = ogr.GetDriverByName('XLSX') if drv is None: - return 'skip' + pytest.skip() - if drv.TestCapability("foo") != 0: - gdaltest.post_reason('fail') - return 'fail' + assert drv.TestCapability("foo") == 0 ds = ogr.Open('data/test.xlsx') - if ds is None: - gdaltest.post_reason('cannot open dataset') - return 'fail' + assert ds is not None, 'cannot open dataset' return ogr_xlsx_check(ds) @@ -147,84 +116,71 @@ def ogr_xlsx_1(): # Test OGR_XLSX_HEADERS = DISABLE -def ogr_xlsx_2(): +def test_ogr_xlsx_2(): drv = ogr.GetDriverByName('XLSX') if drv is None: - return 'skip' + pytest.skip() gdal.SetConfigOption('OGR_XLSX_HEADERS', 'DISABLE') ds = ogr.Open('data/test.xlsx') lyr = ds.GetLayerByName('Feuille7') - if lyr.GetFeatureCount() != 3: - gdaltest.post_reason('fail') - print(lyr.GetFeatureCount()) - return 'fail' + assert lyr.GetFeatureCount() == 3 gdal.SetConfigOption('OGR_XLSX_HEADERS', None) - return 'success' - ############################################################################### # Test OGR_XLSX_FIELD_TYPES = STRING -def ogr_xlsx_3(): +def test_ogr_xlsx_3(): drv = ogr.GetDriverByName('XLSX') if drv is None: - return 'skip' + pytest.skip() gdal.SetConfigOption('OGR_XLSX_FIELD_TYPES', 'STRING') ds = ogr.Open('data/test.xlsx') lyr = ds.GetLayerByName('Feuille7') - if lyr.GetLayerDefn().GetFieldDefn(1).GetType() != ogr.OFTString: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.GetLayerDefn().GetFieldDefn(1).GetType() == ogr.OFTString gdal.SetConfigOption('OGR_XLSX_FIELD_TYPES', None) - return 'success' - ############################################################################### # Run test_ogrsf -def ogr_xlsx_4(): +def test_ogr_xlsx_4(): drv = ogr.GetDriverByName('XLSX') if drv is None: - return 'skip' + pytest.skip() import test_cli_utilities if test_cli_utilities.get_test_ogrsf_path() is None: - return 'skip' + pytest.skip() ret = gdaltest.runexternal(test_cli_utilities.get_test_ogrsf_path() + ' -ro data/test.xlsx') - if ret.find('INFO') == -1 or ret.find('ERROR') != -1: - print(ret) - return 'fail' - - return 'success' + assert ret.find('INFO') != -1 and ret.find('ERROR') == -1 ############################################################################### # Test write support -def ogr_xlsx_5(): +def test_ogr_xlsx_5(): drv = ogr.GetDriverByName('XLSX') if drv is None: - return 'skip' + pytest.skip() import test_cli_utilities if test_cli_utilities.get_ogr2ogr_path() is None: - return 'skip' + pytest.skip() gdaltest.runexternal(test_cli_utilities.get_ogr2ogr_path() + ' -f XLSX tmp/test.xlsx data/test.xlsx') @@ -240,11 +196,11 @@ def ogr_xlsx_5(): # Test reading a file using inlineStr representation. -def ogr_xlsx_6(): +def test_ogr_xlsx_6(): drv = ogr.GetDriverByName('XLSX') if drv is None: - return 'skip' + pytest.skip() # In this dataset the column titles are not recognised by default. gdal.SetConfigOption('OGR_XLSX_HEADERS', 'FORCE') @@ -252,34 +208,26 @@ def ogr_xlsx_6(): lyr = ds.GetLayerByName('inlineStr') - if lyr.GetFeatureCount() != 1: - gdaltest.post_reason('fail') - print(lyr.GetFeatureCount()) - return 'fail' + assert lyr.GetFeatureCount() == 1 lyr.ResetReading() feat = lyr.GetNextFeature() - if feat.Bl_District_t != 'text6': - gdaltest.post_reason('Did not get expected value(1)') - return 'fail' + assert feat.Bl_District_t == 'text6', 'Did not get expected value(1)' - if abs(float(feat.GetField('Lat')) - 23.6247122) > 0.00001: - gdaltest.post_reason('Did not get expected value(2)') - return 'fail' + assert abs(float(feat.GetField('Lat')) - 23.6247122) <= 0.00001, \ + 'Did not get expected value(2)' gdal.SetConfigOption('OGR_XLSX_HEADERS', None) - return 'success' - ############################################################################### # Test update support -def ogr_xlsx_7(): +def test_ogr_xlsx_7(): drv = ogr.GetDriverByName('XLSX') if drv is None: - return 'skip' + pytest.skip() gdal.Unlink('tmp/ogr_xlsx_7.xlsx') shutil.copy('data/test.xlsx', 'tmp/ogr_xlsx_7.xlsx') @@ -288,9 +236,8 @@ def ogr_xlsx_7(): lyr = ds.GetLayerByName('Feuille7') feat = lyr.GetNextFeature() if feat.GetFID() != 2: - gdaltest.post_reason('did not get expected FID') feat.DumpReadable() - return 'fail' + pytest.fail('did not get expected FID') feat.SetField(0, 'modified_value') lyr.SetFeature(feat) feat = None @@ -300,29 +247,25 @@ def ogr_xlsx_7(): lyr = ds.GetLayerByName('Feuille7') feat = lyr.GetNextFeature() if feat.GetFID() != 2: - gdaltest.post_reason('did not get expected FID') feat.DumpReadable() - return 'fail' + pytest.fail('did not get expected FID') if feat.GetField(0) != 'modified_value': - gdaltest.post_reason('did not get expected value') feat.DumpReadable() - return 'fail' + pytest.fail('did not get expected value') feat = None ds = None os.unlink('tmp/ogr_xlsx_7.xlsx') - return 'success' - ############################################################################### # Test number of columns > 26 (#5774) -def ogr_xlsx_8(): +def test_ogr_xlsx_8(): drv = ogr.GetDriverByName('XLSX') if drv is None: - return 'skip' + pytest.skip() ds = drv.CreateDataSource('/vsimem/ogr_xlsx_8.xlsx') lyr = ds.CreateLayer('foo') @@ -339,23 +282,19 @@ def ogr_xlsx_8(): content = gdal.VSIFReadL(1, 10000, f) gdal.VSIFCloseL(f) - if str(content).find('<c r="AA1" t="s">') < 0: - print(content) - return 'fail' + assert str(content).find('<c r="AA1" t="s">') >= 0 gdal.Unlink('/vsimem/ogr_xlsx_8.xlsx') - return 'success' - ############################################################################### # Test Integer64 -def ogr_xlsx_9(): +def test_ogr_xlsx_9(): drv = ogr.GetDriverByName('XLSX') if drv is None: - return 'skip' + pytest.skip() ds = drv.CreateDataSource('/vsimem/ogr_xlsx_9.xlsx') lyr = ds.CreateLayer('foo') @@ -374,29 +313,23 @@ def ogr_xlsx_9(): ds = ogr.Open('/vsimem/ogr_xlsx_9.xlsx') lyr = ds.GetLayer(0) - if lyr.GetLayerDefn().GetFieldDefn(0).GetType() != ogr.OFTInteger64: - gdaltest.post_reason('failure') - return 'fail' + assert lyr.GetLayerDefn().GetFieldDefn(0).GetType() == ogr.OFTInteger64 f = lyr.GetNextFeature() f = lyr.GetNextFeature() - if f.GetField(0) != 12345678901234: - gdaltest.post_reason('failure') - return 'fail' + assert f.GetField(0) == 12345678901234 ds = None gdal.Unlink('/vsimem/ogr_xlsx_9.xlsx') - return 'success' - ############################################################################### # Test DateTime with milliseconds -def ogr_xlsx_10(): +def test_ogr_xlsx_10(): drv = ogr.GetDriverByName('XLSX') if drv is None: - return 'skip' + pytest.skip() ds = drv.CreateDataSource('/vsimem/ogr_xlsx_10.xlsx') lyr = ds.CreateLayer('foo') @@ -414,37 +347,30 @@ def ogr_xlsx_10(): ds = ogr.Open('/vsimem/ogr_xlsx_10.xlsx') lyr = ds.GetLayer(0) for i in range(3): - if lyr.GetLayerDefn().GetFieldDefn(i).GetType() != ogr.OFTDateTime: - gdaltest.post_reason('failure') - return 'fail' + assert lyr.GetLayerDefn().GetFieldDefn(i).GetType() == ogr.OFTDateTime f = lyr.GetNextFeature() if f.GetField(0) != '2015/12/23 12:34:56.789': - gdaltest.post_reason('failure') f.DumpReadable() - return 'fail' + pytest.fail() if f.GetField(1) != '2015/12/23 12:34:56': - gdaltest.post_reason('failure') f.DumpReadable() - return 'fail' + pytest.fail() if f.GetField(2) != '2015/12/23 12:34:56': - gdaltest.post_reason('failure') f.DumpReadable() - return 'fail' + pytest.fail() ds = None gdal.Unlink('/vsimem/ogr_xlsx_10.xlsx') - return 'success' - ############################################################################### # Test reading sheet with more than 26 columns with holes (#6363)" -def ogr_xlsx_11(): +def test_ogr_xlsx_11(): drv = ogr.GetDriverByName('XLSX') if drv is None: - return 'skip' + pytest.skip() ds = ogr.Open('data/not_all_columns_present.xlsx') lyr = ds.GetLayer(0) @@ -452,56 +378,47 @@ def ogr_xlsx_11(): for i in (0, 27, 28, 29): if f['Field%d' % (i + 1)] != 'val%d' % (i + 1): f.DumpReadable() - return 'fail' + pytest.fail() ds = None - return 'success' - ############################################################################### # Test reading a sheet whose file is stored as "absolute" in # workbook.xml.rels (#6733) -def ogr_xlsx_12(): +def test_ogr_xlsx_12(): drv = ogr.GetDriverByName('XLSX') if drv is None: - return 'skip' + pytest.skip() ds = ogr.Open('data/absolute_sheet_filename.xlsx') lyr = ds.GetLayer(0) f = lyr.GetNextFeature() - if f is None: - return 'fail' + assert f is not None ds = None - return 'success' - ############################################################################### # Test that data types are correctly picked up even if first row is missing data -def ogr_xlsx_13(): +def test_ogr_xlsx_13(): drv = ogr.GetDriverByName('XLSX') if drv is None: - return 'skip' + pytest.skip() gdal.SetConfigOption('OGR_XLSX_FIELD_TYPES', None) ds = ogr.Open('data/test_missing_row1_data.xlsx') lyr = ds.GetLayer(0) - if lyr.GetName() != 'Sheet1': - gdaltest.post_reason('bad layer name') - return 'fail' + assert lyr.GetName() == 'Sheet1', 'bad layer name' - if lyr.GetLayerDefn().GetFieldDefn(0).GetName() != 'Asset Reference': - gdaltest.post_reason('invalid field name') - return 'fail' + assert lyr.GetLayerDefn().GetFieldDefn(0).GetName() == 'Asset Reference', \ + 'invalid field name' - if lyr.GetLayerDefn().GetFieldCount() != 18: - gdaltest.post_reason('invalid field count ({})'.format(lyr.GetLayerDefn().GetFieldCount())) - return 'fail' + assert lyr.GetLayerDefn().GetFieldCount() == 18, \ + 'invalid field count ({})'.format(lyr.GetLayerDefn().GetFieldCount()) type_array = [ogr.OFTInteger, ogr.OFTString, @@ -523,37 +440,31 @@ def ogr_xlsx_13(): ogr.OFTString] for i, typ in enumerate(type_array): - if lyr.GetLayerDefn().GetFieldDefn(i).GetType() != typ: - gdaltest.post_reason('invalid type for field {}'.format(i + 1)) - return 'fail' - - return 'success' + assert lyr.GetLayerDefn().GetFieldDefn(i).GetType() == typ, \ + 'invalid type for field {}'.format(i + 1) + ############################################################################### # Test that field names are picked up even if last field has no data -def ogr_xlsx_14(): +def test_ogr_xlsx_14(): drv = ogr.GetDriverByName('XLSX') if drv is None: - return 'skip' + pytest.skip() gdal.SetConfigOption('OGR_XLSX_FIELD_TYPES', None) ds = ogr.Open('data/test_empty_last_field.xlsx') lyr = ds.GetLayer(0) - if lyr.GetName() != 'Sheet1': - gdaltest.post_reason('bad layer name') - return 'fail' + assert lyr.GetName() == 'Sheet1', 'bad layer name' - if lyr.GetLayerDefn().GetFieldDefn(0).GetName() != 'Asset Reference': - gdaltest.post_reason('invalid field name') - return 'fail' + assert lyr.GetLayerDefn().GetFieldDefn(0).GetName() == 'Asset Reference', \ + 'invalid field name' - if lyr.GetLayerDefn().GetFieldCount() != 18: - gdaltest.post_reason('invalid field count ({})'.format(lyr.GetLayerDefn().GetFieldCount())) - return 'fail' + assert lyr.GetLayerDefn().GetFieldCount() == 18, \ + 'invalid field count ({})'.format(lyr.GetLayerDefn().GetFieldCount()) type_array = [ogr.OFTInteger, ogr.OFTString, @@ -575,47 +486,40 @@ def ogr_xlsx_14(): ogr.OFTString] for i, typ in enumerate(type_array): - if lyr.GetLayerDefn().GetFieldDefn(i).GetType() != typ: - gdaltest.post_reason('invalid type for field {}'.format(i + 1)) - return 'fail' - - return 'success' + assert lyr.GetLayerDefn().GetFieldDefn(i).GetType() == typ, \ + 'invalid type for field {}'.format(i + 1) + ############################################################################### # Test appending a layer to an existing document -def ogr_xlsx_15(): +def test_ogr_xlsx_15(): drv = ogr.GetDriverByName('XLSX') if drv is None: - return 'skip' + pytest.skip() out_filename = '/vsimem/ogr_xlsx_15.xlsx' gdal.VectorTranslate(out_filename, 'data/poly.shp', options='-f XLSX -nln first') gdal.VectorTranslate(out_filename, 'data/poly.shp', options='-update -nln second') ds = ogr.Open(out_filename) - if ds.GetLayerByName('first').GetFeatureCount() == 0: - gdaltest.post_reason('fail') - return 'fail' - if ds.GetLayerByName('second').GetFeatureCount() == 0: - gdaltest.post_reason('fail') - return 'fail' + assert ds.GetLayerByName('first').GetFeatureCount() != 0 + assert ds.GetLayerByName('second').GetFeatureCount() != 0 ds = None gdal.Unlink(out_filename) - return 'success' ############################################################################### # Test Boolean -def ogr_xlsx_boolean(): +def test_ogr_xlsx_boolean(): drv = ogr.GetDriverByName('XLSX') if drv is None: - return 'skip' + pytest.skip() out_filename = '/vsimem/ogr_xlsx_boolean.xlsx' ds = drv.CreateDataSource(out_filename) @@ -631,46 +535,13 @@ def ogr_xlsx_boolean(): ds = ogr.Open(out_filename) lyr = ds.GetLayer(0) - if lyr.GetLayerDefn().GetFieldDefn(0).GetType() != ogr.OFTInteger: - gdaltest.post_reason('failure') - return 'fail' - if lyr.GetLayerDefn().GetFieldDefn(0).GetSubType() != ogr.OFSTBoolean: - gdaltest.post_reason('failure') - return 'fail' + assert lyr.GetLayerDefn().GetFieldDefn(0).GetType() == ogr.OFTInteger + assert lyr.GetLayerDefn().GetFieldDefn(0).GetSubType() == ogr.OFSTBoolean f = lyr.GetNextFeature() - if f.GetField(0) != 1: - gdaltest.post_reason('failure') - return 'fail' + assert f.GetField(0) == 1 ds = None gdal.Unlink(out_filename) - return 'success' - - -gdaltest_list = [ - ogr_xlsx_1, - ogr_xlsx_2, - ogr_xlsx_3, - ogr_xlsx_4, - ogr_xlsx_5, - ogr_xlsx_6, - ogr_xlsx_7, - ogr_xlsx_8, - ogr_xlsx_9, - ogr_xlsx_10, - ogr_xlsx_11, - ogr_xlsx_12, - ogr_xlsx_13, - ogr_xlsx_14, - ogr_xlsx_15, - ogr_xlsx_boolean, -] - -if __name__ == '__main__': - - gdaltest.setup_run('ogr_xlsx') - gdaltest.run_tests(gdaltest_list) - sys.exit(gdaltest.summarize()) diff --git a/autotest/ogr/ogr_xplane.py b/autotest/ogr/ogr_xplane.py index fbdc087ca474..3524084ab775 100755 --- a/autotest/ogr/ogr_xplane.py +++ b/autotest/ogr/ogr_xplane.py @@ -28,23 +28,19 @@ # DEALINGS IN THE SOFTWARE. ############################################################################### -import sys -sys.path.append('../pymod') -import gdaltest from osgeo import ogr ############################################################################### # Test apt.dat reading -def ogr_xplane_apt_dat(): +def test_ogr_xplane_apt_dat(): xplane_apt_ds = ogr.Open('data/apt.dat') - if xplane_apt_ds is None: - return 'fail' + assert xplane_apt_ds is not None layers = [('APT', 8, [('apt_icao', 'E46')]), ('RunwayPolygon', 19, [('apt_icao', 'E46')]), @@ -68,29 +64,22 @@ def ogr_xplane_apt_dat(): for layer in layers: lyr = xplane_apt_ds.GetLayerByName(layer[0]) - if lyr.GetFeatureCount() != layer[1]: - gdaltest.post_reason('wrong number of features for layer %s : %d. %d were expected ' % (layer[0], lyr.GetFeatureCount(), layer[1])) - return 'fail' + assert lyr.GetFeatureCount() == layer[1], \ + ('wrong number of features for layer %s : %d. %d were expected ' % (layer[0], lyr.GetFeatureCount(), layer[1])) feat_read = lyr.GetNextFeature() for item in layer[2]: - if feat_read.GetField(item[0]) != item[1]: - print(layer[0]) - print(item[0]) - print(feat_read.GetField(item[0])) - return 'fail' - - return 'success' + assert feat_read.GetField(item[0]) == item[1], layer[0] + ############################################################################### # Test apt.dat v810 reading -def ogr_xplane_apt_v810_dat(): +def test_ogr_xplane_apt_v810_dat(): xplane_apt_ds = ogr.Open('data/apt810/apt.dat') - if xplane_apt_ds is None: - return 'fail' + assert xplane_apt_ds is not None layers = [('APT', 6, [('apt_icao', 'UHP1')]), ('RunwayPolygon', 6, [('apt_icao', 'UHP1')]), @@ -114,29 +103,22 @@ def ogr_xplane_apt_v810_dat(): for layer in layers: lyr = xplane_apt_ds.GetLayerByName(layer[0]) - if lyr.GetFeatureCount() != layer[1]: - gdaltest.post_reason('wrong number of features for layer %s : %d. %d were expected ' % (layer[0], lyr.GetFeatureCount(), layer[1])) - return 'fail' + assert lyr.GetFeatureCount() == layer[1], \ + ('wrong number of features for layer %s : %d. %d were expected ' % (layer[0], lyr.GetFeatureCount(), layer[1])) feat_read = lyr.GetNextFeature() for item in layer[2]: - if feat_read.GetField(item[0]) != item[1]: - print(layer[0]) - print(item[0]) - print(feat_read.GetField(item[0])) - return 'fail' - - return 'success' + assert feat_read.GetField(item[0]) == item[1], layer[0] + ############################################################################### # Test nav.dat reading -def ogr_xplane_nav_dat(): +def test_ogr_xplane_nav_dat(): xplane_nav_ds = ogr.Open('data/nav.dat') - if xplane_nav_ds is None: - return 'fail' + assert xplane_nav_ds is not None layers = [('ILS', 6, [('navaid_id', 'IMQS')]), ('VOR', 3, [('navaid_id', 'AAL')]), @@ -149,31 +131,23 @@ def ogr_xplane_nav_dat(): for layer in layers: lyr = xplane_nav_ds.GetLayerByName(layer[0]) - if lyr.GetFeatureCount() != layer[1]: - gdaltest.post_reason('wrong number of features for layer %s : %d. %d were expected ' % (layer[0], lyr.GetFeatureCount(), layer[1])) - return 'fail' + assert lyr.GetFeatureCount() == layer[1], \ + ('wrong number of features for layer %s : %d. %d were expected ' % (layer[0], lyr.GetFeatureCount(), layer[1])) feat_read = lyr.GetNextFeature() for item in layer[2]: - if feat_read.GetField(item[0]) != item[1]: - print(layer[0]) - print(item[0]) - print(feat_read.GetField(item[0])) - return 'fail' + assert feat_read.GetField(item[0]) == item[1], layer[0] xplane_nav_ds = None - return 'success' - ############################################################################### # Test awy.dat reading -def ogr_xplane_awy_dat(): +def test_ogr_xplane_awy_dat(): xplane_awy_ds = ogr.Open('data/awy.dat') - if xplane_awy_ds is None: - return 'fail' + assert xplane_awy_ds is not None layers = [('AirwaySegment', 11, [('segment_name', 'R464')]), ('AirwayIntersection', 14, [('name', '00MKK')]) @@ -181,63 +155,37 @@ def ogr_xplane_awy_dat(): for layer in layers: lyr = xplane_awy_ds.GetLayerByName(layer[0]) - if lyr.GetFeatureCount() != layer[1]: - gdaltest.post_reason('wrong number of features for layer %s : %d. %d were expected ' % (layer[0], lyr.GetFeatureCount(), layer[1])) - return 'fail' + assert lyr.GetFeatureCount() == layer[1], \ + ('wrong number of features for layer %s : %d. %d were expected ' % (layer[0], lyr.GetFeatureCount(), layer[1])) feat_read = lyr.GetNextFeature() for item in layer[2]: - if feat_read.GetField(item[0]) != item[1]: - print(layer[0]) - print(item[0]) - print(feat_read.GetField(item[0])) - return 'fail' - - return 'success' + assert feat_read.GetField(item[0]) == item[1], layer[0] + ############################################################################### # Test fix.dat reading -def ogr_xplane_fix_dat(): +def test_ogr_xplane_fix_dat(): xplane_fix_ds = ogr.Open('data/fix.dat') - if xplane_fix_ds is None: - return 'fail' + assert xplane_fix_ds is not None layers = [('FIX', 1, [('fix_name', '00MKK')]) ] for layer in layers: lyr = xplane_fix_ds.GetLayerByName(layer[0]) - if lyr.GetFeatureCount() != layer[1]: - gdaltest.post_reason('wrong number of features for layer %s : %d. %d were expected ' % (layer[0], lyr.GetFeatureCount(), layer[1])) - return 'fail' + assert lyr.GetFeatureCount() == layer[1], \ + ('wrong number of features for layer %s : %d. %d were expected ' % (layer[0], lyr.GetFeatureCount(), layer[1])) feat_read = lyr.GetNextFeature() for item in layer[2]: - if feat_read.GetField(item[0]) != item[1]: - print(layer[0]) - print(item[0]) - print(feat_read.GetField(item[0])) - return 'fail' - - return 'success' + assert feat_read.GetField(item[0]) == item[1], layer[0] + ############################################################################### # -gdaltest_list = [ - ogr_xplane_apt_dat, - ogr_xplane_apt_v810_dat, - ogr_xplane_nav_dat, - ogr_xplane_awy_dat, - ogr_xplane_fix_dat] - -if __name__ == '__main__': - - gdaltest.setup_run('ogr_xplane') - - gdaltest.run_tests(gdaltest_list) - sys.exit(gdaltest.summarize()) diff --git a/autotest/ogr/ograpispy.py b/autotest/ogr/ograpispy.py index 4e4f81fd5f52..2b454cb3fad2 100755 --- a/autotest/ogr/ograpispy.py +++ b/autotest/ogr/ograpispy.py @@ -30,23 +30,21 @@ ############################################################################### import os -import sys import shutil from difflib import unified_diff -sys.path.append('../pymod') -import gdaltest import ogrtest import test_py_scripts from osgeo import ogr from osgeo import gdal +import pytest ############################################################################### # Basic test without snapshoting -def ograpispy_1(): +def test_ograpispy_1(): gdal.SetConfigOption('OGR_API_SPY_FILE', 'tmp/ograpispy_1.py') test_py_scripts.run_py_script('data', 'testograpispy', '') @@ -57,30 +55,28 @@ def ograpispy_1(): ogrtest.has_apispy = True except OSError: ogrtest.has_apispy = False - return 'skip' + pytest.skip() ref_data = open('data/testograpispy.py', 'rt').read() got_data = open('tmp/ograpispy_1.py', 'rt').read() if ref_data != got_data: - gdaltest.post_reason('did not get expected script') print() for line in unified_diff(ref_data.splitlines(), got_data.splitlines(), fromfile='expected', tofile='got', lineterm=""): print(line) - return 'fail' - - return 'success' + pytest.fail('did not get expected script') + ############################################################################### # With snapshoting -def ograpispy_2(): +def test_ograpispy_2(): if not ogrtest.has_apispy: - return 'skip' + pytest.skip() try: shutil.rmtree('tmp/snapshot_1') @@ -103,16 +99,12 @@ def ograpispy_2(): ds = ogr.Open('tmp/snapshot_1/source/ograpispy_2.shp') lyr = ds.GetLayer(0) - if lyr.GetFeatureCount() != 0: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.GetFeatureCount() == 0 ds = None ds = ogr.Open('tmp/snapshot_1/working/ograpispy_2.shp', update=1) lyr = ds.GetLayer(0) - if lyr.GetFeatureCount() != 1: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.GetFeatureCount() == 1 # Add a feature to check that running the script will work lyr.CreateFeature(ogr.Feature(lyr.GetLayerDefn())) @@ -123,21 +115,16 @@ def ograpispy_2(): ds = ogr.Open('tmp/snapshot_1/working/ograpispy_2.shp') lyr = ds.GetLayer(0) - if lyr.GetFeatureCount() != 1: - print(lyr.GetFeatureCount()) - gdaltest.post_reason('fail') - return 'fail' + assert lyr.GetFeatureCount() == 1 ds = None shutil.rmtree('tmp/snapshot_1/working') - return 'success' - ############################################################################### # -def ograpispy_cleanup(): +def test_ograpispy_cleanup(): gdal.Unlink('tmp/ograpispy_1.py') gdal.Unlink('tmp/ograpispy_2.py') gdal.Unlink('tmp/ograpispy_2.pyc') @@ -152,19 +139,5 @@ def ograpispy_cleanup(): pass gdal.Unlink('/vsimem/test2.csv') - return 'success' - - -gdaltest_list = [ - ograpispy_1, - ograpispy_2, - ograpispy_cleanup -] - -if __name__ == '__main__': - - gdaltest.setup_run('ograpispy') - gdaltest.run_tests(gdaltest_list) - sys.exit(gdaltest.summarize()) diff --git a/autotest/osr/__init__.py b/autotest/osr/__init__.py new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/autotest/osr/osr_basic.py b/autotest/osr/osr_basic.py index 4c6b38997216..0032f05e76bd 100755 --- a/autotest/osr/osr_basic.py +++ b/autotest/osr/osr_basic.py @@ -31,32 +31,29 @@ # DEALINGS IN THE SOFTWARE. ############################################################################### -import sys -sys.path.append('../pymod') import gdaltest from osgeo import osr +import pytest ############################################################################### # Create a UTM WGS84 coordinate system and check various items. -def osr_basic_1(): +def test_osr_basic_1(): utm_srs = osr.SpatialReference() # Southern hemisphere utm_srs.SetUTM(11, 0) utm_srs.SetWellKnownGeogCS('WGS84') - if utm_srs.GetUTMZone() != -11: - return 'fail' + assert utm_srs.GetUTMZone() == -11 # Northern hemisphere utm_srs.SetUTM(11) - if utm_srs.GetUTMZone() != 11: - return 'fail' + assert utm_srs.GetUTMZone() == 11 parm_list = \ [(osr.SRS_PP_CENTRAL_MERIDIAN, -117.0), @@ -67,34 +64,29 @@ def osr_basic_1(): for parm in parm_list: value = utm_srs.GetProjParm(parm[0], -1111) - if abs(value - parm[1]) > .00000000000010: - gdaltest.post_reason('got %g for %s instead of %g.' + assert abs(value - parm[1]) <= .00000000000010, ('got %g for %s instead of %g.' % (value, parm[0], parm[1])) - return 'fail' auth_list = [('GEOGCS', '4326'), ('DATUM', '6326')] for auth in auth_list: - if utm_srs.GetAuthorityName(auth[0]) != 'EPSG': - gdaltest.post_reason('Got authority %s instead of EPSG for %s' + assert utm_srs.GetAuthorityName(auth[0]) == 'EPSG', \ + ('Got authority %s instead of EPSG for %s' % (utm_srs.GetAuthorityName(auth[0]), auth[0])) - return 'fail' - if str(utm_srs.GetAuthorityCode(auth[0])) != auth[1]: - gdaltest.post_reason('Got code %s instead of %s for %s' + assert str(utm_srs.GetAuthorityCode(auth[0])) == auth[1], \ + ('Got code %s instead of %s for %s' % (utm_srs.GetAuthorityName(auth[0]), auth[1], auth[0])) - return 'fail' - - return 'success' + ############################################################################### # Simple default NAD83 State Plane zone. -def osr_basic_2(): +def test_osr_basic_2(): srs = osr.SpatialReference() srs.SetStatePlane(403, 1) # California III NAD83. @@ -110,10 +102,9 @@ def osr_basic_2(): for parm in parm_list: value = srs.GetProjParm(parm[0], -1111) - if not gdaltest.approx_equal(parm[1], value): - gdaltest.post_reason('got %.16g for %s instead of %.16g.' + assert gdaltest.approx_equal(parm[1], value), \ + ('got %.16g for %s instead of %.16g.' % (value, parm[0], parm[1])) - return 'fail' auth_list = [('GEOGCS', '4269'), ('DATUM', '6269'), @@ -121,25 +112,22 @@ def osr_basic_2(): ('PROJCS|UNIT', '9001')] for auth in auth_list: - if srs.GetAuthorityName(auth[0]) != 'EPSG': - gdaltest.post_reason('Got authority %s instead of EPSG for %s' + assert srs.GetAuthorityName(auth[0]) == 'EPSG', \ + ('Got authority %s instead of EPSG for %s' % (srs.GetAuthorityName(auth[0]), auth[0])) - return 'fail' - if str(srs.GetAuthorityCode(auth[0])) != auth[1]: - gdaltest.post_reason('Got code %s instead of %s for %s' + assert str(srs.GetAuthorityCode(auth[0])) == auth[1], \ + ('Got code %s instead of %s for %s' % (srs.GetAuthorityCode(auth[0]), auth[1], auth[0])) - return 'fail' - - return 'success' + ############################################################################### # NAD83 State Plane zone, but overridden to be in Feet. -def osr_basic_3(): +def test_osr_basic_3(): srs = osr.SpatialReference() @@ -157,62 +145,51 @@ def osr_basic_3(): for parm in parm_list: value = srs.GetProjParm(parm[0], -1111) - if not gdaltest.approx_equal(parm[1], value): - gdaltest.post_reason('got %.16g for %s instead of %.16g.' + assert gdaltest.approx_equal(parm[1], value), \ + ('got %.16g for %s instead of %.16g.' % (value, parm[0], parm[1])) - return 'fail' auth_list = [('GEOGCS', '4269'), ('DATUM', '6269')] for auth in auth_list: - if srs.GetAuthorityName(auth[0]) != 'EPSG': - gdaltest.post_reason('Got authority %s instead of EPSG for %s' + assert srs.GetAuthorityName(auth[0]) == 'EPSG', \ + ('Got authority %s instead of EPSG for %s' % (srs.GetAuthorityName(auth[0]), auth[0])) - return 'fail' - if str(srs.GetAuthorityCode(auth[0])) != auth[1]: - gdaltest.post_reason('Got code %s instead of %s for %s' + assert str(srs.GetAuthorityCode(auth[0])) == auth[1], \ + ('Got code %s instead of %s for %s' % (srs.GetAuthorityCode(auth[0]), auth[1], auth[0])) - return 'fail' - if srs.GetAuthorityName('PROJCS') is not None: - gdaltest.post_reason('Got a PROJCS Authority but we should not') - return 'fail' + assert srs.GetAuthorityName('PROJCS') is None, \ + 'Got a PROJCS Authority but we should not' - if str(srs.GetAuthorityCode('PROJCS|UNIT')) == '9001': - gdaltest.post_reason('Got METER authority code on linear units.') - return 'fail' + assert str(srs.GetAuthorityCode('PROJCS|UNIT')) != '9001', \ + 'Got METER authority code on linear units.' - if srs.GetLinearUnitsName() != 'Foot': - gdaltest.post_reason('Didnt get Foot linear units') - return 'fail' + assert srs.GetLinearUnitsName() == 'Foot', 'Didnt get Foot linear units' if srs.GetLinearUnits() != 0.3048006096012192: - gdaltest.post_reason('Didnt get Foot linear units') print('%.16g' % srs.GetLinearUnits()) - return 'fail' + pytest.fail('Didnt get Foot linear units') if srs.GetTargetLinearUnits('PROJCS') != 0.3048006096012192: - gdaltest.post_reason('Didnt get Foot linear units') print('%.16g' % srs.GetTargetLinearUnits('PROJCS')) - return 'fail' + pytest.fail('Didnt get Foot linear units') if srs.GetTargetLinearUnits(None) != 0.3048006096012192: - gdaltest.post_reason('Didnt get Foot linear units') print('%.16g' % srs.GetTargetLinearUnits(None)) - return 'fail' - - return 'success' + pytest.fail('Didnt get Foot linear units') + ############################################################################### # Translate a coordinate system with nad shift into to PROJ.4 and back # and verify that the TOWGS84 parameters are preserved. -def osr_basic_4(): +def test_osr_basic_4(): srs = osr.SpatialReference() srs.SetGS(cm=-117.0, fe=100000.0, fn=100000) @@ -221,55 +198,42 @@ def osr_basic_4(): srs.SetTOWGS84(1, 2, 3) - if srs.GetTOWGS84() != (1, 2, 3, 0, 0, 0, 0): - gdaltest.post_reason('GetTOWGS84() result is wrong.') - return 'fail' + assert srs.GetTOWGS84() == (1, 2, 3, 0, 0, 0, 0), 'GetTOWGS84() result is wrong.' proj4 = srs.ExportToProj4() srs2 = osr.SpatialReference() srs2.ImportFromProj4(proj4) - if srs2.GetTOWGS84() != (1, 2, 3, 0, 0, 0, 0): - gdaltest.post_reason('GetTOWGS84() result is wrong after PROJ.4 conversion.') - return 'fail' - - return 'success' + assert srs2.GetTOWGS84() == (1, 2, 3, 0, 0, 0, 0), \ + 'GetTOWGS84() result is wrong after PROJ.4 conversion.' ############################################################################### # Test URN support for OGC:CRS84. -def osr_basic_5(): +def test_osr_basic_5(): wkt_1 = osr.GetUserInputAsWKT('urn:ogc:def:crs:OGC:1.3:CRS84') wkt_2 = osr.GetUserInputAsWKT('WGS84') - if wkt_1 != wkt_2: - gdaltest.post_reason('CRS84 lookup not as expected.') - return 'fail' - - return 'success' + assert wkt_1 == wkt_2, 'CRS84 lookup not as expected.' ############################################################################### # Test URN support for EPSG -def osr_basic_6(): +def test_osr_basic_6(): # Without version wkt_1 = osr.GetUserInputAsWKT('urn:x-ogc:def:crs:EPSG::4326') - if wkt_1.find('GEOGCS["WGS 84",DATUM["WGS_1984"') == -1 or wkt_1.find('AXIS["Latitude",NORTH],AXIS["Longitude",EAST]') == -1: - print(wkt_1) - gdaltest.post_reason('EPSG:4326 urn lookup not as expected.') - return 'fail' + assert not (wkt_1.find('GEOGCS["WGS 84",DATUM["WGS_1984"') == -1 or wkt_1.find('AXIS["Latitude",NORTH],AXIS["Longitude",EAST]') == -1), \ + 'EPSG:4326 urn lookup not as expected.' # With a version wkt_2 = osr.GetUserInputAsWKT('urn:x-ogc:def:crs:EPSG:6.6:4326') if wkt_2.find('GEOGCS["WGS 84",DATUM["WGS_1984"') == -1 or wkt_2.find('AXIS["Latitude",NORTH],AXIS["Longitude",EAST]') == -1: print(wkt_1) - print(wkt_2) - gdaltest.post_reason('EPSG:4326 urn lookup not as expected.') - return 'fail' + pytest.fail('EPSG:4326 urn lookup not as expected.') # Without version, but with no repeated :. Probably illegal from my understanding # of http://www.opengeospatial.org/ogcUrnPolicy, but found quite often in the wild @@ -277,33 +241,24 @@ def osr_basic_6(): wkt_2 = osr.GetUserInputAsWKT('urn:x-ogc:def:crs:EPSG:4326') if wkt_2.find('GEOGCS["WGS 84",DATUM["WGS_1984"') == -1 or wkt_2.find('AXIS["Latitude",NORTH],AXIS["Longitude",EAST]') == -1: print(wkt_1) - print(wkt_2) - gdaltest.post_reason('EPSG:4326 urn lookup not as expected.') - return 'fail' - - return 'success' + pytest.fail('EPSG:4326 urn lookup not as expected.') + ############################################################################### # Test URN support for auto projection. -def osr_basic_7(): +def test_osr_basic_7(): wkt_1 = osr.GetUserInputAsWKT('urn:ogc:def:crs:OGC::AUTO42001:-117:33') wkt_2 = 'PROJCS["UTM Zone 11, Northern Hemisphere",GEOGCS["WGS 84",DATUM["WGS_1984",SPHEROID["WGS 84",6378137,298.257223563,AUTHORITY["EPSG","7030"]],AUTHORITY["EPSG","6326"]],PRIMEM["Greenwich",0,AUTHORITY["EPSG","8901"]],UNIT["degree",0.0174532925199433,AUTHORITY["EPSG","9122"]],AUTHORITY["EPSG","4326"]],PROJECTION["Transverse_Mercator"],PARAMETER["latitude_of_origin",0],PARAMETER["central_meridian",-117],PARAMETER["scale_factor",0.9996],PARAMETER["false_easting",500000],PARAMETER["false_northing",0],UNIT["Meter",1,AUTHORITY["EPSG","9001"]]]' - if wkt_1 != wkt_2: - print(wkt_1) - print(wkt_2) - gdaltest.post_reason('AUTO42001 urn lookup not as expected.') - return 'fail' - - return 'success' + assert wkt_1 == wkt_2, 'AUTO42001 urn lookup not as expected.' ############################################################################### # Test the SetLinearUnitsAndUpdateParameters() method. -def osr_basic_8(): +def test_osr_basic_8(): srs = osr.SpatialReference() @@ -311,46 +266,34 @@ def osr_basic_8(): srs.SetLinearUnits('Foot', 0.3048) fe = srs.GetProjParm('false_easting') - if fe != 1000.0: - gdaltest.post_reason('false easting was unexpectedly updated.') - return 'fail' + assert fe == 1000.0, 'false easting was unexpectedly updated.' if 'SetLinearUnitsAndUpdateParameters' not in dir(srs): - return 'skip' + pytest.skip() srs.SetFromUserInput('+proj=tmerc +x_0=1000 +datum=WGS84 +units=m') srs.SetLinearUnitsAndUpdateParameters('Foot', 0.3048) fe = srs.GetProjParm('false_easting') - if fe == 1000.0: - gdaltest.post_reason('false easting was unexpectedly not updated.') - return 'fail' + assert fe != 1000.0, 'false easting was unexpectedly not updated.' - if abs(fe - 3280.840) > 0.01: - print(fe) - gdaltest.post_reason('wrong updated false easting value.') - return 'fail' - - return 'success' + assert abs(fe - 3280.840) <= 0.01, 'wrong updated false easting value.' ############################################################################### # Test the Validate() method. -def osr_basic_9(): +def test_osr_basic_9(): srs = osr.SpatialReference() srs.SetFromUserInput("PROJCS[\"unnamed\",GEOGCS[\"unnamed ellipse\",DATUM[\"unknown\",SPHEROID[\"unnamed\",6378137,0]],PRIMEM[\"Greenwich\",0],UNIT[\"degree\",0.0174532925199433]],PROJECTION[\"Mercator_2SP\"],PARAMETER[\"standard_parallel_1\",0],PARAMETER[\"latitude_of_origin\",0],PARAMETER[\"central_meridian\",0],PARAMETER[\"false_easting\",0],PARAMETER[\"false_northing\",0],UNIT[\"Meter\",1],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\"]]") - if srs.Validate() != 0: - return 'fail' - - return 'success' + assert srs.Validate() == 0 ############################################################################### # Test the Validate() method on PROJCS with AXIS definition (#2739) -def osr_basic_10(): +def test_osr_basic_10(): srs = osr.SpatialReference() srs.SetFromUserInput("""PROJCS["NAD83(CSRS98) / UTM zone 20N (deprecated)", @@ -377,16 +320,13 @@ def osr_basic_10(): AXIS["Northing",NORTH], AUTHORITY["EPSG","2038"]]""") - if srs.Validate() != 0: - return 'fail' - - return 'success' + assert srs.Validate() == 0 ############################################################################### # Test the IsSame() method (and the IsSameGeogCS() method through that) -def osr_basic_11(): +def test_osr_basic_11(): srs1 = osr.SpatialReference() srs1.SetFromUserInput("""PROJCS["NAD83(CSRS98) / UTM zone 20N (deprecated)", @@ -434,29 +374,25 @@ def osr_basic_11(): AXIS["Northing",NORTH]]""") if srs1.IsSame(srs2): - return 'success' + return - return 'fail' + pytest.fail() ############################################################################### # Test URN support for OGC:CRS84. -def osr_basic_12(): +def test_osr_basic_12(): wkt_1 = osr.GetUserInputAsWKT('CRS:84') wkt_2 = osr.GetUserInputAsWKT('WGS84') - if wkt_1 != wkt_2: - gdaltest.post_reason('CRS:84 lookup not as expected.') - return 'fail' - - return 'success' + assert wkt_1 == wkt_2, 'CRS:84 lookup not as expected.' ############################################################################### # Test GEOCCS lookup in supporting data files. -def osr_basic_13(): +def test_osr_basic_13(): srs = osr.SpatialReference() srs.ImportFromEPSG(4328) @@ -464,26 +400,17 @@ def osr_basic_13(): expected_wkt = 'GEOCCS["WGS 84 (geocentric) (deprecated)",DATUM["WGS_1984",SPHEROID["WGS 84",6378137,298.257223563,AUTHORITY["EPSG","7030"]],AUTHORITY["EPSG","6326"]],PRIMEM["Greenwich",0,AUTHORITY["EPSG","8901"]],UNIT["metre",1,AUTHORITY["EPSG","9001"]],AXIS["Geocentric X",OTHER],AXIS["Geocentric Y",OTHER],AXIS["Geocentric Z",NORTH],AUTHORITY["EPSG","4328"]]' wkt = srs.ExportToWkt() - if wkt != expected_wkt: - gdaltest.post_reason('did not get expected GEOCCS WKT.') - print(wkt) - return 'fail' - - if not srs.IsGeocentric(): - gdaltest.post_reason('srs not recognised as geocentric.') - return 'fail' + assert wkt == expected_wkt, 'did not get expected GEOCCS WKT.' - if srs.Validate() != 0: - gdaltest.post_reason('epsg geoccs import does not validate!') - return 'fail' + assert srs.IsGeocentric(), 'srs not recognised as geocentric.' - return 'success' + assert srs.Validate() == 0, 'epsg geoccs import does not validate!' ############################################################################### # Manually setup a simple geocentric/wgs84 srs. -def osr_basic_14(): +def test_osr_basic_14(): srs = osr.SpatialReference() srs.SetGeocCS('My Geocentric') @@ -493,26 +420,17 @@ def osr_basic_14(): expected_wkt = 'GEOCCS["My Geocentric",DATUM["WGS_1984",SPHEROID["WGS 84",6378137,298.257223563,AUTHORITY["EPSG","7030"]],AUTHORITY["EPSG","6326"]],PRIMEM["Greenwich",0,AUTHORITY["EPSG","8901"]],UNIT["meter",1]]' wkt = srs.ExportToWkt() - if wkt != expected_wkt: - gdaltest.post_reason('did not get expected GEOCCS WKT.') - print(wkt) - return 'fail' + assert wkt == expected_wkt, 'did not get expected GEOCCS WKT.' - if not srs.IsGeocentric(): - gdaltest.post_reason('srs not recognised as geocentric.') - return 'fail' + assert srs.IsGeocentric(), 'srs not recognised as geocentric.' - if srs.Validate() != 0: - gdaltest.post_reason('geocentric srs not recognised as valid.') - return 'fail' - - return 'success' + assert srs.Validate() == 0, 'geocentric srs not recognised as valid.' ############################################################################### # Test validation and fixup methods. -def osr_basic_15(): +def test_osr_basic_15(): wkt = """GEOCCS["WGS 84 (geocentric)", PRIMEM["Greenwich",0, @@ -529,23 +447,17 @@ def osr_basic_15(): srs = osr.SpatialReference() srs.SetFromUserInput(wkt) - if srs.Validate() == 0: - gdaltest.post_reason('Validate() fails to detect misordering.') - return 'fail' + assert srs.Validate() != 0, 'Validate() fails to detect misordering.' srs.Fixup() - if srs.Validate() != 0: - gdaltest.post_reason('Fixup() failed to correct srs.') - return 'fail' - - return 'success' + assert srs.Validate() == 0, 'Fixup() failed to correct srs.' ############################################################################### # Test OSRSetGeocCS() -def osr_basic_16(): +def test_osr_basic_16(): # Nominal test : change citation of a GEOCCS srs = osr.SpatialReference() @@ -576,8 +488,7 @@ def osr_basic_16(): if wkt != expect_wkt: print('Got:%s' % wkt) print('Expected:%s' % expect_wkt) - gdaltest.post_reason('Did not get expected result.') - return 'fail' + pytest.fail('Did not get expected result.') # Build GEOCCS from a valid GEOGCS srs = osr.SpatialReference() @@ -594,17 +505,15 @@ def osr_basic_16(): if wkt != expect_wkt: print('Got:%s' % wkt) print('Expected:%s' % expect_wkt) - gdaltest.post_reason('Did not get expected result.') - return 'fail' + pytest.fail('Did not get expected result.') # Error expected. Cannot work on a PROJCS srs = osr.SpatialReference() srs.ImportFromEPSG(32631) ret = srs.SetGeocCS("a") if ret == 0: - gdaltest.post_reason('expected failure') print(srs) - return 'fail' + pytest.fail('expected failure') # Limit test : build GEOCCS from an invalid GEOGCS srs = osr.SpatialReference() @@ -615,45 +524,34 @@ def osr_basic_16(): if wkt != expect_wkt: print('Got:%s' % wkt) print('Expected:%s' % expect_wkt) - gdaltest.post_reason('Did not get expected result.') - return 'fail' - - return 'success' + pytest.fail('Did not get expected result.') + ############################################################################### # Test OGC URL support -def osr_basic_17(): +def test_osr_basic_17(): wkt_1 = osr.GetUserInputAsWKT('urn:ogc:def:crs:EPSG::4326') wkt_2 = osr.GetUserInputAsWKT('http://www.opengis.net/def/crs/EPSG/0/4326') - if wkt_1 != wkt_2: - gdaltest.post_reason('CRS URL parsing not as expected.') - return 'fail' - - return 'success' + assert wkt_1 == wkt_2, 'CRS URL parsing not as expected.' ############################################################################### # Test OGC URL support for compound CRS -def osr_basic_18(): +def test_osr_basic_18(): # This is a dummy one, but who cares wkt = osr.GetUserInputAsWKT('http://www.opengis.net/def/crs-compound?1=http://www.opengis.net/def/crs/EPSG/0/4326&2=http://www.opengis.net/def/crs/EPSG/0/4326') - if wkt.find('COMPD_CS') != 0: - print(wkt) - gdaltest.post_reason('CRS URL parsing not as expected.') - return 'fail' - - return 'success' + assert wkt.find('COMPD_CS') == 0, 'CRS URL parsing not as expected.' ############################################################################### # Test well known GCS names against their corresponding EPSG definitions (#6080) -def osr_basic_19(): +def test_osr_basic_19(): sr = osr.SpatialReference() sr.SetWellKnownGeogCS('WGS84') @@ -661,11 +559,7 @@ def osr_basic_19(): sr_ref = osr.SpatialReference() sr_ref.ImportFromEPSG(4326) - if sr.ExportToWkt() != sr_ref.ExportToWkt(): - gdaltest.post_reason('fail') - print(sr.ExportToWkt()) - print(sr_ref.ExportToWkt()) - return 'fail' + assert sr.ExportToWkt() == sr_ref.ExportToWkt() sr = osr.SpatialReference() sr.SetWellKnownGeogCS('WGS72') @@ -673,11 +567,7 @@ def osr_basic_19(): sr_ref = osr.SpatialReference() sr_ref.ImportFromEPSG(4322) - if sr.ExportToWkt() != sr_ref.ExportToWkt(): - gdaltest.post_reason('fail') - print(sr.ExportToWkt()) - print(sr_ref.ExportToWkt()) - return 'fail' + assert sr.ExportToWkt() == sr_ref.ExportToWkt() sr = osr.SpatialReference() sr.SetWellKnownGeogCS('NAD27') @@ -685,11 +575,7 @@ def osr_basic_19(): sr_ref = osr.SpatialReference() sr_ref.ImportFromEPSG(4267) - if sr.ExportToWkt() != sr_ref.ExportToWkt(): - gdaltest.post_reason('fail') - print(sr.ExportToWkt()) - print(sr_ref.ExportToWkt()) - return 'fail' + assert sr.ExportToWkt() == sr_ref.ExportToWkt() sr = osr.SpatialReference() sr.SetWellKnownGeogCS('NAD83') @@ -697,55 +583,32 @@ def osr_basic_19(): sr_ref = osr.SpatialReference() sr_ref.ImportFromEPSG(4269) - if sr.ExportToWkt() != sr_ref.ExportToWkt(): - gdaltest.post_reason('fail') - print(sr.ExportToWkt()) - print(sr_ref.ExportToWkt()) - return 'fail' - - return 'success' + assert sr.ExportToWkt() == sr_ref.ExportToWkt() ############################################################################### # Test GetAxisName() and GetAxisOrientation() and GetAngularUnitsName() -def osr_basic_20(): +def test_osr_basic_20(): sr = osr.SpatialReference() sr.ImportFromEPSGA(4326) - if sr.GetAxisName(None, 0) != 'Latitude': - gdaltest.post_reason('fail') - print(sr.GetAxisName(None, 0)) - return 'fail' - - if sr.GetAxisOrientation(None, 0) != osr.OAO_North: - gdaltest.post_reason('fail') - print(sr.GetAxisOrientation(None, 0)) - return 'fail' + assert sr.GetAxisName(None, 0) == 'Latitude' - if sr.GetAxisName('GEOGCS', 1) != 'Longitude': - gdaltest.post_reason('fail') - print(sr.GetAxisName('GEOGCS', 1)) - return 'fail' + assert sr.GetAxisOrientation(None, 0) == osr.OAO_North - if sr.GetAxisOrientation('GEOGCS', 1) != osr.OAO_East: - gdaltest.post_reason('fail') - print(sr.GetAxisOrientation('GEOGCS', 1)) - return 'fail' + assert sr.GetAxisName('GEOGCS', 1) == 'Longitude' - if sr.GetAngularUnitsName() != 'degree': - gdaltest.post_reason('fail') - print(sr.GetAngularUnitsName()) - return 'fail' + assert sr.GetAxisOrientation('GEOGCS', 1) == osr.OAO_East - return 'success' + assert sr.GetAngularUnitsName() == 'degree' ############################################################################### # Test IsSame() with equivalent forms of Mercator_1SP and Mercator_2SP -def osr_basic_21(): +def test_osr_basic_21(): wkt1 = """PROJCS["unnamed", GEOGCS["Segara (Jakarta)", @@ -788,28 +651,20 @@ def osr_basic_21(): sr2 = osr.SpatialReference() sr2.ImportFromWkt(wkt2) - if sr1.IsSame(sr2) == 0: - gdaltest.post_reason('fail') - return 'fail' + assert sr1.IsSame(sr2) != 0 - if sr2.IsSame(sr1) == 0: - gdaltest.post_reason('fail') - return 'fail' + assert sr2.IsSame(sr1) != 0 sr2_not_equivalent = osr.SpatialReference() sr2_not_equivalent.ImportFromWkt(wkt2_not_equivalent) - if sr1.IsSame(sr2_not_equivalent) == 1: - gdaltest.post_reason('fail') - return 'fail' - - return 'success' + assert sr1.IsSame(sr2_not_equivalent) != 1 ############################################################################### # Test LCC_2SP -> LCC_1SP -> LCC_2SP -def osr_basic_22(): +def test_osr_basic_22(): sr = osr.SpatialReference() sr.SetFromUserInput("""PROJCS["unnamed", @@ -859,17 +714,11 @@ def osr_basic_22(): expected_sr2 = osr.SpatialReference() expected_sr2.ImportFromWkt(expected_sr2_wkt) - if sr2.IsSame(expected_sr2) == 0: - gdaltest.post_reason('fail') - print(sr2) - return 'fail' + assert sr2.IsSame(expected_sr2) != 0 # Back to LCC_2SP sr3 = sr2.ConvertToOtherProjection(osr.SRS_PT_LAMBERT_CONFORMAL_CONIC_2SP) - if sr3.IsSame(sr) == 0: - gdaltest.post_reason('fail') - print(sr3) - return 'fail' + assert sr3.IsSame(sr) != 0 # Particular case of LCC_2SP with phi0=phi1=phi2 sr.SetFromUserInput("""PROJCS["unnamed", @@ -914,16 +763,10 @@ def osr_basic_22(): expected_sr2 = osr.SpatialReference() expected_sr2.ImportFromWkt(expected_sr2_wkt) - if sr2.IsSame(expected_sr2) == 0: - gdaltest.post_reason('fail') - print(sr2) - return 'fail' + assert sr2.IsSame(expected_sr2) != 0 sr3 = sr2.ConvertToOtherProjection(osr.SRS_PT_LAMBERT_CONFORMAL_CONIC_2SP) - if sr3.IsSame(sr) == 0: - gdaltest.post_reason('fail') - print(sr3) - return 'fail' + assert sr3.IsSame(sr) != 0 # Particular case of LCC_2SP with phi0 != phi1 and phi1=phi2 sr.SetFromUserInput("""PROJCS["unnamed", @@ -968,10 +811,7 @@ def osr_basic_22(): expected_sr2 = osr.SpatialReference() expected_sr2.ImportFromWkt(expected_sr2_wkt) - if sr2.IsSame(expected_sr2) == 0: - gdaltest.post_reason('fail') - print(sr2) - return 'fail' + assert sr2.IsSame(expected_sr2) != 0 sr3 = sr2.ConvertToOtherProjection(osr.SRS_PT_LAMBERT_CONFORMAL_CONIC_2SP) expected_sr3_wkt = """PROJCS["unnamed", @@ -995,18 +835,13 @@ def osr_basic_22(): PARAMETER["false_northing",6637093.292952879]]""" expected_sr3 = osr.SpatialReference() expected_sr3.ImportFromWkt(expected_sr3_wkt) - if sr3.IsSame(expected_sr3) == 0: - gdaltest.post_reason('fail') - print(sr3) - return 'fail' - - return 'success' + assert sr3.IsSame(expected_sr3) != 0 ############################################################################### # Test LCC_1SP -> LCC_2SP -> LCC_1SP -def osr_basic_23(): +def test_osr_basic_23(): sr = osr.SpatialReference() sr.SetFromUserInput("""PROJCS["unnamed", @@ -1056,25 +891,17 @@ def osr_basic_23(): expected_sr2 = osr.SpatialReference() expected_sr2.ImportFromWkt(expected_sr2_wkt) - if sr2.IsSame(expected_sr2) == 0: - gdaltest.post_reason('fail') - print(sr2) - return 'fail' + assert sr2.IsSame(expected_sr2) != 0 # Back to LCC_2SP sr3 = sr2.ConvertToOtherProjection(osr.SRS_PT_LAMBERT_CONFORMAL_CONIC_1SP) - if sr3.IsSame(sr) == 0: - gdaltest.post_reason('fail') - print(sr3) - return 'fail' - - return 'success' + assert sr3.IsSame(sr) != 0 ############################################################################### # Test Mercator_1SP -> Mercator_2SP -> Mercator_1SP -def osr_basic_24(): +def test_osr_basic_24(): sr = osr.SpatialReference() sr.SetFromUserInput("""PROJCS["unnamed", @@ -1114,25 +941,17 @@ def osr_basic_24(): expected_sr2 = osr.SpatialReference() expected_sr2.ImportFromWkt(expected_sr2_wkt) - if sr2.IsSame(expected_sr2) == 0: - gdaltest.post_reason('fail') - print(sr2) - return 'fail' + assert sr2.IsSame(expected_sr2) != 0 # Back to LCC_2SP sr3 = sr2.ConvertToOtherProjection(osr.SRS_PT_MERCATOR_1SP) - if sr3.IsSame(sr) == 0: - gdaltest.post_reason('fail') - print(sr3) - return 'fail' - - return 'success' + assert sr3.IsSame(sr) != 0 ############################################################################### # Test corner cases of ConvertToOtherProjection() -def osr_basic_25(): +def test_osr_basic_25(): sr = osr.SpatialReference() sr.SetFromUserInput("""GEOGCS["WGS 84", @@ -1140,10 +959,7 @@ def osr_basic_25(): SPHEROID["WGS 84",6378137,298.257223563]], UNIT["degree",0.0174532925199433]]""") sr2 = sr.ConvertToOtherProjection('Mercator_1SP') - if sr2 is not None: - gdaltest.post_reason('fail') - print(sr2) - return 'fail' + assert sr2 is None sr.SetFromUserInput("""PROJCS["unnamed", GEOGCS["WGS 84", @@ -1157,20 +973,13 @@ def osr_basic_25(): PARAMETER["false_northing",0]]""") sr2 = sr.ConvertToOtherProjection(None) - if sr2 is not None: - gdaltest.post_reason('fail') - return 'fail' + assert sr2 is None sr2 = sr.ConvertToOtherProjection('foo') - if sr2 is not None: - gdaltest.post_reason('fail') - return 'fail' + assert sr2 is None sr2 = sr.ConvertToOtherProjection('Mercator_1SP') - if sr2.IsSame(sr) == 0: - gdaltest.post_reason('fail') - print(sr2) - return 'fail' + assert sr2.IsSame(sr) != 0 # Mercator_1SP -> Mercator_2SP: Negative scale factor sr = osr.SpatialReference() @@ -1185,10 +994,7 @@ def osr_basic_25(): PARAMETER["false_easting",0], PARAMETER["false_northing",0]]""") sr2 = sr.ConvertToOtherProjection('Mercator_2SP') - if sr2 is not None: - gdaltest.post_reason('fail') - print(sr2) - return 'fail' + assert sr2 is None # Mercator_1SP -> Mercator_2SP: Invalid eccentricity sr = osr.SpatialReference() @@ -1203,10 +1009,7 @@ def osr_basic_25(): PARAMETER["false_easting",0], PARAMETER["false_northing",0]]""") sr2 = sr.ConvertToOtherProjection('Mercator_2SP') - if sr2 is not None: - gdaltest.post_reason('fail') - print(sr2) - return 'fail' + assert sr2 is None # Mercator_2SP -> Mercator_1SP: Invalid standard_parallel_1 sr = osr.SpatialReference() @@ -1221,10 +1024,7 @@ def osr_basic_25(): PARAMETER["false_easting",0], PARAMETER["false_northing",0]]""") sr2 = sr.ConvertToOtherProjection('Mercator_1SP') - if sr2 is not None: - gdaltest.post_reason('fail') - print(sr2) - return 'fail' + assert sr2 is None # Mercator_2SP -> Mercator_1SP: Invalid eccentricity sr = osr.SpatialReference() @@ -1239,10 +1039,7 @@ def osr_basic_25(): PARAMETER["false_easting",0], PARAMETER["false_northing",0]]""") sr2 = sr.ConvertToOtherProjection('Mercator_1SP') - if sr2 is not None: - gdaltest.post_reason('fail') - print(sr2) - return 'fail' + assert sr2 is None # LCC_1SP -> LCC_2SP: Negative scale factor sr = osr.SpatialReference() @@ -1259,10 +1056,7 @@ def osr_basic_25(): PARAMETER["false_easting",234.358], PARAMETER["false_northing",4185861.369]]""") sr2 = sr.ConvertToOtherProjection('Lambert_Conformal_Conic_2SP') - if sr2 is not None: - gdaltest.post_reason('fail') - print(sr2) - return 'fail' + assert sr2 is None # LCC_1SP -> LCC_2SP: Invalid eccentricity sr = osr.SpatialReference() @@ -1279,10 +1073,7 @@ def osr_basic_25(): PARAMETER["false_easting",234.358], PARAMETER["false_northing",4185861.369]]""") sr2 = sr.ConvertToOtherProjection('Lambert_Conformal_Conic_2SP') - if sr2 is not None: - gdaltest.post_reason('fail') - print(sr2) - return 'fail' + assert sr2 is None # LCC_1SP -> LCC_2SP: Invalid latitude_of_origin sr = osr.SpatialReference() @@ -1299,10 +1090,7 @@ def osr_basic_25(): PARAMETER["false_easting",234.358], PARAMETER["false_northing",4185861.369]]""") sr2 = sr.ConvertToOtherProjection('Lambert_Conformal_Conic_2SP') - if sr2 is not None: - gdaltest.post_reason('fail') - print(sr2) - return 'fail' + assert sr2 is None # LCC_1SP -> LCC_2SP: latitude_of_origin == 0 sr = osr.SpatialReference() @@ -1319,10 +1107,7 @@ def osr_basic_25(): PARAMETER["false_easting",234.358], PARAMETER["false_northing",4185861.369]]""") sr2 = sr.ConvertToOtherProjection('Lambert_Conformal_Conic_2SP') - if sr2 is not None: - gdaltest.post_reason('fail') - print(sr2) - return 'fail' + assert sr2 is None # LCC_2SP -> LCC_1SP : Invalid standard_parallel_1 sr.SetFromUserInput("""PROJCS["unnamed", @@ -1338,10 +1123,7 @@ def osr_basic_25(): PARAMETER["false_easting",700000], PARAMETER["false_northing",6600000]]""") sr2 = sr.ConvertToOtherProjection('Lambert_Conformal_Conic_1SP') - if sr2 is not None: - gdaltest.post_reason('fail') - print(sr2) - return 'fail' + assert sr2 is None # LCC_2SP -> LCC_1SP : Invalid standard_parallel_2 sr.SetFromUserInput("""PROJCS["unnamed", @@ -1357,10 +1139,7 @@ def osr_basic_25(): PARAMETER["false_easting",700000], PARAMETER["false_northing",6600000]]""") sr2 = sr.ConvertToOtherProjection('Lambert_Conformal_Conic_1SP') - if sr2 is not None: - gdaltest.post_reason('fail') - print(sr2) - return 'fail' + assert sr2 is None # LCC_2SP -> LCC_1SP : Invalid latitude_of_origin sr.SetFromUserInput("""PROJCS["unnamed", @@ -1376,10 +1155,7 @@ def osr_basic_25(): PARAMETER["false_easting",700000], PARAMETER["false_northing",6600000]]""") sr2 = sr.ConvertToOtherProjection('Lambert_Conformal_Conic_1SP') - if sr2 is not None: - gdaltest.post_reason('fail') - print(sr2) - return 'fail' + assert sr2 is None # LCC_2SP -> LCC_1SP : abs(stdp1) == abs(stdp2) sr.SetFromUserInput("""PROJCS["unnamed", @@ -1395,10 +1171,7 @@ def osr_basic_25(): PARAMETER["false_easting",700000], PARAMETER["false_northing",6600000]]""") sr2 = sr.ConvertToOtherProjection('Lambert_Conformal_Conic_1SP') - if sr2 is not None: - gdaltest.post_reason('fail') - print(sr2) - return 'fail' + assert sr2 is None # LCC_2SP -> LCC_1SP : stdp1 ~= stdp2 ~= 0 sr.SetFromUserInput("""PROJCS["unnamed", @@ -1414,10 +1187,7 @@ def osr_basic_25(): PARAMETER["false_easting",700000], PARAMETER["false_northing",6600000]]""") sr2 = sr.ConvertToOtherProjection('Lambert_Conformal_Conic_1SP') - if sr2 is not None: - gdaltest.post_reason('fail') - print(sr2) - return 'fail' + assert sr2 is None # LCC_2SP -> LCC_1SP : Invalid eccentricity sr.SetFromUserInput("""PROJCS["unnamed", @@ -1433,87 +1203,30 @@ def osr_basic_25(): PARAMETER["false_easting",700000], PARAMETER["false_northing",6600000]]""") sr2 = sr.ConvertToOtherProjection('Lambert_Conformal_Conic_1SP') - if sr2 is not None: - gdaltest.post_reason('fail') - print(sr2) - return 'fail' - - return 'success' + assert sr2 is None ############################################################################### # Test corner cases of osr.SetGeocCS() -def osr_basic_setgeogcs(): +def test_osr_basic_setgeogcs(): sr = osr.SpatialReference() sr.SetGeogCS(None, None, None, 0, 0, None, 0, None, 0) - if sr.ExportToWkt() != 'GEOGCS["unnamed",DATUM["unknown",SPHEROID["unnamed",0,0]],PRIMEM["Greenwich",0],UNIT["degree",0.0174532925199433]]': - gdaltest.post_reason('fail') - print(sr.ExportToWkt()) - return 'fail' + assert sr.ExportToWkt() == 'GEOGCS["unnamed",DATUM["unknown",SPHEROID["unnamed",0,0]],PRIMEM["Greenwich",0],UNIT["degree",0.0174532925199433]]' sr.SetGeogCS('a', 'b', 'c', 1, 2, 'd', 3, 'e', 4) - if sr.ExportToWkt() != 'GEOGCS["a",DATUM["b",SPHEROID["c",1,2]],PRIMEM["d",3],UNIT["e",4]]': - gdaltest.post_reason('fail') - print(sr.ExportToWkt()) - return 'fail' + assert sr.ExportToWkt() == 'GEOGCS["a",DATUM["b",SPHEROID["c",1,2]],PRIMEM["d",3],UNIT["e",4]]' sr.SetUTM(31) sr.SetGeogCS(None, None, None, 0, 0, None, 0, None, 0) - if sr.ExportToWkt() != 'PROJCS["UTM Zone 31, Northern Hemisphere",GEOGCS["unnamed",DATUM["unknown",SPHEROID["unnamed",0,0]],PRIMEM["Greenwich",0],UNIT["degree",0.0174532925199433]],PROJECTION["Transverse_Mercator"],PARAMETER["latitude_of_origin",0],PARAMETER["central_meridian",0.01308996938995747],PARAMETER["scale_factor",0.9996],PARAMETER["false_easting",500000],PARAMETER["false_northing",0],UNIT["Meter",1]]': - gdaltest.post_reason('fail') - print(sr.ExportToWkt()) - return 'fail' + assert sr.ExportToWkt() == 'PROJCS["UTM Zone 31, Northern Hemisphere",GEOGCS["unnamed",DATUM["unknown",SPHEROID["unnamed",0,0]],PRIMEM["Greenwich",0],UNIT["degree",0.0174532925199433]],PROJECTION["Transverse_Mercator"],PARAMETER["latitude_of_origin",0],PARAMETER["central_meridian",0.01308996938995747],PARAMETER["scale_factor",0.9996],PARAMETER["false_easting",500000],PARAMETER["false_northing",0],UNIT["Meter",1]]' sr.ImportFromWkt('FOO["bar",GEOGCS[]]') - if sr.SetGeogCS(None, None, None, 0, 0, None, 0, None, 0) == 0: - gdaltest.post_reason('fail') - print(sr.ExportToWkt()) - return 'fail' - if sr.ExportToWkt() != 'FOO["bar",GEOGCS[]]': - gdaltest.post_reason('fail') - print(sr.ExportToWkt()) - return 'fail' - - return 'success' + assert sr.SetGeogCS(None, None, None, 0, 0, None, 0, None, 0) != 0, sr.ExportToWkt() + assert sr.ExportToWkt() == 'FOO["bar",GEOGCS[]]' ############################################################################### -gdaltest_list = [ - osr_basic_1, - osr_basic_2, - osr_basic_3, - osr_basic_4, - osr_basic_5, - osr_basic_6, - osr_basic_7, - osr_basic_8, - osr_basic_9, - osr_basic_10, - osr_basic_11, - osr_basic_12, - osr_basic_13, - osr_basic_14, - osr_basic_15, - osr_basic_16, - osr_basic_17, - osr_basic_18, - osr_basic_19, - osr_basic_20, - osr_basic_21, - osr_basic_22, - osr_basic_23, - osr_basic_24, - osr_basic_25, - osr_basic_setgeogcs, - None] - -if __name__ == '__main__': - - gdaltest.setup_run('osr_basic') - - gdaltest.run_tests(gdaltest_list) - - sys.exit(gdaltest.summarize()) + diff --git a/autotest/osr/osr_compd.py b/autotest/osr/osr_compd.py index 64876e1832ab..b5b1f07d972c 100755 --- a/autotest/osr/osr_compd.py +++ b/autotest/osr/osr_compd.py @@ -30,13 +30,12 @@ # DEALINGS IN THE SOFTWARE. ############################################################################### -import sys -import osr_proj4 +from osr import osr_proj4 -sys.path.append('../pymod') import gdaltest from osgeo import osr +import pytest example_compd_wkt = 'COMPD_CS["OSGB36 / British National Grid + ODN",PROJCS["OSGB 1936 / British National Grid",GEOGCS["OSGB 1936",DATUM["OSGB_1936",SPHEROID["Airy 1830",6377563.396,299.3249646,AUTHORITY["EPSG",7001]],TOWGS84[375,-111,431,0,0,0,0],AUTHORITY["EPSG",6277]],PRIMEM["Greenwich",0,AUTHORITY["EPSG",8901]],UNIT["DMSH",0.0174532925199433,AUTHORITY["EPSG",9108]],AXIS["Lat",NORTH],AXIS["Long",EAST],AUTHORITY["EPSG",4277]],PROJECTION["Transverse_Mercator"],PARAMETER["latitude_of_origin",49],PARAMETER["central_meridian",-2],PARAMETER["scale_factor",0.999601272],PARAMETER["false_easting",400000],PARAMETER["false_northing",-100000],UNIT["metre_1",1,AUTHORITY["EPSG",9001]],AXIS["E",EAST],AXIS["N",NORTH],AUTHORITY["EPSG",27700]],VERT_CS["Newlyn",VERT_DATUM["Ordnance Datum Newlyn",2005,AUTHORITY["EPSG",5101]],UNIT["metre_2",1,AUTHORITY["EPSG",9001]],AXIS["Up",UP],AUTHORITY["EPSG",5701]],AUTHORITY["EPSG",7405]]' @@ -44,26 +43,18 @@ # Test parsing and a few operations on a compound coordinate system. -def osr_compd_1(): +def test_osr_compd_1(): srs = osr.SpatialReference() srs.ImportFromWkt(example_compd_wkt) - if not srs.IsProjected(): - gdaltest.post_reason('Projected COMPD_CS not recognised as projected.') - return 'fail' + assert srs.IsProjected(), 'Projected COMPD_CS not recognised as projected.' - if srs.IsGeographic(): - gdaltest.post_reason('projected COMPD_CS misrecognised as geographic.') - return 'fail' + assert not srs.IsGeographic(), 'projected COMPD_CS misrecognised as geographic.' - if srs.IsLocal(): - gdaltest.post_reason('projected COMPD_CS misrecognised as local.') - return 'fail' + assert not srs.IsLocal(), 'projected COMPD_CS misrecognised as local.' - if not srs.IsCompound(): - gdaltest.post_reason('COMPD_CS not recognised as compound.') - return 'fail' + assert srs.IsCompound(), 'COMPD_CS not recognised as compound.' expected_proj4 = '+proj=tmerc +lat_0=49 +lon_0=-2 +k=0.999601272 +x_0=400000 +y_0=-100000 +ellps=airy +towgs84=375,-111,431,0,0,0,0 +units=m +vunits=m +no_defs ' got_proj4 = srs.ExportToProj4() @@ -71,50 +62,35 @@ def osr_compd_1(): if expected_proj4 != got_proj4: print('Got: %s' % got_proj4) print('Expected: %s' % expected_proj4) - gdaltest.post_reason('did not get expected proj.4 translation of compd_cs') - return 'fail' + pytest.fail('did not get expected proj.4 translation of compd_cs') - if srs.GetLinearUnitsName() != 'metre_1': - gdaltest.post_reason('Did not get expected linear units.') - return 'fail' + assert srs.GetLinearUnitsName() == 'metre_1', 'Did not get expected linear units.' - if srs.Validate() != 0: - gdaltest.post_reason('Validate() failed.') - return 'fail' - - return 'success' + assert srs.Validate() == 0, 'Validate() failed.' ############################################################################### # Test SetFromUserInput() -def osr_compd_2(): +def test_osr_compd_2(): srs = osr.SpatialReference() srs.SetFromUserInput(example_compd_wkt) - if srs.Validate() != 0: - gdaltest.post_reason('Does not validate') - return 'fail' - - if not srs.IsProjected(): - gdaltest.post_reason('Projected COMPD_CS not recognised as projected.') - return 'fail' + assert srs.Validate() == 0, 'Does not validate' - return 'success' + assert srs.IsProjected(), 'Projected COMPD_CS not recognised as projected.' ############################################################################### # Test expansion of compound coordinate systems from EPSG definition. -def osr_compd_3(): +def test_osr_compd_3(): srs = osr.SpatialReference() srs.ImportFromEPSG(7401) - if srs.Validate() != 0: - gdaltest.post_reason('Does not validate') - return 'fail' + assert srs.Validate() == 0, 'Does not validate' exp_wkt = """COMPD_CS["NTF (Paris) / France II + NGF Lallemand", PROJCS["NTF (Paris) / France II (deprecated)", @@ -149,27 +125,19 @@ def osr_compd_3(): AUTHORITY["EPSG","5719"]], AUTHORITY["EPSG","7401"]]""" wkt = srs.ExportToPrettyWkt() - if gdaltest.equal_srs_from_wkt(exp_wkt, wkt) == 0: - gdaltest.post_reason('did not get expected compound cs for EPSG:7401') - return 'fail' - # elif exp_wkt != wkt: - # print('warning they are equivalent, but not completely the same') - # print(wkt) - - return 'success' + assert gdaltest.equal_srs_from_wkt(exp_wkt, wkt) != 0, \ + 'did not get expected compound cs for EPSG:7401' ############################################################################### # Test expansion of GCS+VERTCS compound coordinate system. -def osr_compd_4(): +def test_osr_compd_4(): srs = osr.SpatialReference() srs.ImportFromEPSG(7400) - if srs.Validate() != 0: - gdaltest.post_reason('Does not validate') - return 'fail' + assert srs.Validate() == 0, 'Does not validate' exp_wkt = """COMPD_CS["NTF (Paris) + NGF IGN69 height", GEOGCS["NTF (Paris)", @@ -193,28 +161,20 @@ def osr_compd_4(): AUTHORITY["EPSG","7400"]]""" wkt = srs.ExportToPrettyWkt() - if gdaltest.equal_srs_from_wkt(exp_wkt, wkt) == 0: - gdaltest.post_reason('did not get expected compound cs for EPSG:7400') - return 'fail' - # elif exp_wkt != wkt: - # print('warning they are equivalent, but not completely the same') - # print(wkt) - - return 'success' + assert gdaltest.equal_srs_from_wkt(exp_wkt, wkt) != 0, \ + 'did not get expected compound cs for EPSG:7400' ############################################################################### # Test that compound coordinate systems with grid shift files are # expanded properly and converted to PROJ.4 format with the grids. -def osr_compd_5(): +def test_osr_compd_5(): srs = osr.SpatialReference() srs.SetFromUserInput('EPSG:26911+5703') - if srs.Validate() != 0: - gdaltest.post_reason('Does not validate') - return 'fail' + assert srs.Validate() == 0, 'Does not validate' exp_wkt = """COMPD_CS["NAD83 / UTM zone 11N + NAVD88 height", PROJCS["NAD83 / UTM zone 11N", @@ -251,38 +211,30 @@ def osr_compd_5(): wkt = srs.ExportToPrettyWkt() if gdaltest.equal_srs_from_wkt(exp_wkt, wkt) == 0: - return 'fail' + pytest.fail() elif exp_wkt != wkt: print('warning they are equivalent, but not completely the same') print(wkt) - if wkt.find('g2012a_conus.gtx') == -1: - gdaltest.post_reason('Did not get PROJ4_GRIDS EXTENSION node') - return 'fail' + assert wkt.find('g2012a_conus.gtx') != -1, 'Did not get PROJ4_GRIDS EXTENSION node' exp_proj4 = '+proj=utm +zone=11 +ellps=GRS80 +towgs84=0,0,0,0,0,0,0 +units=m +geoidgrids=g2012a_conus.gtx,g2012a_alaska.gtx,g2012a_guam.gtx,g2012a_hawaii.gtx,g2012a_puertorico.gtx,g2012a_samoa.gtx +vunits=m +no_defs ' proj4 = srs.ExportToProj4() - if proj4 != exp_proj4: - gdaltest.post_reason('Did not get expected proj.4 string, got:' + proj4) - return 'fail' - - return 'success' + assert proj4 == exp_proj4, ('Did not get expected proj.4 string, got:' + proj4) ############################################################################### # Test conversion from PROJ.4 to WKT including vertical units. -def osr_compd_6(): +def test_osr_compd_6(): if not osr_proj4.have_proj480(): - return 'skip' + pytest.skip() srs = osr.SpatialReference() srs.SetFromUserInput('+proj=utm +zone=11 +ellps=GRS80 +towgs84=0,0,0,0,0,0,0 +units=m +geoidgrids=g2003conus.gtx,g2003alaska.gtx,g2003h01.gtx,g2003p01.gtx +vunits=us-ft +no_defs ') - if srs.Validate() != 0: - gdaltest.post_reason('Does not validate') - return 'fail' + assert srs.Validate() == 0, 'Does not validate' exp_wkt = """COMPD_CS["UTM Zone 11, Northern Hemisphere + Unnamed Vertical Datum", PROJCS["UTM Zone 11, Northern Hemisphere", @@ -308,29 +260,22 @@ def osr_compd_6(): wkt = srs.ExportToPrettyWkt() if gdaltest.equal_srs_from_wkt(exp_wkt, wkt) == 0: - gdaltest.post_reason('fail') - return 'fail' + pytest.fail() elif exp_wkt != wkt: print('warning they are equivalent, but not completely the same') print(wkt) - if wkt.find('g2003conus.gtx') == -1: - gdaltest.post_reason('Did not get PROJ4_GRIDS EXTENSION node') - return 'fail' + assert wkt.find('g2003conus.gtx') != -1, 'Did not get PROJ4_GRIDS EXTENSION node' exp_proj4 = '+proj=utm +zone=11 +ellps=GRS80 +towgs84=0,0,0,0,0,0,0 +units=m +geoidgrids=g2003conus.gtx,g2003alaska.gtx,g2003h01.gtx,g2003p01.gtx +vunits=us-ft +no_defs ' proj4 = srs.ExportToProj4() - if proj4 != exp_proj4: - gdaltest.post_reason('Did not get expected proj.4 string, got:' + proj4) - return 'fail' - - return 'success' + assert proj4 == exp_proj4, ('Did not get expected proj.4 string, got:' + proj4) ############################################################################### # Test SetCompound() -def osr_compd_7(): +def test_osr_compd_7(): srs_horiz = osr.SpatialReference() srs_horiz.ImportFromEPSG(4326) @@ -342,9 +287,7 @@ def osr_compd_7(): srs = osr.SpatialReference() srs.SetCompoundCS('My Compound SRS', srs_horiz, srs_vert) - if srs.Validate() != 0: - gdaltest.post_reason('Does not validate') - return 'fail' + assert srs.Validate() == 0, 'Does not validate' exp_wkt = """COMPD_CS["My Compound SRS", GEOGCS["WGS 84", @@ -368,60 +311,33 @@ def osr_compd_7(): wkt = srs.ExportToPrettyWkt() if gdaltest.equal_srs_from_wkt(exp_wkt, wkt) == 0: - return 'fail' + pytest.fail() elif exp_wkt != wkt: print('warning they are equivalent, but not completely the same') print(wkt) if srs.GetTargetLinearUnits('VERT_CS') != 0.304800609601219: - gdaltest.post_reason('Didnt get expected linear units') print('%.16g' % srs.GetTargetLinearUnits('VERT_CS')) - return 'fail' + pytest.fail('Didnt get expected linear units') if srs.GetTargetLinearUnits(None) != 0.304800609601219: - gdaltest.post_reason('Didnt get expected linear units') print('%.16g' % srs.GetTargetLinearUnits(None)) - return 'fail' - - return 'success' + pytest.fail('Didnt get expected linear units') + ############################################################################### # Test ImportFromURN() -def osr_compd_8(): +def test_osr_compd_8(): srs = osr.SpatialReference() srs.SetFromUserInput('urn:ogc:def:crs,crs:EPSG::27700,crs:EPSG::5701') - if srs.Validate() != 0: - gdaltest.post_reason('Does not validate') - return 'fail' + assert srs.Validate() == 0, 'Does not validate' wkt = srs.ExportToWkt() - if wkt.find('COMPD_CS') != 0: - gdaltest.post_reason('COMPD_CS not recognised as compound.') - print(wkt) - return 'fail' - - return 'success' - - -gdaltest_list = [ - osr_compd_1, - osr_compd_2, - osr_compd_3, - osr_compd_4, - osr_compd_5, - osr_compd_6, - osr_compd_7, - osr_compd_8, - None] - -if __name__ == '__main__': + assert wkt.find('COMPD_CS') == 0, 'COMPD_CS not recognised as compound.' - gdaltest.setup_run('osr_compd') - gdaltest.run_tests(gdaltest_list) - sys.exit(gdaltest.summarize()) diff --git a/autotest/osr/osr_ct.py b/autotest/osr/osr_ct.py index 7597d8bf42ee..a7c646534a4c 100755 --- a/autotest/osr/osr_ct.py +++ b/autotest/osr/osr_ct.py @@ -31,20 +31,19 @@ # DEALINGS IN THE SOFTWARE. ############################################################################### -import sys -sys.path.append('../pymod') from osgeo import gdal from osgeo import osr from osgeo import ogr import gdaltest +import pytest ############################################################################### # Verify that we have PROJ.4 available. -def osr_ct_1(): +def test_osr_ct_1(): gdaltest.have_proj4 = 0 @@ -60,32 +59,26 @@ def osr_ct_1(): ct = osr.CoordinateTransformation(ll_srs, utm_srs) gdal.PopErrorHandler() if gdal.GetLastErrorMsg().find('Unable to load PROJ.4') != -1: - gdaltest.post_reason('PROJ.4 missing, transforms not available.') - return 'skip' + pytest.skip('PROJ.4 missing, transforms not available.') except ValueError: gdal.PopErrorHandler() if gdal.GetLastErrorMsg().find('Unable to load PROJ.4') != -1: - gdaltest.post_reason('PROJ.4 missing, transforms not available.') - return 'skip' - gdaltest.post_reason(gdal.GetLastErrorMsg()) - return 'fail' + pytest.skip('PROJ.4 missing, transforms not available.') + pytest.fail(gdal.GetLastErrorMsg()) - if ct is None or ct.this is None: - gdaltest.post_reason('Unable to create simple CoordinateTransformat.') - return 'fail' + assert not (ct is None or ct.this is None), \ + 'Unable to create simple CoordinateTransformat.' gdaltest.have_proj4 = 1 - return 'success' - ############################################################################### # Actually perform a simple LL to UTM conversion. -def osr_ct_2(): +def test_osr_ct_2(): if gdaltest.have_proj4 == 0: - return 'skip' + pytest.skip() utm_srs = osr.SpatialReference() utm_srs.SetUTM(11) @@ -97,12 +90,8 @@ def osr_ct_2(): gdaltest.ct = osr.CoordinateTransformation(ll_srs, utm_srs) result = gdaltest.ct.TransformPoint(-117.5, 32.0, 0.0) - if abs(result[0] - 452772.06) > 0.01 \ - or abs(result[1] - 3540544.89) > 0.01 \ - or abs(result[2] - 0.0) > 0.01: - gdaltest.post_reason('Wrong LL to UTM result') - return 'fail' - return 'success' + assert abs(result[0] - 452772.06) <= 0.01 and abs(result[1] - 3540544.89) <= 0.01 and abs(result[2] - 0.0) <= 0.01, \ + 'Wrong LL to UTM result' ############################################################################### # Transform an OGR geometry ... this is mostly aimed at ensuring that @@ -110,10 +99,10 @@ def osr_ct_2(): # geometry which also uses it is deleted. -def osr_ct_3(): +def test_osr_ct_3(): if gdaltest.have_proj4 == 0: - return 'skip' + pytest.skip() utm_srs = osr.SpatialReference() utm_srs.SetUTM(11) @@ -126,31 +115,26 @@ def osr_ct_3(): pnt = ogr.CreateGeometryFromWkt('POINT(-117.5 32.0)', ll_srs) result = pnt.Transform(ct) - if result != 0: - return 'fail' + assert result == 0 ll_srs = None ct = None utm_srs = None out_srs = pnt.GetSpatialReference().ExportToPrettyWkt() - if out_srs[0:6] != 'PROJCS': - gdaltest.post_reason('output srs corrupt, ref counting issue?') - return 'fail' + assert out_srs[0:6] == 'PROJCS', 'output srs corrupt, ref counting issue?' pnt = None - return 'success' - ############################################################################### # Actually perform a simple LL to UTM conversion. # Works for both OG and NG bindings -def osr_ct_4(): +def test_osr_ct_4(): if gdaltest.have_proj4 == 0: - return 'skip' + pytest.skip() utm_srs = osr.SpatialReference() utm_srs.SetUTM(11) @@ -164,23 +148,19 @@ def osr_ct_4(): result = gdaltest.ct.TransformPoints([(-117.5, 32.0, 0.0), (-117.5, 32.0)]) for i in range(2): - if abs(result[i][0] - 452772.06) > 0.01 \ - or abs(result[i][1] - 3540544.89) > 0.01 \ - or abs(result[i][2] - 0.0) > 0.01: - gdaltest.post_reason('Wrong LL to UTM result') - return 'fail' - - return 'success' + assert abs(result[i][0] - 452772.06) <= 0.01 and abs(result[i][1] - 3540544.89) <= 0.01 and abs(result[i][2] - 0.0) <= 0.01, \ + 'Wrong LL to UTM result' + ############################################################################### # Same test, but with any sequence of tuples instead of a tuple of tuple # New in NG bindings (#3020) -def osr_ct_5(): +def test_osr_ct_5(): if gdaltest.have_proj4 == 0: - return 'skip' + pytest.skip() utm_srs = osr.SpatialReference() utm_srs.SetUTM(11) @@ -194,26 +174,21 @@ def osr_ct_5(): result = gdaltest.ct.TransformPoints(((-117.5, 32.0, 0.0), (-117.5, 32.0))) for i in range(2): - if abs(result[i][0] - 452772.06) > 0.01 \ - or abs(result[i][1] - 3540544.89) > 0.01 \ - or abs(result[i][2] - 0.0) > 0.01: - gdaltest.post_reason('Wrong LL to UTM result') - return 'fail' - - return 'success' + assert abs(result[i][0] - 452772.06) <= 0.01 and abs(result[i][1] - 3540544.89) <= 0.01 and abs(result[i][2] - 0.0) <= 0.01, \ + 'Wrong LL to UTM result' + ############################################################################### # Test osr.CreateCoordinateTransformation() method -def osr_ct_6(): +def test_osr_ct_6(): if gdaltest.have_proj4 == 0: - return 'skip' + pytest.skip() ct = osr.CreateCoordinateTransformation(None, None) - if ct is not None: - return 'fail' + assert ct is None utm_srs = osr.SpatialReference() utm_srs.SetUTM(11) @@ -223,28 +198,23 @@ def osr_ct_6(): ll_srs.SetWellKnownGeogCS('WGS84') ct = osr.CreateCoordinateTransformation(ll_srs, utm_srs) - if ct is None: - return 'fail' + assert ct is not None result = ct.TransformPoints(((-117.5, 32.0, 0.0), (-117.5, 32.0))) for i in range(2): - if abs(result[i][0] - 452772.06) > 0.01 \ - or abs(result[i][1] - 3540544.89) > 0.01 \ - or abs(result[i][2] - 0.0) > 0.01: - gdaltest.post_reason('Wrong LL to UTM result') - return 'fail' - - return 'success' + assert abs(result[i][0] - 452772.06) <= 0.01 and abs(result[i][1] - 3540544.89) <= 0.01 and abs(result[i][2] - 0.0) <= 0.01, \ + 'Wrong LL to UTM result' + ############################################################################### # Actually perform a simple Pseudo Mercator to LL conversion. -def osr_ct_7(): +def test_osr_ct_7(): if gdaltest.have_proj4 == 0: - return 'skip' + pytest.skip() pm_srs = osr.SpatialReference() pm_srs.ImportFromEPSG(3857) @@ -259,36 +229,32 @@ def osr_ct_7(): if (abs(exp_x - x) > 0.00001 or abs(exp_y - y) > 0.00001 or abs(exp_z - z) > 0.00001): - gdaltest.post_reason('Wrong LL for Pseudo Mercator result') print('Got: (%f, %f, %f)' % (x, y, z)) print('Expected: (%f, %f, %f)' % (exp_x, exp_y, exp_z)) - return 'fail' + pytest.fail('Wrong LL for Pseudo Mercator result') pnt = ogr.CreateGeometryFromWkt('POINT(%g %g)' % (7000000, 7000000), pm_srs) expected_pnt = ogr.CreateGeometryFromWkt('POINT(%.10f %.10f)' % (exp_x, exp_y), ll_srs) result = pnt.Transform(gdaltest.ct) - if result != 0: - return 'fail' + assert result == 0 if (abs(expected_pnt.GetX() - pnt.GetX()) > 0.00001 or abs(expected_pnt.GetY() - pnt.GetY()) > 0.00001 or abs(expected_pnt.GetZ() - pnt.GetZ()) > 0.00001): - gdaltest.post_reason('Failed to transform from Pseudo Mercator to LL') print('Got: %s' % pnt.ExportToWkt()) print('Expected: %s' % expected_pnt.ExportToWkt()) - return 'fail' - - return 'success' + pytest.fail('Failed to transform from Pseudo Mercator to LL') + ############################################################################### # Test WebMercator -> WGS84 optimized transform -def osr_ct_8(): +def test_osr_ct_8(): if gdaltest.have_proj4 == 0: - return 'skip' + pytest.skip() src_srs = osr.SpatialReference() src_srs.ImportFromEPSG(3857) @@ -305,10 +271,9 @@ def osr_ct_8(): for i in range(2): for j in range(3): if abs(result[i][j] - expected_result[i][j]) > 1e-10: - gdaltest.post_reason('Failed to transform from Pseudo Mercator to LL') print('Got: %s' % str(result)) print('Expected: %s' % str(expected_result)) - return 'fail' + pytest.fail('Failed to transform from Pseudo Mercator to LL') pnts = [(0, 6274861.39400658), (1 + 0, 1 + 6274861.39400658)] result = ct.TransformPoints(pnts) @@ -317,45 +282,21 @@ def osr_ct_8(): for i in range(2): for j in range(3): if abs(result[i][j] - expected_result[i][j]) > 1e-10: - gdaltest.post_reason('Failed to transform from Pseudo Mercator to LL') print('Got: %s' % str(result)) print('Expected: %s' % str(expected_result)) - print(i) - print(j) - return 'fail' - - return 'success' + pytest.fail('Failed to transform from Pseudo Mercator to LL') + ############################################################################### # Cleanup -def osr_ct_cleanup(): +def test_osr_ct_cleanup(): if gdaltest.have_proj4 == 0: - return 'skip' + pytest.skip() gdaltest.ct = None - return 'success' - - -gdaltest_list = [ - osr_ct_1, - osr_ct_2, - osr_ct_3, - osr_ct_4, - osr_ct_5, - osr_ct_6, - osr_ct_7, - osr_ct_8, - osr_ct_cleanup, - None] - -if __name__ == '__main__': - - gdaltest.setup_run('osr_ct') - gdaltest.run_tests(gdaltest_list) - sys.exit(gdaltest.summarize()) diff --git a/autotest/osr/osr_ct_proj.py b/autotest/osr/osr_ct_proj.py index 46262a60ff90..ce6ef2e59424 100755 --- a/autotest/osr/osr_ct_proj.py +++ b/autotest/osr/osr_ct_proj.py @@ -31,115 +31,14 @@ ############################################################################### import os -import sys -sys.path.append('../pymod') +import pytest import gdaltest from osgeo import osr, gdal bonne = 'PROJCS["bonne",GEOGCS["GCS_WGS_1984",DATUM["D_WGS_1984",SPHEROID["WGS_1984",6378137.0,298.257223563]],PRIMEM["Greenwich",0.0],UNIT["Degree",0.0174532925199433]],PROJECTION["bonne"],PARAMETER["False_Easting",0.0],PARAMETER["False_Northing",0.0],PARAMETER["Central_Meridian",0.0],PARAMETER["Standard_Parallel_1",60.0],UNIT["Meter",1.0]]' -############################################################################### -# Class to perform the tests. - - -class ProjTest(object): - def __init__(self, src_srs, src_xyz, src_error, - dst_srs, dst_xyz, dst_error, options, requirements): - self.src_srs = src_srs - self.src_xyz = src_xyz - self.src_error = src_error - self.dst_srs = dst_srs - self.dst_xyz = dst_xyz - self.dst_error = dst_error - self.options = options - self.requirements = requirements - - def testProj(self): - - import osr_ct - osr_ct.osr_ct_1() - if gdaltest.have_proj4 == 0: - return 'skip' - - if self.requirements is not None and self.requirements[:5] == 'GRID:': - proj_lib = os.getenv('PROJ_LIB') - if proj_lib is None: - # print( 'PROJ_LIB unset, skipping test.' ) - return 'skip' - - try: - open(proj_lib + '/' + self.requirements[5:]) - except IOError: - # print( 'Did not find GRID:%s' % self.requirements[5:] ) - return 'skip' - - src = osr.SpatialReference() - if src.SetFromUserInput(self.src_srs) != 0: - gdaltest.post_reason('SetFromUserInput(%s) failed.' % self.src_srs) - return 'fail' - - dst = osr.SpatialReference() - if dst.SetFromUserInput(self.dst_srs) != 0: - gdaltest.post_reason('SetFromUserInput(%s) failed.' % self.dst_srs) - return 'fail' - - if self.requirements is not None and self.requirements[0] != 'G': - additionnal_error_str = ' Check that proj version is >= %s ' % self.requirements - else: - additionnal_error_str = '' - - try: - gdal.PushErrorHandler('CPLQuietErrorHandler') - ct = osr.CoordinateTransformation(src, dst) - gdal.PopErrorHandler() - if gdal.GetLastErrorMsg().find('Unable to load PROJ.4') != -1: - gdaltest.post_reason('PROJ.4 missing, transforms not available.') - return 'skip' - except ValueError: - gdal.PopErrorHandler() - if gdal.GetLastErrorMsg().find('Unable to load PROJ.4') != -1: - gdaltest.post_reason('PROJ.4 missing, transforms not available.') - return 'skip' - gdaltest.post_reason('failed to create coordinate transformation. %s' % gdal.GetLastErrorMsg()) - return 'fail' - except: - gdal.PopErrorHandler() - gdaltest.post_reason('failed to create coordinate transformation. %s' % gdal.GetLastErrorMsg()) - return 'fail' - - ###################################################################### - # Transform source point to destination SRS. - - result = ct.TransformPoint(self.src_xyz[0], self.src_xyz[1], self.src_xyz[2]) - - error = abs(result[0] - self.dst_xyz[0]) \ - + abs(result[1] - self.dst_xyz[1]) \ - + abs(result[2] - self.dst_xyz[2]) - - if error > self.dst_error: - gdaltest.post_reason('Dest error is %g, got (%.15g,%.15g,%.15g)%s' - % (error, result[0], result[1], result[2], additionnal_error_str)) - return 'fail' - - ###################################################################### - # Now transform back. - - ct = osr.CoordinateTransformation(dst, src) - - result = ct.TransformPoint(result[0], result[1], result[2]) - - error = abs(result[0] - self.src_xyz[0]) \ - + abs(result[1] - self.src_xyz[1]) \ - + abs(result[2] - self.src_xyz[2]) - - if error > self.src_error: - gdaltest.post_reason('Back to source error is %g.%s' % (error, additionnal_error_str)) - return 'fail' - - return 'success' - ############################################################################### # Table of transformations, inputs and expected results (with a threshold) # @@ -233,18 +132,83 @@ def testProj(self): ############################################################################### # When imported build a list of units based on the files available. -gdaltest_list = [] - -for item in transform_list: - ut = ProjTest(item[0], item[1], item[2], - item[3], item[4], item[5], - item[7], item[8]) - gdaltest_list.append((ut.testProj, item[6])) -if __name__ == '__main__': +@pytest.mark.parametrize( + 'src_srs,src_xyz,src_error,dst_srs,dst_xyz,dst_error,unit_name,options,requirements', + transform_list, + ids=[row[6] for row in transform_list] +) +def test_proj(src_srs, src_xyz, src_error, + dst_srs, dst_xyz, dst_error, unit_name, options, requirements): - gdaltest.setup_run('osr_ct_proj') + import osr_ct + osr_ct.test_osr_ct_1() + if gdaltest.have_proj4 == 0: + pytest.skip() - gdaltest.run_tests(gdaltest_list) + if requirements is not None and requirements[:5] == 'GRID:': + proj_lib = os.getenv('PROJ_LIB') + if proj_lib is None: + # print( 'PROJ_LIB unset, skipping test.' ) + pytest.skip() - sys.exit(gdaltest.summarize()) + try: + open(proj_lib + '/' + requirements[5:]) + except IOError: + # print( 'Did not find GRID:%s' % requirements[5:] ) + pytest.skip() + + src = osr.SpatialReference() + assert src.SetFromUserInput(src_srs) == 0, \ + ('SetFromUserInput(%s) failed.' % src_srs) + + dst = osr.SpatialReference() + assert dst.SetFromUserInput(dst_srs) == 0, \ + ('SetFromUserInput(%s) failed.' % dst_srs) + + if requirements is not None and requirements[0] != 'G': + additionnal_error_str = ' Check that proj version is >= %s ' % requirements + else: + additionnal_error_str = '' + + try: + gdal.PushErrorHandler('CPLQuietErrorHandler') + ct = osr.CoordinateTransformation(src, dst) + gdal.PopErrorHandler() + if gdal.GetLastErrorMsg().find('Unable to load PROJ.4') != -1: + pytest.skip('PROJ.4 missing, transforms not available.') + except ValueError: + gdal.PopErrorHandler() + if gdal.GetLastErrorMsg().find('Unable to load PROJ.4') != -1: + pytest.skip('PROJ.4 missing, transforms not available.') + pytest.fail('failed to create coordinate transformation. %s' % gdal.GetLastErrorMsg()) + except: + gdal.PopErrorHandler() + pytest.fail('failed to create coordinate transformation. %s' % gdal.GetLastErrorMsg()) + + ###################################################################### + # Transform source point to destination SRS. + + result = ct.TransformPoint(src_xyz[0], src_xyz[1], src_xyz[2]) + + error = abs(result[0] - dst_xyz[0]) \ + + abs(result[1] - dst_xyz[1]) \ + + abs(result[2] - dst_xyz[2]) + + assert error <= dst_error, \ + ('Dest error is %g, got (%.15g,%.15g,%.15g)%s' + % (error, result[0], result[1], result[2], additionnal_error_str)) + + ###################################################################### + # Now transform back. + + ct = osr.CoordinateTransformation(dst, src) + + result = ct.TransformPoint(result[0], result[1], result[2]) + + error = abs(result[0] - src_xyz[0]) \ + + abs(result[1] - src_xyz[1]) \ + + abs(result[2] - src_xyz[2]) + + assert error <= src_error, \ + ('Back to source error is %g.%s' % (error, additionnal_error_str)) diff --git a/autotest/osr/osr_epsg.py b/autotest/osr/osr_epsg.py index 706ff9d4129d..bf4c98f5a9f8 100755 --- a/autotest/osr/osr_epsg.py +++ b/autotest/osr/osr_epsg.py @@ -30,54 +30,48 @@ # DEALINGS IN THE SOFTWARE. ############################################################################### -import sys -sys.path.append('../pymod') -import gdaltest from osgeo import osr +import pytest ############################################################################### # Verify that EPSG:26591 picks up the entry from the pcs.override.csv # file with the adjusted central_meridian. -def osr_epsg_1(): +def test_osr_epsg_1(): srs = osr.SpatialReference() srs.ImportFromEPSG(26591) if abs(srs.GetProjParm('central_meridian') - -3.4523333333333) > 0.000005: - gdaltest.post_reason('Wrong central meridian, override missed?') print(srs.ExportToPrettyWkt()) - return 'fail' - - return 'success' + pytest.fail('Wrong central meridian, override missed?') + ############################################################################### # Check that EPSG:4312 lookup has the towgs84 values set properly # from gcs.override.csv. -def osr_epsg_2(): +def test_osr_epsg_2(): srs = osr.SpatialReference() srs.ImportFromEPSG(4312) if abs(float(srs.GetAttrValue('TOWGS84', 6)) - 2.4232) > 0.0005: - gdaltest.post_reason('Wrong TOWGS84, override missed?') print(srs.ExportToPrettyWkt()) - return 'fail' - - return 'success' + pytest.fail('Wrong TOWGS84, override missed?') + ############################################################################### # Check that various EPSG lookups based on Pulvoko 1942 have the # towgs84 values set properly (#3579) -def osr_epsg_3(): +def test_osr_epsg_3(): for epsg in [3120, 2172, 2173, 2174, 2175, 3333, 3334, 3335, 3329, 3330, 3331, 3332, 3328, 4179]: srs = osr.SpatialReference() @@ -88,129 +82,92 @@ def osr_epsg_3(): for i in range(6): if abs(float(srs.GetAttrValue('TOWGS84', i)) - expected_towgs84[i]) > 0.0005: - gdaltest.post_reason('For EPSG:%d. Wrong TOWGS84, override missed?' % epsg) print(srs.ExportToPrettyWkt()) - return 'fail' - - return 'success' + pytest.fail('For EPSG:%d. Wrong TOWGS84, override missed?' % epsg) + ############################################################################### # Check that EPSG:4326 is *not* considered as lat/long (#3813) -def osr_epsg_4(): +def test_osr_epsg_4(): srs = osr.SpatialReference() srs.ImportFromEPSG(4326) - if srs.EPSGTreatsAsLatLong(): - gdaltest.post_reason('not supposed to be treated as lat/long') - return 'fail' - - if srs.ExportToWkt().find('AXIS') != -1: - gdaltest.post_reason('should not have AXIS node') - return 'fail' + assert not srs.EPSGTreatsAsLatLong(), 'not supposed to be treated as lat/long' - return 'success' + assert srs.ExportToWkt().find('AXIS') == -1, 'should not have AXIS node' ############################################################################### # Check that EPSGA:4326 is considered as lat/long -def osr_epsg_5(): +def test_osr_epsg_5(): srs = osr.SpatialReference() srs.ImportFromEPSGA(4326) - if not srs.EPSGTreatsAsLatLong(): - gdaltest.post_reason('supposed to be treated as lat/long') - return 'fail' + assert srs.EPSGTreatsAsLatLong(), 'supposed to be treated as lat/long' - if srs.ExportToWkt().find('AXIS') == -1: - gdaltest.post_reason('should have AXIS node') - return 'fail' - - return 'success' + assert srs.ExportToWkt().find('AXIS') != -1, 'should have AXIS node' ############################################################################### # Test datum shift for OSGB 36 -def osr_epsg_6(): +def test_osr_epsg_6(): srs = osr.SpatialReference() srs.ImportFromEPSG(4277) - if srs.ExportToWkt().find('TOWGS84[446.448,-125.157,542.06,0.15,0.247,0.842,-20.489]') == -1: - gdaltest.post_reason('did not get expected TOWGS84') - print(srs.ExportToWkt()) - return 'fail' - - return 'success' + assert srs.ExportToWkt().find('TOWGS84[446.448,-125.157,542.06,0.15,0.247,0.842,-20.489]') != -1, \ + 'did not get expected TOWGS84' ############################################################################### # Check that EPSG:2193 is *not* considered as N/E -def osr_epsg_7(): +def test_osr_epsg_7(): srs = osr.SpatialReference() srs.ImportFromEPSG(2193) - if srs.EPSGTreatsAsNorthingEasting(): - gdaltest.post_reason('not supposed to be treated as n/e') - return 'fail' + assert not srs.EPSGTreatsAsNorthingEasting(), 'not supposed to be treated as n/e' - if srs.ExportToWkt().find('AXIS') != -1: - gdaltest.post_reason('should not have AXIS node') - return 'fail' - - return 'success' + assert srs.ExportToWkt().find('AXIS') == -1, 'should not have AXIS node' ############################################################################### # Check that EPSGA:2193 is considered as N/E -def osr_epsg_8(): +def test_osr_epsg_8(): srs = osr.SpatialReference() srs.ImportFromEPSGA(2193) - if not srs.EPSGTreatsAsNorthingEasting(): - gdaltest.post_reason('supposed to be treated as n/e') - return 'fail' - - if srs.ExportToWkt().find('AXIS') == -1: - gdaltest.post_reason('should have AXIS node') - return 'fail' + assert srs.EPSGTreatsAsNorthingEasting(), 'supposed to be treated as n/e' - return 'success' + assert srs.ExportToWkt().find('AXIS') != -1, 'should have AXIS node' ############################################################################### # Check EPSG:3857 -def osr_epsg_9(): +def test_osr_epsg_9(): srs = osr.SpatialReference() srs.ImportFromEPSG(3857) - if srs.ExportToWkt() != 'PROJCS["WGS 84 / Pseudo-Mercator",GEOGCS["WGS 84",DATUM["WGS_1984",SPHEROID["WGS 84",6378137,298.257223563,AUTHORITY["EPSG","7030"]],AUTHORITY["EPSG","6326"]],PRIMEM["Greenwich",0,AUTHORITY["EPSG","8901"]],UNIT["degree",0.0174532925199433,AUTHORITY["EPSG","9122"]],AUTHORITY["EPSG","4326"]],PROJECTION["Mercator_1SP"],PARAMETER["central_meridian",0],PARAMETER["scale_factor",1],PARAMETER["false_easting",0],PARAMETER["false_northing",0],UNIT["metre",1,AUTHORITY["EPSG","9001"]],AXIS["X",EAST],AXIS["Y",NORTH],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"],AUTHORITY["EPSG","3857"]]': - gdaltest.post_reason('fail') - print(srs.ExportToWkt()) - return 'fail' + assert srs.ExportToWkt() == 'PROJCS["WGS 84 / Pseudo-Mercator",GEOGCS["WGS 84",DATUM["WGS_1984",SPHEROID["WGS 84",6378137,298.257223563,AUTHORITY["EPSG","7030"]],AUTHORITY["EPSG","6326"]],PRIMEM["Greenwich",0,AUTHORITY["EPSG","8901"]],UNIT["degree",0.0174532925199433,AUTHORITY["EPSG","9122"]],AUTHORITY["EPSG","4326"]],PROJECTION["Mercator_1SP"],PARAMETER["central_meridian",0],PARAMETER["scale_factor",1],PARAMETER["false_easting",0],PARAMETER["false_northing",0],UNIT["metre",1,AUTHORITY["EPSG","9001"]],AXIS["X",EAST],AXIS["Y",NORTH],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"],AUTHORITY["EPSG","3857"]]' - if srs.Validate() != 0: - gdaltest.post_reason('Does not validate') - return 'fail' - - return 'success' + assert srs.Validate() == 0, 'Does not validate' ############################################################################### # Test AutoIdentifyEPSG() on Polar Stereographic -def osr_epsg_10(): +def test_osr_epsg_10(): srs = osr.SpatialReference() srs.SetFromUserInput("""PROJCS["PS WGS84", @@ -231,20 +188,13 @@ def osr_epsg_10(): UNIT["metre",1, AUTHORITY["EPSG","9001"]]]""") - if srs.AutoIdentifyEPSG() != 0: - gdaltest.post_reason('fail') - return 'fail' + assert srs.AutoIdentifyEPSG() == 0 - if srs.GetAuthorityCode(None) != '3031': - gdaltest.post_reason('fail') - print(srs.ExportToWkt()) - return 'fail' + assert srs.GetAuthorityCode(None) == '3031', srs.ExportToWkt() srs_ref = osr.SpatialReference() srs_ref.ImportFromEPSG(3031) - if srs.IsSame(srs_ref) == 0: - gdaltest.post_reason('fail') - return 'fail' + assert srs.IsSame(srs_ref) != 0 srs = osr.SpatialReference() srs.SetFromUserInput("""PROJCS["PS WGS84", @@ -265,45 +215,32 @@ def osr_epsg_10(): UNIT["metre",1, AUTHORITY["EPSG","9001"]]]""") - if srs.AutoIdentifyEPSG() != 0: - gdaltest.post_reason('fail') - return 'fail' + assert srs.AutoIdentifyEPSG() == 0 - if srs.GetAuthorityCode(None) != '3995': - gdaltest.post_reason('fail') - print(srs.ExportToWkt()) - return 'fail' + assert srs.GetAuthorityCode(None) == '3995', srs.ExportToWkt() srs_ref = osr.SpatialReference() srs_ref.ImportFromEPSG(3995) - if srs.IsSame(srs_ref) == 0: - gdaltest.post_reason('fail') - return 'fail' - - return 'success' + assert srs.IsSame(srs_ref) != 0 ############################################################################### # Test datum shift for EPSG:2065 (PCS based override) -def osr_epsg_11(): +def test_osr_epsg_11(): srs = osr.SpatialReference() srs.ImportFromEPSG(2065) - if srs.ExportToWkt().find('TOWGS84[570.8,85.7,462.8,4.998,1.587,5.261,3.56]') == -1: - gdaltest.post_reason('did not get expected TOWGS84') - print(srs.ExportToWkt()) - return 'fail' - - return 'success' + assert srs.ExportToWkt().find('TOWGS84[570.8,85.7,462.8,4.998,1.587,5.261,3.56]') != -1, \ + 'did not get expected TOWGS84' ############################################################################### # Test IsSame() on SRS that differs only by their PROJ4 EXTENSION (besides # different EPSG codes) -def osr_epsg_12(): +def test_osr_epsg_12(): sr1 = osr.SpatialReference() sr1.ImportFromEPSG(3857) @@ -311,15 +248,13 @@ def osr_epsg_12(): sr2 = osr.SpatialReference() sr2.ImportFromEPSG(3395) - if sr1.IsSame(sr2): - return 'fail' - return 'success' + assert not sr1.IsSame(sr2) ############################################################################### # Test FindMatches() -def osr_epsg_13(): +def test_osr_epsg_13(): # One exact match (and test PROJCS) sr = osr.SpatialReference() @@ -327,13 +262,8 @@ def osr_epsg_13(): sr.MorphToESRI() sr.MorphFromESRI() matches = sr.FindMatches() - if len(matches) != 1 or matches[0][1] != 100: - gdaltest.post_reason('fail') - print(matches) - return 'fail' - if matches[0][0].IsSame(sr) == 0: - gdaltest.post_reason('fail') - return 'fail' + assert len(matches) == 1 and matches[0][1] == 100 + assert matches[0][0].IsSame(sr) != 0 # Two matches (and test GEOGCS) sr.SetFromUserInput("""GEOGCS["myLKS94", @@ -343,18 +273,9 @@ def osr_epsg_13(): PRIMEM["Greenwich",0], UNIT["degree",0.0174532925199433]]""") matches = sr.FindMatches() - if len(matches) != 2: - gdaltest.post_reason('fail') - print(matches) - return 'fail' - if matches[0][0].GetAuthorityCode(None) != '4126' or matches[0][1] != 90: - gdaltest.post_reason('fail') - print(matches) - return 'fail' - if matches[1][0].GetAuthorityCode(None) != '4669' or matches[1][1] != 90: - gdaltest.post_reason('fail') - print(matches) - return 'fail' + assert len(matches) == 2 + assert matches[0][0].GetAuthorityCode(None) == '4126' and matches[0][1] == 90 + assert matches[1][0].GetAuthorityCode(None) == '4669' and matches[1][1] == 90 # Zero match sr.SetFromUserInput("""GEOGCS["myGEOGCS", @@ -364,10 +285,7 @@ def osr_epsg_13(): UNIT["degree",0.0174532925199433]] """) matches = sr.FindMatches() - if matches: - gdaltest.post_reason('fail') - print(matches) - return 'fail' + assert not matches # One single match, but not similar according to IsSame() sr = osr.SpatialReference() @@ -392,13 +310,8 @@ def osr_epsg_13(): AUTHORITY["EPSG","9001"]]] """) matches = sr.FindMatches() - if len(matches) != 1 or matches[0][1] != 50: - gdaltest.post_reason('fail') - print(matches) - return 'fail' - if matches[0][0].IsSame(sr) == 1: - gdaltest.post_reason('fail') - return 'fail' + assert len(matches) == 1 and matches[0][1] == 50 + assert matches[0][0].IsSame(sr) != 1 # WKT has EPSG code but the definition doesn't match with the official # one (namely linear units are different) @@ -430,65 +343,28 @@ def osr_epsg_13(): AUTHORITY["EPSG","32122"]] """) matches = sr.FindMatches() - if len(matches) != 1 or matches[0][1] != 50: - gdaltest.post_reason('fail') - print(matches) - return 'fail' - if matches[0][0].IsSame(sr) == 1: - gdaltest.post_reason('fail') - return 'fail' - - return 'success' + assert len(matches) == 1 and matches[0][1] == 50 + assert matches[0][0].IsSame(sr) != 1 ############################################################################### -def osr_epsg_gcs_deprecated(): +def test_osr_epsg_gcs_deprecated(): sr = osr.SpatialReference() sr.ImportFromEPSG(4268) - if sr.ExportToWkt().find('NAD27 Michigan (deprecated)') < 0: - print(sr.ExportToWkt()) - return 'fail' - return 'success' + assert sr.ExportToWkt().find('NAD27 Michigan (deprecated)') >= 0 ############################################################################### -def osr_epsg_geoccs_deprecated(): +def test_osr_epsg_geoccs_deprecated(): sr = osr.SpatialReference() sr.ImportFromEPSG(4346) - if sr.ExportToWkt().find('ETRS89 (geocentric) (deprecated)') < 0: - print(sr.ExportToWkt()) - return 'fail' - return 'success' + assert sr.ExportToWkt().find('ETRS89 (geocentric) (deprecated)') >= 0 ############################################################################### -gdaltest_list = [ - osr_epsg_1, - osr_epsg_2, - osr_epsg_3, - osr_epsg_4, - osr_epsg_5, - osr_epsg_6, - osr_epsg_7, - osr_epsg_8, - osr_epsg_9, - osr_epsg_10, - osr_epsg_11, - osr_epsg_12, - osr_epsg_13, - osr_epsg_gcs_deprecated, - osr_epsg_geoccs_deprecated, - None] - -if __name__ == '__main__': - - gdaltest.setup_run('osr_epsg') - - gdaltest.run_tests(gdaltest_list) - sys.exit(gdaltest.summarize()) diff --git a/autotest/osr/osr_erm.py b/autotest/osr/osr_erm.py index ed4d504c659f..c5f52f20387b 100755 --- a/autotest/osr/osr_erm.py +++ b/autotest/osr/osr_erm.py @@ -25,11 +25,8 @@ # Boston, MA 02111-1307, USA. ############################################################################### -import sys -sys.path.append('../pymod') -import gdaltest from osgeo import osr ############################################################################### @@ -38,54 +35,32 @@ # -def osr_erm_1(): +def test_osr_erm_1(): for sphere_datum in ['SPHERE', 'SPHERE2', 'USSPHERE']: srs = osr.SpatialReference() srs.ImportFromERM('MRWORLD', sphere_datum, 'METRE') - if srs.GetInvFlattening() != 0.0 \ - or abs(srs.GetSemiMajor() - srs.GetSemiMinor() > 0.0000005): - gdaltest.post_reason('Wrong ERMapper spherical datum parameters (bug #3787). Be sure your "ecw_cs.wkt" is from 20890 revision or newer.') - return 'fail' - - return 'success' + assert srs.GetInvFlattening() == 0.0 and not abs(srs.GetSemiMajor() - srs.GetSemiMinor() > 0.0000005), \ + 'Wrong ERMapper spherical datum parameters (bug #3787). Be sure your "ecw_cs.wkt" is from 20890 revision or newer.' + ############################################################################### # Confirm that unsupported SRSes will be translated from/to EPSG:n # format (#3955) # -def osr_erm_2(): +def test_osr_erm_2(): srs = osr.SpatialReference() - if srs.ImportFromERM('EPSG:3395', 'EPSG:3395', 'METRE') != 0 \ - or not srs.IsProjected(): - gdaltest.post_reason('EPSG:n import failed.') - return 'fail' + assert srs.ImportFromERM('EPSG:3395', 'EPSG:3395', 'METRE') == 0 and srs.IsProjected(), \ + 'EPSG:n import failed.' srs2 = osr.SpatialReference() srs2.SetFromUserInput('EPSG:3395') - if not srs2.IsSame(srs): - gdaltest.post_reason('EPSG:n import does not match.') - print(srs) - print(srs2) - return 'fail' - - return 'success' - - -gdaltest_list = [ - osr_erm_1, - osr_erm_2, - None] - -if __name__ == '__main__': + assert srs2.IsSame(srs), 'EPSG:n import does not match.' - gdaltest.setup_run('osr_erm') - gdaltest.run_tests(gdaltest_list) - sys.exit(gdaltest.summarize()) diff --git a/autotest/osr/osr_esri.py b/autotest/osr/osr_esri.py index 488cd0d885ac..9f2b8f7eafa9 100755 --- a/autotest/osr/osr_esri.py +++ b/autotest/osr/osr_esri.py @@ -37,12 +37,12 @@ import os import sys -sys.path.append('../pymod') import gdaltest from osgeo import gdal from osgeo import ogr from osgeo import osr +import pytest ############################################################################### # This test verifies that morphToESRI() translates idiosyncratic datum names @@ -50,145 +50,121 @@ # gdal_datum.csv file. -def osr_esri_1(): +def test_osr_esri_1(): srs = osr.SpatialReference() srs.ImportFromEPSG(4202) - if srs.GetAttrValue('DATUM') != 'Australian_Geodetic_Datum_1966': - gdaltest.post_reason('Got wrong DATUM name (%s) after EPSG import.' % + assert srs.GetAttrValue('DATUM') == 'Australian_Geodetic_Datum_1966', \ + ('Got wrong DATUM name (%s) after EPSG import.' % srs.GetAttrValue('DATUM')) - return 'fail' srs.MorphToESRI() - if srs.GetAttrValue('DATUM') != 'D_Australian_1966': - gdaltest.post_reason('Got wrong DATUM name (%s) after ESRI morph.' % + assert srs.GetAttrValue('DATUM') == 'D_Australian_1966', \ + ('Got wrong DATUM name (%s) after ESRI morph.' % srs.GetAttrValue('DATUM')) - return 'fail' srs.MorphFromESRI() - if srs.GetAttrValue('DATUM') != 'Australian_Geodetic_Datum_1966': - gdaltest.post_reason('Got wrong DATUM name (%s) after ESRI unmorph.' % + assert srs.GetAttrValue('DATUM') == 'Australian_Geodetic_Datum_1966', \ + ('Got wrong DATUM name (%s) after ESRI unmorph.' % srs.GetAttrValue('DATUM')) - return 'fail' - - return 'success' ############################################################################### # Verify that exact correct form of UTM names is established when # translating certain GEOGCSes to ESRI format. -def osr_esri_2(): +def test_osr_esri_2(): srs = osr.SpatialReference() srs.SetFromUserInput('+proj=utm +zone=11 +south +datum=WGS84') srs.MorphToESRI() - if srs.GetAttrValue('GEOGCS') != 'GCS_WGS_1984': - gdaltest.post_reason('Got wrong GEOGCS name (%s) after ESRI morph.' % + assert srs.GetAttrValue('GEOGCS') == 'GCS_WGS_1984', \ + ('Got wrong GEOGCS name (%s) after ESRI morph.' % srs.GetAttrValue('GEOGCS')) - return 'fail' - if srs.GetAttrValue('PROJCS') != 'WGS_1984_UTM_Zone_11S': - gdaltest.post_reason('Got wrong PROJCS name (%s) after ESRI morph.' % + assert srs.GetAttrValue('PROJCS') == 'WGS_1984_UTM_Zone_11S', \ + ('Got wrong PROJCS name (%s) after ESRI morph.' % srs.GetAttrValue('PROJCS')) - return 'fail' - - return 'success' ############################################################################### # Verify that Unnamed is changed to Unknown in morphToESRI(). -def osr_esri_3(): +def test_osr_esri_3(): srs = osr.SpatialReference() srs.SetFromUserInput('+proj=mill +datum=WGS84') srs.MorphToESRI() - if srs.GetAttrValue('PROJCS') != 'Miller_Cylindrical': - gdaltest.post_reason('Got wrong PROJCS name (%s) after ESRI morph.' % + assert srs.GetAttrValue('PROJCS') == 'Miller_Cylindrical', \ + ('Got wrong PROJCS name (%s) after ESRI morph.' % srs.GetAttrValue('PROJCS')) - return 'fail' - - return 'success' ############################################################################### # Verify Polar Stereographic translations work properly OGR to ESRI. -def osr_esri_4(): +def test_osr_esri_4(): srs = osr.SpatialReference() srs.SetFromUserInput('PROJCS["PS Test",GEOGCS["WGS 84",DATUM["WGS_1984",SPHEROID["WGS 84",6378137,298.257223563]],PRIMEM["Greenwich",0],UNIT["degree",0.0174532925199433]],PROJECTION["Polar_Stereographic"],PARAMETER["latitude_of_origin",-80.2333],PARAMETER["central_meridian",171],PARAMETER["scale_factor",0.9999],PARAMETER["false_easting",0],PARAMETER["false_northing",0],UNIT["metre",1]]') srs.MorphToESRI() - if srs.GetAttrValue('PROJECTION') != 'Stereographic_South_Pole': - gdaltest.post_reason('Got wrong PROJECTION name (%s) after ESRI morph.' % + assert srs.GetAttrValue('PROJECTION') == 'Stereographic_South_Pole', \ + ('Got wrong PROJECTION name (%s) after ESRI morph.' % srs.GetAttrValue('PROJECTION')) - return 'fail' - if srs.GetProjParm('standard_parallel_1') != -80.2333: - gdaltest.post_reason('Got wrong parameter value (%g) after ESRI morph.' % + assert srs.GetProjParm('standard_parallel_1') == -80.2333, \ + ('Got wrong parameter value (%g) after ESRI morph.' % srs.GetProjParm('standard_parallel_1')) - return 'fail' - - return 'success' ############################################################################### # Verify Polar Stereographic translations work properly ESRI to OGR. -def osr_esri_5(): +def test_osr_esri_5(): srs = osr.SpatialReference() srs.SetFromUserInput('PROJCS["PS Test",GEOGCS["GCS_WGS_1984",DATUM["D_WGS_1984",SPHEROID["WGS_1984",6378137,298.257223563]],PRIMEM["Greenwich",0],UNIT["Degree",0.017453292519943295]],PROJECTION["Stereographic_South_Pole"],PARAMETER["standard_parallel_1",-80.2333],PARAMETER["central_meridian",171],PARAMETER["scale_factor",0.9999],PARAMETER["false_easting",0],PARAMETER["false_northing",0],UNIT["Meter",1]]') srs.MorphFromESRI() - if srs.GetAttrValue('PROJECTION') != 'Polar_Stereographic': - gdaltest.post_reason('Got wrong PROJECTION name (%s) after ESRI morph.' % + assert srs.GetAttrValue('PROJECTION') == 'Polar_Stereographic', \ + ('Got wrong PROJECTION name (%s) after ESRI morph.' % srs.GetAttrValue('PROJECTION')) - return 'fail' - if srs.GetProjParm('latitude_of_origin') != -80.2333: - gdaltest.post_reason('Got wrong parameter value (%g) after ESRI morph.' % + assert srs.GetProjParm('latitude_of_origin') == -80.2333, \ + ('Got wrong parameter value (%g) after ESRI morph.' % srs.GetProjParm('latitude_of_origin')) - return 'fail' - - return 'success' ############################################################################### # Verify Lambert 2SP with a 1.0 scale factor still gets translated to 2SP # per bug 187. -def osr_esri_6(): +def test_osr_esri_6(): srs = osr.SpatialReference() srs.SetFromUserInput('PROJCS["Texas Centric Mapping System/Lambert Conformal",GEOGCS["GCS_North_American_1983",DATUM["D_North_American_1983",SPHEROID["GRS_1980",6378137.0,298.257222101]],PRIMEM["Greenwich",0.0],UNIT["Degree",0.0174532925199433]],PROJECTION["Lambert_Conformal_Conic"],PARAMETER["False_Easting",1500000.0],PARAMETER["False_Northing",5000000.0],PARAMETER["Central_Meridian",-100.0],PARAMETER["Standard_Parallel_1",27.5],PARAMETER["Standard_Parallel_2",35.0],PARAMETER["Scale_Factor",1.0],PARAMETER["Latitude_Of_Origin",18.0],UNIT["Meter",1.0]]') srs.MorphFromESRI() - if srs.GetAttrValue('PROJECTION') != 'Lambert_Conformal_Conic_2SP': - gdaltest.post_reason( - 'Got wrong PROJECTION name (%s) after ESRI morph, expected 2SP' % + assert srs.GetAttrValue('PROJECTION') == 'Lambert_Conformal_Conic_2SP', \ + ('Got wrong PROJECTION name (%s) after ESRI morph, expected 2SP' % srs.GetAttrValue('PROJECTION')) - return 'fail' - - return 'success' ############################################################################### # Verify that FEET is treated as US survey feet per bug #1533. -def osr_esri_7(): +def test_osr_esri_7(): prj = ['Projection STATEPLANE', 'Fipszone 903', @@ -230,16 +206,14 @@ def osr_esri_7(): if not srs_prj.IsSame(srs_wkt): print('got: ', srs_prj.ExportToPrettyWkt()) - gdaltest.post_reason('old style ESRI projection imported wrong, perhaps linear units?') - return 'fail' - - return 'success' + pytest.fail('old style ESRI projection imported wrong, perhaps linear units?') + ############################################################################### # Verify that handling of numerically specified units (see bug #1533) -def osr_esri_8(): +def test_osr_esri_8(): prj = ['Projection STATEPLANE', 'Fipszone 903', @@ -278,17 +252,14 @@ def osr_esri_8(): srs_wkt = osr.SpatialReference(wkt=wkt) - if not srs_prj.IsSame(srs_wkt): - gdaltest.post_reason('old style ESRI projection imported wrong, perhaps linear units?') - return 'fail' - - return 'success' + assert srs_prj.IsSame(srs_wkt), \ + 'old style ESRI projection imported wrong, perhaps linear units?' ############################################################################### # Verify Equidistant Conic handling. -def osr_esri_9(): +def test_osr_esri_9(): srs = osr.SpatialReference() srs.SetFromUserInput('PROJCS["edc",GEOGCS["GCS_North_American_1983",DATUM["D_North_American_1983",SPHEROID["GRS_1980",6378137.0,298.257222101]],PRIMEM["Greenwich",0.0],UNIT["Degree",0.0174532925199433]],PROJECTION["Equidistant_Conic"],PARAMETER["False_Easting",0.0],PARAMETER["False_Northing",0.0],PARAMETER["Central_Meridian",-96.0],PARAMETER["Standard_Parallel_1",29.5],PARAMETER["Standard_Parallel_2",45.5],PARAMETER["Latitude_Of_Origin",37.5],UNIT["Meter",1.0]]') @@ -301,8 +272,7 @@ def osr_esri_9(): print('') print('Got: ', wkt) print('Expected: ', expected) - gdaltest.post_reason('Did not get expected Equidistant Conic SRS after morphFromESRI') - return 'fail' + pytest.fail('Did not get expected Equidistant Conic SRS after morphFromESRI') expected = 'PROJCS["edc",GEOGCS["GCS_North_American_1983",DATUM["D_North_American_1983",SPHEROID["GRS_1980",6378137.0,298.257222101]],PRIMEM["Greenwich",0.0],UNIT["Degree",0.017453292519943295]],PROJECTION["Equidistant_Conic"],PARAMETER["False_Easting",0.0],PARAMETER["False_Northing",0.0],PARAMETER["central_meridian",-96.0],PARAMETER["Standard_Parallel_1",29.5],PARAMETER["Standard_Parallel_2",45.5],PARAMETER["latitude_of_origin",37.5],UNIT["Meter",1.0]]' @@ -312,16 +282,14 @@ def osr_esri_9(): print('') print('Got: ', wkt) print('Expected: ', expected) - gdaltest.post_reason('Did not get expected Equidistant Conic SRS after morphToESRI') - return 'fail' - - return 'success' + pytest.fail('Did not get expected Equidistant Conic SRS after morphToESRI') + ############################################################################### # Verify Plate_Carree handling. -def osr_esri_10(): +def test_osr_esri_10(): srs = osr.SpatialReference() srs.SetFromUserInput('PROJCS["Sphere_Plate_Carree",GEOGCS["GCS_Sphere",DATUM["D_Sphere",SPHEROID["Sphere",6371000.0,0.0]],PRIMEM["Greenwich",0.0],UNIT["Degree",0.0174532925199433]],PROJECTION["Plate_Carree"],PARAMETER["False_Easting",0.0],PARAMETER["False_Northing",0.0],PARAMETER["Central_Meridian",0.0],UNIT["Meter",1.0]]') @@ -334,8 +302,7 @@ def osr_esri_10(): print('') print('Got: ', wkt) print('Expected: ', expected) - gdaltest.post_reason('Did not get expected Equirectangular SRS after morphFromESRI') - return 'fail' + pytest.fail('Did not get expected Equirectangular SRS after morphFromESRI') expected = 'PROJCS["Sphere_Plate_Carree",GEOGCS["GCS_Sphere",DATUM["D_Sphere",SPHEROID["Sphere",6371000.0,0.0]],PRIMEM["Greenwich",0.0],UNIT["Degree",0.017453292519943295]],PROJECTION["Equidistant_Cylindrical"],PARAMETER["False_Easting",0.0],PARAMETER["False_Northing",0.0],PARAMETER["Central_Meridian",0.0],UNIT["Meter",1.0]]' @@ -345,16 +312,14 @@ def osr_esri_10(): print('') print('Got: ', wkt) print('Expected: ', expected) - gdaltest.post_reason('Did not get expected Equidistant_Cylindrical SRS after morphToESRI') - return 'fail' - - return 'success' + pytest.fail('Did not get expected Equidistant_Cylindrical SRS after morphToESRI') + ############################################################################### # Verify arc/info style TM handling. -def osr_esri_11(): +def test_osr_esri_11(): srs = osr.SpatialReference() srs.ImportFromESRI(['Projection TRANSVERSE', @@ -379,82 +344,70 @@ def osr_esri_11(): print('') print('Got: ', wkt) print('Expected: ', expected) - gdaltest.post_reason('Did not get expected TM SRS after morphFromESRI') - return 'fail' - - return 'success' + pytest.fail('Did not get expected TM SRS after morphFromESRI') + ############################################################################### # Test automatic morphing of ESRI-style LCC WKT prefixed with 'ESRI::' -def osr_esri_12(): +def test_osr_esri_12(): srs = osr.SpatialReference() srs.SetFromUserInput('ESRI::PROJCS["Lambert Conformal Conic",GEOGCS["grs80",DATUM["D_North_American_1983",SPHEROID["Geodetic_Reference_System_1980",6378137,298.257222101]],PRIMEM["Greenwich",0],UNIT["Degree",0.017453292519943295]],PROJECTION["Lambert_Conformal_Conic"],PARAMETER["standard_parallel_1",34.33333333333334],PARAMETER["standard_parallel_2",36.16666666666666],PARAMETER["latitude_of_origin",33.75],PARAMETER["central_meridian",-79],PARAMETER["false_easting",609601.22],PARAMETER["false_northing",0],UNIT["Meter",1]]') # No MorphFromESRI() is required - if srs.GetAttrValue('PROJECTION') != 'Lambert_Conformal_Conic_2SP': - gdaltest.post_reason('Got wrong PROJECTION name (%s) after ESRI morph.' % + assert srs.GetAttrValue('PROJECTION') == 'Lambert_Conformal_Conic_2SP', \ + ('Got wrong PROJECTION name (%s) after ESRI morph.' % srs.GetAttrValue('PROJECTION')) - return 'fail' - if abs(srs.GetProjParm('standard_parallel_1') - 34.333333333) > 0.00001: - gdaltest.post_reason('Got wrong parameter value (%g) after ESRI morph.' % + assert abs(srs.GetProjParm('standard_parallel_1') - 34.333333333) <= 0.00001, \ + ('Got wrong parameter value (%g) after ESRI morph.' % srs.GetProjParm('standard_parallel_1')) - return 'fail' if srs.GetAttrValue('DATUM') != 'North_American_Datum_1983': gdaltest.post_reason('Got wrong DATUM name (%s) after ESRI morph.' % srs.GetAttrValue('DATUM')) - if srs.GetAttrValue('UNIT') != 'Meter': - gdaltest.post_reason('Got wrong UNIT name (%s) after ESRI morph.' % + assert srs.GetAttrValue('UNIT') == 'Meter', \ + ('Got wrong UNIT name (%s) after ESRI morph.' % srs.GetAttrValue('UNIT')) - return 'fail' - - return 'success' ############################################################################### # Test automatic morphing of ESRI-style LCC WKT prefixed with 'ESRI::' # but read directly from file. -def osr_esri_13(): +def test_osr_esri_13(): srs = osr.SpatialReference() srs.SetFromUserInput('data/lcc_esri.prj') # No MorphFromESRI() is required - if srs.GetAttrValue('PROJECTION') != 'Lambert_Conformal_Conic_2SP': - gdaltest.post_reason('Got wrong PROJECTION name (%s) after ESRI morph.' % + assert srs.GetAttrValue('PROJECTION') == 'Lambert_Conformal_Conic_2SP', \ + ('Got wrong PROJECTION name (%s) after ESRI morph.' % srs.GetAttrValue('PROJECTION')) - return 'fail' - if abs(srs.GetProjParm('standard_parallel_1') - 34.333333333) > 0.00001: - gdaltest.post_reason('Got wrong parameter value (%g) after ESRI morph.' % + assert abs(srs.GetProjParm('standard_parallel_1') - 34.333333333) <= 0.00001, \ + ('Got wrong parameter value (%g) after ESRI morph.' % srs.GetProjParm('standard_parallel_1')) - return 'fail' if srs.GetAttrValue('DATUM') != 'North_American_Datum_1983': gdaltest.post_reason('Got wrong DATUM name (%s) after ESRI morph.' % srs.GetAttrValue('DATUM')) - if srs.GetAttrValue('UNIT') != 'Meter': - gdaltest.post_reason('Got wrong UNIT name (%s) after ESRI morph.' % + assert srs.GetAttrValue('UNIT') == 'Meter', \ + ('Got wrong UNIT name (%s) after ESRI morph.' % srs.GetAttrValue('UNIT')) - return 'fail' - - return 'success' ############################################################################### # Verify that state plane epsg authority values are not applied if the # linear units are changed for old style .prj files (bug #1697) -def osr_esri_14(): +def test_osr_esri_14(): srs = osr.SpatialReference() srs.ImportFromESRI(['PROJECTION STATEPLANE', @@ -462,10 +415,8 @@ def osr_esri_14(): 'FIPSZONE 2600', 'DATUM NAD83', 'PARAMETERS']) - if srs.GetAuthorityCode('PROJCS') is not None: - print(srs.GetAuthorityCode('PROJCS')) - gdaltest.post_reason('Get epsg authority code inappropriately.') - return 'fail' + assert srs.GetAuthorityCode('PROJCS') is None, \ + 'Get epsg authority code inappropriately.' srs = osr.SpatialReference() srs.ImportFromESRI(['PROJECTION STATEPLANE', @@ -473,19 +424,15 @@ def osr_esri_14(): 'FIPSZONE 2600', 'DATUM NAD83', 'PARAMETERS']) - if srs.GetAuthorityCode('PROJCS') != '32104': - print(srs.GetAuthorityCode('PROJCS')) - gdaltest.post_reason('Did not get epsg authority code when expected.') - return 'fail' - - return 'success' + assert srs.GetAuthorityCode('PROJCS') == '32104', \ + 'Did not get epsg authority code when expected.' ############################################################################### # Verify hotine oblique mercator handling, particularly handling # of the rectified_grid_angle parameter. -def osr_esri_15(): +def test_osr_esri_15(): srs = osr.SpatialReference() srs.SetFromUserInput('PROJCS["Bern_1898_Bern_LV03C",GEOGCS["GCS_Bern_1898_Bern",DATUM["D_Bern_1898",SPHEROID["Bessel_1841",6377397.155,299.1528128]],PRIMEM["Bern",7.439583333333333],UNIT["Degree",0.0174532925199433]],PROJECTION["Hotine_Oblique_Mercator_Azimuth_Center"],PARAMETER["False_Easting",0.0],PARAMETER["False_Northing",0.0],PARAMETER["Scale_Factor",1.0],PARAMETER["Azimuth",90.0],PARAMETER["Longitude_Of_Center",0.0],PARAMETER["Latitude_Of_Center",46.95240555555556],UNIT["Meter",1.0]]') @@ -495,32 +442,27 @@ def osr_esri_15(): srs.MorphFromESRI() wkt = srs.ExportToWkt() - if wkt.find('rectified_grid_angle') == -1: - print(wkt) - gdaltest.post_reason('Did not get rectified_grid_angle as expected.') - return 'fail' + assert wkt.find('rectified_grid_angle') != -1, \ + 'Did not get rectified_grid_angle as expected.' srs.MorphToESRI() wkt = srs.ExportToWkt() - if wkt.find('rectified_grid_angle') != -1: - gdaltest.post_reason('did not get rectified_grid_angle removed as expected.') - return 'fail' + assert wkt.find('rectified_grid_angle') == -1, \ + 'did not get rectified_grid_angle removed as expected.' if wkt != expected: print('') print('Got: ', wkt) print('Expected: ', expected) - gdaltest.post_reason('Did not get expected HOM projection after morphing') - return 'fail' - - return 'success' + pytest.fail('Did not get expected HOM projection after morphing') + ############################################################################### # Verify translation of equirectangular to equidistant cylindrical with # cleanup of parameters. -def osr_esri_16(): +def test_osr_esri_16(): srs = osr.SpatialReference() srs.SetFromUserInput('+proj=eqc +lat_0=0 +lat_ts=-10 +lon_0=2 +x=100000 +y_0=200000 +ellps=sphere') @@ -530,18 +472,13 @@ def osr_esri_16(): srs.MorphToESRI() wkt = srs.ExportToWkt() - if expected != wkt: - print(wkt) - gdaltest.post_reason('Did not get expected equidistant cylindrical.') - return 'fail' - - return 'success' + assert expected == wkt, 'Did not get expected equidistant cylindrical.' ############################################################################### # Test LAEA support (#3017) -def osr_esri_17(): +def test_osr_esri_17(): original = 'PROJCS["ETRS89 / ETRS-LAEA",GEOGCS["ETRS89",DATUM["European_Terrestrial_Reference_System_1989",SPHEROID["GRS 1980",6378137,298.257222101]],PRIMEM["Greenwich",0],UNIT["degree",0.01745329251994328]],UNIT["metre",1],PROJECTION["Lambert_Azimuthal_Equal_Area"],PARAMETER["latitude_of_center",52],PARAMETER["longitude_of_center",10],PARAMETER["false_easting",4321000],PARAMETER["false_northing",3210000]]' srs = osr.SpatialReference() @@ -555,8 +492,7 @@ def osr_esri_17(): print('') print('Got: ', wkt) print('Expected: ', expected) - gdaltest.post_reason('Did not get expected LAEA SRS after morphToESRI') - return 'fail' + pytest.fail('Did not get expected LAEA SRS after morphToESRI') expected = 'PROJCS["ETRS89_ETRS_LAEA",GEOGCS["GCS_ETRS_1989",DATUM["European_Terrestrial_Reference_System_1989",SPHEROID["GRS_1980",6378137,298.257222101]],PRIMEM["Greenwich",0],UNIT["Degree",0.017453292519943295]],PROJECTION["Lambert_Azimuthal_Equal_Area"],PARAMETER["latitude_of_center",52],PARAMETER["longitude_of_center",10],PARAMETER["false_easting",4321000],PARAMETER["false_northing",3210000],UNIT["Meter",1]]' @@ -566,16 +502,14 @@ def osr_esri_17(): print('') print('Got: ', wkt) print('Expected: ', expected) - gdaltest.post_reason('Did not get expected LAEA SRS after morphFromESRI') - return 'fail' - - return 'success' + pytest.fail('Did not get expected LAEA SRS after morphFromESRI') + ############################################################################### # Test EC morphing. -def osr_esri_18(): +def test_osr_esri_18(): original = """PROJCS["World_Equidistant_Cylindrical", GEOGCS["GCS_WGS_1984", @@ -603,8 +537,7 @@ def osr_esri_18(): print('') print('Got: ', srs.ExportToPrettyWkt()) print('Expected: ', srs_expected.ExportToPrettyWkt()) - gdaltest.post_reason('Did not get expected EC SRS after morphFromESRI') - return 'fail' + pytest.fail('Did not get expected EC SRS after morphFromESRI') srs.MorphToESRI() srs_expected = osr.SpatialReference(wkt=original) @@ -613,16 +546,14 @@ def osr_esri_18(): print('') print('Got: ', srs.ExportToPrettyWkt()) print('Expected: ', srs_expected.ExportToPrettyWkt()) - gdaltest.post_reason('Did not get expected EC SRS after morphToESRI') - return 'fail' - - return 'success' + pytest.fail('Did not get expected EC SRS after morphToESRI') + ############################################################################### # Test spheroid remapping (per #3904) -def osr_esri_19(): +def test_osr_esri_19(): original = """GEOGCS["GCS_South_American_1969",DATUM["D_South_American_1969",SPHEROID["GRS_1967_Truncated",6378160.0,298.25]],PRIMEM["Greenwich",0.0],UNIT["Degree",0.0174532925199433]]""" @@ -635,8 +566,7 @@ def osr_esri_19(): if srs.GetAttrValue('SPHEROID') != expected: print('') print('Got: ', srs.ExportToPrettyWkt()) - gdaltest.post_reason('Did not get expected spheroid name after morphFromESRI') - return 'fail' + pytest.fail('Did not get expected spheroid name after morphFromESRI') srs.MorphToESRI() @@ -644,11 +574,9 @@ def osr_esri_19(): if srs.GetAttrValue('SPHEROID') != expected: print('') print('Got: ', srs.ExportToPrettyWkt()) - gdaltest.post_reason('Did not get expected spheroid name after morphToESRI') - return 'fail' - - return 'success' + pytest.fail('Did not get expected spheroid name after morphToESRI') + ############################################################################### # Test esri->ogc, esri->proj / ogc->esri, ogc->proj / proj->esri, proj->ogc @@ -738,7 +666,7 @@ def osr_esri_test(wkt_esri, wkt_ogc, proj4): # Orthographics (#4249) -def osr_esri_20(): +def test_osr_esri_20(): result = 'success' @@ -788,9 +716,7 @@ def osr_esri_20(): def osr_esri_test_esri_ogc_esri(ifile, ofile_base, fix_config='NO', check_epsg=False): - if not os.path.exists(ifile): - print('input file ' + ifile + ' does not exist') - return 'fail' + assert os.path.exists(ifile), ('input file ' + ifile + ' does not exist') result = 'success' check_srs = True @@ -932,11 +858,11 @@ def osr_esri_test_esri_ogc_esri(ifile, ofile_base, fix_config='NO', check_epsg=F return result -def osr_esri_21(): +def test_osr_esri_21(): # FIXME ? if sys.version_info >= (3, 0, 0): - return 'skip' + pytest.skip() result = 'success' @@ -971,9 +897,7 @@ def osr_esri_21(): def osr_esri_test_ogc_esri_ogc(ifile, ofile_base, fix_config='NO', check_epsg=False): - if not os.path.exists(ifile): - print('input file ' + ifile + ' does not exist') - return 'fail' + assert os.path.exists(ifile), ('input file ' + ifile + ' does not exist') result = 'success' check_srs = True @@ -1117,7 +1041,7 @@ def osr_esri_test_ogc_esri_ogc(ifile, ofile_base, fix_config='NO', check_epsg=Fa # Test EPSG->OGC->ESRI->OGC -def osr_esri_22(): +def test_osr_esri_22(): result = 'success' @@ -1138,7 +1062,7 @@ def osr_esri_22(): # set GDAL_FIX_ESRI_WKT=DATUM (bugs #4378 and #4345), don't expect to fail -def osr_esri_23(): +def test_osr_esri_23(): result = 'success' @@ -1161,7 +1085,7 @@ def osr_esri_23(): # -def osr_esri_24(): +def test_osr_esri_24(): srs = osr.SpatialReference() srs.ImportFromWkt('''PROJCS["Custom", @@ -1179,18 +1103,15 @@ def osr_esri_24(): PARAMETER["Central_Parallel",51.0], UNIT["Meter",1.0]]''') srs.MorphFromESRI() - if srs.GetProjParm(osr.SRS_PP_LATITUDE_OF_ORIGIN, 1000.0) == 1000.0: - gdaltest.post_reason('Failed to set latitude_of_origin') - return 'fail' - - return 'success' + assert srs.GetProjParm(osr.SRS_PP_LATITUDE_OF_ORIGIN, 1000.0) != 1000.0, \ + 'Failed to set latitude_of_origin' ############################################################################### # Test Pseudo-Mercator (#3962) # -def osr_esri_25(): +def test_osr_esri_25(): srs = osr.SpatialReference() srs.SetFromUserInput( 'PROJCS["WGS_1984_Web_Mercator_Auxiliary_Sphere",' @@ -1216,8 +1137,7 @@ def osr_esri_25(): proj4_string = srs.ExportToProj4() if not (expected_proj4_string.split(' ').sort() == proj4_string.split(' ').sort()): # pylint: disable=superfluous-parens print('Got: %s' % expected_proj4_string) - print('Expected: %s' % proj4_string) - return 'fail' + pytest.fail('Expected: %s' % proj4_string) # test an actual conversion (x, y, z) = transformer.TransformPoint(7000000, 7000000, 0) @@ -1226,32 +1146,25 @@ def osr_esri_25(): abs(exp_y - y) > 0.00001 or abs(exp_z - z) > 0.00001): print('Got: (%f, %f, %f)' % (x, y, z)) - print('Expected: (%f, %f, %f)' % (exp_x, exp_y, exp_z)) - return 'fail' - - return 'success' + pytest.fail('Expected: (%f, %f, %f)' % (exp_x, exp_y, exp_z)) + ############################################################################### # Test LCC_1SP (#2072) # -def osr_esri_26(): +def test_osr_esri_26(): srs = osr.SpatialReference() srs.SetFromUserInput("""PROJCS["NAD_1983_HARN_WISCRS_Washburn_County_Meters",GEOGCS["GCS_North_American_1983_HARN",DATUM["D_North_American_1983_HARN",SPHEROID["GRS_1980",6378137.0,298.257222101]],PRIMEM["Greenwich",0.0],UNIT["Degree",0.0174532925199433]],PROJECTION["Lambert_Conformal_Conic"],PARAMETER["False_Easting",234086.8682],PARAMETER["False_Northing",188358.6058],PARAMETER["Central_Meridian",-91.78333333333333],PARAMETER["Standard_Parallel_1",45.96121983333334],PARAMETER["Scale_Factor",1.0000475376],PARAMETER["Latitude_Of_Origin",45.96121983333334],UNIT["Meter",1.0]]""") srs.MorphFromESRI() - if srs.Validate() != 0: - gdaltest.post_reason('fail') - print(srs.ExportToWkt()) - return 'fail' - - return 'success' + assert srs.Validate() == 0, srs.ExportToWkt() ############################################################################### # Test Mercator_2SP (#4861) -def osr_esri_27(): +def test_osr_esri_27(): esri_wkt = """PROJCS["Batavia_NEIEZ", GEOGCS["GCS_Batavia", @@ -1271,7 +1184,7 @@ def osr_esri_27(): srs.MorphFromESRI() got_wkt = srs.ExportToPrettyWkt() - if got_wkt != """PROJCS["Batavia_NEIEZ", + assert got_wkt == """PROJCS["Batavia_NEIEZ", GEOGCS["GCS_Batavia", DATUM["Batavia", SPHEROID["Bessel_1841",6377397.155,299.1528128]], @@ -1282,14 +1195,11 @@ def osr_esri_27(): PARAMETER["False_Northing",900000.0], PARAMETER["Central_Meridian",110.0], PARAMETER["Standard_Parallel_1",4.45405154589751], - UNIT["Meter",1.0]]""": - gdaltest.post_reason('fail') - print(got_wkt) - return 'fail' + UNIT["Meter",1.0]]""" srs.MorphToESRI() got_wkt = srs.ExportToPrettyWkt() - if got_wkt != """PROJCS["Batavia_NEIEZ", + assert got_wkt == """PROJCS["Batavia_NEIEZ", GEOGCS["GCS_Batavia", DATUM["D_Batavia", SPHEROID["Bessel_1841",6377397.155,299.1528128]], @@ -1300,18 +1210,13 @@ def osr_esri_27(): PARAMETER["False_Northing",900000.0], PARAMETER["Central_Meridian",110.0], PARAMETER["Standard_Parallel_1",4.45405154589751], - UNIT["Meter",1.0]]""": - gdaltest.post_reason('fail') - print(got_wkt) - return 'fail' - - return 'success' + UNIT["Meter",1.0]]""" ############################################################################### # Test Mercator_1SP (#4861) -def osr_esri_28(): +def test_osr_esri_28(): ogc_wkt = """PROJCS["Segara (Jakarta) / NEIEZ (deprecated)", GEOGCS["Segara (Jakarta)", @@ -1343,7 +1248,7 @@ def osr_esri_28(): srs.MorphToESRI() got_wkt = srs.ExportToPrettyWkt() # Do not do exact test because of subtle difference of precision among compilers - if got_wkt.find("""PROJCS["Segara_Jakarta_NEIEZ_deprecated", + assert got_wkt.find("""PROJCS["Segara_Jakarta_NEIEZ_deprecated", GEOGCS["GCS_Segara (Jakarta)", DATUM["D_Gunung_Segara", SPHEROID["Bessel_1841",6377397.155,299.1528128]], @@ -1353,15 +1258,12 @@ def osr_esri_28(): PARAMETER["central_meridian",110], PARAMETER["false_easting",3900000], PARAMETER["false_northing",900000], - PARAMETER["standard_parallel_1",4.45405154""") != 0: - gdaltest.post_reason('fail') - print(got_wkt) - return 'fail' + PARAMETER["standard_parallel_1",4.45405154""") == 0 srs.MorphFromESRI() got_wkt = srs.ExportToPrettyWkt() # Do not do exact test because of subtle difference of precision among compilers - if got_wkt.find("""PROJCS["Segara_Jakarta_NEIEZ_deprecated", + assert got_wkt.find("""PROJCS["Segara_Jakarta_NEIEZ_deprecated", GEOGCS["GCS_Segara (Jakarta)", DATUM["Gunung_Segara_Jakarta", SPHEROID["Bessel_1841",6377397.155,299.1528128]], @@ -1371,25 +1273,20 @@ def osr_esri_28(): PARAMETER["central_meridian",110], PARAMETER["false_easting",3900000], PARAMETER["false_northing",900000], - PARAMETER["standard_parallel_1",4.45405154""") != 0: - gdaltest.post_reason('fail') - print(got_wkt) - return 'fail' - - return 'success' + PARAMETER["standard_parallel_1",4.45405154""") == 0 ############################################################################### # Test Web Mercator -def osr_esri_29(): +def test_osr_esri_29(): srs = osr.SpatialReference() srs.ImportFromEPSG(3857) srs.MorphToESRI() got_wkt = srs.ExportToPrettyWkt() - if got_wkt != """PROJCS["WGS_1984_Web_Mercator_Auxiliary_Sphere", + assert got_wkt == """PROJCS["WGS_1984_Web_Mercator_Auxiliary_Sphere", GEOGCS["GCS_WGS_1984", DATUM["D_WGS_1984", SPHEROID["WGS_1984",6378137.0,298.257223563]], @@ -1401,14 +1298,11 @@ def osr_esri_29(): PARAMETER["Central_Meridian",0.0], PARAMETER["Standard_Parallel_1",0.0], PARAMETER["Auxiliary_Sphere_Type",0.0], - UNIT["Meter",1.0]]""": - gdaltest.post_reason('fail') - print(got_wkt) - return 'fail' + UNIT["Meter",1.0]]""" srs.MorphFromESRI() got_wkt = srs.ExportToPrettyWkt() - if got_wkt != """PROJCS["WGS 84 / Pseudo-Mercator", + assert got_wkt == """PROJCS["WGS 84 / Pseudo-Mercator", GEOGCS["WGS 84", DATUM["WGS_1984", SPHEROID["WGS 84",6378137,298.257223563, @@ -1429,16 +1323,13 @@ def osr_esri_29(): AXIS["X",EAST], AXIS["Y",NORTH], 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"], - AUTHORITY["EPSG","3857"]]""": - gdaltest.post_reason('fail') - print(got_wkt) - return 'fail' + AUTHORITY["EPSG","3857"]]""" # 6134 srs.SetFromUserInput("""PROJCS["WGS_84_Pseudo_Mercator",GEOGCS["GCS_WGS_1984",DATUM["D_WGS_1984",SPHEROID["WGS_1984",6378137,298.257223563]],PRIMEM["Greenwich",0],UNIT["Degree",0.017453292519943295]],PROJECTION["Mercator"],PARAMETER["central_meridian",0],PARAMETER["false_easting",0],PARAMETER["false_northing",0],UNIT["Meter",1],PARAMETER["standard_parallel_1",0.0]]""") srs.MorphFromESRI() got_wkt = srs.ExportToPrettyWkt() - if got_wkt != """PROJCS["WGS 84 / Pseudo-Mercator", + assert got_wkt == """PROJCS["WGS 84 / Pseudo-Mercator", GEOGCS["WGS 84", DATUM["WGS_1984", SPHEROID["WGS 84",6378137,298.257223563, @@ -1459,18 +1350,13 @@ def osr_esri_29(): AXIS["X",EAST], AXIS["Y",NORTH], 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"], - AUTHORITY["EPSG","3857"]]""": - gdaltest.post_reason('fail') - print(got_wkt) - return 'fail' - - return 'success' + AUTHORITY["EPSG","3857"]]""" ############################################################################### # Verify import of custom ellipsoid -def osr_esri_30(): +def test_osr_esri_30(): prj = ['Projection GEOGRAPHIC', 'Parameters 6370000.0 6370000.0', @@ -1487,18 +1373,13 @@ def osr_esri_30(): srs_wkt = osr.SpatialReference(wkt=wkt) - if not srs_prj.IsSame(srs_wkt): - gdaltest.post_reason('fail') - print(srs_prj) - return 'fail' - - return 'success' + assert srs_prj.IsSame(srs_wkt) ############################################################################### # Verify import of old-style Mercator -def osr_esri_31(): +def test_osr_esri_31(): prj = ['Projection MERCATOR', 'Datum WGS84', @@ -1538,18 +1419,13 @@ def osr_esri_31(): srs_wkt = osr.SpatialReference(wkt=wkt) - if not srs_prj.IsSame(srs_wkt): - gdaltest.post_reason('fail') - print(srs_prj) - return 'fail' - - return 'success' + assert srs_prj.IsSame(srs_wkt) ############################################################################### # Bad Equidistant Conic -def osr_esri_32(): +def test_osr_esri_32(): # Autofuzz POC from b/65416453 prj = [ 'PROJECTIONLOCA?L_CSw?( EQUIDISTANT_CONIC', @@ -1559,71 +1435,23 @@ def osr_esri_32(): srs_prj = osr.SpatialReference() with gdaltest.error_handler('CPLQuietErrorHandler'): result = srs_prj.ImportFromESRI(prj) - if result != ogr.OGRERR_CORRUPT_DATA: - gdaltest.post_reason('Corrupt EQUIDISTANT_CONIC not marked corrupt') - return 'fail' - - return 'success' + assert result == ogr.OGRERR_CORRUPT_DATA, \ + 'Corrupt EQUIDISTANT_CONIC not marked corrupt' + ############################################################################### # Test morphing invalid PROJCS WKT does not crash -def osr_esri_33(): +def test_osr_esri_33(): sr = osr.SpatialReference() sr.ImportFromWkt('PROJCS[]') sr.MorphFromESRI() sr.MorphToESRI() - return 'success' - ############################################################################### # -gdaltest_list = [ - osr_esri_1, - osr_esri_2, - osr_esri_3, - osr_esri_4, - osr_esri_5, - osr_esri_6, - osr_esri_7, - osr_esri_8, - osr_esri_9, - osr_esri_10, - osr_esri_11, - osr_esri_12, - osr_esri_13, - osr_esri_14, - osr_esri_15, - osr_esri_16, - osr_esri_17, - osr_esri_18, - osr_esri_19, - osr_esri_20, - osr_esri_21, - osr_esri_22, - osr_esri_23, - osr_esri_24, - osr_esri_25, - osr_esri_26, - osr_esri_27, - osr_esri_28, - osr_esri_29, - osr_esri_30, - osr_esri_31, - osr_esri_32, - osr_esri_33, - None] - -if __name__ == '__main__': - - gdaltest.setup_run('osr_esri') - - # make sure GDAL_FIX_ESRI_WKT does not interfere with tests - gdal.SetConfigOption('GDAL_FIX_ESRI_WKT', 'NO') - gdaltest.run_tests(gdaltest_list) - - sys.exit(gdaltest.summarize()) + diff --git a/autotest/osr/osr_getprojectionmethods.py b/autotest/osr/osr_getprojectionmethods.py index 6010febbcbea..ac424fcfc95f 100755 --- a/autotest/osr/osr_getprojectionmethods.py +++ b/autotest/osr/osr_getprojectionmethods.py @@ -28,34 +28,18 @@ # DEALINGS IN THE SOFTWARE. ############################################################################### -import sys -sys.path.append('../pymod') -import gdaltest from osgeo import osr ############################################################################### # Test osr.GetProjectionMethods() -def osr_getprojectionmethods_1(): +def test_osr_getprojectionmethods_1(): methods = osr.GetProjectionMethods() - if methods[0][0] != 'Transverse_Mercator': - return 'fail' + assert methods[0][0] == 'Transverse_Mercator' - return 'success' -gdaltest_list = [ - osr_getprojectionmethods_1, - None] - -if __name__ == '__main__': - - gdaltest.setup_run('osr_getprojectionmethods') - - gdaltest.run_tests(gdaltest_list) - - sys.exit(gdaltest.summarize()) diff --git a/autotest/osr/osr_metacrs.py b/autotest/osr/osr_metacrs.py index 01d889570df5..5318237a1413 100755 --- a/autotest/osr/osr_metacrs.py +++ b/autotest/osr/osr_metacrs.py @@ -30,21 +30,27 @@ # DEALINGS IN THE SOFTWARE. ############################################################################### -import sys +import os import csv -sys.path.append('../pymod') +import pytest import gdaltest from osgeo import osr, gdal + ############################################################################### -# Class to perform the tests. +# When imported build a list of units based on the files available. +csv_rows = list(csv.DictReader(open(os.path.join(os.path.dirname(__file__), 'data/Test_Data_File.csv'), 'rt'))) -class MetaCRSTest(object): - def __init__(self, test_line): + +class TestMetaCRS(object): + @pytest.mark.parametrize( + 'test_line', csv_rows, ids=[row['testName'] for row in csv_rows] + ) + def test_metacrs(self, test_line): self.test_line = test_line self.src_xyz = None self.dst_xyz = None @@ -52,81 +58,22 @@ def __init__(self, test_line): self.dst_srs = None self.dst_error = None - def parse_line(self): - test_line = self.test_line - - self.src_srs = self.build_srs(test_line['srcCrsAuth'], - test_line['srcCrs']) - try: - self.dst_srs = self.build_srs(test_line['tgtCrsAuth'], - test_line['tgtCrs']) - except: - # Old style - self.dst_srs = self.build_srs(test_line['tgtCrsType'], - test_line['tgtCrs']) - - if self.src_srs is None or self.dst_srs is None: - return 'fail' - - try: - self.src_xyz = (float(test_line['srcOrd1']), - float(test_line['srcOrd2']), - float(test_line['srcOrd3'])) - except: - self.src_xyz = (float(test_line['srcOrd1']), - float(test_line['srcOrd2']), - 0.0) - try: - self.dst_xyz = (float(test_line['tgtOrd1']), - float(test_line['tgtOrd2']), - float(test_line['tgtOrd3'])) - except: - self.dst_xyz = (float(test_line['tgtOrd1']), - float(test_line['tgtOrd2']), - 0.0) - try: - self.dst_error = max(float(test_line['tolOrd1']), - float(test_line['tolOrd2']), - float(test_line['tolOrd3'])) - except: - self.dst_error = max(float(test_line['tolOrd1']), - float(test_line['tolOrd2'])) - - return 'success' - - def build_srs(self, typ, crstext): - if typ == 'EPSG': - srs = osr.SpatialReference() - if srs.ImportFromEPSGA(int(crstext)) == 0: - return srs - gdaltest.post_reason('failed to translate EPSG:' + crstext) - return None - gdaltest.post_reason('unsupported srs type: ' + typ) - return None - - def testMetaCRS(self): result = self.parse_line() - if result != 'success': - return result try: gdal.PushErrorHandler('CPLQuietErrorHandler') ct = osr.CoordinateTransformation(self.src_srs, self.dst_srs) gdal.PopErrorHandler() if gdal.GetLastErrorMsg().find('Unable to load PROJ.4') != -1: - gdaltest.post_reason('PROJ.4 missing, transforms not available.') - return 'skip' + pytest.skip('PROJ.4 missing, transforms not available.') except ValueError: gdal.PopErrorHandler() if gdal.GetLastErrorMsg().find('Unable to load PROJ.4') != -1: - gdaltest.post_reason('PROJ.4 missing, transforms not available.') - return 'skip' - gdaltest.post_reason('failed to create coordinate transformation. %s' % gdal.GetLastErrorMsg()) - return 'fail' + pytest.skip('PROJ.4 missing, transforms not available.') + pytest.fail('failed to create coordinate transformation. %s' % gdal.GetLastErrorMsg()) except: gdal.PopErrorHandler() - gdaltest.post_reason('failed to create coordinate transformation. %s' % gdal.GetLastErrorMsg()) - return 'fail' + pytest.fail('failed to create coordinate transformation. %s' % gdal.GetLastErrorMsg()) ###################################################################### # Transform source point to destination SRS, swapping EPSG GEOGCS @@ -153,32 +100,57 @@ def testMetaCRS(self): result[0], result[1], result[2], self.dst_xyz[0], self.dst_xyz[1], self.dst_xyz[2]) - gdaltest.post_reason(err_msg) - gdal.Debug('OSR', 'Src SRS:\n%s\n\nDst SRS:\n%s\n' % (self.src_srs.ExportToPrettyWkt(), self.dst_srs.ExportToPrettyWkt())) - return 'fail' - - return 'success' - -############################################################################### -# When imported build a list of units based on the files available. - - -gdaltest_list = [] + pytest.fail(err_msg) -csv_reader = csv.DictReader(open('data/Test_Data_File.csv', 'rt')) - -for test in csv_reader: - ut = MetaCRSTest(test) - gdaltest_list.append((ut.testMetaCRS, test['testName'])) + def parse_line(self): + test_line = self.test_line -if __name__ == '__main__': + self.src_srs = self.build_srs(test_line['srcCrsAuth'], + test_line['srcCrs']) + try: + self.dst_srs = self.build_srs(test_line['tgtCrsAuth'], + test_line['tgtCrs']) + except: + # Old style + self.dst_srs = self.build_srs(test_line['tgtCrsType'], + test_line['tgtCrs']) - gdaltest.setup_run('osr_metacrs') + assert not (self.src_srs is None or self.dst_srs is None) - gdaltest.run_tests(gdaltest_list) + try: + self.src_xyz = (float(test_line['srcOrd1']), + float(test_line['srcOrd2']), + float(test_line['srcOrd3'])) + except: + self.src_xyz = (float(test_line['srcOrd1']), + float(test_line['srcOrd2']), + 0.0) + try: + self.dst_xyz = (float(test_line['tgtOrd1']), + float(test_line['tgtOrd2']), + float(test_line['tgtOrd3'])) + except: + self.dst_xyz = (float(test_line['tgtOrd1']), + float(test_line['tgtOrd2']), + 0.0) + try: + self.dst_error = max(float(test_line['tolOrd1']), + float(test_line['tolOrd2']), + float(test_line['tolOrd3'])) + except: + self.dst_error = max(float(test_line['tolOrd1']), + float(test_line['tolOrd2'])) - sys.exit(gdaltest.summarize()) + def build_srs(self, typ, crstext): + if typ == 'EPSG': + srs = osr.SpatialReference() + if srs.ImportFromEPSGA(int(crstext)) == 0: + return srs + gdaltest.post_reason('failed to translate EPSG:' + crstext) + return None + gdaltest.post_reason('unsupported srs type: ' + typ) + return None diff --git a/autotest/osr/osr_micoordsys.py b/autotest/osr/osr_micoordsys.py index e89b24b54452..1eb716ddb2f5 100755 --- a/autotest/osr/osr_micoordsys.py +++ b/autotest/osr/osr_micoordsys.py @@ -28,19 +28,17 @@ # DEALINGS IN THE SOFTWARE. ############################################################################### -import sys -sys.path.append('../pymod') -import gdaltest from osgeo import osr +import pytest ############################################################################### # Test the osr.SpatialReference.ImportFromMICoordSys() function. # -def osr_micoordsys_1(): +def test_osr_micoordsys_1(): srs = osr.SpatialReference() srs.ImportFromMICoordSys('Earth Projection 3, 62, "m", -117.474542888889, 33.7644620277778, 33.9036340277778, 33.6252900277778, 0, 0') @@ -52,17 +50,15 @@ def osr_micoordsys_1(): or abs(srs.GetProjParm(osr.SRS_PP_FALSE_EASTING) - 0.0) > 0.0000005 \ or abs(srs.GetProjParm(osr.SRS_PP_FALSE_NORTHING) - 0.0) > 0.0000005: print(srs.ExportToPrettyWkt()) - gdaltest.post_reason('Can not export Lambert Conformal Conic projection.') - return 'fail' - - return 'success' + pytest.fail('Can not export Lambert Conformal Conic projection.') + ############################################################################### # Test the osr.SpatialReference.ExportToMICoordSys() function. # -def osr_micoordsys_2(): +def test_osr_micoordsys_2(): srs = osr.SpatialReference() srs.ImportFromWkt("""PROJCS["unnamed",GEOGCS["NAD27",\ @@ -80,58 +76,32 @@ def osr_micoordsys_2(): proj = srs.ExportToMICoordSys() - if proj != 'Earth Projection 3, 62, "m", -117.474542888889, 33.7644620277778, 33.9036340277778, 33.6252900277778, 0, 0': - print(proj) - gdaltest.post_reason('Can not import Lambert Conformal Conic projection.') - return 'fail' - - return 'success' + assert proj == 'Earth Projection 3, 62, "m", -117.474542888889, 33.7644620277778, 33.9036340277778, 33.6252900277778, 0, 0', \ + 'Can not import Lambert Conformal Conic projection.' ############################################################################### # Test EPSG:3857 # -def osr_micoordsys_3(): +def test_osr_micoordsys_3(): srs = osr.SpatialReference() srs.ImportFromEPSG(3857) proj = srs.ExportToMICoordSys() - if proj != 'Earth Projection 10, 157, "m", 0': - gdaltest.post_reason('failure') - print(proj) - return 'fail' + assert proj == 'Earth Projection 10, 157, "m", 0' srs = osr.SpatialReference() srs.ImportFromMICoordSys('Earth Projection 10, 157, "m", 0') wkt = srs.ExportToWkt() - if wkt.find('EXTENSION["PROJ4"') < 0: - gdaltest.post_reason('failure') - print(wkt) - return 'fail' + assert wkt.find('EXTENSION["PROJ4"') >= 0 # Transform again to MITAB (we no longer have the EPSG code, so we rely on PROJ4 extension node) proj = srs.ExportToMICoordSys() - if proj != 'Earth Projection 10, 157, "m", 0': - gdaltest.post_reason('failure') - print(proj) - return 'fail' - - return 'success' - - -gdaltest_list = [ - osr_micoordsys_1, - osr_micoordsys_2, - osr_micoordsys_3] - -if __name__ == '__main__': + assert proj == 'Earth Projection 10, 157, "m", 0' - gdaltest.setup_run('osr_micoordsys') - gdaltest.run_tests(gdaltest_list) - sys.exit(gdaltest.summarize()) diff --git a/autotest/osr/osr_ozi.py b/autotest/osr/osr_ozi.py index 128008d0652a..7aa98606f351 100755 --- a/autotest/osr/osr_ozi.py +++ b/autotest/osr/osr_ozi.py @@ -28,9 +28,7 @@ # DEALINGS IN THE SOFTWARE. ############################################################################### -import sys -sys.path.append('../pymod') import gdaltest from osgeo import osr @@ -39,7 +37,7 @@ # Test with WGS 84 datum -def osr_ozi_1(): +def test_osr_ozi_1(): srs = osr.SpatialReference() srs.ImportFromOzi(["OziExplorer Map Data File Version 2.2", @@ -52,16 +50,13 @@ def osr_ozi_1(): expected = 'PROJCS["unnamed",GEOGCS["WGS 84",DATUM["WGS_1984",SPHEROID["WGS 84",6378137,298.257223563,AUTHORITY["EPSG","7030"]],AUTHORITY["EPSG","6326"]],PRIMEM["Greenwich",0,AUTHORITY["EPSG","8901"]],UNIT["degree",0.0174532925199433,AUTHORITY["EPSG","9122"]],AUTHORITY["EPSG","4326"]],PROJECTION["Lambert_Conformal_Conic_2SP"],PARAMETER["standard_parallel_1",40],PARAMETER["standard_parallel_2",56],PARAMETER["latitude_of_origin",4],PARAMETER["central_meridian",10],PARAMETER["false_easting",0],PARAMETER["false_northing",0],UNIT["Meter",1]]' - if not gdaltest.equal_srs_from_wkt(expected, srs.ExportToWkt()): - return 'fail' - - return 'success' + assert gdaltest.equal_srs_from_wkt(expected, srs.ExportToWkt()) ############################################################################### # Test with another datum known by OZI and whose EPSG code is known -def osr_ozi_2(): +def test_osr_ozi_2(): srs = osr.SpatialReference() srs.ImportFromOzi(["OziExplorer Map Data File Version 2.2", @@ -75,16 +70,13 @@ def osr_ozi_2(): srs_ref = osr.SpatialReference() srs_ref.ImportFromEPSG(4301) - if not gdaltest.equal_srs_from_wkt(srs_ref.ExportToWkt(), srs.ExportToWkt()): - return 'fail' - - return 'success' + assert gdaltest.equal_srs_from_wkt(srs_ref.ExportToWkt(), srs.ExportToWkt()) ############################################################################### # Test with another datum known by OZI and whose EPSG code is unknown -def osr_ozi_3(): +def test_osr_ozi_3(): srs = osr.SpatialReference() srs.ImportFromOzi(["OziExplorer Map Data File Version 2.2", @@ -97,22 +89,7 @@ def osr_ozi_3(): expected = 'GEOGCS["European 1950 (Mean France)",DATUM["European 1950 (Mean France)",SPHEROID["International 1924",6378388,297],TOWGS84[-87,-96,-120,0,0,0,0]],PRIMEM["Greenwich",0],UNIT["degree",0.0174532925199433]]' - if not gdaltest.equal_srs_from_wkt(expected, srs.ExportToWkt()): - return 'fail' - - return 'success' - - -gdaltest_list = [ - osr_ozi_1, - osr_ozi_2, - osr_ozi_3, - None] - -if __name__ == '__main__': + assert gdaltest.equal_srs_from_wkt(expected, srs.ExportToWkt()) - gdaltest.setup_run('osr_ozi') - gdaltest.run_tests(gdaltest_list) - sys.exit(gdaltest.summarize()) diff --git a/autotest/osr/osr_pci.py b/autotest/osr/osr_pci.py index 6e36cd48cdee..ebf332bc775b 100755 --- a/autotest/osr/osr_pci.py +++ b/autotest/osr/osr_pci.py @@ -25,9 +25,7 @@ # Boston, MA 02111-1307, USA. ############################################################################### -import sys -sys.path.append('../pymod') import gdaltest from osgeo import osr @@ -37,42 +35,29 @@ # -def osr_pci_1(): +def test_osr_pci_1(): prj_parms = (0.0, 0.0, 45.0, 54.5, 47.0, 62.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0) srs = osr.SpatialReference() srs.ImportFromPCI('EC E015', 'METRE', prj_parms) - if abs(srs.GetProjParm(osr.SRS_PP_STANDARD_PARALLEL_1) - 47.0) > 0.0000005 \ - or abs(srs.GetProjParm(osr.SRS_PP_STANDARD_PARALLEL_2) - 62.0) > 0.0000005 \ - or abs(srs.GetProjParm(osr.SRS_PP_LATITUDE_OF_CENTER) - 54.5) > 0.0000005 \ - or abs(srs.GetProjParm(osr.SRS_PP_LONGITUDE_OF_CENTER) - 45.0) > 0.0000005 \ - or abs(srs.GetProjParm(osr.SRS_PP_FALSE_EASTING) - 0.0) > 0.0000005 \ - or abs(srs.GetProjParm(osr.SRS_PP_FALSE_NORTHING) - 0.0) > 0.0000005: - gdaltest.post_reason('Can not import Equidistant Conic projection.') - return 'fail' + assert abs(srs.GetProjParm(osr.SRS_PP_STANDARD_PARALLEL_1) - 47.0) <= 0.0000005 and abs(srs.GetProjParm(osr.SRS_PP_STANDARD_PARALLEL_2) - 62.0) <= 0.0000005 and abs(srs.GetProjParm(osr.SRS_PP_LATITUDE_OF_CENTER) - 54.5) <= 0.0000005 and abs(srs.GetProjParm(osr.SRS_PP_LONGITUDE_OF_CENTER) - 45.0) <= 0.0000005 and abs(srs.GetProjParm(osr.SRS_PP_FALSE_EASTING) - 0.0) <= 0.0000005 and abs(srs.GetProjParm(osr.SRS_PP_FALSE_NORTHING) - 0.0) <= 0.0000005, \ + 'Can not import Equidistant Conic projection.' expected = 'PROJCS["unnamed",GEOGCS["Unknown - PCI E015",DATUM["Unknown - PCI E015",SPHEROID["Krassowsky 1940",6378245,298.3,AUTHORITY["EPSG","7024"]]],PRIMEM["Greenwich",0],UNIT["degree",0.0174532925199433]],PROJECTION["Equidistant_Conic"],PARAMETER["standard_parallel_1",47],PARAMETER["standard_parallel_2",62],PARAMETER["latitude_of_center",54.5],PARAMETER["longitude_of_center",45],PARAMETER["false_easting",0],PARAMETER["false_northing",0],UNIT["Meter",1]]' - if not gdaltest.equal_srs_from_wkt(expected, srs.ExportToWkt()): - return 'fail' + assert gdaltest.equal_srs_from_wkt(expected, srs.ExportToWkt()) pci_parms = srs.ExportToPCI() - if pci_parms[0] != 'EC E015' \ - or pci_parms[1] != 'METRE' \ - or pci_parms[2] != prj_parms: - print(pci_parms) - gdaltest.post_reason('ExportToPCI result wrong.') - return 'fail' - - return 'success' + assert pci_parms[0] == 'EC E015' and pci_parms[1] == 'METRE' and pci_parms[2] == prj_parms, \ + 'ExportToPCI result wrong.' ############################################################################### # Test the osr.SpatialReference.ExportToPCI() function. # -def osr_pci_2(): +def test_osr_pci_2(): srs = osr.SpatialReference() srs.ImportFromWkt("""PROJCS["unnamed",GEOGCS["NAD27",\ @@ -90,22 +75,15 @@ def osr_pci_2(): (proj, units, parms) = srs.ExportToPCI() - if proj != 'LCC D-01' or units != 'METRE' \ - or abs(parms[2] - -117.4745429) > 0.0000005 \ - or abs(parms[3] - 33.76446203) > 0.0000005 \ - or abs(parms[4] - 33.90363403) > 0.0000005 \ - or abs(parms[5] - 33.62529003) > 0.0000005: - gdaltest.post_reason('Can not import Lambert Conformal Conic projection.') - return 'fail' - - return 'success' + assert proj == 'LCC D-01' and units == 'METRE' and abs(parms[2] - -117.4745429) <= 0.0000005 and abs(parms[3] - 33.76446203) <= 0.0000005 and abs(parms[4] - 33.90363403) <= 0.0000005 and abs(parms[5] - 33.62529003) <= 0.0000005, \ + 'Can not import Lambert Conformal Conic projection.' ############################################################################### # Test MGRS interpretation. (#3379) # -def osr_pci_3(): +def test_osr_pci_3(): srs = osr.SpatialReference() srs.ImportFromPCI( @@ -137,14 +115,13 @@ def osr_pci_3(): if wkt.find('13, Northern Hemi') == -1: gdaltest.post_reason('did get southern hemisphere!') - return 'success' - + ############################################################################### # Test Datum lookup in pci_datum.txt # -def osr_pci_4(): +def test_osr_pci_4(): prj_parms = (0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0) @@ -153,25 +130,18 @@ def osr_pci_4(): expected = 'GEOGCS["Rijksdriehoeks Datum",DATUM["Rijksdriehoeks Datum",SPHEROID["Bessel 1841",6377397.155,299.1528128,AUTHORITY["EPSG","7004"]],TOWGS84[565.04,49.91,465.84,0.4094,-0.3597,1.8685,4.077200000063286]],PRIMEM["Greenwich",0],UNIT["degree",0.0174532925199433]]' - if not gdaltest.equal_srs_from_wkt(expected, srs.ExportToWkt()): - return 'fail' + assert gdaltest.equal_srs_from_wkt(expected, srs.ExportToWkt()) pci_parms = srs.ExportToPCI() - if pci_parms[0] != 'LONG/LAT D506' \ - or pci_parms[1] != 'DEGREE' \ - or pci_parms[2] != prj_parms: - print(pci_parms) - gdaltest.post_reason('ExportToPCI result wrong.') - return 'fail' - - return 'success' + assert pci_parms[0] == 'LONG/LAT D506' and pci_parms[1] == 'DEGREE' and pci_parms[2] == prj_parms, \ + 'ExportToPCI result wrong.' ############################################################################### # Test Datum ellisoid lookup in pci_ellpis.txt # -def osr_pci_5(): +def test_osr_pci_5(): prj_parms = (0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0) @@ -180,25 +150,18 @@ def osr_pci_5(): expected = 'GEOGCS["Unknown - PCI E224",DATUM["Unknown - PCI E224",SPHEROID["Xian 1980",6378140,298.2569978029123]],PRIMEM["Greenwich",0],UNIT["degree",0.0174532925199433]]' - if not gdaltest.equal_srs_from_wkt(expected, srs.ExportToWkt()): - return 'fail' + assert gdaltest.equal_srs_from_wkt(expected, srs.ExportToWkt()) pci_parms = srs.ExportToPCI() - if pci_parms[0] != 'LONG/LAT E224' \ - or pci_parms[1] != 'DEGREE' \ - or pci_parms[2] != prj_parms: - print(pci_parms) - gdaltest.post_reason('ExportToPCI result wrong.') - return 'fail' - - return 'success' + assert pci_parms[0] == 'LONG/LAT E224' and pci_parms[1] == 'DEGREE' and pci_parms[2] == prj_parms, \ + 'ExportToPCI result wrong.' ############################################################################### # Test Datum lookup in pci_datum.txt # -def osr_pci_6(): +def test_osr_pci_6(): prj_parms = (0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0) @@ -207,18 +170,11 @@ def osr_pci_6(): expected = 'GEOGCS["AGD84",DATUM["Australian_Geodetic_Datum_1984",SPHEROID["Australian National Spheroid",6378160,298.25,AUTHORITY["EPSG","7003"]],TOWGS84[-134,-48,149,0,0,0,0],AUTHORITY["EPSG","6203"]],PRIMEM["Greenwich",0,AUTHORITY["EPSG","8901"]],UNIT["degree",0.0174532925199433,AUTHORITY["EPSG","9122"]],AUTHORITY["EPSG","4203"]]' - if not gdaltest.equal_srs_from_wkt(expected, srs.ExportToWkt()): - return 'fail' + assert gdaltest.equal_srs_from_wkt(expected, srs.ExportToWkt()) pci_parms = srs.ExportToPCI() - if pci_parms[0] != 'LONG/LAT D030' \ - or pci_parms[1] != 'DEGREE' \ - or pci_parms[2] != prj_parms: - print(pci_parms) - gdaltest.post_reason('ExportToPCI result wrong.') - return 'fail' - - return 'success' + assert pci_parms[0] == 'LONG/LAT D030' and pci_parms[1] == 'DEGREE' and pci_parms[2] == prj_parms, \ + 'ExportToPCI result wrong.' ############################################################################### # Make sure we can translate a datum with only the TOWGS84 parameters to @@ -226,7 +182,7 @@ def osr_pci_6(): # -def osr_pci_7(): +def test_osr_pci_7(): srs = osr.SpatialReference() srs.SetFromUserInput('GEOGCS["My GCS",DATUM["My Datum",SPHEROID["Bessel 1841",6377397.155,299.1528128,AUTHORITY["EPSG","7004"]],TOWGS84[565.04,49.91,465.84,0.4094,-0.3597,1.8685,4.077200000063286]],PRIMEM["Greenwich",0],UNIT["degree",0.0174532925199433]]') @@ -234,30 +190,8 @@ def osr_pci_7(): prj_parms = (0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0) pci_parms = srs.ExportToPCI() - if pci_parms[0] != 'LONG/LAT D506' \ - or pci_parms[1] != 'DEGREE' \ - or pci_parms[2] != prj_parms: - print(pci_parms) - gdaltest.post_reason('ExportToPCI result wrong.') - return 'fail' - - return 'success' - - -gdaltest_list = [ - osr_pci_1, - osr_pci_2, - osr_pci_3, - osr_pci_4, - osr_pci_5, - osr_pci_6, - osr_pci_7, - None] - -if __name__ == '__main__': + assert pci_parms[0] == 'LONG/LAT D506' and pci_parms[1] == 'DEGREE' and pci_parms[2] == prj_parms, \ + 'ExportToPCI result wrong.' - gdaltest.setup_run('osr_pci') - gdaltest.run_tests(gdaltest_list) - sys.exit(gdaltest.summarize()) diff --git a/autotest/osr/osr_pm.py b/autotest/osr/osr_pm.py index dbf9f57f3ac0..2ba01afb401f 100755 --- a/autotest/osr/osr_pm.py +++ b/autotest/osr/osr_pm.py @@ -29,11 +29,8 @@ # DEALINGS IN THE SOFTWARE. ############################################################################### -import sys -sys.path.append('../pymod') -import gdaltest from osgeo import osr ############################################################################### @@ -41,77 +38,49 @@ # and the central meridian. -def osr_pm_1(): +def test_osr_pm_1(): srs = osr.SpatialReference() srs.ImportFromEPSG(27572) - if abs(float(srs.GetAttrValue('PRIMEM', 1)) - 2.33722917) > 0.0000005: - gdaltest.post_reason('Wrong prime meridian.') - return 'fail' + assert abs(float(srs.GetAttrValue('PRIMEM', 1)) - 2.33722917) <= 0.0000005, \ + 'Wrong prime meridian.' - if abs(srs.GetProjParm(osr.SRS_PP_CENTRAL_MERIDIAN) - 0.0) > 0.0000005: - gdaltest.post_reason('Wrong central meridian.') - return 'fail' - - return 'success' + assert abs(srs.GetProjParm(osr.SRS_PP_CENTRAL_MERIDIAN) - 0.0) <= 0.0000005, \ + 'Wrong central meridian.' ############################################################################### # Check that EPSG:27572 lookup has the prime meridian properly set, # and the central meridian in the PROJ.4 string. -def osr_pm_2(): +def test_osr_pm_2(): srs = osr.SpatialReference() srs.ImportFromEPSG(27572) proj4_srs = srs.ExportToProj4() - if proj4_srs.find('+pm=paris') == -1: - print(proj4_srs) - gdaltest.post_reason('prime meridian wrong or missing.') - return 'fail' - - if proj4_srs.find('+lon_0=0') == -1: - print(proj4_srs) - gdaltest.post_reason('+lon_0 is wrong.') - return 'fail' + assert proj4_srs.find('+pm=paris') != -1, 'prime meridian wrong or missing.' - return 'success' + assert proj4_srs.find('+lon_0=0') != -1, '+lon_0 is wrong.' ############################################################################### # Convert PROJ.4 format to WKT and verify that PM and central meridian # are properly preserved. -def osr_pm_3(): +def test_osr_pm_3(): srs = osr.SpatialReference() srs.ImportFromProj4('+proj=utm +zone=30 +datum=WGS84 +pm=bogota') - if abs(float(srs.GetAttrValue('PRIMEM', 1)) + 74.08091666678081) > 0.0000005: - gdaltest.post_reason('Wrong prime meridian.') - return 'fail' - - if abs(srs.GetProjParm(osr.SRS_PP_CENTRAL_MERIDIAN) + 3.0) > 0.0000005: - gdaltest.post_reason('Wrong central meridian.') - return 'fail' + assert abs(float(srs.GetAttrValue('PRIMEM', 1)) + 74.08091666678081) <= 0.0000005, \ + 'Wrong prime meridian.' - return 'success' + assert abs(srs.GetProjParm(osr.SRS_PP_CENTRAL_MERIDIAN) + 3.0) <= 0.0000005, \ + 'Wrong central meridian.' ############################################################################### -gdaltest_list = [ - osr_pm_1, - osr_pm_2, - osr_pm_3, - None] - -if __name__ == '__main__': - - gdaltest.setup_run('osr_pm') - - gdaltest.run_tests(gdaltest_list) - sys.exit(gdaltest.summarize()) diff --git a/autotest/osr/osr_proj4.py b/autotest/osr/osr_proj4.py index 26ab5f641f3d..acc6d4d9173c 100755 --- a/autotest/osr/osr_proj4.py +++ b/autotest/osr/osr_proj4.py @@ -31,13 +31,12 @@ # DEALINGS IN THE SOFTWARE. ############################################################################### -import os import sys -sys.path.append('../pymod') from osgeo import gdal, osr import gdaltest +import pytest ############################################################################### # Return True if proj is at least 4.8.0 @@ -93,16 +92,13 @@ def have_proj480(): # -def osr_proj4_1(): +def test_osr_proj4_1(): srs = osr.SpatialReference() srs.ImportFromProj4('+proj=tmerc +lat_0=53.5000000000 +lon_0=-8.0000000000 +k_0=1.0000350000 +x_0=200000.0000000000 +y_0=250000.0000000000 +a=6377340.189000 +rf=299.324965 +towgs84=482.530,-130.596,564.557,-1.042,-0.214,-0.631,8.15') - if abs(srs.GetProjParm(osr.SRS_PP_SCALE_FACTOR) - 1.000035) > 0.0000005: - gdaltest.post_reason('+k_0 not supported on import from PROJ.4?') - return 'fail' - - return 'success' + assert abs(srs.GetProjParm(osr.SRS_PP_SCALE_FACTOR) - 1.000035) <= 0.0000005, \ + '+k_0 not supported on import from PROJ.4?' ############################################################################### # Verify that we can import strings with parameter values that are exponents @@ -110,28 +106,25 @@ def osr_proj4_1(): # -def osr_proj4_2(): +def test_osr_proj4_2(): srs = osr.SpatialReference() srs.ImportFromProj4("+proj=lcc +x_0=0.6096012192024384e+06 +y_0=0 +lon_0=90dw +lat_0=42dn +lat_1=44d4'n +lat_2=42d44'n +a=6378206.400000 +rf=294.978698 +nadgrids=conus,ntv1_can.dat +units=m") - if abs(srs.GetProjParm(osr.SRS_PP_FALSE_EASTING) - 609601.219) > 0.0005: - gdaltest.post_reason('Parsing exponents not supported?') - return 'fail' + assert abs(srs.GetProjParm(osr.SRS_PP_FALSE_EASTING) - 609601.219) <= 0.0005, \ + 'Parsing exponents not supported?' if srs.Validate() != 0: - gdaltest.post_reason('does not validate') print(srs.ExportToPrettyWkt()) - return 'fail' - - return 'success' + pytest.fail('does not validate') + ############################################################################### # Verify that empty srs'es don't cause a crash (#1718). # -def osr_proj4_3(): +def test_osr_proj4_3(): srs = osr.SpatialReference() @@ -144,10 +137,9 @@ def osr_proj4_3(): gdal.PopErrorHandler() if gdal.GetLastErrorMsg().find('No translation') != -1: - return 'success' + return - gdaltest.post_reason('empty srs not handled properly') - return 'fail' + pytest.fail('empty srs not handled properly') ############################################################################### # Verify that unrecognized projections return an error, not those @@ -155,7 +147,7 @@ def osr_proj4_3(): # -def osr_proj4_4(): +def test_osr_proj4_4(): srs = osr.SpatialReference() srs.SetFromUserInput('+proj=utm +zone=11 +datum=WGS84') @@ -170,29 +162,25 @@ def osr_proj4_4(): gdal.PopErrorHandler() if gdal.GetLastErrorMsg().find('No translation') != -1: - return 'success' + return - gdaltest.post_reason('unknown srs not handled properly') - return 'fail' + pytest.fail('unknown srs not handled properly') ############################################################################### # Verify that prime meridians are preserved when round tripping. (#1940) # -def osr_proj4_5(): +def test_osr_proj4_5(): srs = osr.SpatialReference() srs.ImportFromProj4('+proj=lcc +lat_1=46.8 +lat_0=46.8 +lon_0=0 +k_0=0.99987742 +x_0=600000 +y_0=2200000 +a=6378249.2 +b=6356515 +towgs84=-168,-60,320,0,0,0,0 +pm=paris +units=m +no_defs') - if abs(float(srs.GetAttrValue('PRIMEM', 1)) - 2.3372291667) > 0.00000001: - gdaltest.post_reason('prime meridian lost?') - return 'fail' + assert abs(float(srs.GetAttrValue('PRIMEM', 1)) - 2.3372291667) <= 0.00000001, \ + 'prime meridian lost?' - if abs(srs.GetProjParm('central_meridian')) != 0.0: - gdaltest.post_reason('central meridian altered?') - return 'fail' + assert abs(srs.GetProjParm('central_meridian')) == 0.0, 'central meridian altered?' p4 = srs.ExportToProj4() srs2 = osr.SpatialReference() @@ -203,14 +191,13 @@ def osr_proj4_5(): print(srs.ExportToPrettyWkt()) print(srs2.ExportToPrettyWkt()) - return 'success' - + ############################################################################### # Confirm handling of non-zero latitude of origin mercator (#3026) # -def osr_proj4_6(): +def test_osr_proj4_6(): expect_proj4 = '+proj=merc +lon_0=0 +lat_ts=46.1333331 +x_0=1000 +y_0=2000 +datum=WGS84 +units=m +no_defs ' @@ -239,8 +226,7 @@ def osr_proj4_6(): if proj4 != expect_proj4: print('Got:', proj4) print('Expected:', expect_proj4) - gdaltest.post_reason('Failed to translate non-zero lat-of-origin mercator.') - return 'fail' + pytest.fail('Failed to translate non-zero lat-of-origin mercator.') # Translate back - should be mercator 1sp @@ -267,17 +253,15 @@ def osr_proj4_6(): if wkt != expect_wkt: print('Got: %s' % wkt) print('Expect:%s' % expect_wkt) - gdaltest.post_reason('did not get expected mercator_2sp result.') - return 'fail' - - return 'success' + pytest.fail('did not get expected mercator_2sp result.') + ############################################################################### # Confirm handling of somerc (#3032). # -def osr_proj4_7(): +def test_osr_proj4_7(): srs = osr.SpatialReference() srs.ImportFromEPSG(23700) @@ -285,11 +269,10 @@ def osr_proj4_7(): proj4 = srs.ExportToProj4() expected = '+proj=somerc +lat_0=47.14439372222222 +lon_0=19.04857177777778 +k_0=0.99993 +x_0=650000 +y_0=200000 +ellps=GRS67 +towgs84=52.17,-71.82,-14.9,0,0,0,0 +units=m +no_defs ' if proj4 != expected: - gdaltest.post_reason('did not get expected proj.4 translation of somerc') print('') print('Got: "%s"' % proj4) print('Expected:"%s"' % expected) - return 'fail' + pytest.fail('did not get expected proj.4 translation of somerc') srs.ImportFromProj4(proj4) @@ -312,101 +295,80 @@ def osr_proj4_7(): srs_expected = osr.SpatialReference(wkt=expected) if not srs.IsSame(srs_expected): - gdaltest.post_reason('did not get expected wkt.') print('Got: %s' % srs.ExportToPrettyWkt()) - return 'fail' - - return 'success' + pytest.fail('did not get expected wkt.') + ############################################################################### # Check EPSG:3857, confirm Google Mercator hackery. -def osr_proj4_8(): +def test_osr_proj4_8(): srs = osr.SpatialReference() srs.ImportFromEPSG(3857) proj4 = srs.ExportToProj4() expected = '+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' - if proj4 != expected: - gdaltest.post_reason('did not get expected EPSG:3857 (google mercator) result.') - print(proj4) - return 'fail' + assert proj4 == expected, 'did not get expected EPSG:3857 (google mercator) result.' srs = osr.SpatialReference() srs.ImportFromEPSG(3785) proj4 = srs.ExportToProj4() - if proj4 != expected: - gdaltest.post_reason('did not get expected EPSG:3785 (google mercator) result.') - print(proj4) - return 'fail' - - return 'success' + assert proj4 == expected, 'did not get expected EPSG:3785 (google mercator) result.' ############################################################################### # NAD27 is a bit special - make sure no towgs84 values come through. # -def osr_proj4_9(): +def test_osr_proj4_9(): srs = osr.SpatialReference() srs.ImportFromEPSG(4267) proj4 = srs.ExportToProj4() expected = '+proj=longlat +datum=NAD27 +no_defs ' - if proj4 != expected: - gdaltest.post_reason('did not get expected EPSG:4267 (NAD27)') - print(proj4) - return 'fail' + assert proj4 == expected, 'did not get expected EPSG:4267 (NAD27)' srs = osr.SpatialReference() srs.SetFromUserInput('NAD27') proj4 = srs.ExportToProj4() - if proj4 != expected: - gdaltest.post_reason('did not get expected "NAD27"') - print(proj4) - return 'fail' - - return 'success' + assert proj4 == expected, 'did not get expected "NAD27"' ############################################################################### # Does geocentric work okay? # -def osr_proj4_10(): +def test_osr_proj4_10(): srs = osr.SpatialReference() srs.ImportFromProj4('+proj=geocent +ellps=WGS84 +towgs84=0,0,0 ') wkt_expected = 'GEOCCS["Geocentric",DATUM["unknown",SPHEROID["WGS84",6378137,298.257223563],TOWGS84[0,0,0,0,0,0,0]],PRIMEM["Greenwich",0]]' - if not gdaltest.equal_srs_from_wkt(wkt_expected, srs.ExportToWkt()): - gdaltest.post_reason('did not get expected wkt.') - return 'fail' + assert gdaltest.equal_srs_from_wkt(wkt_expected, srs.ExportToWkt()), \ + 'did not get expected wkt.' p4 = srs.ExportToProj4() srs2 = osr.SpatialReference() srs2.ImportFromProj4(p4) if not srs.IsSame(srs2): - gdaltest.post_reason('round trip via PROJ.4 damaged srs?') print(srs.ExportToPrettyWkt()) print(srs2.ExportToPrettyWkt()) - return 'fail' - - return 'success' + pytest.fail('round trip via PROJ.4 damaged srs?') + ############################################################################### # Test round-tripping of all supported projection methods # -def osr_proj4_11(): +def test_osr_proj4_11(): proj4strlist = ['+proj=bonne +lon_0=2 +lat_1=1 +x_0=3 +y_0=4', '+proj=cass +lat_0=1 +lon_0=2 +x_0=3 +y_0=4', @@ -486,26 +448,20 @@ def osr_proj4_11(): # print(proj4str) srs.ImportFromProj4(proj4str) if srs.Validate() != 0: - gdaltest.post_reason('does not validate') print(proj4str) print(srs.ExportToPrettyWkt()) - return 'fail' + pytest.fail('does not validate') out = srs.ExportToProj4() - if out != proj4str: - gdaltest.post_reason('round trip via PROJ.4 failed') - print(proj4str) - print(out) - return 'fail' - - return 'success' + assert out == proj4str, 'round trip via PROJ.4 failed' + ############################################################################### # Test importing +init=epsg:XXX # -def osr_proj4_12(): +def test_osr_proj4_12(): expect_wkt = """GEOGCS["WGS 84", DATUM["WGS_1984", @@ -525,17 +481,15 @@ def osr_proj4_12(): if wkt.find("""GEOGCS["WGS 84""") != 0: print('Got:%s' % wkt) print('Expected:%s' % expect_wkt) - gdaltest.post_reason('Did not get expected result.') - return 'fail' - - return 'success' + pytest.fail('Did not get expected result.') + ############################################################################### # Test error cases # -def osr_proj4_13(): +def test_osr_proj4_13(): proj4strlist = ['', # None, @@ -552,18 +506,16 @@ def osr_proj4_13(): gdal.ErrorReset() if srs.ImportFromProj4(proj4str) == 0 and gdal.GetLastErrorMsg() == '': gdal.PopErrorHandler() - return 'fail' + pytest.fail() gdal.PopErrorHandler() - return 'success' - ############################################################################### # Test etmerc (#4853) # -def osr_proj4_14(): +def test_osr_proj4_14(): proj4str = '+proj=etmerc +lat_0=0 +lon_0=9 +k=0.9996 +units=m +x_0=500000 +datum=WGS84 +nodefs' @@ -593,8 +545,7 @@ def osr_proj4_14(): if wkt != expect_wkt: print('Got:%s' % wkt) print('Expected:%s' % expect_wkt) - gdaltest.post_reason('Did not get expected result.') - return 'fail' + pytest.fail('Did not get expected result.') srs = osr.SpatialReference() srs.ImportFromEPSG(32600 + 32) @@ -605,8 +556,7 @@ def osr_proj4_14(): if proj4str != expect_proj4str: print('Got:%s' % proj4str) print('Expected:%s' % expect_proj4str) - gdaltest.post_reason('Did not get expected result.') - return 'fail' + pytest.fail('Did not get expected result.') # Test exporting standard Transverse_Mercator, with OSR_USE_ETMERC=YES gdal.SetConfigOption('OSR_USE_ETMERC', 'YES') @@ -616,8 +566,7 @@ def osr_proj4_14(): if proj4str != expect_proj4str: print('Got:%s' % proj4str) print('Expected:%s' % expect_proj4str) - gdaltest.post_reason('Did not get expected result.') - return 'fail' + pytest.fail('Did not get expected result.') # Test exporting standard Transverse_Mercator, with OSR_USE_ETMERC=NO gdal.SetConfigOption('OSR_USE_ETMERC', 'NO') @@ -627,40 +576,30 @@ def osr_proj4_14(): if proj4str != expect_proj4str: print('Got:%s' % proj4str) print('Expected:%s' % expect_proj4str) - gdaltest.post_reason('Did not get expected result.') - return 'fail' - - return 'success' + pytest.fail('Did not get expected result.') + ############################################################################### # Test other authorities than EPSG, e.g. IGNF:XXXX # -def osr_proj4_15(): +def test_osr_proj4_15(): srs = osr.SpatialReference() if srs.ImportFromProj4("+init=IGNF:LAMB93") != 0: - return 'skip' + pytest.skip() - if srs.GetAuthorityName(None) != 'IGNF' or srs.GetAuthorityCode(None) != 'LAMB93': - gdaltest.post_reason('fail') - print(srs) - return 'fail' + assert srs.GetAuthorityName(None) == 'IGNF' and srs.GetAuthorityCode(None) == 'LAMB93' - if srs.Validate() != 0: - gdaltest.post_reason('fail') - print(srs) - return 'fail' - - return 'success' + assert srs.Validate() == 0 ############################################################################### # Test unit parsing # -def osr_proj4_16(): +def test_osr_proj4_16(): def almost(a, b): if abs(a - b) > 0.000000000001: @@ -690,20 +629,17 @@ def almost(a, b): srs = osr.SpatialReference() for u in units: - if srs.ImportFromProj4('+proj=utm +zone=11 +datum=WGS84 +units=%s' % u[0]) != 0: - return 'fail' + assert srs.ImportFromProj4('+proj=utm +zone=11 +datum=WGS84 +units=%s' % u[0]) == 0 to_met = srs.GetLinearUnits() - if not almost(to_met, u[1]): - gdaltest.post_reason('Did not get expected units: %s vs %s' % (str(u), str(to_met))) - return 'fail' - return 'success' - + assert almost(to_met, u[1]), \ + ('Did not get expected units: %s vs %s' % (str(u), str(to_met))) + ############################################################################### # Test unit parsing for name assignment # -def osr_proj4_17(): +def test_osr_proj4_17(): units = (('km', 'kilometre'), ('m', 'Meter'), @@ -729,87 +665,69 @@ def osr_proj4_17(): srs = osr.SpatialReference() for u in units: - if srs.ImportFromProj4('+proj=utm +zone=11 +datum=WGS84 +units=%s' % u[0]) != 0: - return 'fail' + assert srs.ImportFromProj4('+proj=utm +zone=11 +datum=WGS84 +units=%s' % u[0]) == 0 unit_name = srs.GetLinearUnitsName() - if unit_name != u[1]: - gdaltest.post_reason('Did not get expected unit name: %s vs %s' % (str(u), str(unit_name))) - return 'fail' - return 'success' - + assert unit_name == u[1], \ + ('Did not get expected unit name: %s vs %s' % (str(u), str(unit_name))) + ############################################################################### # Test fix for #5511 # -def osr_proj4_18(): +def test_osr_proj4_18(): for p in ['no_off', 'no_uoff']: srs = osr.SpatialReference() srs.ImportFromProj4('+proj=omerc +lat_0=57 +lonc=-133 +alpha=-36 +k=0.9999 +x_0=5000000 +y_0=-5000000 +%s +datum=NAD83 +units=m +no_defs' % p) if srs.Validate() != 0: - gdaltest.post_reason('does not validate') print(srs.ExportToPrettyWkt()) - return 'fail' + pytest.fail('does not validate') out = srs.ExportToProj4() proj4str = '+proj=omerc +lat_0=57 +lonc=-133 +alpha=-36 +k=0.9999 +x_0=5000000 +y_0=-5000000 +no_uoff +gamma=-36 +ellps=GRS80 +towgs84=0,0,0,0,0,0,0 +units=m +no_defs ' if out != proj4str: - gdaltest.post_reason('round trip via PROJ.4 failed') print(p) - print(proj4str) - print(out) - return 'fail' - - return 'success' + pytest.fail('round trip via PROJ.4 failed') + ############################################################################### # Test EXTENSION and AUTHORITY in DATUM -def osr_proj4_19(): +def test_osr_proj4_19(): srs = osr.SpatialReference() srs.ImportFromProj4("+proj=longlat +datum=WGS84 +nadgrids=@null") - if srs.ExportToWkt() != 'GEOGCS["WGS 84",DATUM["WGS_1984",SPHEROID["WGS 84",6378137,298.257223563,AUTHORITY["EPSG","7030"]],EXTENSION["PROJ4_GRIDS","@null"],AUTHORITY["EPSG","6326"]],PRIMEM["Greenwich",0,AUTHORITY["EPSG","8901"]],UNIT["degree",0.0174532925199433,AUTHORITY["EPSG","9122"]],AUTHORITY["EPSG","4326"]]': - gdaltest.post_reason('fail') - print(srs.ExportToWkt()) - return 'fail' + assert srs.ExportToWkt() == 'GEOGCS["WGS 84",DATUM["WGS_1984",SPHEROID["WGS 84",6378137,298.257223563,AUTHORITY["EPSG","7030"]],EXTENSION["PROJ4_GRIDS","@null"],AUTHORITY["EPSG","6326"]],PRIMEM["Greenwich",0,AUTHORITY["EPSG","8901"]],UNIT["degree",0.0174532925199433,AUTHORITY["EPSG","9122"]],AUTHORITY["EPSG","4326"]]' if srs.Validate() != 0: - gdaltest.post_reason('does not validate') print(srs.ExportToPrettyWkt()) - return 'fail' - - return 'success' + pytest.fail('does not validate') + ############################################################################### # Test EXTENSION in GOGCS -def osr_proj4_20(): +def test_osr_proj4_20(): srs = osr.SpatialReference() srs.ImportFromProj4("+proj=longlat +foo=bar +wktext") - if srs.ExportToWkt() != 'GEOGCS["WGS 84",DATUM["unknown",SPHEROID["WGS84",6378137,298.257223563]],PRIMEM["Greenwich",0],UNIT["degree",0.0174532925199433],EXTENSION["PROJ4","+proj=longlat +foo=bar +wktext"]]' and \ - srs.ExportToWkt() != 'GEOGCS["unnamed ellipse",DATUM["unknown",SPHEROID["unnamed",6378137,298.257223563]],PRIMEM["Greenwich",0],UNIT["degree",0.0174532925199433],EXTENSION["PROJ4","+proj=longlat +foo=bar +wktext"]]': - gdaltest.post_reason('fail') - print(srs.ExportToWkt()) - return 'fail' + assert (srs.ExportToWkt() == 'GEOGCS["WGS 84",DATUM["unknown",SPHEROID["WGS84",6378137,298.257223563]],PRIMEM["Greenwich",0],UNIT["degree",0.0174532925199433],EXTENSION["PROJ4","+proj=longlat +foo=bar +wktext"]]' or \ + srs.ExportToWkt() == 'GEOGCS["unnamed ellipse",DATUM["unknown",SPHEROID["unnamed",6378137,298.257223563]],PRIMEM["Greenwich",0],UNIT["degree",0.0174532925199433],EXTENSION["PROJ4","+proj=longlat +foo=bar +wktext"]]') if srs.Validate() != 0: - gdaltest.post_reason('does not validate') print(srs.ExportToPrettyWkt()) - return 'fail' - - return 'success' + pytest.fail('does not validate') + ############################################################################### # Test importing datum other than WGS84, WGS72, NAD27 or NAD83 -def osr_proj4_21(): +def test_osr_proj4_21(): srs = osr.SpatialReference() srs.ImportFromProj4("+proj=longlat +datum=nzgd49") @@ -818,246 +736,176 @@ def osr_proj4_21(): got = srs.ExportToProj4() gdal.SetConfigOption('OVERRIDE_PROJ_DATUM_WITH_TOWGS84', None) - if got.find('+proj=longlat +datum=nzgd49') != 0: - gdaltest.post_reason('fail') - print(got) - return 'fail' - - return 'success' + assert got.find('+proj=longlat +datum=nzgd49') == 0 ############################################################################### # Test importing ellipsoid defined with +R -def osr_proj4_22(): +def test_osr_proj4_22(): srs = osr.SpatialReference() srs.ImportFromProj4("+proj=longlat +R=1") got = srs.ExportToProj4() - if got.find('+proj=longlat +a=1 +b=1') != 0: - gdaltest.post_reason('fail') - print(got) - return 'fail' - - return 'success' + assert got.find('+proj=longlat +a=1 +b=1') == 0 ############################################################################### # Test importing ellipsoid defined with +a and +f -def osr_proj4_23(): +def test_osr_proj4_23(): # +f=0 particular case srs = osr.SpatialReference() srs.ImportFromProj4("+proj=longlat +a=1 +f=0") got = srs.ExportToProj4() - if got.find('+proj=longlat +a=1 +b=1') != 0: - gdaltest.post_reason('fail') - print(got) - return 'fail' + assert got.find('+proj=longlat +a=1 +b=1') == 0 srs = osr.SpatialReference() srs.ImportFromProj4("+proj=longlat +a=2 +f=0.5") got = srs.ExportToProj4() - if got.find('+proj=longlat +a=2 +b=1') != 0: - gdaltest.post_reason('fail') - print(got) - return 'fail' - - return 'success' + assert got.find('+proj=longlat +a=2 +b=1') == 0 ############################################################################### # Test importing linear units defined with +to_meter -def osr_proj4_24(): +def test_osr_proj4_24(): srs = osr.SpatialReference() srs.ImportFromProj4("+proj=merc +to_meter=1.0") got = srs.ExportToProj4() - if got.find('+units=m') < 0: - gdaltest.post_reason('fail') - print(got) - return 'fail' + assert got.find('+units=m') >= 0 # Intl foot srs = osr.SpatialReference() srs.ImportFromProj4("+proj=merc +to_meter=0.3048") got = srs.ExportToProj4() - if got.find('+units=ft') < 0: - gdaltest.post_reason('fail') - print(got) - return 'fail' + assert got.find('+units=ft') >= 0 # US foot srs = osr.SpatialReference() srs.ImportFromProj4("+proj=merc +to_meter=0.3048006096012192") got = srs.ExportToProj4() - if got.find('+units=us-ft') < 0: - gdaltest.post_reason('fail') - print(got) - return 'fail' + assert got.find('+units=us-ft') >= 0 # unknown srs = osr.SpatialReference() srs.ImportFromProj4("+proj=merc +to_meter=0.4") got = srs.ExportToProj4() - if got.find('+to_meter=0.4') < 0: - gdaltest.post_reason('fail') - print(got) - return 'fail' - - return 'success' + assert got.find('+to_meter=0.4') >= 0 ############################################################################### # Test importing linear units defined with +vto_meter -def osr_proj4_25(): +def test_osr_proj4_25(): if not have_proj480(): - return 'skip' + pytest.skip() srs = osr.SpatialReference() srs.ImportFromProj4("+proj=merc +geoidgrids=foo +vto_meter=1.0") got = srs.ExportToProj4() - if got.find('+vunits=m') < 0: - gdaltest.post_reason('fail') - print(got) - return 'fail' + assert got.find('+vunits=m') >= 0 # Intl foot srs = osr.SpatialReference() srs.ImportFromProj4("+proj=merc +geoidgrids=foo +vto_meter=0.3048") got = srs.ExportToProj4() - if got.find('+vunits=ft') < 0: - gdaltest.post_reason('fail') - print(got) - return 'fail' + assert got.find('+vunits=ft') >= 0 # US foot srs = osr.SpatialReference() srs.ImportFromProj4("+proj=merc +geoidgrids=foo +vto_meter=0.3048006096012192") got = srs.ExportToProj4() - if got.find('+vunits=us-ft') < 0: - gdaltest.post_reason('fail') - print(got) - return 'fail' + assert got.find('+vunits=us-ft') >= 0 # Unknown srs = osr.SpatialReference() srs.ImportFromProj4("+proj=merc +geoidgrids=foo +vto_meter=0.4") got = srs.ExportToProj4() - if got.find('+vto_meter=0.4') < 0: - gdaltest.post_reason('fail') - print(got) - return 'fail' - - return 'success' + assert got.find('+vto_meter=0.4') >= 0 ############################################################################### # Test importing linear units defined with +vunits -def osr_proj4_26(): +def test_osr_proj4_26(): if not have_proj480(): - return 'skip' + pytest.skip() srs = osr.SpatialReference() srs.ImportFromProj4("+proj=merc +geoidgrids=foo +vunits=m") got = srs.ExportToProj4() - if got.find('+vunits=m') < 0: - gdaltest.post_reason('fail') - print(got) - return 'fail' + assert got.find('+vunits=m') >= 0 # Intl foot srs = osr.SpatialReference() srs.ImportFromProj4("+proj=merc +geoidgrids=foo +vunits=ft") got = srs.ExportToProj4() - if got.find('+vunits=ft') < 0: - gdaltest.post_reason('fail') - print(got) - return 'fail' + assert got.find('+vunits=ft') >= 0 # US yard srs = osr.SpatialReference() srs.ImportFromProj4("+proj=merc +geoidgrids=foo +vunits=us-yd") got = srs.ExportToProj4() - if got.find('+vunits=us-yd') < 0: - gdaltest.post_reason('fail') - print(got) - return 'fail' - - return 'success' + assert got.find('+vunits=us-yd') >= 0 ############################################################################### # Test geostationary +sweep (#6030) -def osr_proj4_27(): +def test_osr_proj4_27(): if not have_proj480(): - return 'skip' + pytest.skip() srs = osr.SpatialReference() srs.ImportFromProj4("+proj=geos +h=35785831 +lon_0=0 +datum=WGS84 +sweep=x +units=m") got = srs.ExportToProj4() - if got.find('+proj=geos +h=35785831 +lon_0=0 +datum=WGS84 +sweep=x +units=m') < 0: - gdaltest.post_reason('fail') - print(got) - return 'fail' - - return 'success' + assert got.find('+proj=geos +h=35785831 +lon_0=0 +datum=WGS84 +sweep=x +units=m') >= 0 ############################################################################### # Test importing +init=epsg: with an override -def osr_proj4_28(): +def test_osr_proj4_28(): srs = osr.SpatialReference() srs.ImportFromProj4("+init=epsg:32631 +units=cm") got = srs.ExportToWkt() - if got.find('32631') >= 0: - gdaltest.post_reason('fail') - print(got) - return 'fail' - - return 'success' + assert got.find('32631') < 0 -def osr_proj4_28_missing_proj_epsg_dict(): +def test_osr_proj4_28_missing_proj_epsg_dict(): python_exe = sys.executable if sys.platform == 'win32': python_exe = python_exe.replace('\\', '/') ret = gdaltest.runexternal(python_exe + ' osr_proj4.py osr_proj4_28') - if ret.find('fail') >= 0: - print(ret) - return 'fail' - return 'success' + assert ret.find('fail') < 0 -def osr_proj4_error_cases_export_mercator(): +def test_osr_proj4_error_cases_export_mercator(): srs = osr.SpatialReference() @@ -1065,66 +913,14 @@ def osr_proj4_error_cases_export_mercator(): srs.SetMercator(30.0, 0.0, 0.99, 0.0, 0.0) with gdaltest.error_handler(): got = srs.ExportToProj4() - if got != '': - gdaltest.post_reason('fail') - print(got) - return 'fail' + assert got == '' # latitude_of_origin != 0.0 srs.SetMercator2SP(0.0, 40.0, 0.0, 0.0, 0.0) with gdaltest.error_handler(): got = srs.ExportToProj4() - if got != '': - gdaltest.post_reason('fail') - print(got) - return 'fail' - - return 'success' - - -gdaltest_list = [ - osr_proj4_1, - osr_proj4_2, - osr_proj4_3, - osr_proj4_4, - osr_proj4_5, - osr_proj4_6, - osr_proj4_7, - osr_proj4_8, - osr_proj4_9, - osr_proj4_10, - osr_proj4_11, - osr_proj4_12, - osr_proj4_13, - osr_proj4_14, - osr_proj4_15, - osr_proj4_16, - osr_proj4_17, - osr_proj4_18, - osr_proj4_19, - osr_proj4_20, - osr_proj4_21, - osr_proj4_22, - osr_proj4_23, - osr_proj4_24, - osr_proj4_25, - osr_proj4_26, - osr_proj4_27, - osr_proj4_28, - osr_proj4_28_missing_proj_epsg_dict, - osr_proj4_error_cases_export_mercator, -] - - -if __name__ == '__main__': - - if len(sys.argv) == 2 and sys.argv[1] == "osr_proj4_28": - os.putenv('PROJ_LIB', '/i/dont_exist') - gdaltest.run_tests([osr_proj4_28]) - sys.exit(0) - - gdaltest.setup_run('osr_proj4') - - gdaltest.run_tests(gdaltest_list) - - sys.exit(gdaltest.summarize()) + assert got == '' + + + + diff --git a/autotest/osr/osr_url.py b/autotest/osr/osr_url.py index 82de82703d4e..381d2c8953a1 100755 --- a/autotest/osr/osr_url.py +++ b/autotest/osr/osr_url.py @@ -29,13 +29,12 @@ # DEALINGS IN THE SOFTWARE. ############################################################################### -import sys import socket -sys.path.append('../pymod') import gdaltest from osgeo import osr +import pytest expected_wkt = 'GEOGCS["WGS 84",DATUM["WGS_1984",SPHEROID["WGS 84",6378137,298.257223563,AUTHORITY["EPSG","7030"]],AUTHORITY["EPSG","6326"]],PRIMEM["Greenwich",0,AUTHORITY["EPSG","8901"]],UNIT["degree",0.01745329251994328,AUTHORITY["EPSG","9122"]],AUTHORITY["EPSG","4326"]]' @@ -44,7 +43,7 @@ def osr_url_test(url, expected_wkt): timeout = 10 socket.setdefaulttimeout(timeout) if gdaltest.gdalurlopen(url) is None: - return 'skip' + pytest.skip() # Depend on the Accepts headers that ImportFromUrl sets to request SRS from sr.org srs = osr.SpatialReference() @@ -53,44 +52,29 @@ def osr_url_test(url, expected_wkt): try: srs.ImportFromUrl(url) except AttributeError: # old-gen bindings don't have this method yet - return 'skip' + pytest.skip() except Exception: gdal.PopErrorHandler() if gdal.GetLastErrorMsg() == "GDAL/OGR not compiled with libcurl support, remote requests not supported." or \ gdal.GetLastErrorMsg().find("timed out") != -1: - return 'skip' - gdaltest.post_reason('exception: ' + gdal.GetLastErrorMsg()) - return 'fail' + pytest.skip() + pytest.fail('exception: ' + gdal.GetLastErrorMsg()) gdal.PopErrorHandler() if gdal.GetLastErrorMsg() == "GDAL/OGR not compiled with libcurl support, remote requests not supported." or \ gdal.GetLastErrorMsg().find("timed out") != -1: - return 'skip' + pytest.skip() - if not gdaltest.equal_srs_from_wkt(expected_wkt, - srs.ExportToWkt()): - return 'fail' + assert gdaltest.equal_srs_from_wkt(expected_wkt, + srs.ExportToWkt()) - return 'success' - -def osr_url_1(): +def test_osr_url_1(): return osr_url_test('http://spatialreference.org/ref/epsg/4326/', expected_wkt) -def osr_url_2(): +def test_osr_url_2(): return osr_url_test('http://spatialreference.org/ref/epsg/4326/ogcwkt/', expected_wkt) -gdaltest_list = [ - osr_url_1, - osr_url_2, - None] - -if __name__ == '__main__': - - gdaltest.setup_run('osr_url') - - gdaltest.run_tests(gdaltest_list) - sys.exit(gdaltest.summarize()) diff --git a/autotest/osr/osr_usgs.py b/autotest/osr/osr_usgs.py index bb8d083d3486..c71a7b229b3e 100755 --- a/autotest/osr/osr_usgs.py +++ b/autotest/osr/osr_usgs.py @@ -28,11 +28,8 @@ # DEALINGS IN THE SOFTWARE. ############################################################################### -import sys -sys.path.append('../pymod') -import gdaltest from osgeo import gdal from osgeo import osr @@ -41,7 +38,7 @@ # -def osr_usgs_1(): +def test_osr_usgs_1(): srs = osr.SpatialReference() srs.ImportFromUSGS( @@ -52,23 +49,15 @@ def osr_usgs_1(): 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0), 15) - if abs(srs.GetProjParm(osr.SRS_PP_STANDARD_PARALLEL_1) - 47.0) > 0.0000005 \ - or abs(srs.GetProjParm(osr.SRS_PP_STANDARD_PARALLEL_2) - 62.0) > 0.0000005 \ - or abs(srs.GetProjParm(osr.SRS_PP_LATITUDE_OF_CENTER) - 54.5) > 0.0000005 \ - or abs(srs.GetProjParm(osr.SRS_PP_LONGITUDE_OF_CENTER) - 45.0) > 0.0000005 \ - or abs(srs.GetProjParm(osr.SRS_PP_FALSE_EASTING) - 0.0) > 0.0000005 \ - or abs(srs.GetProjParm(osr.SRS_PP_FALSE_NORTHING) - 0.0) > 0.0000005: - gdaltest.post_reason('Can not import Equidistant Conic projection.') - return 'fail' - - return 'success' + assert abs(srs.GetProjParm(osr.SRS_PP_STANDARD_PARALLEL_1) - 47.0) <= 0.0000005 and abs(srs.GetProjParm(osr.SRS_PP_STANDARD_PARALLEL_2) - 62.0) <= 0.0000005 and abs(srs.GetProjParm(osr.SRS_PP_LATITUDE_OF_CENTER) - 54.5) <= 0.0000005 and abs(srs.GetProjParm(osr.SRS_PP_LONGITUDE_OF_CENTER) - 45.0) <= 0.0000005 and abs(srs.GetProjParm(osr.SRS_PP_FALSE_EASTING) - 0.0) <= 0.0000005 and abs(srs.GetProjParm(osr.SRS_PP_FALSE_NORTHING) - 0.0) <= 0.0000005, \ + 'Can not import Equidistant Conic projection.' ############################################################################### # Test the osr.SpatialReference.ExportToUSGS() function. # -def osr_usgs_2(): +def test_osr_usgs_2(): srs = osr.SpatialReference() srs.ImportFromWkt("""PROJCS["unnamed",GEOGCS["NAD27",\ @@ -86,26 +75,8 @@ def osr_usgs_2(): (proj_code, _, parms, datum_code) = srs.ExportToUSGS() - if proj_code != 4 or datum_code != 0 \ - or abs(gdal.PackedDMSToDec(parms[2]) - 33.90363403) > 0.0000005 \ - or abs(gdal.PackedDMSToDec(parms[3]) - 33.62529003) > 0.0000005 \ - or abs(gdal.PackedDMSToDec(parms[4]) - -117.4745429) > 0.0000005 \ - or abs(gdal.PackedDMSToDec(parms[5]) - 33.76446203) > 0.0000005: - gdaltest.post_reason('Can not import Lambert Conformal Conic projection.') - return 'fail' - - return 'success' - - -gdaltest_list = [ - osr_usgs_1, - osr_usgs_2, - None] - -if __name__ == '__main__': + assert proj_code == 4 and datum_code == 0 and abs(gdal.PackedDMSToDec(parms[2]) - 33.90363403) <= 0.0000005 and abs(gdal.PackedDMSToDec(parms[3]) - 33.62529003) <= 0.0000005 and abs(gdal.PackedDMSToDec(parms[4]) - -117.4745429) <= 0.0000005 and abs(gdal.PackedDMSToDec(parms[5]) - 33.76446203) <= 0.0000005, \ + 'Can not import Lambert Conformal Conic projection.' - gdaltest.setup_run('osr_usgs') - gdaltest.run_tests(gdaltest_list) - sys.exit(gdaltest.summarize()) diff --git a/autotest/osr/osr_validate.py b/autotest/osr/osr_validate.py index 364dc53c6602..e1b0e63b84f0 100755 --- a/autotest/osr/osr_validate.py +++ b/autotest/osr/osr_validate.py @@ -29,287 +29,223 @@ # DEALINGS IN THE SOFTWARE. ############################################################################### -import sys -sys.path.append('../pymod') -import gdaltest from osgeo import osr ############################################################################### # No root pointer -def osr_validate_1(): +def test_osr_validate_1(): empty_srs = osr.SpatialReference() - if empty_srs.Validate() == 0: - return 'fail' - - return 'success' + assert empty_srs.Validate() != 0 ############################################################################### # Unrecognized root node -def osr_validate_2(): +def test_osr_validate_2(): srs = osr.SpatialReference() srs.ImportFromWkt("FOO[]") - if srs.Validate() == 0: - return 'fail' - - return 'success' + assert srs.Validate() != 0 ############################################################################### # COMPD_CS errors -def osr_validate_3(): +def test_osr_validate_3(): # No DATUM child in GEOGCS srs = osr.SpatialReference() srs.ImportFromWkt("""COMPD_CS[]""") # 5 is OGRERR_CORRUPT_DATA. - if srs.Validate() == 0: - return 'fail' + assert srs.Validate() != 0 srs.ImportFromWkt("""COMPD_CS["MYNAME",GEOGCS[]]""") - if srs.Validate() == 0: - return 'fail' + assert srs.Validate() != 0 # AUTHORITY has wrong number of children (1), not 2. srs = osr.SpatialReference() srs.ImportFromWkt("""COMPD_CS["MYNAME",AUTHORITY[]]""") - if srs.Validate() == 0: - return 'fail' + assert srs.Validate() != 0 # Unexpected child for COMPD_CS `FOO' srs = osr.SpatialReference() srs.ImportFromWkt("""COMPD_CS["MYNAME",FOO[]]""") - if srs.Validate() == 0: - return 'fail' - - return 'success' + assert srs.Validate() != 0 ############################################################################### # VERT_CS errors -def osr_validate_4(): +def test_osr_validate_4(): # Invalid number of children : 1 srs = osr.SpatialReference() srs.ImportFromWkt("""VERT_CS["MYNAME",VERT_DATUM[]]""") - if srs.Validate() == 0: - return 'fail' + assert srs.Validate() != 0 # UNIT has wrong number of children (1), not 2 srs = osr.SpatialReference() srs.ImportFromWkt("""VERT_CS["MYNAME",UNIT[]]""") - if srs.Validate() == 0: - return 'fail' + assert srs.Validate() != 0 # AXIS has wrong number of children (1), not 2 srs = osr.SpatialReference() srs.ImportFromWkt("""VERT_CS["MYNAME",AXIS[]]""") - if srs.Validate() == 0: - return 'fail' + assert srs.Validate() != 0 # AUTHORITY has wrong number of children (1), not 2 srs = osr.SpatialReference() srs.ImportFromWkt("""VERT_CS["MYNAME",AUTHORITY[]]""") - if srs.Validate() == 0: - return 'fail' + assert srs.Validate() != 0 # Unexpected child for VERT_CS `FOO' srs = osr.SpatialReference() srs.ImportFromWkt("""VERT_CS["MYNAME",FOO[]]""") - if srs.Validate() == 0: - return 'fail' + assert srs.Validate() != 0 # No VERT_DATUM child in VERT_CS srs = osr.SpatialReference() srs.ImportFromWkt("""VERT_CS["MYNAME"]""") - if srs.Validate() == 0: - return 'fail' + assert srs.Validate() != 0 # No UNIT child in VERT_CS srs = osr.SpatialReference() srs.ImportFromWkt("""VERT_CS["MYNAME",VERT_DATUM["MYNAME",2005,AUTHORITY["EPSG","0"]]]""") - if srs.Validate() == 0: - return 'fail' + assert srs.Validate() != 0 # Too many AXIS children in VERT_CS srs = osr.SpatialReference() srs.ImportFromWkt("""VERT_CS["MYNAME",VERT_DATUM["MYNAME",2005,AUTHORITY["EPSG","0"]],UNIT["metre",1],AXIS["foo",foo],AXIS["bar",bar]]""") - if srs.Validate() == 0: - return 'fail' - - return 'success' + assert srs.Validate() != 0 ############################################################################### # GEOCCS errors -def osr_validate_5(): +def test_osr_validate_5(): # srs.ImportFromWkt('GEOCCS["My Geocentric",DATUM["WGS_1984",SPHEROID["WGS 84",6378137,298.257223563,AUTHORITY["EPSG","7030"]],TOWGS84[0,0,0,0,0,0,0],AUTHORITY["EPSG","6326"]],PRIMEM["Greenwich",0,AUTHORITY["EPSG","8901"]],UNIT["meter",1]]') # PRIMEM has wrong number of children (1),not 2 or 3 as expected srs = osr.SpatialReference() srs.ImportFromWkt('GEOCCS["My Geocentric",DATUM["WGS_1984",SPHEROID["WGS 84",6378137,298.257223563,AUTHORITY["EPSG","7030"]],TOWGS84[0,0,0,0,0,0,0],AUTHORITY["EPSG","6326"]],PRIMEM[],UNIT["meter",1]]') - if srs.Validate() == 0: - return 'fail' + assert srs.Validate() != 0 # UNIT has wrong number of children (1), not 2 srs = osr.SpatialReference() srs.ImportFromWkt('GEOCCS["My Geocentric",DATUM["WGS_1984",SPHEROID["WGS 84",6378137,298.257223563,AUTHORITY["EPSG","7030"]],TOWGS84[0,0,0,0,0,0,0],AUTHORITY["EPSG","6326"]],PRIMEM["Greenwich",0,AUTHORITY["EPSG","8901"]],UNIT[]]') - if srs.Validate() == 0: - return 'fail' + assert srs.Validate() != 0 # AXIS has wrong number of children (1), not 2 srs = osr.SpatialReference() srs.ImportFromWkt('GEOCCS["My Geocentric",DATUM["WGS_1984",SPHEROID["WGS 84",6378137,298.257223563,AUTHORITY["EPSG","7030"]],TOWGS84[0,0,0,0,0,0,0],AUTHORITY["EPSG","6326"]],AXIS[],PRIMEM["Greenwich",0,AUTHORITY["EPSG","8901"]],UNIT["meter",1]]') - if srs.Validate() == 0: - return 'fail' + assert srs.Validate() != 0 # AUTHORITY has wrong number of children (1), not 2 srs = osr.SpatialReference() srs.ImportFromWkt('GEOCCS["My Geocentric",DATUM["WGS_1984",SPHEROID["WGS 84",6378137,298.257223563,AUTHORITY["EPSG","7030"]],TOWGS84[0,0,0,0,0,0,0],AUTHORITY["EPSG","6326"]],PRIMEM["Greenwich",0,AUTHORITY["EPSG","8901"]],UNIT["meter",1],AUTHORITY[]]') - if srs.Validate() == 0: - return 'fail' + assert srs.Validate() != 0 # Unexpected child for GEOCCS `FOO' srs = osr.SpatialReference() srs.ImportFromWkt('GEOCCS["My Geocentric",FOO[]]') - if srs.Validate() == 0: - return 'fail' + assert srs.Validate() != 0 # No DATUM child in GEOCCS srs = osr.SpatialReference() srs.ImportFromWkt('GEOCCS["My Geocentric"]') - if srs.Validate() == 0: - return 'fail' + assert srs.Validate() != 0 # No PRIMEM child in GEOCCS srs = osr.SpatialReference() srs.ImportFromWkt('GEOCCS["My Geocentric",DATUM["WGS_1984",SPHEROID["WGS 84",6378137,298.257223563,AUTHORITY["EPSG","7030"]]]]') - if srs.Validate() == 0: - return 'fail' + assert srs.Validate() != 0 # No UNIT child in GEOCCS srs = osr.SpatialReference() srs.ImportFromWkt('GEOCCS["My Geocentric",DATUM["WGS_1984",SPHEROID["WGS 84",6378137,298.257223563,AUTHORITY["EPSG","7030"]]],PRIMEM["Greenwich",0]]') - if srs.Validate() == 0: - return 'fail' + assert srs.Validate() != 0 # Wrong number of AXIS children in GEOCCS srs = osr.SpatialReference() srs.ImportFromWkt('GEOCCS["My Geocentric",DATUM["WGS_1984",SPHEROID["WGS 84",6378137,298.257223563,AUTHORITY["EPSG","7030"]],TOWGS84[0,0,0,0,0,0,0],AUTHORITY["EPSG","6326"]],PRIMEM["Greenwich",0,AUTHORITY["EPSG","8901"]],AXIS["foo",foo],UNIT["meter",1]]') - if srs.Validate() == 0: - return 'fail' - - return 'success' + assert srs.Validate() != 0 ############################################################################### # PROJCS errors -def osr_validate_6(): +def test_osr_validate_6(): # srs.ImportFromWkt('PROJCS["WGS 84 / UTM zone 31N",GEOGCS["WGS 84",DATUM["WGS_1984",SPHEROID["WGS 84",6378137,298.257223563,AUTHORITY["EPSG","7030"]],AUTHORITY["EPSG","6326"]],PRIMEM["Greenwich",0,AUTHORITY["EPSG","8901"]],UNIT["degree",0.0174532925199433,AUTHORITY["EPSG","9122"]],AUTHORITY["EPSG","4326"]],PROJECTION["Transverse_Mercator"],PARAMETER["latitude_of_origin",0],PARAMETER["central_meridian",3],PARAMETER["scale_factor",0.9996],PARAMETER["false_easting",500000],PARAMETER["false_northing",0],UNIT["metre",1,AUTHORITY["EPSG","9001"]],AXIS["Easting",EAST],AXIS["Northing",NORTH],AUTHORITY["EPSG","32631"]]') # UNIT has wrong number of children (1), not 2 srs = osr.SpatialReference() srs.ImportFromWkt('PROJCS["WGS 84 / UTM zone 31N",UNIT[]]') - if srs.Validate() == 0: - return 'fail' + assert srs.Validate() != 0 # PARAMETER has wrong number of children (1),not 2 as expected srs = osr.SpatialReference() srs.ImportFromWkt('PROJCS["WGS 84 / UTM zone 31N",PARAMETER[]]') - if srs.Validate() == 0: - return 'fail' + assert srs.Validate() != 0 # Unrecognized PARAMETER `foo' srs = osr.SpatialReference() srs.ImportFromWkt('PROJCS["WGS 84 / UTM zone 31N",PARAMETER["foo",0]]') - if srs.Validate() == 0: - return 'fail' + assert srs.Validate() != 0 # PROJECTION has wrong number of children (0),not 1 or 2 as expected srs = osr.SpatialReference() srs.ImportFromWkt('PROJCS["WGS 84 / UTM zone 31N",PROJECTION]') - if srs.Validate() == 0: - return 'fail' + assert srs.Validate() != 0 # Unrecognized PROJECTION `foo' srs = osr.SpatialReference() srs.ImportFromWkt('PROJCS["WGS 84 / UTM zone 31N",PROJECTION["foo"]]') - if srs.Validate() == 0: - return 'fail' + assert srs.Validate() != 0 # Unsupported, but recognised PROJECTION `Tunisia_Mining_Grid' srs = osr.SpatialReference() srs.ImportFromWkt('PROJCS["WGS 84 / UTM zone 31N",PROJECTION["Tunisia_Mining_Grid"]]') - if srs.Validate() == 0: - return 'fail' + assert srs.Validate() != 0 # Unexpected child for PROJECTION `FOO' srs = osr.SpatialReference() srs.ImportFromWkt('PROJCS["WGS 84 / UTM zone 31N",PROJECTION["Transverse_Mercator", FOO]]') - if srs.Validate() == 0: - return 'fail' + assert srs.Validate() != 0 # AUTHORITY has wrong number of children (0), not 2 srs = osr.SpatialReference() srs.ImportFromWkt('PROJCS["WGS 84 / UTM zone 31N",PROJECTION["Transverse_Mercator", AUTHORITY]]') - if srs.Validate() == 0: - return 'fail' + assert srs.Validate() != 0 # AUTHORITY has wrong number of children (0), not 2 srs = osr.SpatialReference() srs.ImportFromWkt('PROJCS["WGS 84 / UTM zone 31N",AUTHORITY]]') - if srs.Validate() == 0: - return 'fail' + assert srs.Validate() != 0 # AXIS has wrong number of children (0), not 2 srs = osr.SpatialReference() srs.ImportFromWkt('PROJCS["WGS 84 / UTM zone 31N",AXIS]]') - if srs.Validate() == 0: - return 'fail' + assert srs.Validate() != 0 # Unexpected child for PROJCS `FOO' srs = osr.SpatialReference() srs.ImportFromWkt('PROJCS["WGS 84 / UTM zone 31N",FOO]]') - if srs.Validate() == 0: - return 'fail' + assert srs.Validate() != 0 # PROJCS does not have PROJECTION subnode. srs = osr.SpatialReference() srs.ImportFromWkt('PROJCS["WGS 84 / UTM zone 31N"]') - if srs.Validate() == 0: - return 'fail' - - return 'success' + assert srs.Validate() != 0 ############################################################################### -gdaltest_list = [ - osr_validate_1, - osr_validate_2, - osr_validate_3, - osr_validate_4, - osr_validate_5, - osr_validate_6] - -if __name__ == '__main__': - - gdaltest.setup_run('osr_validate') - - gdaltest.run_tests(gdaltest_list) - sys.exit(gdaltest.summarize()) diff --git a/autotest/osr/osr_xml.py b/autotest/osr/osr_xml.py index de8f5e340ba8..c25a9fe65975 100755 --- a/autotest/osr/osr_xml.py +++ b/autotest/osr/osr_xml.py @@ -29,9 +29,7 @@ ############################################################################### import re -import sys -sys.path.append('../pymod') import gdaltest from osgeo import osr @@ -42,7 +40,7 @@ # -def osr_xml_1(): +def test_osr_xml_1(): gdaltest.srs_xml = """<gml:ProjectedCRS> <gml:srsName>WGS 84 / UTM zone 31N</gml:srsName> @@ -181,18 +179,14 @@ def osr_xml_1(): got = srs.ExportToWkt() expected = gdaltest.srs_wkt - if got != expected: - print(got) - return 'fail' - - return 'success' + assert got == expected ############################################################################### # Test the osr.SpatialReference.ExportToXML() function. # -def osr_xml_2(): +def test_osr_xml_2(): srs = osr.SpatialReference() srs.ImportFromWkt(gdaltest.srs_wkt) @@ -205,21 +199,7 @@ def osr_xml_2(): got = re.sub(r' gml:id="[^"]*"', '', got, 0) expected = re.sub(r' gml:id="[^"]*"', '', expected, 0) - if got != expected: - print(got) - return 'fail' - - return 'success' - - -gdaltest_list = [ - osr_xml_1, - osr_xml_2] - -if __name__ == '__main__': + assert got == expected - gdaltest.setup_run('osr_xml') - gdaltest.run_tests(gdaltest_list) - sys.exit(gdaltest.summarize()) diff --git a/autotest/pymod/gdaltest.py b/autotest/pymod/gdaltest.py index 4f78f1b146de..27fb48df682d 100644 --- a/autotest/pymod/gdaltest.py +++ b/autotest/pymod/gdaltest.py @@ -30,6 +30,7 @@ ############################################################################### import contextlib +import math import os import os.path import stat @@ -39,6 +40,7 @@ from osgeo import gdal from osgeo import osr +import pytest cur_name = 'default' @@ -80,122 +82,11 @@ ############################################################################### -def setup_run(name): - - if 'APPLY_LOCALE' in os.environ: - import locale - locale.setlocale(locale.LC_ALL, '') - - global cur_name - cur_name = name - -############################################################################### - - def git_status(): out, _ = runexternal_out_and_err('git status --porcelain .') return out -############################################################################### - - -def run_tests(test_list): - global success_counter, failure_counter, expected_failure_counter, blow_counter, skip_counter - global reason, failure_summary, cur_name - global start_time, end_time - - before_vsimem = gdal.ReadDirRecursive('/vsimem/') - try: - git_status_before = git_status() - except OSError: - git_status_before = '' - - set_time = start_time is None - if set_time: - start_time = time.time() - had_errors_this_script = 0 - - for test_item in test_list: - if test_item is None: - continue - - try: - (func, name) = test_item - if func.__name__[:4] == 'test': - outline = ' TEST: ' + func.__name__[4:] + ': ' + name + ' ... ' - else: - outline = ' TEST: ' + func.__name__ + ': ' + name + ' ... ' - except TypeError: - func = test_item - name = func.__name__ - outline = ' TEST: ' + name + ' ... ' - - sys.stdout.write(outline) - sys.stdout.flush() - - reason = None - result = run_func(func) - - if result[:4] == 'fail': - if had_errors_this_script == 0: - failure_summary.append('Script: ' + cur_name) - had_errors_this_script = 1 - failure_summary.append(outline + result) - if reason is not None: - failure_summary.append(' ' + reason) - - if reason is not None: - print((' ' + reason)) - - if result == 'success': - success_counter = success_counter + 1 - elif result == 'expected_fail': - expected_failure_counter = expected_failure_counter + 1 - elif result == 'fail': - failure_counter = failure_counter + 1 - elif result == 'skip': - skip_counter = skip_counter + 1 - elif result == 'fail (blowup)': - blow_counter = blow_counter + 1 - else: - failure_counter = failure_counter + 1 - print('Unexpected return value: %s' % result) - if had_errors_this_script == 0: - failure_summary.append('Script: ' + cur_name) - had_errors_this_script = 1 - failure_summary.append(outline + result + ' (unexpected value)') - if reason is not None: - failure_summary.append(' ' + reason) - - if set_time: - end_time = time.time() - - after_vsimem = gdal.ReadDirRecursive('/vsimem/') - if before_vsimem is None: - before_vsimem = [] - if after_vsimem is None: - after_vsimem = [] - if len(after_vsimem) > len(before_vsimem): - failure_counter = failure_counter + 1 - print('Temporary /vsimem/ files remaining: %s' % str(after_vsimem)) - if had_errors_this_script == 0: - failure_summary.append('Script: ' + cur_name) - had_errors_this_script = 1 - failure_summary.append(' /vsimem/ temporary files remaining') - - try: - git_status_after = git_status() - except OSError: - git_status_after = '' - if git_status_after != git_status_before: - failure_counter = failure_counter + 1 - print('Temporary files remaining: %s' % str(git_status_after)) - if had_errors_this_script == 0: - failure_summary.append('Script: ' + cur_name) - had_errors_this_script = 1 - failure_summary.append(' Temporary files remaining') - ############################################################################### @@ -226,143 +117,6 @@ def post_reason(msg, frames=2): ############################################################################### -def summarize(): - global count_skipped_tests_download, count_skipped_tests_slow - global success_counter, failure_counter, blow_counter, skip_counter - global cur_name - global start_time, end_time - - print('') - if cur_name is not None: - print('Test Script: %s' % cur_name) - print('Succeeded: %d' % success_counter) - print('Failed: %d (%d blew exceptions)' - % (failure_counter + blow_counter, blow_counter)) - print('Skipped: %d' % skip_counter) - print('Expected fail:%d' % expected_failure_counter) - if start_time is not None: - duration = end_time - start_time - if duration >= 60: - print('Duration: %02dm%02.1fs' % (duration / 60., duration % 60.)) - else: - print('Duration: %02.2fs' % duration) - if count_skipped_tests_download != 0: - print('As GDAL_DOWNLOAD_TEST_DATA environment variable is not defined or set to NO, %d tests relying on data to downloaded from the Web have been skipped' % count_skipped_tests_download) - if count_skipped_tests_slow != 0: - print('As GDAL_RUN_SLOW_TESTS environment variable is not defined or set to NO, %d "slow" tests have been skipped' % count_skipped_tests_slow) - print('') - - sys.path.append('gcore') - sys.path.append('../gcore') - import testnonboundtoswig - # Do it twice to ensure that cleanup routines properly do their jobs - for _ in range(2): - testnonboundtoswig.OSRCleanup() - testnonboundtoswig.GDALDestroyDriverManager() - testnonboundtoswig.OGRCleanupAll() - - return failure_counter + blow_counter - -############################################################################### - - -def run_all(dirlist, run_as_external=False): - - global start_time, end_time - global cur_name - - start_time = time.time() - - for dir_name in dirlist: - files = os.listdir(dir_name) - - old_path = sys.path - # We prepend '.' rather than append it, so that "import rasterio" - # imports our rasterio.py and not another famous external package. - sys.path = ['.'] + sys.path - - for filename in files: - if not filename.endswith('.py'): - continue - - # Do not use rstrip here since 'test_ogr2ogr_py.py'.rstrip('.py') returns 'test_ogr2ogr_' - module = filename[0:-len('.py')] - try: - wd = os.getcwd() - os.chdir(dir_name) - - # Even try to import as module in run_as_external case - # so as to be able to detect ImportError and skip them - exec("import " + module) - - if run_as_external: - - exec("%s.gdaltest_list" % module) - - python_exe = sys.executable - if sys.platform == 'win32': - python_exe = python_exe.replace('\\', '/') - - print('Running %s/%s...' % (dir_name, filename)) - if 'GDALTEST_ASAN_OPTIONS' in os.environ: - if 'ASAN_OPTIONS' in os.environ: - backup_asan_options = os.environ['ASAN_OPTIONS'] - else: - backup_asan_options = None - os.environ['ASAN_OPTIONS'] = os.environ['GDALTEST_ASAN_OPTIONS'] - ret = runexternal(python_exe + """ -c "import %s; import sys; sys.path.append('../pymod'); import gdaltest; gdaltest.run_tests( %s.gdaltest_list ); gdaltest.summarize()" """ % (module, module), display_live_on_parent_stdout=True) - if 'GDALTEST_ASAN_OPTIONS' in os.environ: - if backup_asan_options is None: - del os.environ['ASAN_OPTIONS'] - else: - os.environ['ASAN_OPTIONS'] = backup_asan_options - - global success_counter, failure_counter, failure_summary - if ret.find('Failed: 0') < 0: - failure_counter += 1 - failure_summary.append(dir_name + '/' + filename) - else: - success_counter += 1 - else: - try: - print('Running tests from %s/%s' % (dir_name, filename)) - setup_run('%s/%s' % (dir_name, filename)) - exec("run_tests( " + module + ".gdaltest_list)") - except KeyboardInterrupt: - raise - except: - # import traceback - # traceback.print_exc(file=sys.stderr) - pass - - os.chdir(wd) - - except KeyboardInterrupt: - raise - except: - os.chdir(wd) - print('... failed to load %s ... skipping.' % filename) - - import traceback - traceback.print_exc() - - # We only add the tool directory to the python path long enough - # to load the tool files. - sys.path = old_path - - end_time = time.time() - cur_name = None - - if failure_summary: - print('') - print(' ------------ Failures ------------') - for item in failure_summary: - print(item) - print(' ----------------------------------') - -############################################################################### - - def clean_tmp(): all_files = os.listdir('tmp') for filename in all_files: @@ -373,7 +127,6 @@ def clean_tmp(): os.remove('tmp/' + filename) except OSError: pass - return 'success' ############################################################################### @@ -415,10 +168,7 @@ def testDriver(self): if self.driver is None: self.driver = gdal.GetDriverByName(self.drivername) if self.driver is None: - post_reason(self.drivername + ' driver not found!') - return 'fail' - - return 'success' + pytest.skip(self.drivername + ' driver not found!') def testOpen(self, check_prj=None, check_gt=None, gt_epsilon=None, check_stat=None, check_approx_stat=None, @@ -428,8 +178,7 @@ def testOpen(self, check_prj=None, check_gt=None, gt_epsilon=None, matrix (tuple), gt_epsilon - geotransformation tolerance, check_stat - band statistics (tuple), stat_epsilon - statistics tolerance.""" - if self.testDriver() == 'fail': - return 'skip' + self.testDriver() if self.filename_absolute: wrk_filename = self.filename @@ -441,13 +190,10 @@ def testOpen(self, check_prj=None, check_gt=None, gt_epsilon=None, else: ds = gdal.Open(wrk_filename, gdal.GA_ReadOnly) - if ds is None: - post_reason('Failed to open dataset: ' + wrk_filename) - return 'fail' + assert ds is not None, ('Failed to open dataset: ' + wrk_filename) - if ds.GetDriver().ShortName != gdal.GetDriverByName(self.drivername).ShortName: - post_reason('The driver of the returned dataset is %s instead of %s.' % (ds.GetDriver().ShortName, self.drivername)) - return 'fail' + assert ds.GetDriver().ShortName == gdal.GetDriverByName(self.drivername).ShortName, \ + ('The driver of the returned dataset is %s instead of %s.' % (ds.GetDriver().ShortName, self.drivername)) if self.xsize == 0 and self.ysize == 0: self.xsize = ds.RasterXSize @@ -465,9 +211,7 @@ def testOpen(self, check_prj=None, check_gt=None, gt_epsilon=None, gdal.Mkdir(target_filename, 0) else: f = gdal.VSIFOpenL(filename, 'rb') - if f is None: - post_reason('File %s does not exist' % filename) - return 'fail' + assert f is not None, ('File %s does not exist' % filename) gdal.VSIFSeekL(f, 0, 2) size = gdal.VSIFTellL(f) gdal.VSIFSeekL(f, 0, 0) @@ -502,12 +246,10 @@ def testOpen(self, check_prj=None, check_gt=None, gt_epsilon=None, for filename in gdal.ReadDirRecursive('/vsimem/tmp_testOpen'): gdal.Unlink('/vsimem/tmp_testOpen/' + filename) - if virtual_ds_is_None: - post_reason('File list is not complete or driver does not support /vsimem/') - return 'fail' - if not other_ds_is_None: - post_reason('When excluding %s, dataset is still opened by driver %s' % (self.drivername, other_ds_driver_name)) - return 'fail' + assert not virtual_ds_is_None, \ + 'File list is not complete or driver does not support /vsimem/' + assert other_ds_is_None, \ + ('When excluding %s, dataset is still opened by driver %s' % (self.drivername, other_ds_driver_name)) # Do we need to check projection? if check_prj is not None: @@ -522,8 +264,7 @@ def testOpen(self, check_prj=None, check_gt=None, gt_epsilon=None, print('') print('old = %s' % src_osr.ExportToPrettyWkt()) print('new = %s' % new_osr.ExportToPrettyWkt()) - post_reason('Projections differ') - return 'fail' + pytest.fail('Projections differ') # Do we need to check geotransform? if check_gt: @@ -537,8 +278,7 @@ def testOpen(self, check_prj=None, check_gt=None, gt_epsilon=None, print('') print('old = ', check_gt) print('new = ', new_gt) - post_reason('Geotransform differs.') - return 'fail' + pytest.fail('Geotransform differs.') oBand = ds.GetRasterBand(self.band) if skip_checksum is None: @@ -558,16 +298,14 @@ def testOpen(self, check_prj=None, check_gt=None, gt_epsilon=None, # because we need to support old and buggy Python 2.3. # Tested on Linux, Mac OS X and Windows, with Python 2.3/2.4/2.5. sv = str(new_stat[i]).lower() - if 'n' in sv or 'i' in sv or '#' in sv: - post_reason('NaN or infinity value encountered \'%s\'.' % sv) - return 'fail' + assert not ('n' in sv or 'i' in sv or '#' in sv), \ + ('NaN or infinity value encountered \'%s\'.' % sv) if abs(new_stat[i] - check_approx_stat[i]) > stat_epsilon: print('') print('old = ', check_approx_stat) print('new = ', new_stat) - post_reason('Approximate statistics differs.') - return 'fail' + pytest.fail('Approximate statistics differs.') # Do we need to check statistics? if check_stat: @@ -582,40 +320,33 @@ def testOpen(self, check_prj=None, check_gt=None, gt_epsilon=None, for i in range(4): sv = str(new_stat[i]).lower() - if 'n' in sv or 'i' in sv or '#' in sv: - post_reason('NaN or infinity value encountered \'%s\'.' % sv) - return 'fail' + assert not ('n' in sv or 'i' in sv or '#' in sv), \ + ('NaN or infinity value encountered \'%s\'.' % sv) if abs(new_stat[i] - check_stat[i]) > stat_epsilon: print('') print('old = ', check_stat) print('new = ', new_stat) - post_reason('Statistics differs.') - return 'fail' + pytest.fail('Statistics differs.') if check_min: - if oBand.GetMinimum() != check_min: - post_reason('Unexpected minimum value %s' % str(oBand.GetMinimum())) - return 'fail' + assert oBand.GetMinimum() == check_min, \ + ('Unexpected minimum value %s' % str(oBand.GetMinimum())) if check_max: - if oBand.GetMaximum() != check_max: - post_reason('Unexpected maximum value %s' % str(oBand.GetMaximum())) - return 'fail' + assert oBand.GetMaximum() == check_max, \ + ('Unexpected maximum value %s' % str(oBand.GetMaximum())) ds = None - if is_file_open(wrk_filename): - post_reason('file still open after dataset closing') - return 'fail' + assert not is_file_open(wrk_filename), 'file still open after dataset closing' if skip_checksum is not None: - return 'success' + return if self.chksum is None or chksum == self.chksum: - return 'success' - post_reason('Checksum for band %d in "%s" is %d, but expected %d.' + return + pytest.fail('Checksum for band %d in "%s" is %d, but expected %d.' % (self.band, self.filename, chksum, self.chksum)) - return 'fail' def testCreateCopy(self, check_minmax=1, check_gt=0, check_srs=None, vsimem=0, new_filename=None, strict_in=0, @@ -623,8 +354,7 @@ def testCreateCopy(self, check_minmax=1, check_gt=0, check_srs=None, check_checksum_not_null=None, interrupt_during_copy=False, dest_open_options=None, quiet_error_handler=True): - if self.testDriver() == 'fail': - return 'skip' + self.testDriver() if self.filename_absolute: wrk_filename = self.filename @@ -667,40 +397,31 @@ def testCreateCopy(self, check_minmax=1, check_gt=0, check_srs=None, gdal.PushErrorHandler('CPLQuietErrorHandler') self.driver.Delete(new_filename) gdal.PopErrorHandler() - return 'success' - post_reason('CreateCopy() should have failed due to interruption') + return new_ds = None self.driver.Delete(new_filename) - return 'fail' + pytest.fail('CreateCopy() should have failed due to interruption') - if new_ds is None: - post_reason('Failed to create test file using CreateCopy method.' + + assert new_ds is not None, ('Failed to create test file using CreateCopy method.' + '\n' + gdal.GetLastErrorMsg()) - return 'fail' - if new_ds.GetDriver().ShortName != gdal.GetDriverByName(self.drivername).ShortName: - post_reason('The driver of the returned dataset is %s instead of %s.' % (new_ds.GetDriver().ShortName, self.drivername)) - return 'fail' + assert new_ds.GetDriver().ShortName == gdal.GetDriverByName(self.drivername).ShortName, \ + ('The driver of the returned dataset is %s instead of %s.' % (new_ds.GetDriver().ShortName, self.drivername)) if self.band > 0 and skip_preclose_test == 0: bnd = new_ds.GetRasterBand(self.band) if check_checksum_not_null is True: - if bnd.Checksum() == 0: - post_reason('Got null checksum on still-open file.') - return 'fail' + assert bnd.Checksum() != 0, 'Got null checksum on still-open file.' elif self.chksum is not None and bnd.Checksum() != self.chksum: - post_reason( + pytest.fail( 'Did not get expected checksum on still-open file.\n' ' Got %d instead of %d.' % (bnd.Checksum(), self.chksum)) - return 'fail' if check_minmax: got_minmax = bnd.ComputeRasterMinMax() - if got_minmax != minmax: - post_reason( - 'Did not get expected min/max values on still-open file.\n' + assert got_minmax == minmax, \ + ('Did not get expected min/max values on still-open file.\n' ' Got %g,%g instead of %g,%g.' % (got_minmax[0], got_minmax[1], minmax[0], minmax[1])) - return 'fail' bnd = None new_ds = None @@ -711,30 +432,23 @@ def testCreateCopy(self, check_minmax=1, check_gt=0, check_srs=None, new_ds = gdal.OpenEx(new_filename, gdal.OF_RASTER, open_options=dest_open_options) else: new_ds = gdal.Open(new_filename) - if new_ds is None: - post_reason('Failed to open dataset: ' + new_filename) - return 'fail' + assert new_ds is not None, ('Failed to open dataset: ' + new_filename) if self.band > 0: bnd = new_ds.GetRasterBand(self.band) if check_checksum_not_null is True: - if bnd.Checksum() == 0: - post_reason('Got null checksum on reopened file.') - return 'fail' + assert bnd.Checksum() != 0, 'Got null checksum on reopened file.' elif self.chksum_after_reopening is not None and bnd.Checksum() not in self.chksum_after_reopening: - post_reason('Did not get expected checksum on reopened file.\n' + pytest.fail('Did not get expected checksum on reopened file.\n' ' Got %d instead of %s.' % (bnd.Checksum(), str(self.chksum_after_reopening))) - return 'fail' if check_minmax: got_minmax = bnd.ComputeRasterMinMax() - if got_minmax != minmax: - post_reason( - 'Did not get expected min/max values on reopened file.\n' + assert got_minmax == minmax, \ + ('Did not get expected min/max values on reopened file.\n' ' Got %g,%g instead of %g,%g.' % (got_minmax[0], got_minmax[1], minmax[0], minmax[1])) - return 'fail' # Do we need to check the geotransform? if check_gt: @@ -752,8 +466,7 @@ def testCreateCopy(self, check_minmax=1, check_gt=0, check_srs=None, print('') print('old = ', src_gt) print('new = ', new_gt) - post_reason('Geotransform differs.') - return 'fail' + pytest.fail('Geotransform differs.') # Do we need to check the geotransform? if check_srs is not None: @@ -766,8 +479,7 @@ def testCreateCopy(self, check_minmax=1, check_gt=0, check_srs=None, print('') print('old = %s' % src_osr.ExportToPrettyWkt()) print('new = %s' % new_osr.ExportToPrettyWkt()) - post_reason('Projections differ') - return 'fail' + pytest.fail('Projections differ') bnd = None new_ds = None @@ -776,12 +488,9 @@ def testCreateCopy(self, check_minmax=1, check_gt=0, check_srs=None, if gdal.GetConfigOption('CPL_DEBUG', 'OFF') != 'ON' and delete_copy == 1: self.driver.Delete(new_filename) - return 'success' - def testCreate(self, vsimem=0, new_filename=None, out_bands=1, check_minmax=1, dest_open_options=None): - if self.testDriver() == 'fail': - return 'skip' + self.testDriver() if self.filename_absolute: wrk_filename = self.filename @@ -807,9 +516,7 @@ def testCreate(self, vsimem=0, new_filename=None, out_bands=1, new_ds = self.driver.Create(new_filename, xsize, ysize, out_bands, src_ds.GetRasterBand(self.band).DataType, options=self.options) - if new_ds is None: - post_reason('Failed to create test file using Create method.') - return 'fail' + assert new_ds is not None, 'Failed to create test file using Create method.' src_ds = None @@ -817,25 +524,19 @@ def testCreate(self, vsimem=0, new_filename=None, out_bands=1, for band in range(1, out_bands + 1): new_ds.GetRasterBand(band).WriteRaster(0, 0, xsize, ysize, src_img) except: - post_reason('Failed to write raster bands to test file.') - return 'fail' + pytest.fail('Failed to write raster bands to test file.') for band in range(1, out_bands + 1): - if self.chksum is not None \ - and new_ds.GetRasterBand(band).Checksum() != self.chksum: - post_reason( - 'Did not get expected checksum on still-open file.\n' + assert self.chksum is None or new_ds.GetRasterBand(band).Checksum() == self.chksum, \ + ('Did not get expected checksum on still-open file.\n' ' Got %d instead of %d.' % (new_ds.GetRasterBand(band).Checksum(), self.chksum)) - return 'fail' - computed_minmax = new_ds.GetRasterBand(band).ComputeRasterMinMax() if computed_minmax != minmax and check_minmax: - post_reason('Did not get expected min/max values on still-open file.') print('expect: ', minmax) print('got: ', computed_minmax) - return 'fail' + pytest.fail('Did not get expected min/max values on still-open file.') new_ds = None @@ -843,32 +544,24 @@ def testCreate(self, vsimem=0, new_filename=None, out_bands=1, new_ds = gdal.OpenEx(new_filename, gdal.OF_RASTER, open_options=dest_open_options) else: new_ds = gdal.Open(new_filename) - if new_ds is None: - post_reason('Failed to open dataset: ' + new_filename) - return 'fail' + assert new_ds is not None, ('Failed to open dataset: ' + new_filename) for band in range(1, out_bands + 1): - if self.chksum is not None \ - and new_ds.GetRasterBand(band).Checksum() != self.chksum: - post_reason('Did not get expected checksum on reopened file.' + assert self.chksum is None or new_ds.GetRasterBand(band).Checksum() == self.chksum, \ + ('Did not get expected checksum on reopened file.' ' Got %d instead of %d.' % (new_ds.GetRasterBand(band).Checksum(), self.chksum)) - return 'fail' - if new_ds.GetRasterBand(band).ComputeRasterMinMax() != minmax and check_minmax: - post_reason('Did not get expected min/max values on reopened file.') - return 'fail' + assert new_ds.GetRasterBand(band).ComputeRasterMinMax() == minmax or not check_minmax, \ + 'Did not get expected min/max values on reopened file.' new_ds = None if gdal.GetConfigOption('CPL_DEBUG', 'OFF') != 'ON': self.driver.Delete(new_filename) - return 'success' - def testSetGeoTransform(self): - if self.testDriver() == 'fail': - return 'skip' + self.testDriver() wrk_filename = 'data/' + self.filename if self.open_options: @@ -883,22 +576,17 @@ def testSetGeoTransform(self): new_ds = self.driver.Create(new_filename, xsize, ysize, 1, src_ds.GetRasterBand(self.band).DataType, options=self.options) - if new_ds is None: - post_reason('Failed to create test file using Create method.') - return 'fail' + assert new_ds is not None, 'Failed to create test file using Create method.' gt = (123.0, 1.18, 0.0, 456.0, 0.0, -1.18) - if new_ds.SetGeoTransform(gt) is not gdal.CE_None: - post_reason('Failed to set geographic transformation.') - return 'fail' + assert new_ds.SetGeoTransform(gt) is gdal.CE_None, \ + 'Failed to set geographic transformation.' src_ds = None new_ds = None new_ds = gdal.Open(new_filename) - if new_ds is None: - post_reason('Failed to open dataset: ' + new_filename) - return 'fail' + assert new_ds is not None, ('Failed to open dataset: ' + new_filename) eps = 0.00000001 new_gt = new_ds.GetGeoTransform() @@ -911,19 +599,15 @@ def testSetGeoTransform(self): print('') print('old = ', gt) print('new = ', new_gt) - post_reason('Did not get expected geotransform.') - return 'fail' + pytest.fail('Did not get expected geotransform.') new_ds = None if gdal.GetConfigOption('CPL_DEBUG', 'OFF') != 'ON': self.driver.Delete(new_filename) - return 'success' - def testSetProjection(self, prj=None, expected_prj=None): - if self.testDriver() == 'fail': - return 'skip' + self.testDriver() wrk_filename = 'data/' + self.filename if self.open_options: @@ -938,9 +622,7 @@ def testSetProjection(self, prj=None, expected_prj=None): new_ds = self.driver.Create(new_filename, xsize, ysize, 1, src_ds.GetRasterBand(self.band).DataType, options=self.options) - if new_ds is None: - post_reason('Failed to create test file using Create method.') - return 'fail' + assert new_ds is not None, 'Failed to create test file using Create method.' gt = (123.0, 1.18, 0.0, 456.0, 0.0, -1.18) if prj is None: @@ -951,17 +633,14 @@ def testSetProjection(self, prj=None, expected_prj=None): src_osr.ImportFromWkt(prj) new_ds.SetGeoTransform(gt) - if new_ds.SetProjection(prj) is not gdal.CE_None: - post_reason('Failed to set geographic projection string.') - return 'fail' + assert new_ds.SetProjection(prj) is gdal.CE_None, \ + 'Failed to set geographic projection string.' src_ds = None new_ds = None new_ds = gdal.Open(new_filename) - if new_ds is None: - post_reason('Failed to open dataset: ' + new_filename) - return 'fail' + assert new_ds is not None, ('Failed to open dataset: ' + new_filename) expected_osr = osr.SpatialReference() if expected_prj is None: @@ -972,23 +651,19 @@ def testSetProjection(self, prj=None, expected_prj=None): new_osr = osr.SpatialReference() new_osr.ImportFromWkt(new_ds.GetProjection()) if not new_osr.IsSame(expected_osr): - post_reason('Did not get expected projection reference.') print('Got: ') print(new_osr.ExportToPrettyWkt()) print('Expected:') print(expected_osr.ExportToPrettyWkt()) - return 'fail' + pytest.fail('Did not get expected projection reference.') new_ds = None if gdal.GetConfigOption('CPL_DEBUG', 'OFF') != 'ON': self.driver.Delete(new_filename) - return 'success' - def testSetMetadata(self): - if self.testDriver() == 'fail': - return 'skip' + self.testDriver() wrk_filename = 'data/' + self.filename if self.open_options: @@ -1003,9 +678,7 @@ def testSetMetadata(self): new_ds = self.driver.Create(new_filename, xsize, ysize, 1, src_ds.GetRasterBand(self.band).DataType, options=self.options) - if new_ds is None: - post_reason('Failed to create test file using Create method.') - return 'fail' + assert new_ds is not None, 'Failed to create test file using Create method.' new_ds.SetMetadata({'TEST_KEY': 'TestValue'}) # FIXME @@ -1018,30 +691,21 @@ def testSetMetadata(self): new_ds = None new_ds = gdal.Open(new_filename) - if new_ds is None: - post_reason('Failed to open dataset: ' + new_filename) - return 'fail' + assert new_ds is not None, ('Failed to open dataset: ' + new_filename) md_dict = new_ds.GetMetadata() - if 'TEST_KEY' not in md_dict: - post_reason('Metadata item TEST_KEY does not exist.') - return 'fail' + assert 'TEST_KEY' in md_dict, 'Metadata item TEST_KEY does not exist.' - if md_dict['TEST_KEY'] != 'TestValue': - post_reason('Did not get expected metadata item.') - return 'fail' + assert md_dict['TEST_KEY'] == 'TestValue', 'Did not get expected metadata item.' new_ds = None if gdal.GetConfigOption('CPL_DEBUG', 'OFF') != 'ON': self.driver.Delete(new_filename) - return 'success' - def testSetNoDataValue(self, delete=False): - if self.testDriver() == 'fail': - return 'skip' + self.testDriver() wrk_filename = 'data/' + self.filename if self.open_options: @@ -1056,17 +720,14 @@ def testSetNoDataValue(self, delete=False): new_ds = self.driver.Create(new_filename, xsize, ysize, 1, src_ds.GetRasterBand(self.band).DataType, options=self.options) - if new_ds is None: - post_reason('Failed to create test file using Create method.') - return 'fail' + assert new_ds is not None, 'Failed to create test file using Create method.' if self.options is None or 'PIXELTYPE=SIGNEDBYTE' not in self.options: nodata = 130 else: nodata = 11 - if new_ds.GetRasterBand(1).SetNoDataValue(nodata) is not gdal.CE_None: - post_reason('Failed to set NoData value.') - return 'fail' + assert new_ds.GetRasterBand(1).SetNoDataValue(nodata) is gdal.CE_None, \ + 'Failed to set NoData value.' src_ds = None new_ds = None @@ -1076,39 +737,31 @@ def testSetNoDataValue(self, delete=False): else: mode = gdal.GA_ReadOnly new_ds = gdal.Open(new_filename, mode) - if new_ds is None: - post_reason('Failed to open dataset: ' + new_filename) - return 'fail' + assert new_ds is not None, ('Failed to open dataset: ' + new_filename) - if nodata != new_ds.GetRasterBand(1).GetNoDataValue(): - post_reason('Did not get expected NoData value.') - return 'fail' + assert nodata == new_ds.GetRasterBand(1).GetNoDataValue(), \ + 'Did not get expected NoData value.' if delete: - if new_ds.GetRasterBand(1).DeleteNoDataValue() != 0: - post_reason('Did not manage to delete nodata value') - return 'fail' + assert new_ds.GetRasterBand(1).DeleteNoDataValue() == 0, \ + 'Did not manage to delete nodata value' new_ds = None if delete: new_ds = gdal.Open(new_filename) - if new_ds.GetRasterBand(1).GetNoDataValue() is not None: - post_reason('Got nodata value whereas none was expected') - return 'fail' + assert new_ds.GetRasterBand(1).GetNoDataValue() is None, \ + 'Got nodata value whereas none was expected' new_ds = None if gdal.GetConfigOption('CPL_DEBUG', 'OFF') != 'ON': self.driver.Delete(new_filename) - return 'success' - def testSetNoDataValueAndDelete(self): return self.testSetNoDataValue(delete=True) def testSetDescription(self): - if self.testDriver() == 'fail': - return 'skip' + self.testDriver() wrk_filename = 'data/' + self.filename if self.open_options: @@ -1123,9 +776,7 @@ def testSetDescription(self): new_ds = self.driver.Create(new_filename, xsize, ysize, 1, src_ds.GetRasterBand(self.band).DataType, options=self.options) - if new_ds is None: - post_reason('Failed to create test file using Create method.') - return 'fail' + assert new_ds is not None, 'Failed to create test file using Create method.' description = "Description test string" new_ds.GetRasterBand(1).SetDescription(description) @@ -1134,24 +785,18 @@ def testSetDescription(self): new_ds = None new_ds = gdal.Open(new_filename) - if new_ds is None: - post_reason('Failed to open dataset: ' + new_filename) - return 'fail' + assert new_ds is not None, ('Failed to open dataset: ' + new_filename) - if description != new_ds.GetRasterBand(1).GetDescription(): - post_reason('Did not get expected description string.') - return 'fail' + assert description == new_ds.GetRasterBand(1).GetDescription(), \ + 'Did not get expected description string.' new_ds = None if gdal.GetConfigOption('CPL_DEBUG', 'OFF') != 'ON': self.driver.Delete(new_filename) - return 'success' - def testSetUnitType(self): - if self.testDriver() == 'fail': - return 'skip' + self.testDriver() wrk_filename = 'data/' + self.filename if self.open_options: @@ -1166,38 +811,30 @@ def testSetUnitType(self): new_ds = self.driver.Create(new_filename, xsize, ysize, 1, src_ds.GetRasterBand(self.band).DataType, options=self.options) - if new_ds is None: - post_reason('Failed to create test file using Create method.') - return 'fail' + assert new_ds is not None, 'Failed to create test file using Create method.' unit = 'mg/m3' - if new_ds.GetRasterBand(1).SetUnitType(unit) is not gdal.CE_None: - post_reason('Failed to set unit type.') - return 'fail' + assert new_ds.GetRasterBand(1).SetUnitType(unit) is gdal.CE_None, \ + 'Failed to set unit type.' src_ds = None new_ds = None new_ds = gdal.Open(new_filename) - if new_ds is None: - post_reason('Failed to open dataset: ' + new_filename) - return 'fail' + assert new_ds is not None, ('Failed to open dataset: ' + new_filename) new_unit = new_ds.GetRasterBand(1).GetUnitType() if new_unit != unit: print('') print('old = ', unit) print('new = ', new_unit) - post_reason('Did not get expected unit type.') - return 'fail' + pytest.fail('Did not get expected unit type.') new_ds = None if gdal.GetConfigOption('CPL_DEBUG', 'OFF') != 'ON': self.driver.Delete(new_filename) - return 'success' - def approx_equal(a, b): a = float(a) @@ -1614,45 +1251,28 @@ def unzip(target_dir, zipfilename, verbose=False): return -############################################################################### -# Return if a number is the NaN number - - -def isnan(val): - return val != val +isnan = math.isnan ############################################################################### # Return NaN def NaN(): - try: - # Python >= 2.6 - return float('nan') - except NameError: - return 1e400 / 1e400 + return float('nan') ############################################################################### # Return positive infinity def posinf(): - try: - # Python >= 2.6 - return float('inf') - except NameError: - return 1e400 + return float('inf') ############################################################################### # Return negative infinity def neginf(): - try: - # Python >= 2.6 - return float('-inf') - except NameError: - return -1e400 + return float('-inf') ############################################################################### # Has the user requested to dowload test data diff --git a/autotest/pymod/gdaltest_python2.py b/autotest/pymod/gdaltest_python2.py index fcd226224075..8c71c2494985 100644 --- a/autotest/pymod/gdaltest_python2.py +++ b/autotest/pymod/gdaltest_python2.py @@ -32,8 +32,9 @@ import urllib2 import socket import os +import subprocess +import shlex import sys -from sys import version_info from Queue import Queue from threading import Thread @@ -106,7 +107,7 @@ def gdalurlopen(url, timeout=10): print('HTTP service for %s is down (HTTP Error: %s)' % (url, e.reason)) socket.setdefaulttimeout(old_timeout) return None - except socket.timeout as e: + except socket.timeout: print('HTTP service for %s is down (timeout)' % url) socket.setdefaulttimeout(old_timeout) return None @@ -123,9 +124,7 @@ def warn_if_memleak(cmd, out_str): print(out_str) -def spawn_async26(cmd): - import shlex - import subprocess +def spawn_async(cmd): command = shlex.split(cmd) try: process = subprocess.Popen(command, stdout=subprocess.PIPE) @@ -134,31 +133,12 @@ def spawn_async26(cmd): return (None, None) -def spawn_async(cmd): - if version_info >= (2, 6, 0): - return spawn_async26(cmd) - - import popen2 - try: - process = popen2.Popen3(cmd) - except OSError: - return (None, None) - if process is None: - return (None, None) - process.tochild.close() - return (process, process.fromchild) - - def wait_process(process): process.wait() -# Compatible with Python 2.6 or above - -def _runexternal_subprocess(cmd, strin=None, check_memleak=True, display_live_on_parent_stdout=False, encoding=None): +def runexternal(cmd, strin=None, check_memleak=True, display_live_on_parent_stdout=False, encoding=None): # pylint: disable=unused-argument - import subprocess - import shlex command = shlex.split(cmd) command = [elt.replace('\x00', '') for elt in command] if strin is None: @@ -180,7 +160,6 @@ def _runexternal_subprocess(cmd, strin=None, check_memleak=True, display_live_on sys.stdout.write(c) else: ret = p.stdout.read() - p.stdout.close() else: ret = '' @@ -193,52 +172,6 @@ def _runexternal_subprocess(cmd, strin=None, check_memleak=True, display_live_on return ret -def runexternal(cmd, strin=None, check_memleak=True, display_live_on_parent_stdout=False, encoding=None): - from gdaltest import is_travis_branch - if not is_travis_branch('mingw'): - has_subprocess = False - try: - import subprocess - import shlex - if hasattr(subprocess, 'Popen') and hasattr(shlex, 'split'): - has_subprocess = True - except (ImportError, AttributeError): - pass - if has_subprocess: - return _runexternal_subprocess(cmd, - strin=strin, - check_memleak=check_memleak, - display_live_on_parent_stdout=display_live_on_parent_stdout, - encoding=encoding) - - if strin is None: - ret_stdout = os.popen(cmd) - else: - (ret_stdin, ret_stdout) = os.popen2(cmd) - ret_stdin.write(strin) - ret_stdin.close() - - if display_live_on_parent_stdout: - out_str = '' - while True: - c = ret_stdout.read(1) - if c == '': - break - out_str = out_str + c - sys.stdout.write(c) - ret_stdout.close() - else: - out_str = ret_stdout.read() - ret_stdout.close() - - if check_memleak: - warn_if_memleak(cmd, out_str) - - if encoding is not None: - out_str = out_str.decode(encoding) - return out_str - - def read_in_thread(f, q): q.put(f.read()) f.close() @@ -248,8 +181,6 @@ def read_in_thread(f, q): def _runexternal_out_and_err_subprocess(cmd, check_memleak=True): # pylint: disable=unused-argument - import subprocess - import shlex command = shlex.split(cmd) command = [elt.replace('\x00', '') for elt in command] p = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE) @@ -283,33 +214,4 @@ def _runexternal_out_and_err_subprocess(cmd, check_memleak=True): def runexternal_out_and_err(cmd, check_memleak=True): - from gdaltest import is_travis_branch - if not is_travis_branch('mingw'): - has_subprocess = False - try: - import subprocess - import shlex - if hasattr(subprocess, 'Popen') and hasattr(shlex, 'split'): - has_subprocess = True - except ImportError: - pass - if has_subprocess: - return _runexternal_out_and_err_subprocess(cmd, check_memleak=check_memleak) - - (ret_stdin, ret_stdout, ret_stderr) = os.popen3(cmd) - ret_stdin.close() - - q_stdout = Queue() - t_stdout = Thread(target=read_in_thread, args=(ret_stdout, q_stdout)) - q_stderr = Queue() - t_stderr = Thread(target=read_in_thread, args=(ret_stderr, q_stderr)) - t_stdout.start() - t_stderr.start() - - out_str = q_stdout.get() - err_str = q_stderr.get() - - if check_memleak: - warn_if_memleak(cmd, out_str) - - return (out_str, err_str) + return _runexternal_out_and_err_subprocess(cmd, check_memleak=check_memleak) diff --git a/autotest/pymod/gdaltest_python3.py b/autotest/pymod/gdaltest_python3.py index 2196ea4f541a..0e3402bbecf1 100644 --- a/autotest/pymod/gdaltest_python3.py +++ b/autotest/pymod/gdaltest_python3.py @@ -152,7 +152,6 @@ def runexternal(cmd, strin=None, check_memleak=True, display_live_on_parent_stdo sys.stdout.write(c) else: ret = p.stdout.read().decode(encoding) - p.stdout.close() else: ret = '' diff --git a/autotest/pymod/ogrtest.py b/autotest/pymod/ogrtest.py index 36d09866e6f9..7ddf1e87eba3 100644 --- a/autotest/pymod/ogrtest.py +++ b/autotest/pymod/ogrtest.py @@ -25,6 +25,7 @@ ############################################################################### import sys +import pytest sys.path.append('../pymod') @@ -170,20 +171,17 @@ def compare_layers(lyr, lyr_ref, excluded_fields=None): for f_ref in lyr_ref: f = lyr.GetNextFeature() if f is None: - gdaltest.post_reason('fail') f_ref.DumpReadable() - return 'fail' + pytest.fail() if check_feature(f, f_ref, excluded_fields=excluded_fields) != 0: f.DumpReadable() f_ref.DumpReadable() - return 'fail' + pytest.fail() f = lyr.GetNextFeature() if f is not None: - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' - return 'success' - + pytest.fail() + ############################################################################### diff --git a/autotest/pymod/test_py_scripts.py b/autotest/pymod/test_py_scripts.py index 056a1e9fafd0..de0fde6d4709 100644 --- a/autotest/pymod/test_py_scripts.py +++ b/autotest/pymod/test_py_scripts.py @@ -32,7 +32,6 @@ import os import sys import gdaltest -from osgeo import gdal ############################################################################### # Return the path in which the Python script is found @@ -61,27 +60,12 @@ def get_py_script(script_name): return None -############################################################################### -# Utility function of run_py_script_as_py_module() -# -has_main = False - - -def find_main_in_module(names): - global has_main - has_main = 'main' in names - - ############################################################################### # Runs a Python script +# Alias of run_py_script_as_external_script() # def run_py_script(script_path, script_name, concatenated_argv): - - run_as_external_script = gdal.GetConfigOption('RUN_AS_EXTERNAL_SCRIPT', 'NO') - - if run_as_external_script == 'yes' or run_as_external_script == 'YES': - return run_py_script_as_external_script(script_path, script_name, concatenated_argv) - return run_py_script_as_py_module(script_path, script_name, concatenated_argv) + return run_py_script_as_external_script(script_path, script_name, concatenated_argv) ############################################################################### @@ -99,75 +83,3 @@ def run_py_script_as_external_script(script_path, script_name, concatenated_argv script_file_path = script_file_path.replace('\\', '/') return gdaltest.runexternal(python_exe + ' ' + script_file_path + ' ' + concatenated_argv, display_live_on_parent_stdout=display_live_on_parent_stdout) - -############################################################################### -# Runs a Python script as a py module -# -# This function is an interesting concentrate of dirty hacks to run python -# scripts without forking a new process. This way we don't need to know the -# name and path of the python interpreter. -# - - -def run_py_script_as_py_module(script_path, script_name, concatenated_argv): - - # Save original sys variables - saved_syspath = sys.path - saved_sysargv = sys.argv - - sys.path.append(script_path) - - # Replace argv by user provided one - # Add first a fake first arg that we set to be the script - # name but which could be any arbitrary name - sys.argv = [script_name + '.py'] - - import shlex - sys.argv.extend(shlex.split(concatenated_argv)) - - has_imported_module = False - - ret = None - - if os.path.exists('tmp'): - tmp_stdout = 'tmp/stdout.txt' - else: - tmp_stdout = 'stdout.txt' - - try: - # Redirect stdout to file - fout = open(tmp_stdout, 'wt') - ori_stdout = sys.stdout - sys.stdout = fout - - exec('import ' + script_name) - has_imported_module = True - - # Detect if the script has a main() function - exec('find_main_in_module(dir(' + script_name + '))') - - # If so, run it (otherwise the import has already run the script) - if has_main: - exec(script_name + '.main()') - finally: - # Restore original stdout - fout.close() - sys.stdout = ori_stdout - - fout = open(tmp_stdout, 'rt') - ret = fout.read() - fout.close() - - os.remove(tmp_stdout) - - # Restore original sys variables - sys.path = saved_syspath - sys.argv = saved_sysargv - - if has_imported_module: - # Unload the module so that it gets imported again next time - # (useful if wanting to run a script without main() function - # several time) - del sys.modules[script_name] - - return ret diff --git a/autotest/pymod/webserver.py b/autotest/pymod/webserver.py index 6af0022a7661..7daf4e52df16 100644 --- a/autotest/pymod/webserver.py +++ b/autotest/pymod/webserver.py @@ -458,5 +458,3 @@ def main(): server.run_server(10) -if __name__ == '__main__': - main() diff --git a/autotest/pymod/xmlvalidate.py b/autotest/pymod/xmlvalidate.py index 7c0f695cb228..c53f4b638855 100644 --- a/autotest/pymod/xmlvalidate.py +++ b/autotest/pymod/xmlvalidate.py @@ -473,70 +473,3 @@ def Usage(): # Main -if __name__ == '__main__': - argv = sys.argv[1:] - i = 0 - filename = None - xsd_filename = None - ogc_schemas_location = None - inspire_schemas_location = None - application_schema_ns = 'http://mapserver.gis.umn.edu/mapserver' - - if has_local_ogc_schemas('SCHEMAS_OPENGIS_NET'): - ogc_schemas_location = 'SCHEMAS_OPENGIS_NET' - - if has_local_inspire_schemas('inspire_schemas'): - inspire_schemas_location = 'inspire_schemas' - # transform_inspire_abs_links_to_ref_links('inspire_schemas') - - target_dir = '.' - - while i < len(argv): - if argv[i] == "-target_dir": - i = i + 1 - target_dir = argv[i] - elif argv[i] == "-download_ogc_schemas": - ret = download_ogc_schemas(target_dir=target_dir, force_download=True) - if i == len(argv) - 1: - if ret: - sys.exit(0) - else: - sys.exit(1) - elif argv[i] == "-download_inspire_schemas": - ret = download_inspire_schemas(target_dir=target_dir, force_download=True) - if i == len(argv) - 1: - if ret: - sys.exit(0) - else: - sys.exit(1) - elif argv[i] == "-schema": - i = i + 1 - xsd_filename = argv[i] - elif argv[i] == "-ogc_schemas_location": - i = i + 1 - ogc_schemas_location = argv[i] - elif argv[i] == "-inspire_schemas_location": - i = i + 1 - inspire_schemas_location = argv[i] - elif argv[i] == "-app_schema_ns": - i = i + 1 - application_schema_ns = argv[i] - elif argv[i][0] == '-': - print('Unhandled option : %s' % argv[i]) - print('') - Usage() - else: - filename = argv[i] - - i = i + 1 - - if filename is None: - Usage() - - if validate(filename, xsd_filename=xsd_filename, - application_schema_ns=application_schema_ns, - ogc_schemas_location=ogc_schemas_location, - inspire_schemas_location=inspire_schemas_location): - sys.exit(0) - else: - sys.exit(1) diff --git a/autotest/pyscripts/__init__.py b/autotest/pyscripts/__init__.py new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/autotest/pyscripts/test_gdal2tiles.py b/autotest/pyscripts/test_gdal2tiles.py index 1ae3710bc303..74c764936e31 100755 --- a/autotest/pyscripts/test_gdal2tiles.py +++ b/autotest/pyscripts/test_gdal2tiles.py @@ -33,17 +33,16 @@ import sys import shutil -sys.path.append('../pymod') from osgeo import gdal # noqa -import gdaltest # noqa # pylint: disable=E0401 import test_py_scripts # noqa # pylint: disable=E0401 +import pytest def test_gdal2tiles_py_simple(): script_path = test_py_scripts.get_py_script('gdal2tiles') if script_path is None: - return 'skip' + pytest.skip() shutil.copy('../gdrivers/data/small_world.tif', 'tmp/out_gdal2tiles_smallworld.tif') @@ -61,26 +60,23 @@ def test_gdal2tiles_py_simple(): expected_cs = [25314, 28114, 6148, 59026] for i in range(4): if ds.GetRasterBand(i + 1).Checksum() != expected_cs[i]: - gdaltest.post_reason('wrong checksum for band %d' % (i + 1)) for j in range(4): print(ds.GetRasterBand(j + 1).Checksum()) - return 'fail' + pytest.fail('wrong checksum for band %d' % (i + 1)) ds = None for filename in ['googlemaps.html', 'leaflet.html', 'openlayers.html', 'tilemapresource.xml']: - if not os.path.exists('tmp/out_gdal2tiles_smallworld/' + filename): - gdaltest.post_reason('%s missing' % filename) - return 'fail' - - return 'success' + assert os.path.exists('tmp/out_gdal2tiles_smallworld/' + filename), \ + ('%s missing' % filename) + def test_gdal2tiles_py_zoom_option(): script_path = test_py_scripts.get_py_script('gdal2tiles') if script_path is None: - return 'skip' + pytest.skip() shutil.rmtree('tmp/out_gdal2tiles_smallworld', ignore_errors=True) @@ -97,19 +93,14 @@ def test_gdal2tiles_py_zoom_option(): expected_cs = [8130, 10496, 65274, 63715] for i in range(4): if ds.GetRasterBand(i + 1).Checksum() != expected_cs[i]: - gdaltest.post_reason('wrong checksum for band %d' % (i + 1)) for j in range(4): print(ds.GetRasterBand(j + 1).Checksum()) - return 'fail' + pytest.fail('wrong checksum for band %d' % (i + 1)) ds = None ds = gdal.Open('tmp/out_gdal2tiles_smallworld/doc.kml') - if ds is None: - gdaltest.post_reason('did not get kml') - return 'fail' - - return 'success' + assert ds is not None, 'did not get kml' def test_does_not_error_when_source_bounds_close_to_tiles_bound(): @@ -128,7 +119,7 @@ def test_does_not_error_when_source_bounds_close_to_tiles_bound(): script_path = test_py_scripts.get_py_script('gdal2tiles') if script_path is None: - return 'skip' + pytest.skip() try: for in_file in in_files: @@ -137,13 +128,11 @@ def test_does_not_error_when_source_bounds_close_to_tiles_bound(): 'gdal2tiles', '-q -z 21-21 %s %s' % (in_file, out_folder)) except TypeError: - gdaltest.post_reason( + pytest.fail( 'Case of tile not getting any data not handled properly ' '(tiles at the border of the image)') - return 'fail' - - return 'success' + def test_does_not_error_when_nothing_to_put_in_the_low_zoom_tile(): """ @@ -159,7 +148,7 @@ def test_does_not_error_when_nothing_to_put_in_the_low_zoom_tile(): script_path = test_py_scripts.get_py_script('gdal2tiles') if script_path is None: - return 'skip' + pytest.skip() try: test_py_scripts.run_py_script( @@ -167,24 +156,23 @@ def test_does_not_error_when_nothing_to_put_in_the_low_zoom_tile(): 'gdal2tiles', '-q -z 10 %s %s' % (in_file, out_folder)) except TypeError: - gdaltest.post_reason( + pytest.fail( 'Case of low level tile not getting any data not handled properly ' '(tile at a zoom level too low)') - return 'fail' - - return 'success' + def test_python2_handles_utf8_by_default(): if sys.version_info[0] >= 3: - return 'skip' + pytest.skip() return _test_utf8(should_raise_unicode=False) +@pytest.mark.skip("This behaviour doesn't actually work as expected") def test_python2_gives_warning_if_bad_lc_ctype_and_non_ascii_chars(): if sys.version_info[0] >= 3: - return 'skip' + pytest.skip() lc_ctype = os.environ.get("LC_CTYPE", "") os.environ['LC_CTYPE'] = 'fr_FR.latin-1' @@ -198,7 +186,7 @@ def test_python2_gives_warning_if_bad_lc_ctype_and_non_ascii_chars(): def test_python2_does_not_give_warning_if_bad_lc_ctype_and_all_ascii_chars(): if sys.version_info[0] >= 3: - return 'skip' + pytest.skip() lc_ctype = os.environ.get("LC_CTYPE", "") os.environ['LC_CTYPE'] = 'fr_FR.latin-1' @@ -214,7 +202,7 @@ def test_python2_does_not_give_warning_if_bad_lc_ctype_and_all_ascii_chars(): def test_python2_does_not_give_warning_if_bad_lc_ctype_and_non_ascii_chars_in_folder(): if sys.version_info[0] >= 3: - return 'skip' + pytest.skip() lc_ctype = os.environ.get("LC_CTYPE", "") os.environ['LC_CTYPE'] = 'fr_FR.latin-1' @@ -230,7 +218,7 @@ def test_python2_does_not_give_warning_if_bad_lc_ctype_and_non_ascii_chars_in_fo def test_python3_handle_utf8_by_default(): if sys.version_info[0] < 3: - return 'skip' + pytest.skip() return _test_utf8(should_raise_unicode=False) @@ -241,7 +229,7 @@ def _test_utf8(should_raise_unicode=False, input_file="data/test_utf8_漢字.vrt"): script_path = test_py_scripts.get_py_script('gdal2tiles') if script_path is None: - return 'skip' + pytest.skip() out_folder = 'tmp/utf8_test' @@ -259,33 +247,24 @@ def _test_utf8(should_raise_unicode=False, print(ret) except UnicodeEncodeError: if should_raise_unicode: - return 'success' - gdaltest.post_reason('Should be handling filenames with utf8 characters in this context') - return 'fail' + return + pytest.fail('Should be handling filenames with utf8 characters in this context') - if should_raise_unicode: - gdaltest.post_reason( - 'Should not be handling filenames with utf8 characters in this context') - return 'fail' + assert not should_raise_unicode, \ + 'Should not be handling filenames with utf8 characters in this context' if should_display_warning: - if "WARNING" not in ret or "LC_CTYPE" not in ret: - gdaltest.post_reason( - 'Should display a warning message about LC_CTYPE variable') - return 'fail' + assert "WARNING" in ret and "LC_CTYPE" in ret, \ + 'Should display a warning message about LC_CTYPE variable' else: - if "WARNING" in ret and "LC_CTYPE" in ret: - gdaltest.post_reason( - 'Should not display a warning message about LC_CTYPE variable') - return 'fail' + assert not ("WARNING" in ret and "LC_CTYPE" in ret), \ + 'Should not display a warning message about LC_CTYPE variable' try: shutil.rmtree(out_folder) except OSError: pass - return 'success' - def test_gdal2tiles_py_cleanup(): @@ -296,13 +275,12 @@ def test_gdal2tiles_py_cleanup(): except Exception: pass - return 'success' - + def test_exclude_transparent_tiles(): script_path = test_py_scripts.get_py_script('gdal2tiles') if script_path is None: - return 'skip' + pytest.skip() output_folder = 'tmp/test_exclude_transparent_tiles' os.makedirs(output_folder) @@ -316,47 +294,25 @@ def test_exclude_transparent_tiles(): # First row totally transparent - no tiles tiles_folder = os.path.join(output_folder, '15', '21898') dir_files = os.listdir(tiles_folder) - if dir_files: - gdaltest.post_reason('Generated empty tiles for row 21898: %s' % dir_files) - return 'fail' + assert not dir_files, ('Generated empty tiles for row 21898: %s' % dir_files) # Second row - only 2 non-transparent tiles tiles_folder = os.path.join(output_folder, '15', '21899') dir_files = sorted(os.listdir(tiles_folder)) - if ['22704.png', '22705.png'] != dir_files: - gdaltest.post_reason('Generated empty tiles for row 21899: %s' % dir_files) - return 'fail' + assert ['22704.png', '22705.png'] == dir_files, \ + ('Generated empty tiles for row 21899: %s' % dir_files) # Third row - only 1 non-transparent tile tiles_folder = os.path.join(output_folder, '15', '21900') dir_files = os.listdir(tiles_folder) - if ['22705.png'] != dir_files: - gdaltest.post_reason('Generated empty tiles for row 21900: %s' % dir_files) - return 'fail' + assert ['22705.png'] == dir_files, \ + ('Generated empty tiles for row 21900: %s' % dir_files) - return 'success' + return finally: shutil.rmtree(output_folder) -gdaltest_list = [ - test_gdal2tiles_py_simple, - test_gdal2tiles_py_zoom_option, - test_does_not_error_when_source_bounds_close_to_tiles_bound, - test_does_not_error_when_nothing_to_put_in_the_low_zoom_tile, - test_python3_handle_utf8_by_default, - test_python2_handles_utf8_by_default, - test_python2_gives_warning_if_bad_lc_ctype_and_non_ascii_chars, - test_python2_does_not_give_warning_if_bad_lc_ctype_and_all_ascii_chars, - test_python2_does_not_give_warning_if_bad_lc_ctype_and_non_ascii_chars_in_folder, - test_gdal2tiles_py_cleanup, - test_exclude_transparent_tiles, -] - -if __name__ == '__main__': - gdaltest.setup_run('test_gdal2tiles_py') - gdaltest.run_tests(gdaltest_list) - sys.exit(gdaltest.summarize()) diff --git a/autotest/pyscripts/test_gdal_calc.py b/autotest/pyscripts/test_gdal_calc.py index 9d79d181a2ba..7cb779a13356 100755 --- a/autotest/pyscripts/test_gdal_calc.py +++ b/autotest/pyscripts/test_gdal_calc.py @@ -34,11 +34,10 @@ import os import shutil -sys.path.append('../pymod') from osgeo import gdal -import gdaltest import test_py_scripts +import pytest # test that gdalnumeric is available, if not skip all tests gdalnumeric_not_available = False @@ -57,12 +56,11 @@ def test_gdal_calc_py_1(): if gdalnumeric_not_available: - gdaltest.post_reason('gdalnumeric is not available, skipping all tests') - return 'skip' + pytest.skip('gdalnumeric is not available, skipping all tests') script_path = test_py_scripts.get_py_script('gdal_calc') if script_path is None: - return 'skip' + pytest.skip() shutil.copy('../gcore/data/stefan_full_rgba.tif', 'tmp/test_gdal_calc_py.tif') @@ -74,32 +72,18 @@ def test_gdal_calc_py_1(): ds2 = gdal.Open('tmp/test_gdal_calc_py_1_2.tif') ds3 = gdal.Open('tmp/test_gdal_calc_py_1_3.tif') - if ds1 is None: - gdaltest.post_reason('ds1 not found') - return 'fail' - if ds2 is None: - gdaltest.post_reason('ds2 not found') - return 'fail' - if ds3 is None: - gdaltest.post_reason('ds3 not found') - return 'fail' - - if ds1.GetRasterBand(1).Checksum() != 12603: - gdaltest.post_reason('ds1 wrong checksum') - return 'fail' - if ds2.GetRasterBand(1).Checksum() != 58561: - gdaltest.post_reason('ds2 wrong checksum') - return 'fail' - if ds3.GetRasterBand(1).Checksum() != 58561: - gdaltest.post_reason('ds3 wrong checksum') - return 'fail' + assert ds1 is not None, 'ds1 not found' + assert ds2 is not None, 'ds2 not found' + assert ds3 is not None, 'ds3 not found' + + assert ds1.GetRasterBand(1).Checksum() == 12603, 'ds1 wrong checksum' + assert ds2.GetRasterBand(1).Checksum() == 58561, 'ds2 wrong checksum' + assert ds3.GetRasterBand(1).Checksum() == 58561, 'ds3 wrong checksum' ds1 = None ds2 = None ds3 = None - return 'success' - ############################################################################### # test simple formulas @@ -107,11 +91,11 @@ def test_gdal_calc_py_1(): def test_gdal_calc_py_2(): if gdalnumeric_not_available: - return 'skip' + pytest.skip() script_path = test_py_scripts.get_py_script('gdal_calc') if script_path is None: - return 'skip' + pytest.skip() test_py_scripts.run_py_script(script_path, 'gdal_calc', '-A tmp/test_gdal_calc_py.tif --A_band 1 -B tmp/test_gdal_calc_py.tif --B_band 2 --calc=A+B --overwrite --outfile tmp/test_gdal_calc_py_2_1.tif') test_py_scripts.run_py_script(script_path, 'gdal_calc', '-A tmp/test_gdal_calc_py.tif --A_band 1 -B tmp/test_gdal_calc_py.tif --B_band 2 --calc=A*B --overwrite --outfile tmp/test_gdal_calc_py_2_2.tif') @@ -121,30 +105,16 @@ def test_gdal_calc_py_2(): ds2 = gdal.Open('tmp/test_gdal_calc_py_2_2.tif') ds3 = gdal.Open('tmp/test_gdal_calc_py_2_3.tif') - if ds1 is None: - gdaltest.post_reason('ds1 not found') - return 'fail' - if ds2 is None: - gdaltest.post_reason('ds2 not found') - return 'fail' - if ds3 is None: - gdaltest.post_reason('ds3 not found') - return 'fail' - if ds1.GetRasterBand(1).Checksum() != 12368: - gdaltest.post_reason('ds1 wrong checksum') - return 'fail' - if ds2.GetRasterBand(1).Checksum() != 62785: - gdaltest.post_reason('ds2 wrong checksum') - return 'fail' - if ds3.GetRasterBand(1).Checksum() != 47132: - gdaltest.post_reason('ds3 wrong checksum') - return 'fail' + assert ds1 is not None, 'ds1 not found' + assert ds2 is not None, 'ds2 not found' + assert ds3 is not None, 'ds3 not found' + assert ds1.GetRasterBand(1).Checksum() == 12368, 'ds1 wrong checksum' + assert ds2.GetRasterBand(1).Checksum() == 62785, 'ds2 wrong checksum' + assert ds3.GetRasterBand(1).Checksum() == 47132, 'ds3 wrong checksum' ds1 = None ds2 = None ds3 = None - return 'success' - ############################################################################### # test --allBands option (simple copy) @@ -152,36 +122,24 @@ def test_gdal_calc_py_2(): def test_gdal_calc_py_3(): if gdalnumeric_not_available: - return 'skip' + pytest.skip() script_path = test_py_scripts.get_py_script('gdal_calc') if script_path is None: - return 'skip' + pytest.skip() test_py_scripts.run_py_script(script_path, 'gdal_calc', '-A tmp/test_gdal_calc_py.tif --allBands A --calc=A --overwrite --outfile tmp/test_gdal_calc_py_3.tif') ds = gdal.Open('tmp/test_gdal_calc_py_3.tif') - if ds is None: - gdaltest.post_reason('ds not found') - return 'fail' - if ds.GetRasterBand(1).Checksum() != 12603: - gdaltest.post_reason('band 1 wrong checksum') - return 'fail' - if ds.GetRasterBand(2).Checksum() != 58561: - gdaltest.post_reason('band 2 wrong checksum') - return 'fail' - if ds.GetRasterBand(3).Checksum() != 36064: - gdaltest.post_reason('band 3 wrong checksum') - return 'fail' - if ds.GetRasterBand(4).Checksum() != 10807: - gdaltest.post_reason('band 4 wrong checksum') - return 'fail' + assert ds is not None, 'ds not found' + assert ds.GetRasterBand(1).Checksum() == 12603, 'band 1 wrong checksum' + assert ds.GetRasterBand(2).Checksum() == 58561, 'band 2 wrong checksum' + assert ds.GetRasterBand(3).Checksum() == 36064, 'band 3 wrong checksum' + assert ds.GetRasterBand(4).Checksum() == 10807, 'band 4 wrong checksum' ds = None - return 'success' - ############################################################################### # test --allBands option (simple calc) @@ -189,11 +147,11 @@ def test_gdal_calc_py_3(): def test_gdal_calc_py_4(): if gdalnumeric_not_available: - return 'skip' + pytest.skip() script_path = test_py_scripts.get_py_script('gdal_calc') if script_path is None: - return 'skip' + pytest.skip() # some values are clipped to 255, but this doesn't matter... small values were visually checked test_py_scripts.run_py_script(script_path, 'gdal_calc', '-A tmp/test_gdal_calc_py.tif --calc=1 --overwrite --outfile tmp/test_gdal_calc_py_4_1.tif') @@ -201,18 +159,10 @@ def test_gdal_calc_py_4(): ds1 = gdal.Open('tmp/test_gdal_calc_py_4_2.tif') - if ds1 is None: - gdaltest.post_reason('ds1 not found') - return 'fail' - if ds1.GetRasterBand(1).Checksum() != 29935: - gdaltest.post_reason('ds1 band 1 wrong checksum') - return 'fail' - if ds1.GetRasterBand(2).Checksum() != 13128: - gdaltest.post_reason('ds1 band 2 wrong checksum') - return 'fail' - if ds1.GetRasterBand(3).Checksum() != 59092: - gdaltest.post_reason('ds1 band 3 wrong checksum') - return 'fail' + assert ds1 is not None, 'ds1 not found' + assert ds1.GetRasterBand(1).Checksum() == 29935, 'ds1 band 1 wrong checksum' + assert ds1.GetRasterBand(2).Checksum() == 13128, 'ds1 band 2 wrong checksum' + assert ds1.GetRasterBand(3).Checksum() == 59092, 'ds1 band 3 wrong checksum' ds1 = None @@ -221,23 +171,13 @@ def test_gdal_calc_py_4(): ds2 = gdal.Open('tmp/test_gdal_calc_py_4_3.tif') - if ds2 is None: - gdaltest.post_reason('ds2 not found') - return 'fail' - if ds2.GetRasterBand(1).Checksum() != 10025: - gdaltest.post_reason('ds2 band 1 wrong checksum') - return 'fail' - if ds2.GetRasterBand(2).Checksum() != 62785: - gdaltest.post_reason('ds2 band 2 wrong checksum') - return 'fail' - if ds2.GetRasterBand(3).Checksum() != 10621: - gdaltest.post_reason('ds2 band 3 wrong checksum') - return 'fail' + assert ds2 is not None, 'ds2 not found' + assert ds2.GetRasterBand(1).Checksum() == 10025, 'ds2 band 1 wrong checksum' + assert ds2.GetRasterBand(2).Checksum() == 62785, 'ds2 band 2 wrong checksum' + assert ds2.GetRasterBand(3).Checksum() == 10621, 'ds2 band 3 wrong checksum' ds2 = None - return 'success' - ############################################################################### # test python interface, basic copy @@ -245,12 +185,11 @@ def test_gdal_calc_py_4(): def test_gdal_calc_py_5(): if gdalnumeric_not_available: - gdaltest.post_reason('gdalnumeric is not available, skipping all tests') - return 'skip' + pytest.skip('gdalnumeric is not available, skipping all tests') script_path = test_py_scripts.get_py_script('gdal_calc') if script_path is None: - return 'skip' + pytest.skip() backup_sys_path = sys.path sys.path.insert(0, script_path) @@ -268,32 +207,18 @@ def test_gdal_calc_py_5(): ds2 = gdal.Open('tmp/test_gdal_calc_py_5_2.tif') ds3 = gdal.Open('tmp/test_gdal_calc_py_5_3.tif') - if ds1 is None: - gdaltest.post_reason('ds1 not found') - return 'fail' - if ds2 is None: - gdaltest.post_reason('ds2 not found') - return 'fail' - if ds3 is None: - gdaltest.post_reason('ds3 not found') - return 'fail' - - if ds1.GetRasterBand(1).Checksum() != 12603: - gdaltest.post_reason('ds1 wrong checksum') - return 'fail' - if ds2.GetRasterBand(1).Checksum() != 58561: - gdaltest.post_reason('ds2 wrong checksum') - return 'fail' - if ds3.GetRasterBand(1).Checksum() != 58561: - gdaltest.post_reason('ds3 wrong checksum') - return 'fail' + assert ds1 is not None, 'ds1 not found' + assert ds2 is not None, 'ds2 not found' + assert ds3 is not None, 'ds3 not found' + + assert ds1.GetRasterBand(1).Checksum() == 12603, 'ds1 wrong checksum' + assert ds2.GetRasterBand(1).Checksum() == 58561, 'ds2 wrong checksum' + assert ds3.GetRasterBand(1).Checksum() == 58561, 'ds3 wrong checksum' ds1 = None ds2 = None ds3 = None - return 'success' - ############################################################################### # test nodata @@ -301,12 +226,11 @@ def test_gdal_calc_py_5(): def test_gdal_calc_py_6(): if gdalnumeric_not_available: - gdaltest.post_reason('gdalnumeric is not available, skipping all tests') - return 'skip' + pytest.skip('gdalnumeric is not available, skipping all tests') script_path = test_py_scripts.get_py_script('gdal_calc') if script_path is None: - return 'skip' + pytest.skip() backup_sys_path = sys.path sys.path.insert(0, script_path) @@ -320,29 +244,20 @@ def test_gdal_calc_py_6(): ds = gdal.Open('tmp/test_gdal_calc_py_6.tif') cs = ds.GetRasterBand(1).Checksum() - if cs != 4673: - gdaltest.post_reason('failure') - print(cs) - return 'fail' + assert cs == 4673 result = ds.GetRasterBand(1).ComputeRasterMinMax() - if result != (90, 255): - gdaltest.post_reason('failure') - print(result) - return 'fail' - - return 'success' + assert result == (90, 255) ############################################################################### # test --optfile def test_gdal_calc_py_7(): if gdalnumeric_not_available: - gdaltest.post_reason('gdalnumeric is not available, skipping all tests') - return 'skip' + pytest.skip('gdalnumeric is not available, skipping all tests') script_path = test_py_scripts.get_py_script('gdal_calc') if script_path is None: - return 'skip' + pytest.skip() shutil.copy('../gcore/data/stefan_full_rgba.tif', 'tmp/test_gdal_calc_py.tif') @@ -376,39 +291,21 @@ def test_gdal_calc_py_7(): ds3 = gdal.Open('tmp/test_gdal_calc_py_7_3.tif') ds4 = gdal.Open('tmp/test_gdal_calc_py_7_4.tif') - if ds1 is None: - gdaltest.post_reason('ds1 not found') - return 'fail' - if ds2 is None: - gdaltest.post_reason('ds2 not found') - return 'fail' - if ds3 is None: - gdaltest.post_reason('ds3 not found') - return 'fail' - if ds4 is None: - gdaltest.post_reason('ds4 not found') - return 'fail' - - if ds1.GetRasterBand(1).Checksum() != 12603: - gdaltest.post_reason('ds1 wrong checksum') - return 'fail' - if ds2.GetRasterBand(1).Checksum() != 58561: - gdaltest.post_reason('ds2 wrong checksum') - return 'fail' - if ds3.GetRasterBand(1).Checksum() != 58561: - gdaltest.post_reason('ds3 wrong checksum') - return 'fail' - if ds4.GetRasterBand(1).Checksum() != 58561: - gdaltest.post_reason('ds4 wrong checksum') - return 'fail' + assert ds1 is not None, 'ds1 not found' + assert ds2 is not None, 'ds2 not found' + assert ds3 is not None, 'ds3 not found' + assert ds4 is not None, 'ds4 not found' + + assert ds1.GetRasterBand(1).Checksum() == 12603, 'ds1 wrong checksum' + assert ds2.GetRasterBand(1).Checksum() == 58561, 'ds2 wrong checksum' + assert ds3.GetRasterBand(1).Checksum() == 58561, 'ds3 wrong checksum' + assert ds4.GetRasterBand(1).Checksum() == 58561, 'ds4 wrong checksum' ds1 = None ds2 = None ds3 = None ds4 = None - return 'success' - def test_gdal_calc_py_cleanup(): lst = ['tmp/test_gdal_calc_py.tif', @@ -440,25 +337,7 @@ def test_gdal_calc_py_cleanup(): except OSError: pass - return 'success' - - -gdaltest_list = [ - test_gdal_calc_py_1, - test_gdal_calc_py_2, - test_gdal_calc_py_3, - test_gdal_calc_py_4, - test_gdal_calc_py_5, - test_gdal_calc_py_6, - test_gdal_calc_py_7, - test_gdal_calc_py_cleanup -] - - -if __name__ == '__main__': + - gdaltest.setup_run('test_gdal_calc_py') - gdaltest.run_tests(gdaltest_list) - sys.exit(gdaltest.summarize()) diff --git a/autotest/pyscripts/test_gdal_edit.py b/autotest/pyscripts/test_gdal_edit.py index 26dbe66404e1..c3e10533d96e 100755 --- a/autotest/pyscripts/test_gdal_edit.py +++ b/autotest/pyscripts/test_gdal_edit.py @@ -33,11 +33,10 @@ import os import shutil -sys.path.append('../pymod') from osgeo import gdal -import gdaltest import test_py_scripts +import pytest # Usage: gdal_edit [--help-general] [-a_srs srs_def] [-a_ullr ulx uly lrx lry] # [-tr xres yres] [-a_nodata value] @@ -53,7 +52,7 @@ def test_gdal_edit_py_1(): script_path = test_py_scripts.get_py_script('gdal_edit') if script_path is None: - return 'skip' + pytest.skip() shutil.copy('../gcore/data/byte.tif', 'tmp/test_gdal_edit_py.tif') @@ -77,39 +76,19 @@ def test_gdal_edit_py_1(): md = ds.GetMetadata() ds = None - if wkt.find('4326') == -1: - gdaltest.post_reason('fail') - print(wkt) - return 'fail' + assert wkt.find('4326') != -1 expected_gt = (2.0, 0.050000000000000003, 0.0, 50.0, 0.0, -0.050000000000000003) for i in range(6): - if abs(gt[i] - expected_gt[i]) > 1e-10: - gdaltest.post_reason('fail') - print(gt) - return 'fail' + assert abs(gt[i] - expected_gt[i]) <= 1e-10 - if nd != 123: - gdaltest.post_reason('fail') - print(nd) - return 'fail' + assert nd == 123 - if md['FOO'] != 'BAR': - gdaltest.post_reason('fail') - print(md) - return 'fail' + assert md['FOO'] == 'BAR' - if md['UTF8'] != val: - gdaltest.post_reason('fail') - print(md) - return 'fail' + assert md['UTF8'] == val - if md[val] != 'UTF8': - gdaltest.post_reason('fail') - print(md) - return 'fail' - - return 'success' + assert md[val] == 'UTF8' ############################################################################### # Test -unsetgt @@ -119,7 +98,7 @@ def test_gdal_edit_py_2(): script_path = test_py_scripts.get_py_script('gdal_edit') if script_path is None: - return 'skip' + pytest.skip() shutil.copy('../gcore/data/byte.tif', 'tmp/test_gdal_edit_py.tif') @@ -130,17 +109,9 @@ def test_gdal_edit_py_2(): gt = ds.GetGeoTransform(can_return_null=True) ds = None - if gt is not None: - gdaltest.post_reason('fail') - print(gt) - return 'fail' - - if wkt == '': - gdaltest.post_reason('fail') - print(wkt) - return 'fail' + assert gt is None - return 'success' + assert wkt != '' ############################################################################### # Test -a_srs '' @@ -150,7 +121,7 @@ def test_gdal_edit_py_3(): script_path = test_py_scripts.get_py_script('gdal_edit') if script_path is None: - return 'skip' + pytest.skip() shutil.copy('../gcore/data/byte.tif', 'tmp/test_gdal_edit_py.tif') @@ -161,17 +132,9 @@ def test_gdal_edit_py_3(): gt = ds.GetGeoTransform() ds = None - if gt == (0.0, 1.0, 0.0, 0.0, 0.0, 1.0): - gdaltest.post_reason('fail') - print(gt) - return 'fail' - - if wkt != '': - gdaltest.post_reason('fail') - print(wkt) - return 'fail' + assert gt != (0.0, 1.0, 0.0, 0.0, 0.0, 1.0) - return 'success' + assert wkt == '' ############################################################################### # Test -unsetstats @@ -181,7 +144,7 @@ def test_gdal_edit_py_4(): script_path = test_py_scripts.get_py_script('gdal_edit') if script_path is None: - return 'skip' + pytest.skip() shutil.copy('../gcore/data/byte.tif', 'tmp/test_gdal_edit_py.tif') ds = gdal.Open('tmp/test_gdal_edit_py.tif', gdal.GA_Update) @@ -192,31 +155,23 @@ def test_gdal_edit_py_4(): ds = gdal.Open('tmp/test_gdal_edit_py.tif') band = ds.GetRasterBand(1) - if (band.GetMetadataItem('STATISTICS_MINIMUM') is None or - band.GetMetadataItem('FOO') is None): - gdaltest.post_reason('fail') - return 'fail' + assert (not (band.GetMetadataItem('STATISTICS_MINIMUM') is None or + band.GetMetadataItem('FOO') is None)) ds = band = None test_py_scripts.run_py_script(script_path, 'gdal_edit', "tmp/test_gdal_edit_py.tif -unsetstats") ds = gdal.Open('tmp/test_gdal_edit_py.tif') band = ds.GetRasterBand(1) - if (band.GetMetadataItem('STATISTICS_MINIMUM') is not None or - band.GetMetadataItem('FOO') is None): - gdaltest.post_reason('fail') - return 'fail' + assert (not (band.GetMetadataItem('STATISTICS_MINIMUM') is not None or + band.GetMetadataItem('FOO') is None)) ds = band = None - try: + with pytest.raises(OSError): os.stat('tmp/test_gdal_edit_py.tif.aux.xml') - gdaltest.post_reason('fail') - return 'fail' - except OSError: - pass - - return 'success' + + ############################################################################### # Test -stats @@ -225,13 +180,13 @@ def test_gdal_edit_py_5(): script_path = test_py_scripts.get_py_script('gdal_edit') if script_path is None: - return 'skip' + pytest.skip() try: from osgeo import gdalnumeric gdalnumeric.BandRasterIONumPy except: - return 'skip' + pytest.skip() shutil.copy('../gcore/data/byte.tif', 'tmp/test_gdal_edit_py.tif') ds = gdal.Open('tmp/test_gdal_edit_py.tif', gdal.GA_Update) @@ -243,18 +198,14 @@ def test_gdal_edit_py_5(): ds = band = None ds = gdal.Open('tmp/test_gdal_edit_py.tif') - if ds.ReadAsArray()[15, 12] != 22: - gdaltest.post_reason('fail') - return 'fail' + assert ds.ReadAsArray()[15, 12] == 22 ds = None test_py_scripts.run_py_script(script_path, 'gdal_edit', "tmp/test_gdal_edit_py.tif -stats") ds = gdal.Open('tmp/test_gdal_edit_py.tif') stat_min = ds.GetRasterBand(1).GetMetadataItem('STATISTICS_MINIMUM') - if stat_min is None or float(stat_min) != 22: - gdaltest.post_reason('fail') - return 'fail' + assert stat_min is not None and float(stat_min) == 22 ds = None ds = gdal.Open('tmp/test_gdal_edit_py.tif', gdal.GA_Update) @@ -265,22 +216,16 @@ def test_gdal_edit_py_5(): ds = band = None ds = gdal.Open('tmp/test_gdal_edit_py.tif') - if ds.ReadAsArray()[15, 12] != 26: - gdaltest.post_reason('fail') - return 'fail' + assert ds.ReadAsArray()[15, 12] == 26 ds = None test_py_scripts.run_py_script(script_path, 'gdal_edit', "tmp/test_gdal_edit_py.tif -stats") ds = gdal.Open('tmp/test_gdal_edit_py.tif') stat_min = ds.GetRasterBand(1).GetMetadataItem('STATISTICS_MINIMUM') - if stat_min is None or float(stat_min) != 26: - gdaltest.post_reason('fail') - return 'fail' + assert stat_min is not None and float(stat_min) == 26 ds = None - return 'success' - ############################################################################### # Test -setstats @@ -289,7 +234,7 @@ def test_gdal_edit_py_6(): script_path = test_py_scripts.get_py_script('gdal_edit') if script_path is None: - return 'skip' + pytest.skip() shutil.copy('../gcore/data/byte.tif', 'tmp/test_gdal_edit_py.tif') @@ -298,46 +243,28 @@ def test_gdal_edit_py_6(): ds = gdal.Open('tmp/test_gdal_edit_py.tif') stat_min = ds.GetRasterBand(1).GetMetadataItem('STATISTICS_MINIMUM') - if stat_min is None or float(stat_min) != 74: - gdaltest.post_reason('fail') - return 'fail' + assert stat_min is not None and float(stat_min) == 74 stat_max = ds.GetRasterBand(1).GetMetadataItem('STATISTICS_MAXIMUM') - if stat_max is None or float(stat_max) != 255: - gdaltest.post_reason('fail') - return 'fail' + assert stat_max is not None and float(stat_max) == 255 stat_mean = ds.GetRasterBand(1).GetMetadataItem('STATISTICS_MEAN') - if stat_mean is None or abs(float(stat_mean) - 126.765)>0.001: - gdaltest.post_reason('fail') - return 'fail' + assert not (stat_mean is None or abs(float(stat_mean) - 126.765)>0.001) stat_stddev = ds.GetRasterBand(1).GetMetadataItem('STATISTICS_STDDEV') - if stat_stddev is None or abs(float(stat_stddev) - 22.928)>0.001: - gdaltest.post_reason('fail') - return 'fail' - + assert not (stat_stddev is None or abs(float(stat_stddev) - 22.928)>0.001) + ds = None test_py_scripts.run_py_script(script_path, 'gdal_edit', "tmp/test_gdal_edit_py.tif -setstats 22 217 100 30") ds = gdal.Open('tmp/test_gdal_edit_py.tif') stat_min = ds.GetRasterBand(1).GetMetadataItem('STATISTICS_MINIMUM') - if stat_min is None or float(stat_min) != 22: - gdaltest.post_reason('fail') - return 'fail' + assert stat_min is not None and float(stat_min) == 22 stat_max = ds.GetRasterBand(1).GetMetadataItem('STATISTICS_MAXIMUM') - if stat_max is None or float(stat_max) != 217: - gdaltest.post_reason('fail') - return 'fail' + assert stat_max is not None and float(stat_max) == 217 stat_mean = ds.GetRasterBand(1).GetMetadataItem('STATISTICS_MEAN') - if stat_mean is None or float(stat_mean) != 100: - gdaltest.post_reason('fail') - return 'fail' + assert stat_mean is not None and float(stat_mean) == 100 stat_stddev = ds.GetRasterBand(1).GetMetadataItem('STATISTICS_STDDEV') - if stat_stddev is None or float(stat_stddev) != 30: - gdaltest.post_reason('fail') - return 'fail' + assert stat_stddev is not None and float(stat_stddev) == 30 ds = None - - return 'success' ############################################################################### # Test -scale and -offset @@ -346,21 +273,15 @@ def test_gdal_edit_py_7(): script_path = test_py_scripts.get_py_script('gdal_edit') if script_path is None: - return 'skip' + pytest.skip() shutil.copy('../gcore/data/byte.tif', 'tmp/test_gdal_edit_py.tif') test_py_scripts.run_py_script(script_path, 'gdal_edit', "tmp/test_gdal_edit_py.tif -scale 2 -offset 3") ds = gdal.Open('tmp/test_gdal_edit_py.tif') - if ds.GetRasterBand(1).GetScale() != 2: - gdaltest.post_reason('fail') - return 'fail' - if ds.GetRasterBand(1).GetOffset() != 3: - gdaltest.post_reason('fail') - return 'fail' - - return 'success' + assert ds.GetRasterBand(1).GetScale() == 2 + assert ds.GetRasterBand(1).GetOffset() == 3 ############################################################################### # Test -colorinterp_X @@ -370,7 +291,7 @@ def test_gdal_edit_py_8(): script_path = test_py_scripts.get_py_script('gdal_edit') if script_path is None: - return 'skip' + pytest.skip() gdal.Translate('tmp/test_gdal_edit_py.tif', '../gcore/data/byte.tif', @@ -379,18 +300,12 @@ def test_gdal_edit_py_8(): test_py_scripts.run_py_script(script_path, 'gdal_edit', "tmp/test_gdal_edit_py.tif -colorinterp_4 alpha") ds = gdal.Open('tmp/test_gdal_edit_py.tif') - if ds.GetRasterBand(4).GetColorInterpretation() != gdal.GCI_AlphaBand: - gdaltest.post_reason('fail') - return 'fail' + assert ds.GetRasterBand(4).GetColorInterpretation() == gdal.GCI_AlphaBand test_py_scripts.run_py_script(script_path, 'gdal_edit', "tmp/test_gdal_edit_py.tif -colorinterp_4 undefined") ds = gdal.Open('tmp/test_gdal_edit_py.tif') - if ds.GetRasterBand(4).GetColorInterpretation() != gdal.GCI_Undefined: - gdaltest.post_reason('fail') - return 'fail' - - return 'success' + assert ds.GetRasterBand(4).GetColorInterpretation() == gdal.GCI_Undefined ############################################################################### @@ -399,7 +314,7 @@ def test_gdal_edit_py_unsetrpc(): script_path = test_py_scripts.get_py_script('gdal_edit') if script_path is None: - return 'skip' + pytest.skip() gdal.Translate('tmp/test_gdal_edit_py.tif', '../gcore/data/byte_rpc.tif') @@ -407,11 +322,7 @@ def test_gdal_edit_py_unsetrpc(): "tmp/test_gdal_edit_py.tif -unsetrpc") ds = gdal.Open('tmp/test_gdal_edit_py.tif') - if ds.GetMetadata('RPC'): - gdaltest.post_reason('fail') - return 'fail' - - return 'success' + assert not ds.GetMetadata('RPC') ############################################################################### # Cleanup @@ -421,27 +332,6 @@ def test_gdal_edit_py_cleanup(): gdal.Unlink('tmp/test_gdal_edit_py.tif') - return 'success' - - -gdaltest_list = [ - test_gdal_edit_py_1, - test_gdal_edit_py_2, - test_gdal_edit_py_3, - test_gdal_edit_py_4, - test_gdal_edit_py_5, - test_gdal_edit_py_6, - test_gdal_edit_py_7, - test_gdal_edit_py_8, - test_gdal_edit_py_unsetrpc, - test_gdal_edit_py_cleanup, -] - - -if __name__ == '__main__': - gdaltest.setup_run('test_gdal_edit_py') - gdaltest.run_tests(gdaltest_list) - sys.exit(gdaltest.summarize()) diff --git a/autotest/pyscripts/test_gdal_fillnodata.py b/autotest/pyscripts/test_gdal_fillnodata.py index f22778b1aa6f..25aaed681ff4 100755 --- a/autotest/pyscripts/test_gdal_fillnodata.py +++ b/autotest/pyscripts/test_gdal_fillnodata.py @@ -29,14 +29,12 @@ ############################################################################### -import sys import os -sys.path.append('../pymod') from osgeo import gdal -import gdaltest import test_py_scripts +import pytest ############################################################################### # Dummy test : there is no nodata value in the source dataset ! @@ -46,17 +44,14 @@ def test_gdal_fillnodata_1(): script_path = test_py_scripts.get_py_script('gdal_fillnodata') if script_path is None: - return 'skip' + pytest.skip() test_py_scripts.run_py_script(script_path, 'gdal_fillnodata', '../gcore/data/byte.tif tmp/test_gdal_fillnodata_1.tif') ds = gdal.Open('tmp/test_gdal_fillnodata_1.tif') - if ds.GetRasterBand(1).Checksum() != 4672: - return 'fail' + assert ds.GetRasterBand(1).Checksum() == 4672 ds = None - return 'success' - ############################################################################### # Make sure we copy the no data value to the dst when created # No data value for nodata_byte.tif is 0. @@ -66,18 +61,15 @@ def test_gdal_fillnodata_2(): script_path = test_py_scripts.get_py_script('gdal_fillnodata') if script_path is None: - return 'skip' + pytest.skip() test_py_scripts.run_py_script(script_path, 'gdal_fillnodata', '../gcore/data/nodata_byte.tif tmp/test_gdal_fillnodata_2.tif') ds = gdal.Open('tmp/test_gdal_fillnodata_2.tif') - if ds.GetRasterBand(1).GetNoDataValue() != 0: - gdaltest.post_reason('Failed to copy No Data Value to dst dataset.') - return 'fail' + assert ds.GetRasterBand(1).GetNoDataValue() == 0, \ + 'Failed to copy No Data Value to dst dataset.' ds = None - return 'success' - ############################################################################### # Cleanup @@ -91,20 +83,7 @@ def test_gdal_fillnodata_cleanup(): except OSError: pass - return 'success' - - -gdaltest_list = [ - test_gdal_fillnodata_1, - test_gdal_fillnodata_2, - test_gdal_fillnodata_cleanup -] - - -if __name__ == '__main__': + - gdaltest.setup_run('test_gdal_fillnodata') - gdaltest.run_tests(gdaltest_list) - sys.exit(gdaltest.summarize()) diff --git a/autotest/pyscripts/test_gdal_ls_py.py b/autotest/pyscripts/test_gdal_ls_py.py index 043e653a241d..5bf1d8119568 100755 --- a/autotest/pyscripts/test_gdal_ls_py.py +++ b/autotest/pyscripts/test_gdal_ls_py.py @@ -32,10 +32,10 @@ import sys from osgeo import gdal -sys.path.append('../pymod') import gdaltest import test_py_scripts +import pytest ############################################################################### @@ -43,7 +43,7 @@ def run_gdal_ls(argv): script_path = test_py_scripts.get_py_script('gdal_ls') if script_path is None: - return ('skip', None) + pytest.skip() saved_syspath = sys.path sys.path.append(script_path) @@ -51,7 +51,7 @@ def run_gdal_ls(argv): import gdal_ls except ImportError: sys.path = saved_syspath - return ('fail', None) + pytest.fail() sys.path = saved_syspath @@ -66,11 +66,9 @@ def run_gdal_ls(argv): retstr = outstr.getvalue() outstr.close() - if ret != 0: - gdaltest.post_reason('got error code : %d' % ret) - return ('fail', 'None') + assert ret == 0, 'got error code : %d' % ret - return ('success', retstr) + return retstr ############################################################################### # List one file @@ -78,69 +76,44 @@ def run_gdal_ls(argv): def test_gdal_ls_py_1(): # TODO: Why the '' as the first element of the list here and below? - ret, ret_str = run_gdal_ls(['', '-l', '../ogr/data/poly.shp']) + ret_str = run_gdal_ls(['', '-l', '../ogr/data/poly.shp']) - if ret != 'success': - return ret - - if ret_str.find('poly.shp') == -1: - print(ret_str) - return 'fail' - - return 'success' + assert ret_str.find('poly.shp') != -1 ############################################################################### # List one dir def test_gdal_ls_py_2(): - ret, ret_str = run_gdal_ls(['', '-l', '../ogr/data']) - - if ret != 'success': - return ret + ret_str = run_gdal_ls(['', '-l', '../ogr/data']) - if ret_str.find('poly.shp') == -1: - print(ret_str) - return 'fail' - - return 'success' + assert ret_str.find('poly.shp') != -1 ############################################################################### # List recursively def test_gdal_ls_py_3(): - ret, ret_str = run_gdal_ls(['', '-R', '../ogr/data']) - - if ret != 'success': - return ret + ret_str = run_gdal_ls(['', '-R', '../ogr/data']) - if ret_str.find('PROJ_UNITS') == -1: - print(ret_str) - return 'fail' + assert ret_str.find('PROJ_UNITS') != -1 - return 'success' ############################################################################### # List in a .zip def test_gdal_ls_py_4(): - ret, ret_str = run_gdal_ls(['', '-l', '/vsizip/../ogr/data/poly.zip']) - - if ret != 'success': - return ret + ret_str = run_gdal_ls(['', '-l', '/vsizip/../ogr/data/poly.zip']) if ret_str.find('-r--r--r-- 1 unknown unknown 415 2008-02-11 21:35 /vsizip/../ogr/data/poly.zip/poly.PRJ') == -1: - print(ret_str) if gdaltest.skip_on_travis(): # FIXME # Fails on Travis with dates at 1970-01-01 00:00 # Looks like a 32/64bit issue with Python bindings of VSIStatL() - return 'skip' - return 'fail' + pytest.skip() + pytest.fail(ret_str) - return 'success' ############################################################################### # List dir in /vsicurl/ @@ -150,30 +123,26 @@ def test_gdal_ls_py_5(): drv = gdal.GetDriverByName('HTTP') if drv is None: - return 'skip' + pytest.skip() if int(gdal.VersionInfo('VERSION_NUM')) < 1900: - gdaltest.post_reason('would stall for a long time') - return 'skip' + pytest.skip('would stall for a long time') f = gdal.VSIFOpenL('/vsicurl/https://raw.githubusercontent.com/OSGeo/gdal/master/autotest/ogr/data/poly.zip', 'rb') if f is None: - return 'skip' + pytest.skip() d = gdal.VSIFReadL(1, 1, f) gdal.VSIFCloseL(f) if not d: - return 'skip' + pytest.skip() + + # ret_str = run_gdal_ls(['', '-R', 'https://raw.githubusercontent.com/OSGeo/gdal/master/autotest/ogr/data/']) - # ret, ret_str = run_gdal_ls(['', '-R', 'https://raw.githubusercontent.com/OSGeo/gdal/master/autotest/ogr/data/']) - # - # if ret != 'success': - # return ret # # if ret_str.find('/vsicurl/https://raw.githubusercontent.com/OSGeo/gdal/master/autotest/ogr/data/wkb_wkt/3d_broken_line.wkb') == -1: # print(ret_str) - # return 'fail' + # pytest.fail() - return 'success' ############################################################################### # List in a .zip in /vsicurl/ @@ -183,31 +152,26 @@ def test_gdal_ls_py_6(): drv = gdal.GetDriverByName('HTTP') if drv is None: - return 'skip' + pytest.skip() f = gdal.VSIFOpenL('/vsicurl/https://raw.githubusercontent.com/OSGeo/gdal/master/autotest/ogr/data/poly.zip', 'rb') if f is None: - return 'skip' + pytest.skip() d = gdal.VSIFReadL(1, 1, f) gdal.VSIFCloseL(f) if not d: - return 'skip' + pytest.skip() - ret, ret_str = run_gdal_ls(['', '-l', '/vsizip/vsicurl/https://raw.githubusercontent.com/OSGeo/gdal/master/autotest/ogr/data/poly.zip']) - - if ret != 'success': - return ret + ret_str = run_gdal_ls(['', '-l', '/vsizip/vsicurl/https://raw.githubusercontent.com/OSGeo/gdal/master/autotest/ogr/data/poly.zip']) if ret_str.find('-r--r--r-- 1 unknown unknown 415 2008-02-11 21:35 /vsizip/vsicurl/https://raw.githubusercontent.com/OSGeo/gdal/master/autotest/ogr/data/poly.zip/poly.PRJ') == -1: - print(ret_str) if gdaltest.skip_on_travis(): # FIXME # Fails on Travis with dates at 1970-01-01 00:00 # Looks like a 32/64bit issue with Python bindings of VSIStatL() - return 'skip' - return 'fail' + pytest.skip() + pytest.fail(ret_str) - return 'success' ############################################################################### # List dir in /vsicurl/ and recurse in zip @@ -217,35 +181,29 @@ def test_gdal_ls_py_7(): # Super slow on AppVeyor since a few weeks (Apr 2016) if gdal.GetConfigOption('APPVEYOR') is not None: - print('Slow on AppVeyor') - return 'skip' + pytest.skip('Slow on AppVeyor') drv = gdal.GetDriverByName('HTTP') if drv is None: - return 'skip' + pytest.skip() if int(gdal.VersionInfo('VERSION_NUM')) < 1900: - gdaltest.post_reason('would stall for a long time') - return 'skip' + pytest.skip('would stall for a long time') f = gdal.VSIFOpenL('/vsicurl/https://raw.githubusercontent.com/OSGeo/gdal/master/autotest/ogr/data/poly.zip', 'rb') if f is None: - return 'skip' + pytest.skip() d = gdal.VSIFReadL(1, 1, f) gdal.VSIFCloseL(f) if not d: - return 'skip' - - # ret, ret_str = run_gdal_ls(['', '-R', '-Rzip', 'https://raw.githubusercontent.com/OSGeo/gdal/master/autotest/ogr/data/']) + pytest.skip() - # if ret != 'success': - # return ret + # ret_str = run_gdal_ls(['', '-R', '-Rzip', 'https://raw.githubusercontent.com/OSGeo/gdal/master/autotest/ogr/data/']) # if ret_str.find('/vsizip//vsicurl/https://raw.githubusercontent.com/OSGeo/gdal/master/autotest/ogr/data/poly.zip/poly.PRJ') == -1: # print(ret_str) - # return 'fail' + # pytest.fail() - return 'success' ############################################################################### # List FTP dir in /vsicurl/ @@ -253,58 +211,25 @@ def test_gdal_ls_py_7(): def test_gdal_ls_py_8(): if not gdaltest.run_slow_tests(): - return 'skip' + pytest.skip() drv = gdal.GetDriverByName('HTTP') if drv is None: - return 'skip' + pytest.skip() if int(gdal.VersionInfo('VERSION_NUM')) < 1900: - gdaltest.post_reason('would stall for a long time') - return 'skip' + pytest.skip('would stall for a long time') f = gdal.VSIFOpenL('/vsicurl/https://raw.githubusercontent.com/OSGeo/gdal/master/autotest/ogr/data/poly.zip', 'rb') if f is None: - return 'skip' + pytest.skip() d = gdal.VSIFReadL(1, 1, f) gdal.VSIFCloseL(f) if not d: - return 'skip' - - ret, ret_str = run_gdal_ls(['', '-l', '-R', '-Rzip', 'ftp://download.osgeo.org/gdal/data/aig']) - - if ret != 'success': - return ret - - if ret_str.find('-r--r--r-- 1 unknown unknown 24576 2007-03-29 00:00 /vsicurl/ftp://download.osgeo.org/gdal/data/aig/nzdem/info/arc0002r.001') == -1: - print(ret_str) - return 'fail' - - if ret_str.find('-r--r--r-- 1 unknown unknown 24576 2007-03-29 12:20 /vsizip//vsicurl/ftp://download.osgeo.org/gdal/data/aig/nzdem.zip/nzdem/info/arc0002r.001') == -1: - print(ret_str) - return 'fail' - - return 'success' - - -gdaltest_list = [ - test_gdal_ls_py_1, - test_gdal_ls_py_2, - test_gdal_ls_py_3, - test_gdal_ls_py_4, - test_gdal_ls_py_5, - test_gdal_ls_py_6, - test_gdal_ls_py_7, - test_gdal_ls_py_8, -] - -if __name__ == '__main__': - - if gdal.GetConfigOption('GDAL_RUN_SLOW_TESTS') is None: - gdal.SetConfigOption('GDAL_RUN_SLOW_TESTS', 'YES') + pytest.skip() - gdaltest.setup_run('test_gdal_ls_py') + ret_str = run_gdal_ls(['', '-l', '-R', '-Rzip', 'ftp://download.osgeo.org/gdal/data/aig']) - gdaltest.run_tests(gdaltest_list) + assert ret_str.find('-r--r--r-- 1 unknown unknown 24576 2007-03-29 00:00 /vsicurl/ftp://download.osgeo.org/gdal/data/aig/nzdem/info/arc0002r.001') != -1 - sys.exit(gdaltest.summarize()) + assert ret_str.find('-r--r--r-- 1 unknown unknown 24576 2007-03-29 12:20 /vsizip//vsicurl/ftp://download.osgeo.org/gdal/data/aig/nzdem.zip/nzdem/info/arc0002r.001') != -1 diff --git a/autotest/pyscripts/test_gdal_merge.py b/autotest/pyscripts/test_gdal_merge.py index ad61fed31aa5..954db227d2ec 100755 --- a/autotest/pyscripts/test_gdal_merge.py +++ b/autotest/pyscripts/test_gdal_merge.py @@ -29,15 +29,13 @@ ############################################################################### -import sys import os -sys.path.append('../pymod') from osgeo import gdal from osgeo import osr -import gdaltest import test_py_scripts +import pytest ############################################################################### # Basic test @@ -47,17 +45,14 @@ def test_gdal_merge_1(): script_path = test_py_scripts.get_py_script('gdal_merge') if script_path is None: - return 'skip' + pytest.skip() test_py_scripts.run_py_script(script_path, 'gdal_merge', '-o tmp/test_gdal_merge_1.tif ../gcore/data/byte.tif') ds = gdal.Open('tmp/test_gdal_merge_1.tif') - if ds.GetRasterBand(1).Checksum() != 4672: - return 'fail' + assert ds.GetRasterBand(1).Checksum() == 4672 ds = None - return 'success' - ############################################################################### # Merge 4 tiles @@ -66,7 +61,7 @@ def test_gdal_merge_2(): script_path = test_py_scripts.get_py_script('gdal_merge') if script_path is None: - return 'skip' + pytest.skip() drv = gdal.GetDriverByName('GTiff') srs = osr.SpatialReference() @@ -100,30 +95,21 @@ def test_gdal_merge_2(): test_py_scripts.run_py_script(script_path, 'gdal_merge', '-q -o tmp/test_gdal_merge_2.tif tmp/in1.tif tmp/in2.tif tmp/in3.tif tmp/in4.tif') ds = gdal.Open('tmp/test_gdal_merge_2.tif') - if ds.GetProjectionRef().find('WGS 84') == -1: - gdaltest.post_reason('Expected WGS 84\nGot : %s' % (ds.GetProjectionRef())) - return 'fail' + assert ds.GetProjectionRef().find('WGS 84') != -1, \ + ('Expected WGS 84\nGot : %s' % (ds.GetProjectionRef())) gt = ds.GetGeoTransform() expected_gt = [2, 0.1, 0, 49, 0, -0.1] for i in range(6): - if abs(gt[i] - expected_gt[i] > 1e-5): - gdaltest.post_reason('Expected : %s\nGot : %s' % (expected_gt, gt)) - return 'fail' - - if ds.RasterXSize != 20 or ds.RasterYSize != 20: - gdaltest.post_reason('Wrong raster dimensions : %d x %d' % (ds.RasterXSize, ds.RasterYSize)) - return 'fail' + assert not abs(gt[i] - expected_gt[i] > 1e-5), \ + ('Expected : %s\nGot : %s' % (expected_gt, gt)) - if ds.RasterCount != 1: - gdaltest.post_reason('Wrong raster count : %d ' % (ds.RasterCount)) - return 'fail' + assert ds.RasterXSize == 20 and ds.RasterYSize == 20, \ + ('Wrong raster dimensions : %d x %d' % (ds.RasterXSize, ds.RasterYSize)) - if ds.GetRasterBand(1).Checksum() != 3508: - gdaltest.post_reason('Wrong checksum') - return 'fail' + assert ds.RasterCount == 1, ('Wrong raster count : %d ' % (ds.RasterCount)) - return 'success' + assert ds.GetRasterBand(1).Checksum() == 3508, 'Wrong checksum' ############################################################################### # Test -separate and -v options @@ -133,35 +119,26 @@ def test_gdal_merge_3(): script_path = test_py_scripts.get_py_script('gdal_merge') if script_path is None: - return 'skip' + pytest.skip() test_py_scripts.run_py_script(script_path, 'gdal_merge', '-separate -v -o tmp/test_gdal_merge_3.tif tmp/in1.tif tmp/in2.tif tmp/in3.tif tmp/in4.tif') ds = gdal.Open('tmp/test_gdal_merge_3.tif') - if ds.GetProjectionRef().find('WGS 84') == -1: - gdaltest.post_reason('Expected WGS 84\nGot : %s' % (ds.GetProjectionRef())) - return 'fail' + assert ds.GetProjectionRef().find('WGS 84') != -1, \ + ('Expected WGS 84\nGot : %s' % (ds.GetProjectionRef())) gt = ds.GetGeoTransform() expected_gt = [2, 0.1, 0, 49, 0, -0.1] for i in range(6): - if abs(gt[i] - expected_gt[i] > 1e-5): - gdaltest.post_reason('Expected : %s\nGot : %s' % (expected_gt, gt)) - return 'fail' + assert not abs(gt[i] - expected_gt[i] > 1e-5), \ + ('Expected : %s\nGot : %s' % (expected_gt, gt)) - if ds.RasterXSize != 20 or ds.RasterYSize != 20: - gdaltest.post_reason('Wrong raster dimensions : %d x %d' % (ds.RasterXSize, ds.RasterYSize)) - return 'fail' + assert ds.RasterXSize == 20 and ds.RasterYSize == 20, \ + ('Wrong raster dimensions : %d x %d' % (ds.RasterXSize, ds.RasterYSize)) - if ds.RasterCount != 4: - gdaltest.post_reason('Wrong raster count : %d ' % (ds.RasterCount)) - return 'fail' + assert ds.RasterCount == 4, ('Wrong raster count : %d ' % (ds.RasterCount)) - if ds.GetRasterBand(1).Checksum() != 0: - gdaltest.post_reason('Wrong checksum') - return 'fail' - - return 'success' + assert ds.GetRasterBand(1).Checksum() == 0, 'Wrong checksum' ############################################################################### # Test -init option @@ -171,18 +148,13 @@ def test_gdal_merge_4(): script_path = test_py_scripts.get_py_script('gdal_merge') if script_path is None: - return 'skip' + pytest.skip() test_py_scripts.run_py_script(script_path, 'gdal_merge', '-init 255 -o tmp/test_gdal_merge_4.tif tmp/in2.tif tmp/in3.tif') ds = gdal.Open('tmp/test_gdal_merge_4.tif') - if ds.GetRasterBand(1).Checksum() != 4725: - print(ds.GetRasterBand(1).Checksum()) - gdaltest.post_reason('Wrong checksum') - return 'fail' - - return 'success' + assert ds.GetRasterBand(1).Checksum() == 4725, 'Wrong checksum' ############################################################################### # Test merging with alpha band (#3669) @@ -193,11 +165,11 @@ def test_gdal_merge_5(): from osgeo import gdalnumeric gdalnumeric.BandRasterIONumPy except (ImportError, AttributeError): - return 'skip' + pytest.skip() script_path = test_py_scripts.get_py_script('gdal_merge') if script_path is None: - return 'skip' + pytest.skip() drv = gdal.GetDriverByName('GTiff') srs = osr.SpatialReference() @@ -222,22 +194,10 @@ def test_gdal_merge_5(): ds = gdal.Open('tmp/test_gdal_merge_5.tif') - if ds.GetRasterBand(1).Checksum() != 0: - print(ds.GetRasterBand(1).Checksum()) - gdaltest.post_reason('Wrong checksum') - return 'fail' - if ds.GetRasterBand(2).Checksum() != cs: - print(ds.GetRasterBand(2).Checksum()) - gdaltest.post_reason('Wrong checksum') - return 'fail' - if ds.GetRasterBand(3).Checksum() != 0: - print(ds.GetRasterBand(3).Checksum()) - gdaltest.post_reason('Wrong checksum') - return 'fail' - if ds.GetRasterBand(4).Checksum() != cs: - print(ds.GetRasterBand(4).Checksum()) - gdaltest.post_reason('Wrong checksum') - return 'fail' + assert ds.GetRasterBand(1).Checksum() == 0, 'Wrong checksum' + assert ds.GetRasterBand(2).Checksum() == cs, 'Wrong checksum' + assert ds.GetRasterBand(3).Checksum() == 0, 'Wrong checksum' + assert ds.GetRasterBand(4).Checksum() == cs, 'Wrong checksum' ds = None os.unlink('tmp/test_gdal_merge_5.tif') @@ -246,24 +206,10 @@ def test_gdal_merge_5(): ds = gdal.Open('tmp/test_gdal_merge_5.tif') - if ds.GetRasterBand(1).Checksum() != 0: - print(ds.GetRasterBand(1).Checksum()) - gdaltest.post_reason('Wrong checksum') - return 'fail' - if ds.GetRasterBand(2).Checksum() != cs: - print(ds.GetRasterBand(2).Checksum()) - gdaltest.post_reason('Wrong checksum') - return 'fail' - if ds.GetRasterBand(3).Checksum() != 0: - print(ds.GetRasterBand(3).Checksum()) - gdaltest.post_reason('Wrong checksum') - return 'fail' - if ds.GetRasterBand(4).Checksum() != cs: - print(ds.GetRasterBand(4).Checksum()) - gdaltest.post_reason('Wrong checksum') - return 'fail' - - return 'success' + assert ds.GetRasterBand(1).Checksum() == 0, 'Wrong checksum' + assert ds.GetRasterBand(2).Checksum() == cs, 'Wrong checksum' + assert ds.GetRasterBand(3).Checksum() == 0, 'Wrong checksum' + assert ds.GetRasterBand(4).Checksum() == cs, 'Wrong checksum' ############################################################################### # Cleanup @@ -288,23 +234,7 @@ def test_gdal_merge_cleanup(): except OSError: pass - return 'success' - - -gdaltest_list = [ - test_gdal_merge_1, - test_gdal_merge_2, - test_gdal_merge_3, - test_gdal_merge_4, - test_gdal_merge_5, - test_gdal_merge_cleanup -] - - -if __name__ == '__main__': + - gdaltest.setup_run('test_gdal_merge') - gdaltest.run_tests(gdaltest_list) - sys.exit(gdaltest.summarize()) diff --git a/autotest/pyscripts/test_gdal_pansharpen.py b/autotest/pyscripts/test_gdal_pansharpen.py index e416044e0c63..006752aa5e5d 100755 --- a/autotest/pyscripts/test_gdal_pansharpen.py +++ b/autotest/pyscripts/test_gdal_pansharpen.py @@ -29,13 +29,11 @@ # DEALINGS IN THE SOFTWARE. ############################################################################### -import sys -sys.path.append('../pymod') from osgeo import gdal -import gdaltest import test_py_scripts +import pytest ############################################################################### # Simple test @@ -45,7 +43,7 @@ def test_gdal_pansharpen_1(): script_path = test_py_scripts.get_py_script('gdal_pansharpen') if script_path is None: - return 'skip' + pytest.skip() src_ds = gdal.Open('../gdrivers/data/small_world.tif') src_data = src_ds.GetRasterBand(1).ReadRaster() @@ -68,12 +66,7 @@ def test_gdal_pansharpen_1(): ds = None gdal.GetDriverByName('GTiff').Delete('tmp/out.tif') - if cs != [4735, 10000, 9742]: - gdaltest.post_reason('fail') - print(cs) - return 'fail' - - return 'success' + assert cs == [4735, 10000, 9742] ############################################################################### # Full options @@ -83,7 +76,7 @@ def test_gdal_pansharpen_2(): script_path = test_py_scripts.get_py_script('gdal_pansharpen') if script_path is None: - return 'skip' + pytest.skip() test_py_scripts.run_py_script(script_path, 'gdal_pansharpen', ' -q -b 3 -b 1 -bitdepth 8 -threads ALL_CPUS -spat_adjust union -w 0.33333333333333333 -w 0.33333333333333333 -w 0.33333333333333333 -of VRT -r cubic tmp/small_world_pan.tif ../gdrivers/data/small_world.tif,band=1 ../gdrivers/data/small_world.tif,band=2 ../gdrivers/data/small_world.tif,band=3 tmp/out.vrt') @@ -92,12 +85,7 @@ def test_gdal_pansharpen_2(): ds = None gdal.GetDriverByName('VRT').Delete('tmp/out.vrt') - if cs != [9742, 4735]: - gdaltest.post_reason('fail') - print(cs) - return 'fail' - - return 'success' + assert cs == [9742, 4735] ############################################################################### # Cleanup @@ -107,23 +95,9 @@ def test_gdal_pansharpen_cleanup(): script_path = test_py_scripts.get_py_script('gdal_pansharpen') if script_path is None: - return 'skip' + pytest.skip() gdal.GetDriverByName('GTiff').Delete('tmp/small_world_pan.tif') - return 'success' - - -gdaltest_list = [ - test_gdal_pansharpen_1, - test_gdal_pansharpen_2, - test_gdal_pansharpen_cleanup -] - -if __name__ == '__main__': - - gdaltest.setup_run('test_gdal_pansharpen') - gdaltest.run_tests(gdaltest_list) - sys.exit(gdaltest.summarize()) diff --git a/autotest/pyscripts/test_gdal_polygonize.py b/autotest/pyscripts/test_gdal_polygonize.py index a89f6fb5a738..a8229bbf5993 100755 --- a/autotest/pyscripts/test_gdal_polygonize.py +++ b/autotest/pyscripts/test_gdal_polygonize.py @@ -30,15 +30,13 @@ ############################################################################### import os -import sys -sys.path.append('../pymod') -import gdaltest import ogrtest import test_py_scripts from osgeo import ogr +import pytest ############################################################################### # Test a fairly simple case, with nodata masking. @@ -48,7 +46,7 @@ def test_gdal_polygonize_1(): script_path = test_py_scripts.get_py_script('gdal_polygonize') if script_path is None: - return 'skip' + pytest.skip() # Create a OGR datasource to put results in. shp_drv = ogr.GetDriverByName('ESRI Shapefile') @@ -76,9 +74,7 @@ def test_gdal_polygonize_1(): shp_lyr = shp_ds.GetLayerByName('poly') expected_feature_number = 13 - if shp_lyr.GetFeatureCount() != expected_feature_number: - gdaltest.post_reason('GetFeatureCount() returned %d instead of %d' % (shp_lyr.GetFeatureCount(), expected_feature_number)) - return 'fail' + assert shp_lyr.GetFeatureCount() == expected_feature_number expect = [107, 123, 115, 115, 140, 148, 123, 140, 156, 100, 101, 102, 103] @@ -98,7 +94,7 @@ def test_gdal_polygonize_1(): shp_drv = ogr.GetDriverByName('ESRI Shapefile') shp_drv.DeleteDataSource('tmp/poly.shp') - return 'success' if tr else 'fail' + assert tr ############################################################################### # Test a simple case without masking. @@ -108,7 +104,7 @@ def test_gdal_polygonize_2(): script_path = test_py_scripts.get_py_script('gdal_polygonize') if script_path is None: - return 'skip' + pytest.skip() shp_drv = ogr.GetDriverByName('ESRI Shapefile') try: @@ -125,9 +121,7 @@ def test_gdal_polygonize_2(): shp_lyr = shp_ds.GetLayerByName('out') expected_feature_number = 17 - if shp_lyr.GetFeatureCount() != expected_feature_number: - gdaltest.post_reason('GetFeatureCount() returned %d instead of %d' % (shp_lyr.GetFeatureCount(), expected_feature_number)) - return 'fail' + assert shp_lyr.GetFeatureCount() == expected_feature_number expect = [107, 123, 115, 132, 115, 132, 140, 132, 148, 123, 140, 132, 156, 100, 101, 102, 103] @@ -139,18 +133,18 @@ def test_gdal_polygonize_2(): shp_drv = ogr.GetDriverByName('ESRI Shapefile') shp_drv.DeleteDataSource('tmp/out.shp') - return 'success' if tr else 'fail' + assert tr def test_gdal_polygonize_3(): script_path = test_py_scripts.get_py_script('gdal_polygonize') if script_path is None: - return 'skip' + pytest.skip() drv = ogr.GetDriverByName('GPKG') if drv is None: - return 'skip' + pytest.skip() try: os.stat('tmp/out.gpkg') drv.DeleteDataSource('tmp/out.gpkg') @@ -172,9 +166,8 @@ def test_gdal_polygonize_3(): drv.DeleteDataSource('tmp/out.gpkg') if geom_is_polygon: - return 'success' - gdaltest.post_reason('GetGeomType() returned %d instead of %d or %d (ogr.wkbPolygon or ogr.wkbMultiPolygon)' % (geom_type, ogr.wkbPolygon, ogr.wkbMultiPolygon)) - return 'fail' + return + pytest.fail('GetGeomType() returned %d instead of %d or %d (ogr.wkbPolygon or ogr.wkbMultiPolygon)' % (geom_type, ogr.wkbPolygon, ogr.wkbMultiPolygon)) ############################################################################### # Test -b mask @@ -184,7 +177,7 @@ def test_gdal_polygonize_4(): script_path = test_py_scripts.get_py_script('gdal_polygonize') if script_path is None: - return 'skip' + pytest.skip() # Test mask syntax test_py_scripts.run_py_script(script_path, 'gdal_polygonize', '-q -f GML -b mask ../gcore/data/byte.tif tmp/out.gml') @@ -193,10 +186,7 @@ def test_gdal_polygonize_4(): os.unlink('tmp/out.gml') - if content.find('<ogr:geometryProperty><gml:Polygon srsName="EPSG:26711"><gml:outerBoundaryIs><gml:LinearRing><gml:coordinates>440720,3751320 440720,3750120 441920,3750120 441920,3751320 440720,3751320</gml:coordinates></gml:LinearRing></gml:outerBoundaryIs></gml:Polygon></ogr:geometryProperty>') < 0: - gdaltest.post_reason('fail') - print(content) - return 'fail' + assert content.find('<ogr:geometryProperty><gml:Polygon srsName="EPSG:26711"><gml:outerBoundaryIs><gml:LinearRing><gml:coordinates>440720,3751320 440720,3750120 441920,3750120 441920,3751320 440720,3751320</gml:coordinates></gml:LinearRing></gml:outerBoundaryIs></gml:Polygon></ogr:geometryProperty>') >= 0 # Test mask,1 syntax test_py_scripts.run_py_script(script_path, 'gdal_polygonize', '-q -f GML -b mask,1 ../gcore/data/byte.tif tmp/out.gml') @@ -205,25 +195,7 @@ def test_gdal_polygonize_4(): os.unlink('tmp/out.gml') - if content.find('<ogr:geometryProperty><gml:Polygon srsName="EPSG:26711"><gml:outerBoundaryIs><gml:LinearRing><gml:coordinates>440720,3751320 440720,3750120 441920,3750120 441920,3751320 440720,3751320</gml:coordinates></gml:LinearRing></gml:outerBoundaryIs></gml:Polygon></ogr:geometryProperty>') < 0: - gdaltest.post_reason('fail') - print(content) - return 'fail' + assert content.find('<ogr:geometryProperty><gml:Polygon srsName="EPSG:26711"><gml:outerBoundaryIs><gml:LinearRing><gml:coordinates>440720,3751320 440720,3750120 441920,3750120 441920,3751320 440720,3751320</gml:coordinates></gml:LinearRing></gml:outerBoundaryIs></gml:Polygon></ogr:geometryProperty>') >= 0 - return 'success' -gdaltest_list = [ - test_gdal_polygonize_1, - test_gdal_polygonize_2, - test_gdal_polygonize_3, - test_gdal_polygonize_4 -] - -if __name__ == '__main__': - - gdaltest.setup_run('test_gdal_polygonize') - - gdaltest.run_tests(gdaltest_list) - - sys.exit(gdaltest.summarize()) diff --git a/autotest/pyscripts/test_gdal_proximity.py b/autotest/pyscripts/test_gdal_proximity.py index 260e2967b9e1..c8ad3321247e 100755 --- a/autotest/pyscripts/test_gdal_proximity.py +++ b/autotest/pyscripts/test_gdal_proximity.py @@ -30,14 +30,12 @@ ############################################################################### import os -import sys -sys.path.append('../pymod') -import gdaltest import test_py_scripts from osgeo import gdal +import pytest ############################################################################### # Test a fairly default case. @@ -47,7 +45,7 @@ def test_gdal_proximity_1(): script_path = test_py_scripts.get_py_script('gdal_proximity') if script_path is None: - return 'skip' + pytest.skip() drv = gdal.GetDriverByName('GTiff') dst_ds = drv.Create('tmp/proximity_1.tif', 25, 25, 1, gdal.GDT_Byte) @@ -66,10 +64,8 @@ def test_gdal_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 @@ -78,7 +74,7 @@ def test_gdal_proximity_2(): script_path = test_py_scripts.get_py_script('gdal_proximity') if script_path is None: - return 'skip' + pytest.skip() test_py_scripts.run_py_script(script_path, 'gdal_proximity', '-q -values 65,64 -maxdist 12 -nodata -1 -fixed-buf-val 255 ../alg/data/pat.tif tmp/proximity_2.tif') @@ -93,10 +89,8 @@ def test_gdal_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 @@ -105,7 +99,7 @@ def test_gdal_proximity_3(): script_path = test_py_scripts.get_py_script('gdal_proximity') if script_path is None: - return 'skip' + pytest.skip() test_py_scripts.run_py_script(script_path, 'gdal_proximity', '-q -values 65,64 -maxdist 12 -nodata 0 -use_input_nodata yes ../alg/data/pat.tif tmp/proximity_3.tif') @@ -120,10 +114,8 @@ def test_gdal_proximity_3(): if cs != cs_expected: print('Got: ', cs) - gdaltest.post_reason('got wrong checksum') - return 'fail' - return 'success' - + pytest.fail('got wrong checksum') + ############################################################################### # Cleanup @@ -139,20 +131,6 @@ def test_gdal_proximity_cleanup(): except OSError: pass - return 'success' - - -gdaltest_list = [ - test_gdal_proximity_1, - test_gdal_proximity_2, - test_gdal_proximity_3, - test_gdal_proximity_cleanup, -] - -if __name__ == '__main__': - - gdaltest.setup_run('test_gdal_proximity') + - gdaltest.run_tests(gdaltest_list) - sys.exit(gdaltest.summarize()) diff --git a/autotest/pyscripts/test_gdal_retile.py b/autotest/pyscripts/test_gdal_retile.py index 2bb6fba219a5..dc5b22582c34 100755 --- a/autotest/pyscripts/test_gdal_retile.py +++ b/autotest/pyscripts/test_gdal_retile.py @@ -29,15 +29,13 @@ ############################################################################### import shutil -import sys import os -sys.path.append('../pymod') from osgeo import gdal from osgeo import osr -import gdaltest import test_py_scripts +import pytest ############################################################################### # Test gdal_retile.py @@ -47,7 +45,7 @@ def test_gdal_retile_1(): script_path = test_py_scripts.get_py_script('gdal_retile') if script_path is None: - return 'skip' + pytest.skip() try: os.mkdir('tmp/outretile') @@ -57,31 +55,23 @@ def test_gdal_retile_1(): test_py_scripts.run_py_script(script_path, 'gdal_retile', '-v -levels 2 -r bilinear -targetDir tmp/outretile ../gcore/data/byte.tif') ds = gdal.Open('tmp/outretile/byte_1_1.tif') - if ds.GetRasterBand(1).Checksum() != 4672: - print(ds.GetRasterBand(1).Checksum()) - return 'fail' + assert ds.GetRasterBand(1).Checksum() == 4672 ds = None ds = gdal.Open('tmp/outretile/1/byte_1_1.tif') - if ds.RasterXSize != 10: - print(ds.RasterXSize) - return 'fail' + assert ds.RasterXSize == 10 # if ds.GetRasterBand(1).Checksum() != 1152: # print(ds.GetRasterBand(1).Checksum()) # return 'fail' ds = None ds = gdal.Open('tmp/outretile/2/byte_1_1.tif') - if ds.RasterXSize != 5: - print(ds.RasterXSize) - return 'fail' + assert ds.RasterXSize == 5 # if ds.GetRasterBand(1).Checksum() != 215: # print(ds.GetRasterBand(1).Checksum()) # return 'fail' ds = None - return 'success' - ############################################################################### # Test gdal_retile.py with RGBA dataset @@ -90,7 +80,7 @@ def test_gdal_retile_2(): script_path = test_py_scripts.get_py_script('gdal_retile') if script_path is None: - return 'skip' + pytest.skip() try: os.mkdir('tmp/outretile2') @@ -100,18 +90,10 @@ def test_gdal_retile_2(): test_py_scripts.run_py_script(script_path, 'gdal_retile', '-v -levels 2 -r bilinear -targetDir tmp/outretile2 ../gcore/data/rgba.tif') ds = gdal.Open('tmp/outretile2/2/rgba_1_1.tif') - if ds.GetRasterBand(1).Checksum() != 35: - gdaltest.post_reason('wrong checksum for band 1') - print(ds.GetRasterBand(1).Checksum()) - return 'fail' - if ds.GetRasterBand(4).Checksum() != 35: - gdaltest.post_reason('wrong checksum for band 4') - print(ds.GetRasterBand(4).Checksum()) - return 'fail' + assert ds.GetRasterBand(1).Checksum() == 35, 'wrong checksum for band 1' + assert ds.GetRasterBand(4).Checksum() == 35, 'wrong checksum for band 4' ds = None - return 'success' - ############################################################################### # Test gdal_retile.py with input images of different pixel sizes @@ -120,7 +102,7 @@ def test_gdal_retile_3(): script_path = test_py_scripts.get_py_script('gdal_retile') if script_path is None: - return 'skip' + pytest.skip() drv = gdal.GetDriverByName('GTiff') srs = osr.SpatialReference() @@ -170,30 +152,21 @@ def test_gdal_retile_3(): test_py_scripts.run_py_script(script_path, 'gdal_retile', '-v -levels 2 -r bilinear -targetDir tmp/outretile3 tmp/in1.tif tmp/in2.tif') ds = gdal.Open('tmp/outretile3/in1_1_1.tif') - if ds.GetProjectionRef().find('WGS 84') == -1: - gdaltest.post_reason('Expected WGS 84\nGot : %s' % (ds.GetProjectionRef())) - return 'fail' + assert ds.GetProjectionRef().find('WGS 84') != -1, \ + ('Expected WGS 84\nGot : %s' % (ds.GetProjectionRef())) gt = ds.GetGeoTransform() expected_gt = [0, px1_x, 0, 60, 0, -px1_y] for i in range(6): - if abs(gt[i] - expected_gt[i] > 1e-5): - gdaltest.post_reason('Expected : %s\nGot : %s' % (expected_gt, gt)) - return 'fail' + assert not abs(gt[i] - expected_gt[i] > 1e-5), \ + ('Expected : %s\nGot : %s' % (expected_gt, gt)) - if ds.RasterXSize != 100 or ds.RasterYSize != 200: - gdaltest.post_reason('Wrong raster dimensions : %d x %d' % (ds.RasterXSize, ds.RasterYSize)) - return 'fail' + assert ds.RasterXSize == 100 and ds.RasterYSize == 200, \ + ('Wrong raster dimensions : %d x %d' % (ds.RasterXSize, ds.RasterYSize)) - if ds.RasterCount != 1: - gdaltest.post_reason('Wrong raster count : %d ' % (ds.RasterCount)) - return 'fail' + assert ds.RasterCount == 1, ('Wrong raster count : %d ' % (ds.RasterCount)) - if ds.GetRasterBand(1).Checksum() != 38999: - gdaltest.post_reason('Wrong checksum') - return 'fail' - - return 'success' + assert ds.GetRasterBand(1).Checksum() == 38999, 'Wrong checksum' ############################################################################### @@ -203,7 +176,7 @@ def test_gdal_retile_4(): script_path = test_py_scripts.get_py_script('gdal_retile') if script_path is None: - return 'skip' + pytest.skip() try: os.mkdir('tmp/outretile4') @@ -235,18 +208,8 @@ def test_gdal_retile_4(): for (filename, width, height) in expected_results: ds = gdal.Open(filename) - if ds.RasterXSize != width: - gdaltest.post_reason('fail') - print(filename) - print(ds.RasterXSize) - print(width) - return 'fail' - if ds.RasterYSize != height: - gdaltest.post_reason('fail') - print(filename) - print(ds.RasterYSize) - print(height) - return 'fail' + assert ds.RasterXSize == width, filename + assert ds.RasterYSize == height, filename ds = None test_py_scripts.run_py_script(script_path, 'gdal_retile', '-v -levels 1 -ps 8 8 -overlap 4 -targetDir tmp/outretile4 ../gcore/data/byte.tif') @@ -274,22 +237,11 @@ def test_gdal_retile_4(): for (filename, width, height) in expected_results: ds = gdal.Open(filename) - if ds.RasterXSize != width: - gdaltest.post_reason('fail') - print(filename) - print(ds.RasterXSize) - print(width) - return 'fail' - if ds.RasterYSize != height: - gdaltest.post_reason('fail') - print(filename) - print(ds.RasterYSize) - print(height) - return 'fail' + assert ds.RasterXSize == width, filename + assert ds.RasterYSize == height, filename ds = None - return 'success' - + ############################################################################### # Cleanup @@ -327,22 +279,6 @@ def test_gdal_retile_cleanup(): shutil.rmtree('tmp/outretile4') - return 'success' - - -gdaltest_list = [ - test_gdal_retile_1, - test_gdal_retile_2, - test_gdal_retile_3, - test_gdal_retile_4, - test_gdal_retile_cleanup -] - - -if __name__ == '__main__': - gdaltest.setup_run('gdal_retile') - gdaltest.run_tests(gdaltest_list) - sys.exit(gdaltest.summarize()) diff --git a/autotest/pyscripts/test_gdal_sieve.py b/autotest/pyscripts/test_gdal_sieve.py index 400782c21992..9bb1e20b6ede 100755 --- a/autotest/pyscripts/test_gdal_sieve.py +++ b/autotest/pyscripts/test_gdal_sieve.py @@ -29,14 +29,12 @@ # DEALINGS IN THE SOFTWARE. ############################################################################### -import sys -sys.path.append('../pymod') -import gdaltest import test_py_scripts from osgeo import gdal +import pytest ############################################################################### # Test a fairly default case. @@ -46,7 +44,7 @@ def test_gdal_sieve_1(): script_path = test_py_scripts.get_py_script('gdal_sieve') if script_path is None: - return 'skip' + pytest.skip() drv = gdal.GetDriverByName('GTiff') dst_ds = drv.Create('tmp/sieve_1.tif', 5, 7, 1, gdal.GDT_Byte) @@ -71,19 +69,7 @@ def test_gdal_sieve_1(): if cs != cs_expected: print('Got: ', cs) - gdaltest.post_reason('got wrong checksum') - return 'fail' - return 'success' + pytest.fail('got wrong checksum') + -gdaltest_list = [ - test_gdal_sieve_1, -] - -if __name__ == '__main__': - - gdaltest.setup_run('test_gdal_sieve') - - gdaltest.run_tests(gdaltest_list) - - sys.exit(gdaltest.summarize()) diff --git a/autotest/pyscripts/test_gdalinfo_py.py b/autotest/pyscripts/test_gdalinfo_py.py index b6edffa4dd0f..f3ce0607e01b 100755 --- a/autotest/pyscripts/test_gdalinfo_py.py +++ b/autotest/pyscripts/test_gdalinfo_py.py @@ -28,13 +28,11 @@ # DEALINGS IN THE SOFTWARE. ############################################################################### -import sys import os -sys.path.append('../pymod') -import gdaltest import test_py_scripts +import pytest ############################################################################### # Simple test @@ -44,13 +42,10 @@ def test_gdalinfo_py_1(): script_path = test_py_scripts.get_py_script('gdalinfo') if script_path is None: - return 'skip' + pytest.skip() ret = test_py_scripts.run_py_script(script_path, 'gdalinfo', '../gcore/data/byte.tif') - if ret.find('Driver: GTiff/GeoTIFF') == -1: - return 'fail' - - return 'success' + assert ret.find('Driver: GTiff/GeoTIFF') != -1 ############################################################################### # Test -checksum option @@ -59,13 +54,10 @@ def test_gdalinfo_py_1(): def test_gdalinfo_py_2(): script_path = test_py_scripts.get_py_script('gdalinfo') if script_path is None: - return 'skip' + pytest.skip() ret = test_py_scripts.run_py_script(script_path, 'gdalinfo', '-checksum ../gcore/data/byte.tif') - if ret.find('Checksum=4672') == -1: - return 'fail' - - return 'success' + assert ret.find('Checksum=4672') != -1 ############################################################################### # Test -nomd option @@ -74,17 +66,13 @@ def test_gdalinfo_py_2(): def test_gdalinfo_py_3(): script_path = test_py_scripts.get_py_script('gdalinfo') if script_path is None: - return 'skip' + pytest.skip() ret = test_py_scripts.run_py_script(script_path, 'gdalinfo', '../gcore/data/byte.tif') - if ret.find('Metadata') == -1: - return 'fail' + assert ret.find('Metadata') != -1 ret = test_py_scripts.run_py_script(script_path, 'gdalinfo', '-nomd ../gcore/data/byte.tif') - if ret.find('Metadata') != -1: - return 'fail' - - return 'success' + assert ret.find('Metadata') == -1 ############################################################################### # Test -noct option @@ -93,17 +81,13 @@ def test_gdalinfo_py_3(): def test_gdalinfo_py_4(): script_path = test_py_scripts.get_py_script('gdalinfo') if script_path is None: - return 'skip' + pytest.skip() ret = test_py_scripts.run_py_script(script_path, 'gdalinfo', '../gdrivers/data/bug407.gif') - if ret.find('0: 255,255,255,255') == -1: - return 'fail' + assert ret.find('0: 255,255,255,255') != -1 ret = test_py_scripts.run_py_script(script_path, 'gdalinfo', '-noct ../gdrivers/data/bug407.gif') - if ret.find('0: 255,255,255,255') != -1: - return 'fail' - - return 'success' + assert ret.find('0: 255,255,255,255') == -1 ############################################################################### # Test -stats option @@ -112,7 +96,7 @@ def test_gdalinfo_py_4(): def test_gdalinfo_py_5(): script_path = test_py_scripts.get_py_script('gdalinfo') if script_path is None: - return 'skip' + pytest.skip() try: os.remove('../gcore/data/byte.tif.aux.xml') @@ -120,22 +104,14 @@ def test_gdalinfo_py_5(): pass ret = test_py_scripts.run_py_script(script_path, 'gdalinfo', '../gcore/data/byte.tif') - if ret.find('STATISTICS_MINIMUM=74') != -1: - gdaltest.post_reason('got wrong minimum.') - print(ret) - return 'fail' + assert ret.find('STATISTICS_MINIMUM=74') == -1, 'got wrong minimum.' ret = test_py_scripts.run_py_script(script_path, 'gdalinfo', '-stats ../gcore/data/byte.tif') - if ret.find('STATISTICS_MINIMUM=74') == -1: - gdaltest.post_reason('got wrong minimum (2).') - print(ret) - return 'fail' + assert ret.find('STATISTICS_MINIMUM=74') != -1, 'got wrong minimum (2).' # We will blow an exception if the file does not exist now! os.remove('../gcore/data/byte.tif.aux.xml') - return 'success' - ############################################################################### # Test a dataset with overviews and RAT @@ -143,15 +119,10 @@ def test_gdalinfo_py_5(): def test_gdalinfo_py_6(): script_path = test_py_scripts.get_py_script('gdalinfo') if script_path is None: - return 'skip' + pytest.skip() ret = test_py_scripts.run_py_script(script_path, 'gdalinfo', '../gdrivers/data/int.img') - if ret.find('Overviews') == -1: - return 'fail' - # if ret.find('GDALRasterAttributeTable') == -1: - # return 'fail' - - return 'success' + assert ret.find('Overviews') != -1 ############################################################################### # Test a dataset with GCPs @@ -160,26 +131,18 @@ def test_gdalinfo_py_6(): def test_gdalinfo_py_7(): script_path = test_py_scripts.get_py_script('gdalinfo') if script_path is None: - return 'skip' + pytest.skip() ret = test_py_scripts.run_py_script(script_path, 'gdalinfo', '../gcore/data/gcps.vrt') - if ret.find('GCP Projection =') == -1: - return 'fail' - if ret.find('PROJCS["NAD27 / UTM zone 11N"') == -1: - return 'fail' - if ret.find('(100,100) -> (446720,3745320,0)') == -1: - return 'fail' + assert ret.find('GCP Projection =') != -1 + assert ret.find('PROJCS["NAD27 / UTM zone 11N"') != -1 + assert ret.find('(100,100) -> (446720,3745320,0)') != -1 # Same but with -nogcps ret = test_py_scripts.run_py_script(script_path, 'gdalinfo', '-nogcp ../gcore/data/gcps.vrt') - if ret.find('GCP Projection =') != -1: - return 'fail' - if ret.find('PROJCS["NAD27 / UTM zone 11N"') != -1: - return 'fail' - if ret.find('(100,100) -> (446720,3745320,0)') != -1: - return 'fail' - - return 'success' + assert ret.find('GCP Projection =') == -1 + assert ret.find('PROJCS["NAD27 / UTM zone 11N"') == -1 + assert ret.find('(100,100) -> (446720,3745320,0)') == -1 ############################################################################### # Test -hist option @@ -188,7 +151,7 @@ def test_gdalinfo_py_7(): def test_gdalinfo_py_8(): script_path = test_py_scripts.get_py_script('gdalinfo') if script_path is None: - return 'skip' + pytest.skip() try: os.remove('../gcore/data/byte.tif.aux.xml') @@ -196,22 +159,16 @@ def test_gdalinfo_py_8(): pass ret = test_py_scripts.run_py_script(script_path, 'gdalinfo', '../gcore/data/byte.tif') - if ret.find('0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 6 0 0 0 0 0 0 0 0 37 0 0 0 0 0 0 0 57 0 0 0 0 0 0 0 62 0 0 0 0 0 0 0 66 0 0 0 0 0 0 0 0 72 0 0 0 0 0 0 0 31 0 0 0 0 0 0 0 24 0 0 0 0 0 0 0 12 0 0 0 0 0 0 0 0 7 0 0 0 0 0 0 0 12 0 0 0 0 0 0 0 5 0 0 0 0 0 0 0 3 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 2 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 1') != -1: - gdaltest.post_reason('did not expect histogram.') - print(ret) - return 'fail' + assert ret.find('0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 6 0 0 0 0 0 0 0 0 37 0 0 0 0 0 0 0 57 0 0 0 0 0 0 0 62 0 0 0 0 0 0 0 66 0 0 0 0 0 0 0 0 72 0 0 0 0 0 0 0 31 0 0 0 0 0 0 0 24 0 0 0 0 0 0 0 12 0 0 0 0 0 0 0 0 7 0 0 0 0 0 0 0 12 0 0 0 0 0 0 0 5 0 0 0 0 0 0 0 3 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 2 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 1') == -1, \ + 'did not expect histogram.' ret = test_py_scripts.run_py_script(script_path, 'gdalinfo', '-hist ../gcore/data/byte.tif') - if ret.find('0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 6 0 0 0 0 0 0 0 0 37 0 0 0 0 0 0 0 57 0 0 0 0 0 0 0 62 0 0 0 0 0 0 0 66 0 0 0 0 0 0 0 0 72 0 0 0 0 0 0 0 31 0 0 0 0 0 0 0 24 0 0 0 0 0 0 0 12 0 0 0 0 0 0 0 0 7 0 0 0 0 0 0 0 12 0 0 0 0 0 0 0 5 0 0 0 0 0 0 0 3 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 2 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 1') == -1: - gdaltest.post_reason('did not get expected histogram.') - print(ret) - return 'fail' + assert ret.find('0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 6 0 0 0 0 0 0 0 0 37 0 0 0 0 0 0 0 57 0 0 0 0 0 0 0 62 0 0 0 0 0 0 0 66 0 0 0 0 0 0 0 0 72 0 0 0 0 0 0 0 31 0 0 0 0 0 0 0 24 0 0 0 0 0 0 0 12 0 0 0 0 0 0 0 0 7 0 0 0 0 0 0 0 12 0 0 0 0 0 0 0 5 0 0 0 0 0 0 0 3 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 2 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 1') != -1, \ + 'did not get expected histogram.' # We will blow an exception if the file does not exist now! os.remove('../gcore/data/byte.tif.aux.xml') - return 'success' - ############################################################################### # Test -mdd option @@ -219,21 +176,13 @@ def test_gdalinfo_py_8(): def test_gdalinfo_py_9(): script_path = test_py_scripts.get_py_script('gdalinfo') if script_path is None: - return 'skip' + pytest.skip() ret = test_py_scripts.run_py_script(script_path, 'gdalinfo', '../gdrivers/data/fake_nsif.ntf') - if ret.find('BLOCKA=010000001000000000') != -1: - gdaltest.post_reason('Got unexpected extra MD.') - print(ret) - return 'fail' + assert ret.find('BLOCKA=010000001000000000') == -1, 'Got unexpected extra MD.' ret = test_py_scripts.run_py_script(script_path, 'gdalinfo', '-mdd TRE ../gdrivers/data/fake_nsif.ntf') - if ret.find('BLOCKA=010000001000000000') == -1: - gdaltest.post_reason('did not get extra MD.') - print(ret) - return 'fail' - - return 'success' + assert ret.find('BLOCKA=010000001000000000') != -1, 'did not get extra MD.' ############################################################################### # Test -mm option @@ -242,37 +191,14 @@ def test_gdalinfo_py_9(): def test_gdalinfo_py_10(): script_path = test_py_scripts.get_py_script('gdalinfo') if script_path is None: - return 'skip' + pytest.skip() ret = test_py_scripts.run_py_script(script_path, 'gdalinfo', '../gcore/data/byte.tif') - if ret.find('Computed Min/Max=74.000,255.000') != -1: - return 'fail' + assert ret.find('Computed Min/Max=74.000,255.000') == -1 ret = test_py_scripts.run_py_script(script_path, 'gdalinfo', '-mm ../gcore/data/byte.tif') - if ret.find('Computed Min/Max=74.000,255.000') == -1: - return 'fail' - - return 'success' - - -gdaltest_list = [ - test_gdalinfo_py_1, - test_gdalinfo_py_2, - test_gdalinfo_py_3, - test_gdalinfo_py_4, - test_gdalinfo_py_5, - test_gdalinfo_py_6, - test_gdalinfo_py_7, - test_gdalinfo_py_8, - test_gdalinfo_py_9, - test_gdalinfo_py_10 -] - + assert ret.find('Computed Min/Max=74.000,255.000') != -1 -if __name__ == '__main__': - gdaltest.setup_run('test_gdalinfo_py') - gdaltest.run_tests(gdaltest_list) - sys.exit(gdaltest.summarize()) diff --git a/autotest/pyscripts/test_gdalmove.py b/autotest/pyscripts/test_gdalmove.py index 43b230a824c2..069b3927f7ff 100755 --- a/autotest/pyscripts/test_gdalmove.py +++ b/autotest/pyscripts/test_gdalmove.py @@ -30,13 +30,11 @@ import os import shutil -import sys -sys.path.append('../pymod') from osgeo import gdal -import gdaltest import test_py_scripts +import pytest ############################################################################### # @@ -46,7 +44,7 @@ def test_gdalmove_1(): script_path = test_py_scripts.get_py_script('gdalmove') if script_path is None: - return 'skip' + pytest.skip() shutil.copy('../gcore/data/byte.tif', 'tmp/test_gdalmove_1.tif') @@ -56,20 +54,11 @@ def test_gdalmove_1(): got_gt = ds.GetGeoTransform() expected_gt = (440719.95870935748, 60.000041745067577, 1.9291142234578728e-05, 3751294.2109841029, 1.9099167548120022e-05, -60.000041705276814) for i in range(6): - if abs(got_gt[i] - expected_gt[i]) / abs(got_gt[i]) > 1e-5: - gdaltest.post_reason('bad gt') - print(got_gt) - print(expected_gt) - return 'fail' + assert abs(got_gt[i] - expected_gt[i]) / abs(got_gt[i]) <= 1e-5, 'bad gt' wkt = ds.GetProjection() - if wkt.find('32611') < 0: - gdaltest.post_reason('bad geotransform') - print(wkt) - return 'fail' + assert wkt.find('32611') >= 0, 'bad geotransform' ds = None - return 'success' - ############################################################################### # Cleanup @@ -83,19 +72,7 @@ def test_gdalmove_cleanup(): except OSError: pass - return 'success' - - -gdaltest_list = [ - test_gdalmove_1, - test_gdalmove_cleanup -] - - -if __name__ == '__main__': + - gdaltest.setup_run('test_gdalmove') - gdaltest.run_tests(gdaltest_list) - sys.exit(gdaltest.summarize()) diff --git a/autotest/pyscripts/test_ogr2ogr_py.py b/autotest/pyscripts/test_ogr2ogr_py.py index e032281280b9..256d3defeebf 100755 --- a/autotest/pyscripts/test_ogr2ogr_py.py +++ b/autotest/pyscripts/test_ogr2ogr_py.py @@ -32,8 +32,8 @@ import sys import os import shutil +import pytest -sys.path.append('../pymod') sys.path.append('../ogr') from osgeo import gdal @@ -51,7 +51,7 @@ def test_ogr2ogr_py_1(): script_path = test_py_scripts.get_py_script('ogr2ogr') if script_path is None: - return 'skip' + pytest.skip() try: os.stat('tmp/poly.shp') @@ -61,25 +61,18 @@ def test_ogr2ogr_py_1(): test_py_scripts.run_py_script(script_path, 'ogr2ogr', 'tmp/poly.shp ../ogr/data/poly.shp') ds = ogr.Open('tmp/poly.shp') - if ds is None or ds.GetLayer(0).GetFeatureCount() != 10: - return 'fail' + assert ds is not None and ds.GetLayer(0).GetFeatureCount() == 10 feat0 = ds.GetLayer(0).GetFeature(0) - if feat0.GetFieldAsDouble('AREA') != 215229.266: - print(feat0.GetFieldAsDouble('AREA')) - gdaltest.post_reason('Did not get expected value for field AREA') - return 'fail' - if feat0.GetFieldAsString('PRFEDEA') != '35043411': - print(feat0.GetFieldAsString('PRFEDEA')) - gdaltest.post_reason('Did not get expected value for field PRFEDEA') - return 'fail' + assert feat0.GetFieldAsDouble('AREA') == 215229.266, \ + 'Did not get expected value for field AREA' + assert feat0.GetFieldAsString('PRFEDEA') == '35043411', \ + 'Did not get expected value for field PRFEDEA' ds.Destroy() ogr.GetDriverByName('ESRI Shapefile').DeleteDataSource('tmp/poly.shp') - return 'success' - ############################################################################### # Test -sql @@ -87,7 +80,7 @@ def test_ogr2ogr_py_1(): def test_ogr2ogr_py_2(): script_path = test_py_scripts.get_py_script('ogr2ogr') if script_path is None: - return 'skip' + pytest.skip() try: os.stat('tmp/poly.shp') @@ -98,14 +91,11 @@ def test_ogr2ogr_py_2(): test_py_scripts.run_py_script(script_path, 'ogr2ogr', 'tmp/poly.shp ../ogr/data/poly.shp -sql "select * from poly"') ds = ogr.Open('tmp/poly.shp') - if ds is None or ds.GetLayer(0).GetFeatureCount() != 10: - return 'fail' + assert ds is not None and ds.GetLayer(0).GetFeatureCount() == 10 ds.Destroy() ogr.GetDriverByName('ESRI Shapefile').DeleteDataSource('tmp/poly.shp') - return 'success' - ############################################################################### # Test -spat @@ -113,7 +103,7 @@ def test_ogr2ogr_py_2(): def test_ogr2ogr_py_3(): script_path = test_py_scripts.get_py_script('ogr2ogr') if script_path is None: - return 'skip' + pytest.skip() try: os.stat('tmp/poly.shp') @@ -125,17 +115,13 @@ def test_ogr2ogr_py_3(): ds = ogr.Open('tmp/poly.shp') if ogrtest.have_geos(): - if ds is None or ds.GetLayer(0).GetFeatureCount() != 4: - return 'fail' + assert ds is not None and ds.GetLayer(0).GetFeatureCount() == 4 else: - if ds is None or ds.GetLayer(0).GetFeatureCount() != 5: - return 'fail' + assert ds is not None and ds.GetLayer(0).GetFeatureCount() == 5 ds.Destroy() ogr.GetDriverByName('ESRI Shapefile').DeleteDataSource('tmp/poly.shp') - return 'success' - ############################################################################### # Test -where @@ -143,7 +129,7 @@ def test_ogr2ogr_py_3(): def test_ogr2ogr_py_4(): script_path = test_py_scripts.get_py_script('ogr2ogr') if script_path is None: - return 'skip' + pytest.skip() try: os.stat('tmp/poly.shp') @@ -154,14 +140,11 @@ def test_ogr2ogr_py_4(): test_py_scripts.run_py_script(script_path, 'ogr2ogr', 'tmp/poly.shp ../ogr/data/poly.shp -where "EAS_ID=171"') ds = ogr.Open('tmp/poly.shp') - if ds is None or ds.GetLayer(0).GetFeatureCount() != 1: - return 'fail' + assert ds is not None and ds.GetLayer(0).GetFeatureCount() == 1 ds.Destroy() ogr.GetDriverByName('ESRI Shapefile').DeleteDataSource('tmp/poly.shp') - return 'success' - ############################################################################### # Test -append @@ -169,7 +152,7 @@ def test_ogr2ogr_py_4(): def test_ogr2ogr_py_5(): script_path = test_py_scripts.get_py_script('ogr2ogr') if script_path is None: - return 'skip' + pytest.skip() try: os.stat('tmp/poly.shp') @@ -181,25 +164,18 @@ def test_ogr2ogr_py_5(): test_py_scripts.run_py_script(script_path, 'ogr2ogr', '-update -append tmp/poly.shp ../ogr/data/poly.shp') ds = ogr.Open('tmp/poly.shp') - if ds is None or ds.GetLayer(0).GetFeatureCount() != 20: - return 'fail' + assert ds is not None and ds.GetLayer(0).GetFeatureCount() == 20 feat10 = ds.GetLayer(0).GetFeature(10) - if feat10.GetFieldAsDouble('AREA') != 215229.266: - print(feat10.GetFieldAsDouble('AREA')) - gdaltest.post_reason('Did not get expected value for field AREA') - return 'fail' - if feat10.GetFieldAsString('PRFEDEA') != '35043411': - print(feat10.GetFieldAsString('PRFEDEA')) - gdaltest.post_reason('Did not get expected value for field PRFEDEA') - return 'fail' + assert feat10.GetFieldAsDouble('AREA') == 215229.266, \ + 'Did not get expected value for field AREA' + assert feat10.GetFieldAsString('PRFEDEA') == '35043411', \ + 'Did not get expected value for field PRFEDEA' ds.Destroy() ogr.GetDriverByName('ESRI Shapefile').DeleteDataSource('tmp/poly.shp') - return 'success' - ############################################################################### # Test -overwrite @@ -210,13 +186,13 @@ def test_ogr2ogr_py_6(): script_path = test_py_scripts.get_py_script('ogr2ogr') if script_path is None: - return 'skip' + pytest.skip() if test_cli_utilities.get_ogrinfo_path() is None: - return 'skip' + pytest.skip() - ogr_pg.ogr_pg_1() + ogr_pg.test_ogr_pg_1() if gdaltest.pg_ds is None: - return 'skip' + pytest.skip() gdaltest.pg_ds.Destroy() gdaltest.runexternal(test_cli_utilities.get_ogrinfo_path() + ' PG:"' + gdaltest.pg_connection_string + '" -sql "DELLAYER:tpoly"') @@ -225,14 +201,11 @@ def test_ogr2ogr_py_6(): test_py_scripts.run_py_script(script_path, 'ogr2ogr', '-update -overwrite -f PostgreSQL PG:"' + gdaltest.pg_connection_string + '" ../ogr/data/poly.shp -nln tpoly') ds = ogr.Open('PG:' + gdaltest.pg_connection_string) - if ds is None or ds.GetLayerByName('tpoly').GetFeatureCount() != 10: - return 'fail' + assert ds is not None and ds.GetLayerByName('tpoly').GetFeatureCount() == 10 ds.Destroy() gdaltest.runexternal(test_cli_utilities.get_ogrinfo_path() + ' PG:"' + gdaltest.pg_connection_string + '" -sql "DELLAYER:tpoly"') - return 'success' - ############################################################################### # Test -gt @@ -243,13 +216,13 @@ def test_ogr2ogr_py_7(): script_path = test_py_scripts.get_py_script('ogr2ogr') if script_path is None: - return 'skip' + pytest.skip() if test_cli_utilities.get_ogrinfo_path() is None: - return 'skip' + pytest.skip() - ogr_pg.ogr_pg_1() + ogr_pg.test_ogr_pg_1() if gdaltest.pg_ds is None: - return 'skip' + pytest.skip() gdaltest.pg_ds.Destroy() gdaltest.runexternal(test_cli_utilities.get_ogrinfo_path() + ' PG:"' + gdaltest.pg_connection_string + '" -sql "DELLAYER:tpoly"') @@ -257,14 +230,11 @@ def test_ogr2ogr_py_7(): test_py_scripts.run_py_script(script_path, 'ogr2ogr', '-f PostgreSQL PG:"' + gdaltest.pg_connection_string + '" ../ogr/data/poly.shp -nln tpoly -gt 1') ds = ogr.Open('PG:' + gdaltest.pg_connection_string) - if ds is None or ds.GetLayerByName('tpoly').GetFeatureCount() != 10: - return 'fail' + assert ds is not None and ds.GetLayerByName('tpoly').GetFeatureCount() == 10 ds.Destroy() gdaltest.runexternal(test_cli_utilities.get_ogrinfo_path() + ' PG:"' + gdaltest.pg_connection_string + '" -sql "DELLAYER:tpoly"') - return 'success' - ############################################################################### # Test -t_srs @@ -272,7 +242,7 @@ def test_ogr2ogr_py_7(): def test_ogr2ogr_py_8(): script_path = test_py_scripts.get_py_script('ogr2ogr') if script_path is None: - return 'skip' + pytest.skip() try: os.stat('tmp/poly.shp') @@ -283,14 +253,11 @@ def test_ogr2ogr_py_8(): test_py_scripts.run_py_script(script_path, 'ogr2ogr', '-t_srs EPSG:4326 tmp/poly.shp ../ogr/data/poly.shp') ds = ogr.Open('tmp/poly.shp') - if str(ds.GetLayer(0).GetSpatialRef()).find('1984') == -1: - return 'fail' + assert str(ds.GetLayer(0).GetSpatialRef()).find('1984') != -1 ds.Destroy() ogr.GetDriverByName('ESRI Shapefile').DeleteDataSource('tmp/poly.shp') - return 'success' - ############################################################################### # Test -a_srs @@ -298,7 +265,7 @@ def test_ogr2ogr_py_8(): def test_ogr2ogr_py_9(): script_path = test_py_scripts.get_py_script('ogr2ogr') if script_path is None: - return 'skip' + pytest.skip() try: os.stat('tmp/poly.shp') @@ -309,14 +276,11 @@ def test_ogr2ogr_py_9(): test_py_scripts.run_py_script(script_path, 'ogr2ogr', '-a_srs EPSG:4326 tmp/poly.shp ../ogr/data/poly.shp') ds = ogr.Open('tmp/poly.shp') - if str(ds.GetLayer(0).GetSpatialRef()).find('1984') == -1: - return 'fail' + assert str(ds.GetLayer(0).GetSpatialRef()).find('1984') != -1 ds.Destroy() ogr.GetDriverByName('ESRI Shapefile').DeleteDataSource('tmp/poly.shp') - return 'success' - ############################################################################### # Test -select @@ -324,7 +288,7 @@ def test_ogr2ogr_py_9(): def test_ogr2ogr_py_10(): script_path = test_py_scripts.get_py_script('ogr2ogr') if script_path is None: - return 'skip' + pytest.skip() try: os.stat('tmp/poly.shp') @@ -337,8 +301,7 @@ def test_ogr2ogr_py_10(): ds = ogr.Open('tmp/poly.shp') lyr = ds.GetLayer(0) - if lyr.GetLayerDefn().GetFieldCount() != 2: - return 'fail' + assert lyr.GetLayerDefn().GetFieldCount() == 2 feat = lyr.GetNextFeature() ret = 'success' if feat.GetFieldAsDouble('EAS_ID') != 168: @@ -364,7 +327,7 @@ def test_ogr2ogr_py_11(): script_path = test_py_scripts.get_py_script('ogr2ogr') if script_path is None: - return 'skip' + pytest.skip() try: os.stat('tmp/poly.shp') @@ -375,14 +338,11 @@ def test_ogr2ogr_py_11(): test_py_scripts.run_py_script(script_path, 'ogr2ogr', '-lco SHPT=POLYGONZ tmp/poly.shp ../ogr/data/poly.shp') ds = ogr.Open('tmp/poly.shp') - if ds.GetLayer(0).GetLayerDefn().GetGeomType() != ogr.wkbPolygon25D: - return 'fail' + assert ds.GetLayer(0).GetLayerDefn().GetGeomType() == ogr.wkbPolygon25D ds.Destroy() ogr.GetDriverByName('ESRI Shapefile').DeleteDataSource('tmp/poly.shp') - return 'success' - ############################################################################### # Test -nlt @@ -391,7 +351,7 @@ def test_ogr2ogr_py_12(): script_path = test_py_scripts.get_py_script('ogr2ogr') if script_path is None: - return 'skip' + pytest.skip() try: os.stat('tmp/poly.shp') @@ -402,14 +362,11 @@ def test_ogr2ogr_py_12(): test_py_scripts.run_py_script(script_path, 'ogr2ogr', '-nlt POLYGON25D tmp/poly.shp ../ogr/data/poly.shp') ds = ogr.Open('tmp/poly.shp') - if ds.GetLayer(0).GetLayerDefn().GetGeomType() != ogr.wkbPolygon25D: - return 'fail' + assert ds.GetLayer(0).GetLayerDefn().GetGeomType() == ogr.wkbPolygon25D ds.Destroy() ogr.GetDriverByName('ESRI Shapefile').DeleteDataSource('tmp/poly.shp') - return 'success' - ############################################################################### # Add explicit source layer name @@ -417,7 +374,7 @@ def test_ogr2ogr_py_12(): def test_ogr2ogr_py_13(): script_path = test_py_scripts.get_py_script('ogr2ogr') if script_path is None: - return 'skip' + pytest.skip() try: os.stat('tmp/poly.shp') @@ -428,22 +385,20 @@ def test_ogr2ogr_py_13(): test_py_scripts.run_py_script(script_path, 'ogr2ogr', 'tmp/poly.shp ../ogr/data/poly.shp poly') ds = ogr.Open('tmp/poly.shp') - if ds is None or ds.GetLayer(0).GetFeatureCount() != 10: - return 'fail' + assert ds is not None and ds.GetLayer(0).GetFeatureCount() == 10 ds.Destroy() ogr.GetDriverByName('ESRI Shapefile').DeleteDataSource('tmp/poly.shp') - return 'success' - ############################################################################### # Test -segmentize +@pytest.mark.skip() def test_ogr2ogr_py_14(): script_path = test_py_scripts.get_py_script('ogr2ogr') if script_path is None: - return 'skip' + pytest.skip() try: os.stat('tmp/poly.shp') @@ -454,17 +409,13 @@ def test_ogr2ogr_py_14(): test_py_scripts.run_py_script(script_path, 'ogr2ogr', '-segmentize 100 tmp/poly.shp ../ogr/data/poly.shp poly') ds = ogr.Open('tmp/poly.shp') - if ds is None or ds.GetLayer(0).GetFeatureCount() != 10: - return 'fail' + assert ds is not None and ds.GetLayer(0).GetFeatureCount() == 10 feat = ds.GetLayer(0).GetNextFeature() - if feat.GetGeometryRef().GetGeometryRef(0).GetPointCount() != 36: - return 'fail' + assert feat.GetGeometryRef().GetGeometryRef(0).GetPointCount() == 36 ds.Destroy() ogr.GetDriverByName('ESRI Shapefile').DeleteDataSource('tmp/poly.shp') - return 'success' - ############################################################################### # Test -overwrite with a shapefile @@ -473,7 +424,7 @@ def test_ogr2ogr_py_15(): script_path = test_py_scripts.get_py_script('ogr2ogr') if script_path is None: - return 'skip' + pytest.skip() try: os.stat('tmp/poly.shp') @@ -484,20 +435,17 @@ def test_ogr2ogr_py_15(): test_py_scripts.run_py_script(script_path, 'ogr2ogr', 'tmp/poly.shp ../ogr/data/poly.shp') ds = ogr.Open('tmp/poly.shp') - if ds is None or ds.GetLayer(0).GetFeatureCount() != 10: - return 'fail' + assert ds is not None and ds.GetLayer(0).GetFeatureCount() == 10 ds.Destroy() # Overwrite test_py_scripts.run_py_script(script_path, 'ogr2ogr', '-overwrite tmp ../ogr/data/poly.shp') ds = ogr.Open('tmp/poly.shp') - if ds is None or ds.GetLayer(0).GetFeatureCount() != 10: - return 'fail' + assert ds is not None and ds.GetLayer(0).GetFeatureCount() == 10 ds.Destroy() ogr.GetDriverByName('ESRI Shapefile').DeleteDataSource('tmp/poly.shp') - return 'success' ############################################################################### # Test -fid @@ -506,7 +454,7 @@ def test_ogr2ogr_py_15(): def test_ogr2ogr_py_16(): script_path = test_py_scripts.get_py_script('ogr2ogr') if script_path is None: - return 'skip' + pytest.skip() try: os.stat('tmp/poly.shp') @@ -518,17 +466,14 @@ def test_ogr2ogr_py_16(): src_ds = ogr.Open('../ogr/data/poly.shp') ds = ogr.Open('tmp/poly.shp') - if ds is None or ds.GetLayer(0).GetFeatureCount() != 1: - return 'fail' + assert ds is not None and ds.GetLayer(0).GetFeatureCount() == 1 src_feat = src_ds.GetLayer(0).GetFeature(8) feat = ds.GetLayer(0).GetNextFeature() - if feat.GetField("EAS_ID") != src_feat.GetField("EAS_ID"): - return 'fail' + assert feat.GetField("EAS_ID") == src_feat.GetField("EAS_ID") ds.Destroy() src_ds.Destroy() ogr.GetDriverByName('ESRI Shapefile').DeleteDataSource('tmp/poly.shp') - return 'success' ############################################################################### # Test -progress @@ -537,7 +482,7 @@ def test_ogr2ogr_py_16(): def test_ogr2ogr_py_17(): script_path = test_py_scripts.get_py_script('ogr2ogr') if script_path is None: - return 'skip' + pytest.skip() try: os.stat('tmp/poly.shp') @@ -546,29 +491,26 @@ def test_ogr2ogr_py_17(): pass ret = test_py_scripts.run_py_script(script_path, 'ogr2ogr', '-progress tmp/poly.shp ../ogr/data/poly.shp') - if ret.find('0...10...20...30...40...50...60...70...80...90...100 - done.') == -1: - print(ret) - return 'fail' + assert ret.find('0...10...20...30...40...50...60...70...80...90...100 - done.') != -1 ds = ogr.Open('tmp/poly.shp') - if ds is None or ds.GetLayer(0).GetFeatureCount() != 10: - return 'fail' + assert ds is not None and ds.GetLayer(0).GetFeatureCount() == 10 ds.Destroy() ogr.GetDriverByName('ESRI Shapefile').DeleteDataSource('tmp/poly.shp') - return 'success' ############################################################################### # Test -wrapdateline +@pytest.mark.skip() def test_ogr2ogr_py_18(): script_path = test_py_scripts.get_py_script('ogr2ogr') if script_path is None: - return 'skip' + pytest.skip() if not ogrtest.have_geos(): - return 'skip' + pytest.skip() try: os.stat('tmp/wrapdateline_src.shp') @@ -608,7 +550,7 @@ def test_ogr2ogr_py_18(): ogr.GetDriverByName('ESRI Shapefile').DeleteDataSource('tmp/wrapdateline_src.shp') ogr.GetDriverByName('ESRI Shapefile').DeleteDataSource('tmp/wrapdateline_dst.shp') - return 'success' if ret == 0 else 'fail' + assert ret == 0 ############################################################################### # Test -clipsrc @@ -617,10 +559,10 @@ def test_ogr2ogr_py_18(): def test_ogr2ogr_py_19(): script_path = test_py_scripts.get_py_script('ogr2ogr') if script_path is None: - return 'skip' + pytest.skip() if not ogrtest.have_geos(): - return 'skip' + pytest.skip() try: os.stat('tmp/poly.shp') @@ -631,20 +573,15 @@ def test_ogr2ogr_py_19(): test_py_scripts.run_py_script(script_path, 'ogr2ogr', 'tmp/poly.shp ../ogr/data/poly.shp -clipsrc spat_extent -spat 479609 4764629 479764 4764817') ds = ogr.Open('tmp/poly.shp') - if ds is None or ds.GetLayer(0).GetFeatureCount() != 4: - return 'fail' + assert ds is not None and ds.GetLayer(0).GetFeatureCount() == 4 - if ds.GetLayer(0).GetExtent() != (479609, 479764, 4764629, 4764817): - print(ds.GetLayer(0).GetExtent()) - gdaltest.post_reason('unexpected extent') - return 'fail' + assert ds.GetLayer(0).GetExtent() == (479609, 479764, 4764629, 4764817), \ + 'unexpected extent' ds.Destroy() ogr.GetDriverByName('ESRI Shapefile').DeleteDataSource('tmp/poly.shp') - return 'success' - ############################################################################### # Test correct remap of fields when laundering to Shapefile format # Test that the data is going into the right field @@ -654,7 +591,7 @@ def test_ogr2ogr_py_19(): def test_ogr2ogr_py_20(): script_path = test_py_scripts.get_py_script('ogr2ogr') if script_path is None: - return 'skip' + pytest.skip() try: os.remove('tmp/Fields.dbf') @@ -696,14 +633,12 @@ def test_ogr2ogr_py_20(): ds = ogr.Open('tmp/Fields.dbf') - if ds is None: - return 'fail' + assert ds is not None layer_defn = ds.GetLayer(0).GetLayerDefn() if layer_defn.GetFieldCount() != 15: - gdaltest.post_reason('Unexpected field count: ' + str(ds.GetLayer(0).GetLayerDefn().GetFieldCount())) ds.Destroy() ogr.GetDriverByName('ESRI Shapefile').DeleteDataSource('tmp/Fields.dbf') - return 'fail' + pytest.fail('Unexpected field count: ' + str(ds.GetLayer(0).GetLayerDefn().GetFieldCount())) error_occurred = False feat = ds.GetLayer(0).GetNextFeature() @@ -718,10 +653,7 @@ def test_ogr2ogr_py_20(): ds.Destroy() ogr.GetDriverByName('ESRI Shapefile').DeleteDataSource('tmp/Fields.dbf') - if error_occurred: - return 'fail' - - return 'success' + assert not error_occurred ############################################################################### # Test ogr2ogr when the output driver has already created the fields @@ -731,7 +663,7 @@ def test_ogr2ogr_py_20(): def test_ogr2ogr_py_21(): script_path = test_py_scripts.get_py_script('ogr2ogr') if script_path is None: - return 'skip' + pytest.skip() try: os.remove('tmp/testogr2ogr21.gtm') @@ -743,24 +675,20 @@ def test_ogr2ogr_py_21(): '-sql "SELECT comment, name FROM dataforogr2ogr21" -nlt POINT') ds = ogr.Open('tmp/testogr2ogr21.gtm') - if ds is None: - return 'fail' + assert ds is not None ds.GetLayer(0).GetLayerDefn() lyr = ds.GetLayer(0) feat = lyr.GetNextFeature() if feat.GetFieldAsString('name') != 'NAME' or \ feat.GetFieldAsString('comment') != 'COMMENT': - print(feat.GetFieldAsString('name')) print(feat.GetFieldAsString('comment')) ds.Destroy() os.remove('tmp/testogr2ogr21.gtm') - return 'fail' + pytest.fail(feat.GetFieldAsString('name')) ds.Destroy() os.remove('tmp/testogr2ogr21.gtm') - return 'success' - ############################################################################### # Test ogr2ogr when the output driver delays the destination layer defn creation (#3384) @@ -768,31 +696,27 @@ def test_ogr2ogr_py_21(): def test_ogr2ogr_py_22(): script_path = test_py_scripts.get_py_script('ogr2ogr') if script_path is None: - return 'skip' + pytest.skip() test_py_scripts.run_py_script(script_path, 'ogr2ogr', '-f "MapInfo File" tmp/testogr2ogr22.mif ../utilities/data/dataforogr2ogr21.csv ' + '-sql "SELECT comment, name FROM dataforogr2ogr21" -nlt POINT') ds = ogr.Open('tmp/testogr2ogr22.mif') - if ds is None: - return 'fail' + assert ds is not None ds.GetLayer(0).GetLayerDefn() lyr = ds.GetLayer(0) feat = lyr.GetNextFeature() if feat.GetFieldAsString('name') != 'NAME' or \ feat.GetFieldAsString('comment') != 'COMMENT': - print(feat.GetFieldAsString('name')) print(feat.GetFieldAsString('comment')) ds.Destroy() ogr.GetDriverByName('MapInfo File').DeleteDataSource('tmp/testogr2ogr22.mif') - return 'fail' + pytest.fail(feat.GetFieldAsString('name')) ds.Destroy() ogr.GetDriverByName('MapInfo File').DeleteDataSource('tmp/testogr2ogr22.mif') - return 'success' - ############################################################################### # Same as previous but with -select @@ -800,33 +724,29 @@ def test_ogr2ogr_py_22(): def test_ogr2ogr_py_23(): script_path = test_py_scripts.get_py_script('ogr2ogr') if script_path is None: - return 'skip' + pytest.skip() if test_cli_utilities.get_ogr2ogr_path() is None: - return 'skip' + pytest.skip() gdaltest.runexternal(test_cli_utilities.get_ogr2ogr_path() + ' -f "MapInfo File" tmp/testogr2ogr23.mif ../utilities/data/dataforogr2ogr21.csv ' + '-sql "SELECT comment, name FROM dataforogr2ogr21" -select comment,name -nlt POINT') ds = ogr.Open('tmp/testogr2ogr23.mif') - if ds is None: - return 'fail' + assert ds is not None ds.GetLayer(0).GetLayerDefn() lyr = ds.GetLayer(0) feat = lyr.GetNextFeature() if feat.GetFieldAsString('name') != 'NAME' or \ feat.GetFieldAsString('comment') != 'COMMENT': - print(feat.GetFieldAsString('name')) print(feat.GetFieldAsString('comment')) ds.Destroy() ogr.GetDriverByName('MapInfo File').DeleteDataSource('tmp/testogr2ogr23.mif') - return 'fail' + pytest.fail(feat.GetFieldAsString('name')) ds.Destroy() ogr.GetDriverByName('MapInfo File').DeleteDataSource('tmp/testogr2ogr23.mif') - return 'success' - ############################################################################### # Test -clipsrc with WKT geometry (#3530) @@ -834,10 +754,10 @@ def test_ogr2ogr_py_23(): def test_ogr2ogr_py_24(): script_path = test_py_scripts.get_py_script('ogr2ogr') if script_path is None: - return 'skip' + pytest.skip() if not ogrtest.have_geos(): - return 'skip' + pytest.skip() try: os.stat('tmp/poly.shp') @@ -848,20 +768,15 @@ def test_ogr2ogr_py_24(): test_py_scripts.run_py_script(script_path, 'ogr2ogr', 'tmp/poly.shp ../ogr/data/poly.shp -clipsrc "POLYGON((479609 4764629,479609 4764817,479764 4764817,479764 4764629,479609 4764629))"') ds = ogr.Open('tmp/poly.shp') - if ds is None or ds.GetLayer(0).GetFeatureCount() != 4: - return 'fail' + assert ds is not None and ds.GetLayer(0).GetFeatureCount() == 4 - if ds.GetLayer(0).GetExtent() != (479609, 479764, 4764629, 4764817): - print(ds.GetLayer(0).GetExtent()) - gdaltest.post_reason('unexpected extent') - return 'fail' + assert ds.GetLayer(0).GetExtent() == (479609, 479764, 4764629, 4764817), \ + 'unexpected extent' ds.Destroy() ogr.GetDriverByName('ESRI Shapefile').DeleteDataSource('tmp/poly.shp') - return 'success' - ############################################################################### # Test -clipsrc with clip from external datasource @@ -869,10 +784,10 @@ def test_ogr2ogr_py_24(): def test_ogr2ogr_py_25(): script_path = test_py_scripts.get_py_script('ogr2ogr') if script_path is None: - return 'skip' + pytest.skip() if not ogrtest.have_geos(): - return 'skip' + pytest.skip() try: os.stat('tmp/poly.shp') @@ -888,21 +803,16 @@ def test_ogr2ogr_py_25(): test_py_scripts.run_py_script(script_path, 'ogr2ogr', 'tmp/poly.shp ../ogr/data/poly.shp -clipsrc tmp/clip.csv -clipsrcwhere foo=\'foo\'') ds = ogr.Open('tmp/poly.shp') - if ds is None or ds.GetLayer(0).GetFeatureCount() != 4: - return 'fail' + assert ds is not None and ds.GetLayer(0).GetFeatureCount() == 4 - if ds.GetLayer(0).GetExtent() != (479609, 479764, 4764629, 4764817): - print(ds.GetLayer(0).GetExtent()) - gdaltest.post_reason('unexpected extent') - return 'fail' + assert ds.GetLayer(0).GetExtent() == (479609, 479764, 4764629, 4764817), \ + 'unexpected extent' ds.Destroy() ogr.GetDriverByName('ESRI Shapefile').DeleteDataSource('tmp/poly.shp') os.remove('tmp/clip.csv') - return 'success' - ############################################################################### # Test -clipdst with WKT geometry (#3530) @@ -910,10 +820,10 @@ def test_ogr2ogr_py_25(): def test_ogr2ogr_py_26(): script_path = test_py_scripts.get_py_script('ogr2ogr') if script_path is None: - return 'skip' + pytest.skip() if not ogrtest.have_geos(): - return 'skip' + pytest.skip() try: os.stat('tmp/poly.shp') @@ -924,20 +834,15 @@ def test_ogr2ogr_py_26(): test_py_scripts.run_py_script(script_path, 'ogr2ogr', 'tmp/poly.shp ../ogr/data/poly.shp -clipdst "POLYGON((479609 4764629,479609 4764817,479764 4764817,479764 4764629,479609 4764629))"') ds = ogr.Open('tmp/poly.shp') - if ds is None or ds.GetLayer(0).GetFeatureCount() != 4: - return 'fail' + assert ds is not None and ds.GetLayer(0).GetFeatureCount() == 4 - if ds.GetLayer(0).GetExtent() != (479609, 479764, 4764629, 4764817): - print(ds.GetLayer(0).GetExtent()) - gdaltest.post_reason('unexpected extent') - return 'fail' + assert ds.GetLayer(0).GetExtent() == (479609, 479764, 4764629, 4764817), \ + 'unexpected extent' ds.Destroy() ogr.GetDriverByName('ESRI Shapefile').DeleteDataSource('tmp/poly.shp') - return 'success' - ############################################################################### # Test -clipdst with clip from external datasource @@ -945,10 +850,10 @@ def test_ogr2ogr_py_26(): def test_ogr2ogr_py_27(): script_path = test_py_scripts.get_py_script('ogr2ogr') if script_path is None: - return 'skip' + pytest.skip() if not ogrtest.have_geos(): - return 'skip' + pytest.skip() try: os.stat('tmp/poly.shp') @@ -964,21 +869,16 @@ def test_ogr2ogr_py_27(): test_py_scripts.run_py_script(script_path, 'ogr2ogr', '-nlt MULTIPOLYGON tmp/poly.shp ../ogr/data/poly.shp -clipdst tmp/clip.csv -clipdstsql "SELECT * from clip"') ds = ogr.Open('tmp/poly.shp') - if ds is None or ds.GetLayer(0).GetFeatureCount() != 4: - return 'fail' + assert ds is not None and ds.GetLayer(0).GetFeatureCount() == 4 - if ds.GetLayer(0).GetExtent() != (479609, 479764, 4764629, 4764817): - print(ds.GetLayer(0).GetExtent()) - gdaltest.post_reason('unexpected extent') - return 'fail' + assert ds.GetLayer(0).GetExtent() == (479609, 479764, 4764629, 4764817), \ + 'unexpected extent' ds.Destroy() ogr.GetDriverByName('ESRI Shapefile').DeleteDataSource('tmp/poly.shp') os.remove('tmp/clip.csv') - return 'success' - ############################################################################### # Test that -overwrite work if the output file doesn't yet exist (#3825) @@ -987,7 +887,7 @@ def test_ogr2ogr_py_31(): script_path = test_py_scripts.get_py_script('ogr2ogr') if script_path is None: - return 'skip' + pytest.skip() try: os.stat('tmp/poly.shp') @@ -998,12 +898,10 @@ def test_ogr2ogr_py_31(): test_py_scripts.run_py_script(script_path, 'ogr2ogr', ' -overwrite tmp/poly.shp ../ogr/data/poly.shp') ds = ogr.Open('tmp/poly.shp') - if ds is None or ds.GetLayer(0).GetFeatureCount() != 10: - return 'fail' + assert ds is not None and ds.GetLayer(0).GetFeatureCount() == 10 ds.Destroy() ogr.GetDriverByName('ESRI Shapefile').DeleteDataSource('tmp/poly.shp') - return 'success' ############################################################################### # Test that -append/-overwrite to a single-file shapefile work without specifying -nln @@ -1013,7 +911,7 @@ def test_ogr2ogr_py_32(): script_path = test_py_scripts.get_py_script('ogr2ogr') if script_path is None: - return 'skip' + pytest.skip() try: os.stat('tmp/test_ogr2ogr_32.shp') @@ -1025,21 +923,17 @@ def test_ogr2ogr_py_32(): test_py_scripts.run_py_script(script_path, 'ogr2ogr', ' -append tmp/test_ogr2ogr_32.shp ../ogr/data/poly.shp') ds = ogr.Open('tmp/test_ogr2ogr_32.shp') - if ds is None or ds.GetLayer(0).GetFeatureCount() != 20: - gdaltest.post_reason('-append failed') - return 'fail' + assert ds is not None and ds.GetLayer(0).GetFeatureCount() == 20, '-append failed' ds = None test_py_scripts.run_py_script(script_path, 'ogr2ogr', ' -overwrite tmp/test_ogr2ogr_32.shp ../ogr/data/poly.shp') ds = ogr.Open('tmp/test_ogr2ogr_32.shp') - if ds is None or ds.GetLayer(0).GetFeatureCount() != 10: - gdaltest.post_reason('-overwrite failed') - return 'fail' + assert ds is not None and ds.GetLayer(0).GetFeatureCount() == 10, \ + '-overwrite failed' ds = None ogr.GetDriverByName('ESRI Shapefile').DeleteDataSource('tmp/test_ogr2ogr_32.shp') - return 'success' ############################################################################### # Test -explodecollections @@ -1049,7 +943,7 @@ def test_ogr2ogr_py_33(): script_path = test_py_scripts.get_py_script('ogr2ogr') if script_path is None: - return 'skip' + pytest.skip() try: os.stat('tmp/test_ogr2ogr_33_src.csv') @@ -1073,40 +967,36 @@ def test_ogr2ogr_py_33(): ds = ogr.Open('tmp/test_ogr2ogr_33_dst.shp') lyr = ds.GetLayer(0) - if lyr.GetFeatureCount() != 3: - gdaltest.post_reason('-explodecollections failed') - print(lyr.GetFeatureCount()) - return 'fail' + assert lyr.GetFeatureCount() == 3, '-explodecollections failed' feat = lyr.GetFeature(0) if feat.GetField("foo") != 'bar': feat.DumpReadable() - return 'fail' + pytest.fail() if feat.GetGeometryRef().ExportToWkt() != 'POLYGON ((10 10,10 11,11 11,11 10,10 10))': feat.DumpReadable() - return 'fail' + pytest.fail() feat = lyr.GetFeature(1) if feat.GetField("foo") != 'bar': feat.DumpReadable() - return 'fail' + pytest.fail() if feat.GetGeometryRef().ExportToWkt() != 'POLYGON ((100 100,100 200,200 200,200 100,100 100),(125 125,175 125,175 175,125 175,125 125))': feat.DumpReadable() - return 'fail' + pytest.fail() feat = lyr.GetFeature(2) if feat.GetField("foo") != 'baz': feat.DumpReadable() - return 'fail' + pytest.fail() if feat.GetGeometryRef().ExportToWkt() != 'POLYGON ((0 0,0 1,1 1,1 0,0 0))': feat.DumpReadable() - return 'fail' + pytest.fail() ds = None ogr.GetDriverByName('CSV').DeleteDataSource('tmp/test_ogr2ogr_33_src.csv') ogr.GetDriverByName('ESRI Shapefile').DeleteDataSource('tmp/test_ogr2ogr_33_dst.shp') - return 'success' ############################################################################### # Test 'ogr2ogr someDirThatDoesNotExist src.shp -nln someDirThatDoesNotExist' @@ -1118,7 +1008,7 @@ def test_ogr2ogr_py_34(): script_path = test_py_scripts.get_py_script('ogr2ogr') if script_path is None: - return 'skip' + pytest.skip() try: os.stat('tmp/test_ogr2ogr_34_dir') @@ -1129,29 +1019,24 @@ def test_ogr2ogr_py_34(): test_py_scripts.run_py_script(script_path, 'ogr2ogr', ' tmp/test_ogr2ogr_34_dir ../ogr/data/poly.shp -nln test_ogr2ogr_34_dir') ds = ogr.Open('tmp/test_ogr2ogr_34_dir/test_ogr2ogr_34_dir.shp') - if ds is None or ds.GetLayer(0).GetFeatureCount() != 10: - gdaltest.post_reason('initial shapefile creation failed') - return 'fail' + assert ds is not None and ds.GetLayer(0).GetFeatureCount() == 10, \ + 'initial shapefile creation failed' ds = None test_py_scripts.run_py_script(script_path, 'ogr2ogr', ' -append tmp/test_ogr2ogr_34_dir ../ogr/data/poly.shp -nln test_ogr2ogr_34_dir') ds = ogr.Open('tmp/test_ogr2ogr_34_dir/test_ogr2ogr_34_dir.shp') - if ds is None or ds.GetLayer(0).GetFeatureCount() != 20: - gdaltest.post_reason('-append failed') - return 'fail' + assert ds is not None and ds.GetLayer(0).GetFeatureCount() == 20, '-append failed' ds = None test_py_scripts.run_py_script(script_path, 'ogr2ogr', ' -overwrite tmp/test_ogr2ogr_34_dir ../ogr/data/poly.shp -nln test_ogr2ogr_34_dir') ds = ogr.Open('tmp/test_ogr2ogr_34_dir/test_ogr2ogr_34_dir.shp') - if ds is None or ds.GetLayer(0).GetFeatureCount() != 10: - gdaltest.post_reason('-overwrite failed') - return 'fail' + assert ds is not None and ds.GetLayer(0).GetFeatureCount() == 10, \ + '-overwrite failed' ds = None ogr.GetDriverByName('ESRI Shapefile').DeleteDataSource('tmp/test_ogr2ogr_34_dir') - return 'success' ############################################################################### # Test 'ogr2ogr someDirThatDoesNotExist src.shp' @@ -1161,7 +1046,7 @@ def test_ogr2ogr_py_35(): script_path = test_py_scripts.get_py_script('ogr2ogr') if script_path is None: - return 'skip' + pytest.skip() try: os.stat('tmp/test_ogr2ogr_35_dir') @@ -1172,29 +1057,24 @@ def test_ogr2ogr_py_35(): test_py_scripts.run_py_script(script_path, 'ogr2ogr', ' tmp/test_ogr2ogr_35_dir ../ogr/data/poly.shp ') ds = ogr.Open('tmp/test_ogr2ogr_35_dir/poly.shp') - if ds is None or ds.GetLayer(0).GetFeatureCount() != 10: - gdaltest.post_reason('initial shapefile creation failed') - return 'fail' + assert ds is not None and ds.GetLayer(0).GetFeatureCount() == 10, \ + 'initial shapefile creation failed' ds = None test_py_scripts.run_py_script(script_path, 'ogr2ogr', ' -append tmp/test_ogr2ogr_35_dir ../ogr/data/poly.shp') ds = ogr.Open('tmp/test_ogr2ogr_35_dir/poly.shp') - if ds is None or ds.GetLayer(0).GetFeatureCount() != 20: - gdaltest.post_reason('-append failed') - return 'fail' + assert ds is not None and ds.GetLayer(0).GetFeatureCount() == 20, '-append failed' ds = None test_py_scripts.run_py_script(script_path, 'ogr2ogr', ' -overwrite tmp/test_ogr2ogr_35_dir ../ogr/data/poly.shp') ds = ogr.Open('tmp/test_ogr2ogr_35_dir/poly.shp') - if ds is None or ds.GetLayer(0).GetFeatureCount() != 10: - gdaltest.post_reason('-overwrite failed') - return 'fail' + assert ds is not None and ds.GetLayer(0).GetFeatureCount() == 10, \ + '-overwrite failed' ds = None ogr.GetDriverByName('ESRI Shapefile').DeleteDataSource('tmp/test_ogr2ogr_35_dir') - return 'success' ############################################################################### # Test ogr2ogr -zfield @@ -1204,7 +1084,7 @@ def test_ogr2ogr_py_36(): script_path = test_py_scripts.get_py_script('ogr2ogr') if script_path is None: - return 'skip' + pytest.skip() try: os.stat('tmp/test_ogr2ogr_36.shp') @@ -1221,10 +1101,7 @@ def test_ogr2ogr_py_36(): ogr.GetDriverByName('ESRI Shapefile').DeleteDataSource('tmp/test_ogr2ogr_36.shp') - if wkt.find(' 168,') == -1: - return 'fail' - - return 'success' + assert wkt.find(' 168,') != -1 ############################################################################### # Test 'ogr2ogr someDirThatDoesNotExist.shp dataSourceWithMultipleLayer' @@ -1234,7 +1111,7 @@ def test_ogr2ogr_py_37(): script_path = test_py_scripts.get_py_script('ogr2ogr') if script_path is None: - return 'skip' + pytest.skip() try: os.stat('tmp/test_ogr2ogr_37_dir.shp') @@ -1256,15 +1133,12 @@ def test_ogr2ogr_py_37(): test_py_scripts.run_py_script(script_path, 'ogr2ogr', ' tmp/test_ogr2ogr_37_dir.shp tmp/test_ogr2ogr_37_src') ds = ogr.Open('tmp/test_ogr2ogr_37_dir.shp') - if ds is None or ds.GetLayerCount() != 2: - return 'fail' + assert ds is not None and ds.GetLayerCount() == 2 ds = None ogr.GetDriverByName('ESRI Shapefile').DeleteDataSource('tmp/test_ogr2ogr_37_src') ogr.GetDriverByName('ESRI Shapefile').DeleteDataSource('tmp/test_ogr2ogr_37_dir.shp') - return 'success' - ############################################################################### # Test that we take into account the fields by the where clause when combining # -select and -where (#4015) @@ -1274,7 +1148,7 @@ def test_ogr2ogr_py_38(): script_path = test_py_scripts.get_py_script('ogr2ogr') if script_path is None: - return 'skip' + pytest.skip() try: os.stat('tmp/test_ogr2ogr_38.shp') @@ -1287,14 +1161,11 @@ def test_ogr2ogr_py_38(): ds = ogr.Open('tmp/test_ogr2ogr_38.shp') lyr = ds.GetLayer(0) feat = lyr.GetNextFeature() - if feat is None: - return 'fail' + assert feat is not None ds = None ogr.GetDriverByName('ESRI Shapefile').DeleteDataSource('tmp/test_ogr2ogr_38.shp') - return 'success' - ############################################################################### # Test 'ogr2ogr someDirThatDoesNotExist.shp dataSourceWithMultipleLayer -sql "select * from alayer"' (#4268) @@ -1303,7 +1174,7 @@ def test_ogr2ogr_py_39(): script_path = test_py_scripts.get_py_script('ogr2ogr') if script_path is None: - return 'skip' + pytest.skip() try: os.stat('tmp/test_ogr2ogr_39_dir.shp') @@ -1325,15 +1196,12 @@ def test_ogr2ogr_py_39(): test_py_scripts.run_py_script(script_path, 'ogr2ogr', ' tmp/test_ogr2ogr_39.shp tmp/test_ogr2ogr_39_src -sql "select * from poly"') ds = ogr.Open('tmp/test_ogr2ogr_39.shp') - if ds is None or ds.GetLayerCount() != 1: - return 'fail' + assert ds is not None and ds.GetLayerCount() == 1 ds = None ogr.GetDriverByName('ESRI Shapefile').DeleteDataSource('tmp/test_ogr2ogr_39_src') ogr.GetDriverByName('ESRI Shapefile').DeleteDataSource('tmp/test_ogr2ogr_39.shp') - return 'success' - ############################################################################### # Test -dim 3 and -dim 2 @@ -1342,7 +1210,7 @@ def test_ogr2ogr_py_43(): script_path = test_py_scripts.get_py_script('ogr2ogr') if script_path is None: - return 'skip' + pytest.skip() try: os.stat('tmp/test_ogr2ogr_43_3d.shp') @@ -1354,8 +1222,7 @@ def test_ogr2ogr_py_43(): ds = ogr.Open('tmp/test_ogr2ogr_43_3d.shp') lyr = ds.GetLayerByIndex(0) - if lyr.GetGeomType() != ogr.wkbPolygon25D: - return 'fail' + assert lyr.GetGeomType() == ogr.wkbPolygon25D ds = None try: @@ -1368,15 +1235,12 @@ def test_ogr2ogr_py_43(): ds = ogr.Open('tmp/test_ogr2ogr_43_2d.shp') lyr = ds.GetLayerByIndex(0) - if lyr.GetGeomType() != ogr.wkbPolygon: - return 'fail' + assert lyr.GetGeomType() == ogr.wkbPolygon ds = None ogr.GetDriverByName('ESRI Shapefile').DeleteDataSource('tmp/test_ogr2ogr_43_2d.shp') ogr.GetDriverByName('ESRI Shapefile').DeleteDataSource('tmp/test_ogr2ogr_43_3d.shp') - return 'success' - ############################################################################### # Test -nlt PROMOTE_TO_MULTI for polygon/multipolygon @@ -1385,7 +1249,7 @@ def test_ogr2ogr_py_44(): script_path = test_py_scripts.get_py_script('ogr2ogr') if script_path is None: - return 'skip' + pytest.skip() try: os.stat('tmp/test_ogr2ogr_44_src.shp') @@ -1412,26 +1276,18 @@ def test_ogr2ogr_py_44(): data = f.read() f.close() - if data.find('type="gml:MultiPolygonPropertyType"') == -1: - gdaltest.post_reason('failure') - print(data) - return 'fail' + assert data.find('type="gml:MultiPolygonPropertyType"') != -1 f = open('tmp/test_ogr2ogr_44.gml') data = f.read() f.close() - if data.find('<ogr:geometryProperty><gml:MultiPolygon><gml:polygonMember><gml:Polygon><gml:outerBoundaryIs><gml:LinearRing><gml:coordinates>0,0 0,1 1,1 0,0</gml:coordinates></gml:LinearRing></gml:outerBoundaryIs></gml:Polygon></gml:polygonMember></gml:MultiPolygon></ogr:geometryProperty>') == -1: - gdaltest.post_reason('failure') - print(data) - return 'fail' + assert data.find('<ogr:geometryProperty><gml:MultiPolygon><gml:polygonMember><gml:Polygon><gml:outerBoundaryIs><gml:LinearRing><gml:coordinates>0,0 0,1 1,1 0,0</gml:coordinates></gml:LinearRing></gml:outerBoundaryIs></gml:Polygon></gml:polygonMember></gml:MultiPolygon></ogr:geometryProperty>') != -1 ogr.GetDriverByName('ESRI Shapefile').DeleteDataSource('tmp/test_ogr2ogr_44_src.shp') os.unlink('tmp/test_ogr2ogr_44.gml') os.unlink('tmp/test_ogr2ogr_44.xsd') - return 'success' - ############################################################################### # Test -nlt PROMOTE_TO_MULTI for polygon/multipolygon @@ -1440,7 +1296,7 @@ def test_ogr2ogr_py_45(): script_path = test_py_scripts.get_py_script('ogr2ogr') if script_path is None: - return 'skip' + pytest.skip() try: os.stat('tmp/test_ogr2ogr_44_src.shp') @@ -1467,26 +1323,18 @@ def test_ogr2ogr_py_45(): data = f.read() f.close() - if data.find('type="gml:MultiPolygonPropertyType"') == -1: - gdaltest.post_reason('failure') - print(data) - return 'fail' + assert data.find('type="gml:MultiPolygonPropertyType"') != -1 f = open('tmp/test_ogr2ogr_44.gml') data = f.read() f.close() - if data.find('<ogr:geometryProperty><gml:MultiPolygon><gml:polygonMember><gml:Polygon><gml:outerBoundaryIs><gml:LinearRing><gml:coordinates>0,0 0,1 1,1 0,0</gml:coordinates></gml:LinearRing></gml:outerBoundaryIs></gml:Polygon></gml:polygonMember></gml:MultiPolygon></ogr:geometryProperty>') == -1: - gdaltest.post_reason('failure') - print(data) - return 'fail' + assert data.find('<ogr:geometryProperty><gml:MultiPolygon><gml:polygonMember><gml:Polygon><gml:outerBoundaryIs><gml:LinearRing><gml:coordinates>0,0 0,1 1,1 0,0</gml:coordinates></gml:LinearRing></gml:outerBoundaryIs></gml:Polygon></gml:polygonMember></gml:MultiPolygon></ogr:geometryProperty>') != -1 ogr.GetDriverByName('ESRI Shapefile').DeleteDataSource('tmp/test_ogr2ogr_44_src.shp') os.unlink('tmp/test_ogr2ogr_44.gml') os.unlink('tmp/test_ogr2ogr_44.xsd') - return 'success' - ############################################################################### # Test -nlt PROMOTE_TO_MULTI for linestring/multilinestring @@ -1495,7 +1343,7 @@ def test_ogr2ogr_py_46(): script_path = test_py_scripts.get_py_script('ogr2ogr') if script_path is None: - return 'skip' + pytest.skip() try: os.stat('tmp/test_ogr2ogr_45_src.shp') @@ -1522,73 +1370,17 @@ def test_ogr2ogr_py_46(): data = f.read() f.close() - if data.find('type="gml:MultiLineStringPropertyType"') == -1: - gdaltest.post_reason('failure') - print(data) - return 'fail' + assert data.find('type="gml:MultiLineStringPropertyType"') != -1 f = open('tmp/test_ogr2ogr_45.gml') data = f.read() f.close() - if data.find('<ogr:geometryProperty><gml:MultiLineString><gml:lineStringMember><gml:LineString><gml:coordinates>0,0 0,1 1,1 0,0</gml:coordinates></gml:LineString></gml:lineStringMember></gml:MultiLineString></ogr:geometryProperty>') == -1: - gdaltest.post_reason('failure') - print(data) - return 'fail' + assert data.find('<ogr:geometryProperty><gml:MultiLineString><gml:lineStringMember><gml:LineString><gml:coordinates>0,0 0,1 1,1 0,0</gml:coordinates></gml:LineString></gml:lineStringMember></gml:MultiLineString></ogr:geometryProperty>') != -1 ogr.GetDriverByName('ESRI Shapefile').DeleteDataSource('tmp/test_ogr2ogr_45_src.shp') gdal.Unlink('tmp/test_ogr2ogr_45.gml') gdal.Unlink('tmp/test_ogr2ogr_45.xsd') - return 'success' - - -gdaltest_list = [ - test_ogr2ogr_py_1, - test_ogr2ogr_py_2, - test_ogr2ogr_py_3, - test_ogr2ogr_py_4, - test_ogr2ogr_py_5, - test_ogr2ogr_py_6, - test_ogr2ogr_py_7, - test_ogr2ogr_py_8, - test_ogr2ogr_py_9, - test_ogr2ogr_py_10, - test_ogr2ogr_py_11, - test_ogr2ogr_py_12, - test_ogr2ogr_py_13, - # test_ogr2ogr_py_14, - test_ogr2ogr_py_15, - test_ogr2ogr_py_16, - test_ogr2ogr_py_17, - # test_ogr2ogr_py_18, - test_ogr2ogr_py_19, - test_ogr2ogr_py_20, - test_ogr2ogr_py_21, - test_ogr2ogr_py_22, - test_ogr2ogr_py_23, - test_ogr2ogr_py_24, - test_ogr2ogr_py_25, - test_ogr2ogr_py_26, - test_ogr2ogr_py_27, - test_ogr2ogr_py_31, - test_ogr2ogr_py_32, - test_ogr2ogr_py_33, - test_ogr2ogr_py_34, - test_ogr2ogr_py_35, - test_ogr2ogr_py_36, - test_ogr2ogr_py_37, - test_ogr2ogr_py_38, - test_ogr2ogr_py_39, - test_ogr2ogr_py_43, - test_ogr2ogr_py_44, - test_ogr2ogr_py_45, - test_ogr2ogr_py_46] - -if __name__ == '__main__': - - gdaltest.setup_run('test_ogr2ogr_py') - - gdaltest.run_tests(gdaltest_list) - - sys.exit(gdaltest.summarize()) + + diff --git a/autotest/pyscripts/test_ogrinfo_py.py b/autotest/pyscripts/test_ogrinfo_py.py index 06f46ab884a2..b5bcf2830f2a 100755 --- a/autotest/pyscripts/test_ogrinfo_py.py +++ b/autotest/pyscripts/test_ogrinfo_py.py @@ -28,14 +28,12 @@ # DEALINGS IN THE SOFTWARE. ############################################################################### -import sys import os -sys.path.append('../pymod') -import gdaltest import ogrtest import test_py_scripts +import pytest ############################################################################### # Simple test @@ -44,13 +42,10 @@ def test_ogrinfo_py_1(): script_path = test_py_scripts.get_py_script('ogrinfo') if script_path is None: - return 'skip' + pytest.skip() ret = test_py_scripts.run_py_script(script_path, 'ogrinfo', '../ogr/data/poly.shp') - if ret.find('ESRI Shapefile') == -1: - return 'fail' - - return 'success' + assert ret.find('ESRI Shapefile') != -1 ############################################################################### # Test -ro option @@ -59,13 +54,10 @@ def test_ogrinfo_py_1(): def test_ogrinfo_py_2(): script_path = test_py_scripts.get_py_script('ogrinfo') if script_path is None: - return 'skip' + pytest.skip() ret = test_py_scripts.run_py_script(script_path, 'ogrinfo', '-ro ../ogr/data/poly.shp') - if ret.find('ESRI Shapefile') == -1: - return 'fail' - - return 'success' + assert ret.find('ESRI Shapefile') != -1 ############################################################################### # Test -al option @@ -74,13 +66,10 @@ def test_ogrinfo_py_2(): def test_ogrinfo_py_3(): script_path = test_py_scripts.get_py_script('ogrinfo') if script_path is None: - return 'skip' + pytest.skip() ret = test_py_scripts.run_py_script(script_path, 'ogrinfo', '-al ../ogr/data/poly.shp') - if ret.find('Feature Count: 10') == -1: - return 'fail' - - return 'success' + assert ret.find('Feature Count: 10') != -1 ############################################################################### # Test layer name @@ -89,13 +78,10 @@ def test_ogrinfo_py_3(): def test_ogrinfo_py_4(): script_path = test_py_scripts.get_py_script('ogrinfo') if script_path is None: - return 'skip' + pytest.skip() ret = test_py_scripts.run_py_script(script_path, 'ogrinfo', '../ogr/data/poly.shp poly') - if ret.find('Feature Count: 10') == -1: - return 'fail' - - return 'success' + assert ret.find('Feature Count: 10') != -1 ############################################################################### # Test -sql option @@ -104,13 +90,10 @@ def test_ogrinfo_py_4(): def test_ogrinfo_py_5(): script_path = test_py_scripts.get_py_script('ogrinfo') if script_path is None: - return 'skip' + pytest.skip() ret = test_py_scripts.run_py_script(script_path, 'ogrinfo', '../ogr/data/poly.shp -sql "select * from poly"') - if ret.find('Feature Count: 10') == -1: - return 'fail' - - return 'success' + assert ret.find('Feature Count: 10') != -1 ############################################################################### # Test -geom=NO option @@ -119,15 +102,11 @@ def test_ogrinfo_py_5(): def test_ogrinfo_py_6(): script_path = test_py_scripts.get_py_script('ogrinfo') if script_path is None: - return 'skip' + pytest.skip() ret = test_py_scripts.run_py_script(script_path, 'ogrinfo', '../ogr/data/poly.shp poly -geom=no') - if ret.find('Feature Count: 10') == -1: - return 'fail' - if ret.find('POLYGON') != -1: - return 'fail' - - return 'success' + assert ret.find('Feature Count: 10') != -1 + assert ret.find('POLYGON') == -1 ############################################################################### # Test -geom=SUMMARY option @@ -136,17 +115,12 @@ def test_ogrinfo_py_6(): def test_ogrinfo_py_7(): script_path = test_py_scripts.get_py_script('ogrinfo') if script_path is None: - return 'skip' + pytest.skip() ret = test_py_scripts.run_py_script(script_path, 'ogrinfo', '../ogr/data/poly.shp poly -geom=summary') - if ret.find('Feature Count: 10') == -1: - return 'fail' - if ret.find('POLYGON (') != -1: - return 'fail' - if ret.find('POLYGON :') == -1: - return 'fail' - - return 'success' + assert ret.find('Feature Count: 10') != -1 + assert ret.find('POLYGON (') == -1 + assert ret.find('POLYGON :') != -1 ############################################################################### # Test -spat option @@ -155,17 +129,15 @@ def test_ogrinfo_py_7(): def test_ogrinfo_py_8(): script_path = test_py_scripts.get_py_script('ogrinfo') if script_path is None: - return 'skip' + pytest.skip() ret = test_py_scripts.run_py_script(script_path, 'ogrinfo', '../ogr/data/poly.shp poly -spat 479609 4764629 479764 4764817') if ogrtest.have_geos(): - if ret.find('Feature Count: 4') == -1: - return 'fail' - return 'success' + assert ret.find('Feature Count: 4') != -1 + return else: - if ret.find('Feature Count: 5') == -1: - return 'fail' - return 'success' + assert ret.find('Feature Count: 5') != -1 + return ############################################################################### # Test -where option @@ -174,13 +146,10 @@ def test_ogrinfo_py_8(): def test_ogrinfo_py_9(): script_path = test_py_scripts.get_py_script('ogrinfo') if script_path is None: - return 'skip' + pytest.skip() ret = test_py_scripts.run_py_script(script_path, 'ogrinfo', '../ogr/data/poly.shp poly -where "EAS_ID=171"') - if ret.find('Feature Count: 1') == -1: - return 'fail' - - return 'success' + assert ret.find('Feature Count: 1') != -1 ############################################################################### # Test -fid option @@ -189,13 +158,10 @@ def test_ogrinfo_py_9(): def test_ogrinfo_py_10(): script_path = test_py_scripts.get_py_script('ogrinfo') if script_path is None: - return 'skip' + pytest.skip() ret = test_py_scripts.run_py_script(script_path, 'ogrinfo', '../ogr/data/poly.shp poly -fid 9') - if ret.find('OGRFeature(poly):9') == -1: - return 'fail' - - return 'success' + assert ret.find('OGRFeature(poly):9') != -1 ############################################################################### # Test -fields=no option @@ -204,15 +170,11 @@ def test_ogrinfo_py_10(): def test_ogrinfo_py_11(): script_path = test_py_scripts.get_py_script('ogrinfo') if script_path is None: - return 'skip' + pytest.skip() ret = test_py_scripts.run_py_script(script_path, 'ogrinfo', '../ogr/data/poly.shp poly -fields=no') - if ret.find('AREA (Real') != -1: - return 'fail' - if ret.find('POLYGON (') == -1: - return 'fail' - - return 'success' + assert ret.find('AREA (Real') == -1 + assert ret.find('POLYGON (') != -1 ############################################################################### # Test RFC 41 support @@ -221,7 +183,7 @@ def test_ogrinfo_py_11(): def test_ogrinfo_py_22(): script_path = test_py_scripts.get_py_script('ogrinfo') if script_path is None: - return 'skip' + pytest.skip() f = open('tmp/test_ogrinfo_22.csv', 'wt') f.write('_WKTgeom1_EPSG_4326,_WKTgeom2_EPSG_32631\n') @@ -229,9 +191,7 @@ def test_ogrinfo_py_22(): f.close() ret = test_py_scripts.run_py_script(script_path, 'ogrinfo', 'tmp/test_ogrinfo_22.csv') - if ret.find('1: test_ogrinfo_22 (Unknown (any), Unknown (any))') < 0: - print(ret) - return 'fail' + assert ret.find('1: test_ogrinfo_22 (Unknown (any), Unknown (any))') >= 0 ret = test_py_scripts.run_py_script(script_path, 'ogrinfo', '-al tmp/test_ogrinfo_22.csv') expected_ret = """INFO: Open of `tmp/test_ogrinfo_22.csv' @@ -290,14 +250,10 @@ def test_ogrinfo_py_22(): expected_lines = expected_ret.splitlines() lines = ret.splitlines() for i, exp_line in enumerate(expected_lines): - if exp_line != lines[i]: - print(ret) - return 'fail' + assert exp_line == lines[i], ret os.unlink('tmp/test_ogrinfo_22.csv') - return 'success' - ############################################################################### # Test -geomfield (RFC 41) support @@ -305,7 +261,7 @@ def test_ogrinfo_py_22(): def test_ogrinfo_py_23(): script_path = test_py_scripts.get_py_script('ogrinfo') if script_path is None: - return 'skip' + pytest.skip() f = open('tmp/test_ogrinfo_23.csv', 'wt') f.write('_WKTgeom1_EPSG_4326,_WKTgeom2_EPSG_32631\n') @@ -370,36 +326,10 @@ def test_ogrinfo_py_23(): expected_lines = expected_ret.splitlines() lines = ret.splitlines() for i, exp_line in enumerate(expected_lines): - if exp_line != lines[i]: - print(ret) - return 'fail' + assert exp_line == lines[i], ret os.unlink('tmp/test_ogrinfo_23.csv') - return 'success' - - -gdaltest_list = [ - test_ogrinfo_py_1, - test_ogrinfo_py_2, - test_ogrinfo_py_3, - test_ogrinfo_py_4, - test_ogrinfo_py_5, - test_ogrinfo_py_6, - test_ogrinfo_py_7, - test_ogrinfo_py_8, - test_ogrinfo_py_9, - test_ogrinfo_py_10, - test_ogrinfo_py_11, - test_ogrinfo_py_22, - test_ogrinfo_py_23, -] - - -if __name__ == '__main__': - gdaltest.setup_run('test_ogrinfo_py') - gdaltest.run_tests(gdaltest_list) - sys.exit(gdaltest.summarize()) diff --git a/autotest/pyscripts/test_ogrmerge.py b/autotest/pyscripts/test_ogrmerge.py index 6b728af940b4..a3a24dda54db 100755 --- a/autotest/pyscripts/test_ogrmerge.py +++ b/autotest/pyscripts/test_ogrmerge.py @@ -28,14 +28,12 @@ # DEALINGS IN THE SOFTWARE. ############################################################################### -import sys -sys.path.append('../pymod') from osgeo import gdal from osgeo import ogr -import gdaltest import test_py_scripts +import pytest ############################################################################### # Test -single @@ -44,21 +42,17 @@ def test_ogrmerge_1(): script_path = test_py_scripts.get_py_script('ogrmerge') if script_path is None: - return 'skip' + pytest.skip() test_py_scripts.run_py_script(script_path, 'ogrmerge', - '-single -o /vsimem/out.shp ../ogr/data/poly.shp ../ogr/data/poly.shp') + '-single -o tmp/out.shp ../ogr/data/poly.shp ../ogr/data/poly.shp') - ds = ogr.Open('/vsimem/out.shp') + ds = ogr.Open('tmp/out.shp') lyr = ds.GetLayer(0) - if lyr.GetFeatureCount() != 20: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.GetFeatureCount() == 20 ds = None - ogr.GetDriverByName('ESRI Shapefile').DeleteDataSource('/vsimem/out.shp') - - return 'success' + ogr.GetDriverByName('ESRI Shapefile').DeleteDataSource('tmp/out.shp') ############################################################################### # Test -append and glob @@ -67,23 +61,19 @@ def test_ogrmerge_1(): def test_ogrmerge_2(): script_path = test_py_scripts.get_py_script('ogrmerge') if script_path is None: - return 'skip' + pytest.skip() test_py_scripts.run_py_script(script_path, 'ogrmerge', - '-single -o /vsimem/out.shp ../ogr/data/poly.shp') + '-single -o tmp/out.shp ../ogr/data/poly.shp') test_py_scripts.run_py_script(script_path, 'ogrmerge', - '-append -single -o /vsimem/out.shp "../ogr/data/p*ly.shp"') + '-append -single -o tmp/out.shp "../ogr/data/p*ly.shp"') - ds = ogr.Open('/vsimem/out.shp') + ds = ogr.Open('tmp/out.shp') lyr = ds.GetLayer(0) - if lyr.GetFeatureCount() != 20: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.GetFeatureCount() == 20 ds = None - ogr.GetDriverByName('ESRI Shapefile').DeleteDataSource('/vsimem/out.shp') - - return 'success' + ogr.GetDriverByName('ESRI Shapefile').DeleteDataSource('tmp/out.shp') ############################################################################### # Test -overwrite_ds @@ -92,23 +82,19 @@ def test_ogrmerge_2(): def test_ogrmerge_3(): script_path = test_py_scripts.get_py_script('ogrmerge') if script_path is None: - return 'skip' + pytest.skip() test_py_scripts.run_py_script(script_path, 'ogrmerge', - '-overwrite_ds -o /vsimem/out.shp ../ogr/data/poly.shp') + '-overwrite_ds -o tmp/out.shp ../ogr/data/poly.shp') test_py_scripts.run_py_script(script_path, 'ogrmerge', - '-overwrite_ds -single -o /vsimem/out.shp ../ogr/data/poly.shp') + '-overwrite_ds -single -o tmp/out.shp ../ogr/data/poly.shp') - ds = ogr.Open('/vsimem/out.shp') + ds = ogr.Open('tmp/out.shp') lyr = ds.GetLayer(0) - if lyr.GetFeatureCount() != 10: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.GetFeatureCount() == 10 ds = None - ogr.GetDriverByName('ESRI Shapefile').DeleteDataSource('/vsimem/out.shp') - - return 'success' + ogr.GetDriverByName('ESRI Shapefile').DeleteDataSource('tmp/out.shp') ############################################################################### # Test -f VRT @@ -117,24 +103,18 @@ def test_ogrmerge_3(): def test_ogrmerge_4(): script_path = test_py_scripts.get_py_script('ogrmerge') if script_path is None: - return 'skip' + pytest.skip() test_py_scripts.run_py_script(script_path, 'ogrmerge', - '-f VRT -o /vsimem/out.vrt ../ogr/data/poly.shp') + '-f VRT -o tmp/out.vrt ../ogr/data/poly.shp') - ds = ogr.Open('/vsimem/out.vrt') + ds = ogr.Open('tmp/out.vrt') lyr = ds.GetLayer(0) - if lyr.GetName() != 'poly': - gdaltest.post_reason('fail') - return 'fail' - if lyr.GetFeatureCount() != 10: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.GetName() == 'poly' + assert lyr.GetFeatureCount() == 10 ds = None - gdal.Unlink('/vsimem/out.vrt') - - return 'success' + gdal.Unlink('tmp/out.vrt') ############################################################################### # Test -nln @@ -143,34 +123,22 @@ def test_ogrmerge_4(): def test_ogrmerge_5(): script_path = test_py_scripts.get_py_script('ogrmerge') if script_path is None: - return 'skip' + pytest.skip() test_py_scripts.run_py_script(script_path, 'ogrmerge', - '-f VRT -o /vsimem/out.vrt ../ogr/data/poly.shp ../ogr/data/testpoly.shp -nln ' + '-f VRT -o tmp/out.vrt ../ogr/data/poly.shp ../ogr/data/testpoly.shp -nln ' '"foo_{DS_NAME}_{DS_BASENAME}_{DS_INDEX}_{LAYER_NAME}_{LAYER_INDEX}"') - ds = ogr.Open('/vsimem/out.vrt') + ds = ogr.Open('tmp/out.vrt') lyr = ds.GetLayer(0) - if lyr.GetName() != 'foo_../ogr/data/poly.shp_poly_0_poly_0': - gdaltest.post_reason('fail') - print(lyr.GetName()) - return 'fail' - if lyr.GetFeatureCount() != 10: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.GetName() == 'foo_../ogr/data/poly.shp_poly_0_poly_0' + assert lyr.GetFeatureCount() == 10 lyr = ds.GetLayer(1) - if lyr.GetName() != 'foo_../ogr/data/testpoly.shp_testpoly_1_testpoly_0': - gdaltest.post_reason('fail') - print(lyr.GetName()) - return 'fail' - if lyr.GetFeatureCount() != 14: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.GetName() == 'foo_../ogr/data/testpoly.shp_testpoly_1_testpoly_0' + assert lyr.GetFeatureCount() == 14 ds = None - gdal.Unlink('/vsimem/out.vrt') - - return 'success' + gdal.Unlink('tmp/out.vrt') ############################################################################### # Test -src_layer_field_name -src_layer_field_content @@ -179,25 +147,22 @@ def test_ogrmerge_5(): def test_ogrmerge_6(): script_path = test_py_scripts.get_py_script('ogrmerge') if script_path is None: - return 'skip' + pytest.skip() test_py_scripts.run_py_script(script_path, 'ogrmerge', - '-single -f VRT -o /vsimem/out.vrt ../ogr/data/poly.shp ' + '-single -f VRT -o tmp/out.vrt ../ogr/data/poly.shp ' '-src_layer_field_name source -src_layer_field_content ' '"foo_{DS_NAME}_{DS_BASENAME}_{DS_INDEX}_{LAYER_NAME}_{LAYER_INDEX}"') - ds = ogr.Open('/vsimem/out.vrt') + ds = ogr.Open('tmp/out.vrt') lyr = ds.GetLayer(0) f = lyr.GetNextFeature() if f['source'] != 'foo_../ogr/data/poly.shp_poly_0_poly_0': - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' + pytest.fail() ds = None - gdal.Unlink('/vsimem/out.vrt') - - return 'success' + gdal.Unlink('tmp/out.vrt') ############################################################################### # Test -src_geom_type @@ -206,61 +171,51 @@ def test_ogrmerge_6(): def test_ogrmerge_7(): script_path = test_py_scripts.get_py_script('ogrmerge') if script_path is None: - return 'skip' + pytest.skip() # No match in -single mode test_py_scripts.run_py_script(script_path, 'ogrmerge', - '-single -f VRT -o /vsimem/out.vrt ../ogr/data/poly.shp ' + '-single -f VRT -o tmp/out.vrt ../ogr/data/poly.shp ' '-src_geom_type POINT') - ds = ogr.Open('/vsimem/out.vrt') - if ds.GetLayerCount() != 0: - gdaltest.post_reason('fail') - return 'fail' + ds = ogr.Open('tmp/out.vrt') + assert ds.GetLayerCount() == 0 ds = None - gdal.Unlink('/vsimem/out.vrt') + gdal.Unlink('tmp/out.vrt') # Match in single mode test_py_scripts.run_py_script(script_path, 'ogrmerge', - '-single -f VRT -o /vsimem/out.vrt ../ogr/data/poly.shp ' + '-single -f VRT -o tmp/out.vrt ../ogr/data/poly.shp ' '-src_geom_type POLYGON') - ds = ogr.Open('/vsimem/out.vrt') - if ds.GetLayerCount() != 1: - gdaltest.post_reason('fail') - return 'fail' + ds = ogr.Open('tmp/out.vrt') + assert ds.GetLayerCount() == 1 ds = None - gdal.Unlink('/vsimem/out.vrt') + gdal.Unlink('tmp/out.vrt') # No match in default mode test_py_scripts.run_py_script(script_path, 'ogrmerge', - '-f VRT -o /vsimem/out.vrt ../ogr/data/poly.shp ' + '-f VRT -o tmp/out.vrt ../ogr/data/poly.shp ' '-src_geom_type POINT') - ds = ogr.Open('/vsimem/out.vrt') - if ds.GetLayerCount() != 0: - gdaltest.post_reason('fail') - return 'fail' + ds = ogr.Open('tmp/out.vrt') + assert ds.GetLayerCount() == 0 ds = None - gdal.Unlink('/vsimem/out.vrt') + gdal.Unlink('tmp/out.vrt') # Match in default mode test_py_scripts.run_py_script(script_path, 'ogrmerge', - '-f VRT -o /vsimem/out.vrt ../ogr/data/poly.shp ' + '-f VRT -o tmp/out.vrt ../ogr/data/poly.shp ' '-src_geom_type POLYGON') - ds = ogr.Open('/vsimem/out.vrt') - if ds.GetLayerCount() != 1: - gdaltest.post_reason('fail') - return 'fail' + ds = ogr.Open('tmp/out.vrt') + assert ds.GetLayerCount() == 1 ds = None - gdal.Unlink('/vsimem/out.vrt') - - return 'success' + gdal.Unlink('tmp/out.vrt') ############################################################################### # Test -s_srs -t_srs in -single mode @@ -269,36 +224,26 @@ def test_ogrmerge_7(): def test_ogrmerge_8(): script_path = test_py_scripts.get_py_script('ogrmerge') if script_path is None: - return 'skip' + pytest.skip() test_py_scripts.run_py_script(script_path, 'ogrmerge', - '-single -f VRT -o /vsimem/out.vrt ../ogr/data/poly.shp ' + '-single -f VRT -o tmp/out.vrt ../ogr/data/poly.shp ' '-s_srs EPSG:32630 -t_srs EPSG:4326') - ds = ogr.Open('/vsimem/out.vrt') - if ds is None: - gdaltest.post_reason('fail') - return 'fail' + ds = ogr.Open('tmp/out.vrt') + assert ds is not None ds = None - f = gdal.VSIFOpenL('/vsimem/out.vrt', 'rb') + f = gdal.VSIFOpenL('tmp/out.vrt', 'rb') content = '' if f is not None: content = gdal.VSIFReadL(1, 10000, f).decode('UTF-8') gdal.VSIFCloseL(f) - gdal.Unlink('/vsimem/out.vrt') - - if content.find('<SrcSRS>EPSG:32630</SrcSRS>') < 0: - gdaltest.post_reason('fail') - print(content) - return 'fail' + gdal.Unlink('tmp/out.vrt') - if content.find('<TargetSRS>EPSG:4326</TargetSRS>') < 0: - gdaltest.post_reason('fail') - print(content) - return 'fail' + assert content.find('<SrcSRS>EPSG:32630</SrcSRS>') >= 0 - return 'success' + assert content.find('<TargetSRS>EPSG:4326</TargetSRS>') >= 0 ############################################################################### # Test -s_srs -t_srs in default mode @@ -307,36 +252,26 @@ def test_ogrmerge_8(): def test_ogrmerge_9(): script_path = test_py_scripts.get_py_script('ogrmerge') if script_path is None: - return 'skip' + pytest.skip() test_py_scripts.run_py_script(script_path, 'ogrmerge', - '-f VRT -o /vsimem/out.vrt ../ogr/data/poly.shp ' + '-f VRT -o tmp/out.vrt ../ogr/data/poly.shp ' '-s_srs EPSG:32630 -t_srs EPSG:4326') - ds = ogr.Open('/vsimem/out.vrt') - if ds is None: - gdaltest.post_reason('fail') - return 'fail' + ds = ogr.Open('tmp/out.vrt') + assert ds is not None ds = None - f = gdal.VSIFOpenL('/vsimem/out.vrt', 'rb') + f = gdal.VSIFOpenL('tmp/out.vrt', 'rb') content = '' if f is not None: content = gdal.VSIFReadL(1, 10000, f).decode('UTF-8') gdal.VSIFCloseL(f) - gdal.Unlink('/vsimem/out.vrt') + gdal.Unlink('tmp/out.vrt') - if content.find('<SrcSRS>EPSG:32630</SrcSRS>') < 0: - gdaltest.post_reason('fail') - print(content) - return 'fail' + assert content.find('<SrcSRS>EPSG:32630</SrcSRS>') >= 0 - if content.find('<TargetSRS>EPSG:4326</TargetSRS>') < 0: - gdaltest.post_reason('fail') - print(content) - return 'fail' - - return 'success' + assert content.find('<TargetSRS>EPSG:4326</TargetSRS>') >= 0 ############################################################################### # Test -a_srs in -single mode @@ -345,31 +280,24 @@ def test_ogrmerge_9(): def test_ogrmerge_10(): script_path = test_py_scripts.get_py_script('ogrmerge') if script_path is None: - return 'skip' + pytest.skip() test_py_scripts.run_py_script(script_path, 'ogrmerge', - '-single -f VRT -o /vsimem/out.vrt ../ogr/data/poly.shp ' + '-single -f VRT -o tmp/out.vrt ../ogr/data/poly.shp ' '-a_srs EPSG:32630') - ds = ogr.Open('/vsimem/out.vrt') - if ds is None: - gdaltest.post_reason('fail') - return 'fail' + ds = ogr.Open('tmp/out.vrt') + assert ds is not None ds = None - f = gdal.VSIFOpenL('/vsimem/out.vrt', 'rb') + f = gdal.VSIFOpenL('tmp/out.vrt', 'rb') content = '' if f is not None: content = gdal.VSIFReadL(1, 10000, f).decode('UTF-8') gdal.VSIFCloseL(f) - gdal.Unlink('/vsimem/out.vrt') - - if content.find('<LayerSRS>EPSG:32630</LayerSRS>') < 0: - gdaltest.post_reason('fail') - print(content) - return 'fail' + gdal.Unlink('tmp/out.vrt') - return 'success' + assert content.find('<LayerSRS>EPSG:32630</LayerSRS>') >= 0 ############################################################################### # Test -a_srs in default mode @@ -378,31 +306,24 @@ def test_ogrmerge_10(): def test_ogrmerge_11(): script_path = test_py_scripts.get_py_script('ogrmerge') if script_path is None: - return 'skip' + pytest.skip() test_py_scripts.run_py_script(script_path, 'ogrmerge', - '-f VRT -o /vsimem/out.vrt ../ogr/data/poly.shp ' + '-f VRT -o tmp/out.vrt ../ogr/data/poly.shp ' '-a_srs EPSG:32630') - ds = ogr.Open('/vsimem/out.vrt') - if ds is None: - gdaltest.post_reason('fail') - return 'fail' + ds = ogr.Open('tmp/out.vrt') + assert ds is not None ds = None - f = gdal.VSIFOpenL('/vsimem/out.vrt', 'rb') + f = gdal.VSIFOpenL('tmp/out.vrt', 'rb') content = '' if f is not None: content = gdal.VSIFReadL(1, 10000, f).decode('UTF-8') gdal.VSIFCloseL(f) - gdal.Unlink('/vsimem/out.vrt') + gdal.Unlink('tmp/out.vrt') - if content.find('<LayerSRS>EPSG:32630</LayerSRS>') < 0: - gdaltest.post_reason('fail') - print(content) - return 'fail' - - return 'success' + assert content.find('<LayerSRS>EPSG:32630</LayerSRS>') >= 0 ############################################################################### # Test layer names with accents @@ -411,46 +332,21 @@ def test_ogrmerge_11(): def test_ogrmerge_12(): script_path = test_py_scripts.get_py_script('ogrmerge') if script_path is None: - return 'skip' + pytest.skip() with open('tmp/tmp.json', 'wt') as f: f.write("""{ "type": "FeatureCollection", "name": "\xc3\xa9ven", "features": [ { "type": "Feature", "properties": {}, "geometry": null} ]}""") test_py_scripts.run_py_script(script_path, 'ogrmerge', - '-f VRT -o /vsimem/out.vrt tmp/tmp.json') + '-f VRT -o tmp/out.vrt tmp/tmp.json') - ds = ogr.Open('/vsimem/out.vrt') - if ds is None: - gdaltest.post_reason('fail') - return 'fail' + ds = ogr.Open('tmp/out.vrt') + assert ds is not None ds = None gdal.Unlink('tmp/tmp.json') - gdal.Unlink('/vsimem/out.vrt') - - return 'success' - - -gdaltest_list = [ - test_ogrmerge_1, - test_ogrmerge_2, - test_ogrmerge_3, - test_ogrmerge_4, - test_ogrmerge_5, - test_ogrmerge_6, - test_ogrmerge_7, - test_ogrmerge_8, - test_ogrmerge_9, - test_ogrmerge_10, - test_ogrmerge_11, - test_ogrmerge_12 -] - + gdal.Unlink('tmp/out.vrt') -if __name__ == '__main__': - gdaltest.setup_run('test_ogrmerge') - gdaltest.run_tests(gdaltest_list) - sys.exit(gdaltest.summarize()) diff --git a/autotest/pyscripts/test_rgb2pct.py b/autotest/pyscripts/test_rgb2pct.py index 270aad56d194..780825e6ac18 100755 --- a/autotest/pyscripts/test_rgb2pct.py +++ b/autotest/pyscripts/test_rgb2pct.py @@ -29,15 +29,14 @@ ############################################################################### -import sys import os import struct -sys.path.append('../pymod') from osgeo import gdal import gdaltest import test_py_scripts +import pytest ############################################################################### # Test rgb2pct @@ -47,18 +46,14 @@ def test_rgb2pct_1(): script_path = test_py_scripts.get_py_script('rgb2pct') if script_path is None: - return 'skip' + pytest.skip() test_py_scripts.run_py_script(script_path, 'rgb2pct', '../gcore/data/rgbsmall.tif tmp/test_rgb2pct_1.tif') ds = gdal.Open('tmp/test_rgb2pct_1.tif') - if ds.GetRasterBand(1).Checksum() != 31231: - print(ds.GetRasterBand(1).Checksum()) - return 'fail' + assert ds.GetRasterBand(1).Checksum() == 31231 ds = None - return 'success' - ############################################################################### # Test pct2rgb @@ -68,29 +63,24 @@ def test_pct2rgb_1(): from osgeo import gdalnumeric gdalnumeric.BandRasterIONumPy except: - return 'skip' + pytest.skip() script_path = test_py_scripts.get_py_script('pct2rgb') if script_path is None: - return 'skip' + pytest.skip() test_py_scripts.run_py_script(script_path, 'pct2rgb', 'tmp/test_rgb2pct_1.tif tmp/test_pct2rgb_1.tif') ds = gdal.Open('tmp/test_pct2rgb_1.tif') - if ds.GetRasterBand(1).Checksum() != 20963: - print(ds.GetRasterBand(1).Checksum()) - return 'fail' + assert ds.GetRasterBand(1).Checksum() == 20963 ori_ds = gdal.Open('../gcore/data/rgbsmall.tif') max_diff = gdaltest.compare_ds(ori_ds, ds) - if max_diff > 18: - return 'fail' + assert max_diff <= 18 ds = None ori_ds = None - return 'success' - ############################################################################### # Test rgb2pct -n option @@ -99,26 +89,21 @@ def test_rgb2pct_2(): script_path = test_py_scripts.get_py_script('rgb2pct') if script_path is None: - return 'skip' + pytest.skip() test_py_scripts.run_py_script(script_path, 'rgb2pct', '-n 16 ../gcore/data/rgbsmall.tif tmp/test_rgb2pct_2.tif') ds = gdal.Open('tmp/test_rgb2pct_2.tif') - if ds.GetRasterBand(1).Checksum() != 16596: - print(ds.GetRasterBand(1).Checksum()) - return 'fail' + assert ds.GetRasterBand(1).Checksum() == 16596 ct = ds.GetRasterBand(1).GetRasterColorTable() for i in range(16, 255): entry = ct.GetColorEntry(i) - if not (entry[0] == 0 and entry[1] == 0 and entry[2] == 0): - gdaltest.post_reason('Color table has more than 16 entries') - return 'fail' + assert (entry[0] == 0 and entry[1] == 0 and entry[2] == 0), \ + 'Color table has more than 16 entries' ds = None - return 'success' - ############################################################################### # Test rgb2pct -pct option @@ -127,26 +112,21 @@ def test_rgb2pct_3(): script_path = test_py_scripts.get_py_script('rgb2pct') if script_path is None: - return 'skip' + pytest.skip() test_py_scripts.run_py_script(script_path, 'rgb2pct', '-pct tmp/test_rgb2pct_2.tif ../gcore/data/rgbsmall.tif tmp/test_rgb2pct_3.tif') ds = gdal.Open('tmp/test_rgb2pct_3.tif') - if ds.GetRasterBand(1).Checksum() != 16596: - print(ds.GetRasterBand(1).Checksum()) - return 'fail' + assert ds.GetRasterBand(1).Checksum() == 16596 ct = ds.GetRasterBand(1).GetRasterColorTable() for i in range(16, 255): entry = ct.GetColorEntry(i) - if not (entry[0] == 0 and entry[1] == 0 and entry[2] == 0): - gdaltest.post_reason('Color table has more than 16 entries') - return 'fail' + assert (entry[0] == 0 and entry[1] == 0 and entry[2] == 0), \ + 'Color table has more than 16 entries' ds = None - return 'success' - ############################################################################### # Test pct2rgb with big CT (>256 entries) @@ -156,11 +136,11 @@ def test_pct2rgb_4(): from osgeo import gdalnumeric gdalnumeric.BandRasterIONumPy except (ImportError, AttributeError): - return 'skip' + pytest.skip() script_path = test_py_scripts.get_py_script('pct2rgb') if script_path is None: - return 'skip' + pytest.skip() test_py_scripts.run_py_script(script_path, 'pct2rgb', '-rgba ../gcore/data/rat.img tmp/test_pct2rgb_4.tif') @@ -176,14 +156,11 @@ def test_pct2rgb_4(): ct = ori_ds.GetRasterBand(1).GetRasterColorTable() entry = ct.GetColorEntry(ori_data) - if entry != data: - return 'fail' + assert entry == data ds = None ori_ds = None - return 'success' - ############################################################################### # Cleanup @@ -202,23 +179,7 @@ def test_rgb2pct_cleanup(): except OSError: pass - return 'success' - - -gdaltest_list = [ - test_rgb2pct_1, - test_pct2rgb_1, - test_rgb2pct_2, - test_rgb2pct_3, - test_pct2rgb_4, - test_rgb2pct_cleanup -] - - -if __name__ == '__main__': + - gdaltest.setup_run('test_rgb2pct') - gdaltest.run_tests(gdaltest_list) - sys.exit(gdaltest.summarize()) diff --git a/autotest/pytest.ini b/autotest/pytest.ini new file mode 100644 index 000000000000..68ff57b77059 --- /dev/null +++ b/autotest/pytest.ini @@ -0,0 +1,6 @@ +[pytest] +python_files = *.py +testpaths = ogr gcore gdrivers osr alg gnm utilities pyscripts + +markers = + require_driver: Skip test(s) if driver isn't present diff --git a/autotest/requirements.txt b/autotest/requirements.txt new file mode 100644 index 000000000000..fdfaccb5fd14 --- /dev/null +++ b/autotest/requirements.txt @@ -0,0 +1,2 @@ +pytest>=3 +pytest-sugar diff --git a/autotest/run_all.py b/autotest/run_all.py deleted file mode 100755 index 3e3c8d8afe36..000000000000 --- a/autotest/run_all.py +++ /dev/null @@ -1,76 +0,0 @@ -#!/usr/bin/env python -############################################################################### -# $Id$ -# -# Project: GDAL/OGR Test Suite -# Purpose: High level test executive ... it runs sub test scripts. -# Author: Frank Warmerdam <warmerdam@pobox.com> -# -############################################################################### -# Copyright (c) 2003, Frank Warmerdam <warmerdam@pobox.com> -# -# This library is free software; you can redistribute it and/or -# modify it under the terms of the GNU Library General Public -# License as published by the Free Software Foundation; either -# version 2 of the License, or (at your option) any later version. -# -# This library is distributed in the hope that it will be useful, -# but WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -# Library General Public License for more details. -# -# You should have received a copy of the GNU Library General Public -# License along with this library; if not, write to the -# Free Software Foundation, Inc., 59 Temple Place - Suite 330, -# Boston, MA 02111-1307, USA. -############################################################################### - -import sys -import os - -# Make sure we run from the directory of the script -if os.path.basename(sys.argv[0]) == os.path.basename(__file__): - if os.path.dirname(sys.argv[0]) != '': - os.chdir(os.path.dirname(sys.argv[0])) - -sys.path.append('pymod') -import gdaltest -from osgeo import gdal - -all_test_list = ['ogr', 'gcore', 'gdrivers', 'osr', 'alg', 'gnm', 'utilities', 'pyscripts'] - -run_as_external = False - -test_list = [] - -for arg in gdaltest.argv[1:]: - if arg == '-l': - print('List of GDAL Autotest modules') - for test in all_test_list: - print('* ' + test) - sys.exit(0) - elif arg == '-run_as_external': - run_as_external = True - elif arg == '-h' or arg[0] == '-': - print('Usage: ' + sys.argv[0] + ' [OPTION]') - print('\t<tests> - list of test modules to run, run all if none specified') - print('\t-l - list available test modules') - print('\t-h - print this usage message') - print('\t-run_as_external - run each test script in a dedicated Python instance') - sys.exit(0) - else: - test_list.append(arg) - -if not test_list: - test_list = all_test_list - -# we set ECW to not resolve projection and datum strings to get 3.x behavior. -gdal.SetConfigOption("ECW_DO_NOT_RESOLVE_DATUM_PROJECTION", "YES") - -gdaltest.setup_run('gdalautotest_all') - -gdaltest.run_all(test_list, run_as_external=run_as_external) - -errors = gdaltest.summarize() - -sys.exit(errors) diff --git a/autotest/utilities/__init__.py b/autotest/utilities/__init__.py new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/autotest/utilities/test_gdal_contour.py b/autotest/utilities/test_gdal_contour.py index 1433e40c132e..de00f78bf167 100755 --- a/autotest/utilities/test_gdal_contour.py +++ b/autotest/utilities/test_gdal_contour.py @@ -29,11 +29,9 @@ # DEALINGS IN THE SOFTWARE. ############################################################################### -import sys import os import array -sys.path.append('../pymod') from osgeo import gdal from osgeo import ogr @@ -41,6 +39,7 @@ import gdaltest import ogrtest import test_cli_utilities +import pytest ############################################################################### # Test with -a and -i options @@ -48,7 +47,7 @@ def test_gdal_contour_1(): if test_cli_utilities.get_gdal_contour_path() is None: - return 'skip' + pytest.skip() try: os.remove('tmp/contour.shp') @@ -96,10 +95,7 @@ def test_gdal_contour_1(): ds = None (_, err) = gdaltest.runexternal_out_and_err(test_cli_utilities.get_gdal_contour_path() + ' -a elev -i 10 tmp/gdal_contour.tif tmp/contour.shp') - if not (err is None or err == ''): - gdaltest.post_reason('got error/warning') - print(err) - return 'fail' + assert (err is None or err == ''), 'got error/warning' ds = ogr.Open('tmp/contour.shp') @@ -109,45 +105,33 @@ def test_gdal_contour_1(): lyr = ds.ExecuteSQL("select * from contour order by elev asc") - if lyr.GetSpatialRef().ExportToWkt() != wkt: - print('Did not get expected spatial ref') - print(lyr.GetSpatialRef().ExportToWkt()) - print(wkt) - return 'fail' + assert lyr.GetSpatialRef().ExportToWkt() == wkt, 'Did not get expected spatial ref' - 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() ds.ReleaseResultSet(lyr) ds.Destroy() - return 'success' - ############################################################################### # Test with -fl option and -3d option def test_gdal_contour_2(): if test_cli_utilities.get_gdal_contour_path() is None: - return 'skip' + pytest.skip() try: os.remove('tmp/contour.shp') @@ -177,42 +161,32 @@ def test_gdal_contour_2(): lyr = 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() ds.ReleaseResultSet(lyr) ds.Destroy() - return 'success' - ############################################################################### # Test on a real DEM def test_gdal_contour_3(): if test_cli_utilities.get_gdal_contour_path() is None: - return 'skip' + pytest.skip() try: os.remove('tmp/contour.shp') @@ -235,30 +209,25 @@ def test_gdal_contour_3(): lyr = ds.ExecuteSQL("select distinct elev from contour order by elev asc") expected_heights = [100, 150, 200, 250, 300, 350, 400, 450] - if lyr.GetFeatureCount() != len(expected_heights): - print('Got %d features. Expected %d' % (lyr.GetFeatureCount(), len(expected_heights))) - return 'fail' + assert lyr.GetFeatureCount() == len(expected_heights) i = 0 feat = lyr.GetNextFeature() while feat is not None: - if feat.GetField('elev') != expected_heights[i]: - return 'fail' + assert feat.GetField('elev') == expected_heights[i] i = i + 1 feat = lyr.GetNextFeature() ds.ReleaseResultSet(lyr) ds.Destroy() - return 'success' - ############################################################################### # Test contour orientation def test_gdal_contour_4(): if test_cli_utilities.get_gdal_contour_path() is None: - return 'skip' + pytest.skip() try: os.remove('tmp/contour_orientation.shp') @@ -334,18 +303,14 @@ def test_gdal_contour_4(): lyr = ds.ExecuteSQL("select * from contour_orientation1 order by elev asc") - if lyr.GetFeatureCount() != len(expected_contours): - print('Got %d features. Expected %d' % (lyr.GetFeatureCount(), len(expected_contours))) - return 'fail' + assert lyr.GetFeatureCount() == len(expected_contours) i = 0 test_failed = False feat = lyr.GetNextFeature() while feat is not None: expected_geom = ogr.CreateGeometryFromWkt(expected_contours[i]) - if feat.GetField('elev') != expected_elev[i]: - print('Got %f. Expected %f' % (feat.GetField('elev'), expected_elev[i])) - return 'fail' + assert feat.GetField('elev') == expected_elev[i] if ogrtest.check_feature_geometry(feat, expected_geom, 0.01) != 0: print('Got %s.\nExpected %s' % (feat.GetGeometryRef().ExportToWkt(), expected_contours[i])) test_failed = True @@ -355,7 +320,7 @@ def test_gdal_contour_4(): ds.ReleaseResultSet(lyr) ds.Destroy() - return 'fail' if test_failed else 'success' + assert not test_failed ############################################################################### # Test contour orientation @@ -363,7 +328,7 @@ def test_gdal_contour_4(): def test_gdal_contour_5(): if test_cli_utilities.get_gdal_contour_path() is None: - return 'skip' + pytest.skip() ds = None @@ -383,18 +348,14 @@ def test_gdal_contour_5(): lyr = ds.ExecuteSQL("select * from contour_orientation2 order by elev asc") - if lyr.GetFeatureCount() != len(expected_contours): - print('Got %d features. Expected %d' % (lyr.GetFeatureCount(), len(expected_contours))) - return 'fail' + assert lyr.GetFeatureCount() == len(expected_contours) i = 0 test_failed = False feat = lyr.GetNextFeature() while feat is not None: expected_geom = ogr.CreateGeometryFromWkt(expected_contours[i]) - if feat.GetField('elev') != expected_elev[i]: - print('Got %f. Expected %f' % (feat.GetField('elev'), expected_elev[i])) - return 'fail' + assert feat.GetField('elev') == expected_elev[i] if ogrtest.check_feature_geometry(feat, expected_geom) != 0: print('Got %s.\nExpected %s' % (feat.GetGeometryRef().ExportToWkt(), expected_contours[i])) test_failed = True @@ -404,7 +365,7 @@ def test_gdal_contour_5(): ds.ReleaseResultSet(lyr) ds.Destroy() - return 'fail' if test_failed else 'success' + assert not test_failed ############################################################################### # Cleanup @@ -412,7 +373,7 @@ def test_gdal_contour_5(): def test_gdal_contour_cleanup(): if test_cli_utilities.get_gdal_contour_path() is None: - return 'skip' + pytest.skip() ogr.GetDriverByName('ESRI Shapefile').DeleteDataSource('tmp/contour.shp') ogr.GetDriverByName('ESRI Shapefile').DeleteDataSource('tmp/contour_orientation1.shp') @@ -423,23 +384,7 @@ def test_gdal_contour_cleanup(): except OSError: pass - return 'success' - - -gdaltest_list = [ - test_gdal_contour_1, - test_gdal_contour_2, - test_gdal_contour_3, - test_gdal_contour_4, - test_gdal_contour_5, - test_gdal_contour_cleanup -] - - -if __name__ == '__main__': + - gdaltest.setup_run('test_gdal_contour') - gdaltest.run_tests(gdaltest_list) - sys.exit(gdaltest.summarize()) diff --git a/autotest/utilities/test_gdal_grid.py b/autotest/utilities/test_gdal_grid.py index df09f584749b..40a72ed59818 100755 --- a/autotest/utilities/test_gdal_grid.py +++ b/autotest/utilities/test_gdal_grid.py @@ -32,8 +32,8 @@ import sys import os import struct +import pytest -sys.path.append('../pymod') sys.path.append('../gcore') from osgeo import gdal @@ -56,7 +56,7 @@ def test_gdal_grid_1(): if gdal_grid is None: - return 'skip' + pytest.skip() shape_drv = ogr.GetDriverByName('ESRI Shapefile') outfiles.append('tmp/n43.tif') @@ -105,32 +105,24 @@ def test_gdal_grid_1(): # Create a GDAL dataset from the previous generated OGR grid (_, err) = gdaltest.runexternal_out_and_err(gdal_grid + ' -txe -80.0041667 -78.9958333 -tye 42.9958333 44.0041667 -outsize 121 121 -ot Int16 -a nearest:radius1=0.0:radius2=0.0:angle=0.0 -co TILED=YES -co BLOCKXSIZE=256 -co BLOCKYSIZE=256 tmp/n43.shp ' + outfiles[-1]) - if not (err is None or err == ''): - gdaltest.post_reason('got error/warning') - print(err) - return 'fail' + assert (err is None or err == ''), 'got error/warning' # We should get the same values as in n43.td0 ds2 = gdal.Open(outfiles[-1]) - if ds.GetRasterBand(1).Checksum() != ds2.GetRasterBand(1).Checksum(): - print('bad checksum : got %d, expected %d' % (ds.GetRasterBand(1).Checksum(), ds2.GetRasterBand(1).Checksum())) - return 'fail' - if ds2.GetRasterBand(1).GetNoDataValue() is not None: - print('did not expect nodata value') - return 'fail' + assert ds.GetRasterBand(1).Checksum() == ds2.GetRasterBand(1).Checksum(), \ + ('bad checksum : got %d, expected %d' % (ds.GetRasterBand(1).Checksum(), ds2.GetRasterBand(1).Checksum())) + assert ds2.GetRasterBand(1).GetNoDataValue() is None, 'did not expect nodata value' ds = None ds2 = None - return 'success' - ############################################################################### # Test Nearest Neighbour gridding algorithm def test_gdal_grid_2(): if gdal_grid is None: - return 'skip' + pytest.skip() # Open reference dataset ds_ref = gdal.Open('../gcore/data/byte.tif') @@ -151,13 +143,10 @@ def test_gdal_grid_2(): # We should get the same values as in "gcore/data/byte.tif" ds = gdal.Open(outfiles[-1]) if ds.GetRasterBand(1).Checksum() != checksum_ref: - gdaltest.post_reason('bad checksum') print('bad checksum : got %d, expected %d' % (ds.GetRasterBand(1).Checksum(), checksum_ref)) - return 'fail' - if ds.GetRasterBand(1).GetNoDataValue() != 0.0: - print('expected a nodata value') - return 'fail' + pytest.fail('bad checksum') + assert ds.GetRasterBand(1).GetNoDataValue() == 0.0, 'expected a nodata value' ds = None ################# @@ -174,10 +163,9 @@ def test_gdal_grid_2(): # We should get the same values as in "gcore/data/byte.tif" ds = gdal.Open(outfiles[-1]) if ds.GetRasterBand(1).Checksum() != checksum_ref: - gdaltest.post_reason('bad checksum') print('bad checksum : got %d, expected %d' % (ds.GetRasterBand(1).Checksum(), checksum_ref)) - return 'fail' + pytest.fail('bad checksum') ds = None ################# @@ -193,10 +181,9 @@ def test_gdal_grid_2(): # We should get the same values as in "gcore/data/byte.tif" ds = gdal.Open(outfiles[-1]) if ds.GetRasterBand(1).Checksum() != checksum_ref: - gdaltest.post_reason('bad checksum') print('bad checksum : got %d, expected %d' % (ds.GetRasterBand(1).Checksum(), checksum_ref)) - return 'fail' + pytest.fail('bad checksum') ds = None ################# @@ -212,10 +199,9 @@ def test_gdal_grid_2(): # We should get the same values as in "gcore/data/byte.tif" ds = gdal.Open(outfiles[-1]) if ds.GetRasterBand(1).Checksum() != checksum_ref: - gdaltest.post_reason('bad checksum') print('bad checksum : got %d, expected %d' % (ds.GetRasterBand(1).Checksum(), checksum_ref)) - return 'fail' + pytest.fail('bad checksum') ds = None ################# @@ -231,10 +217,9 @@ def test_gdal_grid_2(): # We should get the same values as in "gcore/data/byte.tif" ds = gdal.Open(outfiles[-1]) if ds.GetRasterBand(1).Checksum() != checksum_ref: - gdaltest.post_reason('bad checksum') print('bad checksum : got %d, expected %d' % (ds.GetRasterBand(1).Checksum(), checksum_ref)) - return 'fail' + pytest.fail('bad checksum') ds = None ################# @@ -250,21 +235,18 @@ def test_gdal_grid_2(): # We should get the same values as in "gcore/data/byte.tif" ds = gdal.Open(outfiles[-1]) if ds.GetRasterBand(1).Checksum() != checksum_ref: - gdaltest.post_reason('bad checksum') print('bad checksum : got %d, expected %d' % (ds.GetRasterBand(1).Checksum(), checksum_ref)) - return 'fail' + pytest.fail('bad checksum') ds = None - return 'success' - ############################################################################### # Test Inverse Distance to a Power gridding algorithm def test_gdal_grid_3(): if gdal_grid is None: - return 'skip' + pytest.skip() ################# # Test generic implementation (no AVX, no SSE) @@ -289,8 +271,7 @@ def test_gdal_grid_3(): maxdiff = gdaltest.compare_ds(ds, ds_ref, verbose=0) if maxdiff > 1: gdaltest.compare_ds(ds, ds_ref, verbose=1) - gdaltest.post_reason('Image too different from the reference') - return 'fail' + pytest.fail('Image too different from the reference') ds_ref = None ds = None @@ -317,8 +298,7 @@ def test_gdal_grid_3(): maxdiff = gdaltest.compare_ds(ds, ds_ref, verbose=0) if maxdiff > 1: gdaltest.compare_ds(ds, ds_ref, verbose=1) - gdaltest.post_reason('Image too different from the reference') - return 'fail' + pytest.fail('Image too different from the reference') ds_ref = None ds = None @@ -345,8 +325,7 @@ def test_gdal_grid_3(): maxdiff = gdaltest.compare_ds(ds, ds_ref, verbose=0) if maxdiff > 1: gdaltest.compare_ds(ds, ds_ref, verbose=1) - gdaltest.post_reason('Image too different from the reference') - return 'fail' + pytest.fail('Image too different from the reference') ds_ref = None ds = None @@ -368,8 +347,7 @@ def test_gdal_grid_3(): maxdiff = gdaltest.compare_ds(ds, ds_ref, verbose=0) if maxdiff > 1: gdaltest.compare_ds(ds, ds_ref, verbose=1) - gdaltest.post_reason('Image too different from the reference') - return 'fail' + pytest.fail('Image too different from the reference') ds_ref = None ds = None @@ -391,8 +369,7 @@ def test_gdal_grid_3(): maxdiff = gdaltest.compare_ds(ds, ds_ref, verbose=0) if maxdiff > 1: gdaltest.compare_ds(ds, ds_ref, verbose=1) - gdaltest.post_reason('Image too different from the reference') - return 'fail' + pytest.fail('Image too different from the reference') ds_ref = None ds = None @@ -413,20 +390,17 @@ def test_gdal_grid_3(): maxdiff = gdaltest.compare_ds(ds, ds_ref, verbose=0) if maxdiff > 1: gdaltest.compare_ds(ds, ds_ref, verbose=1) - gdaltest.post_reason('Image too different from the reference') - return 'fail' + pytest.fail('Image too different from the reference') ds_ref = None ds = None - return 'success' - ############################################################################### # Test Moving Average gridding algorithm def test_gdal_grid_4(): if gdal_grid is None: - return 'skip' + pytest.skip() ################# outfiles.append('tmp/grid_average.tif') @@ -447,8 +421,7 @@ def test_gdal_grid_4(): ds_ref = None if maxdiff > 1: gdaltest.compare_ds(ds, ds_ref, verbose=1) - gdaltest.post_reason('Image too different from the reference') - return 'fail' + pytest.fail('Image too different from the reference') ds = None ################# @@ -469,8 +442,7 @@ def test_gdal_grid_4(): ds_ref = None if maxdiff > 1: gdaltest.compare_ds(ds, ds_ref, verbose=1) - gdaltest.post_reason('Image too different from the reference') - return 'fail' + pytest.fail('Image too different from the reference') ds = None ################# @@ -491,8 +463,7 @@ def test_gdal_grid_4(): ds_ref = None if maxdiff > 1: gdaltest.compare_ds(ds, ds_ref, verbose=1) - gdaltest.post_reason('Image too different from the reference') - return 'fail' + pytest.fail('Image too different from the reference') ds = None ################# @@ -513,19 +484,16 @@ def test_gdal_grid_4(): ds_ref = None if maxdiff > 1: gdaltest.compare_ds(ds, ds_ref, verbose=1) - gdaltest.post_reason('Image too different from the reference') - return 'fail' + pytest.fail('Image too different from the reference') ds = None - return 'success' - ############################################################################### # Test Minimum data metric def test_gdal_grid_5(): if gdal_grid is None: - return 'skip' + pytest.skip() ################# outfiles.append('tmp/grid_minimum.tif') @@ -541,10 +509,9 @@ def test_gdal_grid_5(): # We should get the same values as in "ref_data/grid_minimum.tif" ds = gdal.Open(outfiles[-1]) ds_ref = gdal.Open('ref_data/grid_minimum.tif') - if ds.GetRasterBand(1).Checksum() != ds_ref.GetRasterBand(1).Checksum(): - print('bad checksum : got %d, expected %d' % + assert ds.GetRasterBand(1).Checksum() == ds_ref.GetRasterBand(1).Checksum(), \ + ('bad checksum : got %d, expected %d' % (ds.GetRasterBand(1).Checksum(), ds_ref.GetRasterBand(1).checksum_ref)) - return 'fail' ds_ref = None ds = None @@ -562,22 +529,19 @@ def test_gdal_grid_5(): # We should get the same values as in "ref_data/grid_minimum_400_100_120.tif" ds = gdal.Open(outfiles[-1]) ds_ref = gdal.Open('ref_data/grid_minimum_400_100_120.tif') - if ds.GetRasterBand(1).Checksum() != ds_ref.GetRasterBand(1).Checksum(): - print('bad checksum : got %d, expected %d' % + assert ds.GetRasterBand(1).Checksum() == ds_ref.GetRasterBand(1).Checksum(), \ + ('bad checksum : got %d, expected %d' % (ds.GetRasterBand(1).Checksum(), ds_ref.GetRasterBand(1).checksum_ref)) - return 'fail' ds_ref = None ds = None - return 'success' - ############################################################################### # Test Maximum data metric def test_gdal_grid_6(): if gdal_grid is None: - return 'skip' + pytest.skip() ################# outfiles.append('tmp/grid_maximum.tif') @@ -593,10 +557,9 @@ def test_gdal_grid_6(): # We should get the same values as in "ref_data/grid_maximum.tif" ds = gdal.Open(outfiles[-1]) ds_ref = gdal.Open('ref_data/grid_maximum.tif') - if ds.GetRasterBand(1).Checksum() != ds_ref.GetRasterBand(1).Checksum(): - print('bad checksum : got %d, expected %d' % + assert ds.GetRasterBand(1).Checksum() == ds_ref.GetRasterBand(1).Checksum(), \ + ('bad checksum : got %d, expected %d' % (ds.GetRasterBand(1).Checksum(), ds_ref.GetRasterBand(1).checksum_ref)) - return 'fail' ds_ref = None ds = None @@ -614,22 +577,19 @@ def test_gdal_grid_6(): # We should get the same values as in "ref_data/grid_maximum_100_100.tif" ds = gdal.Open(outfiles[-1]) ds_ref = gdal.Open('ref_data/grid_maximum_100_100.tif') - if ds.GetRasterBand(1).Checksum() != ds_ref.GetRasterBand(1).Checksum(): - print('bad checksum : got %d, expected %d' % + assert ds.GetRasterBand(1).Checksum() == ds_ref.GetRasterBand(1).Checksum(), \ + ('bad checksum : got %d, expected %d' % (ds.GetRasterBand(1).Checksum(), ds_ref.GetRasterBand(1).checksum_ref)) - return 'fail' ds_ref = None ds = None - return 'success' - ############################################################################### # Test Range data metric def test_gdal_grid_7(): if gdal_grid is None: - return 'skip' + pytest.skip() ################# outfiles.append('tmp/grid_range.tif') @@ -645,10 +605,9 @@ def test_gdal_grid_7(): # We should get the same values as in "ref_data/grid_range.tif" ds = gdal.Open(outfiles[-1]) ds_ref = gdal.Open('ref_data/grid_range.tif') - if ds.GetRasterBand(1).Checksum() != ds_ref.GetRasterBand(1).Checksum(): - print('bad checksum : got %d, expected %d' % + assert ds.GetRasterBand(1).Checksum() == ds_ref.GetRasterBand(1).Checksum(), \ + ('bad checksum : got %d, expected %d' % (ds.GetRasterBand(1).Checksum(), ds_ref.GetRasterBand(1).checksum_ref)) - return 'fail' ds_ref = None ds = None @@ -667,22 +626,19 @@ def test_gdal_grid_7(): # We should get the same values as in "ref_data/grid_range_90_90_8p.tif" ds = gdal.Open(outfiles[-1]) ds_ref = gdal.Open('ref_data/grid_range_90_90_8p.tif') - if ds.GetRasterBand(1).Checksum() != ds_ref.GetRasterBand(1).Checksum(): - print('bad checksum : got %d, expected %d' % + assert ds.GetRasterBand(1).Checksum() == ds_ref.GetRasterBand(1).Checksum(), \ + ('bad checksum : got %d, expected %d' % (ds.GetRasterBand(1).Checksum(), ds_ref.GetRasterBand(1).checksum_ref)) - return 'fail' ds_ref = None ds = None - return 'success' - ############################################################################### # Test Count data metric def test_gdal_grid_8(): if gdal_grid is None: - return 'skip' + pytest.skip() ################# outfiles.append('tmp/grid_count_70_70.tif') @@ -697,10 +653,9 @@ def test_gdal_grid_8(): # We should get the same values as in "ref_data/grid_count_70_70.tif" ds = gdal.Open(outfiles[-1]) ds_ref = gdal.Open('ref_data/grid_count_70_70.tif') - if ds.GetRasterBand(1).Checksum() != ds_ref.GetRasterBand(1).Checksum(): - print('bad checksum : got %d, expected %d' % + assert ds.GetRasterBand(1).Checksum() == ds_ref.GetRasterBand(1).Checksum(), \ + ('bad checksum : got %d, expected %d' % (ds.GetRasterBand(1).Checksum(), ds_ref.GetRasterBand(1).checksum_ref)) - return 'fail' ds_ref = None ds = None @@ -717,22 +672,19 @@ def test_gdal_grid_8(): # We should get the same values as in "ref_data/grid_count_300_300.tif" ds = gdal.Open(outfiles[-1]) ds_ref = gdal.Open('ref_data/grid_count_300_300.tif') - if ds.GetRasterBand(1).Checksum() != ds_ref.GetRasterBand(1).Checksum(): - print('bad checksum : got %d, expected %d' % + assert ds.GetRasterBand(1).Checksum() == ds_ref.GetRasterBand(1).Checksum(), \ + ('bad checksum : got %d, expected %d' % (ds.GetRasterBand(1).Checksum(), ds_ref.GetRasterBand(1).checksum_ref)) - return 'fail' ds_ref = None ds = None - return 'success' - ############################################################################### # Test Average Distance data metric def test_gdal_grid_9(): if gdal_grid is None: - return 'skip' + pytest.skip() ################# outfiles.append('tmp/grid_avdist.tif') @@ -753,8 +705,7 @@ def test_gdal_grid_9(): ds_ref = None if maxdiff > 1: gdaltest.compare_ds(ds, ds_ref, verbose=1) - gdaltest.post_reason('Image too different from the reference') - return 'fail' + pytest.fail('Image too different from the reference') ds = None ################# @@ -776,19 +727,16 @@ def test_gdal_grid_9(): ds_ref = None if maxdiff > 1: gdaltest.compare_ds(ds, ds_ref, verbose=1) - gdaltest.post_reason('Image too different from the reference') - return 'fail' + pytest.fail('Image too different from the reference') ds = None - return 'success' - ############################################################################### # Test Average Distance Between Points data metric def test_gdal_grid_10(): if gdal_grid is None: - return 'skip' + pytest.skip() ################# outfiles.append('tmp/grid_avdist_150_50_-15.tif') @@ -809,48 +757,39 @@ def test_gdal_grid_10(): ds_ref = None if maxdiff > 1: gdaltest.compare_ds(ds, ds_ref, verbose=1) - gdaltest.post_reason('Image too different from the reference') - return 'fail' + pytest.fail('Image too different from the reference') ds = None - return 'success' - ############################################################################### # Test linear def test_gdal_grid_11(): if gdal_grid is None: - return 'skip' + pytest.skip() outfiles.append('tmp/n43_linear.tif') # Create a GDAL dataset from the previous generated OGR grid (_, err) = gdaltest.runexternal_out_and_err(gdal_grid + ' -txe -80.0041667 -78.9958333 -tye 42.9958333 44.0041667 -outsize 121 121 -ot Int16 -l n43 -a linear -co TILED=YES -co BLOCKXSIZE=256 -co BLOCKYSIZE=256 tmp/n43.shp ' + outfiles[-1]) - if not (err is None or err == ''): - gdaltest.post_reason('got error/warning') - print(err) - return 'fail' + assert (err is None or err == ''), 'got error/warning' # We should get the same values as in n43.td0 ds = gdal.Open('../gdrivers/data/n43.dt0') ds2 = gdal.Open(outfiles[-1]) - if ds.GetRasterBand(1).Checksum() != ds2.GetRasterBand(1).Checksum(): - print('bad checksum : got %d, expected %d' % (ds.GetRasterBand(1).Checksum(), ds2.GetRasterBand(1).Checksum())) - return 'fail' + assert ds.GetRasterBand(1).Checksum() == ds2.GetRasterBand(1).Checksum(), \ + ('bad checksum : got %d, expected %d' % (ds.GetRasterBand(1).Checksum(), ds2.GetRasterBand(1).Checksum())) ds = None ds2 = None - return 'success' - ############################################################################### # Test Inverse Distance to a Power with Nearest Neighbor gridding algorithm def test_gdal_grid_12(): if gdal_grid is None: - return 'skip' + pytest.skip() ################# # Test generic implementation (no AVX, no SSE) @@ -869,8 +808,7 @@ def test_gdal_grid_12(): maxdiff = gdaltest.compare_ds(ds, ds_ref, verbose=0) if maxdiff > 0.00001: gdaltest.compare_ds(ds, ds_ref, verbose=1) - gdaltest.post_reason('Image too different from the reference') - return 'fail' + pytest.fail('Image too different from the reference') ds_ref = None ds = None @@ -891,8 +829,7 @@ def test_gdal_grid_12(): maxdiff = gdaltest.compare_ds(ds, ds_ref, verbose=0) if maxdiff > 0.00001: gdaltest.compare_ds(ds, ds_ref, verbose=1) - gdaltest.post_reason('Image too different from the reference') - return 'fail' + pytest.fail('Image too different from the reference') ds_ref = None ds = None @@ -913,23 +850,20 @@ def test_gdal_grid_12(): maxdiff = gdaltest.compare_ds(ds, ds_ref, verbose=0) if maxdiff > 0.00001: gdaltest.compare_ds(ds, ds_ref, verbose=1) - gdaltest.post_reason('Image too different from the reference') - return 'fail' + pytest.fail('Image too different from the reference') ds_ref = None ds = None - return 'success' - ############################################################################### # Test -clipsrc def test_gdal_grid_clipsrc(): if gdal_grid is None: - return 'skip' + pytest.skip() if not ogrtest.have_geos(): - return 'skip' + pytest.skip() ################# outfiles.append('tmp/grid_clipsrc.tif') @@ -950,14 +884,9 @@ def test_gdal_grid_clipsrc(): # We should get the same values as in "gcore/data/byte.tif" ds = gdal.Open(outfiles[-1]) cs = ds.GetRasterBand(1).Checksum() - if cs == 0 or cs == 4672: - gdaltest.post_reason('bad checksum') - print(cs) - return 'fail' + assert not (cs == 0 or cs == 4672), 'bad checksum' ds = None - return 'success' - ############################################################################### # Cleanup @@ -969,31 +898,7 @@ def test_gdal_grid_cleanup(): for outfile in outfiles: drv.Delete(outfile) - return 'success' - - -gdaltest_list = [ - test_gdal_grid_1, - test_gdal_grid_2, - test_gdal_grid_3, - test_gdal_grid_4, - test_gdal_grid_5, - test_gdal_grid_6, - test_gdal_grid_7, - test_gdal_grid_8, - test_gdal_grid_9, - test_gdal_grid_10, - test_gdal_grid_11, - test_gdal_grid_12, - test_gdal_grid_clipsrc, - test_gdal_grid_cleanup -] - - -if __name__ == '__main__': + - gdaltest.setup_run('test_gdal_grid') - gdaltest.run_tests(gdaltest_list) - sys.exit(gdaltest.summarize()) diff --git a/autotest/utilities/test_gdal_grid_lib.py b/autotest/utilities/test_gdal_grid_lib.py index af3e8609f01d..e08620c7a548 100755 --- a/autotest/utilities/test_gdal_grid_lib.py +++ b/autotest/utilities/test_gdal_grid_lib.py @@ -29,14 +29,11 @@ # DEALINGS IN THE SOFTWARE. ############################################################################### -import sys import struct -sys.path.append('../pymod') from osgeo import gdal, ogr -import gdaltest import ogrtest ############################################################################### @@ -79,18 +76,13 @@ def test_gdal_grid_lib_1(): algorithm='nearest:radius1=0.0:radius2=0.0:angle=0.0', spatFilter=spatFilter) # We should get the same values as in n43.td0 - if ds.GetRasterBand(1).Checksum() != ds2.GetRasterBand(1).Checksum(): - print('bad checksum : got %d, expected %d' % (ds.GetRasterBand(1).Checksum(), ds2.GetRasterBand(1).Checksum())) - return 'fail' - if ds2.GetRasterBand(1).GetNoDataValue() is not None: - print('did not expect nodata value') - return 'fail' + assert ds.GetRasterBand(1).Checksum() == ds2.GetRasterBand(1).Checksum(), \ + ('bad checksum : got %d, expected %d' % (ds.GetRasterBand(1).Checksum(), ds2.GetRasterBand(1).Checksum())) + assert ds2.GetRasterBand(1).GetNoDataValue() is None, 'did not expect nodata value' ds = None ds2 = None - return 'success' - ############################################################################### # Test with a point number not multiple of 8 or 16 @@ -122,19 +114,12 @@ def test_gdal_grid_lib_2(): gdal.SetConfigOption('GDAL_USE_SSE', None) cs = ds1.GetRasterBand(1).Checksum() - if cs != 2: - gdaltest.post_reason('fail') - print(cs) - return 'fail' + assert cs == 2 cs = ds2.GetRasterBand(1).Checksum() - if cs != 1064: - gdaltest.post_reason('fail') - print(cs) - return 'fail' - - return 'success' + assert cs == 1064 + ############################################################################### # Test bugfix for #7101 (segmentation fault with linear interpolation) @@ -148,8 +133,6 @@ def test_gdal_grid_lib_3(): width=115, height=93, outputBounds=[37.3495161160827, 55.6901531392856, 37.3497618734837, 55.6902650179072], format='MEM', algorithm='linear') - return 'success' - ############################################################################### # Cleanup @@ -158,21 +141,6 @@ def test_gdal_grid_lib_cleanup(): ogr.GetDriverByName('ESRI Shapefile').DeleteDataSource('/vsimem/tmp') - return 'success' - - -gdaltest_list = [ - test_gdal_grid_lib_1, - test_gdal_grid_lib_2, - test_gdal_grid_lib_3, - test_gdal_grid_lib_cleanup, -] - - -if __name__ == '__main__': - gdaltest.setup_run('test_gdal_grid_lib') - gdaltest.run_tests(gdaltest_list) - sys.exit(gdaltest.summarize()) diff --git a/autotest/utilities/test_gdal_rasterize.py b/autotest/utilities/test_gdal_rasterize.py index 0cedad48708a..54932c147407 100755 --- a/autotest/utilities/test_gdal_rasterize.py +++ b/autotest/utilities/test_gdal_rasterize.py @@ -32,8 +32,8 @@ import sys import os +import pytest -sys.path.append('../pymod') sys.path.append('../gcore') from osgeo import gdal @@ -49,7 +49,7 @@ def test_gdal_rasterize_1(): if test_cli_utilities.get_gdal_rasterize_path() is None: - return 'skip' + pytest.skip() # Setup working spatial reference # sr_wkt = 'LOCAL_CS["arbitrary"]' @@ -105,26 +105,17 @@ def test_gdal_rasterize_1(): # Run the algorithm. (_, err) = gdaltest.runexternal_out_and_err(test_cli_utilities.get_gdal_rasterize_path() + ' -b 3 -b 2 -b 1 -burn 200 -burn 220 -burn 240 -l rast1 tmp/rast1.tab tmp/rast1.tif') - if not (err is None or err == ''): - gdaltest.post_reason('got error/warning') - print(err) - return 'fail' + assert (err is None or err == ''), 'got error/warning' # Check results. target_ds = gdal.Open('tmp/rast1.tif') expected = 6452 checksum = target_ds.GetRasterBand(2).Checksum() - if checksum != expected: - print(checksum) - gdaltest.post_reason('Did not get expected image checksum') - - return 'fail' + assert checksum == expected, 'Did not get expected image checksum' target_ds = None - return 'success' - ############################################################################### # Test rasterization with ALL_TOUCHED (adapted from alg/rasterize.py). @@ -132,7 +123,7 @@ def test_gdal_rasterize_1(): def test_gdal_rasterize_2(): if test_cli_utilities.get_gdal_rasterize_path() is None: - return 'skip' + pytest.skip() # Create a raster to rasterize into. @@ -151,16 +142,10 @@ def test_gdal_rasterize_2(): target_ds = gdal.Open('tmp/rast2.tif') expected = 121 checksum = target_ds.GetRasterBand(2).Checksum() - if checksum != expected: - print(checksum) - gdaltest.post_reason('Did not get expected image checksum') - - return 'fail' + assert checksum == expected, 'Did not get expected image checksum' target_ds = None - return 'success' - ############################################################################### # Test creating an output file @@ -168,10 +153,10 @@ def test_gdal_rasterize_2(): def test_gdal_rasterize_3(): if test_cli_utilities.get_gdal_contour_path() is None: - return 'skip' + pytest.skip() if test_cli_utilities.get_gdal_rasterize_path() is None: - return 'skip' + pytest.skip() gdaltest.runexternal(test_cli_utilities.get_gdal_contour_path() + ' ../gdrivers/data/n43.dt0 tmp/n43dt0.shp -i 10 -3d') @@ -180,30 +165,19 @@ def test_gdal_rasterize_3(): ds_ref = gdal.Open('../gdrivers/data/n43.dt0') ds = gdal.Open('tmp/n43dt0.tif') - if ds.GetRasterBand(1).GetNoDataValue() != 0.0: - gdaltest.post_reason('did not get expected nodata value') - return 'fail' + assert ds.GetRasterBand(1).GetNoDataValue() == 0.0, \ + 'did not get expected nodata value' - if ds.RasterXSize != 121 or ds.RasterYSize != 121: - gdaltest.post_reason('did not get expected dimensions') - return 'fail' + assert ds.RasterXSize == 121 and ds.RasterYSize == 121, \ + 'did not get expected dimensions' gt_ref = ds_ref.GetGeoTransform() gt = ds.GetGeoTransform() for i in range(6): - if abs(gt[i] - gt_ref[i]) > 1e-6: - gdaltest.post_reason('did not get expected geotransform') - print(gt) - print(gt_ref) - return 'fail' + assert abs(gt[i] - gt_ref[i]) <= 1e-6, 'did not get expected geotransform' wkt = ds.GetProjectionRef() - if wkt.find("WGS_1984") == -1: - gdaltest.post_reason('did not get expected SRS') - print(wkt) - return 'fail' - - return 'success' + assert wkt.find("WGS_1984") != -1, 'did not get expected SRS' ############################################################################### # Same but with -tr argument @@ -212,10 +186,10 @@ def test_gdal_rasterize_3(): def test_gdal_rasterize_4(): if test_cli_utilities.get_gdal_contour_path() is None: - return 'skip' + pytest.skip() if test_cli_utilities.get_gdal_rasterize_path() is None: - return 'skip' + pytest.skip() gdal.GetDriverByName('GTiff').Delete('tmp/n43dt0.tif') @@ -224,38 +198,25 @@ def test_gdal_rasterize_4(): ds_ref = gdal.Open('../gdrivers/data/n43.dt0') ds = gdal.Open('tmp/n43dt0.tif') - if ds.GetRasterBand(1).GetNoDataValue() != 0.0: - gdaltest.post_reason('did not get expected nodata value') - return 'fail' + assert ds.GetRasterBand(1).GetNoDataValue() == 0.0, \ + 'did not get expected nodata value' # Allow output to grow by 1/2 cell, as per #6058 - if ds.RasterXSize != 122 or ds.RasterYSize != 122: - gdaltest.post_reason('did not get expected dimensions') - return 'fail' + assert ds.RasterXSize == 122 and ds.RasterYSize == 122, \ + 'did not get expected dimensions' gt_ref = ds_ref.GetGeoTransform() gt = ds.GetGeoTransform() - if abs(gt[1] - gt_ref[1]) > 1e-6 or abs(gt[5] - gt_ref[5]) > 1e-6: - gdaltest.post_reason('did not get expected geotransform(dx/dy)') - print(gt) - print(gt_ref) - return 'fail' + assert abs(gt[1] - gt_ref[1]) <= 1e-6 and abs(gt[5] - gt_ref[5]) <= 1e-6, \ + 'did not get expected geotransform(dx/dy)' # Allow output to grow by 1/2 cell, as per #6058 - if abs(gt[0] + (gt[1] / 2) - gt_ref[0]) > 1e-6 or \ - abs(gt[3] + (gt[5] / 2) - gt_ref[3]) > 1e-6: - gdaltest.post_reason('did not get expected geotransform') - print(gt) - print(gt_ref) - return 'fail' + assert (abs(gt[0] + (gt[1] / 2) - gt_ref[0]) <= 1e-6 and \ + abs(gt[3] + (gt[5] / 2) - gt_ref[3]) <= 1e-6), \ + 'did not get expected geotransform' wkt = ds.GetProjectionRef() - if wkt.find("WGS_1984") == -1: - gdaltest.post_reason('did not get expected SRS') - print(wkt) - return 'fail' - - return 'success' + assert wkt.find("WGS_1984") != -1, 'did not get expected SRS' ############################################################################### # Test point rasterization (#3774) @@ -264,7 +225,7 @@ def test_gdal_rasterize_4(): def test_gdal_rasterize_5(): if test_cli_utilities.get_gdal_rasterize_path() is None: - return 'skip' + pytest.skip() f = open('tmp/test_gdal_rasterize_5.csv', 'wb') f.write("""x,y,Value @@ -289,30 +250,20 @@ def test_gdal_rasterize_5(): gdaltest.runexternal(test_cli_utilities.get_gdal_rasterize_path() + ' -l test tmp/test_gdal_rasterize_5.vrt tmp/test_gdal_rasterize_5.tif -a Value -tr 1 1 -ot Byte') ds = gdal.Open('tmp/test_gdal_rasterize_5.tif') - if ds.RasterXSize != 3 or ds.RasterYSize != 3: - gdaltest.post_reason('did not get expected dimensions') - print(ds.RasterXSize) - print(ds.RasterYSize) - return 'fail' + assert ds.RasterXSize == 3 and ds.RasterYSize == 3, \ + 'did not get expected dimensions' gt_ref = [0, 1, 0, 3, 0, -1] gt = ds.GetGeoTransform() for i in range(6): - if abs(gt[i] - gt_ref[i]) > 1e-6: - gdaltest.post_reason('did not get expected geotransform') - print(gt) - print(gt_ref) - return 'fail' + assert abs(gt[i] - gt_ref[i]) <= 1e-6, 'did not get expected geotransform' data = ds.GetRasterBand(1).ReadRaster(0, 0, 3, 3) - if data.decode('iso-8859-1') != '\x02\x00\x03\x00\x05\x00\x01\x00\x04': - gdaltest.post_reason('did not get expected values') - return 'fail' + assert data.decode('iso-8859-1') == '\x02\x00\x03\x00\x05\x00\x01\x00\x04', \ + 'did not get expected values' ds = None - return 'success' - ############################################################################### # Test on the fly reprojection of input data @@ -320,7 +271,7 @@ def test_gdal_rasterize_5(): def test_gdal_rasterize_6(): if test_cli_utilities.get_gdal_rasterize_path() is None: - return 'skip' + pytest.skip() f = open('tmp/test_gdal_rasterize_6.csv', 'wb') f.write("""WKT,Value @@ -342,15 +293,10 @@ def test_gdal_rasterize_6(): gdaltest.runexternal(test_cli_utilities.get_gdal_rasterize_path() + ' -l test_gdal_rasterize_6 tmp/test_gdal_rasterize_6.csv tmp/test_gdal_rasterize_6.tif -a Value') ds = gdal.Open('tmp/test_gdal_rasterize_6.tif') - if ds.GetRasterBand(1).Checksum() != 39190: - gdaltest.post_reason('did not get expected checksum') - print(ds.GetRasterBand(1).Checksum()) - return 'fail' + assert ds.GetRasterBand(1).Checksum() == 39190, 'did not get expected checksum' ds = None - return 'success' - ############################################################################### # Test SQLITE dialect in SQL @@ -361,18 +307,18 @@ def test_gdal_rasterize_7(): from osgeo import gdalnumeric gdalnumeric.zeros except (ImportError, AttributeError): - return 'skip' + pytest.skip() if test_cli_utilities.get_gdal_rasterize_path() is None: - return 'skip' + pytest.skip() drv = ogr.GetDriverByName('SQLite') if drv is None: - return 'skip' + pytest.skip() gdal.PushErrorHandler('CPLQuietErrorHandler') ds = drv.CreateDataSource('/vsimem/foo.db', options=['SPATIALITE=YES']) if ds is None: - return 'skip' + pytest.skip() ds = None gdal.Unlink('/vsimem/foo.db') gdal.PopErrorHandler() @@ -397,14 +343,10 @@ def test_gdal_rasterize_7(): ds = gdal.Open('tmp/test_gdal_rasterize_7.tif') data = ds.GetRasterBand(1).ReadAsArray() - if data.sum() <= 5: - gdaltest.post_reason('Only rasterized 5 pixels or less.') - return 'fail' + assert data.sum() > 5, 'Only rasterized 5 pixels or less.' ds = None - return 'success' - ############################################################################### # Make sure we create output that encompasses all the input points on a point # layer, #6058. @@ -413,7 +355,7 @@ def test_gdal_rasterize_7(): def test_gdal_rasterize_8(): if test_cli_utilities.get_gdal_rasterize_path() is None: - return 'skip' + pytest.skip() f = open('tmp/test_gdal_rasterize_8.csv', 'wb') f.write('WKT,Value\n'.encode('ascii')) @@ -426,21 +368,16 @@ def test_gdal_rasterize_8(): ds = gdal.Open('tmp/test_gdal_rasterize_8.tif') cs = ds.GetRasterBand(1).Checksum() - if cs != 21: - gdaltest.post_reason('Did not rasterize line data properly') - print(cs) - return 'fail' + assert cs == 21, 'Did not rasterize line data properly' ds = None - return 'success' - ########################################### def test_gdal_rasterize_cleanup(): if test_cli_utilities.get_gdal_rasterize_path() is None: - return 'skip' + pytest.skip() gdal.GetDriverByName('GTiff').Delete('tmp/rast1.tif') ogr.GetDriverByName('MapInfo File').DeleteDataSource('tmp/rast1.tab') @@ -466,25 +403,5 @@ def test_gdal_rasterize_cleanup(): gdal.GetDriverByName('GTiff').Delete('tmp/test_gdal_rasterize_8.tif') os.unlink('tmp/test_gdal_rasterize_8.csv') - return 'success' - - -gdaltest_list = [ - test_gdal_rasterize_1, - test_gdal_rasterize_2, - test_gdal_rasterize_3, - test_gdal_rasterize_4, - test_gdal_rasterize_5, - test_gdal_rasterize_6, - test_gdal_rasterize_7, - test_gdal_rasterize_8, - test_gdal_rasterize_cleanup -] - -if __name__ == '__main__': - - gdaltest.setup_run('test_gdal_rasterize') - gdaltest.run_tests(gdaltest_list) - sys.exit(gdaltest.summarize()) diff --git a/autotest/utilities/test_gdal_rasterize_lib.py b/autotest/utilities/test_gdal_rasterize_lib.py index 6d5467826de3..d3afd247295d 100755 --- a/autotest/utilities/test_gdal_rasterize_lib.py +++ b/autotest/utilities/test_gdal_rasterize_lib.py @@ -30,12 +30,11 @@ # DEALINGS IN THE SOFTWARE. ############################################################################### -import sys -sys.path.append('../pymod') from osgeo import gdal, ogr, osr import gdaltest +import pytest ############################################################################### # Simple polygon rasterization (adapted from alg/rasterize.py). @@ -90,23 +89,15 @@ def test_gdal_rasterize_lib_1(): rast_lyr.CreateFeature(feat) ret = gdal.Rasterize(target_ds, vector_ds, bands=[3, 2, 1], burnValues=[200, 220, 240], layers='rast1') - if ret != 1: - gdaltest.post_reason('fail') - return 'fail' + assert ret == 1 # Check results. expected = 6452 checksum = target_ds.GetRasterBand(2).Checksum() - if checksum != expected: - print(checksum) - gdaltest.post_reason('Did not get expected image checksum') - - return 'fail' + assert checksum == expected, 'Did not get expected image checksum' target_ds = None - return 'success' - ############################################################################### # Test creating an output file @@ -115,15 +106,13 @@ def test_gdal_rasterize_lib_3(): import test_cli_utilities if test_cli_utilities.get_gdal_contour_path() is None: - return 'skip' + pytest.skip() gdaltest.runexternal(test_cli_utilities.get_gdal_contour_path() + ' ../gdrivers/data/n43.dt0 tmp/n43dt0.shp -i 10 -3d') with gdaltest.error_handler(): ds = gdal.Rasterize('/vsimem/bogus.tif', 'tmp/n43dt0.shp') - if ds is not None: - gdaltest.post_reason('did not expected success') - return 'fail' + assert ds is None, 'did not expected success' ds = gdal.Rasterize('', 'tmp/n43dt0.shp', format='MEM', outputType=gdal.GDT_Byte, useZ=True, layers=['n43dt0'], width=121, height=121, noData=0) @@ -131,30 +120,19 @@ def test_gdal_rasterize_lib_3(): ds_ref = gdal.Open('../gdrivers/data/n43.dt0') - if ds.GetRasterBand(1).GetNoDataValue() != 0.0: - gdaltest.post_reason('did not get expected nodata value') - return 'fail' + assert ds.GetRasterBand(1).GetNoDataValue() == 0.0, \ + 'did not get expected nodata value' - if ds.RasterXSize != 121 or ds.RasterYSize != 121: - gdaltest.post_reason('did not get expected dimensions') - return 'fail' + assert ds.RasterXSize == 121 and ds.RasterYSize == 121, \ + 'did not get expected dimensions' gt_ref = ds_ref.GetGeoTransform() gt = ds.GetGeoTransform() for i in range(6): - if abs(gt[i] - gt_ref[i]) > 1e-6: - gdaltest.post_reason('did not get expected geotransform') - print(gt) - print(gt_ref) - return 'fail' + assert abs(gt[i] - gt_ref[i]) <= 1e-6, 'did not get expected geotransform' wkt = ds.GetProjectionRef() - if wkt.find("WGS_1984") == -1: - gdaltest.post_reason('did not get expected SRS') - print(wkt) - return 'fail' - - return 'success' + assert wkt.find("WGS_1984") != -1, 'did not get expected SRS' ############################################################################### # Rasterization without georeferencing @@ -178,23 +156,15 @@ def test_gdal_rasterize_lib_100(): rast_lyr.CreateFeature(feat) ret = gdal.Rasterize(target_ds, vector_ds, burnValues=[255]) - if ret != 1: - gdaltest.post_reason('fail') - return 'fail' + assert ret == 1 # Check results. expected = 44190 checksum = target_ds.GetRasterBand(1).Checksum() - if checksum != expected: - print(checksum) - gdaltest.post_reason('Did not get expected image checksum') - - return 'fail' + assert checksum == expected, 'Did not get expected image checksum' target_ds = None - return 'success' - ############################################################################### # Rasterization on empty geometry @@ -218,22 +188,14 @@ def test_gdal_rasterize_lib_101(): rast_lyr.CreateFeature(feat) ret = gdal.Rasterize(target_ds, vector_ds, burnValues=[255]) - if ret != 1: - gdaltest.post_reason('fail') - return 'fail' + assert ret == 1 # Check results. checksum = target_ds.GetRasterBand(1).Checksum() - if checksum != 0: - print(checksum) - gdaltest.post_reason('Did not get expected image checksum') - - return 'fail' + assert checksum == 0, 'Did not get expected image checksum' target_ds = None - return 'success' - ############################################################################### # Rasterization on raster with RPC @@ -275,37 +237,23 @@ def test_gdal_rasterize_lib_102(): rast_lyr.CreateFeature(feat) ret = gdal.Rasterize(target_ds, vector_ds, burnValues=[0]) - if ret != 1: - gdaltest.post_reason('fail') - return 'fail' + assert ret == 1 # Check results. checksum = target_ds.GetRasterBand(1).Checksum() - if checksum != 1604: - print(checksum) - gdaltest.post_reason('Did not get expected image checksum') - - return 'fail' + assert checksum == 1604, 'Did not get expected image checksum' # Re-try with transformer options target_ds.GetRasterBand(1).Fill(255) ret = gdal.Rasterize(target_ds, vector_ds, burnValues=[0], transformerOptions=['RPC_HEIGHT=1000']) - if ret != 1: - gdaltest.post_reason('fail') - return 'fail' + assert ret == 1 # Check results. checksum = target_ds.GetRasterBand(1).Checksum() - if checksum != 2003: - print(checksum) - gdaltest.post_reason('Did not get expected image checksum') - - return 'fail' + assert checksum == 2003, 'Did not get expected image checksum' target_ds = None - return 'success' - ############################################################################### # Simple rasterization with all values of the optim option @@ -359,37 +307,18 @@ def test_gdal_rasterize_lib_4(): rast_lyr.CreateFeature(feat) ret = gdal.Rasterize(target_ds, vector_ds, bands=[3, 2, 1], burnValues=[200, 220, 240], layers='rast1', optim=optim) - if ret != 1: - gdaltest.post_reason('fail') - return 'fail' + assert ret == 1 # Check results. expected = 6452 checksum = target_ds.GetRasterBand(2).Checksum() if checksum != expected: print(checksum, optim) - gdaltest.post_reason('Did not get expected image checksum') - return 'fail' + pytest.fail('Did not get expected image checksum') target_ds = None - return 'success' - - -gdaltest_list = [ - test_gdal_rasterize_lib_1, - test_gdal_rasterize_lib_3, - test_gdal_rasterize_lib_100, - test_gdal_rasterize_lib_101, - test_gdal_rasterize_lib_102, - test_gdal_rasterize_lib_4 -] - -if __name__ == '__main__': - - gdaltest.setup_run('test_gdal_rasterize_lib') + - gdaltest.run_tests(gdaltest_list) - sys.exit(gdaltest.summarize()) diff --git a/autotest/utilities/test_gdal_translate.py b/autotest/utilities/test_gdal_translate.py index c16c66a07c99..911d6e36ba00 100755 --- a/autotest/utilities/test_gdal_translate.py +++ b/autotest/utilities/test_gdal_translate.py @@ -29,14 +29,13 @@ # DEALINGS IN THE SOFTWARE. ############################################################################### -import sys import os -sys.path.append('../pymod') from osgeo import gdal import gdaltest import test_cli_utilities +import pytest ############################################################################### # Simple test @@ -44,489 +43,367 @@ def test_gdal_translate_1(): if test_cli_utilities.get_gdal_translate_path() is None: - return 'skip' + pytest.skip() (_, err) = gdaltest.runexternal_out_and_err(test_cli_utilities.get_gdal_translate_path() + ' ../gcore/data/byte.tif tmp/test1.tif') - if not (err is None or err == ''): - gdaltest.post_reason('got error/warning') - print(err) - return 'fail' + assert (err is None or err == ''), 'got error/warning' ds = gdal.Open('tmp/test1.tif') - if ds is None: - return 'fail' + assert ds is not None - if ds.GetRasterBand(1).Checksum() != 4672: - gdaltest.post_reason('Bad checksum') - return 'fail' + assert ds.GetRasterBand(1).Checksum() == 4672, 'Bad checksum' ds = None - return 'success' - ############################################################################### # Test -of option def test_gdal_translate_2(): if test_cli_utilities.get_gdal_translate_path() is None: - return 'skip' + pytest.skip() gdaltest.runexternal(test_cli_utilities.get_gdal_translate_path() + ' -of GTiff ../gcore/data/byte.tif tmp/test2.tif') ds = gdal.Open('tmp/test2.tif') - if ds is None: - return 'fail' + assert ds is not None - if ds.GetRasterBand(1).Checksum() != 4672: - gdaltest.post_reason('Bad checksum') - return 'fail' + assert ds.GetRasterBand(1).Checksum() == 4672, 'Bad checksum' ds = None - return 'success' - ############################################################################### # Test -ot option def test_gdal_translate_3(): if test_cli_utilities.get_gdal_translate_path() is None: - return 'skip' + pytest.skip() gdaltest.runexternal(test_cli_utilities.get_gdal_translate_path() + ' -ot Int16 ../gcore/data/byte.tif tmp/test3.tif') ds = gdal.Open('tmp/test3.tif') - if ds is None: - return 'fail' + assert ds is not None - if ds.GetRasterBand(1).DataType != gdal.GDT_Int16: - gdaltest.post_reason('Bad data type') - return 'fail' + assert ds.GetRasterBand(1).DataType == gdal.GDT_Int16, 'Bad data type' - if ds.GetRasterBand(1).Checksum() != 4672: - gdaltest.post_reason('Bad checksum') - return 'fail' + assert ds.GetRasterBand(1).Checksum() == 4672, 'Bad checksum' ds = None - return 'success' - ############################################################################### # Test -b option def test_gdal_translate_4(): if test_cli_utilities.get_gdal_translate_path() is None: - return 'skip' + pytest.skip() gdaltest.runexternal(test_cli_utilities.get_gdal_translate_path() + ' -b 3 -b 2 -b 1 ../gcore/data/rgbsmall.tif tmp/test4.tif') ds = gdal.Open('tmp/test4.tif') - if ds is None: - return 'fail' + assert ds is not None - if ds.GetRasterBand(1).Checksum() != 21349: - gdaltest.post_reason('Bad checksum') - return 'fail' + assert ds.GetRasterBand(1).Checksum() == 21349, 'Bad checksum' - if ds.GetRasterBand(2).Checksum() != 21053: - gdaltest.post_reason('Bad checksum') - return 'fail' + assert ds.GetRasterBand(2).Checksum() == 21053, 'Bad checksum' - if ds.GetRasterBand(3).Checksum() != 21212: - gdaltest.post_reason('Bad checksum') - return 'fail' + assert ds.GetRasterBand(3).Checksum() == 21212, 'Bad checksum' ds = None - return 'success' - ############################################################################### # Test -expand option def test_gdal_translate_5(): if test_cli_utilities.get_gdal_translate_path() is None: - return 'skip' + pytest.skip() gdaltest.runexternal(test_cli_utilities.get_gdal_translate_path() + ' -expand rgb ../gdrivers/data/bug407.gif tmp/test5.tif') ds = gdal.Open('tmp/test5.tif') - if ds is None: - return 'fail' + assert ds is not None - if ds.GetRasterBand(1).GetRasterColorInterpretation() != gdal.GCI_RedBand: - gdaltest.post_reason('Bad color interpretation') - return 'fail' + assert ds.GetRasterBand(1).GetRasterColorInterpretation() == gdal.GCI_RedBand, \ + 'Bad color interpretation' - if ds.GetRasterBand(2).GetRasterColorInterpretation() != gdal.GCI_GreenBand: - gdaltest.post_reason('Bad color interpretation') - return 'fail' + assert ds.GetRasterBand(2).GetRasterColorInterpretation() == gdal.GCI_GreenBand, \ + 'Bad color interpretation' - if ds.GetRasterBand(3).GetRasterColorInterpretation() != gdal.GCI_BlueBand: - gdaltest.post_reason('Bad color interpretation') - return 'fail' + assert ds.GetRasterBand(3).GetRasterColorInterpretation() == gdal.GCI_BlueBand, \ + 'Bad color interpretation' - if ds.GetRasterBand(1).Checksum() != 20615: - gdaltest.post_reason('Bad checksum') - return 'fail' + assert ds.GetRasterBand(1).Checksum() == 20615, 'Bad checksum' - if ds.GetRasterBand(2).Checksum() != 59147: - gdaltest.post_reason('Bad checksum') - return 'fail' + assert ds.GetRasterBand(2).Checksum() == 59147, 'Bad checksum' - if ds.GetRasterBand(3).Checksum() != 63052: - gdaltest.post_reason('Bad checksum') - return 'fail' + assert ds.GetRasterBand(3).Checksum() == 63052, 'Bad checksum' ds = None - return 'success' - ############################################################################### # Test -outsize option in absolute mode def test_gdal_translate_6(): if test_cli_utilities.get_gdal_translate_path() is None: - return 'skip' + pytest.skip() gdaltest.runexternal(test_cli_utilities.get_gdal_translate_path() + ' -outsize 40 40 ../gcore/data/byte.tif tmp/test6.tif') ds = gdal.Open('tmp/test6.tif') - if ds is None: - return 'fail' + assert ds is not None - if ds.GetRasterBand(1).Checksum() != 18784: - gdaltest.post_reason('Bad checksum') - return 'fail' + assert ds.GetRasterBand(1).Checksum() == 18784, 'Bad checksum' ds = None - return 'success' - ############################################################################### # Test -outsize option in percentage mode def test_gdal_translate_7(): if test_cli_utilities.get_gdal_translate_path() is None: - return 'skip' + pytest.skip() gdaltest.runexternal(test_cli_utilities.get_gdal_translate_path() + ' -outsize 200% 200% ../gcore/data/byte.tif tmp/test7.tif') ds = gdal.Open('tmp/test7.tif') - if ds is None: - return 'fail' + assert ds is not None - if ds.GetRasterBand(1).Checksum() != 18784: - gdaltest.post_reason('Bad checksum') - return 'fail' + assert ds.GetRasterBand(1).Checksum() == 18784, 'Bad checksum' ds = None - return 'success' - ############################################################################### # Test -a_srs and -gcp options def test_gdal_translate_8(): if test_cli_utilities.get_gdal_translate_path() is None: - return 'skip' + pytest.skip() gdaltest.runexternal(test_cli_utilities.get_gdal_translate_path() + ' -a_srs EPSG:26711 -gcp 0 0 440720.000 3751320.000 -gcp 20 0 441920.000 3751320.000 -gcp 20 20 441920.000 3750120.000 0 -gcp 0 20 440720.000 3750120.000 ../gcore/data/byte.tif tmp/test8.tif') ds = gdal.Open('tmp/test8.tif') - if ds is None: - return 'fail' + assert ds is not None - if ds.GetRasterBand(1).Checksum() != 4672: - gdaltest.post_reason('Bad checksum') - return 'fail' + assert ds.GetRasterBand(1).Checksum() == 4672, 'Bad checksum' gcps = ds.GetGCPs() - if len(gcps) != 4: - gdaltest.post_reason('GCP count wrong.') - return 'fail' + assert len(gcps) == 4, 'GCP count wrong.' - if ds.GetGCPProjection().find('26711') == -1: - gdaltest.post_reason('Bad GCP projection.') - return 'fail' + assert ds.GetGCPProjection().find('26711') != -1, 'Bad GCP projection.' ds = None - return 'success' - ############################################################################### # Test -a_nodata option def test_gdal_translate_9(): if test_cli_utilities.get_gdal_translate_path() is None: - return 'skip' + pytest.skip() gdaltest.runexternal(test_cli_utilities.get_gdal_translate_path() + ' -a_nodata 1 ../gcore/data/byte.tif tmp/test9.tif') ds = gdal.Open('tmp/test9.tif') - if ds is None: - return 'fail' + assert ds is not None - if ds.GetRasterBand(1).GetNoDataValue() != 1: - gdaltest.post_reason('Bad nodata value') - return 'fail' + assert ds.GetRasterBand(1).GetNoDataValue() == 1, 'Bad nodata value' ds = None - return 'success' - ############################################################################### # Test -srcwin option def test_gdal_translate_10(): if test_cli_utilities.get_gdal_translate_path() is None: - return 'skip' + pytest.skip() gdaltest.runexternal(test_cli_utilities.get_gdal_translate_path() + ' -srcwin 0 0 1 1 ../gcore/data/byte.tif tmp/test10.tif') ds = gdal.Open('tmp/test10.tif') - if ds is None: - return 'fail' + assert ds is not None - if ds.GetRasterBand(1).Checksum() != 2: - gdaltest.post_reason('Bad checksum') - return 'fail' + assert ds.GetRasterBand(1).Checksum() == 2, 'Bad checksum' ds = None - return 'success' - ############################################################################### # Test -projwin option def test_gdal_translate_11(): if test_cli_utilities.get_gdal_translate_path() is None: - return 'skip' + pytest.skip() gdaltest.runexternal(test_cli_utilities.get_gdal_translate_path() + ' -projwin 440720.000 3751320.000 441920.000 3750120.000 ../gcore/data/byte.tif tmp/test11.tif') ds = gdal.Open('tmp/test11.tif') - if ds is None: - return 'fail' + assert ds is not None - if ds.GetRasterBand(1).Checksum() != 4672: - gdaltest.post_reason('Bad checksum') - return 'fail' + assert ds.GetRasterBand(1).Checksum() == 4672, 'Bad checksum' - if not gdaltest.geotransform_equals(gdal.Open('../gcore/data/byte.tif').GetGeoTransform(), ds.GetGeoTransform(), 1e-9): - gdaltest.post_reason('Bad geotransform') - return 'fail' + assert gdaltest.geotransform_equals(gdal.Open('../gcore/data/byte.tif').GetGeoTransform(), ds.GetGeoTransform(), 1e-9), \ + 'Bad geotransform' ds = None - return 'success' - ############################################################################### # Test -a_ullr option def test_gdal_translate_12(): if test_cli_utilities.get_gdal_translate_path() is None: - return 'skip' + pytest.skip() gdaltest.runexternal(test_cli_utilities.get_gdal_translate_path() + ' -a_ullr 440720.000 3751320.000 441920.000 3750120.000 ../gcore/data/byte.tif tmp/test12.tif') ds = gdal.Open('tmp/test12.tif') - if ds is None: - return 'fail' + assert ds is not None - if ds.GetRasterBand(1).Checksum() != 4672: - gdaltest.post_reason('Bad checksum') - return 'fail' + assert ds.GetRasterBand(1).Checksum() == 4672, 'Bad checksum' - if not gdaltest.geotransform_equals(gdal.Open('../gcore/data/byte.tif').GetGeoTransform(), ds.GetGeoTransform(), 1e-9): - gdaltest.post_reason('Bad geotransform') - return 'fail' + assert gdaltest.geotransform_equals(gdal.Open('../gcore/data/byte.tif').GetGeoTransform(), ds.GetGeoTransform(), 1e-9), \ + 'Bad geotransform' ds = None - return 'success' - ############################################################################### # Test -mo option def test_gdal_translate_13(): if test_cli_utilities.get_gdal_translate_path() is None: - return 'skip' + pytest.skip() gdaltest.runexternal(test_cli_utilities.get_gdal_translate_path() + ' -mo TIFFTAG_DOCUMENTNAME=test13 ../gcore/data/byte.tif tmp/test13.tif') ds = gdal.Open('tmp/test13.tif') - if ds is None: - return 'fail' + assert ds is not None md = ds.GetMetadata() - if 'TIFFTAG_DOCUMENTNAME' not in md: - gdaltest.post_reason('Did not get TIFFTAG_DOCUMENTNAME') - return 'fail' + assert 'TIFFTAG_DOCUMENTNAME' in md, 'Did not get TIFFTAG_DOCUMENTNAME' ds = None - return 'success' - ############################################################################### # Test -co option def test_gdal_translate_14(): if test_cli_utilities.get_gdal_translate_path() is None: - return 'skip' + pytest.skip() gdaltest.runexternal(test_cli_utilities.get_gdal_translate_path() + ' -co COMPRESS=LZW ../gcore/data/byte.tif tmp/test14.tif') ds = gdal.Open('tmp/test14.tif') - if ds is None: - return 'fail' + assert ds is not None md = ds.GetMetadata('IMAGE_STRUCTURE') - if 'COMPRESSION' not in md or md['COMPRESSION'] != 'LZW': - gdaltest.post_reason('Did not get COMPRESSION') - return 'fail' + assert 'COMPRESSION' in md and md['COMPRESSION'] == 'LZW', 'Did not get COMPRESSION' ds = None - return 'success' - ############################################################################### # Test -sds option def test_gdal_translate_15(): if test_cli_utilities.get_gdal_translate_path() is None: - return 'skip' + pytest.skip() gdaltest.runexternal(test_cli_utilities.get_gdal_translate_path() + ' -sds ../gdrivers/data/A.TOC tmp/test15.tif') ds = gdal.Open('tmp/test15_1.tif') - if ds is None: - return 'fail' + assert ds is not None ds = None - return 'success' - ############################################################################### # Test -of VRT which is a special case def test_gdal_translate_16(): if test_cli_utilities.get_gdal_translate_path() is None: - return 'skip' + pytest.skip() gdaltest.runexternal(test_cli_utilities.get_gdal_translate_path() + ' -of VRT ../gcore/data/byte.tif tmp/test16.vrt') ds = gdal.Open('tmp/test16.vrt') - if ds is None: - return 'fail' + assert ds is not None - if ds.GetRasterBand(1).Checksum() != 4672: - gdaltest.post_reason('Bad checksum') - return 'fail' + assert ds.GetRasterBand(1).Checksum() == 4672, 'Bad checksum' ds = None - return 'success' - ############################################################################### # Test -expand option to VRT def test_gdal_translate_17(): if test_cli_utilities.get_gdal_translate_path() is None: - return 'skip' + pytest.skip() gdaltest.runexternal(test_cli_utilities.get_gdal_translate_path() + ' -of VRT -expand rgba ../gdrivers/data/bug407.gif tmp/test17.vrt') ds = gdal.Open('tmp/test17.vrt') - if ds is None: - return 'fail' + assert ds is not None - if ds.GetRasterBand(1).GetRasterColorInterpretation() != gdal.GCI_RedBand: - gdaltest.post_reason('Bad color interpretation') - return 'fail' + assert ds.GetRasterBand(1).GetRasterColorInterpretation() == gdal.GCI_RedBand, \ + 'Bad color interpretation' - if ds.GetRasterBand(2).GetRasterColorInterpretation() != gdal.GCI_GreenBand: - gdaltest.post_reason('Bad color interpretation') - return 'fail' + assert ds.GetRasterBand(2).GetRasterColorInterpretation() == gdal.GCI_GreenBand, \ + 'Bad color interpretation' - if ds.GetRasterBand(3).GetRasterColorInterpretation() != gdal.GCI_BlueBand: - gdaltest.post_reason('Bad color interpretation') - return 'fail' + assert ds.GetRasterBand(3).GetRasterColorInterpretation() == gdal.GCI_BlueBand, \ + 'Bad color interpretation' - if ds.GetRasterBand(4).GetRasterColorInterpretation() != gdal.GCI_AlphaBand: - gdaltest.post_reason('Bad color interpretation') - return 'fail' + assert ds.GetRasterBand(4).GetRasterColorInterpretation() == gdal.GCI_AlphaBand, \ + 'Bad color interpretation' - if ds.GetRasterBand(1).Checksum() != 20615: - gdaltest.post_reason('Bad checksum') - return 'fail' + assert ds.GetRasterBand(1).Checksum() == 20615, 'Bad checksum' - if ds.GetRasterBand(2).Checksum() != 59147: - gdaltest.post_reason('Bad checksum') - return 'fail' + assert ds.GetRasterBand(2).Checksum() == 59147, 'Bad checksum' - if ds.GetRasterBand(3).Checksum() != 63052: - gdaltest.post_reason('Bad checksum') - return 'fail' + assert ds.GetRasterBand(3).Checksum() == 63052, 'Bad checksum' - if ds.GetRasterBand(4).Checksum() != 63052: - print(ds.GetRasterBand(3).Checksum()) - gdaltest.post_reason('Bad checksum') - return 'fail' + assert ds.GetRasterBand(4).Checksum() == 63052, 'Bad checksum' ds = None - return 'success' - ############################################################################### # Test translation of a VRT made of VRT def test_gdal_translate_18(): if test_cli_utilities.get_gdal_translate_path() is None: - return 'skip' + pytest.skip() gdaltest.runexternal(test_cli_utilities.get_gdal_translate_path() + ' ../gcore/data/8bit_pal.bmp -of VRT tmp/test18_1.vrt') gdaltest.runexternal(test_cli_utilities.get_gdal_translate_path() + ' tmp/test18_1.vrt -expand rgb -of VRT tmp/test18_2.vrt') (_, ret_stderr) = gdaltest.runexternal_out_and_err(test_cli_utilities.get_gdal_translate_path() + ' tmp/test18_2.vrt tmp/test18_2.tif') # Check that all datasets are closed - if ret_stderr.find('Open GDAL Datasets') != -1: - return 'fail' + assert ret_stderr.find('Open GDAL Datasets') == -1 ds = gdal.Open('tmp/test18_2.tif') - if ds is None: - return 'fail' + assert ds is not None - if ds.GetRasterBand(1).Checksum() != 4672: - gdaltest.post_reason('Bad checksum') - return 'fail' + assert ds.GetRasterBand(1).Checksum() == 4672, 'Bad checksum' ds = None - return 'success' - ############################################################################### # Test -expand rgba on a color indexed dataset with an alpha band def test_gdal_translate_19(): if test_cli_utilities.get_gdal_translate_path() is None: - return 'skip' + pytest.skip() ds = gdal.GetDriverByName('GTiff').Create('tmp/test_gdal_translate_19_src.tif', 1, 1, 2) ct = gdal.ColorTable() @@ -539,25 +416,14 @@ def test_gdal_translate_19(): gdaltest.runexternal(test_cli_utilities.get_gdal_translate_path() + ' -expand rgba tmp/test_gdal_translate_19_src.tif tmp/test_gdal_translate_19_dst.tif') ds = gdal.Open('tmp/test_gdal_translate_19_dst.tif') - if ds is None: - return 'fail' - - if ds.GetRasterBand(1).Checksum() != 1: - gdaltest.post_reason('Bad checksum for band 1') - return 'fail' - if ds.GetRasterBand(2).Checksum() != 2: - gdaltest.post_reason('Bad checksum for band 2') - return 'fail' - if ds.GetRasterBand(3).Checksum() != 3: - gdaltest.post_reason('Bad checksum for band 3') - return 'fail' - if ds.GetRasterBand(4).Checksum() != 250 % 7: - gdaltest.post_reason('Bad checksum for band 4') - return 'fail' + assert ds is not None - ds = None + assert ds.GetRasterBand(1).Checksum() == 1, 'Bad checksum for band 1' + assert ds.GetRasterBand(2).Checksum() == 2, 'Bad checksum for band 2' + assert ds.GetRasterBand(3).Checksum() == 3, 'Bad checksum for band 3' + assert ds.GetRasterBand(4).Checksum() == 250 % 7, 'Bad checksum for band 4' - return 'success' + ds = None ############################################################################### # Test -a_nodata None @@ -565,24 +431,19 @@ def test_gdal_translate_19(): def test_gdal_translate_20(): if test_cli_utilities.get_gdal_translate_path() is None: - return 'skip' + pytest.skip() gdaltest.runexternal(test_cli_utilities.get_gdal_translate_path() + ' -a_nodata 255 ../gcore/data/byte.tif tmp/test_gdal_translate_20_src.tif') gdaltest.runexternal(test_cli_utilities.get_gdal_translate_path() + ' -a_nodata None tmp/test_gdal_translate_20_src.tif tmp/test_gdal_translate_20_dst.tif') ds = gdal.Open('tmp/test_gdal_translate_20_dst.tif') - if ds is None: - return 'fail' + assert ds is not None nodata = ds.GetRasterBand(1).GetNoDataValue() - if nodata is not None: - print(nodata) - return 'fail' + assert nodata is None ds = None - return 'success' - ############################################################################### # Test that statistics are copied only when appropriate (#3889) # in that case, they must be copied @@ -590,7 +451,7 @@ def test_gdal_translate_20(): def test_gdal_translate_21(): if test_cli_utilities.get_gdal_translate_path() is None: - return 'skip' + pytest.skip() gdaltest.runexternal(test_cli_utilities.get_gdal_translate_path() + ' -of HFA ../gcore/data/utmsmall.img tmp/test_gdal_translate_21.img') @@ -598,16 +459,10 @@ def test_gdal_translate_21(): md = ds.GetRasterBand(1).GetMetadata() ds = None - if md['STATISTICS_MINIMUM'] != '8': - gdaltest.post_reason('STATISTICS_MINIMUM is wrong.') - print(md['STATISTICS_MINIMUM']) - return 'fail' + assert md['STATISTICS_MINIMUM'] == '8', 'STATISTICS_MINIMUM is wrong.' - if md['STATISTICS_HISTOBINVALUES'] != '0|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|': - gdaltest.post_reason('STATISTICS_HISTOBINVALUES is wrong.') - return 'fail' - - return 'success' + assert md['STATISTICS_HISTOBINVALUES'] == '0|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|', \ + 'STATISTICS_HISTOBINVALUES is wrong.' ############################################################################### # Test that statistics are copied only when appropriate (#3889) @@ -616,7 +471,7 @@ def test_gdal_translate_21(): def test_gdal_translate_22(): if test_cli_utilities.get_gdal_translate_path() is None: - return 'skip' + pytest.skip() gdaltest.runexternal(test_cli_utilities.get_gdal_translate_path() + ' -of HFA -scale 0 255 0 128 ../gcore/data/utmsmall.img tmp/test_gdal_translate_22.img') @@ -624,15 +479,11 @@ def test_gdal_translate_22(): md = ds.GetRasterBand(1).GetMetadata() ds = None - if 'STATISTICS_MINIMUM' in md: - gdaltest.post_reason('did not expected a STATISTICS_MINIMUM value.') - return 'fail' - - if 'STATISTICS_HISTOBINVALUES' in md: - gdaltest.post_reason( 'did not expected a STATISTICS_HISTOBINVALUES value.' ) - return 'fail' + assert 'STATISTICS_MINIMUM' not in md, \ + 'did not expected a STATISTICS_MINIMUM value.' - return 'success' + assert 'STATISTICS_HISTOBINVALUES' not in md, \ + 'did not expected a STATISTICS_HISTOBINVALUES value.' ############################################################################### # Test -stats option (#3889) @@ -640,7 +491,7 @@ def test_gdal_translate_22(): def test_gdal_translate_23(): if test_cli_utilities.get_gdal_translate_path() is None: - return 'skip' + pytest.skip() gdaltest.runexternal(test_cli_utilities.get_gdal_translate_path() + ' -stats ../gcore/data/byte.tif tmp/test_gdal_translate_23.tif') @@ -648,72 +499,54 @@ def test_gdal_translate_23(): md = ds.GetRasterBand(1).GetMetadata() ds = None - if md['STATISTICS_MINIMUM'] != '74': - gdaltest.post_reason('STATISTICS_MINIMUM is wrong.') - print(md['STATISTICS_MINIMUM']) - return 'fail' + assert md['STATISTICS_MINIMUM'] == '74', 'STATISTICS_MINIMUM is wrong.' - try: + with pytest.raises(OSError, message='did not expect .aux.xml file presence'): os.stat('tmp/test_gdal_translate_23.tif.aux.xml') - gdaltest.post_reason('did not expect .aux.xml file presence') - return 'fail' - except OSError: - pass + gdal.Unlink('../gcore/data/byte.tif.aux.xml') - return 'success' - ############################################################################### # Test -srcwin option when partially outside def test_gdal_translate_24(): if test_cli_utilities.get_gdal_translate_path() is None: - return 'skip' + pytest.skip() gdaltest.runexternal(test_cli_utilities.get_gdal_translate_path() + ' -q -srcwin -10 -10 40 40 ../gcore/data/byte.tif tmp/test_gdal_translate_24.tif') ds = gdal.Open('tmp/test_gdal_translate_24.tif') - if ds is None: - return 'fail' + assert ds is not None cs = ds.GetRasterBand(1).Checksum() - if cs != 4620: - gdaltest.post_reason('Bad checksum') - print(cs) - return 'fail' + assert cs == 4620, 'Bad checksum' ds = None - return 'success' - ############################################################################### # Test -norat def test_gdal_translate_25(): if test_cli_utilities.get_gdal_translate_path() is None: - return 'skip' + pytest.skip() gdaltest.runexternal(test_cli_utilities.get_gdal_translate_path() + ' -q ../gdrivers/data/int.img tmp/test_gdal_translate_25.tif -norat') ds = gdal.Open('tmp/test_gdal_translate_25.tif') - if ds.GetRasterBand(1).GetDefaultRAT() is not None: - gdaltest.post_reason('RAT unexpected') - return 'fail' + assert ds.GetRasterBand(1).GetDefaultRAT() is None, 'RAT unexpected' ds = None - return 'success' - ############################################################################### # Test -a_nodata and -stats (#5463) def test_gdal_translate_26(): if test_cli_utilities.get_gdal_translate_path() is None: - return 'skip' + pytest.skip() f = open('tmp/test_gdal_translate_26.xyz', 'wb') f.write("""X Y Z @@ -725,28 +558,20 @@ def test_gdal_translate_26(): gdaltest.runexternal(test_cli_utilities.get_gdal_translate_path() + ' -a_nodata -999 -stats tmp/test_gdal_translate_26.xyz tmp/test_gdal_translate_26.tif') ds = gdal.Open('tmp/test_gdal_translate_26.tif') - if ds.GetRasterBand(1).GetMinimum() != 10: - gdaltest.post_reason('failure') - print(ds.GetRasterBand(1).GetMinimum()) - return 'fail' - if ds.GetRasterBand(1).GetNoDataValue() != -999: - gdaltest.post_reason('failure') - print(ds.GetRasterBand(1).GetNoDataValue()) - return 'fail' + assert ds.GetRasterBand(1).GetMinimum() == 10 + assert ds.GetRasterBand(1).GetNoDataValue() == -999 ds = None - return 'success' - ############################################################################### # Test that we don't preserve statistics when we ought not. def test_gdal_translate_27(): if test_cli_utilities.get_gdal_translate_path() is None: - return 'skip' + pytest.skip() if test_cli_utilities.get_gdalinfo_path() is None: - return 'skip' + pytest.skip() f = open('tmp/test_gdal_translate_27.asc', 'wb') f.write("""ncols 2 @@ -764,181 +589,130 @@ def test_gdal_translate_27(): gdaltest.runexternal(test_cli_utilities.get_gdal_translate_path() + ' tmp/test_gdal_translate_27.asc tmp/test_gdal_translate_27.tif -ot UInt16') ds = gdal.Open('tmp/test_gdal_translate_27.tif') - if ds.GetRasterBand(1).GetMetadataItem('STATISTICS_MINIMUM') is None: - gdaltest.post_reason('failure') - return 'fail' + assert ds.GetRasterBand(1).GetMetadataItem('STATISTICS_MINIMUM') is not None ds = None # Translate to an output type that accepts 256 as maximum gdaltest.runexternal(test_cli_utilities.get_gdal_translate_path() + ' tmp/test_gdal_translate_27.asc tmp/test_gdal_translate_27.tif -ot Float64') ds = gdal.Open('tmp/test_gdal_translate_27.tif') - if ds.GetRasterBand(1).GetMetadataItem('STATISTICS_MINIMUM') is None: - gdaltest.post_reason('failure') - return 'fail' + assert ds.GetRasterBand(1).GetMetadataItem('STATISTICS_MINIMUM') is not None ds = None # Translate to an output type that doesn't accept 256 as maximum gdaltest.runexternal(test_cli_utilities.get_gdal_translate_path() + ' tmp/test_gdal_translate_27.asc tmp/test_gdal_translate_27.tif -ot Byte') ds = gdal.Open('tmp/test_gdal_translate_27.tif') - if ds.GetRasterBand(1).GetMetadataItem('STATISTICS_MINIMUM') is not None: - gdaltest.post_reason('failure') - return 'fail' + assert ds.GetRasterBand(1).GetMetadataItem('STATISTICS_MINIMUM') is None ds = None - return 'success' - ############################################################################### # Test -oo def test_gdal_translate_28(): if test_cli_utilities.get_gdal_translate_path() is None: - return 'skip' + pytest.skip() gdaltest.runexternal(test_cli_utilities.get_gdal_translate_path() + ' ../gdrivers/data/float64.asc tmp/test_gdal_translate_28.tif -oo datatype=float64') ds = gdal.Open('tmp/test_gdal_translate_28.tif') - if ds.GetRasterBand(1).DataType != gdal.GDT_Float64: - gdaltest.post_reason('failure') - return 'fail' + assert ds.GetRasterBand(1).DataType == gdal.GDT_Float64 ds = None - return 'success' - ############################################################################### # Test -r def test_gdal_translate_29(): if test_cli_utilities.get_gdal_translate_path() is None: - return 'skip' + pytest.skip() (_, err) = gdaltest.runexternal_out_and_err(test_cli_utilities.get_gdal_translate_path() + ' ../gcore/data/byte.tif tmp/test_gdal_translate_29.tif -outsize 50% 50% -r cubic') - if not (err is None or err == ''): - gdaltest.post_reason('got error/warning') - print(err) - return 'fail' + assert (err is None or err == ''), 'got error/warning' ds = gdal.Open('tmp/test_gdal_translate_29.tif') - if ds is None: - return 'fail' + assert ds is not None cs = ds.GetRasterBand(1).Checksum() - if cs != 1059: - gdaltest.post_reason('Bad checksum') - print(cs) - return 'fail' + assert cs == 1059, 'Bad checksum' ds = None (_, err) = gdaltest.runexternal_out_and_err(test_cli_utilities.get_gdal_translate_path() + ' ../gcore/data/byte.tif tmp/test_gdal_translate_29.vrt -outsize 50% 50% -r cubic -of VRT') - if not (err is None or err == ''): - gdaltest.post_reason('got error/warning') - print(err) - return 'fail' + assert (err is None or err == ''), 'got error/warning' (_, err) = gdaltest.runexternal_out_and_err(test_cli_utilities.get_gdal_translate_path() + ' tmp/test_gdal_translate_29.vrt tmp/test_gdal_translate_29.tif') - if not (err is None or err == ''): - gdaltest.post_reason('got error/warning') - print(err) - return 'fail' + assert (err is None or err == ''), 'got error/warning' ds = gdal.Open('tmp/test_gdal_translate_29.tif') - if ds is None: - return 'fail' + assert ds is not None cs = ds.GetRasterBand(1).Checksum() - if cs != 1059: - gdaltest.post_reason('Bad checksum') - print(cs) - return 'fail' + assert cs == 1059, 'Bad checksum' ds = None - return 'success' - ############################################################################### # Test -tr option def test_gdal_translate_30(): if test_cli_utilities.get_gdal_translate_path() is None: - return 'skip' + pytest.skip() gdaltest.runexternal(test_cli_utilities.get_gdal_translate_path() + ' -tr 30 30 ../gcore/data/byte.tif tmp/test_gdal_translate_30.tif') ds = gdal.Open('tmp/test_gdal_translate_30.tif') - if ds is None: - return 'fail' + assert ds is not None cs = ds.GetRasterBand(1).Checksum() - if cs != 18784: - print(cs) - gdaltest.post_reason('Bad checksum') - return 'fail' + assert cs == 18784, 'Bad checksum' ds = None - return 'success' - ############################################################################### # Test -projwin_srs option def test_gdal_translate_31(): if test_cli_utilities.get_gdal_translate_path() is None: - return 'skip' + pytest.skip() gdaltest.runexternal(test_cli_utilities.get_gdal_translate_path() + ' -projwin_srs EPSG:4267 -projwin -117.641168620797 33.9023526904262 -117.628110837847 33.8915970129613 ../gcore/data/byte.tif tmp/test_gdal_translate_31.tif') ds = gdal.Open('tmp/test_gdal_translate_31.tif') - if ds is None: - return 'fail' + assert ds is not None - if ds.GetRasterBand(1).Checksum() != 4672: - gdaltest.post_reason('Bad checksum') - return 'fail' + assert ds.GetRasterBand(1).Checksum() == 4672, 'Bad checksum' - if not gdaltest.geotransform_equals(gdal.Open('../gcore/data/byte.tif').GetGeoTransform(), ds.GetGeoTransform(), 1e-6): - gdaltest.post_reason('Bad geotransform') - return 'fail' + assert gdaltest.geotransform_equals(gdal.Open('../gcore/data/byte.tif').GetGeoTransform(), ds.GetGeoTransform(), 1e-6), \ + 'Bad geotransform' ds = None - return 'success' - ############################################################################### # Test subsetting a file with a RPC def test_gdal_translate_32(): if test_cli_utilities.get_gdal_translate_path() is None: - return 'skip' + pytest.skip() gdaltest.runexternal(test_cli_utilities.get_gdal_translate_path() + ' ../gcore/data/byte_rpc.tif tmp/test_gdal_translate_32.tif -srcwin 1 2 13 14 -outsize 150% 300%') ds = gdal.Open('tmp/test_gdal_translate_32.tif') md = ds.GetMetadata('RPC') - if abs(float(md['LINE_OFF']) - 47496) > 1e-5 or \ - abs(float(md['LINE_SCALE']) - 47502) > 1e-5 or \ - abs(float(md['SAMP_OFF']) - 19676.6923076923) > 1e-5 or \ - abs(float(md['SAMP_SCALE']) - 19678.1538461538) > 1e-5: - gdaltest.post_reason('fail') - print(md) - return 'fail' + assert (abs(float(md['LINE_OFF']) - 47496) <= 1e-5 and \ + abs(float(md['LINE_SCALE']) - 47502) <= 1e-5 and \ + abs(float(md['SAMP_OFF']) - 19676.6923076923) <= 1e-5 and \ + abs(float(md['SAMP_SCALE']) - 19678.1538461538) <= 1e-5) gdaltest.runexternal_out_and_err(test_cli_utilities.get_gdal_translate_path() + ' ../gcore/data/byte_rpc.tif tmp/test_gdal_translate_32.tif -srcwin -10 -5 20 20') ds = gdal.Open('tmp/test_gdal_translate_32.tif') md = ds.GetMetadata('RPC') - if abs(float(md['LINE_OFF']) - (15834 - -5)) > 1e-5 or \ - abs(float(md['LINE_SCALE']) - 15834) > 1e-5 or \ - abs(float(md['SAMP_OFF']) - (13464 - -10)) > 1e-5 or \ - abs(float(md['SAMP_SCALE']) - 13464) > 1e-5: - gdaltest.post_reason('fail') - print(md) - return 'fail' - - return 'success' + assert (abs(float(md['LINE_OFF']) - (15834 - -5)) <= 1e-5 and \ + abs(float(md['LINE_SCALE']) - 15834) <= 1e-5 and \ + abs(float(md['SAMP_OFF']) - (13464 - -10)) <= 1e-5 and \ + abs(float(md['SAMP_SCALE']) - 13464) <= 1e-5) ############################################################################### # Test -outsize option in auto mode @@ -946,34 +720,24 @@ def test_gdal_translate_32(): def test_gdal_translate_33(): if test_cli_utilities.get_gdal_translate_path() is None: - return 'skip' + pytest.skip() gdaltest.runexternal(test_cli_utilities.get_gdal_translate_path() + ' -outsize 100 0 ../gdrivers/data/small_world.tif tmp/test_gdal_translate_33.tif') ds = gdal.Open('tmp/test_gdal_translate_33.tif') - if ds.RasterYSize != 50: - gdaltest.post_reason('fail') - print(ds.RasterYSize) - return 'fail' + assert ds.RasterYSize == 50 ds = None gdaltest.runexternal(test_cli_utilities.get_gdal_translate_path() + ' -outsize 0 100 ../gdrivers/data/small_world.tif tmp/test_gdal_translate_33.tif') ds = gdal.Open('tmp/test_gdal_translate_33.tif') - if ds.RasterXSize != 200: - gdaltest.post_reason('fail') - print(ds.RasterYSize) - return 'fail' + assert ds.RasterXSize == 200, ds.RasterYSize ds = None os.unlink('tmp/test_gdal_translate_33.tif') (_, err) = gdaltest.runexternal_out_and_err(test_cli_utilities.get_gdal_translate_path() + ' -outsize 0 0 ../gdrivers/data/small_world.tif tmp/test_gdal_translate_33.tif') - if err.find('-outsize 0 0 invalid') < 0: - gdaltest.post_reason('fail') - return 'fail' - - return 'success' + assert err.find('-outsize 0 0 invalid') >= 0 ############################################################################### # Test NBITS is preserved @@ -981,143 +745,98 @@ def test_gdal_translate_33(): def test_gdal_translate_34(): if test_cli_utilities.get_gdal_translate_path() is None: - return 'skip' + pytest.skip() gdaltest.runexternal(test_cli_utilities.get_gdal_translate_path() + ' ../gcore/data/oddsize1bit.tif tmp/test_gdal_translate_34.vrt -of VRT -mo FOO=BAR') ds = gdal.Open('tmp/test_gdal_translate_34.vrt') - if ds.GetRasterBand(1).GetMetadataItem('NBITS', 'IMAGE_STRUCTURE') != '1': - gdaltest.post_reason('fail') - return 'fail' + assert ds.GetRasterBand(1).GetMetadataItem('NBITS', 'IMAGE_STRUCTURE') == '1' ds = None os.unlink('tmp/test_gdal_translate_34.vrt') - return 'success' - ############################################################################### # Test various errors (missing source or dest...) def test_gdal_translate_35(): if test_cli_utilities.get_gdal_translate_path() is None: - return 'skip' + pytest.skip() (_, err) = gdaltest.runexternal_out_and_err(test_cli_utilities.get_gdal_translate_path()) - if err.find('No source dataset specified') < 0: - gdaltest.post_reason('fail') - print(err) - return 'fail' + assert err.find('No source dataset specified') >= 0 (_, err) = gdaltest.runexternal_out_and_err(test_cli_utilities.get_gdal_translate_path() + ' ../gcore/data/byte.tif') - if err.find('No target dataset specified') < 0: - gdaltest.post_reason('fail') - print(err) - return 'fail' + assert err.find('No target dataset specified') >= 0 (_, err) = gdaltest.runexternal_out_and_err(test_cli_utilities.get_gdal_translate_path() + ' /non_existing_path/non_existing.tif /vsimem/out.tif') - if err.find('does not exist in the file system') < 0 and err.find('No such file or directory') < 0: - gdaltest.post_reason('fail') - print(err) - return 'fail' + assert err.find('does not exist in the file system') >= 0 or err.find('No such file or directory') >= 0 (_, err) = gdaltest.runexternal_out_and_err(test_cli_utilities.get_gdal_translate_path() + ' ../gcore/data/byte.tif /non_existing_path/non_existing.tif') - if err.find('Attempt to create new tiff file') < 0: - gdaltest.post_reason('fail') - print(err) - return 'fail' - - return 'success' + assert err.find('Attempt to create new tiff file') >= 0 ############################################################################### # Test RAT is copied from hfa to gtiff - continuous/athematic def test_gdal_translate_36(): if test_cli_utilities.get_gdal_translate_path() is None: - return 'skip' + pytest.skip() gdaltest.runexternal(test_cli_utilities.get_gdal_translate_path() + ' -of gtiff data/onepixelcontinuous.img tmp/test_gdal_translate_36.tif') ds = gdal.Open('tmp/test_gdal_translate_36.tif') - if ds is None: - return 'fail' + assert ds is not None rat = ds.GetRasterBand(1).GetDefaultRAT() - if not rat: - gdaltest.post_reason('Did not get RAT') - return 'fail' + assert rat, 'Did not get RAT' - if not rat.GetRowCount() == 256: - gdaltest.post_reason('RAT has incorrect row count') - return 'fail' + assert rat.GetRowCount() == 256, 'RAT has incorrect row count' - if rat.GetTableType() != 1: - gdaltest.post_reason('RAT not athematic') - return 'fail' + assert rat.GetTableType() == 1, 'RAT not athematic' rat = None ds = None - return 'success' - ############################################################################### # Test RAT is copied from hfa to gtiff - thematic def test_gdal_translate_37(): if test_cli_utilities.get_gdal_translate_path() is None: - return 'skip' + pytest.skip() gdaltest.runexternal(test_cli_utilities.get_gdal_translate_path() + ' -q -of gtiff data/onepixelthematic.img tmp/test_gdal_translate_37.tif') ds = gdal.Open('tmp/test_gdal_translate_37.tif') - if ds is None: - return 'fail' + assert ds is not None rat = ds.GetRasterBand(1).GetDefaultRAT() - if not rat: - gdaltest.post_reason('Did not get RAT') - return 'fail' + assert rat, 'Did not get RAT' - if not rat.GetRowCount() == 256: - gdaltest.post_reason('RAT has incorrect row count') - return 'fail' + assert rat.GetRowCount() == 256, 'RAT has incorrect row count' - if rat.GetTableType() != 0: - gdaltest.post_reason('RAT not thematic') - return 'fail' + assert rat.GetTableType() == 0, 'RAT not thematic' rat = None ds = None - return 'success' - # Test RAT is copied round trip back to hfa def test_gdal_translate_38(): if test_cli_utilities.get_gdal_translate_path() is None: - return 'skip' + pytest.skip() gdaltest.runexternal(test_cli_utilities.get_gdal_translate_path() + ' -q -of hfa tmp/test_gdal_translate_37.tif tmp/test_gdal_translate_38.img') ds = gdal.Open('tmp/test_gdal_translate_38.img') - if ds is None: - return 'fail' + assert ds is not None rat = ds.GetRasterBand(1).GetDefaultRAT() - if not rat: - gdaltest.post_reason('Did not get RAT') - return 'fail' + assert rat, 'Did not get RAT' - if not rat.GetRowCount() == 256: - gdaltest.post_reason('RAT has incorrect row count') - return 'fail' + assert rat.GetRowCount() == 256, 'RAT has incorrect row count' - if rat.GetTableType() != 0: - gdaltest.post_reason('RAT not thematic') - return 'fail' + assert rat.GetTableType() == 0, 'RAT not thematic' rat = None ds = None - return 'success' - ############################################################################### # Cleanup @@ -1246,56 +965,7 @@ def test_gdal_translate_cleanup(): gdal.GetDriverByName('HFA').Delete('tmp/test_gdal_translate_38.img') except: pass - return 'success' - - -gdaltest_list = [ - test_gdal_translate_1, - test_gdal_translate_2, - test_gdal_translate_3, - test_gdal_translate_4, - test_gdal_translate_5, - test_gdal_translate_6, - test_gdal_translate_7, - test_gdal_translate_8, - test_gdal_translate_9, - test_gdal_translate_10, - test_gdal_translate_11, - test_gdal_translate_12, - test_gdal_translate_13, - test_gdal_translate_14, - test_gdal_translate_15, - test_gdal_translate_16, - test_gdal_translate_17, - test_gdal_translate_18, - test_gdal_translate_19, - test_gdal_translate_20, - test_gdal_translate_21, - test_gdal_translate_22, - test_gdal_translate_23, - test_gdal_translate_24, - test_gdal_translate_25, - test_gdal_translate_26, - test_gdal_translate_27, - test_gdal_translate_28, - test_gdal_translate_29, - test_gdal_translate_30, - test_gdal_translate_31, - test_gdal_translate_32, - test_gdal_translate_33, - test_gdal_translate_34, - test_gdal_translate_35, - test_gdal_translate_36, - test_gdal_translate_37, - test_gdal_translate_38, - test_gdal_translate_cleanup -] - - -if __name__ == '__main__': - - gdaltest.setup_run('test_gdal_translate') - - gdaltest.run_tests(gdaltest_list) - - sys.exit(gdaltest.summarize()) + + + + diff --git a/autotest/utilities/test_gdal_translate_lib.py b/autotest/utilities/test_gdal_translate_lib.py index 1f8422e5ab8c..48d471b57fdb 100755 --- a/autotest/utilities/test_gdal_translate_lib.py +++ b/autotest/utilities/test_gdal_translate_lib.py @@ -29,13 +29,12 @@ # DEALINGS IN THE SOFTWARE. ############################################################################### -import sys import os -sys.path.append('../pymod') from osgeo import gdal import gdaltest +import pytest ############################################################################### # Simple test @@ -46,28 +45,19 @@ def test_gdal_translate_lib_1(): ds = gdal.Open('../gcore/data/byte.tif') ds = gdal.Translate('tmp/test1.tif', ds) - if ds is None: - gdaltest.post_reason('got error/warning') - return 'fail' + assert ds is not None, 'got error/warning' - if ds.GetRasterBand(1).Checksum() != 4672: - gdaltest.post_reason('Bad checksum') - return 'fail' + assert ds.GetRasterBand(1).Checksum() == 4672, 'Bad checksum' ds = None ds = gdal.Open('tmp/test1.tif') - if ds is None: - return 'fail' + assert ds is not None - if ds.GetRasterBand(1).Checksum() != 4672: - gdaltest.post_reason('Bad checksum') - return 'fail' + assert ds.GetRasterBand(1).Checksum() == 4672, 'Bad checksum' ds = None - return 'success' - ############################################################################### # Test format option and callback @@ -83,21 +73,14 @@ def test_gdal_translate_lib_2(): src_ds = gdal.Open('../gcore/data/byte.tif') tab = [0] ds = gdal.Translate('tmp/test2.tif', src_ds, format='GTiff', callback=mycallback, callback_data=tab) - if ds is None: - return 'fail' + assert ds is not None - if ds.GetRasterBand(1).Checksum() != 4672: - gdaltest.post_reason('Bad checksum') - return 'fail' + assert ds.GetRasterBand(1).Checksum() == 4672, 'Bad checksum' - if tab[0] != 1.0: - gdaltest.post_reason('Bad percentage') - return 'fail' + assert tab[0] == 1.0, 'Bad percentage' ds = None - return 'success' - ############################################################################### # Test outputType option @@ -106,21 +89,14 @@ def test_gdal_translate_lib_3(): ds = gdal.Open('../gcore/data/byte.tif') ds = gdal.Translate('tmp/test3.tif', ds, outputType=gdal.GDT_Int16) - if ds is None: - return 'fail' + assert ds is not None - if ds.GetRasterBand(1).DataType != gdal.GDT_Int16: - gdaltest.post_reason('Bad data type') - return 'fail' + assert ds.GetRasterBand(1).DataType == gdal.GDT_Int16, 'Bad data type' - if ds.GetRasterBand(1).Checksum() != 4672: - gdaltest.post_reason('Bad checksum') - return 'fail' + assert ds.GetRasterBand(1).Checksum() == 4672, 'Bad checksum' ds = None - return 'success' - ############################################################################### # Test bandList option @@ -130,26 +106,16 @@ def test_gdal_translate_lib_4(): ds = gdal.Open('../gcore/data/rgbsmall.tif') ds = gdal.Translate('tmp/test4.tif', ds, bandList=[3, 2, 1]) - if ds is None: - gdaltest.post_reason('got error/warning') - return 'fail' + assert ds is not None, 'got error/warning' - if ds.GetRasterBand(1).Checksum() != 21349: - gdaltest.post_reason('Bad checksum') - return 'fail' + assert ds.GetRasterBand(1).Checksum() == 21349, 'Bad checksum' - if ds.GetRasterBand(2).Checksum() != 21053: - gdaltest.post_reason('Bad checksum') - return 'fail' + assert ds.GetRasterBand(2).Checksum() == 21053, 'Bad checksum' - if ds.GetRasterBand(3).Checksum() != 21212: - gdaltest.post_reason('Bad checksum') - return 'fail' + assert ds.GetRasterBand(3).Checksum() == 21212, 'Bad checksum' ds = None - return 'success' - ############################################################################### # Test rgbExpand option @@ -158,37 +124,25 @@ def test_gdal_translate_lib_5(): ds = gdal.Open('../gdrivers/data/bug407.gif') ds = gdal.Translate('tmp/test5.tif', ds, rgbExpand='rgb') - if ds is None: - return 'fail' + assert ds is not None - if ds.GetRasterBand(1).GetRasterColorInterpretation() != gdal.GCI_RedBand: - gdaltest.post_reason('Bad color interpretation') - return 'fail' + assert ds.GetRasterBand(1).GetRasterColorInterpretation() == gdal.GCI_RedBand, \ + 'Bad color interpretation' - if ds.GetRasterBand(2).GetRasterColorInterpretation() != gdal.GCI_GreenBand: - gdaltest.post_reason('Bad color interpretation') - return 'fail' + assert ds.GetRasterBand(2).GetRasterColorInterpretation() == gdal.GCI_GreenBand, \ + 'Bad color interpretation' - if ds.GetRasterBand(3).GetRasterColorInterpretation() != gdal.GCI_BlueBand: - gdaltest.post_reason('Bad color interpretation') - return 'fail' + assert ds.GetRasterBand(3).GetRasterColorInterpretation() == gdal.GCI_BlueBand, \ + 'Bad color interpretation' - if ds.GetRasterBand(1).Checksum() != 20615: - gdaltest.post_reason('Bad checksum') - return 'fail' + assert ds.GetRasterBand(1).Checksum() == 20615, 'Bad checksum' - if ds.GetRasterBand(2).Checksum() != 59147: - gdaltest.post_reason('Bad checksum') - return 'fail' + assert ds.GetRasterBand(2).Checksum() == 59147, 'Bad checksum' - if ds.GetRasterBand(3).Checksum() != 63052: - gdaltest.post_reason('Bad checksum') - return 'fail' + assert ds.GetRasterBand(3).Checksum() == 63052, 'Bad checksum' ds = None - return 'success' - ############################################################################### # Test oXSizePixel and oYSizePixel option @@ -197,17 +151,12 @@ def test_gdal_translate_lib_6(): ds = gdal.Open('../gcore/data/byte.tif') ds = gdal.Translate('tmp/test6.tif', ds, width=40, height=40) - if ds is None: - return 'fail' + assert ds is not None - if ds.GetRasterBand(1).Checksum() != 18784: - gdaltest.post_reason('Bad checksum') - return 'fail' + assert ds.GetRasterBand(1).Checksum() == 18784, 'Bad checksum' ds = None - return 'success' - ############################################################################### # Test oXSizePct and oYSizePct option @@ -216,17 +165,12 @@ def test_gdal_translate_lib_7(): ds = gdal.Open('../gcore/data/byte.tif') ds = gdal.Translate('tmp/test7.tif', ds, widthPct=200.0, heightPct=200.0) - if ds is None: - return 'fail' + assert ds is not None - if ds.GetRasterBand(1).Checksum() != 18784: - gdaltest.post_reason('Bad checksum') - return 'fail' + assert ds.GetRasterBand(1).Checksum() == 18784, 'Bad checksum' ds = None - return 'success' - ############################################################################### # Test outputSRS and GCPs options @@ -236,26 +180,17 @@ def test_gdal_translate_lib_8(): gcpList = [gdal.GCP(440720.000, 3751320.000, 0, 0, 0), gdal.GCP(441920.000, 3751320.000, 0, 20, 0), gdal.GCP(441920.000, 3750120.000, 0, 20, 20), gdal.GCP(440720.000, 3750120.000, 0, 0, 20)] ds = gdal.Open('../gcore/data/byte.tif') ds = gdal.Translate('tmp/test8.tif', ds, outputSRS='EPSG:26711', GCPs=gcpList) - if ds is None: - return 'fail' + assert ds is not None - if ds.GetRasterBand(1).Checksum() != 4672: - gdaltest.post_reason('Bad checksum') - return 'fail' + assert ds.GetRasterBand(1).Checksum() == 4672, 'Bad checksum' gcps = ds.GetGCPs() - if len(gcps) != 4: - gdaltest.post_reason('GCP count wrong.') - return 'fail' + assert len(gcps) == 4, 'GCP count wrong.' - if ds.GetGCPProjection().find('26711') == -1: - gdaltest.post_reason('Bad GCP projection.') - return 'fail' + assert ds.GetGCPProjection().find('26711') != -1, 'Bad GCP projection.' ds = None - return 'success' - ############################################################################### # Test nodata option @@ -264,17 +199,12 @@ def test_gdal_translate_lib_9(): ds = gdal.Open('../gcore/data/byte.tif') ds = gdal.Translate('tmp/test9.tif', ds, noData=1) - if ds is None: - return 'fail' + assert ds is not None - if ds.GetRasterBand(1).GetNoDataValue() != 1: - gdaltest.post_reason('Bad nodata value') - return 'fail' + assert ds.GetRasterBand(1).GetNoDataValue() == 1, 'Bad nodata value' ds = None - return 'success' - ############################################################################### # Test srcWin option @@ -283,17 +213,12 @@ def test_gdal_translate_lib_10(): ds = gdal.Open('../gcore/data/byte.tif') ds = gdal.Translate('tmp/test10.tif', ds, srcWin=[0, 0, 1, 1]) - if ds is None: - return 'fail' + assert ds is not None - if ds.GetRasterBand(1).Checksum() != 2: - gdaltest.post_reason('Bad checksum') - return 'fail' + assert ds.GetRasterBand(1).Checksum() == 2, 'Bad checksum' ds = None - return 'success' - ############################################################################### # Test projWin option @@ -302,21 +227,15 @@ def test_gdal_translate_lib_11(): ds = gdal.Open('../gcore/data/byte.tif') ds = gdal.Translate('tmp/test11.tif', ds, projWin=[440720.000, 3751320.000, 441920.000, 3750120.000]) - if ds is None: - return 'fail' + assert ds is not None - if ds.GetRasterBand(1).Checksum() != 4672: - gdaltest.post_reason('Bad checksum') - return 'fail' + assert ds.GetRasterBand(1).Checksum() == 4672, 'Bad checksum' - if not gdaltest.geotransform_equals(gdal.Open('../gcore/data/byte.tif').GetGeoTransform(), ds.GetGeoTransform(), 1e-9): - gdaltest.post_reason('Bad geotransform') - return 'fail' + assert gdaltest.geotransform_equals(gdal.Open('../gcore/data/byte.tif').GetGeoTransform(), ds.GetGeoTransform(), 1e-9), \ + 'Bad geotransform' ds = None - return 'success' - ############################################################################### # Test outputBounds option @@ -325,21 +244,15 @@ def test_gdal_translate_lib_12(): ds = gdal.Open('../gcore/data/byte.tif') ds = gdal.Translate('tmp/test12.tif', ds, outputBounds=[440720.000, 3751320.000, 441920.000, 3750120.000]) - if ds is None: - return 'fail' + assert ds is not None - if ds.GetRasterBand(1).Checksum() != 4672: - gdaltest.post_reason('Bad checksum') - return 'fail' + assert ds.GetRasterBand(1).Checksum() == 4672, 'Bad checksum' - if not gdaltest.geotransform_equals(gdal.Open('../gcore/data/byte.tif').GetGeoTransform(), ds.GetGeoTransform(), 1e-9): - gdaltest.post_reason('Bad geotransform') - return 'fail' + assert gdaltest.geotransform_equals(gdal.Open('../gcore/data/byte.tif').GetGeoTransform(), ds.GetGeoTransform(), 1e-9), \ + 'Bad geotransform' ds = None - return 'success' - ############################################################################### # Test metadataOptions @@ -348,18 +261,13 @@ def test_gdal_translate_lib_13(): ds = gdal.Open('../gcore/data/byte.tif') ds = gdal.Translate('tmp/test13.tif', ds, metadataOptions=['TIFFTAG_DOCUMENTNAME=test13']) - if ds is None: - return 'fail' + assert ds is not None md = ds.GetMetadata() - if 'TIFFTAG_DOCUMENTNAME' not in md: - gdaltest.post_reason('Did not get TIFFTAG_DOCUMENTNAME') - return 'fail' + assert 'TIFFTAG_DOCUMENTNAME' in md, 'Did not get TIFFTAG_DOCUMENTNAME' ds = None - return 'success' - ############################################################################### # Test creationOptions @@ -368,18 +276,13 @@ def test_gdal_translate_lib_14(): ds = gdal.Open('../gcore/data/byte.tif') ds = gdal.Translate('tmp/test14.tif', ds, creationOptions=['COMPRESS=LZW']) - if ds is None: - return 'fail' + assert ds is not None md = ds.GetMetadata('IMAGE_STRUCTURE') - if 'COMPRESSION' not in md or md['COMPRESSION'] != 'LZW': - gdaltest.post_reason('Did not get COMPRESSION') - return 'fail' + assert 'COMPRESSION' in md and md['COMPRESSION'] == 'LZW', 'Did not get COMPRESSION' ds = None - return 'success' - ############################################################################### # Test internal wrappers @@ -400,8 +303,7 @@ def test_gdal_translate_lib_100(): except: pass - return 'success' - + ############################################################################### # Test behaviour with SIGNEDBYTE @@ -409,21 +311,15 @@ def test_gdal_translate_lib_100(): def test_gdal_translate_lib_101(): ds = gdal.Translate('/vsimem/test_gdal_translate_lib_101.tif', gdal.Open('../gcore/data/byte.tif'), creationOptions=['PIXELTYPE=SIGNEDBYTE'], noData='-128') - if ds.GetRasterBand(1).GetMetadataItem('PIXELTYPE', 'IMAGE_STRUCTURE') != 'SIGNEDBYTE': - gdaltest.post_reason('Did not get SIGNEDBYTE') - return 'fail' - if ds.GetRasterBand(1).GetNoDataValue() != -128: - gdaltest.post_reason('Did not get -128') - return 'fail' + assert ds.GetRasterBand(1).GetMetadataItem('PIXELTYPE', 'IMAGE_STRUCTURE') == 'SIGNEDBYTE', \ + 'Did not get SIGNEDBYTE' + assert ds.GetRasterBand(1).GetNoDataValue() == -128, 'Did not get -128' ds2 = gdal.Translate('/vsimem/test_gdal_translate_lib_101_2.tif', ds, noData=-127) - if ds2.GetRasterBand(1).GetNoDataValue() != -127: - gdaltest.post_reason('Did not get -127') - return 'fail' + assert ds2.GetRasterBand(1).GetNoDataValue() == -127, 'Did not get -127' ds = None ds2 = None gdal.Unlink('/vsimem/test_gdal_translate_lib_101.tif') gdal.Unlink('/vsimem/test_gdal_translate_lib_101_2.tif') - return 'success' ############################################################################### # Test -scale @@ -433,10 +329,7 @@ def test_gdal_translate_lib_102(): ds = gdal.Translate('', gdal.Open('../gcore/data/byte.tif'), format='MEM', scaleParams=[[0, 255, 0, 65535]], outputType=gdal.GDT_UInt16) result = ds.GetRasterBand(1).ComputeRasterMinMax(False) - if result != (19018.0, 65535.0): - gdaltest.post_reason('failure') - print(result) - return 'fail' + assert result == (19018.0, 65535.0) (approx_min, approx_max) = ds.GetRasterBand(1).ComputeRasterMinMax(True) ds2 = gdal.Translate('', ds, format='MEM', scaleParams=[[approx_min, approx_max]], outputType=gdal.GDT_Byte) @@ -446,13 +339,9 @@ def test_gdal_translate_lib_102(): ds2 = gdal.Translate('', ds, format='MEM', scaleParams=[[]], outputType=gdal.GDT_Byte) stats = ds2.GetRasterBand(1).ComputeStatistics(False) for i in range(4): - if abs(stats[i] - expected_stats[i]) > 1e-3: - gdaltest.post_reason('failure') - print(stats) - return 'fail' - - return 'success' + assert abs(stats[i] - expected_stats[i]) <= 1e-3 + ############################################################################### # Test that -projwin with nearest neighbor resampling uses integer source # pixel boundaries (#6610) @@ -461,18 +350,12 @@ def test_gdal_translate_lib_102(): def test_gdal_translate_lib_103(): ds = gdal.Translate('', '../gcore/data/byte.tif', format='MEM', projWin=[440730, 3751310, 441910, 3750140]) - if ds is None: - return 'fail' + assert ds is not None - if ds.GetRasterBand(1).Checksum() != 4672: - gdaltest.post_reason('Bad checksum') - return 'fail' + assert ds.GetRasterBand(1).Checksum() == 4672, 'Bad checksum' - if not gdaltest.geotransform_equals(gdal.Open('../gcore/data/byte.tif').GetGeoTransform(), ds.GetGeoTransform(), 1e-9): - gdaltest.post_reason('Bad geotransform') - return 'fail' - - return 'success' + assert gdaltest.geotransform_equals(gdal.Open('../gcore/data/byte.tif').GetGeoTransform(), ds.GetGeoTransform(), 1e-9), \ + 'Bad geotransform' ############################################################################### # Test translate with a MEM source to a anonymous VRT @@ -483,11 +366,7 @@ def test_gdal_translate_lib_104(): src_ds = gdal.GetDriverByName('MEM').Create('', 2, 2) src_ds.GetRasterBand(1).Fill(255) ds = gdal.Translate('', '../gcore/data/byte.tif', format='VRT', width=1, height=1) - if ds.GetRasterBand(1).Checksum() != 3: - gdaltest.post_reason('Bad checksum') - return 'fail' - - return 'success' + assert ds.GetRasterBand(1).Checksum() == 3, 'Bad checksum' ############################################################################### # Test GCPs propagation in "VRT path" @@ -497,20 +376,14 @@ def test_gdal_translate_lib_gcp_vrt_path(): src_ds = gdal.Open('../gcore/data/gcps.vrt') ds = gdal.Translate('', src_ds, format='MEM', metadataOptions=['FOO=BAR']) - if len(ds.GetGCPs()) != len(src_ds.GetGCPs()): - return 'fail' + assert len(ds.GetGCPs()) == len(src_ds.GetGCPs()) for i in range(len(src_ds.GetGCPs())): - if ds.GetGCPs()[i].GCPX != src_ds.GetGCPs()[i].GCPX: - return 'fail' - if ds.GetGCPs()[i].GCPY != src_ds.GetGCPs()[i].GCPY: - return 'fail' - if ds.GetGCPs()[i].GCPPixel != src_ds.GetGCPs()[i].GCPPixel: - return 'fail' - if ds.GetGCPs()[i].GCPLine != src_ds.GetGCPs()[i].GCPLine: - return 'fail' - - return 'success' + assert ds.GetGCPs()[i].GCPX == src_ds.GetGCPs()[i].GCPX + assert ds.GetGCPs()[i].GCPY == src_ds.GetGCPs()[i].GCPY + assert ds.GetGCPs()[i].GCPPixel == src_ds.GetGCPs()[i].GCPPixel + assert ds.GetGCPs()[i].GCPLine == src_ds.GetGCPs()[i].GCPLine + ############################################################################### # Test RPC propagation in "VRT path" @@ -519,10 +392,7 @@ def test_gdal_translate_lib_rcp_vrt_path(): src_ds = gdal.Open('../gcore/data/rpc.vrt') ds = gdal.Translate('', src_ds, format='MEM', metadataOptions=['FOO=BAR']) - if ds.GetMetadata('RPC') != src_ds.GetMetadata('RPC'): - return 'fail' - - return 'success' + assert ds.GetMetadata('RPC') == src_ds.GetMetadata('RPC') ############################################################################### # Test GeoLocation propagation in "VRT path" @@ -532,12 +402,9 @@ def test_gdal_translate_lib_geolocation_vrt_path(): src_ds = gdal.Open('../gcore/data/sstgeo.vrt') ds = gdal.Translate('/vsimem/temp.vrt', src_ds, format='VRT', metadataOptions=['FOO=BAR']) - if ds.GetMetadata('GEOLOCATION') != src_ds.GetMetadata('GEOLOCATION'): - return 'fail' + assert ds.GetMetadata('GEOLOCATION') == src_ds.GetMetadata('GEOLOCATION') gdal.Unlink('/vsimem/temp.vrt') - return 'success' - ############################################################################### # Test -colorinterp and -colorinterp_X @@ -548,52 +415,30 @@ def test_gdal_translate_lib_colorinterp(): # Less bands specified than available ds = gdal.Translate('', src_ds, options='-f MEM -colorinterp blue,gray') - if ds.GetRasterBand(1).GetColorInterpretation() != gdal.GCI_BlueBand: - gdaltest.post_reason('fail') - return 'fail' - if ds.GetRasterBand(2).GetColorInterpretation() != gdal.GCI_GrayIndex: - gdaltest.post_reason('fail') - return 'fail' - if ds.GetRasterBand(3).GetColorInterpretation() != gdal.GCI_BlueBand: - gdaltest.post_reason('fail') - return 'fail' + assert ds.GetRasterBand(1).GetColorInterpretation() == gdal.GCI_BlueBand + assert ds.GetRasterBand(2).GetColorInterpretation() == gdal.GCI_GrayIndex + assert ds.GetRasterBand(3).GetColorInterpretation() == gdal.GCI_BlueBand # More bands specified than available and a unknown color interpretation with gdaltest.error_handler(): ds = gdal.Translate('', src_ds, options='-f MEM -colorinterp alpha,red,undefined,foo') - if ds.GetRasterBand(1).GetColorInterpretation() != gdal.GCI_AlphaBand: - gdaltest.post_reason('fail') - return 'fail' - if ds.GetRasterBand(2).GetColorInterpretation() != gdal.GCI_RedBand: - gdaltest.post_reason('fail') - return 'fail' - if ds.GetRasterBand(3).GetColorInterpretation() != gdal.GCI_Undefined: - gdaltest.post_reason('fail') - return 'fail' + assert ds.GetRasterBand(1).GetColorInterpretation() == gdal.GCI_AlphaBand + assert ds.GetRasterBand(2).GetColorInterpretation() == gdal.GCI_RedBand + assert ds.GetRasterBand(3).GetColorInterpretation() == gdal.GCI_Undefined # Test colorinterp_ ds = gdal.Translate('', src_ds, options='-f MEM -colorinterp_2 alpha') - if ds.GetRasterBand(1).GetColorInterpretation() != gdal.GCI_RedBand: - gdaltest.post_reason('fail') - return 'fail' - if ds.GetRasterBand(2).GetColorInterpretation() != gdal.GCI_AlphaBand: - gdaltest.post_reason('fail') - return 'fail' - if ds.GetRasterBand(3).GetColorInterpretation() != gdal.GCI_BlueBand: - gdaltest.post_reason('fail') - return 'fail' + assert ds.GetRasterBand(1).GetColorInterpretation() == gdal.GCI_RedBand + assert ds.GetRasterBand(2).GetColorInterpretation() == gdal.GCI_AlphaBand + assert ds.GetRasterBand(3).GetColorInterpretation() == gdal.GCI_BlueBand # Test invalid colorinterp_ - try: + with pytest.raises(Exception): with gdaltest.error_handler(): gdal.Translate('', src_ds, options='-f MEM -colorinterp_0 alpha') - gdaltest.post_reason('fail') - return 'fail' - except: - pass - - return 'success' + + ############################################################################### # Cleanup @@ -609,41 +454,7 @@ def test_gdal_translate_lib_cleanup(): except OSError: pass - return 'success' - - -gdaltest_list = [ - test_gdal_translate_lib_1, - test_gdal_translate_lib_2, - test_gdal_translate_lib_3, - test_gdal_translate_lib_4, - test_gdal_translate_lib_5, - test_gdal_translate_lib_6, - test_gdal_translate_lib_7, - test_gdal_translate_lib_8, - test_gdal_translate_lib_9, - test_gdal_translate_lib_10, - test_gdal_translate_lib_11, - test_gdal_translate_lib_12, - test_gdal_translate_lib_13, - test_gdal_translate_lib_14, - test_gdal_translate_lib_100, - test_gdal_translate_lib_101, - test_gdal_translate_lib_102, - test_gdal_translate_lib_103, - test_gdal_translate_lib_104, - test_gdal_translate_lib_gcp_vrt_path, - test_gdal_translate_lib_rcp_vrt_path, - test_gdal_translate_lib_geolocation_vrt_path, - test_gdal_translate_lib_colorinterp, - test_gdal_translate_lib_cleanup -] - - -if __name__ == '__main__': - - gdaltest.setup_run('test_gdal_translate_lib') - - gdaltest.run_tests(gdaltest_list) - - sys.exit(gdaltest.summarize()) + + + + diff --git a/autotest/utilities/test_gdaladdo.py b/autotest/utilities/test_gdaladdo.py index 4e74fe1dae7d..f4465ac73633 100755 --- a/autotest/utilities/test_gdaladdo.py +++ b/autotest/utilities/test_gdaladdo.py @@ -29,17 +29,14 @@ # DEALINGS IN THE SOFTWARE. ############################################################################### -import sys import os import shutil - -sys.path.append('../pymod') -sys.path.append('../gcore') +import pytest from osgeo import gdal import gdaltest import test_cli_utilities -import tiff_ovr +from gcore import tiff_ovr ############################################################################### # Similar to tiff_ovr_1 @@ -47,16 +44,13 @@ def test_gdaladdo_1(): if test_cli_utilities.get_gdaladdo_path() is None: - return 'skip' + pytest.skip() shutil.copy('../gcore/data/mfloat32.vrt', 'tmp/mfloat32.vrt') shutil.copy('../gcore/data/float32.tif', 'tmp/float32.tif') (_, err) = gdaltest.runexternal_out_and_err(test_cli_utilities.get_gdaladdo_path() + ' tmp/mfloat32.vrt 2 4') - if not (err is None or err == ''): - gdaltest.post_reason('got error/warning') - print(err) - return 'fail' + assert (err is None or err == ''), 'got error/warning' ds = gdal.Open('tmp/mfloat32.vrt') ret = tiff_ovr.tiff_ovr_check(ds) @@ -74,7 +68,7 @@ def test_gdaladdo_1(): def test_gdaladdo_2(): if test_cli_utilities.get_gdaladdo_path() is None: - return 'skip' + pytest.skip() shutil.copyfile('../gcore/data/nodata_byte.tif', 'tmp/ovr5.tif') @@ -84,24 +78,19 @@ def test_gdaladdo_2(): cs = 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' + assert cs == exp_cs, 'got wrong overview checksum.' ds = None os.remove('tmp/ovr5.tif') - return 'success' - ############################################################################### # Test -ro def test_gdaladdo_3(): if test_cli_utilities.get_gdaladdo_path() is None: - return 'skip' + pytest.skip() gdal.Translate('tmp/test_gdaladdo_3.tif', '../gcore/data/nodata_byte.tif', options='-outsize 1024 1024') @@ -111,28 +100,23 @@ def test_gdaladdo_3(): cs = ds.GetRasterBand(1).GetOverview(0).Checksum() exp_cs = 20683 - if cs != exp_cs: - gdaltest.post_reason('got wrong overview checksum.') - print(exp_cs, cs) - return 'fail' + assert cs == exp_cs, 'got wrong overview checksum.' ds = None try: os.stat('tmp/test_gdaladdo_3.tif.ovr') except OSError: - gdaltest.post_reason('no external overview.') - return 'fail' - - return 'success' + pytest.fail('no external overview.') + ############################################################################### # Test -clean def test_gdaladdo_4(): if test_cli_utilities.get_gdaladdo_path() is None: - return 'skip' + pytest.skip() gdaltest.runexternal(test_cli_utilities.get_gdaladdo_path() + ' -clean tmp/test_gdaladdo_3.tif') @@ -140,28 +124,21 @@ def test_gdaladdo_4(): cnt = ds.GetRasterBand(1).GetOverviewCount() ds = None - if cnt != 0: - gdaltest.post_reason('did not clean overviews.') - return 'fail' + assert cnt == 0, 'did not clean overviews.' - try: + with pytest.raises(OSError, message='.ovr file still exists'): os.stat('tmp/test_gdaladdo_3.tif.ovr') - gdaltest.post_reason('.ovr file still exists') - return 'fail' - except OSError: - pass + os.remove('tmp/test_gdaladdo_3.tif') - return 'success' - ############################################################################### # Test implicit levels def test_gdaladdo_5(): if test_cli_utilities.get_gdaladdo_path() is None: - return 'skip' + pytest.skip() shutil.copyfile('../gcore/data/nodata_byte.tif', 'tmp/test_gdaladdo_5.tif') @@ -172,10 +149,7 @@ def test_gdaladdo_5(): cnt = ds.GetRasterBand(1).GetOverviewCount() ds = None - if cnt != 0: - gdaltest.post_reason('fail') - print(cnt) - return 'fail' + assert cnt == 0 # Will generate overviews of size 10 5 3 2 1 gdaltest.runexternal(test_cli_utilities.get_gdaladdo_path() + ' -minsize 1 tmp/test_gdaladdo_5.tif') @@ -184,10 +158,7 @@ def test_gdaladdo_5(): cnt = ds.GetRasterBand(1).GetOverviewCount() ds = None - if cnt != 5: - gdaltest.post_reason('fail') - print(cnt) - return 'fail' + assert cnt == 5 gdal.Translate('tmp/test_gdaladdo_5.tif', '../gcore/data/nodata_byte.tif', options='-outsize 257 257') @@ -198,29 +169,10 @@ def test_gdaladdo_5(): cnt = ds.GetRasterBand(1).GetOverviewCount() ds = None - if cnt != 1: - gdaltest.post_reason('fail') - print(cnt) - return 'fail' + assert cnt == 1 os.remove('tmp/test_gdaladdo_5.tif') - return 'success' - - -gdaltest_list = [ - test_gdaladdo_1, - test_gdaladdo_2, - test_gdaladdo_3, - test_gdaladdo_4, - test_gdaladdo_5 -] - - -if __name__ == '__main__': - gdaltest.setup_run('test_gdaladdo') - gdaltest.run_tests(gdaltest_list) - sys.exit(gdaltest.summarize()) diff --git a/autotest/utilities/test_gdalbuildvrt.py b/autotest/utilities/test_gdalbuildvrt.py index 2133964b1874..f1f800dce58c 100755 --- a/autotest/utilities/test_gdalbuildvrt.py +++ b/autotest/utilities/test_gdalbuildvrt.py @@ -29,54 +29,46 @@ # DEALINGS IN THE SOFTWARE. ############################################################################### -import sys import os -sys.path.append('../pymod') from osgeo import gdal from osgeo import ogr from osgeo import osr import gdaltest import test_cli_utilities +import pytest ############################################################################### -def test_gdalbuildvrt_check(): +def gdalbuildvrt_check(): ds = gdal.Open('tmp/mosaic.vrt') - if ds.GetProjectionRef().find('WGS 84') == -1: - gdaltest.post_reason('Expected WGS 84\nGot : %s' % (ds.GetProjectionRef())) - return 'fail' - - gt = ds.GetGeoTransform() - expected_gt = [2, 0.1, 0, 49, 0, -0.1] - for i in range(6): - if abs(gt[i] - expected_gt[i] > 1e-5): - gdaltest.post_reason('Expected : %s\nGot : %s' % (expected_gt, gt)) - return 'fail' - - if ds.RasterXSize != 20 or ds.RasterYSize != 20: - gdaltest.post_reason('Wrong raster dimensions : %d x %d' % (ds.RasterXSize, ds.RasterYSize)) - return 'fail' + try: + assert ds.GetProjectionRef().find('WGS 84') != -1, \ + ('Expected WGS 84\nGot : %s' % (ds.GetProjectionRef())) - if ds.RasterCount != 1: - gdaltest.post_reason('Wrong raster count : %d ' % (ds.RasterCount)) - return 'fail' + gt = ds.GetGeoTransform() + expected_gt = [2, 0.1, 0, 49, 0, -0.1] + for i in range(6): + assert not abs(gt[i] - expected_gt[i] > 1e-5), \ + ('Expected : %s\nGot : %s' % (expected_gt, gt)) - if ds.GetRasterBand(1).Checksum() != 3508: - gdaltest.post_reason('Wrong checksum') - return 'fail' + assert ds.RasterXSize == 20 and ds.RasterYSize == 20, \ + ('Wrong raster dimensions : %d x %d' % (ds.RasterXSize, ds.RasterYSize)) - return 'success' + assert ds.RasterCount == 1, ('Wrong raster count : %d ' % (ds.RasterCount)) + assert ds.GetRasterBand(1).Checksum() == 3508, 'Wrong checksum' + finally: + del ds ############################################################################### # Simple test def test_gdalbuildvrt_1(): if test_cli_utilities.get_gdalbuildvrt_path() is None: - return 'skip' + pytest.skip() drv = gdal.GetDriverByName('GTiff') srs = osr.SpatialReference() @@ -108,12 +100,9 @@ def test_gdalbuildvrt_1(): ds = None (_, err) = gdaltest.runexternal_out_and_err(test_cli_utilities.get_gdalbuildvrt_path() + ' tmp/mosaic.vrt tmp/gdalbuildvrt1.tif tmp/gdalbuildvrt2.tif tmp/gdalbuildvrt3.tif tmp/gdalbuildvrt4.tif') - if not (err is None or err == ''): - gdaltest.post_reason('got error/warning') - print(err) - return 'fail' + assert (err is None or err == ''), 'got error/warning' - return test_gdalbuildvrt_check() + return gdalbuildvrt_check() ############################################################################### # Test with tile index @@ -121,9 +110,9 @@ def test_gdalbuildvrt_1(): def test_gdalbuildvrt_2(): if test_cli_utilities.get_gdalbuildvrt_path() is None: - return 'skip' + pytest.skip() if test_cli_utilities.get_gdaltindex_path() is None: - return 'skip' + pytest.skip() try: os.remove('tmp/tileindex.shp') @@ -146,7 +135,7 @@ def test_gdalbuildvrt_2(): gdaltest.runexternal(test_cli_utilities.get_gdalbuildvrt_path() + ' tmp/mosaic.vrt tmp/tileindex.shp') - return test_gdalbuildvrt_check() + return gdalbuildvrt_check() ############################################################################### # Test with file list @@ -154,13 +143,13 @@ def test_gdalbuildvrt_2(): def test_gdalbuildvrt_3(): if test_cli_utilities.get_gdalbuildvrt_path() is None: - return 'skip' + pytest.skip() open('tmp/filelist.txt', 'wt').write('tmp/gdalbuildvrt1.tif\ntmp/gdalbuildvrt2.tif\ntmp/gdalbuildvrt3.tif\ntmp/gdalbuildvrt4.tif') gdaltest.runexternal(test_cli_utilities.get_gdalbuildvrt_path() + ' -input_file_list tmp/filelist.txt tmp/mosaic.vrt') - return test_gdalbuildvrt_check() + return gdalbuildvrt_check() ############################################################################### @@ -168,7 +157,7 @@ def test_gdalbuildvrt_3(): def test_gdalbuildvrt_4(): if test_cli_utilities.get_gdalbuildvrt_path() is None: - return 'skip' + pytest.skip() drv = gdal.GetDriverByName('GTiff') wkt = 'GEOGCS[\"WGS 72\",DATUM[\"WGS_1972\"]]' @@ -180,15 +169,17 @@ def test_gdalbuildvrt_4(): gdaltest.runexternal(test_cli_utilities.get_gdalbuildvrt_path() + ' tmp/mosaic.vrt tmp/gdalbuildvrt1.tif tmp/gdalbuildvrt2.tif tmp/gdalbuildvrt3.tif tmp/gdalbuildvrt4.tif tmp/gdalbuildvrt5.tif') - return test_gdalbuildvrt_check() + return gdalbuildvrt_check() ############################################################################### # Try adding a raster with different band count +# NOTE: fails. commented out originally in 4ef886421c99a4451f8873cb6e094d45ecc86d3f, not sure why +@pytest.mark.skip() def test_gdalbuildvrt_5(): if test_cli_utilities.get_gdalbuildvrt_path() is None: - return 'skip' + pytest.skip() drv = gdal.GetDriverByName('GTiff') srs = osr.SpatialReference() @@ -202,7 +193,7 @@ def test_gdalbuildvrt_5(): gdaltest.runexternal(test_cli_utilities.get_gdalbuildvrt_path() + ' tmp/mosaic.vrt tmp/gdalbuildvrt1.tif tmp/gdalbuildvrt2.tif tmp/gdalbuildvrt3.tif tmp/gdalbuildvrt4.tif tmp/gdalbuildvrt5.tif') - return test_gdalbuildvrt_check() + return gdalbuildvrt_check() ############################################################################### # Test -separate option @@ -210,35 +201,26 @@ def test_gdalbuildvrt_5(): def test_gdalbuildvrt_6(): if test_cli_utilities.get_gdalbuildvrt_path() is None: - return 'skip' + pytest.skip() gdaltest.runexternal(test_cli_utilities.get_gdalbuildvrt_path() + ' -separate tmp/stacked.vrt tmp/gdalbuildvrt1.tif tmp/gdalbuildvrt2.tif tmp/gdalbuildvrt3.tif tmp/gdalbuildvrt4.tif') ds = gdal.Open('tmp/stacked.vrt') - if ds.GetProjectionRef().find('WGS 84') == -1: - gdaltest.post_reason('Expected WGS 84\nGot : %s' % (ds.GetProjectionRef())) - return 'fail' + assert ds.GetProjectionRef().find('WGS 84') != -1, \ + ('Expected WGS 84\nGot : %s' % (ds.GetProjectionRef())) gt = ds.GetGeoTransform() expected_gt = [2, 0.1, 0, 49, 0, -0.1] for i in range(6): - if abs(gt[i] - expected_gt[i] > 1e-5): - gdaltest.post_reason('Expected : %s\nGot : %s' % (expected_gt, gt)) - return 'fail' - - if ds.RasterXSize != 20 or ds.RasterYSize != 20: - gdaltest.post_reason('Wrong raster dimensions : %d x %d' % (ds.RasterXSize, ds.RasterYSize)) - return 'fail' + assert not abs(gt[i] - expected_gt[i] > 1e-5), \ + ('Expected : %s\nGot : %s' % (expected_gt, gt)) - if ds.RasterCount != 4: - gdaltest.post_reason('Wrong raster count : %d ' % (ds.RasterCount)) - return 'fail' + assert ds.RasterXSize == 20 and ds.RasterYSize == 20, \ + ('Wrong raster dimensions : %d x %d' % (ds.RasterXSize, ds.RasterYSize)) - if ds.GetRasterBand(1).Checksum() != 0: - gdaltest.post_reason('Wrong checksum') - return 'fail' + assert ds.RasterCount == 4, ('Wrong raster count : %d ' % (ds.RasterCount)) - return 'success' + assert ds.GetRasterBand(1).Checksum() == 0, 'Wrong checksum' ############################################################################### # Test source rasters with nodata @@ -246,7 +228,7 @@ def test_gdalbuildvrt_6(): def test_gdalbuildvrt_7(): if test_cli_utilities.get_gdalbuildvrt_path() is None: - return 'skip' + pytest.skip() out_ds = gdal.GetDriverByName('GTiff').Create('tmp/vrtnull1.tif', 20, 10, 3, gdal.GDT_UInt16) out_ds.SetGeoTransform([2, 0.1, 0, 49, 0, -0.1]) @@ -287,29 +269,21 @@ def test_gdalbuildvrt_7(): ds = gdal.Open('tmp/gdalbuildvrt7.vrt') - if ds.GetRasterBand(1).Checksum() != 1217: - gdaltest.post_reason('Wrong checksum') - return 'fail' + assert ds.GetRasterBand(1).Checksum() == 1217, 'Wrong checksum' - if ds.GetRasterBand(2).Checksum() != 1218: - gdaltest.post_reason('Wrong checksum') - return 'fail' + assert ds.GetRasterBand(2).Checksum() == 1218, 'Wrong checksum' - if ds.GetRasterBand(3).Checksum() != 0: - gdaltest.post_reason('Wrong checksum') - return 'fail' + assert ds.GetRasterBand(3).Checksum() == 0, 'Wrong checksum' ds = None - return 'success' - ############################################################################### # Test -tr option def test_gdalbuildvrt_8(): if test_cli_utilities.get_gdalbuildvrt_path() is None: - return 'skip' + pytest.skip() gdaltest.runexternal(test_cli_utilities.get_gdalbuildvrt_path() + ' -tr 0.05 0.05 tmp/mosaic2.vrt tmp/gdalbuildvrt1.tif tmp/gdalbuildvrt2.tif tmp/gdalbuildvrt3.tif tmp/gdalbuildvrt4.tif') @@ -318,17 +292,15 @@ def test_gdalbuildvrt_8(): gt = ds.GetGeoTransform() expected_gt = [2, 0.05, 0, 49, 0, -0.05] for i in range(6): - if abs(gt[i] - expected_gt[i] > 1e-5): - gdaltest.post_reason('Expected : %s\nGot : %s' % (expected_gt, gt)) - return 'fail' + assert not abs(gt[i] - expected_gt[i] > 1e-5), \ + ('Expected : %s\nGot : %s' % (expected_gt, gt)) - if ds.RasterXSize != 40 or ds.RasterYSize != 40: - gdaltest.post_reason('Wrong raster dimensions : %d x %d' % (ds.RasterXSize, ds.RasterYSize)) - return 'fail' + assert ds.RasterXSize == 40 and ds.RasterYSize == 40, \ + ('Wrong raster dimensions : %d x %d' % (ds.RasterXSize, ds.RasterYSize)) gdaltest.runexternal(test_cli_utilities.get_gdalbuildvrt_path() + ' -tr 0.1 0.1 tmp/mosaic.vrt tmp/mosaic2.vrt') - return test_gdalbuildvrt_check() + return gdalbuildvrt_check() ############################################################################### # Test -te option @@ -336,7 +308,7 @@ def test_gdalbuildvrt_8(): def test_gdalbuildvrt_9(): if test_cli_utilities.get_gdalbuildvrt_path() is None: - return 'skip' + pytest.skip() gdaltest.runexternal(test_cli_utilities.get_gdalbuildvrt_path() + ' -te 1 46 5 50 tmp/mosaic2.vrt tmp/gdalbuildvrt1.tif tmp/gdalbuildvrt2.tif tmp/gdalbuildvrt3.tif tmp/gdalbuildvrt4.tif') @@ -345,17 +317,15 @@ def test_gdalbuildvrt_9(): gt = ds.GetGeoTransform() expected_gt = [1, 0.1, 0, 50, 0, -0.1] for i in range(6): - if abs(gt[i] - expected_gt[i] > 1e-5): - gdaltest.post_reason('Expected : %s\nGot : %s' % (expected_gt, gt)) - return 'fail' + assert not abs(gt[i] - expected_gt[i] > 1e-5), \ + ('Expected : %s\nGot : %s' % (expected_gt, gt)) - if ds.RasterXSize != 40 or ds.RasterYSize != 40: - gdaltest.post_reason('Wrong raster dimensions : %d x %d' % (ds.RasterXSize, ds.RasterYSize)) - return 'fail' + assert ds.RasterXSize == 40 and ds.RasterYSize == 40, \ + ('Wrong raster dimensions : %d x %d' % (ds.RasterXSize, ds.RasterYSize)) gdaltest.runexternal(test_cli_utilities.get_gdalbuildvrt_path() + ' -te 2 47 4 49 tmp/mosaic.vrt tmp/mosaic2.vrt') - return test_gdalbuildvrt_check() + return gdalbuildvrt_check() ############################################################################### # Test explicit nodata setting (#3254) @@ -363,7 +333,7 @@ def test_gdalbuildvrt_9(): def test_gdalbuildvrt_10(): if test_cli_utilities.get_gdalbuildvrt_path() is None: - return 'skip' + pytest.skip() out_ds = gdal.GetDriverByName('GTiff').Create('tmp/test_gdalbuildvrt_10_1.tif', 10, 10, 1, gdal.GDT_Byte, options=['NBITS=1', 'PHOTOMETRIC=MINISWHITE']) out_ds.SetGeoTransform([2, 0.1, 0, 49, 0, -0.1]) @@ -387,22 +357,17 @@ def test_gdalbuildvrt_10(): ds = gdal.Open('tmp/gdalbuildvrt10.vrt') - if ds.GetRasterBand(1).Checksum() != 18: - print(ds.GetRasterBand(1).Checksum()) - gdaltest.post_reason('Wrong checksum') - return 'fail' + assert ds.GetRasterBand(1).Checksum() == 18, 'Wrong checksum' ds = None - return 'success' - ############################################################################### # Test that we can stack ungeoreference single band images with -separate (#3432) def test_gdalbuildvrt_11(): if test_cli_utilities.get_gdalbuildvrt_path() is None: - return 'skip' + pytest.skip() out_ds = gdal.GetDriverByName('GTiff').Create('tmp/test_gdalbuildvrt_11_1.tif', 10, 10, 1) out_ds.GetRasterBand(1).Fill(255) @@ -418,35 +383,24 @@ def test_gdalbuildvrt_11(): ds = gdal.Open('tmp/gdalbuildvrt11.vrt') - if ds.GetRasterBand(1).Checksum() != cs1: - print(ds.GetRasterBand(1).Checksum()) - print(cs1) - gdaltest.post_reason('Wrong checksum') - return 'fail' + assert ds.GetRasterBand(1).Checksum() == cs1, 'Wrong checksum' - if ds.GetRasterBand(2).Checksum() != cs2: - print(ds.GetRasterBand(2).Checksum()) - print(cs2) - gdaltest.post_reason('Wrong checksum') - return 'fail' + assert ds.GetRasterBand(2).Checksum() == cs2, 'Wrong checksum' ds = None - return 'success' - ############################################################################### # Test -tap option def test_gdalbuildvrt_12(): if test_cli_utilities.get_gdalbuildvrt_path() is None: - return 'skip' + pytest.skip() (_, err) = gdaltest.runexternal_out_and_err(test_cli_utilities.get_gdalbuildvrt_path() + ' -tap tmp/gdalbuildvrt12.vrt ../gcore/data/byte.tif', check_memleak=False) - if err.find('-tap option cannot be used without using -tr') == -1: - gdaltest.post_reason('expected error') - return 'fail' + assert err.find('-tap option cannot be used without using -tr') != -1, \ + 'expected error' gdaltest.runexternal(test_cli_utilities.get_gdalbuildvrt_path() + ' -tr 100 50 -tap tmp/gdalbuildvrt12.vrt ../gcore/data/byte.tif') @@ -455,15 +409,11 @@ def test_gdalbuildvrt_12(): gt = ds.GetGeoTransform() expected_gt = [440700.0, 100.0, 0.0, 3751350.0, 0.0, -50.0] for i in range(6): - if abs(gt[i] - expected_gt[i] > 1e-5): - gdaltest.post_reason('Expected : %s\nGot : %s' % (expected_gt, gt)) - return 'fail' + assert not abs(gt[i] - expected_gt[i] > 1e-5), \ + ('Expected : %s\nGot : %s' % (expected_gt, gt)) - if ds.RasterXSize != 13 or ds.RasterYSize != 25: - gdaltest.post_reason('Wrong raster dimensions : %d x %d' % (ds.RasterXSize, ds.RasterYSize)) - return 'fail' - - return 'success' + assert ds.RasterXSize == 13 and ds.RasterYSize == 25, \ + ('Wrong raster dimensions : %d x %d' % (ds.RasterXSize, ds.RasterYSize)) ############################################################################### # Test -a_srs @@ -471,26 +421,23 @@ def test_gdalbuildvrt_12(): def test_gdalbuildvrt_13(): if test_cli_utilities.get_gdalbuildvrt_path() is None: - return 'skip' + pytest.skip() gdaltest.runexternal(test_cli_utilities.get_gdalbuildvrt_path() + ' tmp/gdalbuildvrt13.vrt ../gcore/data/byte.tif -a_srs EPSG:4326') ds = gdal.Open('tmp/gdalbuildvrt13.vrt') - if ds.GetProjectionRef().find('4326') == -1: - return 'fail' + assert ds.GetProjectionRef().find('4326') != -1 ds = None - return 'success' - ############################################################################### # Test -r def test_gdalbuildvrt_14(): if test_cli_utilities.get_gdalbuildvrt_path() is None: - return 'skip' + pytest.skip() if test_cli_utilities.get_gdal_translate_path() is None: - return 'skip' + pytest.skip() gdaltest.runexternal(test_cli_utilities.get_gdalbuildvrt_path() + ' tmp/test_gdalbuildvrt_14.vrt ../gcore/data/byte.tif -r cubic -tr 30 30') @@ -503,13 +450,7 @@ def test_gdalbuildvrt_14(): ds = None ds_ref = None - if cs != cs_ref: - gdaltest.post_reason('fail') - print(cs) - print(cs_ref) - return 'fail' - - return 'success' + assert cs == cs_ref ############################################################################### # Test -b @@ -517,7 +458,7 @@ def test_gdalbuildvrt_14(): def test_gdalbuildvrt_15(): if test_cli_utilities.get_gdalbuildvrt_path() is None: - return 'skip' + pytest.skip() gdaltest.runexternal(test_cli_utilities.get_gdalbuildvrt_path() + ' tmp/test_gdalbuildvrt_15.vrt ../gcore/data/byte.tif -b 1') @@ -525,12 +466,7 @@ def test_gdalbuildvrt_15(): cs = ds.GetRasterBand(1).Checksum() ds = None - if cs != 4672: - gdaltest.post_reason('fail') - print(cs) - return 'fail' - - return 'success' + assert cs == 4672 ############################################################################### # Test output to non writable file @@ -538,26 +474,17 @@ def test_gdalbuildvrt_15(): def test_gdalbuildvrt_16(): if test_cli_utilities.get_gdalbuildvrt_path() is None: - return 'skip' + pytest.skip() (out, err) = gdaltest.runexternal_out_and_err(test_cli_utilities.get_gdalbuildvrt_path() + ' /non_existing_dir/non_existing_subdir/out.vrt ../gcore/data/byte.tif') if not gdaltest.is_travis_branch('mingw'): - if err.find('ERROR ret code = 1') < 0: - gdaltest.post_reason('fail') - print(out) - print(err) - return 'fail' + assert err.find('ERROR ret code = 1') >= 0, out else: # We don't get the error code on Travis mingw - if err.find('ERROR') < 0: - gdaltest.post_reason('fail') - print(out) - print(err) - return 'fail' - - return 'success' + assert err.find('ERROR') >= 0, out + ############################################################################### # Cleanup @@ -565,7 +492,7 @@ def test_gdalbuildvrt_16(): def test_gdalbuildvrt_cleanup(): if test_cli_utilities.get_gdalbuildvrt_path() is None: - return 'skip' + pytest.skip() ogr.GetDriverByName('ESRI Shapefile').DeleteDataSource('tmp/tileindex.shp') @@ -599,34 +526,7 @@ def test_gdalbuildvrt_cleanup(): except OSError: pass - return 'success' - - -gdaltest_list = [ - test_gdalbuildvrt_1, - test_gdalbuildvrt_2, - test_gdalbuildvrt_3, - test_gdalbuildvrt_4, - # test_gdalbuildvrt_5, - test_gdalbuildvrt_6, - test_gdalbuildvrt_7, - test_gdalbuildvrt_8, - test_gdalbuildvrt_9, - test_gdalbuildvrt_10, - test_gdalbuildvrt_11, - test_gdalbuildvrt_12, - test_gdalbuildvrt_13, - test_gdalbuildvrt_14, - test_gdalbuildvrt_15, - test_gdalbuildvrt_16, - test_gdalbuildvrt_cleanup -] - - -if __name__ == '__main__': + - gdaltest.setup_run('test_gdalbuildvrt') - gdaltest.run_tests(gdaltest_list) - sys.exit(gdaltest.summarize()) diff --git a/autotest/utilities/test_gdalbuildvrt_lib.py b/autotest/utilities/test_gdalbuildvrt_lib.py index 96d3267ce6d6..f9f89161efeb 100755 --- a/autotest/utilities/test_gdalbuildvrt_lib.py +++ b/autotest/utilities/test_gdalbuildvrt_lib.py @@ -29,12 +29,9 @@ # DEALINGS IN THE SOFTWARE. ############################################################################### -import sys -sys.path.append('../pymod') from osgeo import gdal -import gdaltest ############################################################################### # Simple test @@ -44,45 +41,27 @@ def test_gdalbuildvrt_lib_1(): # Source = String ds = gdal.BuildVRT('', '../gcore/data/byte.tif') - if ds is None: - gdaltest.post_reason('got error/warning') - return 'fail' + assert ds is not None, 'got error/warning' - if ds.GetRasterBand(1).Checksum() != 4672: - gdaltest.post_reason('Bad checksum') - return 'fail' + assert ds.GetRasterBand(1).Checksum() == 4672, 'Bad checksum' # Source = Array of string ds = gdal.BuildVRT('', ['../gcore/data/byte.tif']) - if ds is None: - gdaltest.post_reason('got error/warning') - return 'fail' + assert ds is not None, 'got error/warning' - if ds.GetRasterBand(1).Checksum() != 4672: - gdaltest.post_reason('Bad checksum') - return 'fail' + assert ds.GetRasterBand(1).Checksum() == 4672, 'Bad checksum' # Source = Dataset ds = gdal.BuildVRT('', gdal.Open('../gcore/data/byte.tif')) - if ds is None: - gdaltest.post_reason('got error/warning') - return 'fail' + assert ds is not None, 'got error/warning' - if ds.GetRasterBand(1).Checksum() != 4672: - gdaltest.post_reason('Bad checksum') - return 'fail' + assert ds.GetRasterBand(1).Checksum() == 4672, 'Bad checksum' # Source = Array of dataset ds = gdal.BuildVRT('', [gdal.Open('../gcore/data/byte.tif')]) - if ds is None: - gdaltest.post_reason('got error/warning') - return 'fail' + assert ds is not None, 'got error/warning' - if ds.GetRasterBand(1).Checksum() != 4672: - gdaltest.post_reason('Bad checksum') - return 'fail' - - return 'success' + assert ds.GetRasterBand(1).Checksum() == 4672, 'Bad checksum' ############################################################################### # Test callback @@ -98,32 +77,14 @@ def test_gdalbuildvrt_lib_2(): tab = [0] ds = gdal.BuildVRT('', '../gcore/data/byte.tif', callback=mycallback, callback_data=tab) - if ds is None: - return 'fail' + assert ds is not None - if ds.GetRasterBand(1).Checksum() != 4672: - gdaltest.post_reason('Bad checksum') - return 'fail' + assert ds.GetRasterBand(1).Checksum() == 4672, 'Bad checksum' - if tab[0] != 1.0: - gdaltest.post_reason('Bad percentage') - return 'fail' + assert tab[0] == 1.0, 'Bad percentage' ds = None - return 'success' - - -gdaltest_list = [ - test_gdalbuildvrt_lib_1, - test_gdalbuildvrt_lib_2, -] - - -if __name__ == '__main__': - gdaltest.setup_run('test_gdalbuildvrt_lib') - gdaltest.run_tests(gdaltest_list) - sys.exit(gdaltest.summarize()) diff --git a/autotest/utilities/test_gdaldem.py b/autotest/utilities/test_gdaldem.py index 24c53a864b02..72faa60f9773 100755 --- a/autotest/utilities/test_gdaldem.py +++ b/autotest/utilities/test_gdaldem.py @@ -29,15 +29,14 @@ # DEALINGS IN THE SOFTWARE. ############################################################################### -import sys import os -sys.path.append('../pymod') from osgeo import gdal from osgeo import osr import gdaltest import test_cli_utilities +import pytest ############################################################################### # Test gdaldem hillshade @@ -45,79 +44,54 @@ def test_gdaldem_hillshade(): if test_cli_utilities.get_gdaldem_path() is None: - return 'skip' + pytest.skip() (_, err) = gdaltest.runexternal_out_and_err(test_cli_utilities.get_gdaldem_path() + ' hillshade -s 111120 -z 30 ../gdrivers/data/n43.dt0 tmp/n43_hillshade.tif') - if not (err is None or err == ''): - gdaltest.post_reason('got error/warning') - print(err) - return 'fail' + assert (err is None or err == ''), 'got error/warning' src_ds = gdal.Open('../gdrivers/data/n43.dt0') ds = gdal.Open('tmp/n43_hillshade.tif') - if ds is None: - return 'fail' + assert ds is not None cs = ds.GetRasterBand(1).Checksum() - if cs != 45587: - gdaltest.post_reason('Bad checksum') - print(cs) - return 'fail' + assert cs == 45587, 'Bad checksum' src_gt = src_ds.GetGeoTransform() dst_gt = ds.GetGeoTransform() for i in range(6): - if abs(src_gt[i] - dst_gt[i]) > 1e-10: - gdaltest.post_reason('Bad geotransform') - return 'fail' + assert abs(src_gt[i] - dst_gt[i]) <= 1e-10, 'Bad geotransform' dst_wkt = ds.GetProjectionRef() - if dst_wkt.find('AUTHORITY["EPSG","4326"]') == -1: - gdaltest.post_reason('Bad projection') - return 'fail' + assert dst_wkt.find('AUTHORITY["EPSG","4326"]') != -1, 'Bad projection' - if ds.GetRasterBand(1).GetNoDataValue() != 0: - gdaltest.post_reason('Bad nodata value') - return 'fail' + assert ds.GetRasterBand(1).GetNoDataValue() == 0, 'Bad nodata value' src_ds = None ds = None - return 'success' - ############################################################################### # Test gdaldem hillshade def test_gdaldem_hillshade_compressed_tiled_output(): if test_cli_utilities.get_gdaldem_path() is None: - return 'skip' + pytest.skip() (_, err) = gdaltest.runexternal_out_and_err(test_cli_utilities.get_gdaldem_path() + ' hillshade -s 111120 -z 30 ../gdrivers/data/n43.dt0 tmp/n43_hillshade_compressed_tiled.tif -co TILED=YES -co COMPRESS=DEFLATE --config GDAL_CACHEMAX 0') - if not (err is None or err == ''): - gdaltest.post_reason('got error/warning') - print(err) - return 'fail' + assert (err is None or err == ''), 'got error/warning' ds = gdal.Open('tmp/n43_hillshade_compressed_tiled.tif') - if ds is None: - return 'fail' + assert ds is not None cs = ds.GetRasterBand(1).Checksum() - if cs != 45587: - gdaltest.post_reason('Bad checksum') - print(cs) - return 'fail' + assert cs == 45587, 'Bad checksum' ds = None stat_uncompressed = os.stat('tmp/n43_hillshade.tif') stat_compressed = os.stat('tmp/n43_hillshade_compressed_tiled.tif') - if stat_uncompressed.st_size < stat_compressed.st_size: - gdaltest.post_reason('failure: compressed size greater than uncompressed one') - return 'fail' - - return 'success' + assert stat_uncompressed.st_size >= stat_compressed.st_size, \ + 'failure: compressed size greater than uncompressed one' ############################################################################### # Test gdaldem hillshade -combined @@ -125,73 +99,55 @@ def test_gdaldem_hillshade_compressed_tiled_output(): def test_gdaldem_hillshade_combined(): if test_cli_utilities.get_gdaldem_path() is None: - return 'skip' + pytest.skip() gdaltest.runexternal(test_cli_utilities.get_gdaldem_path() + ' hillshade -s 111120 -z 30 -combined ../gdrivers/data/n43.dt0 tmp/n43_hillshade_combined.tif') src_ds = gdal.Open('../gdrivers/data/n43.dt0') ds = gdal.Open('tmp/n43_hillshade_combined.tif') - if ds is None: - return 'fail' + assert ds is not None cs = ds.GetRasterBand(1).Checksum() - if cs != 43876: - gdaltest.post_reason('Bad checksum') - print(cs) - return 'fail' + assert cs == 43876, 'Bad checksum' src_gt = src_ds.GetGeoTransform() dst_gt = ds.GetGeoTransform() for i in range(6): - if abs(src_gt[i] - dst_gt[i]) > 1e-10: - gdaltest.post_reason('Bad geotransform') - return 'fail' + assert abs(src_gt[i] - dst_gt[i]) <= 1e-10, 'Bad geotransform' dst_wkt = ds.GetProjectionRef() - if dst_wkt.find('AUTHORITY["EPSG","4326"]') == -1: - gdaltest.post_reason('Bad projection') - return 'fail' + assert dst_wkt.find('AUTHORITY["EPSG","4326"]') != -1, 'Bad projection' - if ds.GetRasterBand(1).GetNoDataValue() != 0: - gdaltest.post_reason('Bad nodata value') - return 'fail' + assert ds.GetRasterBand(1).GetNoDataValue() == 0, 'Bad nodata value' src_ds = None ds = None - return 'success' - ############################################################################### # Test gdaldem hillshade with -compute_edges def test_gdaldem_hillshade_compute_edges(): if test_cli_utilities.get_gdaldem_path() is None: - return 'skip' + pytest.skip() gdaltest.runexternal(test_cli_utilities.get_gdaldem_path() + ' hillshade -compute_edges -s 111120 -z 30 ../gdrivers/data/n43.dt0 tmp/n43_hillshade_compute_edges.tif') ds = gdal.Open('tmp/n43_hillshade_compute_edges.tif') - if ds is None: - return 'fail' + assert ds is not None cs = ds.GetRasterBand(1).Checksum() - if cs != 50239: - gdaltest.post_reason('Bad checksum') - print(cs) - return 'fail' + assert cs == 50239, 'Bad checksum' ds = None - return 'success' - ############################################################################### # Test gdaldem hillshade with -az parameter def test_gdaldem_hillshade_azimuth(): if test_cli_utilities.get_gdaldem_path() is None: - return 'skip' + pytest.skip() from sys import version_info ds = gdal.GetDriverByName('GTiff').Create('tmp/pyramid.tif', 100, 100, 1) @@ -215,443 +171,304 @@ def test_gdaldem_hillshade_azimuth(): ds_ref = gdal.Open('data/pyramid_shaded_ref.tif') ds = gdal.Open('tmp/pyramid_shaded.tif') - if gdaltest.compare_ds(ds, ds_ref, verbose=1) > 1: - gdaltest.post_reason('Bad checksum') - return 'fail' + assert gdaltest.compare_ds(ds, ds_ref, verbose=1) <= 1, 'Bad checksum' ds = None ds_ref = None - return 'success' - ############################################################################### # Test gdaldem hillshade to PNG def test_gdaldem_hillshade_png(): if test_cli_utilities.get_gdaldem_path() is None: - return 'skip' + pytest.skip() gdaltest.runexternal(test_cli_utilities.get_gdaldem_path() + ' hillshade -of PNG -s 111120 -z 30 ../gdrivers/data/n43.dt0 tmp/n43_hillshade.png') ds = gdal.Open('tmp/n43_hillshade.png') - if ds is None: - return 'fail' + assert ds is not None cs = ds.GetRasterBand(1).Checksum() - if cs != 45587: - gdaltest.post_reason('Bad checksum') - print(cs) - return 'fail' + assert cs == 45587, 'Bad checksum' ds = None - return 'success' - ############################################################################### # Test gdaldem hillshade to PNG with -compute_edges def test_gdaldem_hillshade_png_compute_edges(): if test_cli_utilities.get_gdaldem_path() is None: - return 'skip' + pytest.skip() gdaltest.runexternal(test_cli_utilities.get_gdaldem_path() + ' hillshade -compute_edges -of PNG -s 111120 -z 30 ../gdrivers/data/n43.dt0 tmp/n43_hillshade_compute_edges.png') ds = gdal.Open('tmp/n43_hillshade_compute_edges.png') - if ds is None: - return 'fail' + assert ds is not None cs = ds.GetRasterBand(1).Checksum() - if cs != 50239: - gdaltest.post_reason('Bad checksum') - print(cs) - return 'fail' + assert cs == 50239, 'Bad checksum' ds = None - return 'success' - ############################################################################### # Test gdaldem slope def test_gdaldem_slope(): if test_cli_utilities.get_gdaldem_path() is None: - return 'skip' + pytest.skip() gdaltest.runexternal(test_cli_utilities.get_gdaldem_path() + ' slope -s 111120 ../gdrivers/data/n43.dt0 tmp/n43_slope.tif') src_ds = gdal.Open('../gdrivers/data/n43.dt0') ds = gdal.Open('tmp/n43_slope.tif') - if ds is None: - return 'fail' + assert ds is not None - if ds.GetRasterBand(1).Checksum() != 63748: - gdaltest.post_reason('Bad checksum') - return 'fail' + assert ds.GetRasterBand(1).Checksum() == 63748, 'Bad checksum' src_gt = src_ds.GetGeoTransform() dst_gt = ds.GetGeoTransform() for i in range(6): - if abs(src_gt[i] - dst_gt[i]) > 1e-10: - gdaltest.post_reason('Bad geotransform') - return 'fail' + assert abs(src_gt[i] - dst_gt[i]) <= 1e-10, 'Bad geotransform' dst_wkt = ds.GetProjectionRef() - if dst_wkt.find('AUTHORITY["EPSG","4326"]') == -1: - gdaltest.post_reason('Bad projection') - return 'fail' + assert dst_wkt.find('AUTHORITY["EPSG","4326"]') != -1, 'Bad projection' - if ds.GetRasterBand(1).GetNoDataValue() != -9999.0: - gdaltest.post_reason('Bad nodata value') - return 'fail' + assert ds.GetRasterBand(1).GetNoDataValue() == -9999.0, 'Bad nodata value' src_ds = None ds = None - return 'success' - ############################################################################### # Test gdaldem aspect def test_gdaldem_aspect(): if test_cli_utilities.get_gdaldem_path() is None: - return 'skip' + pytest.skip() gdaltest.runexternal(test_cli_utilities.get_gdaldem_path() + ' aspect ../gdrivers/data/n43.dt0 tmp/n43_aspect.tif') src_ds = gdal.Open('../gdrivers/data/n43.dt0') ds = gdal.Open('tmp/n43_aspect.tif') - if ds is None: - return 'fail' + assert ds is not None - if ds.GetRasterBand(1).Checksum() != 54885: - gdaltest.post_reason('Bad checksum') - return 'fail' + assert ds.GetRasterBand(1).Checksum() == 54885, 'Bad checksum' src_gt = src_ds.GetGeoTransform() dst_gt = ds.GetGeoTransform() for i in range(6): - if abs(src_gt[i] - dst_gt[i]) > 1e-10: - gdaltest.post_reason('Bad geotransform') - return 'fail' + assert abs(src_gt[i] - dst_gt[i]) <= 1e-10, 'Bad geotransform' dst_wkt = ds.GetProjectionRef() - if dst_wkt.find('AUTHORITY["EPSG","4326"]') == -1: - gdaltest.post_reason('Bad projection') - return 'fail' + assert dst_wkt.find('AUTHORITY["EPSG","4326"]') != -1, 'Bad projection' - if ds.GetRasterBand(1).GetNoDataValue() != -9999.0: - gdaltest.post_reason('Bad nodata value') - return 'fail' + assert ds.GetRasterBand(1).GetNoDataValue() == -9999.0, 'Bad nodata value' src_ds = None ds = None - return 'success' - ############################################################################### # Test gdaldem color relief def test_gdaldem_color_relief(): if test_cli_utilities.get_gdaldem_path() is None: - return 'skip' + pytest.skip() gdaltest.runexternal(test_cli_utilities.get_gdaldem_path() + ' color-relief ../gdrivers/data/n43.dt0 data/color_file.txt tmp/n43_colorrelief.tif') src_ds = gdal.Open('../gdrivers/data/n43.dt0') ds = gdal.Open('tmp/n43_colorrelief.tif') - if ds is None: - return 'fail' + assert ds is not None - if ds.GetRasterBand(1).Checksum() != 55009: - print(ds.GetRasterBand(1).Checksum()) - gdaltest.post_reason('Bad checksum') - return 'fail' + assert ds.GetRasterBand(1).Checksum() == 55009, 'Bad checksum' - if ds.GetRasterBand(2).Checksum() != 37543: - print(ds.GetRasterBand(2).Checksum()) - gdaltest.post_reason('Bad checksum') - return 'fail' + assert ds.GetRasterBand(2).Checksum() == 37543, 'Bad checksum' - if ds.GetRasterBand(3).Checksum() != 47711: - print(ds.GetRasterBand(3).Checksum()) - gdaltest.post_reason('Bad checksum') - return 'fail' + assert ds.GetRasterBand(3).Checksum() == 47711, 'Bad checksum' src_gt = src_ds.GetGeoTransform() dst_gt = ds.GetGeoTransform() for i in range(6): - if abs(src_gt[i] - dst_gt[i]) > 1e-10: - gdaltest.post_reason('Bad geotransform') - return 'fail' + assert abs(src_gt[i] - dst_gt[i]) <= 1e-10, 'Bad geotransform' dst_wkt = ds.GetProjectionRef() - if dst_wkt.find('AUTHORITY["EPSG","4326"]') == -1: - gdaltest.post_reason('Bad projection') - return 'fail' + assert dst_wkt.find('AUTHORITY["EPSG","4326"]') != -1, 'Bad projection' src_ds = None ds = None - return 'success' - ############################################################################### # Test gdaldem color relief on a GMT .cpt file def test_gdaldem_color_relief_cpt(): if test_cli_utilities.get_gdaldem_path() is None: - return 'skip' + pytest.skip() gdaltest.runexternal(test_cli_utilities.get_gdaldem_path() + ' color-relief ../gdrivers/data/n43.dt0 data/color_file.cpt tmp/n43_colorrelief_cpt.tif') src_ds = gdal.Open('../gdrivers/data/n43.dt0') ds = gdal.Open('tmp/n43_colorrelief_cpt.tif') - if ds is None: - return 'fail' + assert ds is not None - if ds.GetRasterBand(1).Checksum() != 55009: - print(ds.GetRasterBand(1).Checksum()) - gdaltest.post_reason('Bad checksum') - return 'fail' + assert ds.GetRasterBand(1).Checksum() == 55009, 'Bad checksum' - if ds.GetRasterBand(2).Checksum() != 37543: - print(ds.GetRasterBand(2).Checksum()) - gdaltest.post_reason('Bad checksum') - return 'fail' + assert ds.GetRasterBand(2).Checksum() == 37543, 'Bad checksum' - if ds.GetRasterBand(3).Checksum() != 47711: - print(ds.GetRasterBand(3).Checksum()) - gdaltest.post_reason('Bad checksum') - return 'fail' + assert ds.GetRasterBand(3).Checksum() == 47711, 'Bad checksum' src_gt = src_ds.GetGeoTransform() dst_gt = ds.GetGeoTransform() for i in range(6): - if abs(src_gt[i] - dst_gt[i]) > 1e-10: - gdaltest.post_reason('Bad geotransform') - return 'fail' + assert abs(src_gt[i] - dst_gt[i]) <= 1e-10, 'Bad geotransform' dst_wkt = ds.GetProjectionRef() - if dst_wkt.find('AUTHORITY["EPSG","4326"]') == -1: - gdaltest.post_reason('Bad projection') - return 'fail' + assert dst_wkt.find('AUTHORITY["EPSG","4326"]') != -1, 'Bad projection' src_ds = None ds = None - return 'success' - ############################################################################### # Test gdaldem color relief to VRT def test_gdaldem_color_relief_vrt(): if test_cli_utilities.get_gdaldem_path() is None: - return 'skip' + pytest.skip() gdaltest.runexternal(test_cli_utilities.get_gdaldem_path() + ' color-relief -of VRT ../gdrivers/data/n43.dt0 data/color_file.txt tmp/n43_colorrelief.vrt') src_ds = gdal.Open('../gdrivers/data/n43.dt0') ds = gdal.Open('tmp/n43_colorrelief.vrt') - if ds is None: - return 'fail' + assert ds is not None ds_ref = gdal.Open('tmp/n43_colorrelief.tif') - if gdaltest.compare_ds(ds, ds_ref, verbose=0) > 1: - gdaltest.post_reason('Bad checksum') - return 'fail' + assert gdaltest.compare_ds(ds, ds_ref, verbose=0) <= 1, 'Bad checksum' ds_ref = None src_gt = src_ds.GetGeoTransform() dst_gt = ds.GetGeoTransform() for i in range(6): - if abs(src_gt[i] - dst_gt[i]) > 1e-10: - gdaltest.post_reason('Bad geotransform') - return 'fail' + assert abs(src_gt[i] - dst_gt[i]) <= 1e-10, 'Bad geotransform' dst_wkt = ds.GetProjectionRef() - if dst_wkt.find('AUTHORITY["EPSG","4326"]') == -1: - gdaltest.post_reason('Bad projection') - return 'fail' + assert dst_wkt.find('AUTHORITY["EPSG","4326"]') != -1, 'Bad projection' src_ds = None ds = None - return 'success' - ############################################################################### # Test gdaldem color relief from a Float32 dataset def test_gdaldem_color_relief_from_float32(): if test_cli_utilities.get_gdaldem_path() is None: - return 'skip' + pytest.skip() if test_cli_utilities.get_gdal_translate_path() is None: - return 'skip' + pytest.skip() gdaltest.runexternal(test_cli_utilities.get_gdal_translate_path() + ' -ot Float32 ../gdrivers/data/n43.dt0 tmp/n43_float32.tif') gdaltest.runexternal(test_cli_utilities.get_gdaldem_path() + ' color-relief tmp/n43_float32.tif data/color_file.txt tmp/n43_colorrelief_from_float32.tif') ds = gdal.Open('tmp/n43_colorrelief_from_float32.tif') - if ds is None: - return 'fail' + assert ds is not None - if ds.GetRasterBand(1).Checksum() != 55009: - print(ds.GetRasterBand(1).Checksum()) - gdaltest.post_reason('Bad checksum') - return 'fail' + assert ds.GetRasterBand(1).Checksum() == 55009, 'Bad checksum' - if ds.GetRasterBand(2).Checksum() != 37543: - print(ds.GetRasterBand(2).Checksum()) - gdaltest.post_reason('Bad checksum') - return 'fail' + assert ds.GetRasterBand(2).Checksum() == 37543, 'Bad checksum' - if ds.GetRasterBand(3).Checksum() != 47711: - print(ds.GetRasterBand(3).Checksum()) - gdaltest.post_reason('Bad checksum') - return 'fail' + assert ds.GetRasterBand(3).Checksum() == 47711, 'Bad checksum' ds = None - return 'success' - ############################################################################### # Test gdaldem color relief to PNG def test_gdaldem_color_relief_png(): if test_cli_utilities.get_gdaldem_path() is None: - return 'skip' + pytest.skip() gdaltest.runexternal(test_cli_utilities.get_gdaldem_path() + ' color-relief -of PNG ../gdrivers/data/n43.dt0 data/color_file.txt tmp/n43_colorrelief.png') ds = gdal.Open('tmp/n43_colorrelief.png') - if ds is None: - return 'fail' + assert ds is not None - if ds.GetRasterBand(1).Checksum() != 55009: - print(ds.GetRasterBand(1).Checksum()) - gdaltest.post_reason('Bad checksum') - return 'fail' + assert ds.GetRasterBand(1).Checksum() == 55009, 'Bad checksum' - if ds.GetRasterBand(2).Checksum() != 37543: - print(ds.GetRasterBand(2).Checksum()) - gdaltest.post_reason('Bad checksum') - return 'fail' + assert ds.GetRasterBand(2).Checksum() == 37543, 'Bad checksum' - if ds.GetRasterBand(3).Checksum() != 47711: - print(ds.GetRasterBand(3).Checksum()) - gdaltest.post_reason('Bad checksum') - return 'fail' + assert ds.GetRasterBand(3).Checksum() == 47711, 'Bad checksum' ds = None - return 'success' - ############################################################################### # Test gdaldem color relief from a Float32 to PNG def test_gdaldem_color_relief_from_float32_to_png(): if test_cli_utilities.get_gdaldem_path() is None: - return 'skip' + pytest.skip() if test_cli_utilities.get_gdal_translate_path() is None: - return 'skip' + pytest.skip() gdaltest.runexternal(test_cli_utilities.get_gdaldem_path() + ' color-relief -of PNG tmp/n43_float32.tif data/color_file.txt tmp/n43_colorrelief_from_float32.png') ds = gdal.Open('tmp/n43_colorrelief_from_float32.png') - if ds is None: - return 'fail' + assert ds is not None - if ds.GetRasterBand(1).Checksum() != 55009: - print(ds.GetRasterBand(1).Checksum()) - gdaltest.post_reason('Bad checksum') - return 'fail' + assert ds.GetRasterBand(1).Checksum() == 55009, 'Bad checksum' - if ds.GetRasterBand(2).Checksum() != 37543: - print(ds.GetRasterBand(2).Checksum()) - gdaltest.post_reason('Bad checksum') - return 'fail' + assert ds.GetRasterBand(2).Checksum() == 37543, 'Bad checksum' - if ds.GetRasterBand(3).Checksum() != 47711: - print(ds.GetRasterBand(3).Checksum()) - gdaltest.post_reason('Bad checksum') - return 'fail' + assert ds.GetRasterBand(3).Checksum() == 47711, 'Bad checksum' ds = None - return 'success' - ############################################################################### # Test gdaldem color relief with -nearest_color_entry def test_gdaldem_color_relief_nearest_color_entry(): if test_cli_utilities.get_gdaldem_path() is None: - return 'skip' + pytest.skip() gdaltest.runexternal(test_cli_utilities.get_gdaldem_path() + ' color-relief -nearest_color_entry ../gdrivers/data/n43.dt0 data/color_file.txt tmp/n43_colorrelief_nearest.tif') ds = gdal.Open('tmp/n43_colorrelief_nearest.tif') - if ds is None: - return 'fail' + assert ds is not None - if ds.GetRasterBand(1).Checksum() != 57296: - print(ds.GetRasterBand(1).Checksum()) - gdaltest.post_reason('Bad checksum') - return 'fail' + assert ds.GetRasterBand(1).Checksum() == 57296, 'Bad checksum' - if ds.GetRasterBand(2).Checksum() != 42926: - print(ds.GetRasterBand(2).Checksum()) - gdaltest.post_reason('Bad checksum') - return 'fail' + assert ds.GetRasterBand(2).Checksum() == 42926, 'Bad checksum' - if ds.GetRasterBand(3).Checksum() != 47181: - print(ds.GetRasterBand(3).Checksum()) - gdaltest.post_reason('Bad checksum') - return 'fail' + assert ds.GetRasterBand(3).Checksum() == 47181, 'Bad checksum' ds = None - return 'success' - ############################################################################### # Test gdaldem color relief with -nearest_color_entry and -of VRT def test_gdaldem_color_relief_nearest_color_entry_vrt(): if test_cli_utilities.get_gdaldem_path() is None: - return 'skip' + pytest.skip() gdaltest.runexternal(test_cli_utilities.get_gdaldem_path() + ' color-relief -of VRT -nearest_color_entry ../gdrivers/data/n43.dt0 data/color_file.txt tmp/n43_colorrelief_nearest.vrt') ds = gdal.Open('tmp/n43_colorrelief_nearest.vrt') - if ds is None: - return 'fail' + assert ds is not None - if ds.GetRasterBand(1).Checksum() != 57296: - print(ds.GetRasterBand(1).Checksum()) - gdaltest.post_reason('Bad checksum') - return 'fail' + assert ds.GetRasterBand(1).Checksum() == 57296, 'Bad checksum' - if ds.GetRasterBand(2).Checksum() != 42926: - print(ds.GetRasterBand(2).Checksum()) - gdaltest.post_reason('Bad checksum') - return 'fail' + assert ds.GetRasterBand(2).Checksum() == 42926, 'Bad checksum' - if ds.GetRasterBand(3).Checksum() != 47181: - print(ds.GetRasterBand(3).Checksum()) - gdaltest.post_reason('Bad checksum') - return 'fail' + assert ds.GetRasterBand(3).Checksum() == 47181, 'Bad checksum' ds = None - return 'success' - ############################################################################### # Test gdaldem color relief with a nan nodata def test_gdaldem_color_relief_nodata_nan(): if test_cli_utilities.get_gdaldem_path() is None: - return 'skip' + pytest.skip() f = open('tmp/nodata_nan_src.asc', 'wt') f.write("""ncols 2 @@ -677,24 +494,19 @@ def test_gdaldem_color_relief_nodata_nan(): import struct val = struct.unpack('B' * 4, val) - if val != (0, 0, 0, 1): - gdaltest.post_reason('fail') - print(val) - return 'fail' + assert val == (0, 0, 0, 1) os.unlink('tmp/nodata_nan_src.asc') os.unlink('tmp/nodata_nan_plt.txt') os.unlink('tmp/nodata_nan_out.tif') - return 'success' - ############################################################################### # Test gdaldem color relief with entries with repeated DEM values in the color table (#6422) def test_gdaldem_color_relief_repeated_entry(): if test_cli_utilities.get_gdaldem_path() is None: - return 'skip' + pytest.skip() f = open('tmp/test_gdaldem_color_relief_repeated_entry.asc', 'wt') f.write("""ncols 2 @@ -716,7 +528,10 @@ def test_gdaldem_color_relief_repeated_entry(): f.write('nv 5 5 5\n') f.close() - gdaltest.runexternal(test_cli_utilities.get_gdaldem_path() + ' color-relief tmp/test_gdaldem_color_relief_repeated_entry.asc tmp/test_gdaldem_color_relief_repeated_entry.txt tmp/test_gdaldem_color_relief_repeated_entry_out.tif') + gdaltest.runexternal( + test_cli_utilities.get_gdaldem_path() + ' color-relief tmp/test_gdaldem_color_relief_repeated_entry.asc tmp/test_gdaldem_color_relief_repeated_entry.txt tmp/test_gdaldem_color_relief_repeated_entry_out.tif', + display_live_on_parent_stdout=True, + ) ds = gdal.Open('tmp/test_gdaldem_color_relief_repeated_entry_out.tif') val = ds.GetRasterBand(1).ReadRaster() @@ -724,30 +539,25 @@ def test_gdaldem_color_relief_repeated_entry(): import struct val = struct.unpack('B' * 6, val) - if val != (1, 1, 5, 10, 10, 25): - gdaltest.post_reason('fail') - print(val) - return 'fail' + assert val == (1, 1, 5, 10, 10, 25) - gdaltest.runexternal(test_cli_utilities.get_gdaldem_path() + ' color-relief tmp/test_gdaldem_color_relief_repeated_entry.asc tmp/test_gdaldem_color_relief_repeated_entry.txt tmp/test_gdaldem_color_relief_repeated_entry_out.vrt -of VRT') + gdaltest.runexternal( + test_cli_utilities.get_gdaldem_path() + ' color-relief tmp/test_gdaldem_color_relief_repeated_entry.asc tmp/test_gdaldem_color_relief_repeated_entry.txt tmp/test_gdaldem_color_relief_repeated_entry_out.vrt -of VRT', + display_live_on_parent_stdout=True, + ) ds = gdal.Open('tmp/test_gdaldem_color_relief_repeated_entry_out.vrt') val = ds.GetRasterBand(1).ReadRaster() ds = None val = struct.unpack('B' * 6, val) - if val != (1, 1, 5, 10, 10, 25): - gdaltest.post_reason('fail') - print(val) - return 'fail' + assert val == (1, 1, 5, 10, 10, 25) os.unlink('tmp/test_gdaldem_color_relief_repeated_entry.asc') os.unlink('tmp/test_gdaldem_color_relief_repeated_entry.txt') os.unlink('tmp/test_gdaldem_color_relief_repeated_entry_out.tif') os.unlink('tmp/test_gdaldem_color_relief_repeated_entry_out.vrt') - return 'success' - ############################################################################### # Cleanup @@ -827,37 +637,7 @@ def test_gdaldem_cleanup(): os.remove('tmp/n43_colorrelief_nearest.vrt') except OSError: pass - return 'success' - - -gdaltest_list = [ - test_gdaldem_hillshade, - test_gdaldem_hillshade_compressed_tiled_output, - test_gdaldem_hillshade_combined, - test_gdaldem_hillshade_compute_edges, - test_gdaldem_hillshade_azimuth, - test_gdaldem_hillshade_png, - test_gdaldem_hillshade_png_compute_edges, - test_gdaldem_slope, - test_gdaldem_aspect, - test_gdaldem_color_relief, - test_gdaldem_color_relief_cpt, - test_gdaldem_color_relief_vrt, - test_gdaldem_color_relief_from_float32, - test_gdaldem_color_relief_png, - test_gdaldem_color_relief_from_float32_to_png, - test_gdaldem_color_relief_nearest_color_entry, - test_gdaldem_color_relief_nearest_color_entry_vrt, - test_gdaldem_color_relief_nodata_nan, - test_gdaldem_color_relief_repeated_entry, - test_gdaldem_cleanup -] - - -if __name__ == '__main__': - - gdaltest.setup_run('test_gdaldem') - - gdaltest.run_tests(gdaltest_list) - - sys.exit(gdaltest.summarize()) + + + + diff --git a/autotest/utilities/test_gdaldem_lib.py b/autotest/utilities/test_gdaldem_lib.py index 6cd723ebcfa4..6c4c2dacae11 100755 --- a/autotest/utilities/test_gdaldem_lib.py +++ b/autotest/utilities/test_gdaldem_lib.py @@ -30,13 +30,12 @@ ############################################################################### import struct -import sys -sys.path.append('../pymod') from osgeo import gdal from osgeo import osr import gdaltest +import pytest ############################################################################### # Test gdaldem hillshade @@ -46,36 +45,24 @@ def test_gdaldem_lib_hillshade(): src_ds = gdal.Open('../gdrivers/data/n43.dt0') ds = gdal.DEMProcessing('', src_ds, 'hillshade', format='MEM', scale=111120, zFactor=30) - if ds is None: - return 'fail' + assert ds is not None cs = ds.GetRasterBand(1).Checksum() - if cs != 45587: - gdaltest.post_reason('Bad checksum') - print(cs) - return 'fail' + assert cs == 45587, 'Bad checksum' src_gt = src_ds.GetGeoTransform() dst_gt = ds.GetGeoTransform() for i in range(6): - if abs(src_gt[i] - dst_gt[i]) > 1e-10: - gdaltest.post_reason('Bad geotransform') - return 'fail' + assert abs(src_gt[i] - dst_gt[i]) <= 1e-10, 'Bad geotransform' dst_wkt = ds.GetProjectionRef() - if dst_wkt.find('AUTHORITY["EPSG","4326"]') == -1: - gdaltest.post_reason('Bad projection') - return 'fail' + assert dst_wkt.find('AUTHORITY["EPSG","4326"]') != -1, 'Bad projection' - if ds.GetRasterBand(1).GetNoDataValue() != 0: - gdaltest.post_reason('Bad nodata value') - return 'fail' + assert ds.GetRasterBand(1).GetNoDataValue() == 0, 'Bad nodata value' src_ds = None ds = None - return 'success' - ############################################################################### # Test gdaldem hillshade with source being floating point @@ -84,36 +71,24 @@ def test_gdaldem_lib_hillshade_float(): src_ds = gdal.Translate('', gdal.Open('../gdrivers/data/n43.dt0'), format='MEM', outputType=gdal.GDT_Float32) ds = gdal.DEMProcessing('', src_ds, 'hillshade', format='MEM', scale=111120, zFactor=30) - if ds is None: - return 'fail' + assert ds is not None cs = ds.GetRasterBand(1).Checksum() - if cs != 45587: - gdaltest.post_reason('Bad checksum') - print(cs) - return 'fail' + assert cs == 45587, 'Bad checksum' src_gt = src_ds.GetGeoTransform() dst_gt = ds.GetGeoTransform() for i in range(6): - if abs(src_gt[i] - dst_gt[i]) > 1e-10: - gdaltest.post_reason('Bad geotransform') - return 'fail' + assert abs(src_gt[i] - dst_gt[i]) <= 1e-10, 'Bad geotransform' dst_wkt = ds.GetProjectionRef() - if dst_wkt.find('AUTHORITY["EPSG","4326"]') == -1: - gdaltest.post_reason('Bad projection') - return 'fail' + assert dst_wkt.find('AUTHORITY["EPSG","4326"]') != -1, 'Bad projection' - if ds.GetRasterBand(1).GetNoDataValue() != 0: - gdaltest.post_reason('Bad nodata value') - return 'fail' + assert ds.GetRasterBand(1).GetNoDataValue() == 0, 'Bad nodata value' src_ds = None ds = None - return 'success' - ############################################################################### # Test gdaldem hillshade with source being floating point @@ -122,38 +97,26 @@ def test_gdaldem_lib_hillshade_float_png(): src_ds = gdal.Translate('', gdal.Open('../gdrivers/data/n43.dt0'), format='MEM', outputType=gdal.GDT_Float32) ds = gdal.DEMProcessing('/vsimem/test_gdaldem_lib_hillshade_float_png.png', src_ds, 'hillshade', format='PNG', scale=111120, zFactor=30) - if ds is None: - return 'fail' + assert ds is not None cs = ds.GetRasterBand(1).Checksum() - if cs != 45587: - gdaltest.post_reason('Bad checksum') - print(cs) - return 'fail' + assert cs == 45587, 'Bad checksum' src_gt = src_ds.GetGeoTransform() dst_gt = ds.GetGeoTransform() for i in range(6): - if abs(src_gt[i] - dst_gt[i]) > 1e-10: - gdaltest.post_reason('Bad geotransform') - return 'fail' + assert abs(src_gt[i] - dst_gt[i]) <= 1e-10, 'Bad geotransform' dst_wkt = ds.GetProjectionRef() - if dst_wkt.find('AUTHORITY["EPSG","4326"]') == -1: - gdaltest.post_reason('Bad projection') - return 'fail' + assert dst_wkt.find('AUTHORITY["EPSG","4326"]') != -1, 'Bad projection' - if ds.GetRasterBand(1).GetNoDataValue() != 0: - gdaltest.post_reason('Bad nodata value') - return 'fail' + assert ds.GetRasterBand(1).GetNoDataValue() == 0, 'Bad nodata value' src_ds = None ds = None gdal.GetDriverByName('PNG').Delete('/vsimem/test_gdaldem_lib_hillshade_float_png.png') - return 'success' - ############################################################################### # Test gdaldem hillshade -combined @@ -162,36 +125,24 @@ def test_gdaldem_lib_hillshade_combined(): src_ds = gdal.Open('../gdrivers/data/n43.dt0') ds = gdal.DEMProcessing('', src_ds, 'hillshade', format='MEM', combined=True, scale=111120, zFactor=30) - if ds is None: - return 'fail' + assert ds is not None cs = ds.GetRasterBand(1).Checksum() - if cs != 43876: - gdaltest.post_reason('Bad checksum') - print(cs) - return 'fail' + assert cs == 43876, 'Bad checksum' src_gt = src_ds.GetGeoTransform() dst_gt = ds.GetGeoTransform() for i in range(6): - if abs(src_gt[i] - dst_gt[i]) > 1e-10: - gdaltest.post_reason('Bad geotransform') - return 'fail' + assert abs(src_gt[i] - dst_gt[i]) <= 1e-10, 'Bad geotransform' dst_wkt = ds.GetProjectionRef() - if dst_wkt.find('AUTHORITY["EPSG","4326"]') == -1: - gdaltest.post_reason('Bad projection') - return 'fail' + assert dst_wkt.find('AUTHORITY["EPSG","4326"]') != -1, 'Bad projection' - if ds.GetRasterBand(1).GetNoDataValue() != 0: - gdaltest.post_reason('Bad nodata value') - return 'fail' + assert ds.GetRasterBand(1).GetNoDataValue() == 0, 'Bad nodata value' src_ds = None ds = None - return 'success' - ############################################################################### # Test gdaldem hillshade -alg ZevenbergenThorne @@ -200,36 +151,24 @@ def test_gdaldem_lib_hillshade_ZevenbergenThorne(): src_ds = gdal.Open('../gdrivers/data/n43.dt0') ds = gdal.DEMProcessing('', src_ds, 'hillshade', format='MEM', alg='ZevenbergenThorne', scale=111120, zFactor=30) - if ds is None: - return 'fail' + assert ds is not None cs = ds.GetRasterBand(1).Checksum() - if cs != 46544: - gdaltest.post_reason('Bad checksum') - print(cs) - return 'fail' + assert cs == 46544, 'Bad checksum' src_gt = src_ds.GetGeoTransform() dst_gt = ds.GetGeoTransform() for i in range(6): - if abs(src_gt[i] - dst_gt[i]) > 1e-10: - gdaltest.post_reason('Bad geotransform') - return 'fail' + assert abs(src_gt[i] - dst_gt[i]) <= 1e-10, 'Bad geotransform' dst_wkt = ds.GetProjectionRef() - if dst_wkt.find('AUTHORITY["EPSG","4326"]') == -1: - gdaltest.post_reason('Bad projection') - return 'fail' + assert dst_wkt.find('AUTHORITY["EPSG","4326"]') != -1, 'Bad projection' - if ds.GetRasterBand(1).GetNoDataValue() != 0: - gdaltest.post_reason('Bad nodata value') - return 'fail' + assert ds.GetRasterBand(1).GetNoDataValue() == 0, 'Bad nodata value' src_ds = None ds = None - return 'success' - ############################################################################### # Test gdaldem hillshade -alg ZevenbergenThorne -combined @@ -238,36 +177,24 @@ def test_gdaldem_lib_hillshade_ZevenbergenThorne_combined(): src_ds = gdal.Open('../gdrivers/data/n43.dt0') ds = gdal.DEMProcessing('', src_ds, 'hillshade', format='MEM', alg='ZevenbergenThorne', combined=True, scale=111120, zFactor=30) - if ds is None: - return 'fail' + assert ds is not None cs = ds.GetRasterBand(1).Checksum() - if cs != 43112: - gdaltest.post_reason('Bad checksum') - print(cs) - return 'fail' + assert cs == 43112, 'Bad checksum' src_gt = src_ds.GetGeoTransform() dst_gt = ds.GetGeoTransform() for i in range(6): - if abs(src_gt[i] - dst_gt[i]) > 1e-10: - gdaltest.post_reason('Bad geotransform') - return 'fail' + assert abs(src_gt[i] - dst_gt[i]) <= 1e-10, 'Bad geotransform' dst_wkt = ds.GetProjectionRef() - if dst_wkt.find('AUTHORITY["EPSG","4326"]') == -1: - gdaltest.post_reason('Bad projection') - return 'fail' + assert dst_wkt.find('AUTHORITY["EPSG","4326"]') != -1, 'Bad projection' - if ds.GetRasterBand(1).GetNoDataValue() != 0: - gdaltest.post_reason('Bad nodata value') - return 'fail' + assert ds.GetRasterBand(1).GetNoDataValue() == 0, 'Bad nodata value' src_ds = None ds = None - return 'success' - ############################################################################### # Test gdaldem hillshade with -compute_edges @@ -276,19 +203,13 @@ def test_gdaldem_lib_hillshade_compute_edges(): src_ds = gdal.Open('../gdrivers/data/n43.dt0') ds = gdal.DEMProcessing('', src_ds, 'hillshade', format='MEM', computeEdges=True, scale=111120, zFactor=30) - if ds is None: - return 'fail' + assert ds is not None cs = ds.GetRasterBand(1).Checksum() - if cs != 50239: - gdaltest.post_reason('Bad checksum') - print(cs) - return 'fail' + assert cs == 50239, 'Bad checksum' ds = None - return 'success' - ############################################################################### # Test gdaldem hillshade with -compute_edges with floating point @@ -297,19 +218,13 @@ def test_gdaldem_lib_hillshade_compute_edges_float(): src_ds = gdal.Translate('', gdal.Open('../gdrivers/data/n43.dt0'), format='MEM', outputType=gdal.GDT_Float32) ds = gdal.DEMProcessing('', src_ds, 'hillshade', format='MEM', computeEdges=True, scale=111120, zFactor=30) - if ds is None: - return 'fail' + assert ds is not None cs = ds.GetRasterBand(1).Checksum() - if cs != 50239: - gdaltest.post_reason('Bad checksum') - print(cs) - return 'fail' + assert cs == 50239, 'Bad checksum' ds = None - return 'success' - ############################################################################### # Test gdaldem hillshade with -az parameter @@ -333,17 +248,12 @@ def test_gdaldem_lib_hillshade_azimuth(): # Light from the east ds = gdal.DEMProcessing('', src_ds, 'hillshade', format='MEM', azimuth=90, scale=111120, zFactor=100) - if ds is None: - return 'fail' + assert ds is not None ds_ref = gdal.Open('data/pyramid_shaded_ref.tif') - if gdaltest.compare_ds(ds, ds_ref, verbose=1) > 1: - gdaltest.post_reason('Bad checksum') - return 'fail' + assert gdaltest.compare_ds(ds, ds_ref, verbose=1) <= 1, 'Bad checksum' ds = None ds_ref = None - return 'success' - ############################################################################### # Test gdaldem hillshade -multidirectional @@ -352,19 +262,13 @@ def test_gdaldem_lib_hillshade_multidirectional(): src_ds = gdal.Open('../gdrivers/data/n43.dt0') ds = gdal.DEMProcessing('', src_ds, 'hillshade', format='MEM', multiDirectional=True, computeEdges=True, scale=111120, zFactor=30) - if ds is None: - return 'fail' + assert ds is not None cs = ds.GetRasterBand(1).Checksum() - if cs != 51784: - gdaltest.post_reason('Bad checksum') - print(cs) - return 'fail' + assert cs == 51784, 'Bad checksum' ds = None - return 'success' - ############################################################################### # Test gdaldem hillshade -multidirectional @@ -373,19 +277,13 @@ def test_gdaldem_lib_hillshade_multidirectional_ZevenbergenThorne(): src_ds = gdal.Open('../gdrivers/data/n43.dt0') ds = gdal.DEMProcessing('', src_ds, 'hillshade', format='MEM', alg='ZevenbergenThorne', multiDirectional=True, computeEdges=True, scale=111120, zFactor=30) - if ds is None: - return 'fail' + assert ds is not None cs = ds.GetRasterBand(1).Checksum() - if cs != 50860: - gdaltest.post_reason('Bad checksum') - print(cs) - return 'fail' + assert cs == 50860, 'Bad checksum' ds = None - return 'success' - ############################################################################### # Test gdaldem color relief @@ -394,46 +292,28 @@ def test_gdaldem_lib_color_relief(): src_ds = gdal.Open('../gdrivers/data/n43.dt0') ds = gdal.DEMProcessing('', src_ds, 'color-relief', format='MEM', colorFilename='data/color_file.txt') - if ds is None: - return 'fail' + assert ds is not None - if ds.GetRasterBand(1).Checksum() != 55009: - print(ds.GetRasterBand(1).Checksum()) - gdaltest.post_reason('Bad checksum') - return 'fail' + assert ds.GetRasterBand(1).Checksum() == 55009, 'Bad checksum' - if ds.GetRasterBand(2).Checksum() != 37543: - print(ds.GetRasterBand(2).Checksum()) - gdaltest.post_reason('Bad checksum') - return 'fail' + assert ds.GetRasterBand(2).Checksum() == 37543, 'Bad checksum' - if ds.GetRasterBand(3).Checksum() != 47711: - print(ds.GetRasterBand(3).Checksum()) - gdaltest.post_reason('Bad checksum') - return 'fail' + assert ds.GetRasterBand(3).Checksum() == 47711, 'Bad checksum' src_gt = src_ds.GetGeoTransform() dst_gt = ds.GetGeoTransform() for i in range(6): - if abs(src_gt[i] - dst_gt[i]) > 1e-10: - gdaltest.post_reason('Bad geotransform') - return 'fail' + assert abs(src_gt[i] - dst_gt[i]) <= 1e-10, 'Bad geotransform' dst_wkt = ds.GetProjectionRef() - if dst_wkt.find('AUTHORITY["EPSG","4326"]') == -1: - gdaltest.post_reason('Bad projection') - return 'fail' + assert dst_wkt.find('AUTHORITY["EPSG","4326"]') != -1, 'Bad projection' ds = gdal.DEMProcessing('', src_ds, 'color-relief', format='MEM', colorFilename='data/color_file.txt', addAlpha=True) - if ds.RasterCount != 4: - gdaltest.post_reason('Bad RasterCount') - return 'fail' + assert ds.RasterCount == 4, 'Bad RasterCount' src_ds = None ds = None - return 'success' - ############################################################################### # Test gdaldem tpi @@ -442,19 +322,13 @@ def test_gdaldem_lib_tpi(): src_ds = gdal.Open('../gdrivers/data/n43.dt0') ds = gdal.DEMProcessing('', src_ds, 'tpi', format='MEM') - if ds is None: - return 'fail' + assert ds is not None cs = ds.GetRasterBand(1).Checksum() - if cs != 60504: - gdaltest.post_reason('Bad checksum') - print(cs) - return 'fail' + assert cs == 60504, 'Bad checksum' ds = None - return 'success' - ############################################################################### # Test gdaldem tri @@ -463,19 +337,13 @@ def test_gdaldem_lib_tri(): src_ds = gdal.Open('../gdrivers/data/n43.dt0') ds = gdal.DEMProcessing('', src_ds, 'tri', format='MEM') - if ds is None: - return 'fail' + assert ds is not None cs = ds.GetRasterBand(1).Checksum() - if cs != 61143: - gdaltest.post_reason('Bad checksum') - print(cs) - return 'fail' + assert cs == 61143, 'Bad checksum' ds = None - return 'success' - ############################################################################### # Test gdaldem roughness @@ -484,19 +352,13 @@ def test_gdaldem_lib_roughness(): src_ds = gdal.Open('../gdrivers/data/n43.dt0') ds = gdal.DEMProcessing('', src_ds, 'roughness', format='MEM') - if ds is None: - return 'fail' + assert ds is not None cs = ds.GetRasterBand(1).Checksum() - if cs != 38624: - gdaltest.post_reason('Bad checksum') - print(cs) - return 'fail' + assert cs == 38624, 'Bad checksum' ds = None - return 'success' - ############################################################################### # Test gdaldem slope -alg ZevenbergenThorne @@ -505,16 +367,10 @@ def test_gdaldem_lib_slope_ZevenbergenThorne(): src_ds = gdal.Open('../gdrivers/data/n43.dt0') ds = gdal.DEMProcessing('', src_ds, 'slope', format='MEM', alg='ZevenbergenThorne', scale=111120, zFactor=30) - if ds is None: - return 'fail' + assert ds is not None cs = ds.GetRasterBand(1).Checksum() - if cs != 64393: - gdaltest.post_reason('Bad checksum') - print(cs) - return 'fail' - - return 'success' + assert cs == 64393, 'Bad checksum' ############################################################################### # Test gdaldem aspect -alg ZevenbergenThorne @@ -524,16 +380,10 @@ def test_gdaldem_lib_aspect_ZevenbergenThorne(): src_ds = gdal.Open('../gdrivers/data/n43.dt0') ds = gdal.DEMProcessing('', src_ds, 'aspect', format='MEM', alg='ZevenbergenThorne', scale=111120, zFactor=30) - if ds is None: - return 'fail' + assert ds is not None cs = ds.GetRasterBand(1).Checksum() - if cs != 50539: - gdaltest.post_reason('Bad checksum') - print(cs) - return 'fail' - - return 'success' + assert cs == 50539, 'Bad checksum' ############################################################################### # Test gdaldem hillshade with nodata values @@ -555,14 +405,10 @@ def test_gdaldem_lib_nodata(): src_ds.GetRasterBand(1).Fill(value) ds = gdal.DEMProcessing('', src_ds, 'hillshade', format='MEM') - if ds is None: - return 'fail' + assert ds is not None cs = ds.GetRasterBand(1).Checksum() - if cs != 0: - gdaltest.post_reason('Bad checksum') - print(cs) - return 'fail' + assert cs == 0, 'Bad checksum' src_ds = None ds = None @@ -574,18 +420,14 @@ def test_gdaldem_lib_nodata(): ds = gdal.DEMProcessing('', src_ds, 'hillshade', format='MEM') cs = ds.GetRasterBand(1).Checksum() if cs != 0: - gdaltest.post_reason('Bad checksum') - print(cs) print(ds.ReadAsArray()) - return 'fail' + pytest.fail('Bad checksum') ds = gdal.DEMProcessing('', src_ds, 'hillshade', format='MEM', computeEdges=True) cs = ds.GetRasterBand(1).Checksum() if cs != 10: - gdaltest.post_reason('Bad checksum') - print(cs) print(ds.ReadAsArray()) # Should be 0 0 0 0 181 0 0 0 0 - return 'fail' + pytest.fail('Bad checksum') # Same with floating point src_ds = gdal.GetDriverByName('MEM').Create('', 3, 3, 1, gdal.GDT_Float32) @@ -595,48 +437,16 @@ def test_gdaldem_lib_nodata(): ds = gdal.DEMProcessing('', src_ds, 'hillshade', format='MEM') cs = ds.GetRasterBand(1).Checksum() if cs != 0: - gdaltest.post_reason('Bad checksum') - print(cs) print(ds.ReadAsArray()) - return 'fail' + pytest.fail('Bad checksum') ds = gdal.DEMProcessing('', src_ds, 'hillshade', format='MEM', computeEdges=True) cs = ds.GetRasterBand(1).Checksum() if cs != 10: - gdaltest.post_reason('Bad checksum') - print(cs) print(ds.ReadAsArray()) # Should be 0 0 0 0 181 0 0 0 0 - return 'fail' - - return 'success' - - -gdaltest_list = [ - test_gdaldem_lib_hillshade, - test_gdaldem_lib_hillshade_float, - test_gdaldem_lib_hillshade_float_png, - test_gdaldem_lib_hillshade_combined, - test_gdaldem_lib_hillshade_ZevenbergenThorne, - test_gdaldem_lib_hillshade_ZevenbergenThorne_combined, - test_gdaldem_lib_hillshade_compute_edges, - test_gdaldem_lib_hillshade_compute_edges_float, - test_gdaldem_lib_hillshade_azimuth, - test_gdaldem_lib_hillshade_multidirectional, - test_gdaldem_lib_hillshade_multidirectional_ZevenbergenThorne, - test_gdaldem_lib_color_relief, - test_gdaldem_lib_tpi, - test_gdaldem_lib_tri, - test_gdaldem_lib_roughness, - test_gdaldem_lib_slope_ZevenbergenThorne, - test_gdaldem_lib_aspect_ZevenbergenThorne, - test_gdaldem_lib_nodata -] - + pytest.fail('Bad checksum') -if __name__ == '__main__': + - gdaltest.setup_run('test_gdaldem_lib') - gdaltest.run_tests(gdaltest_list) - sys.exit(gdaltest.summarize()) diff --git a/autotest/utilities/test_gdalinfo.py b/autotest/utilities/test_gdalinfo.py index ad5824afa680..61982e4551ce 100755 --- a/autotest/utilities/test_gdalinfo.py +++ b/autotest/utilities/test_gdalinfo.py @@ -29,15 +29,14 @@ # DEALINGS IN THE SOFTWARE. ############################################################################### -import sys import os import json -sys.path.append('../pymod') from osgeo import gdal import gdaltest import test_cli_utilities +import pytest ############################################################################### # Simple test @@ -45,17 +44,11 @@ def test_gdalinfo_1(): if test_cli_utilities.get_gdalinfo_path() is None: - return 'skip' + pytest.skip() (ret, err) = gdaltest.runexternal_out_and_err(test_cli_utilities.get_gdalinfo_path() + ' ../gcore/data/byte.tif') - if not (err is None or err == ''): - gdaltest.post_reason('got error/warning') - print(err) - return 'fail' - if ret.find('Driver: GTiff/GeoTIFF') == -1: - return 'fail' - - return 'success' + assert (err is None or err == ''), 'got error/warning' + assert ret.find('Driver: GTiff/GeoTIFF') != -1 ############################################################################### # Test -checksum option @@ -63,13 +56,10 @@ def test_gdalinfo_1(): def test_gdalinfo_2(): if test_cli_utilities.get_gdalinfo_path() is None: - return 'skip' + pytest.skip() ret = gdaltest.runexternal(test_cli_utilities.get_gdalinfo_path() + ' -checksum ../gcore/data/byte.tif') - if ret.find('Checksum=4672') == -1: - return 'fail' - - return 'success' + assert ret.find('Checksum=4672') != -1 ############################################################################### # Test -nomd option @@ -77,17 +67,13 @@ def test_gdalinfo_2(): def test_gdalinfo_3(): if test_cli_utilities.get_gdalinfo_path() is None: - return 'skip' + pytest.skip() ret = gdaltest.runexternal(test_cli_utilities.get_gdalinfo_path() + ' ../gcore/data/byte.tif') - if ret.find('Metadata') == -1: - return 'fail' + assert ret.find('Metadata') != -1 ret = gdaltest.runexternal(test_cli_utilities.get_gdalinfo_path() + ' -nomd ../gcore/data/byte.tif') - if ret.find('Metadata') != -1: - return 'fail' - - return 'success' + assert ret.find('Metadata') == -1 ############################################################################### # Test -noct option @@ -95,17 +81,13 @@ def test_gdalinfo_3(): def test_gdalinfo_4(): if test_cli_utilities.get_gdalinfo_path() is None: - return 'skip' + pytest.skip() ret = gdaltest.runexternal(test_cli_utilities.get_gdalinfo_path() + ' ../gdrivers/data/bug407.gif') - if ret.find('0: 255,255,255,255') == -1: - return 'fail' + assert ret.find('0: 255,255,255,255') != -1 ret = gdaltest.runexternal(test_cli_utilities.get_gdalinfo_path() + ' -noct ../gdrivers/data/bug407.gif') - if ret.find('0: 255,255,255,255') != -1: - return 'fail' - - return 'success' + assert ret.find('0: 255,255,255,255') == -1 ############################################################################### # Test -stats option @@ -113,7 +95,7 @@ def test_gdalinfo_4(): def test_gdalinfo_5(): if test_cli_utilities.get_gdalinfo_path() is None: - return 'skip' + pytest.skip() try: os.remove('../gcore/data/byte.tif.aux.xml') @@ -121,37 +103,25 @@ def test_gdalinfo_5(): pass ret = gdaltest.runexternal(test_cli_utilities.get_gdalinfo_path() + ' ../gcore/data/byte.tif') - if ret.find('STATISTICS_MINIMUM=74') != -1: - gdaltest.post_reason('got wrong minimum.') - print(ret) - return 'fail' + assert ret.find('STATISTICS_MINIMUM=74') == -1, 'got wrong minimum.' ret = gdaltest.runexternal(test_cli_utilities.get_gdalinfo_path() + ' -stats ../gcore/data/byte.tif') - if ret.find('STATISTICS_MINIMUM=74') == -1: - gdaltest.post_reason('got wrong minimum (2).') - print(ret) - return 'fail' + assert ret.find('STATISTICS_MINIMUM=74') != -1, 'got wrong minimum (2).' # We will blow an exception if the file does not exist now! os.remove('../gcore/data/byte.tif.aux.xml') - return 'success' - ############################################################################### # Test a dataset with overviews and RAT def test_gdalinfo_6(): if test_cli_utilities.get_gdalinfo_path() is None: - return 'skip' + pytest.skip() ret = gdaltest.runexternal(test_cli_utilities.get_gdalinfo_path() + ' ../gdrivers/data/int.img') - if ret.find('Overviews') == -1: - return 'fail' - if ret.find('GDALRasterAttributeTable') == -1: - return 'fail' - - return 'success' + assert ret.find('Overviews') != -1 + assert ret.find('GDALRasterAttributeTable') != -1 ############################################################################### # Test a dataset with GCPs @@ -159,26 +129,18 @@ def test_gdalinfo_6(): def test_gdalinfo_7(): if test_cli_utilities.get_gdalinfo_path() is None: - return 'skip' + pytest.skip() ret = gdaltest.runexternal(test_cli_utilities.get_gdalinfo_path() + ' ../gcore/data/gcps.vrt') - if ret.find('GCP Projection =') == -1: - return 'fail' - if ret.find('PROJCS["NAD27 / UTM zone 11N"') == -1: - return 'fail' - if ret.find('(100,100) -> (446720,3745320,0)') == -1: - return 'fail' + assert ret.find('GCP Projection =') != -1 + assert ret.find('PROJCS["NAD27 / UTM zone 11N"') != -1 + assert ret.find('(100,100) -> (446720,3745320,0)') != -1 # Same but with -nogcps ret = gdaltest.runexternal(test_cli_utilities.get_gdalinfo_path() + ' -nogcp ../gcore/data/gcps.vrt') - if ret.find('GCP Projection =') != -1: - return 'fail' - if ret.find('PROJCS["NAD27 / UTM zone 11N"') != -1: - return 'fail' - if ret.find('(100,100) -> (446720,3745320,0)') != -1: - return 'fail' - - return 'success' + assert ret.find('GCP Projection =') == -1 + assert ret.find('PROJCS["NAD27 / UTM zone 11N"') == -1 + assert ret.find('(100,100) -> (446720,3745320,0)') == -1 ############################################################################### # Test -hist option @@ -186,7 +148,7 @@ def test_gdalinfo_7(): def test_gdalinfo_8(): if test_cli_utilities.get_gdalinfo_path() is None: - return 'skip' + pytest.skip() try: os.remove('../gcore/data/byte.tif.aux.xml') @@ -194,43 +156,29 @@ def test_gdalinfo_8(): pass ret = gdaltest.runexternal(test_cli_utilities.get_gdalinfo_path() + ' ../gcore/data/byte.tif') - if ret.find('0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 6 0 0 0 0 0 0 0 0 37 0 0 0 0 0 0 0 57 0 0 0 0 0 0 0 62 0 0 0 0 0 0 0 66 0 0 0 0 0 0 0 0 72 0 0 0 0 0 0 0 31 0 0 0 0 0 0 0 24 0 0 0 0 0 0 0 12 0 0 0 0 0 0 0 0 7 0 0 0 0 0 0 0 12 0 0 0 0 0 0 0 5 0 0 0 0 0 0 0 3 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 2 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 1') != -1: - gdaltest.post_reason('did not expect histogram.') - print(ret) - return 'fail' + assert ret.find('0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 6 0 0 0 0 0 0 0 0 37 0 0 0 0 0 0 0 57 0 0 0 0 0 0 0 62 0 0 0 0 0 0 0 66 0 0 0 0 0 0 0 0 72 0 0 0 0 0 0 0 31 0 0 0 0 0 0 0 24 0 0 0 0 0 0 0 12 0 0 0 0 0 0 0 0 7 0 0 0 0 0 0 0 12 0 0 0 0 0 0 0 5 0 0 0 0 0 0 0 3 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 2 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 1') == -1, \ + 'did not expect histogram.' ret = gdaltest.runexternal(test_cli_utilities.get_gdalinfo_path() + ' -hist ../gcore/data/byte.tif') - if ret.find('0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 6 0 0 0 0 0 0 0 0 37 0 0 0 0 0 0 0 57 0 0 0 0 0 0 0 62 0 0 0 0 0 0 0 66 0 0 0 0 0 0 0 0 72 0 0 0 0 0 0 0 31 0 0 0 0 0 0 0 24 0 0 0 0 0 0 0 12 0 0 0 0 0 0 0 0 7 0 0 0 0 0 0 0 12 0 0 0 0 0 0 0 5 0 0 0 0 0 0 0 3 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 2 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 1') == -1: - gdaltest.post_reason('did not get expected histogram.') - print(ret) - return 'fail' + assert ret.find('0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 6 0 0 0 0 0 0 0 0 37 0 0 0 0 0 0 0 57 0 0 0 0 0 0 0 62 0 0 0 0 0 0 0 66 0 0 0 0 0 0 0 0 72 0 0 0 0 0 0 0 31 0 0 0 0 0 0 0 24 0 0 0 0 0 0 0 12 0 0 0 0 0 0 0 0 7 0 0 0 0 0 0 0 12 0 0 0 0 0 0 0 5 0 0 0 0 0 0 0 3 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 2 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 1') != -1, \ + 'did not get expected histogram.' # We will blow an exception if the file does not exist now! os.remove('../gcore/data/byte.tif.aux.xml') - return 'success' - ############################################################################### # Test -mdd option def test_gdalinfo_9(): if test_cli_utilities.get_gdalinfo_path() is None: - return 'skip' + pytest.skip() ret = gdaltest.runexternal(test_cli_utilities.get_gdalinfo_path() + ' ../gdrivers/data/fake_nsif.ntf') - if ret.find('BLOCKA=010000001000000000') != -1: - gdaltest.post_reason('got unexpected extra MD.') - print(ret) - return 'fail' + assert ret.find('BLOCKA=010000001000000000') == -1, 'got unexpected extra MD.' ret = gdaltest.runexternal(test_cli_utilities.get_gdalinfo_path() + ' -mdd TRE ../gdrivers/data/fake_nsif.ntf') - if ret.find('BLOCKA=010000001000000000') == -1: - gdaltest.post_reason('did not get extra MD.') - print(ret) - return 'fail' - - return 'success' + assert ret.find('BLOCKA=010000001000000000') != -1, 'did not get extra MD.' ############################################################################### # Test -mm option @@ -238,17 +186,13 @@ def test_gdalinfo_9(): def test_gdalinfo_10(): if test_cli_utilities.get_gdalinfo_path() is None: - return 'skip' + pytest.skip() ret = gdaltest.runexternal(test_cli_utilities.get_gdalinfo_path() + ' ../gcore/data/byte.tif') - if ret.find('Computed Min/Max=74.000,255.000') != -1: - return 'fail' + assert ret.find('Computed Min/Max=74.000,255.000') == -1 ret = gdaltest.runexternal(test_cli_utilities.get_gdalinfo_path() + ' -mm ../gcore/data/byte.tif') - if ret.find('Computed Min/Max=74.000,255.000') == -1: - return 'fail' - - return 'success' + assert ret.find('Computed Min/Max=74.000,255.000') != -1 ############################################################################### # Test gdalinfo --version @@ -257,14 +201,10 @@ def test_gdalinfo_10(): def test_gdalinfo_11(): if test_cli_utilities.get_gdalinfo_path() is None: - return 'skip' + pytest.skip() ret = gdaltest.runexternal(test_cli_utilities.get_gdalinfo_path() + ' --version', check_memleak=False) - if ret.find(gdal.VersionInfo('--version')) != 0: - print(ret) - return 'fail' - - return 'success' + assert ret.find(gdal.VersionInfo('--version')) == 0 ############################################################################### # Test gdalinfo --build @@ -272,15 +212,11 @@ def test_gdalinfo_11(): def test_gdalinfo_12(): if test_cli_utilities.get_gdalinfo_path() is None: - return 'skip' + pytest.skip() ret = gdaltest.runexternal(test_cli_utilities.get_gdalinfo_path() + ' --build', check_memleak=False) ret = ret.replace('\r\n', '\n') - if ret.find(gdal.VersionInfo('BUILD_INFO')) != 0: - print(ret) - return 'fail' - - return 'success' + assert ret.find(gdal.VersionInfo('BUILD_INFO')) == 0 ############################################################################### # Test gdalinfo --license @@ -288,33 +224,27 @@ def test_gdalinfo_12(): def test_gdalinfo_13(): if test_cli_utilities.get_gdalinfo_path() is None: - return 'skip' + pytest.skip() ret = gdaltest.runexternal(test_cli_utilities.get_gdalinfo_path() + ' --license', check_memleak=False) ret = ret.replace('\r\n', '\n') if ret.find(gdal.VersionInfo('LICENSE')) != 0: - print(ret) print(gdal.VersionInfo('LICENSE')) if gdaltest.is_travis_branch('mingw'): return 'expected_fail' - return 'fail' - - return 'success' + pytest.fail(ret) + ############################################################################### # Test erroneous use of --config. def test_gdalinfo_14(): if test_cli_utilities.get_gdalinfo_path() is None: - return 'skip' + pytest.skip() (_, err) = gdaltest.runexternal_out_and_err(test_cli_utilities.get_gdalinfo_path() + ' --config', check_memleak=False) - if err.find('--config option given without a key and value argument') < 0: - print(err) - return 'fail' - - return 'success' + assert err.find('--config option given without a key and value argument') >= 0 ############################################################################### # Test erroneous use of --mempreload. @@ -322,14 +252,10 @@ def test_gdalinfo_14(): def test_gdalinfo_15(): if test_cli_utilities.get_gdalinfo_path() is None: - return 'skip' + pytest.skip() (_, err) = gdaltest.runexternal_out_and_err(test_cli_utilities.get_gdalinfo_path() + ' --mempreload', check_memleak=False) - if err.find('--mempreload option given without directory path') < 0: - print(err) - return 'fail' - - return 'success' + assert err.find('--mempreload option given without directory path') >= 0 ############################################################################### # Test --mempreload @@ -337,14 +263,10 @@ def test_gdalinfo_15(): def test_gdalinfo_16(): if test_cli_utilities.get_gdalinfo_path() is None: - return 'skip' + pytest.skip() (ret, _) = gdaltest.runexternal_out_and_err(test_cli_utilities.get_gdalinfo_path() + ' --debug on --mempreload ../gcore/data /vsimem/byte.tif', check_memleak=False) - if ret.find('Driver: GTiff/GeoTIFF') != 0: - print(ret) - return 'fail' - - return 'success' + assert ret.find('Driver: GTiff/GeoTIFF') == 0 ############################################################################### # Test erroneous use of --debug. @@ -352,14 +274,10 @@ def test_gdalinfo_16(): def test_gdalinfo_17(): if test_cli_utilities.get_gdalinfo_path() is None: - return 'skip' + pytest.skip() (_, err) = gdaltest.runexternal_out_and_err(test_cli_utilities.get_gdalinfo_path() + ' --debug', check_memleak=False) - if err.find('--debug option given without debug level') < 0: - print(err) - return 'fail' - - return 'success' + assert err.find('--debug option given without debug level') >= 0 ############################################################################### # Test erroneous use of --optfile. @@ -367,21 +285,13 @@ def test_gdalinfo_17(): def test_gdalinfo_18(): if test_cli_utilities.get_gdalinfo_path() is None: - return 'skip' + pytest.skip() (_, err) = gdaltest.runexternal_out_and_err(test_cli_utilities.get_gdalinfo_path() + ' --optfile', check_memleak=False) - if err.find('--optfile option given without filename') < 0: - gdaltest.post_reason('fail') - print(err) - return 'fail' + assert err.find('--optfile option given without filename') >= 0 (_, err) = gdaltest.runexternal_out_and_err(test_cli_utilities.get_gdalinfo_path() + ' --optfile /foo/bar', check_memleak=False) - if err.find('Unable to open optfile') < 0: - gdaltest.post_reason('fail') - print(err) - return 'fail' - - return 'success' + assert err.find('Unable to open optfile') >= 0 ############################################################################### # Test --optfile @@ -389,7 +299,7 @@ def test_gdalinfo_18(): def test_gdalinfo_19(): if test_cli_utilities.get_gdalinfo_path() is None: - return 'skip' + pytest.skip() f = open('tmp/optfile.txt', 'wt') f.write('# comment\n') @@ -397,11 +307,7 @@ def test_gdalinfo_19(): f.close() ret = gdaltest.runexternal(test_cli_utilities.get_gdalinfo_path() + ' --optfile tmp/optfile.txt', check_memleak=False) os.unlink('tmp/optfile.txt') - if ret.find('Driver: GTiff/GeoTIFF') != 0: - print(ret) - return 'fail' - - return 'success' + assert ret.find('Driver: GTiff/GeoTIFF') == 0 ############################################################################### # Test --formats @@ -409,14 +315,10 @@ def test_gdalinfo_19(): def test_gdalinfo_20(): if test_cli_utilities.get_gdalinfo_path() is None: - return 'skip' + pytest.skip() ret = gdaltest.runexternal(test_cli_utilities.get_gdalinfo_path() + ' --formats', check_memleak=False) - if ret.find('GTiff -raster- (rw+vs): GeoTIFF') < 0: - print(ret) - return 'fail' - - return 'success' + assert ret.find('GTiff -raster- (rw+vs): GeoTIFF') >= 0 ############################################################################### # Test erroneous use of --format. @@ -424,21 +326,13 @@ def test_gdalinfo_20(): def test_gdalinfo_21(): if test_cli_utilities.get_gdalinfo_path() is None: - return 'skip' + pytest.skip() (_, err) = gdaltest.runexternal_out_and_err(test_cli_utilities.get_gdalinfo_path() + ' --format', check_memleak=False) - if err.find('--format option given without a format code') < 0: - gdaltest.post_reason('fail') - print(err) - return 'fail' + assert err.find('--format option given without a format code') >= 0 (_, err) = gdaltest.runexternal_out_and_err(test_cli_utilities.get_gdalinfo_path() + ' --format foo_bar', check_memleak=False) - if err.find('--format option given with format') < 0: - gdaltest.post_reason('fail') - print(err) - return 'fail' - - return 'success' + assert err.find('--format option given with format') >= 0 ############################################################################### # Test --format @@ -446,7 +340,7 @@ def test_gdalinfo_21(): def test_gdalinfo_22(): if test_cli_utilities.get_gdalinfo_path() is None: - return 'skip' + pytest.skip() ret = gdaltest.runexternal(test_cli_utilities.get_gdalinfo_path() + ' --format GTiff', check_memleak=False) @@ -462,27 +356,19 @@ def test_gdalinfo_22(): 'Creation Datatypes', '<CreationOptionList>'] for expected_string in expected_strings: - if ret.find(expected_string) < 0: - gdaltest.post_reason('did not find %s' % expected_string) - print(ret) - return 'fail' - - return 'success' + assert ret.find(expected_string) >= 0, ('did not find %s' % expected_string) + ############################################################################### # Test --help-general def test_gdalinfo_23(): if test_cli_utilities.get_gdalinfo_path() is None: - return 'skip' + pytest.skip() ret = gdaltest.runexternal(test_cli_utilities.get_gdalinfo_path() + ' --help-general', check_memleak=False) - if ret.find('Generic GDAL utility command options') < 0: - print(ret) - return 'fail' - - return 'success' + assert ret.find('Generic GDAL utility command options') >= 0 ############################################################################### # Test --locale @@ -490,14 +376,10 @@ def test_gdalinfo_23(): def test_gdalinfo_24(): if test_cli_utilities.get_gdalinfo_path() is None: - return 'skip' + pytest.skip() ret = gdaltest.runexternal(test_cli_utilities.get_gdalinfo_path() + ' --locale C ../gcore/data/byte.tif', check_memleak=False) - if ret.find('Driver: GTiff/GeoTIFF') != 0: - print(ret) - return 'fail' - - return 'success' + assert ret.find('Driver: GTiff/GeoTIFF') == 0 ############################################################################### # Test -listmdd @@ -505,17 +387,11 @@ def test_gdalinfo_24(): def test_gdalinfo_25(): if test_cli_utilities.get_gdalinfo_path() is None: - return 'skip' + pytest.skip() ret = gdaltest.runexternal(test_cli_utilities.get_gdalinfo_path() + ' ../gdrivers/data/byte_with_xmp.tif -listmdd', check_memleak=False) - if ret.find('Metadata domains:') < 0: - print(ret) - return 'fail' - if ret.find(' xml:XMP') < 0: - print(ret) - return 'fail' - - return 'success' + assert ret.find('Metadata domains:') >= 0 + assert ret.find(' xml:XMP') >= 0 ############################################################################### # Test -mdd all @@ -523,14 +399,10 @@ def test_gdalinfo_25(): def test_gdalinfo_26(): if test_cli_utilities.get_gdalinfo_path() is None: - return 'skip' + pytest.skip() ret = gdaltest.runexternal(test_cli_utilities.get_gdalinfo_path() + ' ../gdrivers/data/byte_with_xmp.tif -mdd all', check_memleak=False) - if ret.find('Metadata (xml:XMP)') < 0: - print(ret) - return 'fail' - - return 'success' + assert ret.find('Metadata (xml:XMP)') >= 0 ############################################################################### # Test -oo @@ -538,14 +410,10 @@ def test_gdalinfo_26(): def test_gdalinfo_27(): if test_cli_utilities.get_gdalinfo_path() is None: - return 'skip' + pytest.skip() ret = gdaltest.runexternal(test_cli_utilities.get_gdalinfo_path() + ' ../gdrivers/data/float64.asc -oo datatype=float64', check_memleak=False) - if ret.find('Type=Float64') < 0: - print(ret) - return 'fail' - - return 'success' + assert ret.find('Type=Float64') >= 0 ############################################################################### # Simple -json test @@ -553,18 +421,12 @@ def test_gdalinfo_27(): def test_gdalinfo_28(): if test_cli_utilities.get_gdalinfo_path() is None: - return 'skip' + pytest.skip() (ret, err) = gdaltest.runexternal_out_and_err(test_cli_utilities.get_gdalinfo_path() + ' -json ../gcore/data/byte.tif') ret = json.loads(ret) - if not (err is None or err == ''): - gdaltest.post_reason('got error/warning') - print(err) - return 'fail' - if ret['driverShortName'] != 'GTiff': - return 'fail' - - return 'success' + assert (err is None or err == ''), 'got error/warning' + assert ret['driverShortName'] == 'GTiff' ############################################################################### # Test -json -checksum option @@ -572,14 +434,11 @@ def test_gdalinfo_28(): def test_gdalinfo_29(): if test_cli_utilities.get_gdalinfo_path() is None: - return 'skip' + pytest.skip() ret = gdaltest.runexternal(test_cli_utilities.get_gdalinfo_path() + ' -json -checksum ../gcore/data/byte.tif') ret = json.loads(ret) - if ret['bands'][0]['checksum'] != 4672: - return 'fail' - - return 'success' + assert ret['bands'][0]['checksum'] == 4672 ############################################################################### # Test -json -nomd option @@ -587,19 +446,15 @@ def test_gdalinfo_29(): def test_gdalinfo_30(): if test_cli_utilities.get_gdalinfo_path() is None: - return 'skip' + pytest.skip() ret = gdaltest.runexternal(test_cli_utilities.get_gdalinfo_path() + ' -json ../gcore/data/byte.tif') ret = json.loads(ret) - if 'metadata' not in ret: - return 'fail' + assert 'metadata' in ret ret = gdaltest.runexternal(test_cli_utilities.get_gdalinfo_path() + ' -json -nomd ../gcore/data/byte.tif') ret = json.loads(ret) - if 'metadata' in ret: - return 'fail' - - return 'success' + assert 'metadata' not in ret ############################################################################### # Test -json -noct option @@ -607,19 +462,15 @@ def test_gdalinfo_30(): def test_gdalinfo_31(): if test_cli_utilities.get_gdalinfo_path() is None: - return 'skip' + pytest.skip() ret = gdaltest.runexternal(test_cli_utilities.get_gdalinfo_path() + ' -json ../gdrivers/data/bug407.gif') ret = json.loads(ret) - if ret['bands'][0]['colorTable']['entries'][0] != [255, 255, 255, 255]: - return 'fail' + assert ret['bands'][0]['colorTable']['entries'][0] == [255, 255, 255, 255] ret = gdaltest.runexternal(test_cli_utilities.get_gdalinfo_path() + ' -json -noct ../gdrivers/data/bug407.gif') ret = json.loads(ret) - if 'colorTable' in ret['bands'][0]: - return 'fail' - - return 'success' + assert 'colorTable' not in ret['bands'][0] ############################################################################### # Test -stats option @@ -627,7 +478,7 @@ def test_gdalinfo_31(): def test_gdalinfo_32(): if test_cli_utilities.get_gdalinfo_path() is None: - return 'skip' + pytest.skip() try: os.remove('../gcore/data/byte.tif.aux.xml') @@ -636,39 +487,28 @@ def test_gdalinfo_32(): ret = gdaltest.runexternal(test_cli_utilities.get_gdalinfo_path() + ' -json ../gcore/data/byte.tif') ret = json.loads(ret) - if '' in ret['bands'][0]['metadata']: - gdaltest.post_reason('got wrong minimum.') - print(ret) - return 'fail' + assert '' not in ret['bands'][0]['metadata'], 'got wrong minimum.' ret = gdaltest.runexternal(test_cli_utilities.get_gdalinfo_path() + ' -json -stats ../gcore/data/byte.tif') ret = json.loads(ret) - if ret['bands'][0]['metadata']['']['STATISTICS_MINIMUM'] != '74': - gdaltest.post_reason('got wrong minimum (2).') - print(ret) - return 'fail' + assert ret['bands'][0]['metadata']['']['STATISTICS_MINIMUM'] == '74', \ + 'got wrong minimum (2).' # We will blow an exception if the file does not exist now! os.remove('../gcore/data/byte.tif.aux.xml') - return 'success' - ############################################################################### # Test a dataset with overviews and RAT def test_gdalinfo_33(): if test_cli_utilities.get_gdalinfo_path() is None: - return 'skip' + pytest.skip() ret = gdaltest.runexternal(test_cli_utilities.get_gdalinfo_path() + ' -json ../gdrivers/data/int.img') ret = json.loads(ret) - if 'overviews' not in ret['bands'][0]: - return 'fail' - if 'rat' not in ret: - return 'fail' - - return 'success' + assert 'overviews' in ret['bands'][0] + assert 'rat' in ret ############################################################################### # Test a dataset with GCPs @@ -676,23 +516,17 @@ def test_gdalinfo_33(): def test_gdalinfo_34(): if test_cli_utilities.get_gdalinfo_path() is None: - return 'skip' + pytest.skip() ret = gdaltest.runexternal(test_cli_utilities.get_gdalinfo_path() + ' -json ../gcore/data/gcps.vrt') ret = json.loads(ret) - if 'wkt' not in ret['gcps']['coordinateSystem']: - return 'fail' - if ret['gcps']['coordinateSystem']['wkt'].find('PROJCS["NAD27 / UTM zone 11N"') == -1: - return 'fail' - if ret['gcps']['gcpList'][0]['x'] != 440720.0: - return 'fail' + assert 'wkt' in ret['gcps']['coordinateSystem'] + assert ret['gcps']['coordinateSystem']['wkt'].find('PROJCS["NAD27 / UTM zone 11N"') != -1 + assert ret['gcps']['gcpList'][0]['x'] == 440720.0 ret = gdaltest.runexternal(test_cli_utilities.get_gdalinfo_path() + ' -json -nogcp ../gcore/data/gcps.vrt') ret = json.loads(ret) - if 'gcps' in ret: - return 'fail' - - return 'success' + assert 'gcps' not in ret ############################################################################### # Test -hist option @@ -700,7 +534,7 @@ def test_gdalinfo_34(): def test_gdalinfo_35(): if test_cli_utilities.get_gdalinfo_path() is None: - return 'skip' + pytest.skip() try: os.remove('../gcore/data/byte.tif.aux.xml') @@ -709,46 +543,32 @@ def test_gdalinfo_35(): ret = gdaltest.runexternal(test_cli_utilities.get_gdalinfo_path() + ' -json ../gcore/data/byte.tif') ret = json.loads(ret) - if 'histogram' in ret['bands'][0]: - gdaltest.post_reason('did not expect histogram.') - print(ret) - return 'fail' + assert 'histogram' not in ret['bands'][0], 'did not expect histogram.' ret = gdaltest.runexternal(test_cli_utilities.get_gdalinfo_path() + ' -json -hist ../gcore/data/byte.tif') ret = json.loads(ret) - if ret['bands'][0]['histogram']['buckets'] != [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 0, 0, 0, 0, 0, 0, 0, 0, 37, 0, 0, 0, 0, 0, 0, 0, 57, 0, 0, 0, 0, 0, 0, 0, 62, 0, 0, 0, 0, 0, 0, 0, 66, 0, 0, 0, 0, 0, 0, 0, 0, 72, 0, 0, 0, 0, 0, 0, 0, 31, 0, 0, 0, 0, 0, 0, 0, 24, 0, 0, 0, 0, 0, 0, 0, 12, 0, 0, 0, 0, 0, 0, 0, 0, 7, 0, 0, 0, 0, 0, 0, 0, 12, 0, 0, 0, 0, 0, 0, 0, 5, 0, 0, 0, 0, 0, 0, 0, 3, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1]: - gdaltest.post_reason('did not get expected histogram.') - print(ret) - return 'fail' + assert ret['bands'][0]['histogram']['buckets'] == [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 0, 0, 0, 0, 0, 0, 0, 0, 37, 0, 0, 0, 0, 0, 0, 0, 57, 0, 0, 0, 0, 0, 0, 0, 62, 0, 0, 0, 0, 0, 0, 0, 66, 0, 0, 0, 0, 0, 0, 0, 0, 72, 0, 0, 0, 0, 0, 0, 0, 31, 0, 0, 0, 0, 0, 0, 0, 24, 0, 0, 0, 0, 0, 0, 0, 12, 0, 0, 0, 0, 0, 0, 0, 0, 7, 0, 0, 0, 0, 0, 0, 0, 12, 0, 0, 0, 0, 0, 0, 0, 5, 0, 0, 0, 0, 0, 0, 0, 3, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1], \ + 'did not get expected histogram.' # We will blow an exception if the file does not exist now! os.remove('../gcore/data/byte.tif.aux.xml') - return 'success' - ############################################################################### # Test -mdd option def test_gdalinfo_36(): if test_cli_utilities.get_gdalinfo_path() is None: - return 'skip' + pytest.skip() ret = gdaltest.runexternal(test_cli_utilities.get_gdalinfo_path() + ' -json ../gdrivers/data/fake_nsif.ntf') ret = json.loads(ret) - if 'TRE' in ret['metadata']: - gdaltest.post_reason('got unexpected extra MD.') - print(ret) - return 'fail' + assert 'TRE' not in ret['metadata'], 'got unexpected extra MD.' ret = gdaltest.runexternal(test_cli_utilities.get_gdalinfo_path() + ' -json -mdd TRE ../gdrivers/data/fake_nsif.ntf') ret = json.loads(ret) - if ret['metadata']['TRE']['BLOCKA'].find('010000001000000000') == -1: - gdaltest.post_reason('did not get extra MD.') - print(ret) - return 'fail' - - return 'success' + assert ret['metadata']['TRE']['BLOCKA'].find('010000001000000000') != -1, \ + 'did not get extra MD.' ############################################################################### # Test -mm option @@ -756,19 +576,15 @@ def test_gdalinfo_36(): def test_gdalinfo_37(): if test_cli_utilities.get_gdalinfo_path() is None: - return 'skip' + pytest.skip() ret = gdaltest.runexternal(test_cli_utilities.get_gdalinfo_path() + ' -json ../gcore/data/byte.tif') ret = json.loads(ret) - if 'computedMin' in ret['bands'][0]: - return 'fail' + assert 'computedMin' not in ret['bands'][0] ret = gdaltest.runexternal(test_cli_utilities.get_gdalinfo_path() + ' -json -mm ../gcore/data/byte.tif') ret = json.loads(ret) - if ret['bands'][0]['computedMin'] != 74.000: - return 'fail' - - return 'success' + assert ret['bands'][0]['computedMin'] == 74.000 ############################################################################### # Test -listmdd @@ -776,18 +592,12 @@ def test_gdalinfo_37(): def test_gdalinfo_38(): if test_cli_utilities.get_gdalinfo_path() is None: - return 'skip' + pytest.skip() ret = gdaltest.runexternal(test_cli_utilities.get_gdalinfo_path() + ' -json ../gdrivers/data/byte_with_xmp.tif -listmdd', check_memleak=False) ret = json.loads(ret) - if 'metadataDomains' not in ret['metadata']: - print(ret) - return 'fail' - if ret['metadata']['metadataDomains'][0] != 'xml:XMP': - print(ret) - return 'fail' - - return 'success' + assert 'metadataDomains' in ret['metadata'] + assert ret['metadata']['metadataDomains'][0] == 'xml:XMP' ############################################################################### # Test -mdd all @@ -795,15 +605,11 @@ def test_gdalinfo_38(): def test_gdalinfo_39(): if test_cli_utilities.get_gdalinfo_path() is None: - return 'skip' + pytest.skip() ret = gdaltest.runexternal(test_cli_utilities.get_gdalinfo_path() + ' -json ../gdrivers/data/byte_with_xmp.tif -mdd all', check_memleak=False) ret = json.loads(ret) - if 'xml:XMP' not in ret['metadata']: - print(ret) - return 'fail' - - return 'success' + assert 'xml:XMP' in ret['metadata'] ############################################################################### # Test -json wgs84Extent @@ -811,77 +617,16 @@ def test_gdalinfo_39(): def test_gdalinfo_40(): if test_cli_utilities.get_gdalinfo_path() is None: - return 'skip' + pytest.skip() ret = gdaltest.runexternal(test_cli_utilities.get_gdalinfo_path() + ' -json ../gdrivers/data/small_world.tif') ret = json.loads(ret) - if 'wgs84Extent' not in ret: - print(ret) - return 'fail' - if 'type' not in ret['wgs84Extent']: - print(ret) - return 'fail' - if ret['wgs84Extent']['type'] != 'Polygon': - print(ret) - return 'fail' - if 'coordinates' not in ret['wgs84Extent']: - print(ret) - return 'fail' - if ret['wgs84Extent']['coordinates'] != [[[-180.0, 90.0], [-180.0, -90.0], [180.0, -90.0], [180.0, 90.0], [-180.0, 90.0]]]: - print(ret) - return 'fail' - - return 'success' - - -gdaltest_list = [ - test_gdalinfo_1, - test_gdalinfo_2, - test_gdalinfo_3, - test_gdalinfo_4, - test_gdalinfo_5, - test_gdalinfo_6, - test_gdalinfo_7, - test_gdalinfo_8, - test_gdalinfo_9, - test_gdalinfo_10, - test_gdalinfo_11, - test_gdalinfo_12, - test_gdalinfo_13, - test_gdalinfo_14, - test_gdalinfo_15, - test_gdalinfo_16, - test_gdalinfo_17, - test_gdalinfo_18, - test_gdalinfo_19, - test_gdalinfo_20, - test_gdalinfo_21, - test_gdalinfo_22, - test_gdalinfo_23, - test_gdalinfo_24, - test_gdalinfo_25, - test_gdalinfo_26, - test_gdalinfo_27, - test_gdalinfo_28, - test_gdalinfo_29, - test_gdalinfo_30, - test_gdalinfo_31, - test_gdalinfo_32, - test_gdalinfo_33, - test_gdalinfo_34, - test_gdalinfo_35, - test_gdalinfo_36, - test_gdalinfo_37, - test_gdalinfo_38, - test_gdalinfo_39, - test_gdalinfo_40, -] - - -if __name__ == '__main__': - - gdaltest.setup_run('test_gdalinfo') - - gdaltest.run_tests(gdaltest_list) - - sys.exit(gdaltest.summarize()) + assert 'wgs84Extent' in ret + assert 'type' in ret['wgs84Extent'] + assert ret['wgs84Extent']['type'] == 'Polygon' + assert 'coordinates' in ret['wgs84Extent'] + assert ret['wgs84Extent']['coordinates'] == [[[-180.0, 90.0], [-180.0, -90.0], [180.0, -90.0], [180.0, 90.0], [-180.0, 90.0]]] + + + + diff --git a/autotest/utilities/test_gdalinfo_lib.py b/autotest/utilities/test_gdalinfo_lib.py index 351429e92a20..433954f2e644 100755 --- a/autotest/utilities/test_gdalinfo_lib.py +++ b/autotest/utilities/test_gdalinfo_lib.py @@ -29,12 +29,9 @@ # DEALINGS IN THE SOFTWARE. ############################################################################### -import sys -sys.path.append('../pymod') from osgeo import gdal -import gdaltest ############################################################################### # Simple test @@ -45,12 +42,7 @@ def test_gdalinfo_lib_1(): ds = gdal.Open('../gcore/data/byte.tif') ret = gdal.Info(ds) - if ret.find('Driver: GTiff/GeoTIFF') == -1: - gdaltest.post_reason('did not get expected string.') - print(ret) - return 'fail' - - return 'success' + assert ret.find('Driver: GTiff/GeoTIFF') != -1, 'did not get expected string.' ############################################################################### # Test Json format @@ -61,12 +53,7 @@ def test_gdalinfo_lib_2(): ds = gdal.Open('../gcore/data/byte.tif') ret = gdal.Info(ds, format='json') - if ret['driverShortName'] != 'GTiff': - gdaltest.post_reason('wrong value for driverShortName.') - print(ret) - return 'fail' - - return 'success' + assert ret['driverShortName'] == 'GTiff', 'wrong value for driverShortName.' ############################################################################### # Test extraMDDomains() @@ -77,19 +64,12 @@ def test_gdalinfo_lib_3(): ds = gdal.Open('../gdrivers/data/fake_nsif.ntf') ret = gdal.Info(ds, format='json') - if 'TRE' in ret['metadata']: - gdaltest.post_reason('got unexpected extra MD.') - print(ret) - return 'fail' + assert 'TRE' not in ret['metadata'], 'got unexpected extra MD.' options = gdal.InfoOptions(format='json', extraMDDomains=['TRE']) ret = gdal.Info(ds, options=options) - if ret['metadata']['TRE']['BLOCKA'].find('010000001000000000') == -1: - gdaltest.post_reason('did not get extra MD.') - print(ret) - return 'fail' - - return 'success' + assert ret['metadata']['TRE']['BLOCKA'].find('010000001000000000') != -1, \ + 'did not get extra MD.' ############################################################################### # Test allMetadata @@ -100,11 +80,7 @@ def test_gdalinfo_lib_4(): ds = gdal.Open('../gdrivers/data/byte_with_xmp.tif') ret = gdal.Info(ds, allMetadata=True, format='json') - if 'xml:XMP' not in ret['metadata']: - print(ret) - return 'fail' - - return 'success' + assert 'xml:XMP' in ret['metadata'] ############################################################################### # Test all options @@ -119,26 +95,16 @@ def test_gdalinfo_lib_5(): stats=True, approxStats=True, computeChecksum=True, showGCPs=False, showMetadata=False, showRAT=False, showColorTable=False, listMDD=True, showFileList=False) - if 'files' in ret: - gdaltest.post_reason('fail') - return 'fail' + assert 'files' not in ret band = ret['bands'][0] - if 'computedMin' not in band: - gdaltest.post_reason('fail') - return 'fail' - if 'histogram' not in band: - gdaltest.post_reason('fail') - return 'fail' - if 'checksum' not in band: - gdaltest.post_reason('fail') - return 'fail' + assert 'computedMin' in band + assert 'histogram' in band + assert 'checksum' in band ds = None gdal.Unlink('../gdrivers/data/byte.tif.aux.xml') - return 'success' - ############################################################################### # Test command line syntax + dataset as string @@ -146,12 +112,7 @@ def test_gdalinfo_lib_5(): def test_gdalinfo_lib_6(): ret = gdal.Info('../gcore/data/byte.tif', options='-json') - if ret['driverShortName'] != 'GTiff': - gdaltest.post_reason('wrong value for driverShortName.') - print(ret) - return 'fail' - - return 'success' + assert ret['driverShortName'] == 'GTiff', 'wrong value for driverShortName.' ############################################################################### # Test with unicode strings @@ -160,12 +121,7 @@ def test_gdalinfo_lib_6(): def test_gdalinfo_lib_7(): ret = gdal.Info('../gcore/data/byte.tif'.encode('ascii').decode('ascii'), options='-json'.encode('ascii').decode('ascii')) - if ret['driverShortName'] != 'GTiff': - gdaltest.post_reason('wrong value for driverShortName.') - print(ret) - return 'fail' - - return 'success' + assert ret['driverShortName'] == 'GTiff', 'wrong value for driverShortName.' ############################################################################### @@ -174,29 +130,7 @@ def test_gdalinfo_lib_nodatavalues(): ds = gdal.Translate('', '../gcore/data/byte.tif', options='-of VRT -b 1 -b 1 -b 1 -mo "NODATA_VALUES=0 1 2"') ret = gdal.Info(ds) - if ret.find('PER_DATASET NODATA') < 0: - gdaltest.post_reason('wrong value for mask flags.') - print(ret) - return 'fail' - - return 'success' - - -gdaltest_list = [ - test_gdalinfo_lib_1, - test_gdalinfo_lib_2, - test_gdalinfo_lib_3, - test_gdalinfo_lib_4, - test_gdalinfo_lib_5, - test_gdalinfo_lib_6, - test_gdalinfo_lib_7, - test_gdalinfo_lib_nodatavalues, -] - -if __name__ == '__main__': + assert ret.find('PER_DATASET NODATA') >= 0, 'wrong value for mask flags.' - gdaltest.setup_run('test_gdalinfo_lib') - gdaltest.run_tests(gdaltest_list) - sys.exit(gdaltest.summarize()) diff --git a/autotest/utilities/test_gdallocationinfo.py b/autotest/utilities/test_gdallocationinfo.py index 38c1f141037c..c0e220afe5e3 100755 --- a/autotest/utilities/test_gdallocationinfo.py +++ b/autotest/utilities/test_gdallocationinfo.py @@ -30,8 +30,8 @@ ############################################################################### import sys +import pytest -sys.path.append('../pymod') sys.path.append('../gcore') from osgeo import gdal @@ -44,24 +44,17 @@ def test_gdallocationinfo_1(): if test_cli_utilities.get_gdallocationinfo_path() is None: - return 'skip' + pytest.skip() (ret, err) = gdaltest.runexternal_out_and_err(test_cli_utilities.get_gdallocationinfo_path() + ' ../gcore/data/byte.tif 0 0') - if not (err is None or err == ''): - gdaltest.post_reason('got error/warning') - print(err) - return 'fail' + assert (err is None or err == ''), 'got error/warning' ret = ret.replace('\r\n', '\n') expected_ret = """Report: Location: (0P,0L) Band 1: Value: 107""" - if ret.find(expected_ret) != 0: - print(ret) - return 'fail' - - return 'success' + assert ret.find(expected_ret) == 0 ############################################################################### # Test -xml @@ -69,7 +62,7 @@ def test_gdallocationinfo_1(): def test_gdallocationinfo_2(): if test_cli_utilities.get_gdallocationinfo_path() is None: - return 'skip' + pytest.skip() ret = gdaltest.runexternal(test_cli_utilities.get_gdallocationinfo_path() + ' -xml ../gcore/data/byte.tif 0 0') ret = ret.replace('\r\n', '\n') @@ -78,11 +71,7 @@ def test_gdallocationinfo_2(): <Value>107</Value> </BandReport> </Report>""" - if ret.find(expected_ret) != 0: - print(ret) - return 'fail' - - return 'success' + assert ret.find(expected_ret) == 0 ############################################################################### # Test -valonly @@ -90,15 +79,11 @@ def test_gdallocationinfo_2(): def test_gdallocationinfo_3(): if test_cli_utilities.get_gdallocationinfo_path() is None: - return 'skip' + pytest.skip() ret = gdaltest.runexternal(test_cli_utilities.get_gdallocationinfo_path() + ' -b 1 -valonly ../gcore/data/byte.tif 0 0') expected_ret = """107""" - if ret.find(expected_ret) != 0: - print(ret) - return 'fail' - - return 'success' + assert ret.find(expected_ret) == 0 ############################################################################### # Test -geoloc @@ -106,7 +91,7 @@ def test_gdallocationinfo_3(): def test_gdallocationinfo_4(): if test_cli_utilities.get_gdallocationinfo_path() is None: - return 'skip' + pytest.skip() ret = gdaltest.runexternal(test_cli_utilities.get_gdallocationinfo_path() + ' -geoloc ../gcore/data/byte.tif 440720.000 3751320.000') ret = ret.replace('\r\n', '\n') @@ -114,11 +99,7 @@ def test_gdallocationinfo_4(): Location: (0P,0L) Band 1: Value: 107""" - if ret.find(expected_ret) != 0: - print(ret) - return 'fail' - - return 'success' + assert ret.find(expected_ret) == 0 ############################################################################### # Test -lifonly @@ -126,16 +107,12 @@ def test_gdallocationinfo_4(): def test_gdallocationinfo_5(): if test_cli_utilities.get_gdallocationinfo_path() is None: - return 'skip' + pytest.skip() ret = gdaltest.runexternal(test_cli_utilities.get_gdallocationinfo_path() + ' -lifonly ../gcore/data/byte.vrt 0 0') expected_ret1 = """../gcore/data/byte.tif""" expected_ret2 = """../gcore/data\\byte.tif""" - if ret.find(expected_ret1) < 0 and ret.find(expected_ret2) < 0: - print(ret) - return 'fail' - - return 'success' + assert ret.find(expected_ret1) >= 0 or ret.find(expected_ret2) >= 0 ############################################################################### # Test -overview @@ -143,7 +120,7 @@ def test_gdallocationinfo_5(): def test_gdallocationinfo_6(): if test_cli_utilities.get_gdallocationinfo_path() is None: - return 'skip' + pytest.skip() src_ds = gdal.Open('../gcore/data/byte.tif') ds = gdal.GetDriverByName('GTiff').CreateCopy('tmp/test_gdallocationinfo_6.tif', src_ds) @@ -155,27 +132,8 @@ def test_gdallocationinfo_6(): gdal.GetDriverByName('GTiff').Delete('tmp/test_gdallocationinfo_6.tif') expected_ret = """Value: 130""" - if ret.find(expected_ret) < 0: - print(ret) - return 'fail' - - return 'success' - - -gdaltest_list = [ - test_gdallocationinfo_1, - test_gdallocationinfo_2, - test_gdallocationinfo_3, - test_gdallocationinfo_4, - test_gdallocationinfo_5, - test_gdallocationinfo_6, -] - + assert ret.find(expected_ret) >= 0 -if __name__ == '__main__': - gdaltest.setup_run('test_gdallocationinfo') - gdaltest.run_tests(gdaltest_list) - sys.exit(gdaltest.summarize()) diff --git a/autotest/utilities/test_gdalsrsinfo.py b/autotest/utilities/test_gdalsrsinfo.py index d9a45b43f97d..e50088efbc6a 100755 --- a/autotest/utilities/test_gdalsrsinfo.py +++ b/autotest/utilities/test_gdalsrsinfo.py @@ -31,10 +31,10 @@ import sys -sys.path.append('../pymod') import gdaltest import test_cli_utilities +import pytest ############################################################################### # Simple test @@ -42,20 +42,13 @@ def test_gdalsrsinfo_1(): if test_cli_utilities.get_gdalsrsinfo_path() is None: - return 'skip' + pytest.skip() (ret, err) = gdaltest.runexternal_out_and_err(test_cli_utilities.get_gdalsrsinfo_path() + ' ../gcore/data/byte.tif') - if not (err is None or err == ''): - gdaltest.post_reason('got error/warning') - print(err) - return 'fail' + assert (err is None or err == ''), 'got error/warning' - if ret.find('PROJ.4 :') == -1: - return 'fail' - if ret.find('OGC WKT :') == -1: - return 'fail' - - return 'success' + assert ret.find('PROJ.4 :') != -1 + assert ret.find('OGC WKT :') != -1 ############################################################################### # Test -o proj4 option @@ -63,16 +56,12 @@ def test_gdalsrsinfo_1(): def test_gdalsrsinfo_2(): if test_cli_utilities.get_gdalsrsinfo_path() is None: - return 'skip' + pytest.skip() ret = gdaltest.runexternal(test_cli_utilities.get_gdalsrsinfo_path() + ' -o proj4 ../gcore/data/byte.tif') - if ret.strip() != "+proj=utm +zone=11 +datum=NAD27 +units=m +no_defs": - print(ret.strip()) - return 'fail' - - return 'success' + assert ret.strip() == "+proj=utm +zone=11 +datum=NAD27 +units=m +no_defs" ############################################################################### # Test -o wkt option @@ -80,7 +69,7 @@ def test_gdalsrsinfo_2(): def test_gdalsrsinfo_3(): if test_cli_utilities.get_gdalsrsinfo_path() is None: - return 'skip' + pytest.skip() ret = gdaltest.runexternal(test_cli_utilities.get_gdalsrsinfo_path() + ' -o wkt ../gcore/data/byte.tif') @@ -88,11 +77,7 @@ def test_gdalsrsinfo_3(): first_val = 'PROJCS["NAD27 / UTM zone 11N",GEOGCS["NAD27",DATUM["North_American_Datum_1927",SPHEROID["Clarke 1866",6378206.4,294.9786982139006,AUTHORITY["EPSG","7008"]],AUTHORITY["EPSG","6267"]],PRIMEM["Greenwich",0],UNIT["degree",0.0174532925199433],AUTHORITY["EPSG","4267"]],PROJECTION["Transverse_Mercator"],PARAMETER["latitude_of_origin",0],PARAMETER["central_meridian",-117],PARAMETER["scale_factor",0.9996],PARAMETER["false_easting",500000],PARAMETER["false_northing",0],UNIT["metre",1,AUTHORITY["EPSG","9001"]],AUTHORITY["EPSG","26711"]]' second_val = 'PROJCS["NAD27 / UTM zone 11N",GEOGCS["NAD27",DATUM["North_American_Datum_1927",SPHEROID["Clarke 1866",6378206.4,294.9786982138982,AUTHORITY["EPSG","7008"]],AUTHORITY["EPSG","6267"]],PRIMEM["Greenwich",0],UNIT["degree",0.0174532925199433],AUTHORITY["EPSG","4267"]],PROJECTION["Transverse_Mercator"],PARAMETER["latitude_of_origin",0],PARAMETER["central_meridian",-117],PARAMETER["scale_factor",0.9996],PARAMETER["false_easting",500000],PARAMETER["false_northing",0],UNIT["metre",1,AUTHORITY["EPSG","9001"]],AUTHORITY["EPSG","26711"]]' third_val = 'PROJCS["NAD27 / UTM zone 11N",GEOGCS["NAD27",DATUM["North_American_Datum_1927",SPHEROID["Clarke 1866",6378206.4,294.9786982138982,AUTHORITY["EPSG","7008"]],AUTHORITY["EPSG","6267"]],PRIMEM["Greenwich",0,AUTHORITY["EPSG","8901"]],UNIT["degree",0.0174532925199433,AUTHORITY["EPSG","9122"]],AUTHORITY["EPSG","4267"]],PROJECTION["Transverse_Mercator"],PARAMETER["latitude_of_origin",0],PARAMETER["central_meridian",-117],PARAMETER["scale_factor",0.9996],PARAMETER["false_easting",500000],PARAMETER["false_northing",0],UNIT["metre",1,AUTHORITY["EPSG","9001"]],AXIS["Easting",EAST],AXIS["Northing",NORTH],AUTHORITY["EPSG","26711"]]' - if ret.strip() != first_val and ret.strip() != second_val and ret.strip() != third_val: - print(ret.strip()) - return 'fail' - - return 'success' + assert ret.strip() == first_val or ret.strip() == second_val or ret.strip() == third_val ############################################################################### # Test -o wkt_esri option @@ -100,15 +85,12 @@ def test_gdalsrsinfo_3(): def test_gdalsrsinfo_4(): if test_cli_utilities.get_gdalsrsinfo_path() is None: - return 'skip' + pytest.skip() ret = gdaltest.runexternal(test_cli_utilities.get_gdalsrsinfo_path() + ' -o wkt_esri ../gcore/data/byte.tif') - if ret.strip() != 'PROJCS["NAD_1927_UTM_Zone_11N",GEOGCS["GCS_North_American_1927",DATUM["D_North_American_1927",SPHEROID["Clarke_1866",6378206.4,294.9786982]],PRIMEM["Greenwich",0],UNIT["Degree",0.017453292519943295]],PROJECTION["Transverse_Mercator"],PARAMETER["latitude_of_origin",0],PARAMETER["central_meridian",-117],PARAMETER["scale_factor",0.9996],PARAMETER["false_easting",500000],PARAMETER["false_northing",0],UNIT["Meter",1]]': - return 'fail' - - return 'success' + assert ret.strip() == 'PROJCS["NAD_1927_UTM_Zone_11N",GEOGCS["GCS_North_American_1927",DATUM["D_North_American_1927",SPHEROID["Clarke_1866",6378206.4,294.9786982]],PRIMEM["Greenwich",0],UNIT["Degree",0.017453292519943295]],PROJECTION["Transverse_Mercator"],PARAMETER["latitude_of_origin",0],PARAMETER["central_meridian",-117],PARAMETER["scale_factor",0.9996],PARAMETER["false_easting",500000],PARAMETER["false_northing",0],UNIT["Meter",1]]' ############################################################################### # Test -o wkt_old option @@ -116,18 +98,14 @@ def test_gdalsrsinfo_4(): def test_gdalsrsinfo_5(): if test_cli_utilities.get_gdalsrsinfo_path() is None: - return 'skip' + pytest.skip() ret = gdaltest.runexternal(test_cli_utilities.get_gdalsrsinfo_path() + ' -o wkt_noct ../gcore/data/byte.tif') first_val = 'PROJCS["NAD27 / UTM zone 11N",GEOGCS["NAD27",DATUM["North_American_Datum_1927",SPHEROID["Clarke 1866",6378206.4,294.9786982139006]],PRIMEM["Greenwich",0],UNIT["degree",0.0174532925199433]],PROJECTION["Transverse_Mercator"],PARAMETER["latitude_of_origin",0],PARAMETER["central_meridian",-117],PARAMETER["scale_factor",0.9996],PARAMETER["false_easting",500000],PARAMETER["false_northing",0],UNIT["metre",1]]' second_val = 'PROJCS["NAD27 / UTM zone 11N",GEOGCS["NAD27",DATUM["North_American_Datum_1927",SPHEROID["Clarke 1866",6378206.4,294.9786982138982]],PRIMEM["Greenwich",0],UNIT["degree",0.0174532925199433]],PROJECTION["Transverse_Mercator"],PARAMETER["latitude_of_origin",0],PARAMETER["central_meridian",-117],PARAMETER["scale_factor",0.9996],PARAMETER["false_easting",500000],PARAMETER["false_northing",0],UNIT["metre",1]]' - if ret.strip() != first_val and ret.strip() != second_val: - print(ret.strip()) - return 'fail' - - return 'success' + assert ret.strip() == first_val or ret.strip() == second_val ############################################################################### # Test -o wkt_simple option @@ -135,7 +113,7 @@ def test_gdalsrsinfo_5(): def test_gdalsrsinfo_6(): if test_cli_utilities.get_gdalsrsinfo_path() is None: - return 'skip' + pytest.skip() ret = gdaltest.runexternal(test_cli_utilities.get_gdalsrsinfo_path() + ' -o wkt_simple ../gcore/data/byte.tif') @@ -168,11 +146,7 @@ def test_gdalsrsinfo_6(): PARAMETER["false_northing",0], UNIT["metre",1]]""" - if ret.strip() != first_val and ret.strip() != second_val: - print(ret.strip()) - return 'fail' - - return 'success' + assert ret.strip() == first_val or ret.strip() == second_val ############################################################################### # Test -o mapinfo option @@ -180,15 +154,12 @@ def test_gdalsrsinfo_6(): def test_gdalsrsinfo_7(): if test_cli_utilities.get_gdalsrsinfo_path() is None: - return 'skip' + pytest.skip() ret = gdaltest.runexternal(test_cli_utilities.get_gdalsrsinfo_path() + ' -o mapinfo ../gcore/data/byte.tif') - if ret.strip() != """'Earth Projection 8, 62, "m", -117, 0, 0.9996, 500000, 0'""": - return 'fail' - - return 'success' + assert ret.strip() == """'Earth Projection 8, 62, "m", -117, 0, 0.9996, 500000, 0'""" ############################################################################### @@ -196,13 +167,13 @@ def test_gdalsrsinfo_7(): def test_gdalsrsinfo_8(): if test_cli_utilities.get_gdalsrsinfo_path() is None: - return 'skip' + pytest.skip() ret = gdaltest.runexternal(test_cli_utilities.get_gdalsrsinfo_path() + ' -o wkt -p EPSG:4326') ret = ret.replace('\r\n', '\n') - if ret.strip() != """GEOGCS["WGS 84", + assert ret.strip() == """GEOGCS["WGS 84", DATUM["WGS_1984", SPHEROID["WGS 84",6378137,298.257223563, AUTHORITY["EPSG","7030"]], @@ -211,10 +182,7 @@ def test_gdalsrsinfo_8(): AUTHORITY["EPSG","8901"]], UNIT["degree",0.0174532925199433, AUTHORITY["EPSG","9122"]], - AUTHORITY["EPSG","4326"]]""": - return 'fail' - - return 'success' + AUTHORITY["EPSG","4326"]]""" ############################################################################### @@ -222,15 +190,12 @@ def test_gdalsrsinfo_8(): def test_gdalsrsinfo_9(): if test_cli_utilities.get_gdalsrsinfo_path() is None: - return 'skip' + pytest.skip() _, err = gdaltest.runexternal_out_and_err( test_cli_utilities.get_gdalsrsinfo_path() + ' nonexistent_file') - if err.strip() != "ERROR 1: ERROR - failed to load SRS definition from nonexistent_file": - return 'fail' - - return 'success' + assert err.strip() == "ERROR 1: ERROR - failed to load SRS definition from nonexistent_file" ############################################################################### @@ -238,7 +203,7 @@ def test_gdalsrsinfo_9(): def test_gdalsrsinfo_10(): if test_cli_utilities.get_gdalsrsinfo_path() is None: - return 'skip' + pytest.skip() wkt = 'GEOGCS["WGS 84",DATUM["WGS_1984",SPHEROID["WGS 84",6378137,298.257223563,AUTHORITY["EPSG","7030"]],AUTHORITY["EPSG","6326"]],PRIMEM["Greenwich",0,AUTHORITY["EPSG","8901"]],UNIT["degree",0.0174532925199433,AUTHORITY["EPSG","9122"]],AUTHORITY["EPSG","4326"]]' if sys.platform == 'win32': @@ -250,11 +215,7 @@ def test_gdalsrsinfo_10(): ret = gdaltest.runexternal(test_cli_utilities.get_gdalsrsinfo_path() + " -V -o proj4 '" + wkt + "'") - if ret.find('Validate Succeeds') == -1: - print(ret) - return 'fail' - - return 'success' + assert ret.find('Validate Succeeds') != -1 ############################################################################### # Test -V option - invalid @@ -262,7 +223,7 @@ def test_gdalsrsinfo_10(): def test_gdalsrsinfo_11(): if test_cli_utilities.get_gdalsrsinfo_path() is None: - return 'skip' + pytest.skip() wkt = 'GEOGCS["WGS 84",DATUM["WGS_1984",SPHEROID["WGS 84",6378137,298.257223563,AUTHORITY["EPSG","7030"]],AUTHORITY["EPSG","6326"]],PRIMEM["Greenwich",0,AUTHORITY["EPSG","8901"]],UNIT["degree",0.0174532925199433,AUTHORITY["EPSG","9122"]],BADAUTHORITY["EPSG","4326"]]' if sys.platform == 'win32': @@ -274,10 +235,7 @@ def test_gdalsrsinfo_11(): ret = gdaltest.runexternal(test_cli_utilities.get_gdalsrsinfo_path() + " -V -o proj4 '" + wkt + "'") - if ret.find('Validate Fails') == -1: - return 'fail' - - return 'success' + assert ret.find('Validate Fails') != -1 ############################################################################### # Test EPSG:epsg format @@ -285,15 +243,12 @@ def test_gdalsrsinfo_11(): def test_gdalsrsinfo_12(): if test_cli_utilities.get_gdalsrsinfo_path() is None: - return 'skip' + pytest.skip() ret = gdaltest.runexternal(test_cli_utilities.get_gdalsrsinfo_path() + ' -o wkt EPSG:4326') - if ret.strip() != """GEOGCS["WGS 84",DATUM["WGS_1984",SPHEROID["WGS 84",6378137,298.257223563,AUTHORITY["EPSG","7030"]],AUTHORITY["EPSG","6326"]],PRIMEM["Greenwich",0,AUTHORITY["EPSG","8901"]],UNIT["degree",0.0174532925199433,AUTHORITY["EPSG","9122"]],AUTHORITY["EPSG","4326"]]""": - return 'fail' - - return 'success' + assert ret.strip() == """GEOGCS["WGS 84",DATUM["WGS_1984",SPHEROID["WGS 84",6378137,298.257223563,AUTHORITY["EPSG","7030"]],AUTHORITY["EPSG","6326"]],PRIMEM["Greenwich",0,AUTHORITY["EPSG","8901"]],UNIT["degree",0.0174532925199433,AUTHORITY["EPSG","9122"]],AUTHORITY["EPSG","4326"]]""" ############################################################################### @@ -301,15 +256,12 @@ def test_gdalsrsinfo_12(): def test_gdalsrsinfo_13(): if test_cli_utilities.get_gdalsrsinfo_path() is None: - return 'skip' + pytest.skip() ret = gdaltest.runexternal(test_cli_utilities.get_gdalsrsinfo_path() + ' -o wkt "+proj=longlat +datum=WGS84 +no_defs"') - if ret.strip() != """GEOGCS["WGS 84",DATUM["WGS_1984",SPHEROID["WGS 84",6378137,298.257223563,AUTHORITY["EPSG","7030"]],AUTHORITY["EPSG","6326"]],PRIMEM["Greenwich",0,AUTHORITY["EPSG","8901"]],UNIT["degree",0.0174532925199433,AUTHORITY["EPSG","9122"]],AUTHORITY["EPSG","4326"]]""": - return 'fail' - - return 'success' + assert ret.strip() == """GEOGCS["WGS 84",DATUM["WGS_1984",SPHEROID["WGS 84",6378137,298.257223563,AUTHORITY["EPSG","7030"]],AUTHORITY["EPSG","6326"]],PRIMEM["Greenwich",0,AUTHORITY["EPSG","8901"]],UNIT["degree",0.0174532925199433,AUTHORITY["EPSG","9122"]],AUTHORITY["EPSG","4326"]]""" ############################################################################### # Test VSILFILE format @@ -317,15 +269,12 @@ def test_gdalsrsinfo_13(): def test_gdalsrsinfo_14(): if test_cli_utilities.get_gdalsrsinfo_path() is None: - return 'skip' + pytest.skip() ret = gdaltest.runexternal(test_cli_utilities.get_gdalsrsinfo_path() + ' -o proj4 /vsizip/../gcore/data/byte.tif.zip') - if ret.strip() != "+proj=utm +zone=11 +datum=NAD27 +units=m +no_defs": - return 'fail' - - return 'success' + assert ret.strip() == "+proj=utm +zone=11 +datum=NAD27 +units=m +no_defs" ############################################################################### # Test .shp format @@ -333,15 +282,12 @@ def test_gdalsrsinfo_14(): def test_gdalsrsinfo_14bis(): if test_cli_utilities.get_gdalsrsinfo_path() is None: - return 'skip' + pytest.skip() ret = gdaltest.runexternal(test_cli_utilities.get_gdalsrsinfo_path() + ' -o proj4 ../ogr/data/Stacks.shp') - if ret.strip() != "+proj=lcc +lat_1=30.28333333333333 +lat_2=28.38333333333333 +lat_0=27.83333333333333 +lon_0=-99 +x_0=600000 +y_0=3999999.9998984 +ellps=GRS80 +towgs84=0,0,0,0,0,0,0 +units=us-ft +no_defs": - return 'fail' - - return 'success' + assert ret.strip() == "+proj=lcc +lat_1=30.28333333333333 +lat_2=28.38333333333333 +lat_0=27.83333333333333 +lon_0=-99 +x_0=600000 +y_0=3999999.9998984 +ellps=GRS80 +towgs84=0,0,0,0,0,0,0 +units=us-ft +no_defs" ############################################################################### # Test .prj format @@ -349,15 +295,12 @@ def test_gdalsrsinfo_14bis(): def test_gdalsrsinfo_15(): if test_cli_utilities.get_gdalsrsinfo_path() is None: - return 'skip' + pytest.skip() ret = gdaltest.runexternal(test_cli_utilities.get_gdalsrsinfo_path() + ' -o proj4 ../osr/data/lcc_esri.prj') - if ret.strip() != "+proj=lcc +lat_1=34.33333333333334 +lat_2=36.16666666666666 +lat_0=33.75 +lon_0=-79 +x_0=609601.22 +y_0=0 +datum=NAD83 +units=m +no_defs": - return 'fail' - - return 'success' + assert ret.strip() == "+proj=lcc +lat_1=34.33333333333334 +lat_2=36.16666666666666 +lat_0=33.75 +lon_0=-79 +x_0=609601.22 +y_0=0 +datum=NAD83 +units=m +no_defs" ############################################################################### # Test DRIVER:file syntax (bug #4493) - similar test should be done with OGR @@ -365,7 +308,7 @@ def test_gdalsrsinfo_15(): def test_gdalsrsinfo_16(): if test_cli_utilities.get_gdalsrsinfo_path() is None: - return 'skip' + pytest.skip() cmd = test_cli_utilities.get_gdalsrsinfo_path() +\ ' GTIFF_RAW:../gcore/data/byte.tif' @@ -373,13 +316,9 @@ def test_gdalsrsinfo_16(): try: (_, err) = gdaltest.runexternal_out_and_err(cmd) except: - gdaltest.post_reason('gdalsrsinfo execution failed') - return 'fail' - - if err != '': - return 'fail' + pytest.fail('gdalsrsinfo execution failed') - return 'success' + assert err == '' ############################################################################### # Test -e @@ -387,67 +326,28 @@ def test_gdalsrsinfo_16(): def test_gdalsrsinfo_17(): if test_cli_utilities.get_gdalsrsinfo_path() is None: - return 'skip' + pytest.skip() # Zero match ret = gdaltest.runexternal(test_cli_utilities.get_gdalsrsinfo_path() + ' -e "LOCAL_CS[foo]"') - if ret.find('EPSG:-1') < 0: - gdaltest.post_reason('fail') - print(ret) - return 'fail' + assert ret.find('EPSG:-1') >= 0 # One match ret = gdaltest.runexternal(test_cli_utilities.get_gdalsrsinfo_path() + ' -e ../osr/data/lcc_esri.prj') - if ret.find('EPSG:32119') < 0: - gdaltest.post_reason('fail') - print(ret) - return 'fail' + assert ret.find('EPSG:32119') >= 0 # Two matches ret = gdaltest.runexternal(test_cli_utilities.get_gdalsrsinfo_path() + """ -e "GEOGCS[\"myLKS94\",DATUM[\"Lithuania_1994_ETRS89\",SPHEROID[\"GRS_1980\",6378137,298.257222101],TOWGS84[0,0,0,0,0,0,0]],PRIMEM[\"Greenwich\",0],UNIT[\"degree\",0.0174532925199433]]" """) - if ret.find('EPSG:4126') < 0 or ret.find('EPSG:4669') < 0: - gdaltest.post_reason('fail') - print(ret) - return 'fail' - - return 'success' + assert ret.find('EPSG:4126') >= 0 and ret.find('EPSG:4669') >= 0 ############################################################################### # -gdaltest_list = [ - test_gdalsrsinfo_1, - test_gdalsrsinfo_2, - test_gdalsrsinfo_3, - test_gdalsrsinfo_4, - test_gdalsrsinfo_5, - test_gdalsrsinfo_6, - test_gdalsrsinfo_7, - test_gdalsrsinfo_8, - test_gdalsrsinfo_9, - test_gdalsrsinfo_10, - test_gdalsrsinfo_11, - test_gdalsrsinfo_12, - test_gdalsrsinfo_13, - test_gdalsrsinfo_14, - test_gdalsrsinfo_14bis, - test_gdalsrsinfo_15, - test_gdalsrsinfo_16, - test_gdalsrsinfo_17, - None -] - - -if __name__ == '__main__': - - gdaltest.setup_run('test_gdalsrsinfo') - - gdaltest.run_tests(gdaltest_list) - - sys.exit(gdaltest.summarize()) + + diff --git a/autotest/utilities/test_gdaltindex.py b/autotest/utilities/test_gdaltindex.py index 6cf76a53d5b7..82c734c56467 100755 --- a/autotest/utilities/test_gdaltindex.py +++ b/autotest/utilities/test_gdaltindex.py @@ -29,16 +29,15 @@ # DEALINGS IN THE SOFTWARE. ############################################################################### -import sys import os -sys.path.append('../pymod') from osgeo import gdal from osgeo import ogr from osgeo import osr import gdaltest import test_cli_utilities +import pytest ############################################################################### # Simple test @@ -46,7 +45,7 @@ def test_gdaltindex_1(): if test_cli_utilities.get_gdaltindex_path() is None: - return 'skip' + pytest.skip() try: os.remove('tmp/tileindex.shp') @@ -89,27 +88,18 @@ def test_gdaltindex_1(): ds = None (_, err) = gdaltest.runexternal_out_and_err(test_cli_utilities.get_gdaltindex_path() + ' tmp/tileindex.shp tmp/gdaltindex1.tif tmp/gdaltindex2.tif') - if not (err is None or err == ''): - gdaltest.post_reason('got error/warning') - print(err) - return 'fail' + assert (err is None or err == ''), 'got error/warning' (ret_stdout, ret_stderr) = gdaltest.runexternal_out_and_err(test_cli_utilities.get_gdaltindex_path() + ' tmp/tileindex.shp tmp/gdaltindex3.tif tmp/gdaltindex4.tif') ds = ogr.Open('tmp/tileindex.shp') if ds.GetLayer(0).GetFeatureCount() != 4: - gdaltest.post_reason('fail') print(ret_stdout) - print(ret_stderr) - print(ds.GetLayer(0).GetFeatureCount()) - return 'fail' + pytest.fail(ret_stderr) tileindex_wkt = ds.GetLayer(0).GetSpatialRef().ExportToWkt() if tileindex_wkt.find('WGS_1984') == -1: - gdaltest.post_reason('fail') print(ret_stdout) - print(ret_stderr) - print(tileindex_wkt) - return 'fail' + pytest.fail(ret_stderr) expected_wkts = ['POLYGON ((49 2,50 2,50 1,49 1,49 2))', 'POLYGON ((49 3,50 3,50 2,49 2,49 3))', @@ -118,40 +108,32 @@ def test_gdaltindex_1(): i = 0 feat = ds.GetLayer(0).GetNextFeature() while feat is not None: - if feat.GetGeometryRef().ExportToWkt() != expected_wkts[i]: - print('i=%d, wkt=%s' % (i, feat.GetGeometryRef().ExportToWkt())) - return 'fail' + assert feat.GetGeometryRef().ExportToWkt() == expected_wkts[i], \ + ('i=%d, wkt=%s' % (i, feat.GetGeometryRef().ExportToWkt())) i = i + 1 feat = ds.GetLayer(0).GetNextFeature() ds.Destroy() - return 'success' - ############################################################################### # Try adding the same rasters again def test_gdaltindex_2(): if test_cli_utilities.get_gdaltindex_path() is None: - return 'skip' + pytest.skip() (_, ret_stderr) = gdaltest.runexternal_out_and_err(test_cli_utilities.get_gdaltindex_path() + ' tmp/tileindex.shp tmp/gdaltindex1.tif tmp/gdaltindex2.tif tmp/gdaltindex3.tif tmp/gdaltindex4.tif') - if ret_stderr.find('File tmp/gdaltindex1.tif is already in tileindex. Skipping it.') == -1 or \ + assert (not (ret_stderr.find('File tmp/gdaltindex1.tif is already in tileindex. Skipping it.') == -1 or \ ret_stderr.find('File tmp/gdaltindex2.tif is already in tileindex. Skipping it.') == -1 or \ ret_stderr.find('File tmp/gdaltindex3.tif is already in tileindex. Skipping it.') == -1 or \ - ret_stderr.find('File tmp/gdaltindex4.tif is already in tileindex. Skipping it.') == -1: - print(ret_stderr) - gdaltest.post_reason('got unexpected error messages.') - return 'fail' + ret_stderr.find('File tmp/gdaltindex4.tif is already in tileindex. Skipping it.') == -1)), \ + 'got unexpected error messages.' ds = ogr.Open('tmp/tileindex.shp') - if ds.GetLayer(0).GetFeatureCount() != 4: - return 'fail' + assert ds.GetLayer(0).GetFeatureCount() == 4 ds.Destroy() - return 'success' - ############################################################################### # Try adding a raster in another projection with -skip_different_projection @@ -159,7 +141,7 @@ def test_gdaltindex_2(): def test_gdaltindex_3(): if test_cli_utilities.get_gdaltindex_path() is None: - return 'skip' + pytest.skip() drv = gdal.GetDriverByName('GTiff') wkt = 'GEOGCS[\"WGS 72\",DATUM[\"WGS_1972\"]]' @@ -171,19 +153,14 @@ def test_gdaltindex_3(): (_, ret_stderr) = gdaltest.runexternal_out_and_err(test_cli_utilities.get_gdaltindex_path() + ' -skip_different_projection tmp/tileindex.shp tmp/gdaltindex5.tif') - if ret_stderr.find('Warning : tmp/gdaltindex5.tif is not using the same projection system as other files in the tileindex.') == -1 or \ - ret_stderr.find('Use -t_srs option to set target projection system (not supported by MapServer).') == -1: - print(ret_stderr) - gdaltest.post_reason('got unexpected error message \n[%s]' % (ret_stderr)) - return 'fail' + assert (not (ret_stderr.find('Warning : tmp/gdaltindex5.tif is not using the same projection system as other files in the tileindex.') == -1 or \ + ret_stderr.find('Use -t_srs option to set target projection system (not supported by MapServer).') == -1)), \ + ('got unexpected error message \n[%s]' % (ret_stderr)) ds = ogr.Open('tmp/tileindex.shp') - if ds.GetLayer(0).GetFeatureCount() != 4: - return 'fail' + assert ds.GetLayer(0).GetFeatureCount() == 4 ds.Destroy() - return 'success' - ############################################################################### # Try adding a raster in another projection with -t_srs # 5th tile should be inserted, will not be if there is a srs transformation error @@ -191,7 +168,7 @@ def test_gdaltindex_3(): def test_gdaltindex_4(): if test_cli_utilities.get_gdaltindex_path() is None: - return 'skip' + pytest.skip() drv = gdal.GetDriverByName('GTiff') wkt = 'GEOGCS[\"WGS 72\",DATUM[\"WGS_1972\"]]' @@ -204,20 +181,17 @@ def test_gdaltindex_4(): gdaltest.runexternal_out_and_err(test_cli_utilities.get_gdaltindex_path() + ' -t_srs EPSG:4326 tmp/tileindex.shp tmp/gdaltindex5.tif') ds = ogr.Open('tmp/tileindex.shp') - if ds.GetLayer(0).GetFeatureCount() != 5: - gdaltest.post_reason('got %d features, expecting 5' % ds.GetLayer(0).GetFeatureCount()) - return 'fail' + assert ds.GetLayer(0).GetFeatureCount() == 5, \ + ('got %d features, expecting 5' % ds.GetLayer(0).GetFeatureCount()) ds.Destroy() - return 'success' - ############################################################################### # Test -src_srs_name, -src_srs_format options def test_gdaltindex_5(): if test_cli_utilities.get_gdaltindex_path() is None: - return 'skip' + pytest.skip() drv = gdal.GetDriverByName('GTiff') @@ -236,37 +210,32 @@ def test_gdaltindex_5(): ds = ogr.Open('tmp/test_gdaltindex_5.shp') lyr = ds.GetLayer(0) - if lyr.GetFeatureCount() != 2: - gdaltest.post_reason('got %d features, expecting 2' % ds.GetLayer(0).GetFeatureCount()) - return 'fail' + assert lyr.GetFeatureCount() == 2, \ + ('got %d features, expecting 2' % ds.GetLayer(0).GetFeatureCount()) feat = lyr.GetNextFeature() feat = lyr.GetNextFeature() if src_srs_format == '-src_srs_format PROJ': if feat.GetField('src_srs').find('+proj=longlat +ellps=WGS72') != 0: - gdaltest.post_reason('fail') feat.DumpReadable() - return 'fail' + pytest.fail() elif src_srs_format == '-src_srs_format WKT': if feat.GetField('src_srs').find('GEOGCS["WGS 72"') != 0: - gdaltest.post_reason('fail') feat.DumpReadable() - return 'fail' + pytest.fail() else: if feat.GetField('src_srs') != 'EPSG:4322': - gdaltest.post_reason('fail') feat.DumpReadable() - return 'fail' + pytest.fail() ds = None - return 'success' - + ############################################################################### # Test -f, -lyr_name def test_gdaltindex_6(): if test_cli_utilities.get_gdaltindex_path() is None: - return 'skip' + pytest.skip() for option in ['', '-lyr_name tileindex']: gdal.PushErrorHandler('CPLQuietErrorHandler') @@ -275,13 +244,11 @@ def test_gdaltindex_6(): gdaltest.runexternal_out_and_err(test_cli_utilities.get_gdaltindex_path() + ' -f "MapInfo File" %s tmp/test_gdaltindex_6.mif tmp/gdaltindex1.tif' % option) ds = ogr.Open('tmp/test_gdaltindex_6.mif') lyr = ds.GetLayer(0) - if lyr.GetFeatureCount() != 1: - gdaltest.post_reason('got %d features, expecting 1' % lyr.GetFeatureCount()) - return 'fail' + assert lyr.GetFeatureCount() == 1, \ + ('got %d features, expecting 1' % lyr.GetFeatureCount()) ds = None - return 'success' - + ############################################################################### # Cleanup @@ -301,24 +268,6 @@ def test_gdaltindex_cleanup(): drv.Delete('tmp/gdaltindex5.tif') drv.Delete('tmp/gdaltindex6.tif') - return 'success' - - -gdaltest_list = [ - test_gdaltindex_1, - test_gdaltindex_2, - test_gdaltindex_3, - test_gdaltindex_4, - test_gdaltindex_5, - test_gdaltindex_6, - test_gdaltindex_cleanup -] - - -if __name__ == '__main__': - gdaltest.setup_run('test_gdaltindex') - gdaltest.run_tests(gdaltest_list) - sys.exit(gdaltest.summarize()) diff --git a/autotest/utilities/test_gdaltransform.py b/autotest/utilities/test_gdaltransform.py index 71bfaafe043e..559c0d946530 100755 --- a/autotest/utilities/test_gdaltransform.py +++ b/autotest/utilities/test_gdaltransform.py @@ -28,12 +28,11 @@ # DEALINGS IN THE SOFTWARE. ############################################################################### -import sys -sys.path.append('../pymod') import gdaltest import test_cli_utilities +import pytest ############################################################################### # Test -s_srs and -t_srs @@ -41,19 +40,13 @@ def test_gdaltransform_1(): if test_cli_utilities.get_gdaltransform_path() is None: - return 'skip' + pytest.skip() strin = '2 49 1\n' + '3 50 2\n' ret = gdaltest.runexternal(test_cli_utilities.get_gdaltransform_path() + ' -s_srs EPSG:4326 -t_srs EPSG:4326', strin) - if ret.find('2 49 1') == -1: - print(ret) - return 'fail' - if ret.find('3 50 2') == -1: - print(ret) - return 'fail' - - return 'success' + assert ret.find('2 49 1') != -1 + assert ret.find('3 50 2') != -1 ############################################################################### # Test -gcp @@ -61,25 +54,15 @@ def test_gdaltransform_1(): def test_gdaltransform_2(): if test_cli_utilities.get_gdaltransform_path() is None: - return 'skip' + pytest.skip() strin = '0 0\n' + '20 0\n' + '20 20\n' + '0 20\n' ret = gdaltest.runexternal(test_cli_utilities.get_gdaltransform_path() + ' -gcp 0 0 440720.000 3751320.000 -gcp 20 0 441920.000 3751320.000 -gcp 20 20 441920.000 3750120.000 0 -gcp 0 20 440720.000 3750120.000', strin) - if ret.find('440720 3751320') == -1: - print(ret) - return 'fail' - if ret.find('441920 3751320') == -1: - print(ret) - return 'fail' - if ret.find('441920 3750120') == -1: - print(ret) - return 'fail' - if ret.find('440720 3750120') == -1: - print(ret) - return 'fail' - - return 'success' + assert ret.find('440720 3751320') != -1 + assert ret.find('441920 3751320') != -1 + assert ret.find('441920 3750120') != -1 + assert ret.find('440720 3750120') != -1 ############################################################################### # Test -gcp -tps @@ -87,25 +70,15 @@ def test_gdaltransform_2(): def test_gdaltransform_3(): if test_cli_utilities.get_gdaltransform_path() is None: - return 'skip' + pytest.skip() strin = '0 0\n' + '20 0\n' + '20 20\n' + '0 20\n' ret = gdaltest.runexternal(test_cli_utilities.get_gdaltransform_path() + ' -tps -gcp 0 0 440720.000 3751320.000 -gcp 20 0 441920.000 3751320.000 -gcp 20 20 441920.000 3750120.000 0 -gcp 0 20 440720.000 3750120.000', strin) - if ret.find('440720 3751320') == -1: - print(ret) - return 'fail' - if ret.find('441920 3751320') == -1: - print(ret) - return 'fail' - if ret.find('441920 3750120') == -1: - print(ret) - return 'fail' - if ret.find('440720 3750120') == -1: - print(ret) - return 'fail' - - return 'success' + assert ret.find('440720 3751320') != -1 + assert ret.find('441920 3751320') != -1 + assert ret.find('441920 3750120') != -1 + assert ret.find('440720 3750120') != -1 ############################################################################### # Test -gcp -order 1 @@ -113,25 +86,15 @@ def test_gdaltransform_3(): def test_gdaltransform_4(): if test_cli_utilities.get_gdaltransform_path() is None: - return 'skip' + pytest.skip() strin = '0 0\n' + '20 0\n' + '20 20\n' + '0 20\n' ret = gdaltest.runexternal(test_cli_utilities.get_gdaltransform_path() + ' -order 1 -gcp 0 0 440720.000 3751320.000 -gcp 20 0 441920.000 3751320.000 -gcp 20 20 441920.000 3750120.000 0 -gcp 0 20 440720.000 3750120.000', strin) - if ret.find('440720 3751320') == -1: - print(ret) - return 'fail' - if ret.find('441920 3751320') == -1: - print(ret) - return 'fail' - if ret.find('441920 3750120') == -1: - print(ret) - return 'fail' - if ret.find('440720 3750120') == -1: - print(ret) - return 'fail' - - return 'success' + assert ret.find('440720 3751320') != -1 + assert ret.find('441920 3751320') != -1 + assert ret.find('441920 3750120') != -1 + assert ret.find('440720 3750120') != -1 ############################################################################### # Test with input file and -t_srs @@ -139,7 +102,7 @@ def test_gdaltransform_4(): def test_gdaltransform_5(): if test_cli_utilities.get_gdaltransform_path() is None: - return 'skip' + pytest.skip() strin = '0 0\n' ret = gdaltest.runexternal(test_cli_utilities.get_gdaltransform_path() + ' -t_srs EPSG:26711 ../gcore/data/byte.tif', strin) @@ -148,11 +111,7 @@ def test_gdaltransform_5(): x = float(text_split[0]) y = float(text_split[1]) - if abs(x - 440720) > 1e-4 or abs(y - 3751320) > 1e-4: - print(ret) - return 'fail' - - return 'success' + assert abs(x - 440720) <= 1e-4 and abs(y - 3751320) <= 1e-4, ret ############################################################################### # Test with input file and output file @@ -160,7 +119,7 @@ def test_gdaltransform_5(): def test_gdaltransform_6(): if test_cli_utilities.get_gdaltransform_path() is None: - return 'skip' + pytest.skip() strin = '440720 3751320\n' ret = gdaltest.runexternal(test_cli_utilities.get_gdaltransform_path() + ' ../gcore/data/byte.tif ../gcore/data/byte.tif', strin) @@ -169,11 +128,7 @@ def test_gdaltransform_6(): x = float(text_split[0]) y = float(text_split[1]) - if abs(x - 440720) > 1e-4 or abs(y - 3751320) > 1e-4: - print(ret) - return 'fail' - - return 'success' + assert abs(x - 440720) <= 1e-4 and abs(y - 3751320) <= 1e-4, ret ############################################################################### @@ -181,7 +136,7 @@ def test_gdaltransform_6(): def test_gdaltransform_7(): if test_cli_utilities.get_gdaltransform_path() is None: - return 'skip' + pytest.skip() strin = '440720 3751320\n' ret = gdaltest.runexternal(test_cli_utilities.get_gdaltransform_path() + ' -t_srs EPSG:26711 ../gcore/data/byte.tif -i', strin) @@ -190,11 +145,7 @@ def test_gdaltransform_7(): x = float(text_split[0]) y = float(text_split[1]) - if abs(x - 0) > 1e-4 or abs(y - 0) > 1e-4: - print(ret) - return 'fail' - - return 'success' + assert abs(x - 0) <= 1e-4 and abs(y - 0) <= 1e-4, ret ############################################################################### # Test -to @@ -202,16 +153,12 @@ def test_gdaltransform_7(): def test_gdaltransform_8(): if test_cli_utilities.get_gdaltransform_path() is None: - return 'skip' + pytest.skip() strin = '2 49 1\n' ret = gdaltest.runexternal(test_cli_utilities.get_gdaltransform_path() + ' -to "SRC_SRS=WGS84" -to "DST_SRS=WGS84"', strin) - if ret.find('2 49 1') == -1: - print(ret) - return 'fail' - - return 'success' + assert ret.find('2 49 1') != -1 ############################################################################### # Test -output_xy @@ -219,36 +166,14 @@ def test_gdaltransform_8(): def test_gdaltransform_9(): if test_cli_utilities.get_gdaltransform_path() is None: - return 'skip' + pytest.skip() strin = '0 0 0\n' ret = gdaltest.runexternal(test_cli_utilities.get_gdaltransform_path() + ' ../gcore/data/byte.tif -output_xy', strin) text_split = ret.split(' ') - if len(text_split) != 2: - print(ret) - return 'fail' - - return 'success' - - -gdaltest_list = [ - test_gdaltransform_1, - test_gdaltransform_2, - test_gdaltransform_3, - test_gdaltransform_4, - test_gdaltransform_5, - test_gdaltransform_6, - test_gdaltransform_7, - test_gdaltransform_8, - test_gdaltransform_9 -] - + assert len(text_split) == 2, ret -if __name__ == '__main__': - gdaltest.setup_run('test_gdaltransform') - gdaltest.run_tests(gdaltest_list) - sys.exit(gdaltest.summarize()) diff --git a/autotest/utilities/test_gdalwarp.py b/autotest/utilities/test_gdalwarp.py index 23b98b253180..0ebbc8db9c18 100755 --- a/autotest/utilities/test_gdalwarp.py +++ b/autotest/utilities/test_gdalwarp.py @@ -29,15 +29,14 @@ # DEALINGS IN THE SOFTWARE. ############################################################################### -import sys import os import stat -sys.path.append('../pymod') from osgeo import gdal import gdaltest import test_cli_utilities +import pytest ############################################################################### # Simple test @@ -45,257 +44,201 @@ def test_gdalwarp_1(): if test_cli_utilities.get_gdalwarp_path() is None: - return 'skip' + pytest.skip() (_, err) = gdaltest.runexternal_out_and_err(test_cli_utilities.get_gdalwarp_path() + ' ../gcore/data/byte.tif tmp/testgdalwarp1.tif') - if not (err is None or err == ''): - gdaltest.post_reason('got error/warning') - print(err) - return 'fail' + assert (err is None or err == ''), 'got error/warning' ds = gdal.Open('tmp/testgdalwarp1.tif') - if ds is None: - return 'fail' + assert ds is not None - if ds.GetRasterBand(1).Checksum() != 4672: - gdaltest.post_reason('Bad checksum') - return 'fail' + assert ds.GetRasterBand(1).Checksum() == 4672, 'Bad checksum' ds = None - return 'success' - ############################################################################### # Test -of option def test_gdalwarp_2(): if test_cli_utilities.get_gdalwarp_path() is None: - return 'skip' + pytest.skip() gdaltest.runexternal(test_cli_utilities.get_gdalwarp_path() + ' -of GTiff ../gcore/data/byte.tif tmp/testgdalwarp2.tif') ds = gdal.Open('tmp/testgdalwarp2.tif') - if ds is None: - return 'fail' + assert ds is not None - if ds.GetRasterBand(1).Checksum() != 4672: - gdaltest.post_reason('Bad checksum') - return 'fail' + assert ds.GetRasterBand(1).Checksum() == 4672, 'Bad checksum' ds = None - return 'success' - ############################################################################### # Test -ot option def test_gdalwarp_3(): if test_cli_utilities.get_gdalwarp_path() is None: - return 'skip' + pytest.skip() gdaltest.runexternal(test_cli_utilities.get_gdalwarp_path() + ' -ot Int16 ../gcore/data/byte.tif tmp/testgdalwarp3.tif') ds = gdal.Open('tmp/testgdalwarp3.tif') - if ds is None: - return 'fail' + assert ds is not None - if ds.GetRasterBand(1).DataType != gdal.GDT_Int16: - gdaltest.post_reason('Bad data type') - return 'fail' + assert ds.GetRasterBand(1).DataType == gdal.GDT_Int16, 'Bad data type' - if ds.GetRasterBand(1).Checksum() != 4672: - gdaltest.post_reason('Bad checksum') - return 'fail' + assert ds.GetRasterBand(1).Checksum() == 4672, 'Bad checksum' ds = None - return 'success' - ############################################################################### # Test -t_srs option def test_gdalwarp_4(): if test_cli_utilities.get_gdalwarp_path() is None: - return 'skip' + pytest.skip() gdaltest.runexternal(test_cli_utilities.get_gdalwarp_path() + ' -t_srs EPSG:32611 ../gcore/data/byte.tif tmp/testgdalwarp4.tif') ds = gdal.Open('tmp/testgdalwarp4.tif') - if ds is None: - return 'fail' + assert ds is not None - if ds.GetRasterBand(1).Checksum() != 4672: - gdaltest.post_reason('Bad checksum') - return 'fail' + assert ds.GetRasterBand(1).Checksum() == 4672, 'Bad checksum' ds = None - return 'success' - ############################################################################### # Test warping from GCPs without any explicit option def test_gdalwarp_5(): if test_cli_utilities.get_gdalwarp_path() is None: - return 'skip' + pytest.skip() if test_cli_utilities.get_gdal_translate_path() is None: - return 'skip' + pytest.skip() gdaltest.runexternal(test_cli_utilities.get_gdal_translate_path() + ' -a_srs EPSG:26711 -gcp 0 0 440720.000 3751320.000 -gcp 20 0 441920.000 3751320.000 -gcp 20 20 441920.000 3750120.000 0 -gcp 0 20 440720.000 3750120.000 ../gcore/data/byte.tif tmp/testgdalwarp_gcp.tif') gdaltest.runexternal(test_cli_utilities.get_gdalwarp_path() + ' tmp/testgdalwarp_gcp.tif tmp/testgdalwarp5.tif') ds = gdal.Open('tmp/testgdalwarp5.tif') - if ds is None: - return 'fail' + assert ds is not None - if ds.GetRasterBand(1).Checksum() != 4672: - gdaltest.post_reason('Bad checksum') - return 'fail' + assert ds.GetRasterBand(1).Checksum() == 4672, 'Bad checksum' - if not gdaltest.geotransform_equals(gdal.Open('../gcore/data/byte.tif').GetGeoTransform(), ds.GetGeoTransform(), 1e-9): - gdaltest.post_reason('Bad geotransform') - return 'fail' + assert gdaltest.geotransform_equals(gdal.Open('../gcore/data/byte.tif').GetGeoTransform(), ds.GetGeoTransform(), 1e-9), \ + 'Bad geotransform' ds = None - return 'success' - ############################################################################### # Test warping from GCPs with -tps def test_gdalwarp_6(): if test_cli_utilities.get_gdalwarp_path() is None: - return 'skip' + pytest.skip() gdaltest.runexternal(test_cli_utilities.get_gdalwarp_path() + ' -tps tmp/testgdalwarp_gcp.tif tmp/testgdalwarp6.tif') ds = gdal.Open('tmp/testgdalwarp6.tif') - if ds is None: - return 'fail' + assert ds is not None - if ds.GetRasterBand(1).Checksum() != 4672: - gdaltest.post_reason('Bad checksum') - return 'fail' + assert ds.GetRasterBand(1).Checksum() == 4672, 'Bad checksum' - if not gdaltest.geotransform_equals(gdal.Open('../gcore/data/byte.tif').GetGeoTransform(), ds.GetGeoTransform(), 1e-9): - gdaltest.post_reason('Bad geotransform') - return 'fail' + assert gdaltest.geotransform_equals(gdal.Open('../gcore/data/byte.tif').GetGeoTransform(), ds.GetGeoTransform(), 1e-9), \ + 'Bad geotransform' ds = None - return 'success' - ############################################################################### # Test -tr def test_gdalwarp_7(): if test_cli_utilities.get_gdalwarp_path() is None: - return 'skip' + pytest.skip() gdaltest.runexternal(test_cli_utilities.get_gdalwarp_path() + ' -tr 120 120 tmp/testgdalwarp_gcp.tif tmp/testgdalwarp7.tif') ds = gdal.Open('tmp/testgdalwarp7.tif') - if ds is None: - return 'fail' + assert ds is not None expected_gt = (440720.0, 120.0, 0.0, 3751320.0, 0.0, -120.0) - if not gdaltest.geotransform_equals(expected_gt, ds.GetGeoTransform(), 1e-9): - gdaltest.post_reason('Bad geotransform') - return 'fail' + assert gdaltest.geotransform_equals(expected_gt, ds.GetGeoTransform(), 1e-9), \ + 'Bad geotransform' ds = None - return 'success' - ############################################################################### # Test -ts def test_gdalwarp_8(): if test_cli_utilities.get_gdalwarp_path() is None: - return 'skip' + pytest.skip() gdaltest.runexternal(test_cli_utilities.get_gdalwarp_path() + ' -ts 10 10 tmp/testgdalwarp_gcp.tif tmp/testgdalwarp8.tif') ds = gdal.Open('tmp/testgdalwarp8.tif') - if ds is None: - return 'fail' + assert ds is not None expected_gt = (440720.0, 120.0, 0.0, 3751320.0, 0.0, -120.0) - if not gdaltest.geotransform_equals(expected_gt, ds.GetGeoTransform(), 1e-9): - gdaltest.post_reason('Bad geotransform') - return 'fail' + assert gdaltest.geotransform_equals(expected_gt, ds.GetGeoTransform(), 1e-9), \ + 'Bad geotransform' ds = None - return 'success' - ############################################################################### # Test -te def test_gdalwarp_9(): if test_cli_utilities.get_gdalwarp_path() is None: - return 'skip' + pytest.skip() gdaltest.runexternal(test_cli_utilities.get_gdalwarp_path() + ' -te 440720.000 3750120.000 441920.000 3751320.000 tmp/testgdalwarp_gcp.tif tmp/testgdalwarp9.tif') ds = gdal.Open('tmp/testgdalwarp9.tif') - if ds is None: - return 'fail' + assert ds is not None - if not gdaltest.geotransform_equals(gdal.Open('../gcore/data/byte.tif').GetGeoTransform(), ds.GetGeoTransform(), 1e-9): - gdaltest.post_reason('Bad geotransform') - return 'fail' + assert gdaltest.geotransform_equals(gdal.Open('../gcore/data/byte.tif').GetGeoTransform(), ds.GetGeoTransform(), 1e-9), \ + 'Bad geotransform' ds = None - return 'success' - ############################################################################### # Test -rn def test_gdalwarp_10(): if test_cli_utilities.get_gdalwarp_path() is None: - return 'skip' + pytest.skip() gdaltest.runexternal(test_cli_utilities.get_gdalwarp_path() + ' -ts 40 40 -rn tmp/testgdalwarp_gcp.tif tmp/testgdalwarp10.tif') ds = gdal.Open('tmp/testgdalwarp10.tif') - if ds is None: - return 'fail' + assert ds is not None - if ds.GetRasterBand(1).Checksum() != 18784: - print(ds.GetRasterBand(1).Checksum()) - gdaltest.post_reason('Bad checksum') - return 'fail' + assert ds.GetRasterBand(1).Checksum() == 18784, 'Bad checksum' ds = None - return 'success' - ############################################################################### # Test -rb def test_gdalwarp_11(): if test_cli_utilities.get_gdalwarp_path() is None: - return 'skip' + pytest.skip() gdaltest.runexternal(test_cli_utilities.get_gdalwarp_path() + ' -ts 40 40 -rb tmp/testgdalwarp_gcp.tif tmp/testgdalwarp11.tif') ds = gdal.Open('tmp/testgdalwarp11.tif') - if ds is None: - return 'fail' + assert ds is not None ref_ds = gdal.Open('ref_data/testgdalwarp11.tif') maxdiff = gdaltest.compare_ds(ds, ref_ds, verbose=0) @@ -303,26 +246,22 @@ def test_gdalwarp_11(): if maxdiff > 1: gdaltest.compare_ds(ds, ref_ds, verbose=1) - gdaltest.post_reason('Image too different from reference') - return 'fail' + pytest.fail('Image too different from reference') ds = None - return 'success' - ############################################################################### # Test -rc def test_gdalwarp_12(): if test_cli_utilities.get_gdalwarp_path() is None: - return 'skip' + pytest.skip() gdaltest.runexternal(test_cli_utilities.get_gdalwarp_path() + ' -ts 40 40 -rc tmp/testgdalwarp_gcp.tif tmp/testgdalwarp12.tif') ds = gdal.Open('tmp/testgdalwarp12.tif') - if ds is None: - return 'fail' + assert ds is not None ref_ds = gdal.Open('ref_data/testgdalwarp12.tif') maxdiff = gdaltest.compare_ds(ds, ref_ds, verbose=0) @@ -330,288 +269,219 @@ def test_gdalwarp_12(): if maxdiff > 1: gdaltest.compare_ds(ds, ref_ds, verbose=1) ref_ds = None - gdaltest.post_reason('Image too different from reference') - return 'fail' + pytest.fail('Image too different from reference') ds = None ref_ds = None - return 'success' - ############################################################################### # Test -rcs def test_gdalwarp_13(): if test_cli_utilities.get_gdalwarp_path() is None: - return 'skip' + pytest.skip() gdaltest.runexternal(test_cli_utilities.get_gdalwarp_path() + ' -ts 40 40 -rcs tmp/testgdalwarp_gcp.tif tmp/testgdalwarp13.tif') ds = gdal.Open('tmp/testgdalwarp13.tif') - if ds is None: - return 'fail' + assert ds is not None ref_ds = gdal.Open('ref_data/testgdalwarp13.tif') maxdiff = gdaltest.compare_ds(ds, ref_ds) ref_ds = None - if maxdiff > 1: - gdaltest.post_reason('Image too different from reference') - return 'fail' + assert maxdiff <= 1, 'Image too different from reference' ds = None - return 'success' - ############################################################################### # Test -r lanczos def test_gdalwarp_14(): if test_cli_utilities.get_gdalwarp_path() is None: - return 'skip' + pytest.skip() gdaltest.runexternal(test_cli_utilities.get_gdalwarp_path() + ' -ts 40 40 -r lanczos tmp/testgdalwarp_gcp.tif tmp/testgdalwarp14.tif') ds = gdal.Open('tmp/testgdalwarp14.tif') - if ds is None: - return 'fail' + assert ds is not None ref_ds = gdal.Open('ref_data/testgdalwarp14.tif') maxdiff = gdaltest.compare_ds(ds, ref_ds) ref_ds = None - if maxdiff > 1: - gdaltest.post_reason('Image too different from reference') - return 'fail' + assert maxdiff <= 1, 'Image too different from reference' ds = None - return 'success' - ############################################################################### # Test -dstnodata def test_gdalwarp_15(): if test_cli_utilities.get_gdalwarp_path() is None: - return 'skip' + pytest.skip() gdaltest.runexternal(test_cli_utilities.get_gdalwarp_path() + ' -dstnodata 1 -t_srs EPSG:32610 tmp/testgdalwarp_gcp.tif tmp/testgdalwarp15.tif') ds = gdal.Open('tmp/testgdalwarp15.tif') - if ds is None: - return 'fail' + assert ds is not None - if ds.GetRasterBand(1).GetNoDataValue() != 1: - print(ds.GetRasterBand(1).GetNoDataValue()) - gdaltest.post_reason('Bad nodata value') - return 'fail' + assert ds.GetRasterBand(1).GetNoDataValue() == 1, 'Bad nodata value' - if ds.GetRasterBand(1).Checksum() != 4523: - print(ds.GetRasterBand(1).Checksum()) - gdaltest.post_reason('Bad checksum') - return 'fail' + assert ds.GetRasterBand(1).Checksum() == 4523, 'Bad checksum' ds = None - return 'success' - ############################################################################### # Test -of VRT which is a special case def test_gdalwarp_16(): if test_cli_utilities.get_gdalwarp_path() is None: - return 'skip' + pytest.skip() gdaltest.runexternal(test_cli_utilities.get_gdalwarp_path() + ' -of VRT tmp/testgdalwarp_gcp.tif tmp/testgdalwarp16.vrt') ds = gdal.Open('tmp/testgdalwarp16.vrt') - if ds is None: - return 'fail' + assert ds is not None - if ds.GetRasterBand(1).Checksum() != 4672: - print(ds.GetRasterBand(1).Checksum()) - gdaltest.post_reason('Bad checksum') - return 'fail' + assert ds.GetRasterBand(1).Checksum() == 4672, 'Bad checksum' ds = None - return 'success' - ############################################################################### # Test -dstalpha def test_gdalwarp_17(): if test_cli_utilities.get_gdalwarp_path() is None: - return 'skip' + pytest.skip() gdaltest.runexternal(test_cli_utilities.get_gdalwarp_path() + ' -dstalpha ../gcore/data/rgbsmall.tif tmp/testgdalwarp17.tif') ds = gdal.Open('tmp/testgdalwarp17.tif') - if ds is None: - return 'fail' + assert ds is not None - if ds.GetRasterBand(4) is None: - gdaltest.post_reason('No alpha band generated') - return 'fail' + assert ds.GetRasterBand(4) is not None, 'No alpha band generated' ds = None - return 'success' - ############################################################################### # Test -wm -multi def test_gdalwarp_18(): if test_cli_utilities.get_gdalwarp_path() is None: - return 'skip' + pytest.skip() (_, ret_stderr) = gdaltest.runexternal_out_and_err(test_cli_utilities.get_gdalwarp_path() + ' -wm 20 -multi ../gcore/data/byte.tif tmp/testgdalwarp18.tif') # This error will be returned if GDAL is not compiled with thread support if ret_stderr.find('CPLCreateThread() failed in ChunkAndWarpMulti()') != -1: - print('GDAL not compiled with thread support') - return 'skip' + pytest.skip('GDAL not compiled with thread support') ds = gdal.Open('tmp/testgdalwarp18.tif') - if ds is None: - return 'fail' + assert ds is not None - if ds.GetRasterBand(1).Checksum() != 4672: - gdaltest.post_reason('Bad checksum') - return 'fail' + assert ds.GetRasterBand(1).Checksum() == 4672, 'Bad checksum' ds = None - return 'success' - ############################################################################### # Test -et 0 which is a special case def test_gdalwarp_19(): if test_cli_utilities.get_gdalwarp_path() is None: - return 'skip' + pytest.skip() gdaltest.runexternal(test_cli_utilities.get_gdalwarp_path() + ' -et 0 tmp/testgdalwarp_gcp.tif tmp/testgdalwarp19.tif') ds = gdal.Open('tmp/testgdalwarp19.tif') - if ds is None: - return 'fail' + assert ds is not None - if ds.GetRasterBand(1).Checksum() != 4672: - print(ds.GetRasterBand(1).Checksum()) - gdaltest.post_reason('Bad checksum') - return 'fail' + assert ds.GetRasterBand(1).Checksum() == 4672, 'Bad checksum' ds = None - return 'success' - ############################################################################### # Test -of VRT -et 0 which is a special case def test_gdalwarp_20(): if test_cli_utilities.get_gdalwarp_path() is None: - return 'skip' + pytest.skip() gdaltest.runexternal(test_cli_utilities.get_gdalwarp_path() + ' -of VRT -et 0 tmp/testgdalwarp_gcp.tif tmp/testgdalwarp20.vrt') ds = gdal.Open('tmp/testgdalwarp20.vrt') - if ds is None: - return 'fail' + assert ds is not None - if ds.GetRasterBand(1).Checksum() != 4672: - print(ds.GetRasterBand(1).Checksum()) - gdaltest.post_reason('Bad checksum') - return 'fail' + assert ds.GetRasterBand(1).Checksum() == 4672, 'Bad checksum' ds = None - return 'success' - ############################################################################### # Test cutline from OGR datasource. def test_gdalwarp_21(): if test_cli_utilities.get_gdalwarp_path() is None: - return 'skip' + pytest.skip() gdaltest.runexternal(test_cli_utilities.get_gdalwarp_path() + ' ../gcore/data/utmsmall.tif tmp/testgdalwarp21.tif -cutline data/cutline.vrt -cl cutline') ds = gdal.Open('tmp/testgdalwarp21.tif') - if ds is None: - return 'fail' + assert ds is not None - if ds.GetRasterBand(1).Checksum() != 19139: - print(ds.GetRasterBand(1).Checksum()) - gdaltest.post_reason('Bad checksum') - return 'fail' + assert ds.GetRasterBand(1).Checksum() == 19139, 'Bad checksum' ds = None - return 'success' - ############################################################################### # Test with a cutline and an output at a different resolution. def test_gdalwarp_22(): if test_cli_utilities.get_gdalwarp_path() is None: - return 'skip' + pytest.skip() gdaltest.runexternal(test_cli_utilities.get_gdalwarp_path() + ' ../gcore/data/utmsmall.tif tmp/testgdalwarp22.tif -cutline data/cutline.vrt -cl cutline -tr 30 30') ds = gdal.Open('tmp/testgdalwarp22.tif') - if ds is None: - return 'fail' + assert ds is not None - if ds.GetRasterBand(1).Checksum() != 14047: - print(ds.GetRasterBand(1).Checksum()) - gdaltest.post_reason('Bad checksum') - return 'fail' + assert ds.GetRasterBand(1).Checksum() == 14047, 'Bad checksum' ds = None - return 'success' - ############################################################################### # Test cutline with ALL_TOUCHED enabled. def test_gdalwarp_23(): if test_cli_utilities.get_gdalwarp_path() is None: - return 'skip' + pytest.skip() gdaltest.runexternal(test_cli_utilities.get_gdalwarp_path() + ' -wo CUTLINE_ALL_TOUCHED=TRUE ../gcore/data/utmsmall.tif tmp/testgdalwarp23.tif -cutline data/cutline.vrt -cl cutline') ds = gdal.Open('tmp/testgdalwarp23.tif') - if ds is None: - return 'fail' + assert ds is not None - if ds.GetRasterBand(1).Checksum() != 20123: - print(ds.GetRasterBand(1).Checksum()) - gdaltest.post_reason('Bad checksum') - return 'fail' + assert ds.GetRasterBand(1).Checksum() == 20123, 'Bad checksum' ds = None - return 'success' - ############################################################################### # Test warping an image crossing the 180E/180W longitude (#3206) def test_gdalwarp_24(): if test_cli_utilities.get_gdalwarp_path() is None: - return 'skip' + pytest.skip() ds = gdal.GetDriverByName('GTiff').Create('tmp/testgdalwarp24src.tif', 100, 100) ds.SetGeoTransform([179.5, 0.01, 0, 45, 0, -0.01]) @@ -622,127 +492,93 @@ def test_gdalwarp_24(): gdaltest.runexternal(test_cli_utilities.get_gdalwarp_path() + ' -t_srs EPSG:32660 tmp/testgdalwarp24src.tif tmp/testgdalwarp24dst.tif') ds = gdal.Open('tmp/testgdalwarp24dst.tif') - if ds is None: - return 'fail' + assert ds is not None - if ds.GetRasterBand(1).Checksum() != 50634: - print(ds.GetRasterBand(1).Checksum()) - gdaltest.post_reason('Bad checksum') - return 'fail' + assert ds.GetRasterBand(1).Checksum() == 50634, 'Bad checksum' ds = None - return 'success' - ############################################################################### # Test warping a full EPSG:4326 extent to +proj=sinu (#2305) def test_gdalwarp_25(): if test_cli_utilities.get_gdalwarp_path() is None: - return 'skip' + pytest.skip() gdaltest.runexternal(test_cli_utilities.get_gdalwarp_path() + ' -t_srs "+proj=sinu" data/w_jpeg.tiff tmp/testgdalwarp25.tif') ds = gdal.Open('tmp/testgdalwarp25.tif') - if ds is None: - return 'fail' + assert ds is not None cs = ds.GetRasterBand(1).Checksum() - if cs != 8016 and cs != 6157: - print(cs) - gdaltest.post_reason('Bad checksum') - return 'fail' + assert cs == 8016 or cs == 6157, 'Bad checksum' gt = ds.GetGeoTransform() expected_gt = [-20037508.342789248, 78245.302611923355, 0.0, 10001965.729313632, 0.0, -77939.656898595524] for i in range(6): - if abs(gt[i] - expected_gt[i]) > 1: - print(gt) - gdaltest.post_reason('Bad gt') - return 'fail' + assert abs(gt[i] - expected_gt[i]) <= 1, 'Bad gt' ds = None - return 'success' - ############################################################################### # Test warping a full EPSG:4326 extent to +proj=eck4 (#2305) def test_gdalwarp_26(): if test_cli_utilities.get_gdalwarp_path() is None: - return 'skip' + pytest.skip() gdaltest.runexternal(test_cli_utilities.get_gdalwarp_path() + ' -t_srs "+proj=eck4" data/w_jpeg.tiff tmp/testgdalwarp26.tif') ds = gdal.Open('tmp/testgdalwarp26.tif') - if ds is None: - return 'fail' + assert ds is not None cs = ds.GetRasterBand(1).Checksum() - if cs != 8582 and cs != 3938: - print(cs) - gdaltest.post_reason('Bad checksum') - return 'fail' + assert cs == 8582 or cs == 3938, 'Bad checksum' gt = ds.GetGeoTransform() expected_gt = [-16921202.922943164, 41752.719393322564, 0.0, 8460601.4614715818, 0.0, -41701.109109770863] for i in range(6): - if abs(gt[i] - expected_gt[i]) > 1: - print(gt) - gdaltest.post_reason('Bad gt') - return 'fail' + assert abs(gt[i] - expected_gt[i]) <= 1, 'Bad gt' ds = None - return 'success' - ############################################################################### # Test warping a full EPSG:4326 extent to +proj=vandg (#2305) def test_gdalwarp_27(): if test_cli_utilities.get_gdalwarp_path() is None: - return 'skip' + pytest.skip() gdaltest.runexternal(test_cli_utilities.get_gdalwarp_path() + ' -t_srs "+proj=vandg" data/w_jpeg.tiff tmp/testgdalwarp27.tif') ds = gdal.Open('tmp/testgdalwarp27.tif') - if ds is None: - return 'fail' + assert ds is not None cs = ds.GetRasterBand(1).Checksum() - if cs != 22006 and cs != 22615: - print(cs) - gdaltest.post_reason('Bad checksum') - return 'fail' + assert cs == 22006 or cs == 22615, 'Bad checksum' gt = ds.GetGeoTransform() expected_gt = [-20015109.356056381, 98651.645855415176, 0.0, 20015109.356056374, 0.0, -98651.645855415176] for i in range(6): - if abs(gt[i] - expected_gt[i]) > 1: - print(gt) - gdaltest.post_reason('Bad gt') - return 'fail' + assert abs(gt[i] - expected_gt[i]) <= 1, 'Bad gt' ds = None - return 'success' - ############################################################################### # Test warping a full EPSG:4326 extent to +proj=aeqd +lat_0=45 +lon_0=90 (#2305) def test_gdalwarp_28(): if test_cli_utilities.get_gdalwarp_path() is None: - return 'skip' + pytest.skip() gdaltest.runexternal(test_cli_utilities.get_gdalwarp_path() + ' -t_srs "+proj=aeqd +lat_0=45 +lon_0=90" data/w_jpeg.tiff tmp/testgdalwarp28.tif') ds = gdal.Open('tmp/testgdalwarp28.tif') - if ds is None: - return 'fail' + assert ds is not None # Check that there is no hole at the south pole location # First is gcc unoptimized with proj 5.1 @@ -750,10 +586,7 @@ def test_gdalwarp_28(): # Third is mingw_w64 with proj 4.9.2 # Fourth is macosx with proj 5.0.1 cs = ds.GetRasterBand(1).Checksum() - if cs not in (37509, 46728, 26309, 32622): - print(cs) - gdaltest.post_reason('Bad checksum') - return 'fail' + assert cs in (37509, 46728, 26309, 32622), 'Bad checksum' gt = ds.GetGeoTransform() # First is GCC; Second is MSVC 6.0. Third is proj 4.9.2. Fourth is proj 4.9.3 @@ -762,54 +595,41 @@ def test_gdalwarp_28(): expected_gt3 = [-19976414.463615071, 95707.390034570519, 0.0, 20003931.458625447, 0.0, -95707.390034570519] expected_gt4 = (-19976414.463615071, 95709.342728086922, 0.0, 19004529.751051534, 0.0, -95474.761005714157) for i in range(6): - if abs(gt[i] - expected_gt1[i]) > 1 and abs(gt[i] - expected_gt2[i]) > 1 and abs(gt[i] - expected_gt3[i]) > 1 and abs(gt[i] - expected_gt4[i]) > 1: - print(gt) - gdaltest.post_reason('Bad gt') - return 'fail' + assert abs(gt[i] - expected_gt1[i]) <= 1 or abs(gt[i] - expected_gt2[i]) <= 1 or abs(gt[i] - expected_gt3[i]) <= 1 or abs(gt[i] - expected_gt4[i]) <= 1, \ + 'Bad gt' ds = None - return 'success' - ############################################################################### # Test warping a full EPSG:4326 extent to EPSG:3785 (#2305) def test_gdalwarp_29(): if test_cli_utilities.get_gdalwarp_path() is None: - return 'skip' + pytest.skip() gdaltest.runexternal(test_cli_utilities.get_gdalwarp_path() + ' -t_srs EPSG:3785 data/w_jpeg.tiff tmp/testgdalwarp29.tif') ds = gdal.Open('tmp/testgdalwarp29.tif') - if ds is None: - return 'fail' + assert ds is not None cs = ds.GetRasterBand(1).Checksum() - if cs != 55149 and cs != 56054: - print(cs) - gdaltest.post_reason('Bad checksum') - return 'fail' + assert cs == 55149 or cs == 56054, 'Bad checksum' gt = ds.GetGeoTransform() expected_gt = [-20037508.342789248, 90054.726863985939, 0.0, 16213801.067583967, 0.0, -90056.750611190684] for i in range(6): - if abs(gt[i] - expected_gt[i]) > 1: - print(gt) - gdaltest.post_reason('Bad gt') - return 'fail' + assert abs(gt[i] - expected_gt[i]) <= 1, 'Bad gt' ds = None - return 'success' - ############################################################################### # Test the effect of the -wo OPTIMIZE_SIZE=TRUE and -wo STREAMABLE_OUTPUT=TRUE options (#3459, #1866) def test_gdalwarp_30(): if test_cli_utilities.get_gdalwarp_path() is None: - return 'skip' + pytest.skip() # First run : no parameter gdaltest.runexternal(test_cli_utilities.get_gdalwarp_path() + " data/w_jpeg.tiff tmp/testgdalwarp30_1.tif -t_srs EPSG:3785 -co COMPRESS=LZW -wm 500000 --config GDAL_CACHEMAX 1 -ts 1000 500 -co TILED=YES") @@ -825,54 +645,34 @@ def test_gdalwarp_30(): file_size3 = os.stat('tmp/testgdalwarp30_3.tif')[stat.ST_SIZE] ds = gdal.Open('tmp/testgdalwarp30_1.tif') - if ds is None: - return 'fail' + assert ds is not None cs = ds.GetRasterBand(1).Checksum() - if cs != 64629 and cs != 1302: - print(cs) - gdaltest.post_reason('Bad checksum on testgdalwarp30_1') - return 'fail' + assert cs == 64629 or cs == 1302, 'Bad checksum on testgdalwarp30_1' ds = None ds = gdal.Open('tmp/testgdalwarp30_2.tif') - if ds is None: - return 'fail' + assert ds is not None cs = ds.GetRasterBand(1).Checksum() - if cs != 64629 and cs != 1302: - print(cs) - gdaltest.post_reason('Bad checksum on testgdalwarp30_2') - return 'fail' + assert cs == 64629 or cs == 1302, 'Bad checksum on testgdalwarp30_2' ds = None ds = gdal.Open('tmp/testgdalwarp30_3.tif') - if ds is None: - return 'fail' + assert ds is not None cs = ds.GetRasterBand(1).Checksum() - if cs != 64629 and cs != 1302: - print(cs) - gdaltest.post_reason('Bad checksum on testgdalwarp30_3') - return 'fail' + assert cs == 64629 or cs == 1302, 'Bad checksum on testgdalwarp30_3' ds = None - if file_size1 <= file_size2: - print(file_size1) - print(file_size2) - gdaltest.post_reason('Size with -wo OPTIMIZE_SIZE=TRUE larger than without !') - return 'fail' + assert file_size1 > file_size2, \ + 'Size with -wo OPTIMIZE_SIZE=TRUE larger than without !' - if file_size1 <= file_size3: - print(file_size1) - print(file_size3) - gdaltest.post_reason('Size with -wo STREAMABLE_OUTPUT=TRUE larger than without !') - return 'fail' - - return 'success' + assert file_size1 > file_size3, \ + 'Size with -wo STREAMABLE_OUTPUT=TRUE larger than without !' ############################################################################### # Test -overwrite (#3759) @@ -880,7 +680,7 @@ def test_gdalwarp_30(): def test_gdalwarp_31(): if test_cli_utilities.get_gdalwarp_path() is None: - return 'skip' + pytest.skip() gdaltest.runexternal(test_cli_utilities.get_gdalwarp_path() + " ../gcore/data/byte.tif tmp/testgdalwarp31.tif") @@ -900,13 +700,7 @@ def test_gdalwarp_31(): cs3 = ds.GetRasterBand(1).Checksum() ds = None - if cs1 != 4672 or cs2 != 4672 or cs3 != 4727 or err == '' or err2 != '': - print(cs1, cs2, cs3) - print(err) - print(err2) - return 'fail' - - return 'success' + assert cs1 == 4672 and cs2 == 4672 and cs3 == 4727 and err != '' and err2 == '' ############################################################################### # Test -tap @@ -914,57 +708,47 @@ def test_gdalwarp_31(): def test_gdalwarp_32(): if test_cli_utilities.get_gdalwarp_path() is None: - return 'skip' + pytest.skip() (_, err) = gdaltest.runexternal_out_and_err(test_cli_utilities.get_gdalwarp_path() + ' -tap ../gcore/data/byte.tif tmp/testgdalwarp32.tif', check_memleak=False) - if err.find('-tap option cannot be used without using -tr') == -1: - gdaltest.post_reason('expected error') - return 'fail' + assert err.find('-tap option cannot be used without using -tr') != -1, \ + 'expected error' gdaltest.runexternal(test_cli_utilities.get_gdalwarp_path() + ' -tr 100 50 -tap ../gcore/data/byte.tif tmp/testgdalwarp32.tif') ds = gdal.Open('tmp/testgdalwarp32.tif') - if ds is None: - return 'fail' + assert ds is not None expected_gt = (440700.0, 100.0, 0.0, 3751350.0, 0.0, -50.0) got_gt = ds.GetGeoTransform() - if not gdaltest.geotransform_equals(expected_gt, got_gt, 1e-9): - gdaltest.post_reason('Bad geotransform') - print(got_gt) - return 'fail' + assert gdaltest.geotransform_equals(expected_gt, got_gt, 1e-9), 'Bad geotransform' - if ds.RasterXSize != 13 or ds.RasterYSize != 25: - gdaltest.post_reason('Wrong raster dimensions : %d x %d' % (ds.RasterXSize, ds.RasterYSize)) - return 'fail' + assert ds.RasterXSize == 13 and ds.RasterYSize == 25, \ + ('Wrong raster dimensions : %d x %d' % (ds.RasterXSize, ds.RasterYSize)) ds = None - return 'success' - ############################################################################### # Test warping a JPEG compressed image with a mask into a RGBA image def test_gdalwarp_33(): if test_cli_utilities.get_gdalwarp_path() is None: - return 'skip' + pytest.skip() if test_cli_utilities.get_gdal_translate_path() is None: - return 'skip' + pytest.skip() gdaltest.runexternal(test_cli_utilities.get_gdalwarp_path() + ' -dstalpha ../gcore/data/ycbcr_with_mask.tif tmp/testgdalwarp33.tif') src_ds = gdal.Open('../gcore/data/ycbcr_with_mask.tif') ds = gdal.Open('tmp/testgdalwarp33.tif') - if ds is None: - return 'fail' + assert ds is not None # There are expected diffs because of the artifacts due to JPEG compression in 8x8 blocks # that are partially masked. gdalwarp will remove those artifacts max_diff = gdaltest.compare_ds(src_ds, ds) - if max_diff > 40: - return 'fail' + assert max_diff <= 40 src_ds = None @@ -978,13 +762,7 @@ def test_gdalwarp_33(): ds = None - if cs != expected_cs: - gdaltest.post_reason('did not get expected checksum on alpha band') - print(cs) - print(expected_cs) - return 'fail' - - return 'success' + assert cs == expected_cs, 'did not get expected checksum on alpha band' ############################################################################### # Test warping multiple sources @@ -992,9 +770,9 @@ def test_gdalwarp_33(): def test_gdalwarp_34(): if test_cli_utilities.get_gdalwarp_path() is None: - return 'skip' + pytest.skip() if test_cli_utilities.get_gdal_translate_path() is None: - return 'skip' + pytest.skip() try: os.remove('tmp/testgdalwarp34.tif') @@ -1016,150 +794,113 @@ def test_gdalwarp_34(): os.remove('tmp/testgdalwarp34.tif') - if xsize != 20 or ysize != 20: - gdaltest.post_reason('bad dimensions') - print(xsize) - print(ysize) - return 'fail' + assert xsize == 20 and ysize == 20, 'bad dimensions' - if cs != 4672: - gdaltest.post_reason('bad checksum') - print(cs) - return 'fail' + assert cs == 4672, 'bad checksum' expected_gt = (440720.0, 60.0, 0.0, 3751320.0, 0.0, -60.0) for i in range(6): - if abs(gt[i] - expected_gt[i]) > 1e-5: - gdaltest.post_reason('bad gt') - print(gt) - return 'fail' - - return 'success' + assert abs(gt[i] - expected_gt[i]) <= 1e-5, 'bad gt' + ############################################################################### # Test -ts and -te optimization (doesn't need calling GDALSuggestedWarpOutput2, #4804) def test_gdalwarp_35(): if test_cli_utilities.get_gdalwarp_path() is None: - return 'skip' + pytest.skip() gdaltest.runexternal(test_cli_utilities.get_gdalwarp_path() + ' -ts 20 20 -te 440720.000 3750120.000 441920.000 3751320.000 ../gcore/data/byte.tif tmp/testgdalwarp35.tif') ds = gdal.Open('tmp/testgdalwarp35.tif') - if ds is None: - return 'fail' + assert ds is not None - if not gdaltest.geotransform_equals(gdal.Open('../gcore/data/byte.tif').GetGeoTransform(), ds.GetGeoTransform(), 1e-9): - gdaltest.post_reason('Bad geotransform') - return 'fail' + assert gdaltest.geotransform_equals(gdal.Open('../gcore/data/byte.tif').GetGeoTransform(), ds.GetGeoTransform(), 1e-9), \ + 'Bad geotransform' ds = None - return 'success' - ############################################################################### # Test -tr and -te optimization (doesn't need calling GDALSuggestedWarpOutput2, #4804) def test_gdalwarp_36(): if test_cli_utilities.get_gdalwarp_path() is None: - return 'skip' + pytest.skip() gdaltest.runexternal(test_cli_utilities.get_gdalwarp_path() + ' -tr 60 60 -te 440720.000 3750120.000 441920.000 3751320.000 ../gcore/data/byte.tif tmp/testgdalwarp36.tif') ds = gdal.Open('tmp/testgdalwarp36.tif') - if ds is None: - return 'fail' + assert ds is not None - if not gdaltest.geotransform_equals(gdal.Open('../gcore/data/byte.tif').GetGeoTransform(), ds.GetGeoTransform(), 1e-9): - gdaltest.post_reason('Bad geotransform') - return 'fail' + assert gdaltest.geotransform_equals(gdal.Open('../gcore/data/byte.tif').GetGeoTransform(), ds.GetGeoTransform(), 1e-9), \ + 'Bad geotransform' ds = None - return 'success' - ############################################################################### # Test metadata copying - stats should not be copied (#5319) def test_gdalwarp_37(): if test_cli_utilities.get_gdalwarp_path() is None: - return 'skip' + pytest.skip() gdaltest.runexternal(test_cli_utilities.get_gdalwarp_path() + ' -tr 60 60 ./data/utmsmall.tif tmp/testgdalwarp37.tif') ds = gdal.Open('tmp/testgdalwarp37.tif') - if ds is None: - return 'fail' + assert ds is not None md = ds.GetRasterBand(1).GetMetadata() # basic metadata test - if 'testkey' not in md or md['testkey'] != 'test value': - gdaltest.post_reason('Output file metadata is wrong : { %s }' % md) - return 'fail' + assert 'testkey' in md and md['testkey'] == 'test value', \ + ('Output file metadata is wrong : { %s }' % md) # make sure stats not copied - if 'STATISTICS_MEAN' in md: - gdaltest.post_reason('Output file contains statistics metadata') - return 'fail' + assert 'STATISTICS_MEAN' not in md, 'Output file contains statistics metadata' - if ds.GetRasterBand(1).GetMinimum() is not None: - gdaltest.post_reason('Output file has statistics') - return 'fail' + assert ds.GetRasterBand(1).GetMinimum() is None, 'Output file has statistics' ds = None - return 'success' - ############################################################################### # Test implicit nodata setting (#5675) def test_gdalwarp_38(): if test_cli_utilities.get_gdalwarp_path() is None: - return 'skip' + pytest.skip() gdaltest.runexternal(test_cli_utilities.get_gdalwarp_path() + ' data/withnodata.asc tmp/testgdalwarp38.tif') ds = gdal.Open('tmp/testgdalwarp38.tif') - if ds.GetRasterBand(1).Checksum() != 65531: - gdaltest.post_reason('failure') - return 'fail' - if ds.GetRasterBand(1).GetNoDataValue() != -999: - gdaltest.post_reason('failure') - return 'fail' + assert ds.GetRasterBand(1).Checksum() == 65531 + assert ds.GetRasterBand(1).GetNoDataValue() == -999 ds = None - return 'success' - ############################################################################### # Test -oo def test_gdalwarp_39(): if test_cli_utilities.get_gdalwarp_path() is None: - return 'skip' + pytest.skip() gdaltest.runexternal(test_cli_utilities.get_gdalwarp_path() + ' ../gdrivers/data/float64.asc tmp/test_gdalwarp_39.tif -oo DATATYPE=Float64 -overwrite') ds = gdal.Open('tmp/test_gdalwarp_39.tif') - if ds.GetRasterBand(1).DataType != gdal.GDT_Float64: - gdaltest.post_reason('failure') - return 'fail' + assert ds.GetRasterBand(1).DataType == gdal.GDT_Float64 ds = None - return 'success' - ############################################################################### # Test -ovr def test_gdalwarp_40(): if test_cli_utilities.get_gdalwarp_path() is None: - return 'skip' + pytest.skip() src_ds = gdal.Open('../gcore/data/byte.tif') out_ds = gdal.GetDriverByName('GTiff').CreateCopy('tmp/test_gdalwarp_40_src.tif', src_ds) @@ -1175,18 +916,14 @@ def test_gdalwarp_40(): gdaltest.runexternal(test_cli_utilities.get_gdalwarp_path() + ' tmp/test_gdalwarp_40_src.tif tmp/test_gdalwarp_40.tif -overwrite') ds = gdal.Open('tmp/test_gdalwarp_40.tif') - if ds.GetRasterBand(1).Checksum() != cs_main: - gdaltest.post_reason('failure') - return 'fail' + assert ds.GetRasterBand(1).Checksum() == cs_main ds = None # Test -ovr AUTO. Should select main resolution gdaltest.runexternal(test_cli_utilities.get_gdalwarp_path() + ' tmp/test_gdalwarp_40_src.tif tmp/test_gdalwarp_40.tif -overwrite -ovr AUTO') ds = gdal.Open('tmp/test_gdalwarp_40.tif') - if ds.GetRasterBand(1).Checksum() != cs_main: - gdaltest.post_reason('failure') - return 'fail' + assert ds.GetRasterBand(1).Checksum() == cs_main ds = None gdaltest.runexternal(test_cli_utilities.get_gdalwarp_path() + ' ../gcore/data/byte.tif tmp/test_gdalwarp_40.tif -overwrite -ts 5 5') @@ -1198,9 +935,7 @@ def test_gdalwarp_40(): gdaltest.runexternal(test_cli_utilities.get_gdalwarp_path() + ' tmp/test_gdalwarp_40_src.tif tmp/test_gdalwarp_40.tif -overwrite -ovr NONE -ts 5 5') ds = gdal.Open('tmp/test_gdalwarp_40.tif') - if ds.GetRasterBand(1).Checksum() != expected_cs: - gdaltest.post_reason('failure') - return 'fail' + assert ds.GetRasterBand(1).Checksum() == expected_cs ds = None gdaltest.runexternal(test_cli_utilities.get_gdalwarp_path() + ' ../gcore/data/byte.tif tmp/test_gdalwarp_40.tif -overwrite -ts 15 15') @@ -1212,27 +947,21 @@ def test_gdalwarp_40(): gdaltest.runexternal(test_cli_utilities.get_gdalwarp_path() + ' tmp/test_gdalwarp_40_src.tif tmp/test_gdalwarp_40.tif -overwrite -ts 15 15') ds = gdal.Open('tmp/test_gdalwarp_40.tif') - if ds.GetRasterBand(1).Checksum() != expected_cs: - gdaltest.post_reason('failure') - return 'fail' + assert ds.GetRasterBand(1).Checksum() == expected_cs ds = None # Should select overview 0 gdaltest.runexternal(test_cli_utilities.get_gdalwarp_path() + ' tmp/test_gdalwarp_40_src.tif tmp/test_gdalwarp_40.tif -overwrite -ts 10 10') ds = gdal.Open('tmp/test_gdalwarp_40.tif') - if ds.GetRasterBand(1).Checksum() != cs_ov0: - gdaltest.post_reason('failure') - return 'fail' + assert ds.GetRasterBand(1).Checksum() == cs_ov0 ds = None # Should select overview 0 through VRT gdaltest.runexternal(test_cli_utilities.get_gdalwarp_path() + ' tmp/test_gdalwarp_40_src.tif tmp/test_gdalwarp_40.vrt -overwrite -ts 10 10 -of VRT') ds = gdal.Open('tmp/test_gdalwarp_40.vrt') - if ds.GetRasterBand(1).Checksum() != cs_ov0: - gdaltest.post_reason('failure') - return 'fail' + assert ds.GetRasterBand(1).Checksum() == cs_ov0 ds = None gdaltest.runexternal(test_cli_utilities.get_gdalwarp_path() + ' tmp/test_gdalwarp_40_src.tif -oo OVERVIEW_LEVEL=0 tmp/test_gdalwarp_40.tif -overwrite -ts 7 7') @@ -1244,9 +973,7 @@ def test_gdalwarp_40(): gdaltest.runexternal(test_cli_utilities.get_gdalwarp_path() + ' tmp/test_gdalwarp_40_src.tif tmp/test_gdalwarp_40.tif -overwrite -ts 7 7') ds = gdal.Open('tmp/test_gdalwarp_40.tif') - if ds.GetRasterBand(1).Checksum() != expected_cs: - gdaltest.post_reason('failure') - return 'fail' + assert ds.GetRasterBand(1).Checksum() == expected_cs ds = None gdaltest.runexternal(test_cli_utilities.get_gdalwarp_path() + ' tmp/test_gdalwarp_40_src.tif -ovr NONE -oo OVERVIEW_LEVEL=0 tmp/test_gdalwarp_40.tif -overwrite -ts 5 5') @@ -1258,18 +985,14 @@ def test_gdalwarp_40(): gdaltest.runexternal(test_cli_utilities.get_gdalwarp_path() + ' tmp/test_gdalwarp_40_src.tif tmp/test_gdalwarp_40.tif -overwrite -ts 5 5 -ovr AUTO-1') ds = gdal.Open('tmp/test_gdalwarp_40.tif') - if ds.GetRasterBand(1).Checksum() != expected_cs: - gdaltest.post_reason('failure') - return 'fail' + assert ds.GetRasterBand(1).Checksum() == expected_cs ds = None # Should select overview 1 gdaltest.runexternal(test_cli_utilities.get_gdalwarp_path() + ' tmp/test_gdalwarp_40_src.tif tmp/test_gdalwarp_40.tif -overwrite -ts 5 5') ds = gdal.Open('tmp/test_gdalwarp_40.tif') - if ds.GetRasterBand(1).Checksum() != cs_ov1: - gdaltest.post_reason('failure') - return 'fail' + assert ds.GetRasterBand(1).Checksum() == cs_ov1 ds = None gdaltest.runexternal(test_cli_utilities.get_gdalwarp_path() + ' tmp/test_gdalwarp_40_src.tif -oo OVERVIEW_LEVEL=1 tmp/test_gdalwarp_40.tif -overwrite -ts 3 3') @@ -1281,9 +1004,7 @@ def test_gdalwarp_40(): gdaltest.runexternal(test_cli_utilities.get_gdalwarp_path() + ' tmp/test_gdalwarp_40_src.tif tmp/test_gdalwarp_40.tif -overwrite -ts 3 3') ds = gdal.Open('tmp/test_gdalwarp_40.tif') - if ds.GetRasterBand(1).Checksum() != expected_cs: - gdaltest.post_reason('failure') - return 'fail' + assert ds.GetRasterBand(1).Checksum() == expected_cs ds = None gdaltest.runexternal(test_cli_utilities.get_gdalwarp_path() + ' tmp/test_gdalwarp_40_src.tif -oo OVERVIEW_LEVEL=1 tmp/test_gdalwarp_40.tif -overwrite -ts 20 20') @@ -1295,20 +1016,16 @@ def test_gdalwarp_40(): gdaltest.runexternal(test_cli_utilities.get_gdalwarp_path() + ' tmp/test_gdalwarp_40_src.tif tmp/test_gdalwarp_40.tif -overwrite -ovr 5') ds = gdal.Open('tmp/test_gdalwarp_40.tif') - if ds.GetRasterBand(1).Checksum() != expected_cs: - gdaltest.post_reason('failure') - return 'fail' + assert ds.GetRasterBand(1).Checksum() == expected_cs ds = None - return 'success' - ############################################################################### # Test source fill ratio heuristics (#3120) def test_gdalwarp_41(): if test_cli_utilities.get_gdalwarp_path() is None: - return 'skip' + pytest.skip() src_ds = gdal.GetDriverByName('GTiff').Create('tmp/test_gdalwarp_41_src.tif', 666, 666) src_ds.SetGeoTransform([-3333500, 10010.510510510510358, 0, 3333500.000000000000000, 0, -10010.510510510510358]) @@ -1336,33 +1053,25 @@ def test_gdalwarp_41(): gdaltest.runexternal(test_cli_utilities.get_gdalwarp_path() + ' tmp/test_gdalwarp_41_src.tif tmp/test_gdalwarp_41.tif -overwrite -t_srs EPSG:4326 -te -180 -90 180 90 -wo INIT_DEST=127 -wo SKIP_NOSOURCE=YES') ds = gdal.Open('tmp/test_gdalwarp_41.tif') - if ds.GetRasterBand(1).Checksum() != 25945: - gdaltest.post_reason('failure') - print(ds.GetRasterBand(1).Checksum()) - return 'fail' + assert ds.GetRasterBand(1).Checksum() == 25945 ds = None # Check when source fill ratio heuristics is OFF gdaltest.runexternal(test_cli_utilities.get_gdalwarp_path() + ' tmp/test_gdalwarp_41_src.tif tmp/test_gdalwarp_41.tif -overwrite -t_srs EPSG:4326 -te -180 -90 180 90 -wo INIT_DEST=127 -wo SKIP_NOSOURCE=YES -wo SRC_FILL_RATIO_HEURISTICS=NO') ds = gdal.Open('tmp/test_gdalwarp_41.tif') - if ds.GetRasterBand(1).Checksum() != 65068: - gdaltest.post_reason('failure') - print(ds.GetRasterBand(1).Checksum()) - return 'fail' + assert ds.GetRasterBand(1).Checksum() == 65068 ds = None - return 'success' - ############################################################################### # Test warping multiple source images, in one step or several, with INIT_DEST/nodata (#5909, #5387) def test_gdalwarp_42(): if test_cli_utilities.get_gdalwarp_path() is None: - return 'skip' + pytest.skip() if test_cli_utilities.get_gdal_translate_path() is None: - return 'skip' + pytest.skip() gdaltest.runexternal(test_cli_utilities.get_gdal_translate_path() + ' ../gdrivers/data/small_world.tif tmp/small_world_left.tif -srcwin 0 0 200 200 -a_nodata 255') gdaltest.runexternal(test_cli_utilities.get_gdal_translate_path() + ' ../gdrivers/data/small_world.tif tmp/small_world_right.tif -srcwin 200 0 200 200 -a_nodata 255') @@ -1373,10 +1082,7 @@ def test_gdalwarp_42(): ds = gdal.Open('tmp/test_gdalwarp_42.tif') got_cs = [ds.GetRasterBand(i + 1).Checksum() for i in range(4)] expected_cs = [25382, 27573, 35297, 59540] - if got_cs != expected_cs: - gdaltest.post_reason('failure') - print(got_cs) - return 'fail' + assert got_cs == expected_cs ds = None # In one step @@ -1385,10 +1091,7 @@ def test_gdalwarp_42(): ds = gdal.Open('tmp/test_gdalwarp_42.tif') got_cs = [ds.GetRasterBand(i + 1).Checksum() for i in range(4)] expected_cs = [25382, 27573, 35297, 59540] - if got_cs != expected_cs: - gdaltest.post_reason('failure') - print(got_cs) - return 'fail' + assert got_cs == expected_cs ds = None # In one step with -wo INIT_DEST=255,255,255,0 @@ -1397,10 +1100,7 @@ def test_gdalwarp_42(): ds = gdal.Open('tmp/test_gdalwarp_42.tif') got_cs = [ds.GetRasterBand(i + 1).Checksum() for i in range(4)] expected_cs = [30111, 32302, 40026, 59540] - if got_cs != expected_cs: - gdaltest.post_reason('failure') - print(got_cs) - return 'fail' + assert got_cs == expected_cs ds = None # In one step with -wo INIT_DEST=0,0,0,0 @@ -1410,43 +1110,29 @@ def test_gdalwarp_42(): ds = gdal.Open('tmp/test_gdalwarp_42.tif') got_cs = [ds.GetRasterBand(i + 1).Checksum() for i in range(4)] expected_cs = [25382, 27573, 35297, 59540] - if got_cs != expected_cs: - gdaltest.post_reason('failure') - print(got_cs) - return 'fail' + assert got_cs == expected_cs ds = None - return 'success' - ############################################################################### # Test that NODATA_VALUES is honoured, but not transferred when adding an alpha channel. def test_gdalwarp_43(): if test_cli_utilities.get_gdalwarp_path() is None: - return 'skip' + pytest.skip() if test_cli_utilities.get_gdal_translate_path() is None: - return 'skip' + pytest.skip() gdaltest.runexternal(test_cli_utilities.get_gdal_translate_path() + ' ../gdrivers/data/small_world.tif tmp/small_world.tif -mo "FOO=BAR" -mo "NODATA_VALUES=62 93 23"') gdaltest.runexternal(test_cli_utilities.get_gdalwarp_path() + ' tmp/small_world.tif tmp/test_gdalwarp_43.tif -overwrite -dstalpha') ds = gdal.Open('tmp/test_gdalwarp_43.tif') - if ds.GetMetadataItem('NODATA_VALUES') is not None: - gdaltest.post_reason('failure') - return 'fail' - if ds.GetMetadataItem('FOO') != 'BAR': - gdaltest.post_reason('failure') - return 'fail' + assert ds.GetMetadataItem('NODATA_VALUES') is None + assert ds.GetMetadataItem('FOO') == 'BAR' got_cs = [ds.GetRasterBand(i + 1).Checksum() for i in range(4)] expected_cs = [30106, 32285, 40022, 64261] - if got_cs != expected_cs: - gdaltest.post_reason('failure') - print(got_cs) - return 'fail' - - return 'success' + assert got_cs == expected_cs ############################################################################### # Test effect of -wo SRC_COORD_PRECISION @@ -1454,7 +1140,7 @@ def test_gdalwarp_43(): def test_gdalwarp_44(): if test_cli_utilities.get_gdalwarp_path() is None: - return 'skip' + pytest.skip() # Without -wo SRC_COORD_PRECISION gdaltest.runexternal(test_cli_utilities.get_gdalwarp_path() + ' -q ../gcore/data/byte.tif tmp/test_gdalwarp_44.tif -wm 10 -overwrite -ts 500 500 -r cubic -ot float32 -t_srs EPSG:4326') @@ -1481,11 +1167,7 @@ def test_gdalwarp_44(): cs4 = ds.GetRasterBand(1).Checksum() ds = None - if cs3 != cs4: - gdaltest.post_reason('fail') - return 'fail' - - return 'success' + assert cs3 == cs4 ############################################################################### # Test -te_srs @@ -1493,50 +1175,38 @@ def test_gdalwarp_44(): def test_gdalwarp_45(): if test_cli_utilities.get_gdalwarp_path() is None: - return 'skip' + pytest.skip() gdaltest.runexternal(test_cli_utilities.get_gdalwarp_path() + ' -te_srs EPSG:4267 -te -117.641087629972 33.8915301685897 -117.628190189534 33.9024195619201 ../gcore/data/byte.tif tmp/test_gdalwarp_45.tif -overwrite') ds = gdal.Open('tmp/test_gdalwarp_45.tif') - if ds.GetRasterBand(1).Checksum() != 4672: - gdaltest.post_reason('fail') - print(ds.GetRasterBand(1).Checksum()) - return 'fail' + assert ds.GetRasterBand(1).Checksum() == 4672 ds = None gdaltest.runexternal(test_cli_utilities.get_gdalwarp_path() + ' -te_srs EPSG:4267 -te -117.641087629972 33.8915301685897 -117.628190189534 33.9024195619201 -t_srs EPSG:32611 ../gcore/data/byte.tif tmp/test_gdalwarp_45.tif -overwrite') ds = gdal.Open('tmp/test_gdalwarp_45.tif') - if ds.GetRasterBand(1).Checksum() != 4672: - gdaltest.post_reason('fail') - print(ds.GetRasterBand(1).Checksum()) - return 'fail' + assert ds.GetRasterBand(1).Checksum() == 4672 ds = None - return 'success' - ############################################################################### # Test -crop_to_cutline def test_gdalwarp_46(): if test_cli_utilities.get_gdalwarp_path() is None: - return 'skip' + pytest.skip() if test_cli_utilities.get_ogr2ogr_path() is None: - return 'skip' + pytest.skip() gdaltest.runexternal(test_cli_utilities.get_gdalwarp_path() + ' ../gcore/data/utmsmall.tif tmp/test_gdalwarp_46.tif -cutline data/cutline.vrt -crop_to_cutline -overwrite') ds = gdal.Open('tmp/test_gdalwarp_46.tif') - if ds is None: - return 'fail' + assert ds is not None - if ds.GetRasterBand(1).Checksum() != 18837: - print(ds.GetRasterBand(1).Checksum()) - gdaltest.post_reason('Bad checksum') - return 'fail' + assert ds.GetRasterBand(1).Checksum() == 18837, 'Bad checksum' ds = None @@ -1544,13 +1214,9 @@ def test_gdalwarp_46(): gdaltest.runexternal(test_cli_utilities.get_gdalwarp_path() + ' ../gcore/data/utmsmall.tif tmp/test_gdalwarp_46.tif -cutline data/cutline.vrt -crop_to_cutline -overwrite -s_srs EPSG:26711 -t_srs EPSG:26711') ds = gdal.Open('tmp/test_gdalwarp_46.tif') - if ds is None: - return 'fail' + assert ds is not None - if ds.GetRasterBand(1).Checksum() != 18837: - print(ds.GetRasterBand(1).Checksum()) - gdaltest.post_reason('Bad checksum') - return 'fail' + assert ds.GetRasterBand(1).Checksum() == 18837, 'Bad checksum' ds = None @@ -1559,18 +1225,12 @@ def test_gdalwarp_46(): gdaltest.runexternal(test_cli_utilities.get_gdalwarp_path() + ' ../gcore/data/utmsmall.tif tmp/test_gdalwarp_46.tif -cutline tmp/cutline_4326.shp -crop_to_cutline -overwrite -t_srs EPSG:32711') ds = gdal.Open('tmp/test_gdalwarp_46.tif') - if ds is None: - return 'fail' + assert ds is not None - if ds.GetRasterBand(1).Checksum() != 19582: - print(ds.GetRasterBand(1).Checksum()) - gdaltest.post_reason('Bad checksum') - return 'fail' + assert ds.GetRasterBand(1).Checksum() == 19582, 'Bad checksum' ds = None - return 'success' - ############################################################################### # Cleanup @@ -1579,7 +1239,7 @@ def test_gdalwarp_cleanup(): # We don't clean up when run in debug mode. if gdal.GetConfigOption('CPL_DEBUG', 'OFF') == 'ON': - return 'success' + return for i in range(37): try: @@ -1675,70 +1335,3 @@ def test_gdalwarp_cleanup(): os.remove('tmp/cutline_4326.prj') except OSError: pass - - return 'success' - - -gdaltest_list = [ - test_gdalwarp_cleanup, - test_gdalwarp_1, - test_gdalwarp_2, - test_gdalwarp_3, - test_gdalwarp_4, - test_gdalwarp_5, - test_gdalwarp_6, - test_gdalwarp_7, - test_gdalwarp_8, - test_gdalwarp_9, - test_gdalwarp_10, - test_gdalwarp_11, - test_gdalwarp_12, - test_gdalwarp_13, - test_gdalwarp_14, - test_gdalwarp_15, - test_gdalwarp_16, - test_gdalwarp_17, - test_gdalwarp_18, - test_gdalwarp_19, - test_gdalwarp_20, - test_gdalwarp_21, - test_gdalwarp_22, - test_gdalwarp_23, - test_gdalwarp_24, - test_gdalwarp_25, - test_gdalwarp_26, - test_gdalwarp_27, - test_gdalwarp_28, - test_gdalwarp_29, - test_gdalwarp_30, - test_gdalwarp_31, - test_gdalwarp_32, - test_gdalwarp_33, - test_gdalwarp_34, - test_gdalwarp_35, - test_gdalwarp_36, - test_gdalwarp_37, - test_gdalwarp_38, - test_gdalwarp_39, - test_gdalwarp_40, - test_gdalwarp_41, - test_gdalwarp_42, - test_gdalwarp_43, - test_gdalwarp_44, - test_gdalwarp_45, - test_gdalwarp_46, - test_gdalwarp_cleanup -] - -disabled_gdaltest_list = [ - test_gdalwarp_cleanup, - test_gdalwarp_46, - test_gdalwarp_cleanup] - -if __name__ == '__main__': - - gdaltest.setup_run('test_gdalwarp') - - gdaltest.run_tests(gdaltest_list) - - sys.exit(gdaltest.summarize()) diff --git a/autotest/utilities/test_gdalwarp_lib.py b/autotest/utilities/test_gdalwarp_lib.py index c69347c7f280..e537b0147b0e 100755 --- a/autotest/utilities/test_gdalwarp_lib.py +++ b/autotest/utilities/test_gdalwarp_lib.py @@ -31,14 +31,13 @@ ############################################################################### import struct -import sys import os -sys.path.append('../pymod') from osgeo import gdal, ogr, osr import gdaltest import ogrtest +import pytest ############################################################################### # Simple test @@ -49,14 +48,10 @@ def test_gdalwarp_lib_1(): ds1 = gdal.Open('../gcore/data/byte.tif') dstDS = gdal.Warp('tmp/testgdalwarp1.tif', ds1) - if dstDS.GetRasterBand(1).Checksum() != 4672: - gdaltest.post_reason('Bad checksum') - return 'fail' + assert dstDS.GetRasterBand(1).Checksum() == 4672, 'Bad checksum' dstDS = None - return 'success' - ############################################################################### # Test -of option @@ -66,14 +61,10 @@ def test_gdalwarp_lib_2(): ds1 = gdal.Open('../gcore/data/byte.tif') dstDS = gdal.Warp('tmp/testgdalwarp2.tif'.encode('ascii').decode('ascii'), [ds1], format='GTiff') - if dstDS.GetRasterBand(1).Checksum() != 4672: - gdaltest.post_reason('Bad checksum') - return 'fail' + assert dstDS.GetRasterBand(1).Checksum() == 4672, 'Bad checksum' dstDS = None - return 'success' - ############################################################################### # Test -ot option @@ -83,18 +74,12 @@ def test_gdalwarp_lib_3(): ds1 = gdal.Open('../gcore/data/byte.tif') dstDS = gdal.Warp('', ds1, format='MEM', outputType=gdal.GDT_Int16) - if dstDS.GetRasterBand(1).DataType != gdal.GDT_Int16: - gdaltest.post_reason('Bad data type') - return 'fail' + assert dstDS.GetRasterBand(1).DataType == gdal.GDT_Int16, 'Bad data type' - if dstDS.GetRasterBand(1).Checksum() != 4672: - gdaltest.post_reason('Bad checksum') - return 'fail' + assert dstDS.GetRasterBand(1).Checksum() == 4672, 'Bad checksum' dstDS = None - return 'success' - ############################################################################### # Test -t_srs option @@ -104,14 +89,10 @@ def test_gdalwarp_lib_4(): ds1 = gdal.Open('../gcore/data/byte.tif') dstDS = gdal.Warp('', ds1, format='MEM', dstSRS='EPSG:32611') - if dstDS.GetRasterBand(1).Checksum() != 4672: - gdaltest.post_reason('Bad checksum') - return 'fail' + assert dstDS.GetRasterBand(1).Checksum() == 4672, 'Bad checksum' dstDS = None - return 'success' - ############################################################################### # Test warping from GCPs without any explicit option @@ -123,18 +104,13 @@ def test_gdalwarp_lib_5(): ds1 = gdal.Translate('tmp/testgdalwarp_gcp.tif', ds, outputSRS='EPSG:26711', GCPs=gcpList) dstDS = gdal.Warp('', ds1, format='MEM', tps=True) - if dstDS.GetRasterBand(1).Checksum() != 4672: - gdaltest.post_reason('Bad checksum') - return 'fail' + assert dstDS.GetRasterBand(1).Checksum() == 4672, 'Bad checksum' - if not gdaltest.geotransform_equals(ds.GetGeoTransform(), dstDS.GetGeoTransform(), 1e-9): - gdaltest.post_reason('Bad geotransform') - return 'fail' + assert gdaltest.geotransform_equals(ds.GetGeoTransform(), dstDS.GetGeoTransform(), 1e-9), \ + 'Bad geotransform' dstDS = None - return 'success' - ############################################################################### # Test warping from GCPs with -tps @@ -144,18 +120,13 @@ def test_gdalwarp_lib_6(): ds1 = gdal.Open('tmp/testgdalwarp_gcp.tif') dstDS = gdal.Warp('', ds1, format='MEM', tps=True) - if dstDS.GetRasterBand(1).Checksum() != 4672: - gdaltest.post_reason('Bad checksum') - return 'fail' + assert dstDS.GetRasterBand(1).Checksum() == 4672, 'Bad checksum' - if not gdaltest.geotransform_equals(gdal.Open('../gcore/data/byte.tif').GetGeoTransform(), dstDS.GetGeoTransform(), 1e-9): - gdaltest.post_reason('Bad geotransform') - return 'fail' + assert gdaltest.geotransform_equals(gdal.Open('../gcore/data/byte.tif').GetGeoTransform(), dstDS.GetGeoTransform(), 1e-9), \ + 'Bad geotransform' dstDS = None - return 'success' - ############################################################################### # Test -tr @@ -164,18 +135,14 @@ def test_gdalwarp_lib_7(): ds1 = gdal.Open('tmp/testgdalwarp_gcp.tif') dstDS = gdal.Warp('', [ds1], format='MEM', xRes=120, yRes=120) - if dstDS is None: - return 'fail' + assert dstDS is not None expected_gt = (440720.0, 120.0, 0.0, 3751320.0, 0.0, -120.0) - if not gdaltest.geotransform_equals(expected_gt, dstDS.GetGeoTransform(), 1e-9): - gdaltest.post_reason('Bad geotransform') - return 'fail' + assert gdaltest.geotransform_equals(expected_gt, dstDS.GetGeoTransform(), 1e-9), \ + 'Bad geotransform' dstDS = None - return 'success' - ############################################################################### # Test -ts @@ -184,18 +151,14 @@ def test_gdalwarp_lib_8(): ds1 = gdal.Open('tmp/testgdalwarp_gcp.tif') dstDS = gdal.Warp('', [ds1], format='MEM', width=10, height=10) - if dstDS is None: - return 'fail' + assert dstDS is not None expected_gt = (440720.0, 120.0, 0.0, 3751320.0, 0.0, -120.0) - if not gdaltest.geotransform_equals(expected_gt, dstDS.GetGeoTransform(), 1e-9): - gdaltest.post_reason('Bad geotransform') - return 'fail' + assert gdaltest.geotransform_equals(expected_gt, dstDS.GetGeoTransform(), 1e-9), \ + 'Bad geotransform' dstDS = None - return 'success' - ############################################################################### # Test -te @@ -204,14 +167,11 @@ def test_gdalwarp_lib_9(): ds = gdal.Warp('', '../gcore/data/byte.tif', format='MEM', outputBounds=[440720.000, 3750120.000, 441920.000, 3751320.000]) - if not gdaltest.geotransform_equals(gdal.Open('../gcore/data/byte.tif').GetGeoTransform(), ds.GetGeoTransform(), 1e-9): - gdaltest.post_reason('Bad geotransform') - return 'fail' + assert gdaltest.geotransform_equals(gdal.Open('../gcore/data/byte.tif').GetGeoTransform(), ds.GetGeoTransform(), 1e-9), \ + 'Bad geotransform' ds = None - return 'success' - ############################################################################### # Test -rn @@ -220,15 +180,10 @@ def test_gdalwarp_lib_10(): ds = gdal.Warp('', '../gcore/data/byte.tif', format='MEM', width=40, height=40, resampleAlg=gdal.GRIORA_NearestNeighbour) - if ds.GetRasterBand(1).Checksum() != 18784: - print(ds.GetRasterBand(1).Checksum()) - gdaltest.post_reason('Bad checksum') - return 'fail' + assert ds.GetRasterBand(1).Checksum() == 18784, 'Bad checksum' ds = None - return 'success' - ############################################################################### # Test -rb @@ -243,13 +198,10 @@ def test_gdalwarp_lib_11(): if maxdiff > 1: gdaltest.compare_ds(ds, ref_ds, verbose=1) - gdaltest.post_reason('Image too different from reference') - return 'fail' + pytest.fail('Image too different from reference') ds = None - return 'success' - ############################################################################### # Test -rc @@ -264,13 +216,10 @@ def test_gdalwarp_lib_12(): if maxdiff > 1: gdaltest.compare_ds(ds, ref_ds, verbose=1) - gdaltest.post_reason('Image too different from reference') - return 'fail' + pytest.fail('Image too different from reference') ds = None - return 'success' - ############################################################################### # Test -rcs @@ -285,13 +234,10 @@ def test_gdalwarp_lib_13(): if maxdiff > 1: gdaltest.compare_ds(ds, ref_ds, verbose=1) - gdaltest.post_reason('Image too different from reference') - return 'fail' + pytest.fail('Image too different from reference') ds = None - return 'success' - ############################################################################### # Test -r lanczos @@ -306,13 +252,10 @@ def test_gdalwarp_lib_14(): if maxdiff > 1: gdaltest.compare_ds(ds, ref_ds, verbose=1) - gdaltest.post_reason('Image too different from reference') - return 'fail' + pytest.fail('Image too different from reference') ds = None - return 'success' - ############################################################################### # Test -dstnodata @@ -321,20 +264,12 @@ def test_gdalwarp_lib_15(): ds = gdal.Warp('', 'tmp/testgdalwarp_gcp.tif', format='MEM', dstSRS='EPSG:32610', dstNodata=1) - if ds.GetRasterBand(1).GetNoDataValue() != 1: - print(ds.GetRasterBand(1).GetNoDataValue()) - gdaltest.post_reason('Bad nodata value') - return 'fail' + assert ds.GetRasterBand(1).GetNoDataValue() == 1, 'Bad nodata value' - if ds.GetRasterBand(1).Checksum() != 4523: - print(ds.GetRasterBand(1).Checksum()) - gdaltest.post_reason('Bad checksum') - return 'fail' + assert ds.GetRasterBand(1).Checksum() == 4523, 'Bad checksum' ds = None - return 'success' - ############################################################################### # Test -of VRT which is a special case @@ -342,14 +277,9 @@ def test_gdalwarp_lib_15(): def test_gdalwarp_lib_16(): ds = gdal.Warp('/vsimem/test_gdalwarp_lib_16.vrt', 'tmp/testgdalwarp_gcp.tif', format='VRT') - if ds is None: - gdaltest.post_reason('fail') - return 'fail' + assert ds is not None - if ds.GetRasterBand(1).Checksum() != 4672: - print(ds.GetRasterBand(1).Checksum()) - gdaltest.post_reason('Bad checksum') - return 'fail' + assert ds.GetRasterBand(1).Checksum() == 4672, 'Bad checksum' ds = None @@ -358,11 +288,7 @@ def test_gdalwarp_lib_16(): # Cannot write file with gdaltest.error_handler(): ds = gdal.Warp('/i_dont/exist/test_gdalwarp_lib_16.vrt', 'tmp/testgdalwarp_gcp.tif', format='VRT') - if ds is not None: - gdaltest.post_reason('fail') - return 'fail' - - return 'success' + assert ds is None ############################################################################### # Test -dstalpha @@ -371,17 +297,12 @@ def test_gdalwarp_lib_16(): def test_gdalwarp_lib_17(): ds = gdal.Warp('', '../gcore/data/rgbsmall.tif', format='MEM', dstAlpha=True) - if ds is None: - return 'fail' + assert ds is not None - if ds.GetRasterBand(4) is None: - gdaltest.post_reason('No alpha band generated') - return 'fail' + assert ds.GetRasterBand(4) is not None, 'No alpha band generated' ds = None - return 'success' - ############################################################################### # Test -et 0 which is a special case @@ -389,18 +310,12 @@ def test_gdalwarp_lib_17(): def test_gdalwarp_lib_19(): ds = gdal.Warp('', 'tmp/testgdalwarp_gcp.tif', format='MEM', errorThreshold=0) - if ds is None: - return 'fail' + assert ds is not None - if ds.GetRasterBand(1).Checksum() != 4672: - print(ds.GetRasterBand(1).Checksum()) - gdaltest.post_reason('Bad checksum') - return 'fail' + assert ds.GetRasterBand(1).Checksum() == 4672, 'Bad checksum' ds = None - return 'success' - ############################################################################### # Test cutline from OGR datasource. @@ -408,18 +323,12 @@ def test_gdalwarp_lib_19(): def test_gdalwarp_lib_21(): ds = gdal.Warp('', '../gcore/data/utmsmall.tif', format='MEM', cutlineDSName='data/cutline.vrt', cutlineLayer='cutline') - if ds is None: - return 'fail' + assert ds is not None - if ds.GetRasterBand(1).Checksum() != 19139: - print(ds.GetRasterBand(1).Checksum()) - gdaltest.post_reason('Bad checksum') - return 'fail' + assert ds.GetRasterBand(1).Checksum() == 19139, 'Bad checksum' ds = None - return 'success' - ############################################################################### # Test cutline with ALL_TOUCHED enabled. @@ -427,18 +336,12 @@ def test_gdalwarp_lib_21(): def test_gdalwarp_lib_23(): ds = gdal.Warp('', '../gcore/data/utmsmall.tif', format='MEM', warpOptions=['CUTLINE_ALL_TOUCHED=TRUE'], cutlineDSName='data/cutline.vrt', cutlineLayer='cutline') - if ds is None: - return 'fail' + assert ds is not None - if ds.GetRasterBand(1).Checksum() != 20123: - print(ds.GetRasterBand(1).Checksum()) - gdaltest.post_reason('Bad checksum') - return 'fail' + assert ds.GetRasterBand(1).Checksum() == 20123, 'Bad checksum' ds = None - return 'success' - ############################################################################### # Test -tap @@ -446,24 +349,17 @@ def test_gdalwarp_lib_23(): def test_gdalwarp_lib_32(): ds = gdal.Warp('', '../gcore/data/byte.tif', format='MEM', targetAlignedPixels=True, xRes=100, yRes=50) - if ds is None: - return 'fail' + assert ds is not None expected_gt = (440700.0, 100.0, 0.0, 3751350.0, 0.0, -50.0) got_gt = ds.GetGeoTransform() - if not gdaltest.geotransform_equals(expected_gt, got_gt, 1e-9): - gdaltest.post_reason('Bad geotransform') - print(got_gt) - return 'fail' + assert gdaltest.geotransform_equals(expected_gt, got_gt, 1e-9), 'Bad geotransform' - if ds.RasterXSize != 13 or ds.RasterYSize != 25: - gdaltest.post_reason('Wrong raster dimensions : %d x %d' % (ds.RasterXSize, ds.RasterYSize)) - return 'fail' + assert ds.RasterXSize == 13 and ds.RasterYSize == 25, \ + ('Wrong raster dimensions : %d x %d' % (ds.RasterXSize, ds.RasterYSize)) ds = None - return 'success' - ############################################################################### # Test warping multiple sources @@ -480,26 +376,15 @@ def test_gdalwarp_lib_34(): ysize = ds.RasterYSize ds = None - if xsize != 20 or ysize != 20: - gdaltest.post_reason('bad dimensions') - print(xsize) - print(ysize) - return 'fail' + assert xsize == 20 and ysize == 20, 'bad dimensions' - if cs != 4672: - gdaltest.post_reason('bad checksum') - print(cs) - return 'fail' + assert cs == 4672, 'bad checksum' expected_gt = (440720.0, 60.0, 0.0, 3751320.0, 0.0, -60.0) for i in range(6): - if abs(gt[i] - expected_gt[i]) > 1e-5: - gdaltest.post_reason('bad gt') - print(gt) - return 'fail' - - return 'success' + assert abs(gt[i] - expected_gt[i]) <= 1e-5, 'bad gt' + ############################################################################### # Test -te_srs @@ -507,15 +392,10 @@ def test_gdalwarp_lib_34(): def test_gdalwarp_lib_45(): ds = gdal.Warp('', ['../gcore/data/byte.tif'], format='MEM', outputBounds=[-117.641087629972, 33.8915301685897, -117.628190189534, 33.9024195619201], outputBoundsSRS='EPSG:4267') - if ds.GetRasterBand(1).Checksum() != 4672: - gdaltest.post_reason('fail') - print(ds.GetRasterBand(1).Checksum()) - return 'fail' + assert ds.GetRasterBand(1).Checksum() == 4672 ds = None - return 'success' - ############################################################################### # Test -crop_to_cutline @@ -523,10 +403,7 @@ def test_gdalwarp_lib_45(): def test_gdalwarp_lib_46(): ds = gdal.Warp('', ['../gcore/data/utmsmall.tif'], format='MEM', cutlineDSName='data/cutline.vrt', cropToCutline=True) - if ds.GetRasterBand(1).Checksum() != 18837: - print(ds.GetRasterBand(1).Checksum()) - gdaltest.post_reason('Bad checksum') - return 'fail' + assert ds.GetRasterBand(1).Checksum() == 18837, 'Bad checksum' ds = None @@ -550,14 +427,8 @@ def test_gdalwarp_lib_46(): cropToCutline=True) got_gt = ds.GetGeoTransform() expected_gt = (2.15, 0.05, 0.0, 48.8, 0.0, -0.05) - if max([abs(got_gt[i]-expected_gt[i]) for i in range(6)]) > 1e-8: - gdaltest.post_reason('fail') - print(got_gt) - return 'fail' - if ds.RasterXSize != 13 or ds.RasterYSize != 13: - gdaltest.post_reason('fail') - print(ds.RasterXSize, ds.RasterYSize) - return 'fail' + assert max([abs(got_gt[i]-expected_gt[i]) for i in range(6)]) <= 1e-8 + assert ds.RasterXSize == 13 and ds.RasterYSize == 13 # Same but with CUTLINE_ALL_TOUCHED=YES: the extent should be larger # than the cutline @@ -566,14 +437,8 @@ def test_gdalwarp_lib_46(): warpOptions=['CUTLINE_ALL_TOUCHED=YES']) got_gt = ds.GetGeoTransform() expected_gt = (2.1, 0.05, 0.0, 48.85, 0.0, -0.05) - if max([abs(got_gt[i]-expected_gt[i]) for i in range(6)]) > 1e-8: - gdaltest.post_reason('fail') - print(got_gt) - return 'fail' - if ds.RasterXSize != 15 or ds.RasterYSize != 15: - gdaltest.post_reason('fail') - print(ds.RasterXSize, ds.RasterYSize) - return 'fail' + assert max([abs(got_gt[i]-expected_gt[i]) for i in range(6)]) <= 1e-8 + assert ds.RasterXSize == 15 and ds.RasterYSize == 15 # Test numeric stability when the cutline is exactly on pixel boundaries cutline_ds = ogr.GetDriverByName('GeoJSON').CreateDataSource(cutlineDSName) @@ -590,19 +455,11 @@ def test_gdalwarp_lib_46(): cropToCutline=True, warpOptions=warpOptions) got_gt = ds.GetGeoTransform() expected_gt = (2.15, 0.05, 0.0, 48.85, 0.0, -0.05) - if max([abs(got_gt[i]-expected_gt[i]) for i in range(6)]) > 1e-8: - gdaltest.post_reason('fail') - print(got_gt) - return 'fail' - if ds.RasterXSize != 14 or ds.RasterYSize != 14: - gdaltest.post_reason('fail') - print(ds.RasterXSize, ds.RasterYSize) - return 'fail' + assert max([abs(got_gt[i]-expected_gt[i]) for i in range(6)]) <= 1e-8 + assert ds.RasterXSize == 14 and ds.RasterYSize == 14 gdal.Unlink(cutlineDSName) - return 'success' - ############################################################################### # Test callback @@ -617,21 +474,14 @@ def test_gdalwarp_lib_100(): tab = [0] ds = gdal.Warp('', '../gcore/data/byte.tif', format='MEM', callback=mycallback, callback_data=tab) - if ds is None: - return 'fail' + assert ds is not None - if ds.GetRasterBand(1).Checksum() != 4672: - gdaltest.post_reason('Bad checksum') - return 'fail' + assert ds.GetRasterBand(1).Checksum() == 4672, 'Bad checksum' - if tab[0] != 1.0: - gdaltest.post_reason('Bad percentage') - return 'fail' + assert tab[0] == 1.0, 'Bad percentage' ds = None - return 'success' - ############################################################################### # Test with color table @@ -639,11 +489,7 @@ def test_gdalwarp_lib_100(): def test_gdalwarp_lib_101(): ds = gdal.Warp('', '../gdrivers/data/small_world_pct.tif', format='MEM') - if ds.GetRasterBand(1).GetColorTable() is None: - gdaltest.post_reason('Did not get color table') - return 'fail' - - return 'success' + assert ds.GetRasterBand(1).GetColorTable() is not None, 'Did not get color table' ############################################################################### # Test with a dataset with no bands @@ -654,10 +500,7 @@ def test_gdalwarp_lib_102(): no_band_ds = gdal.GetDriverByName('MEM').Create('no band', 1, 1, 0) with gdaltest.error_handler(): ds = gdal.Warp('', ['../gdrivers/data/small_world_pct.tif', no_band_ds], format='MEM') - if ds is not None: - gdaltest.post_reason('Did not expected dataset') - return 'fail' - return 'success' + assert ds is None, 'Did not expected dataset' ############################################################################### # Test failed transformer @@ -667,10 +510,7 @@ def test_gdalwarp_lib_103(): with gdaltest.error_handler(): ds = gdal.Warp('', ['../gdrivers/data/small_world_pct.tif', '../gcore/data/stefan_full_rgba.tif'], format='MEM') - if ds is not None: - gdaltest.post_reason('Did not expected dataset') - return 'fail' - return 'success' + assert ds is None, 'Did not expected dataset' ############################################################################### # Test no usable source image @@ -680,10 +520,7 @@ def test_gdalwarp_lib_104(): with gdaltest.error_handler(): ds = gdal.Warp('', [], format='MEM') - if ds is not None: - gdaltest.post_reason('Did not expected dataset') - return 'fail' - return 'success' + assert ds is None, 'Did not expected dataset' ############################################################################### # Test failure in GDALSuggestedWarpOutput2 @@ -697,8 +534,7 @@ def test_gdalwarp_lib_105(): with gdaltest.error_handler(): gdal.Warp('', ['../gdrivers/data/small_world_pct.tif', '../gcore/data/byte.tif'], format='MEM', dstSRS='EPSG:32645', width=100, height=100) - return 'success' - + ############################################################################### # Test failure in creation @@ -707,10 +543,7 @@ def test_gdalwarp_lib_106(): with gdaltest.error_handler(): ds = gdal.Warp('/not_existing_dir/not_existing_file', ['../gdrivers/data/small_world_pct.tif', '../gcore/data/byte.tif']) - if ds is not None: - gdaltest.post_reason('Did not expected dataset') - return 'fail' - return 'success' + assert ds is None, 'Did not expected dataset' ############################################################################### # Test forced width only @@ -719,12 +552,7 @@ def test_gdalwarp_lib_106(): def test_gdalwarp_lib_107(): ds = gdal.Warp('', '../gcore/data/byte.tif', format='MEM', width=20) - if ds.GetRasterBand(1).Checksum() != 4672: - print(ds.GetRasterBand(1).Checksum()) - gdaltest.post_reason('Bad checksum') - return 'fail' - - return 'success' + assert ds.GetRasterBand(1).Checksum() == 4672, 'Bad checksum' ############################################################################### # Test forced height only @@ -733,12 +561,7 @@ def test_gdalwarp_lib_107(): def test_gdalwarp_lib_108(): ds = gdal.Warp('', '../gcore/data/byte.tif', format='MEM', height=20) - if ds.GetRasterBand(1).Checksum() != 4672: - print(ds.GetRasterBand(1).Checksum()) - gdaltest.post_reason('Bad checksum') - return 'fail' - - return 'success' + assert ds.GetRasterBand(1).Checksum() == 4672, 'Bad checksum' ############################################################################### # Test wrong cutline name @@ -748,10 +571,7 @@ def test_gdalwarp_lib_109(): with gdaltest.error_handler(): ds = gdal.Warp('', '../gcore/data/byte.tif', format='MEM', cutlineDSName='/does/not/exist') - if ds is not None: - gdaltest.post_reason('Did not expected dataset') - return 'fail' - return 'success' + assert ds is None, 'Did not expected dataset' ############################################################################### # Test wrong cutline layer name @@ -761,10 +581,7 @@ def test_gdalwarp_lib_110(): with gdaltest.error_handler(): ds = gdal.Warp('', '../gcore/data/byte.tif', format='MEM', cutlineDSName='data/cutline.vrt', cutlineLayer='wrong_name') - if ds is not None: - gdaltest.post_reason('Did not expected dataset') - return 'fail' - return 'success' + assert ds is None, 'Did not expected dataset' ############################################################################### # Test cutline SQL @@ -773,18 +590,12 @@ def test_gdalwarp_lib_110(): def test_gdalwarp_lib_111(): ds = gdal.Warp('', '../gcore/data/utmsmall.tif', format='MEM', cutlineDSName='data/cutline.vrt', cutlineSQL='SELECT * FROM cutline', cutlineWhere='1 = 1') - if ds is None: - return 'fail' + assert ds is not None - if ds.GetRasterBand(1).Checksum() != 19139: - print(ds.GetRasterBand(1).Checksum()) - gdaltest.post_reason('Bad checksum') - return 'fail' + assert ds.GetRasterBand(1).Checksum() == 19139, 'Bad checksum' ds = None - return 'success' - ############################################################################### # Test cutline without geometry @@ -799,13 +610,9 @@ def test_gdalwarp_lib_112(): ds = None with gdaltest.error_handler(): ds = gdal.Warp('', '../gcore/data/utmsmall.tif', format='MEM', cutlineDSName='/vsimem/cutline.shp', cutlineSQL='SELECT * FROM cutline') - if ds is not None: - gdaltest.post_reason('Did not expected dataset') - return 'fail' + assert ds is None, 'Did not expected dataset' ogr.GetDriverByName('ESRI Shapefile').DeleteDataSource('/vsimem/cutline.shp') - return 'success' - ############################################################################### # Test cutline with non polygon geometry @@ -821,13 +628,9 @@ def test_gdalwarp_lib_113(): ds = None with gdaltest.error_handler(): ds = gdal.Warp('', '../gcore/data/utmsmall.tif', format='MEM', cutlineDSName='/vsimem/cutline.shp') - if ds is not None: - gdaltest.post_reason('Did not expected dataset') - return 'fail' + assert ds is None, 'Did not expected dataset' ogr.GetDriverByName('ESRI Shapefile').DeleteDataSource('/vsimem/cutline.shp') - return 'success' - ############################################################################### # Test cutline without feature @@ -839,13 +642,9 @@ def test_gdalwarp_lib_114(): ds = None with gdaltest.error_handler(): ds = gdal.Warp('', '../gcore/data/utmsmall.tif', format='MEM', cutlineDSName='/vsimem/cutline.shp') - if ds is not None: - gdaltest.post_reason('Did not expected dataset') - return 'fail' + assert ds is None, 'Did not expected dataset' ogr.GetDriverByName('ESRI Shapefile').DeleteDataSource('/vsimem/cutline.shp') - return 'success' - ############################################################################### # Test source dataset without band @@ -857,11 +656,7 @@ def test_gdalwarp_lib_115(): with gdaltest.error_handler(): ret = gdal.Warp(out_ds, no_band_ds, cutlineDSName='data/cutline.vrt', cutlineLayer='cutline') - if ret != 0: - gdaltest.post_reason('Expected failure') - return 'fail' - - return 'success' + assert ret == 0, 'Expected failure' ############################################################################### # Test failed cropToCutline due to invalid SRC_SRS @@ -871,11 +666,7 @@ def test_gdalwarp_lib_116(): with gdaltest.error_handler(): ds = gdal.Warp('', '../gcore/data/utmsmall.tif', format='MEM', cutlineDSName='data/cutline.vrt', cutlineLayer='cutline', cropToCutline=True, transformerOptions=['SRC_SRS=invalid']) - if ds is not None: - gdaltest.post_reason('Did not expected dataset') - return 'fail' - - return 'success' + assert ds is None, 'Did not expected dataset' ############################################################################### # Test failed cropToCutline due to invalid DST_SRS @@ -885,11 +676,7 @@ def test_gdalwarp_lib_117(): with gdaltest.error_handler(): ds = gdal.Warp('', '../gcore/data/utmsmall.tif', format='MEM', cutlineDSName='data/cutline.vrt', cutlineLayer='cutline', cropToCutline=True, transformerOptions=['DST_SRS=invalid']) - if ds is not None: - gdaltest.post_reason('Did not expected dataset') - return 'fail' - - return 'success' + assert ds is None, 'Did not expected dataset' ############################################################################### # Test failed cropToCutline due to no source raster @@ -899,11 +686,7 @@ def test_gdalwarp_lib_118(): with gdaltest.error_handler(): ds = gdal.Warp('', [], format='MEM', cutlineDSName='data/cutline.vrt', cutlineLayer='cutline', cropToCutline=True) - if ds is not None: - gdaltest.post_reason('Did not expected dataset') - return 'fail' - - return 'success' + assert ds is None, 'Did not expected dataset' ############################################################################### # Test failed cropToCutline due to source raster without projection @@ -914,11 +697,7 @@ def test_gdalwarp_lib_119(): no_proj_ds = gdal.GetDriverByName('MEM').Create('no_proj_ds', 1, 1) with gdaltest.error_handler(): ds = gdal.Warp('', no_proj_ds, format='MEM', cutlineDSName='data/cutline.vrt', cutlineLayer='cutline', cropToCutline=True) - if ds is not None: - gdaltest.post_reason('Did not expected dataset') - return 'fail' - - return 'success' + assert ds is None, 'Did not expected dataset' ############################################################################### # Test failed cropToCutline due to source raster with dummy projection @@ -930,11 +709,7 @@ def test_gdalwarp_lib_120(): dummy_proj_ds.SetProjection('dummy') with gdaltest.error_handler(): ds = gdal.Warp('', dummy_proj_ds, format='MEM', cutlineDSName='data/cutline.vrt', cutlineLayer='cutline', cropToCutline=True) - if ds is not None: - gdaltest.post_reason('Did not expected dataset') - return 'fail' - - return 'success' + assert ds is None, 'Did not expected dataset' ############################################################################### # Test internal wrappers @@ -964,8 +739,7 @@ def test_gdalwarp_lib_121(): with gdaltest.error_handler(): gdal.wrapper_GDALWarpDestDS(gdal.GetDriverByName('MEM').Create('', 1, 1), [], None, gdal.TermProgress) - return 'success' - + ############################################################################### # Test unnamed output VRT @@ -973,10 +747,7 @@ def test_gdalwarp_lib_121(): def test_gdalwarp_lib_122(): ds = gdal.Warp('', '../gcore/data/byte.tif', format='VRT') - if ds.GetRasterBand(1).Checksum() != 4672: - gdaltest.post_reason('Bad checksum') - return 'fail' - return 'success' + assert ds.GetRasterBand(1).Checksum() == 4672, 'Bad checksum' ############################################################################### # Test failure during warping @@ -986,10 +757,7 @@ def test_gdalwarp_lib_123(): with gdaltest.error_handler(): ds = gdal.Warp('', '../gcore/data/byte_truncated.tif', format='MEM') - if ds is not None: - return 'fail' - - return 'success' + assert ds is None ############################################################################### # Test warping to dataset with existing nodata @@ -1011,13 +779,7 @@ def test_gdalwarp_lib_124(): gdal.Warp(out_ds, src_ds) cs = out_ds.GetRasterBand(1).Checksum() - if cs != expected_cs: - gdaltest.post_reason('Bad checksum') - print(cs) - print(expected_cs) - return 'fail' - - return 'success' + assert cs == expected_cs, 'Bad checksum' ############################################################################### # Test that statistics are not propagated @@ -1039,12 +801,9 @@ def test_gdalwarp_lib_125(): out_ds = gdal.Warp('', [src_ds_1, src_ds_2], format='MEM') - if out_ds.GetRasterBand(1).GetMetadataItem('STATISTICS_MINIUM') is not None: - print(i) - return 'fail' - - return 'success' + assert out_ds.GetRasterBand(1).GetMetadataItem('STATISTICS_MINIUM') is None, i + ############################################################################### # Test cutline with invalid geometry @@ -1052,7 +811,7 @@ def test_gdalwarp_lib_125(): def test_gdalwarp_lib_126(): if not ogrtest.have_geos(): - return 'skip' + pytest.skip() ds = ogr.GetDriverByName('ESRI Shapefile').CreateDataSource('/vsimem/cutline.shp') lyr = ds.CreateLayer('cutline') @@ -1063,13 +822,9 @@ def test_gdalwarp_lib_126(): ds = None with gdaltest.error_handler(): ds = gdal.Warp('', '../gcore/data/utmsmall.tif', format='MEM', cutlineDSName='/vsimem/cutline.shp') - if ds is not None: - gdaltest.post_reason('Did not expected dataset') - return 'fail' + assert ds is None, 'Did not expected dataset' ogr.GetDriverByName('ESRI Shapefile').DeleteDataSource('/vsimem/cutline.shp') - return 'success' - ############################################################################### # Test -srcnodata (#6315) @@ -1077,16 +832,8 @@ def test_gdalwarp_lib_126(): def test_gdalwarp_lib_127(): ds = gdal.Warp('', '../gcore/data/byte.tif', format='MEM', srcNodata=1) - if ds.GetRasterBand(1).GetNoDataValue() != 1: - gdaltest.post_reason('bad nodata value') - print(ds.GetRasterBand(1).GetNoDataValue()) - return 'fail' - if ds.GetRasterBand(1).Checksum() != 4672: - gdaltest.post_reason('bad checksum') - print(ds.GetRasterBand(1).Checksum()) - return 'fail' - - return 'success' + assert ds.GetRasterBand(1).GetNoDataValue() == 1, 'bad nodata value' + assert ds.GetRasterBand(1).Checksum() == 4672, 'bad checksum' ############################################################################### # Test automatic densification of cutline (#6375) @@ -1130,15 +877,12 @@ def test_gdalwarp_lib_128(): transformerOptions=['RPC_DEM=data/test_gdalwarp_lib_128_dem.tif']) cs = ds.GetRasterBand(1).Checksum() - if cs != 4248: - gdaltest.post_reason('bad checksum') - print(cs) - return 'fail' + assert cs == 4248, 'bad checksum' # Below steps depend on GEOS if not ogrtest.have_geos(): gdal.Unlink(cutlineDSName) - return 'success' + return gdal.SetConfigOption('GDALWARP_DENSIFY_CUTLINE', 'ONLY_IF_INVALID') ds = gdal.Warp('', mem_ds, format='MEM', cutlineDSName=cutlineDSName, @@ -1149,10 +893,7 @@ def test_gdalwarp_lib_128(): gdal.SetConfigOption('GDALWARP_DENSIFY_CUTLINE', None) cs = ds.GetRasterBand(1).Checksum() - if cs != 4248: - gdaltest.post_reason('bad checksum') - print(cs) - return 'fail' + assert cs == 4248, 'bad checksum' gdal.SetConfigOption('GDALWARP_DENSIFY_CUTLINE', 'NO') with gdaltest.error_handler(): @@ -1162,14 +903,10 @@ def test_gdalwarp_lib_128(): xRes=0.000226555, yRes=0.000226555, transformerOptions=['RPC_DEM=data/test_gdalwarp_lib_128_dem.tif']) gdal.SetConfigOption('GDALWARP_DENSIFY_CUTLINE', None) - if ds is not None: - gdaltest.post_reason('expected none return') - return 'fail' + assert ds is None, 'expected none return' gdal.Unlink(cutlineDSName) - return 'success' - ############################################################################### # Test automatic densification of cutline, but with initial guess leading # to an invalid geometry (#6375) @@ -1177,7 +914,7 @@ def test_gdalwarp_lib_128(): def test_gdalwarp_lib_129(): if not ogrtest.have_geos(): - return 'skip' + pytest.skip() mem_ds = gdal.GetDriverByName('MEM').Create('', 1000, 2000) rpc = ["HEIGHT_OFF=1767", @@ -1215,15 +952,10 @@ def test_gdalwarp_lib_129(): transformerOptions=['RPC_DEM=data/test_gdalwarp_lib_129_dem.vrt']) cs = ds.GetRasterBand(1).Checksum() - if cs != 399: - gdaltest.post_reason('bad checksum') - print(cs) - return 'fail' + assert cs == 399, 'bad checksum' gdal.Unlink(cutlineDSName) - return 'success' - ############################################################################### # Test automatic detection and setting of alpha channel, and setting RGB on # GTiff output @@ -1242,20 +974,14 @@ def test_gdalwarp_lib_130(): src_ds.GetRasterBand(5).Fill(255) ds = gdal.Warp('/vsimem/test_gdalwarp_lib_130_dst.tif', src_ds) - if ds.GetRasterBand(1).GetColorInterpretation() != gdal.GCI_RedBand: - gdaltest.post_reason('bad color interpretation') - return 'fail' - if ds.GetRasterBand(5).GetColorInterpretation() != gdal.GCI_AlphaBand: - gdaltest.post_reason('bad color interpretation') - return 'fail' + assert ds.GetRasterBand(1).GetColorInterpretation() == gdal.GCI_RedBand, \ + 'bad color interpretation' + assert ds.GetRasterBand(5).GetColorInterpretation() == gdal.GCI_AlphaBand, \ + 'bad color interpretation' expected_val = [1, 2, 3, 4, 255] for i in range(5): data = struct.unpack('B' * 1, ds.GetRasterBand(i + 1).ReadRaster())[0] - if data != expected_val[i]: - gdaltest.post_reason('bad checksum') - print(i) - print(data) - return 'fail' + assert data == expected_val[i], 'bad checksum' # Wrap onto existing file for i in range(5): @@ -1263,24 +989,17 @@ def test_gdalwarp_lib_130(): gdal.Warp(ds, src_ds) for i in range(5): data = struct.unpack('B' * 1, ds.GetRasterBand(i + 1).ReadRaster())[0] - if data != expected_val[i]: - gdaltest.post_reason('bad checksum') - print(i) - print(data) - return 'fail' + assert data == expected_val[i], 'bad checksum' src_ds = None ds = None - if gdal.VSIStatL('/vsimem/test_gdalwarp_lib_130_dst.tif.aux.xml') is not None: - gdaltest.post_reason('got PAM file') - return 'fail' + assert gdal.VSIStatL('/vsimem/test_gdalwarp_lib_130_dst.tif.aux.xml') is None, \ + 'got PAM file' gdal.Unlink('/vsimem/test_gdalwarp_lib_130.tif') gdal.Unlink('/vsimem/test_gdalwarp_lib_130_dst.tif') - return 'success' - ############################################################################### # Test -nosrcalpha @@ -1298,19 +1017,13 @@ def test_gdalwarp_lib_131(): expected_val = [1, 0] for i in range(2): data = struct.unpack('B' * 1, ds.GetRasterBand(i + 1).ReadRaster())[0] - if data != expected_val[i]: - gdaltest.post_reason('bad checksum') - print(i) - print(data) - return 'fail' + assert data == expected_val[i], 'bad checksum' src_ds = None ds = None gdal.Unlink('/vsimem/test_gdalwarp_lib_131.tif') gdal.Unlink('/vsimem/test_gdalwarp_lib_131_dst.tif') gdal.Unlink('/vsimem/test_gdalwarp_lib_131_dst.tif.aux.xml') - return 'success' - ############################################################################### # Test that alpha blending works by warping onto an existing dataset # with alpha > 0 and < 255 @@ -1342,13 +1055,9 @@ def test_gdalwarp_lib_132(): for x in range(33): data = struct.unpack('B' * 1, ds.GetRasterBand(i + 1).ReadRaster(i, 0, 1, 1, buf_type=gdal.GDT_Byte))[0] if abs(data - expected_val[i]) > 1: - gdaltest.post_reason('bad checksum') print(dt) - print(i) print(x) - print(data) - print(expected_val[i]) - return 'fail' + pytest.fail('bad checksum') ds = None src_ds = None @@ -1357,8 +1066,7 @@ def test_gdalwarp_lib_132(): gdal.Unlink('/vsimem/test_gdalwarp_lib_132_dst.tif') gdal.Unlink('/vsimem/test_gdalwarp_lib_132_dst.tif.aux.xml') - return 'success' - + ############################################################################### # Test cutline with multiple touching polygons @@ -1380,20 +1088,14 @@ def test_gdalwarp_lib_133(): src_ds.SetGeoTransform([0, 1, 0, 1, 0, -1]) src_ds.GetRasterBand(1).Fill(255) ds = gdal.Warp('', src_ds, format='MEM', cutlineDSName='/vsimem/test_gdalwarp_lib_133.shp') - if ds is None: - return 'fail' + assert ds is not None - if ds.GetRasterBand(1).Checksum() != 5: - print(ds.GetRasterBand(1).Checksum()) - gdaltest.post_reason('Bad checksum') - return 'fail' + assert ds.GetRasterBand(1).Checksum() == 5, 'Bad checksum' ds = None ogr.GetDriverByName('ESRI Shapefile').DeleteDataSource('/vsimem/test_gdalwarp_lib_133.shp') - return 'success' - ############################################################################### # Test SRC_METHOD=NO_GEOTRANSFORM and DST_METHOD=NO_GEOTRANSFORM (#6721) @@ -1412,29 +1114,23 @@ def test_gdalwarp_lib_134(): src_ds = gdal.GetDriverByName('MEM').Create('', 20, 20) src_ds.GetRasterBand(1).WriteRaster(0, 0, 20, 20, src_src_ds.GetRasterBand(1).ReadRaster()) ds = gdal.Warp('', src_ds, format='MEM', transformerOptions=['SRC_METHOD=NO_GEOTRANSFORM', 'DST_METHOD=NO_GEOTRANSFORM'], outputBounds=[1, 2, 4, 6]) - if ds is None: - return 'fail' + assert ds is not None - if ds.GetRasterBand(1).ReadRaster() != src_src_ds.GetRasterBand(1).ReadRaster(1, 2, 4 - 1, 6 - 2): - gdaltest.post_reason('Bad checksum') - return 'fail' + assert ds.GetRasterBand(1).ReadRaster() == src_src_ds.GetRasterBand(1).ReadRaster(1, 2, 4 - 1, 6 - 2), \ + 'Bad checksum' ds = None ds = gdal.Warp('', src_ds, format='MEM', transformerOptions=['SRC_METHOD=NO_GEOTRANSFORM', 'DST_METHOD=NO_GEOTRANSFORM'], cutlineDSName='/vsimem/test_gdalwarp_lib_134.shp', cropToCutline=True) - if ds is None: - return 'fail' + assert ds is not None - if ds.GetRasterBand(1).ReadRaster() != src_src_ds.GetRasterBand(1).ReadRaster(2, 2, 16, 16): - gdaltest.post_reason('Bad checksum') - return 'fail' + assert ds.GetRasterBand(1).ReadRaster() == src_src_ds.GetRasterBand(1).ReadRaster(2, 2, 16, 16), \ + 'Bad checksum' ds = None ogr.GetDriverByName('ESRI Shapefile').DeleteDataSource('/vsimem/test_gdalwarp_lib_134.shp') - return 'success' - ############################################################################### # Test vertical datum shift @@ -1468,50 +1164,35 @@ def test_gdalwarp_lib_135(): srcSRS='+proj=utm +zone=31 +datum=WGS84 +units=m +geoidgrids=/vsimem/grid.tif +vunits=m +no_defs', dstSRS='EPSG:4979') data = struct.unpack('B' * 1, ds.GetRasterBand(1).ReadRaster())[0] - if data != 120: - gdaltest.post_reason('Bad value') - print(data) - return 'fail' + assert data == 120, 'Bad value' # Inverse transform ds = gdal.Warp('', src_ds, format='MEM', srcSRS='+proj=utm +zone=31 +datum=WGS84 +units=m +no_defs', dstSRS='+proj=longlat +datum=WGS84 +geoidgrids=/vsimem/grid.tif +vunits=m +no_defs') data = struct.unpack('B' * 1, ds.GetRasterBand(1).ReadRaster())[0] - if data != 80: - gdaltest.post_reason('Bad value') - print(data) - return 'fail' + assert data == 80, 'Bad value' # Both transforms ds = gdal.Warp('', src_ds, format='MEM', srcSRS='+proj=utm +zone=31 +datum=WGS84 +units=m +geoidgrids=/vsimem/grid.tif +vunits=m +no_defs', dstSRS='+proj=longlat +datum=WGS84 +geoidgrids=/vsimem/grid2.tif +vunits=m +no_defs') data = struct.unpack('B' * 1, ds.GetRasterBand(1).ReadRaster())[0] - if data != 115: - gdaltest.post_reason('Bad value') - print(data) - return 'fail' + assert data == 115, 'Bad value' # Both transforms, but none of them have geoidgrids ds = gdal.Warp('', src_ds, format='MEM', srcSRS='EPSG:32631+5730', dstSRS='EPSG:4326+5621') data = struct.unpack('B' * 1, ds.GetRasterBand(1).ReadRaster())[0] - if data != 100: - gdaltest.post_reason('Bad value') - print(data) - return 'fail' + assert data == 100, 'Bad value' # Both transforms being a no-op ds = gdal.Warp('', src_ds, format='MEM', srcSRS='+proj=utm +zone=31 +datum=WGS84 +units=m +geoidgrids=/vsimem/grid.tif +vunits=m +no_defs', dstSRS='+proj=longlat +datum=WGS84 +geoidgrids=/vsimem/grid.tif +vunits=m +no_defs') data = struct.unpack('B' * 1, ds.GetRasterBand(1).ReadRaster())[0] - if data != 100: - gdaltest.post_reason('Bad value') - print(data) - return 'fail' + assert data == 100, 'Bad value' # Both transforms to anonymous VRT ds = gdal.Warp('', src_ds, format='VRT', @@ -1519,10 +1200,7 @@ def test_gdalwarp_lib_135(): dstSRS='+proj=longlat +datum=WGS84 +geoidgrids=/vsimem/grid2.tif +vunits=m +no_defs') src_ds = None # drop the ref to src_ds before for fun data = struct.unpack('B' * 1, ds.GetRasterBand(1).ReadRaster())[0] - if data != 115: - gdaltest.post_reason('Bad value') - print(data) - return 'fail' + assert data == 115, 'Bad value' src_ds = gdal.GetDriverByName('MEM').Create('', 1, 1) src_ds.SetGeoTransform([500000, 1, 0, 4000000, 0, -1]) @@ -1538,19 +1216,14 @@ def test_gdalwarp_lib_135(): ds = None gdal.Unlink('/vsimem/dem.tif') gdal.Unlink('/vsimem/tmp.vrt') - if data != 115: - gdaltest.post_reason('Bad value') - print(data) - return 'fail' + assert data == 115, 'Bad value' # Missing grid in forward path with gdaltest.error_handler(): ds = gdal.Warp('', src_ds, format='MEM', srcSRS='+proj=utm +zone=31 +datum=WGS84 +units=m +geoidgrids=i_dont_exist.tif +vunits=m +no_defs', dstSRS='EPSG:4979') - if ds is not None: - gdaltest.post_reason('fail') - return 'fail' + assert ds is None # Missing grid in forward path with PROJ_LIB old_proj_lib = os.environ.get('PROJ_LIB', None) @@ -1563,74 +1236,56 @@ def test_gdalwarp_lib_135(): os.environ['PROJ_LIB'] = old_proj_lib else: del os.environ['PROJ_LIB'] - if ds is not None: - gdaltest.post_reason('fail') - return 'fail' + assert ds is None # Missing grid in forward path with gdaltest.error_handler(): ds = gdal.Warp('', src_ds, format='MEM', srcSRS='+proj=utm +zone=31 +datum=WGS84 +units=m +geoidgrids=~/i_dont_exist.tif +vunits=m +no_defs', dstSRS='EPSG:4979') - if ds is not None: - gdaltest.post_reason('fail') - return 'fail' + assert ds is None # Missing grid in forward path with gdaltest.error_handler(): ds = gdal.Warp('', src_ds, format='MEM', srcSRS='+proj=utm +zone=31 +datum=WGS84 +units=m +geoidgrids=/i_dont/exist.tif +vunits=m +no_defs', dstSRS='EPSG:4979') - if ds is not None: - gdaltest.post_reason('fail') - return 'fail' + assert ds is None # Ungeoref grid in forward path with gdaltest.error_handler(): ds = gdal.Warp('', src_ds, format='MEM', srcSRS='+proj=utm +zone=31 +datum=WGS84 +units=m +geoidgrids=/vsimem/ungeoref_grid.tif +vunits=m +no_defs', dstSRS='EPSG:4979') - if ds is not None: - gdaltest.post_reason('fail') - return 'fail' + assert ds is None # Missing grid in inverse path with gdaltest.error_handler(): ds = gdal.Warp('', src_ds, format='MEM', srcSRS='+proj=utm +zone=31 +datum=WGS84 +units=m +no_defs', dstSRS='+proj=longlat +datum=WGS84 +geoidgrids=i_dont_exist.tif +vunits=m +no_defs') - if ds is not None: - gdaltest.post_reason('fail') - return 'fail' + assert ds is None # Ungeoref grid in inverse path with gdaltest.error_handler(): ds = gdal.Warp('', src_ds, format='MEM', srcSRS='+proj=utm +zone=31 +datum=WGS84 +units=m +no_defs', dstSRS='+proj=longlat +datum=WGS84 +geoidgrids=/vsimem/ungeoref_grid.tif +vunits=m +no_defs') - if ds is not None: - gdaltest.post_reason('fail') - return 'fail' + assert ds is None # Missing grid in forward path, but this is OK ds = gdal.Warp('', src_ds, format='MEM', srcSRS='+proj=utm +zone=31 +datum=WGS84 +units=m +geoidgrids=@i_dont_exist.tif +vunits=m +no_defs', dstSRS='EPSG:4979') data = struct.unpack('B' * 1, ds.GetRasterBand(1).ReadRaster())[0] - if data != 100: - gdaltest.post_reason('Bad value') - print(data) - return 'fail' + assert data == 100, 'Bad value' # Missing grid in inverse path but this is OK ds = gdal.Warp('', src_ds, format='MEM', srcSRS='+proj=utm +zone=31 +datum=WGS84 +units=m +no_defs', dstSRS='+proj=longlat +datum=WGS84 +geoidgrids=@i_dont_exist.tif +vunits=m +no_defs') data = struct.unpack('B' * 1, ds.GetRasterBand(1).ReadRaster())[0] - if data != 100: - gdaltest.post_reason('Bad value') - print(data) - return 'fail' + assert data == 100, 'Bad value' # Forward transform with explicit m unit src_ds = gdal.GetDriverByName('MEM').Create('', 1, 1) @@ -1644,10 +1299,7 @@ def test_gdalwarp_lib_135(): ds = gdal.Warp('', src_ds, format='MEM', dstSRS='EPSG:4979') data = struct.unpack('B' * 1, ds.GetRasterBand(1).ReadRaster())[0] - if data != 120: - gdaltest.post_reason('Bad value') - print(data) - return 'fail' + assert data == 120, 'Bad value' # Forward transform with explicit ft unit src_ds = gdal.GetDriverByName('MEM').Create('', 1, 1, 1, gdal.GDT_Float32) @@ -1661,10 +1313,7 @@ def test_gdalwarp_lib_135(): ds = gdal.Warp('', src_ds, format='MEM', dstSRS='EPSG:4979', outputType=gdal.GDT_Byte) data = struct.unpack('B' * 1, ds.GetRasterBand(1).ReadRaster())[0] - if data != 120: - gdaltest.post_reason('Bad value') - print(data) - return 'fail' + assert data == 120, 'Bad value' # Forward transform with explicit unhandled unit src_ds = gdal.GetDriverByName('MEM').Create('', 1, 1) @@ -1679,10 +1328,7 @@ def test_gdalwarp_lib_135(): ds = gdal.Warp('', src_ds, format='MEM', dstSRS='EPSG:4979') data = struct.unpack('B' * 1, ds.GetRasterBand(1).ReadRaster())[0] - if data != 120: - gdaltest.post_reason('Bad value') - print(data) - return 'fail' + assert data == 120, 'Bad value' grid_ds = gdal.GetDriverByName('GTiff').Create('/vsimem/empty_grid.tif', 1, 1) sr = osr.SpatialReference() @@ -1702,10 +1348,7 @@ def test_gdalwarp_lib_135(): srcSRS='+proj=utm +zone=31 +datum=WGS84 +units=m +geoidgrids=/vsimem/empty_grid.tif +vunits=m +no_defs', dstSRS='EPSG:4979') data = struct.unpack('B' * 1, ds.GetRasterBand(1).ReadRaster())[0] - if data != 100: - gdaltest.post_reason('Bad value') - print(data) - return 'fail' + assert data == 100, 'Bad value' # Same, but make it an error with gdaltest.error_handler(): @@ -1714,29 +1357,22 @@ def test_gdalwarp_lib_135(): dstSRS='EPSG:4979', transformerOptions=['ERROR_ON_MISSING_VERT_SHIFT=YES']) if ds is not None: - gdaltest.post_reason('Bad value') print(data) - return 'fail' + pytest.fail('Bad value') # Test several grids ds = gdal.Warp('', src_ds, format='MEM', srcSRS='+proj=utm +zone=31 +datum=WGS84 +units=m +geoidgrids=/vsimem/grid.tif,/vsimem/empty_grid.tif +vunits=m +no_defs', dstSRS='EPSG:4979') data = struct.unpack('B' * 1, ds.GetRasterBand(1).ReadRaster())[0] - if data != 120: - gdaltest.post_reason('Bad value') - print(data) - return 'fail' + assert data == 120, 'Bad value' # Same, but different order ds = gdal.Warp('', src_ds, format='MEM', srcSRS='+proj=utm +zone=31 +datum=WGS84 +units=m +geoidgrids=/vsimem/empty_grid.tif,/vsimem/grid.tif +vunits=m +no_defs', dstSRS='EPSG:4979') data = struct.unpack('B' * 1, ds.GetRasterBand(1).ReadRaster())[0] - if data != 120: - gdaltest.post_reason('Bad value') - print(data) - return 'fail' + assert data == 120, 'Bad value' # Test several grids, with some missing with gdaltest.error_handler(): @@ -1744,37 +1380,28 @@ def test_gdalwarp_lib_135(): srcSRS='+proj=utm +zone=31 +datum=WGS84 +units=m +geoidgrids=/vsimem/grid.tif,i_dont_exist.tif +vunits=m +no_defs', dstSRS='EPSG:4979') if ds is not None: - gdaltest.post_reason('Bad value') print(data) - return 'fail' + pytest.fail('Bad value') # Test several grids, with some missing, but that's OK ds = gdal.Warp('', src_ds, format='MEM', srcSRS='+proj=utm +zone=31 +datum=WGS84 +units=m +geoidgrids=/vsimem/grid.tif,@i_dont_exist.tif +vunits=m +no_defs', dstSRS='EPSG:4979') data = struct.unpack('B' * 1, ds.GetRasterBand(1).ReadRaster())[0] - if data != 120: - gdaltest.post_reason('Bad value') - print(data) - return 'fail' + assert data == 120, 'Bad value' # Test several grids, with all missing, but that's OK ds = gdal.Warp('', src_ds, format='MEM', srcSRS='+proj=utm +zone=31 +datum=WGS84 +units=m +geoidgrids=@i_dont_exist.tif,@i_dont_exist_either.tif +vunits=m +no_defs', dstSRS='EPSG:4979') data = struct.unpack('B' * 1, ds.GetRasterBand(1).ReadRaster())[0] - if data != 100: - gdaltest.post_reason('Bad value') - print(data) - return 'fail' + assert data == 100, 'Bad value' gdal.GetDriverByName('GTiff').Delete('/vsimem/grid.tif') gdal.GetDriverByName('GTiff').Delete('/vsimem/grid2.tif') gdal.GetDriverByName('GTiff').Delete('/vsimem/ungeoref_grid.tif') gdal.GetDriverByName('GTiff').Delete('/vsimem/empty_grid.tif') - return 'success' - ############################################################################### # Test error code path linked with failed warper initialization @@ -1783,17 +1410,11 @@ def test_gdalwarp_lib_136(): with gdaltest.error_handler(): ds = gdal.Warp('', '../gcore/data/utmsmall.tif', format='MEM', warpOptions=['CUTLINE=invalid']) - if ds is not None: - gdaltest.post_reason('fail') - return 'fail' + assert ds is None with gdaltest.error_handler(): ds = gdal.Warp('', '../gcore/data/utmsmall.tif', format='VRT', warpOptions=['CUTLINE=invalid']) - if ds is not None: - gdaltest.post_reason('fail') - return 'fail' - - return 'success' + assert ds is None ############################################################################### # Test warping two input datasets with different SRS, with no explicit target SRS @@ -1810,20 +1431,10 @@ def test_gdalwarp_lib_several_sources_with_different_srs_no_explicit_target_srs( src_ds_4326_right = gdal.Warp('', src_ds_32611_right, format='MEM', dstSRS='EPSG:4326') out_ds = gdal.Warp('', [src_ds_4326_right, src_ds_32611_left], format='MEM') - if out_ds is None: - gdaltest.post_reason('fail') - return 'fail' - if out_ds.RasterXSize != 23: - gdaltest.post_reason('fail') - print(out_ds.RasterXSize) - return 'fail' + assert out_ds is not None + assert out_ds.RasterXSize == 23 cs = out_ds.GetRasterBand(1).Checksum() - if cs != 5048: - gdaltest.post_reason('fail') - print(cs) - return 'fail' - - return 'success' + assert cs == 5048 ############################################################################### # Test fix for https://trac.osgeo.org/gdal/ticket/7243 @@ -1837,12 +1448,7 @@ def test_gdalwarp_lib_touching_dateline(): sr.ImportFromEPSG(3411) src_ds.SetProjection(sr.ExportToWkt()) out_ds = gdal.Warp('', src_ds, dstSRS='EPSG:4326', format='MEM') - if out_ds.RasterXSize != 319: - gdaltest.post_reason('fail') - print(out_ds.RasterXSize) - return 'fail' - - return 'success' + assert out_ds.RasterXSize == 319 ############################################################################### # Test fix for https://trac.osgeo.org/gdal/ticket/7245 @@ -1852,7 +1458,7 @@ def test_gdalwarp_lib_override_default_output_nodata(): drv = gdal.GetDriverByName('netCDF') if drv is None: - return 'skip' + pytest.skip() creationoptionlist = drv.GetMetadataItem('DMD_CREATIONOPTIONLIST') formats = ['NC'] @@ -1865,20 +1471,12 @@ def test_gdalwarp_lib_override_default_output_nodata(): gdal.Warp('tmp/out.nc', '../gcore/data/byte.tif', srcNodata=255, format='netCDF', creationOptions=['FORMAT=' + frmt]) ds = gdal.Open('tmp/out.nc') - if ds.GetRasterBand(1).GetNoDataValue() != 255: - gdaltest.post_reason('fail') - print(frmt) - print(ds.GetRasterBand(1).GetNoDataValue()) - return 'fail' - if ds.GetProjection() == '': - gdaltest.post_reason('fail') - print(frmt) - return 'fail' + assert ds.GetRasterBand(1).GetNoDataValue() == 255, frmt + assert ds.GetProjection() != '', frmt ds = None os.unlink('tmp/out.nc') - return 'success' - + ############################################################################### # Test automatting setting (or not) of SKIP_NOSOURCE=YES @@ -1905,10 +1503,7 @@ def test_gdalwarp_lib_auto_skip_nosource(): options='-te 1.5 48 3.5 49.5 -wm 100000 ' + '-of GTiff ' + options) cs = out_ds.GetRasterBand(1).Checksum() - if cs != 41500: - gdaltest.post_reason('fail') - print(options, cs) - return 'fail' + assert cs == 41500, (options, cs) # Same with MEM for options in ['', @@ -1919,10 +1514,7 @@ def test_gdalwarp_lib_auto_skip_nosource(): options='-te 1.5 48 3.5 49.5 -wm 100000 ' + '-of MEM ' + options) cs = out_ds.GetRasterBand(1).Checksum() - if cs != 41500: - gdaltest.post_reason('fail') - print(options, cs) - return 'fail' + assert cs == 41500, (options, cs) # Use fill/nodata at 1 for options in [ # '-wo SKIP_NOSOURCE=NO -dstnodata 1', @@ -1934,10 +1526,7 @@ def test_gdalwarp_lib_auto_skip_nosource(): options='-te 1.5 48 3.5 49.5 -wm 100000 ' + '-of GTiff ' + options) cs = out_ds.GetRasterBand(1).Checksum() - if cs != 51132: - gdaltest.post_reason('fail') - print(options, cs) - return 'fail' + assert cs == 51132, (options, cs) # Same with MEM for options in [ # '-wo SKIP_NOSOURCE=NO -dstnodata 1', @@ -1949,10 +1538,7 @@ def test_gdalwarp_lib_auto_skip_nosource(): options='-te 1.5 48 3.5 49.5 -wm 100000 ' + '-of MEM ' + options) cs = out_ds.GetRasterBand(1).Checksum() - if cs != 51132: - gdaltest.post_reason('fail') - print(options, cs) - return 'fail' + assert cs == 51132, (options, cs) # Rather dummy: use a INIT_DEST different of the target dstnodata for options in [ # '-wo SKIP_NOSOURCE=NO -dstnodata 1 -wo INIT_DEST=0', @@ -1962,10 +1548,7 @@ def test_gdalwarp_lib_auto_skip_nosource(): options='-te 1.5 48 3.5 49.5 -wm 100000 ' + '-of GTiff ' + options) cs = out_ds.GetRasterBand(1).Checksum() - if cs != 41500: - gdaltest.post_reason('fail') - print(options, cs) - return 'fail' + assert cs == 41500, (options, cs) # Test with 2 input datasets src_ds1 = gdal.GetDriverByName('MEM').Create('', 500, 500) @@ -1984,15 +1567,10 @@ def test_gdalwarp_lib_auto_skip_nosource(): options='-te 1.5 48 3.5 49.5 -wm 100000 ' + '-of GTiff ' + options) cs = out_ds.GetRasterBand(1).Checksum() - if cs != 41500: - gdaltest.post_reason('fail') - print(options, cs) - return 'fail' + assert cs == 41500, (options, cs) gdal.Unlink(tmpfilename) - return 'success' - ############################################################################### # Test warping a full EPSG:4326 extent to +proj=ortho # (https://github.com/OSGeo/gdal/issues/862) @@ -2006,19 +1584,13 @@ def test_gdalwarp_lib_to_ortho(): line = out_ds.GetRasterBand(1).ReadRaster(0, 0, out_ds.RasterXSize, 1) line = struct.unpack('B' * out_ds.RasterXSize, line) # Fail if the first line is completely black - if line.count(0) == out_ds.RasterXSize: - gdaltest.post_reason('first line is completely black') - return 'fail' + assert line.count(0) != out_ds.RasterXSize, 'first line is completely black' line = out_ds.GetRasterBand(1).ReadRaster(0, out_ds.RasterYSize - 1, out_ds.RasterXSize, 1) line = struct.unpack('B' * out_ds.RasterXSize, line) # Fail if the last line is completely black - if line.count(0) == out_ds.RasterXSize: - gdaltest.post_reason('last line is completely black') - return 'fail' - - return 'success' + assert line.count(0) != out_ds.RasterXSize, 'last line is completely black' ############################################################################### @@ -2027,11 +1599,9 @@ def test_gdalwarp_lib_insufficient_dst_band_count(): src_ds = gdal.Translate('', '../gcore/data/byte.tif', options='-of MEM -b 1 -b 1') dst_ds = gdal.Translate('', '../gcore/data/byte.tif', options='-of MEM') with gdaltest.error_handler(): - if gdal.Warp(dst_ds, src_ds) != 0: - return 'fail' - - return 'success' + assert gdal.Warp(dst_ds, src_ds) == 0 + ############################################################################### # Cleanup @@ -2040,7 +1610,7 @@ def test_gdalwarp_lib_cleanup(): # We don't clean up when run in debug mode. if gdal.GetConfigOption('CPL_DEBUG', 'OFF') == 'ON': - return 'success' + return for i in range(2): try: @@ -2052,85 +1622,6 @@ def test_gdalwarp_lib_cleanup(): except OSError: pass - return 'success' - - -gdaltest_list = [ - test_gdalwarp_lib_cleanup, - test_gdalwarp_lib_1, - test_gdalwarp_lib_2, - test_gdalwarp_lib_3, - test_gdalwarp_lib_4, - test_gdalwarp_lib_5, - test_gdalwarp_lib_6, - test_gdalwarp_lib_7, - test_gdalwarp_lib_8, - test_gdalwarp_lib_9, - test_gdalwarp_lib_10, - test_gdalwarp_lib_11, - test_gdalwarp_lib_12, - test_gdalwarp_lib_13, - test_gdalwarp_lib_14, - test_gdalwarp_lib_15, - test_gdalwarp_lib_16, - test_gdalwarp_lib_17, - test_gdalwarp_lib_19, - test_gdalwarp_lib_21, - test_gdalwarp_lib_23, - test_gdalwarp_lib_32, - test_gdalwarp_lib_34, - test_gdalwarp_lib_45, - test_gdalwarp_lib_46, - test_gdalwarp_lib_100, - test_gdalwarp_lib_101, - test_gdalwarp_lib_102, - test_gdalwarp_lib_103, - test_gdalwarp_lib_104, - test_gdalwarp_lib_105, - test_gdalwarp_lib_106, - test_gdalwarp_lib_107, - test_gdalwarp_lib_108, - test_gdalwarp_lib_109, - test_gdalwarp_lib_110, - test_gdalwarp_lib_111, - test_gdalwarp_lib_112, - test_gdalwarp_lib_113, - test_gdalwarp_lib_114, - test_gdalwarp_lib_115, - test_gdalwarp_lib_116, - test_gdalwarp_lib_117, - test_gdalwarp_lib_118, - test_gdalwarp_lib_119, - test_gdalwarp_lib_120, - test_gdalwarp_lib_121, - test_gdalwarp_lib_122, - test_gdalwarp_lib_123, - test_gdalwarp_lib_124, - test_gdalwarp_lib_125, - test_gdalwarp_lib_126, - test_gdalwarp_lib_127, - test_gdalwarp_lib_128, - test_gdalwarp_lib_129, - test_gdalwarp_lib_130, - test_gdalwarp_lib_131, - test_gdalwarp_lib_132, - test_gdalwarp_lib_133, - test_gdalwarp_lib_134, - test_gdalwarp_lib_135, - test_gdalwarp_lib_136, - test_gdalwarp_lib_several_sources_with_different_srs_no_explicit_target_srs, - test_gdalwarp_lib_touching_dateline, - test_gdalwarp_lib_override_default_output_nodata, - test_gdalwarp_lib_auto_skip_nosource, - test_gdalwarp_lib_to_ortho, - test_gdalwarp_lib_insufficient_dst_band_count, - test_gdalwarp_lib_cleanup, -] - -if __name__ == '__main__': - - gdaltest.setup_run('test_gdalwarp_lib') - - gdaltest.run_tests(gdaltest_list) - - sys.exit(gdaltest.summarize()) + + + diff --git a/autotest/utilities/test_gnmutils.py b/autotest/utilities/test_gnmutils.py index 1e8fa4a623a7..f5c660961df7 100755 --- a/autotest/utilities/test_gnmutils.py +++ b/autotest/utilities/test_gnmutils.py @@ -31,13 +31,12 @@ # DEALINGS IN THE SOFTWARE. ############################################################################### -import sys import os -sys.path.append('../pymod') import gdaltest import test_cli_utilities +import pytest ############################################################################### # Test create @@ -46,22 +45,17 @@ def test_gnmmanage_1(): if test_cli_utilities.get_gnmmanage_path() is None: - return 'skip' + pytest.skip() (_, err) = gdaltest.runexternal_out_and_err(test_cli_utilities.get_gnmmanage_path() + ' create -f GNMFile -t_srs EPSG:4326 -dsco net_name=test_gnm -dsco net_description="Test file based GNM" tmp') - if not (err is None or err == ''): - gdaltest.post_reason('got error/warning') - print(err) - return 'fail' + assert (err is None or err == ''), 'got error/warning' try: os.stat('tmp/test_gnm') except OSError: - gdaltest.post_reason('Expected create tmp/test_gnm') - return 'fail' - - return 'success' + pytest.fail('Expected create tmp/test_gnm') + ############################################################################### # Test import # gnmmanage import /home/bishop/tmp/data/pipes.shp /home/bishop/tmp/test_gnm --config CPL_DEBUG ON @@ -70,21 +64,13 @@ def test_gnmmanage_1(): def test_gnmmanage_2(): if test_cli_utilities.get_gnmmanage_path() is None: - return 'skip' + pytest.skip() (_, err) = gdaltest.runexternal_out_and_err(test_cli_utilities.get_gnmmanage_path() + ' import ../gnm/data/pipes.shp tmp/test_gnm') - if not (err is None or err == ''): - gdaltest.post_reason('got error/warning') - print(err) - return 'fail' + assert (err is None or err == ''), 'got error/warning' (_, err) = gdaltest.runexternal_out_and_err(test_cli_utilities.get_gnmmanage_path() + ' import ../gnm/data/wells.shp tmp/test_gnm') - if not (err is None or err == ''): - gdaltest.post_reason('got error/warning') - print(err) - return 'fail' - - return 'success' + assert (err is None or err == ''), 'got error/warning' ############################################################################### # Test info @@ -93,21 +79,13 @@ def test_gnmmanage_2(): def test_gnmmanage_3(): if test_cli_utilities.get_gnmmanage_path() is None: - return 'skip' + pytest.skip() ret = gdaltest.runexternal(test_cli_utilities.get_gnmmanage_path() + ' info tmp/test_gnm') - if ret.find('Network version: 1.0.') == -1: - gdaltest.post_reason('fail') - return 'fail' - if ret.find('Network name: test_gnm.') == -1: - gdaltest.post_reason('fail') - return 'fail' - if ret.find('Network description') == -1: - gdaltest.post_reason('fail') - return 'fail' - - return 'success' + assert ret.find('Network version: 1.0.') != -1 + assert ret.find('Network name: test_gnm.') != -1 + assert ret.find('Network description') != -1 ############################################################################### # Test autoconect @@ -116,13 +94,10 @@ def test_gnmmanage_3(): def test_gnmmanage_4(): if test_cli_utilities.get_gnmmanage_path() is None: - return 'skip' + pytest.skip() ret = gdaltest.runexternal(test_cli_utilities.get_gnmmanage_path() + ' autoconnect 0.000001 tmp/test_gnm') - if ret.find('success') == -1: - return 'fail' - - return 'success' + assert ret.find('success') != -1 ############################################################################### # Test dijkstra @@ -131,15 +106,12 @@ def test_gnmmanage_4(): def test_gnmanalyse_1(): if test_cli_utilities.get_gnmmanage_path() is None: - return 'skip' + pytest.skip() if test_cli_utilities.get_gnmanalyse_path() is None: - return 'skip' + pytest.skip() ret = gdaltest.runexternal(test_cli_utilities.get_gnmanalyse_path() + ' dijkstra 61 50 tmp/test_gnm') - if ret.find('Feature Count: 19') == -1: - return 'fail' - - return 'success' + assert ret.find('Feature Count: 19') != -1 ############################################################################### # Test kpaths @@ -148,15 +120,12 @@ def test_gnmanalyse_1(): def test_gnmanalyse_2(): if test_cli_utilities.get_gnmmanage_path() is None: - return 'skip' + pytest.skip() if test_cli_utilities.get_gnmanalyse_path() is None: - return 'skip' + pytest.skip() ret = gdaltest.runexternal(test_cli_utilities.get_gnmanalyse_path() + ' kpaths 61 50 3 tmp/test_gnm') - if ret.find('Feature Count: 61') == -1: - return 'fail' - - return 'success' + assert ret.find('Feature Count: 61') != -1 ############################################################################### # Test cleanup @@ -164,39 +133,16 @@ def test_gnmanalyse_2(): def test_gnm_cleanup(): if test_cli_utilities.get_gnmmanage_path() is None: - return 'skip' + pytest.skip() (_, err) = gdaltest.runexternal_out_and_err(test_cli_utilities.get_gnmmanage_path() + ' delete tmp/test_gnm') - if not (err is None or err == ''): - gdaltest.post_reason('got error/warning') - print(err) - return 'fail' + assert (err is None or err == ''), 'got error/warning' - try: + with pytest.raises(OSError, message='Expected delete tmp/test_gnm'): os.stat('tmp/test_gnm') - gdaltest.post_reason('Expected delete tmp/test_gnm') - return 'fail' - except OSError: - pass - - return 'success' - - -gdaltest_list = [ - test_gnmmanage_1, - test_gnmmanage_2, - test_gnmmanage_3, - test_gnmmanage_4, - test_gnmanalyse_1, - test_gnmanalyse_2, - test_gnm_cleanup -] - + -if __name__ == '__main__': + - gdaltest.setup_run('test_gnmutils') - gdaltest.run_tests(gdaltest_list) - sys.exit(gdaltest.summarize()) diff --git a/autotest/utilities/test_nearblack.py b/autotest/utilities/test_nearblack.py index 789b9ddabb54..ca78ce0d6f70 100755 --- a/autotest/utilities/test_nearblack.py +++ b/autotest/utilities/test_nearblack.py @@ -29,15 +29,14 @@ # DEALINGS IN THE SOFTWARE. ############################################################################### -import sys import os import shutil -sys.path.append('../pymod') from osgeo import gdal import gdaltest import test_cli_utilities +import pytest ############################################################################### # Basic test @@ -45,154 +44,112 @@ def test_nearblack_1(): if test_cli_utilities.get_nearblack_path() is None: - return 'skip' + pytest.skip() (_, err) = gdaltest.runexternal_out_and_err(test_cli_utilities.get_nearblack_path() + ' ../gdrivers/data/rgbsmall.tif -nb 0 -of GTiff -o tmp/nearblack1.tif') - if not (err is None or err == ''): - gdaltest.post_reason('got error/warning') - print(err) - return 'fail' + assert (err is None or err == ''), 'got error/warning' src_ds = gdal.Open('../gdrivers/data/rgbsmall.tif') ds = gdal.Open('tmp/nearblack1.tif') - if ds is None: - return 'fail' + assert ds is not None - if ds.GetRasterBand(1).Checksum() != 21106: - print(ds.GetRasterBand(1).Checksum()) - gdaltest.post_reason('Bad checksum band 1') - return 'fail' + assert ds.GetRasterBand(1).Checksum() == 21106, 'Bad checksum band 1' - if ds.GetRasterBand(2).Checksum() != 20736: - print(ds.GetRasterBand(2).Checksum()) - gdaltest.post_reason('Bad checksum band 2') - return 'fail' + assert ds.GetRasterBand(2).Checksum() == 20736, 'Bad checksum band 2' - if ds.GetRasterBand(3).Checksum() != 21309: - print(ds.GetRasterBand(3).Checksum()) - gdaltest.post_reason('Bad checksum band 3') - return 'fail' + assert ds.GetRasterBand(3).Checksum() == 21309, 'Bad checksum band 3' src_gt = src_ds.GetGeoTransform() dst_gt = ds.GetGeoTransform() for i in range(6): - if abs(src_gt[i] - dst_gt[i]) > 1e-10: - gdaltest.post_reason('Bad geotransform') - return 'fail' + assert abs(src_gt[i] - dst_gt[i]) <= 1e-10, 'Bad geotransform' dst_wkt = ds.GetProjectionRef() - if dst_wkt.find('AUTHORITY["EPSG","4326"]') == -1: - gdaltest.post_reason('Bad projection') - return 'fail' + assert dst_wkt.find('AUTHORITY["EPSG","4326"]') != -1, 'Bad projection' src_ds = None ds = None - return 'success' - ############################################################################### # Add alpha band def test_nearblack_2(): if test_cli_utilities.get_nearblack_path() is None: - return 'skip' + pytest.skip() gdaltest.runexternal(test_cli_utilities.get_nearblack_path() + ' ../gdrivers/data/rgbsmall.tif -setalpha -nb 0 -of GTiff -o tmp/nearblack2.tif -co TILED=YES') ds = gdal.Open('tmp/nearblack2.tif') - if ds is None: - return 'fail' + assert ds is not None - if ds.GetRasterBand(4).Checksum() != 22002: - print(ds.GetRasterBand(4).Checksum()) - gdaltest.post_reason('Bad checksum band 0') - return 'fail' + assert ds.GetRasterBand(4).Checksum() == 22002, 'Bad checksum band 0' ds = None - return 'success' - ############################################################################### # Set existing alpha band def test_nearblack_3(): if test_cli_utilities.get_nearblack_path() is None: - return 'skip' + pytest.skip() shutil.copy('tmp/nearblack2.tif', 'tmp/nearblack3.tif') gdaltest.runexternal(test_cli_utilities.get_nearblack_path() + ' -setalpha -nb 0 -of GTiff tmp/nearblack3.tif') ds = gdal.Open('tmp/nearblack3.tif') - if ds is None: - return 'fail' + assert ds is not None - if ds.GetRasterBand(4).Checksum() != 22002: - print(ds.GetRasterBand(4).Checksum()) - gdaltest.post_reason('Bad checksum band 0') - return 'fail' + assert ds.GetRasterBand(4).Checksum() == 22002, 'Bad checksum band 0' ds = None - return 'success' - ############################################################################### # Test -white def test_nearblack_4(): if test_cli_utilities.get_nearblack_path() is None: - return 'skip' + pytest.skip() if test_cli_utilities.get_gdalwarp_path() is None: - return 'skip' + pytest.skip() gdaltest.runexternal(test_cli_utilities.get_gdalwarp_path() + ' -wo "INIT_DEST=255" ../gdrivers/data/rgbsmall.tif tmp/nearblack4_src.tif -srcnodata 0') gdaltest.runexternal(test_cli_utilities.get_nearblack_path() + ' -q -setalpha -white -nb 0 -of GTiff tmp/nearblack4_src.tif -o tmp/nearblack4.tif') ds = gdal.Open('tmp/nearblack4.tif') - if ds is None: - return 'fail' + assert ds is not None - if ds.GetRasterBand(4).Checksum() != 24151: - print(ds.GetRasterBand(4).Checksum()) - gdaltest.post_reason('Bad checksum band 0') - return 'fail' + assert ds.GetRasterBand(4).Checksum() == 24151, 'Bad checksum band 0' ds = None - return 'success' - ############################################################################### # Add mask band def test_nearblack_5(): if test_cli_utilities.get_nearblack_path() is None: - return 'skip' + pytest.skip() gdaltest.runexternal(test_cli_utilities.get_nearblack_path() + ' ../gdrivers/data/rgbsmall.tif --config GDAL_TIFF_INTERNAL_MASK NO -setmask -nb 0 -of GTiff -o tmp/nearblack5.tif -co TILED=YES') ds = gdal.Open('tmp/nearblack5.tif') - if ds is None: - return 'fail' + assert ds is not None - if ds.GetRasterBand(1).GetMaskBand().Checksum() != 22002: - print(ds.GetRasterBand(1).GetMaskBand().Checksum()) - gdaltest.post_reason('Bad checksum mask band') - return 'fail' + assert ds.GetRasterBand(1).GetMaskBand().Checksum() == 22002, \ + 'Bad checksum mask band' ds = None - return 'success' - ############################################################################### # Set existing mask band def test_nearblack_6(): if test_cli_utilities.get_nearblack_path() is None: - return 'skip' + pytest.skip() shutil.copy('tmp/nearblack5.tif', 'tmp/nearblack6.tif') shutil.copy('tmp/nearblack5.tif.msk', 'tmp/nearblack6.tif.msk') @@ -200,44 +157,31 @@ def test_nearblack_6(): gdaltest.runexternal(test_cli_utilities.get_nearblack_path() + ' -setmask -nb 0 -of GTiff tmp/nearblack6.tif') ds = gdal.Open('tmp/nearblack6.tif') - if ds is None: - return 'fail' + assert ds is not None - if ds.GetRasterBand(1).GetMaskBand().Checksum() != 22002: - print(ds.GetRasterBand(1).GetMaskBand().Checksum()) - gdaltest.post_reason('Bad checksum mask band') - return 'fail' + assert ds.GetRasterBand(1).GetMaskBand().Checksum() == 22002, \ + 'Bad checksum mask band' ds = None - return 'success' - ############################################################################### # Test -color def test_nearblack_7(): if test_cli_utilities.get_nearblack_path() is None: - return 'skip' + pytest.skip() gdaltest.runexternal(test_cli_utilities.get_nearblack_path() + ' data/whiteblackred.tif -o tmp/nearblack7.tif -color 0,0,0 -color 255,255,255 -of GTiff') ds = gdal.Open('tmp/nearblack7.tif') - if ds is None: - return 'fail' - - if ds.GetRasterBand(1).Checksum() != 418 or \ - ds.GetRasterBand(2).Checksum() != 0 or \ - ds.GetRasterBand(3).Checksum() != 0: - print(ds.GetRasterBand(1).Checksum()) - print(ds.GetRasterBand(2).Checksum()) - print(ds.GetRasterBand(3).Checksum()) - gdaltest.post_reason('Bad checksum') - return 'fail' + assert ds is not None - ds = None + assert (ds.GetRasterBand(1).Checksum() == 418 and \ + ds.GetRasterBand(2).Checksum() == 0 and \ + ds.GetRasterBand(3).Checksum() == 0), 'Bad checksum' - return 'success' + ds = None ############################################################################### # Test in-place update @@ -245,38 +189,23 @@ def test_nearblack_7(): def test_nearblack_8(): if test_cli_utilities.get_nearblack_path() is None: - return 'skip' + pytest.skip() src_ds = gdal.Open('../gdrivers/data/rgbsmall.tif') gdal.GetDriverByName('GTiff').CreateCopy('tmp/nearblack8.tif', src_ds) src_ds = None (_, err) = gdaltest.runexternal_out_and_err(test_cli_utilities.get_nearblack_path() + ' tmp/nearblack8.tif -nb 0') - if not (err is None or err == ''): - gdaltest.post_reason('got error/warning') - print(err) - return 'fail' + assert (err is None or err == ''), 'got error/warning' ds = gdal.Open('tmp/nearblack8.tif') - if ds is None: - return 'fail' - - if ds.GetRasterBand(1).Checksum() != 21106: - print(ds.GetRasterBand(1).Checksum()) - gdaltest.post_reason('Bad checksum band 1') - return 'fail' + assert ds is not None - if ds.GetRasterBand(2).Checksum() != 20736: - print(ds.GetRasterBand(2).Checksum()) - gdaltest.post_reason('Bad checksum band 2') - return 'fail' + assert ds.GetRasterBand(1).Checksum() == 21106, 'Bad checksum band 1' - if ds.GetRasterBand(3).Checksum() != 21309: - print(ds.GetRasterBand(3).Checksum()) - gdaltest.post_reason('Bad checksum band 3') - return 'fail' + assert ds.GetRasterBand(2).Checksum() == 20736, 'Bad checksum band 2' - return 'success' + assert ds.GetRasterBand(3).Checksum() == 21309, 'Bad checksum band 3' ############################################################################### # Cleanup @@ -327,26 +256,7 @@ def test_nearblack_cleanup(): os.remove('tmp/nearblack8.tif') except OSError: pass - return 'success' - - -gdaltest_list = [ - test_nearblack_1, - test_nearblack_2, - test_nearblack_3, - test_nearblack_4, - test_nearblack_5, - test_nearblack_6, - test_nearblack_7, - test_nearblack_8, - test_nearblack_cleanup -] - - -if __name__ == '__main__': + - gdaltest.setup_run('test_nearblack') - gdaltest.run_tests(gdaltest_list) - sys.exit(gdaltest.summarize()) diff --git a/autotest/utilities/test_nearblack_lib.py b/autotest/utilities/test_nearblack_lib.py index 156e3b09c207..9d19481f5e05 100755 --- a/autotest/utilities/test_nearblack_lib.py +++ b/autotest/utilities/test_nearblack_lib.py @@ -29,12 +29,9 @@ # DEALINGS IN THE SOFTWARE. ############################################################################### -import sys -sys.path.append('../pymod') from osgeo import gdal -import gdaltest ############################################################################### # Basic test @@ -44,41 +41,25 @@ def test_nearblack_lib_1(): src_ds = gdal.Open('../gdrivers/data/rgbsmall.tif') ds = gdal.Nearblack('', src_ds, format='MEM', maxNonBlack=0, nearDist=15) - if ds is None: - return 'fail' + assert ds is not None - if ds.GetRasterBand(1).Checksum() != 21106: - print(ds.GetRasterBand(1).Checksum()) - gdaltest.post_reason('Bad checksum band 1') - return 'fail' + assert ds.GetRasterBand(1).Checksum() == 21106, 'Bad checksum band 1' - if ds.GetRasterBand(2).Checksum() != 20736: - print(ds.GetRasterBand(2).Checksum()) - gdaltest.post_reason('Bad checksum band 2') - return 'fail' + assert ds.GetRasterBand(2).Checksum() == 20736, 'Bad checksum band 2' - if ds.GetRasterBand(3).Checksum() != 21309: - print(ds.GetRasterBand(3).Checksum()) - gdaltest.post_reason('Bad checksum band 3') - return 'fail' + assert ds.GetRasterBand(3).Checksum() == 21309, 'Bad checksum band 3' src_gt = src_ds.GetGeoTransform() dst_gt = ds.GetGeoTransform() for i in range(6): - if abs(src_gt[i] - dst_gt[i]) > 1e-10: - gdaltest.post_reason('Bad geotransform') - return 'fail' + assert abs(src_gt[i] - dst_gt[i]) <= 1e-10, 'Bad geotransform' dst_wkt = ds.GetProjectionRef() - if dst_wkt.find('AUTHORITY["EPSG","4326"]') == -1: - gdaltest.post_reason('Bad projection') - return 'fail' + assert dst_wkt.find('AUTHORITY["EPSG","4326"]') != -1, 'Bad projection' src_ds = None ds = None - return 'success' - ############################################################################### # Add alpha band @@ -86,18 +67,12 @@ def test_nearblack_lib_1(): def test_nearblack_lib_2(): ds = gdal.Nearblack('', '../gdrivers/data/rgbsmall.tif', format='MEM', maxNonBlack=0, setAlpha=True) - if ds is None: - return 'fail' + assert ds is not None - if ds.GetRasterBand(4).Checksum() != 22002: - print(ds.GetRasterBand(4).Checksum()) - gdaltest.post_reason('Bad checksum band 0') - return 'fail' + assert ds.GetRasterBand(4).Checksum() == 22002, 'Bad checksum band 0' ds = None - return 'success' - ############################################################################### # Set existing alpha band @@ -106,18 +81,12 @@ def test_nearblack_lib_3(): src_ds = gdal.Nearblack('', '../gdrivers/data/rgbsmall.tif', format='MEM', maxNonBlack=0, setAlpha=True) ds = gdal.Nearblack('', src_ds, format='MEM', maxNonBlack=0, setAlpha=True) - if ds is None: - return 'fail' + assert ds is not None - if ds.GetRasterBand(4).Checksum() != 22002: - print(ds.GetRasterBand(4).Checksum()) - gdaltest.post_reason('Bad checksum band 0') - return 'fail' + assert ds.GetRasterBand(4).Checksum() == 22002, 'Bad checksum band 0' ds = None - return 'success' - ############################################################################### # Test -white @@ -126,18 +95,12 @@ def test_nearblack_lib_4(): src_ds = gdal.Warp('', '../gdrivers/data/rgbsmall.tif', format='MEM', warpOptions=["INIT_DEST=255"], srcNodata=0) ds = gdal.Nearblack('', src_ds, format='MEM', white=True, maxNonBlack=0, setAlpha=True) - if ds is None: - return 'fail' + assert ds is not None - if ds.GetRasterBand(4).Checksum() != 24151: - print(ds.GetRasterBand(4).Checksum()) - gdaltest.post_reason('Bad checksum band 0') - return 'fail' + assert ds.GetRasterBand(4).Checksum() == 24151, 'Bad checksum band 0' ds = None - return 'success' - ############################################################################### # Add mask band @@ -145,21 +108,16 @@ def test_nearblack_lib_4(): def test_nearblack_lib_5(): ds = gdal.Nearblack('/vsimem/test_nearblack_lib_5.tif', '../gdrivers/data/rgbsmall.tif', format='GTiff', maxNonBlack=0, setMask=True) - if ds is None: - return 'fail' + assert ds is not None - if ds.GetRasterBand(1).GetMaskBand().Checksum() != 22002: - print(ds.GetRasterBand(1).GetMaskBand().Checksum()) - gdaltest.post_reason('Bad checksum mask band') - return 'fail' + assert ds.GetRasterBand(1).GetMaskBand().Checksum() == 22002, \ + 'Bad checksum mask band' ds = None gdal.Unlink('/vsimem/test_nearblack_lib_5.tif') gdal.Unlink('/vsimem/test_nearblack_lib_5.tif.msk') - return 'success' - ############################################################################### # Test -color @@ -167,21 +125,13 @@ def test_nearblack_lib_5(): def test_nearblack_lib_7(): ds = gdal.Nearblack('', 'data/whiteblackred.tif', format='MEM', colors=((0, 0, 0), (255, 255, 255))) - if ds is None: - return 'fail' - - if ds.GetRasterBand(1).Checksum() != 418 or \ - ds.GetRasterBand(2).Checksum() != 0 or \ - ds.GetRasterBand(3).Checksum() != 0: - print(ds.GetRasterBand(1).Checksum()) - print(ds.GetRasterBand(2).Checksum()) - print(ds.GetRasterBand(3).Checksum()) - gdaltest.post_reason('Bad checksum') - return 'fail' + assert ds is not None - ds = None + assert (ds.GetRasterBand(1).Checksum() == 418 and \ + ds.GetRasterBand(2).Checksum() == 0 and \ + ds.GetRasterBand(3).Checksum() == 0), 'Bad checksum' - return 'success' + ds = None ############################################################################### # Test in-place update @@ -192,43 +142,14 @@ def test_nearblack_lib_8(): src_ds = gdal.Open('../gdrivers/data/rgbsmall.tif') ds = gdal.GetDriverByName('MEM').CreateCopy('', src_ds) ret = gdal.Nearblack(ds, ds, maxNonBlack=0) - if ret != 1: - gdaltest.post_reason('failure') - return 'fail' - - if ds.GetRasterBand(1).Checksum() != 21106: - print(ds.GetRasterBand(1).Checksum()) - gdaltest.post_reason('Bad checksum band 1') - return 'fail' - - if ds.GetRasterBand(2).Checksum() != 20736: - print(ds.GetRasterBand(2).Checksum()) - gdaltest.post_reason('Bad checksum band 2') - return 'fail' - - if ds.GetRasterBand(3).Checksum() != 21309: - print(ds.GetRasterBand(3).Checksum()) - gdaltest.post_reason('Bad checksum band 3') - return 'fail' - - return 'success' + assert ret == 1 + assert ds.GetRasterBand(1).Checksum() == 21106, 'Bad checksum band 1' -gdaltest_list = [ - test_nearblack_lib_1, - test_nearblack_lib_2, - test_nearblack_lib_3, - test_nearblack_lib_4, - test_nearblack_lib_5, - test_nearblack_lib_7, - test_nearblack_lib_8, -] + assert ds.GetRasterBand(2).Checksum() == 20736, 'Bad checksum band 2' + assert ds.GetRasterBand(3).Checksum() == 21309, 'Bad checksum band 3' -if __name__ == '__main__': - gdaltest.setup_run('test_nearblack_lib') - gdaltest.run_tests(gdaltest_list) - sys.exit(gdaltest.summarize()) diff --git a/autotest/utilities/test_ogr2ogr.py b/autotest/utilities/test_ogr2ogr.py index 7bf485e0673e..e7600dc5bd2a 100755 --- a/autotest/utilities/test_ogr2ogr.py +++ b/autotest/utilities/test_ogr2ogr.py @@ -32,8 +32,8 @@ import sys import os import shutil +import pytest -sys.path.append('../pymod') sys.path.append('../ogr') from osgeo import gdal, ogr, osr @@ -47,7 +47,7 @@ def test_ogr2ogr_1(): if test_cli_utilities.get_ogr2ogr_path() is None: - return 'skip' + pytest.skip() try: os.stat('tmp/poly.shp') @@ -56,38 +56,28 @@ def test_ogr2ogr_1(): pass (_, err) = gdaltest.runexternal_out_and_err(test_cli_utilities.get_ogr2ogr_path() + ' tmp/poly.shp ../ogr/data/poly.shp') - if not (err is None or err == ''): - gdaltest.post_reason('got error/warning') - print(err) - return 'fail' + assert (err is None or err == ''), 'got error/warning' ds = ogr.Open('tmp/poly.shp') - if ds is None or ds.GetLayer(0).GetFeatureCount() != 10: - return 'fail' + assert ds is not None and ds.GetLayer(0).GetFeatureCount() == 10 feat0 = ds.GetLayer(0).GetFeature(0) - if feat0.GetFieldAsDouble('AREA') != 215229.266: - print(feat0.GetFieldAsDouble('AREA')) - gdaltest.post_reason('Did not get expected value for field AREA') - return 'fail' - if feat0.GetFieldAsString('PRFEDEA') != '35043411': - print(feat0.GetFieldAsString('PRFEDEA')) - gdaltest.post_reason('Did not get expected value for field PRFEDEA') - return 'fail' + assert feat0.GetFieldAsDouble('AREA') == 215229.266, \ + 'Did not get expected value for field AREA' + assert feat0.GetFieldAsString('PRFEDEA') == '35043411', \ + 'Did not get expected value for field PRFEDEA' ds.Destroy() ogr.GetDriverByName('ESRI Shapefile').DeleteDataSource('tmp/poly.shp') - return 'success' - ############################################################################### # Test -sql def test_ogr2ogr_2(): if test_cli_utilities.get_ogr2ogr_path() is None: - return 'skip' + pytest.skip() try: os.stat('tmp/poly.shp') @@ -98,21 +88,18 @@ def test_ogr2ogr_2(): gdaltest.runexternal(test_cli_utilities.get_ogr2ogr_path() + ' tmp/poly.shp ../ogr/data/poly.shp -sql "select * from poly"') ds = ogr.Open('tmp/poly.shp') - if ds is None or ds.GetLayer(0).GetFeatureCount() != 10: - return 'fail' + assert ds is not None and ds.GetLayer(0).GetFeatureCount() == 10 ds.Destroy() ogr.GetDriverByName('ESRI Shapefile').DeleteDataSource('tmp/poly.shp') - return 'success' - ############################################################################### # Test -spat def test_ogr2ogr_3(): if test_cli_utilities.get_ogr2ogr_path() is None: - return 'skip' + pytest.skip() try: os.stat('tmp/poly.shp') @@ -124,24 +111,20 @@ def test_ogr2ogr_3(): ds = ogr.Open('tmp/poly.shp') if ogrtest.have_geos(): - if ds is None or ds.GetLayer(0).GetFeatureCount() != 4: - return 'fail' + assert ds is not None and ds.GetLayer(0).GetFeatureCount() == 4 else: - if ds is None or ds.GetLayer(0).GetFeatureCount() != 5: - return 'fail' + assert ds is not None and ds.GetLayer(0).GetFeatureCount() == 5 ds.Destroy() ogr.GetDriverByName('ESRI Shapefile').DeleteDataSource('tmp/poly.shp') - return 'success' - ############################################################################### # Test -where def test_ogr2ogr_4(): if test_cli_utilities.get_ogr2ogr_path() is None: - return 'skip' + pytest.skip() try: os.stat('tmp/poly.shp') @@ -152,21 +135,18 @@ def test_ogr2ogr_4(): gdaltest.runexternal(test_cli_utilities.get_ogr2ogr_path() + ' tmp/poly.shp ../ogr/data/poly.shp -where "EAS_ID=171"') ds = ogr.Open('tmp/poly.shp') - if ds is None or ds.GetLayer(0).GetFeatureCount() != 1: - return 'fail' + assert ds is not None and ds.GetLayer(0).GetFeatureCount() == 1 ds.Destroy() ogr.GetDriverByName('ESRI Shapefile').DeleteDataSource('tmp/poly.shp') - return 'success' - ############################################################################### # Test -append def test_ogr2ogr_5(): if test_cli_utilities.get_ogr2ogr_path() is None: - return 'skip' + pytest.skip() try: os.stat('tmp/poly.shp') @@ -181,25 +161,18 @@ def test_ogr2ogr_5(): gdaltest.runexternal(test_cli_utilities.get_ogr2ogr_path() + ' -append -update tmp/poly.shp ../ogr/data/poly.shp') ds = ogr.Open('tmp/poly.shp') - if ds is None or ds.GetLayer(0).GetFeatureCount() != 40: - return 'fail' + assert ds is not None and ds.GetLayer(0).GetFeatureCount() == 40 feat10 = ds.GetLayer(0).GetFeature(10) - if feat10.GetFieldAsDouble('AREA') != 215229.266: - print(feat10.GetFieldAsDouble('AREA')) - gdaltest.post_reason('Did not get expected value for field AREA') - return 'fail' - if feat10.GetFieldAsString('PRFEDEA') != '35043411': - print(feat10.GetFieldAsString('PRFEDEA')) - gdaltest.post_reason('Did not get expected value for field PRFEDEA') - return 'fail' + assert feat10.GetFieldAsDouble('AREA') == 215229.266, \ + 'Did not get expected value for field AREA' + assert feat10.GetFieldAsString('PRFEDEA') == '35043411', \ + 'Did not get expected value for field PRFEDEA' ds.Destroy() ogr.GetDriverByName('ESRI Shapefile').DeleteDataSource('tmp/poly.shp') - return 'success' - ############################################################################### # Test -overwrite @@ -209,13 +182,13 @@ def test_ogr2ogr_6(): import ogr_pg if test_cli_utilities.get_ogr2ogr_path() is None: - return 'skip' + pytest.skip() if test_cli_utilities.get_ogrinfo_path() is None: - return 'skip' + pytest.skip() - ogr_pg.ogr_pg_1() + ogr_pg.test_ogr_pg_1() if gdaltest.pg_ds is None: - return 'skip' + pytest.skip() gdaltest.pg_ds.Destroy() gdaltest.runexternal(test_cli_utilities.get_ogrinfo_path() + ' PG:"' + gdaltest.pg_connection_string + '" -sql "DELLAYER:tpoly"') @@ -224,14 +197,11 @@ def test_ogr2ogr_6(): gdaltest.runexternal(test_cli_utilities.get_ogr2ogr_path() + ' -update -overwrite -f PostgreSQL PG:"' + gdaltest.pg_connection_string + '" ../ogr/data/poly.shp -nln tpoly') ds = ogr.Open('PG:' + gdaltest.pg_connection_string) - if ds is None or ds.GetLayerByName('tpoly').GetFeatureCount() != 10: - return 'fail' + assert ds is not None and ds.GetLayerByName('tpoly').GetFeatureCount() == 10 ds.Destroy() gdaltest.runexternal(test_cli_utilities.get_ogrinfo_path() + ' PG:"' + gdaltest.pg_connection_string + '" -sql "DELLAYER:tpoly"') - return 'success' - ############################################################################### # Test -gt @@ -241,13 +211,13 @@ def test_ogr2ogr_7(): import ogr_pg if test_cli_utilities.get_ogr2ogr_path() is None: - return 'skip' + pytest.skip() if test_cli_utilities.get_ogrinfo_path() is None: - return 'skip' + pytest.skip() - ogr_pg.ogr_pg_1() + ogr_pg.test_ogr_pg_1() if gdaltest.pg_ds is None: - return 'skip' + pytest.skip() gdaltest.pg_ds.Destroy() gdaltest.runexternal(test_cli_utilities.get_ogrinfo_path() + ' PG:"' + gdaltest.pg_connection_string + '" -sql "DELLAYER:tpoly"') @@ -255,21 +225,18 @@ def test_ogr2ogr_7(): gdaltest.runexternal(test_cli_utilities.get_ogr2ogr_path() + ' -f PostgreSQL PG:"' + gdaltest.pg_connection_string + '" ../ogr/data/poly.shp -nln tpoly -gt 1') ds = ogr.Open('PG:' + gdaltest.pg_connection_string) - if ds is None or ds.GetLayerByName('tpoly').GetFeatureCount() != 10: - return 'fail' + assert ds is not None and ds.GetLayerByName('tpoly').GetFeatureCount() == 10 ds.Destroy() gdaltest.runexternal(test_cli_utilities.get_ogrinfo_path() + ' PG:"' + gdaltest.pg_connection_string + '" -sql "DELLAYER:tpoly"') - return 'success' - ############################################################################### # Test -t_srs def test_ogr2ogr_8(): if test_cli_utilities.get_ogr2ogr_path() is None: - return 'skip' + pytest.skip() try: os.stat('tmp/poly.shp') @@ -280,21 +247,18 @@ def test_ogr2ogr_8(): gdaltest.runexternal(test_cli_utilities.get_ogr2ogr_path() + ' -t_srs EPSG:4326 tmp/poly.shp ../ogr/data/poly.shp') ds = ogr.Open('tmp/poly.shp') - if str(ds.GetLayer(0).GetSpatialRef()).find('1984') == -1: - return 'fail' + assert str(ds.GetLayer(0).GetSpatialRef()).find('1984') != -1 ds.Destroy() ogr.GetDriverByName('ESRI Shapefile').DeleteDataSource('tmp/poly.shp') - return 'success' - ############################################################################### # Test -a_srs def test_ogr2ogr_9(): if test_cli_utilities.get_ogr2ogr_path() is None: - return 'skip' + pytest.skip() try: os.stat('tmp/poly.shp') @@ -305,21 +269,18 @@ def test_ogr2ogr_9(): gdaltest.runexternal(test_cli_utilities.get_ogr2ogr_path() + ' -a_srs EPSG:4326 tmp/poly.shp ../ogr/data/poly.shp') ds = ogr.Open('tmp/poly.shp') - if str(ds.GetLayer(0).GetSpatialRef()).find('1984') == -1: - return 'fail' + assert str(ds.GetLayer(0).GetSpatialRef()).find('1984') != -1 ds.Destroy() ogr.GetDriverByName('ESRI Shapefile').DeleteDataSource('tmp/poly.shp') - return 'success' - ############################################################################### # Test -select def test_ogr2ogr_10(): if test_cli_utilities.get_ogr2ogr_path() is None: - return 'skip' + pytest.skip() try: os.stat('tmp/poly.shp') @@ -332,8 +293,7 @@ def test_ogr2ogr_10(): ds = ogr.Open('tmp/poly.shp') lyr = ds.GetLayer(0) - if lyr.GetLayerDefn().GetFieldCount() != 2: - return 'fail' + assert lyr.GetLayerDefn().GetFieldCount() == 2 feat = lyr.GetNextFeature() ret = 'success' if feat.GetFieldAsDouble('EAS_ID') != 168: @@ -357,7 +317,7 @@ def test_ogr2ogr_10(): def test_ogr2ogr_11(): if test_cli_utilities.get_ogr2ogr_path() is None: - return 'skip' + pytest.skip() try: os.stat('tmp/poly.shp') @@ -368,21 +328,18 @@ def test_ogr2ogr_11(): gdaltest.runexternal(test_cli_utilities.get_ogr2ogr_path() + ' -lco SHPT=POLYGONZ tmp/poly.shp ../ogr/data/poly.shp') ds = ogr.Open('tmp/poly.shp') - if ds.GetLayer(0).GetLayerDefn().GetGeomType() != ogr.wkbPolygon25D: - return 'fail' + assert ds.GetLayer(0).GetLayerDefn().GetGeomType() == ogr.wkbPolygon25D ds.Destroy() ogr.GetDriverByName('ESRI Shapefile').DeleteDataSource('tmp/poly.shp') - return 'success' - ############################################################################### # Test -nlt def test_ogr2ogr_12(): if test_cli_utilities.get_ogr2ogr_path() is None: - return 'skip' + pytest.skip() try: os.stat('tmp/poly.shp') @@ -393,21 +350,18 @@ def test_ogr2ogr_12(): gdaltest.runexternal(test_cli_utilities.get_ogr2ogr_path() + ' -nlt POLYGON25D tmp/poly.shp ../ogr/data/poly.shp') ds = ogr.Open('tmp/poly.shp') - if ds.GetLayer(0).GetLayerDefn().GetGeomType() != ogr.wkbPolygon25D: - return 'fail' + assert ds.GetLayer(0).GetLayerDefn().GetGeomType() == ogr.wkbPolygon25D ds.Destroy() ogr.GetDriverByName('ESRI Shapefile').DeleteDataSource('tmp/poly.shp') - return 'success' - ############################################################################### # Add explicit source layer name def test_ogr2ogr_13(): if test_cli_utilities.get_ogr2ogr_path() is None: - return 'skip' + pytest.skip() try: os.stat('tmp/poly.shp') @@ -418,21 +372,18 @@ def test_ogr2ogr_13(): gdaltest.runexternal(test_cli_utilities.get_ogr2ogr_path() + ' tmp/poly.shp ../ogr/data/poly.shp poly') ds = ogr.Open('tmp/poly.shp') - if ds is None or ds.GetLayer(0).GetFeatureCount() != 10: - return 'fail' + assert ds is not None and ds.GetLayer(0).GetFeatureCount() == 10 ds.Destroy() ogr.GetDriverByName('ESRI Shapefile').DeleteDataSource('tmp/poly.shp') - return 'success' - ############################################################################### # Test -segmentize def test_ogr2ogr_14(): if test_cli_utilities.get_ogr2ogr_path() is None: - return 'skip' + pytest.skip() try: os.stat('tmp/poly.shp') @@ -443,17 +394,13 @@ def test_ogr2ogr_14(): gdaltest.runexternal(test_cli_utilities.get_ogr2ogr_path() + ' -segmentize 100 tmp/poly.shp ../ogr/data/poly.shp poly') ds = ogr.Open('tmp/poly.shp') - if ds is None or ds.GetLayer(0).GetFeatureCount() != 10: - return 'fail' + assert ds is not None and ds.GetLayer(0).GetFeatureCount() == 10 feat = ds.GetLayer(0).GetNextFeature() - if feat.GetGeometryRef().GetGeometryRef(0).GetPointCount() != 36: - return 'fail' + assert feat.GetGeometryRef().GetGeometryRef(0).GetPointCount() == 36 ds.Destroy() ogr.GetDriverByName('ESRI Shapefile').DeleteDataSource('tmp/poly.shp') - return 'success' - ############################################################################### # Test -overwrite with a shapefile @@ -461,7 +408,7 @@ def test_ogr2ogr_14(): def test_ogr2ogr_15(): if test_cli_utilities.get_ogr2ogr_path() is None: - return 'skip' + pytest.skip() try: os.stat('tmp/poly.shp') @@ -472,20 +419,17 @@ def test_ogr2ogr_15(): gdaltest.runexternal(test_cli_utilities.get_ogr2ogr_path() + ' tmp/poly.shp ../ogr/data/poly.shp') ds = ogr.Open('tmp/poly.shp') - if ds is None or ds.GetLayer(0).GetFeatureCount() != 10: - return 'fail' + assert ds is not None and ds.GetLayer(0).GetFeatureCount() == 10 ds.Destroy() # Overwrite gdaltest.runexternal(test_cli_utilities.get_ogr2ogr_path() + ' -overwrite tmp ../ogr/data/poly.shp') ds = ogr.Open('tmp/poly.shp') - if ds is None or ds.GetLayer(0).GetFeatureCount() != 10: - return 'fail' + assert ds is not None and ds.GetLayer(0).GetFeatureCount() == 10 ds.Destroy() ogr.GetDriverByName('ESRI Shapefile').DeleteDataSource('tmp/poly.shp') - return 'success' ############################################################################### # Test -fid @@ -494,7 +438,7 @@ def test_ogr2ogr_15(): def test_ogr2ogr_16(): if test_cli_utilities.get_ogr2ogr_path() is None: - return 'skip' + pytest.skip() try: os.stat('tmp/poly.shp') @@ -506,17 +450,14 @@ def test_ogr2ogr_16(): src_ds = ogr.Open('../ogr/data/poly.shp') ds = ogr.Open('tmp/poly.shp') - if ds is None or ds.GetLayer(0).GetFeatureCount() != 1: - return 'fail' + assert ds is not None and ds.GetLayer(0).GetFeatureCount() == 1 src_feat = src_ds.GetLayer(0).GetFeature(8) feat = ds.GetLayer(0).GetNextFeature() - if feat.GetField("EAS_ID") != src_feat.GetField("EAS_ID"): - return 'fail' + assert feat.GetField("EAS_ID") == src_feat.GetField("EAS_ID") ds.Destroy() src_ds.Destroy() ogr.GetDriverByName('ESRI Shapefile').DeleteDataSource('tmp/poly.shp') - return 'success' ############################################################################### # Test -progress @@ -525,7 +466,7 @@ def test_ogr2ogr_16(): def test_ogr2ogr_17(): if test_cli_utilities.get_ogr2ogr_path() is None: - return 'skip' + pytest.skip() try: os.stat('tmp/poly.shp') @@ -534,16 +475,13 @@ def test_ogr2ogr_17(): pass ret = gdaltest.runexternal(test_cli_utilities.get_ogr2ogr_path() + ' -progress tmp/poly.shp ../ogr/data/poly.shp') - if ret.find('0...10...20...30...40...50...60...70...80...90...100 - done.') == -1: - return 'fail' + assert ret.find('0...10...20...30...40...50...60...70...80...90...100 - done.') != -1 ds = ogr.Open('tmp/poly.shp') - if ds is None or ds.GetLayer(0).GetFeatureCount() != 10: - return 'fail' + assert ds is not None and ds.GetLayer(0).GetFeatureCount() == 10 ds.Destroy() ogr.GetDriverByName('ESRI Shapefile').DeleteDataSource('tmp/poly.shp') - return 'success' ############################################################################### # Test -wrapdateline @@ -552,10 +490,10 @@ def test_ogr2ogr_17(): def test_ogr2ogr_18(): if test_cli_utilities.get_ogr2ogr_path() is None: - return 'skip' + pytest.skip() if not ogrtest.have_geos(): - return 'skip' + pytest.skip() try: os.stat('tmp/wrapdateline_src.shp') @@ -598,9 +536,8 @@ def test_ogr2ogr_18(): ogr.GetDriverByName('ESRI Shapefile').DeleteDataSource('tmp/wrapdateline_dst.shp') if ret == 0: - return 'success' - print(got_wkt) - return 'fail' + return + pytest.fail(got_wkt) ############################################################################### # Test -clipsrc @@ -608,10 +545,10 @@ def test_ogr2ogr_18(): def test_ogr2ogr_19(): if test_cli_utilities.get_ogr2ogr_path() is None: - return 'skip' + pytest.skip() if not ogrtest.have_geos(): - return 'skip' + pytest.skip() try: os.stat('tmp/poly.shp') @@ -622,20 +559,15 @@ def test_ogr2ogr_19(): gdaltest.runexternal(test_cli_utilities.get_ogr2ogr_path() + ' tmp/poly.shp ../ogr/data/poly.shp -clipsrc spat_extent -spat 479609 4764629 479764 4764817') ds = ogr.Open('tmp/poly.shp') - if ds is None or ds.GetLayer(0).GetFeatureCount() != 4: - return 'fail' + assert ds is not None and ds.GetLayer(0).GetFeatureCount() == 4 - if ds.GetLayer(0).GetExtent() != (479609, 479764, 4764629, 4764817): - print(ds.GetLayer(0).GetExtent()) - gdaltest.post_reason('unexpected extent') - return 'fail' + assert ds.GetLayer(0).GetExtent() == (479609, 479764, 4764629, 4764817), \ + 'unexpected extent' ds.Destroy() ogr.GetDriverByName('ESRI Shapefile').DeleteDataSource('tmp/poly.shp') - return 'success' - ############################################################################### # Test correct remap of fields when laundering to Shapefile format # Test that the data is going into the right field @@ -644,7 +576,7 @@ def test_ogr2ogr_19(): def test_ogr2ogr_20(): if test_cli_utilities.get_ogr2ogr_path() is None: - return 'skip' + pytest.skip() expected_fields = ['a', 'A_1', @@ -681,14 +613,12 @@ def test_ogr2ogr_20(): ds = ogr.Open('tmp/Fields.dbf') - if ds is None: - return 'fail' + assert ds is not None layer_defn = ds.GetLayer(0).GetLayerDefn() if layer_defn.GetFieldCount() != 15: - gdaltest.post_reason('Unexpected field count: ' + str(ds.GetLayer(0).GetLayerDefn().GetFieldCount())) ds.Destroy() ogr.GetDriverByName('ESRI Shapefile').DeleteDataSource('tmp/Fields.dbf') - return 'fail' + pytest.fail('Unexpected field count: ' + str(ds.GetLayer(0).GetLayerDefn().GetFieldCount())) error_occurred = False feat = ds.GetLayer(0).GetNextFeature() @@ -703,10 +633,7 @@ def test_ogr2ogr_20(): ds.Destroy() ogr.GetDriverByName('ESRI Shapefile').DeleteDataSource('tmp/Fields.dbf') - if error_occurred: - return 'fail' - - return 'success' + assert not error_occurred ############################################################################### # Test ogr2ogr when the output driver has already created the fields @@ -715,7 +642,7 @@ def test_ogr2ogr_20(): def test_ogr2ogr_21(): if test_cli_utilities.get_ogr2ogr_path() is None: - return 'skip' + pytest.skip() try: os.remove('tmp/testogr2ogr21.gtm') @@ -727,96 +654,84 @@ def test_ogr2ogr_21(): '-sql "SELECT comment, name FROM dataforogr2ogr21" -nlt POINT') ds = ogr.Open('tmp/testogr2ogr21.gtm') - if ds is None: - return 'fail' + assert ds is not None ds.GetLayer(0).GetLayerDefn() lyr = ds.GetLayer(0) feat = lyr.GetNextFeature() if feat.GetFieldAsString('name') != 'NAME' or \ feat.GetFieldAsString('comment') != 'COMMENT': - print(feat.GetFieldAsString('name')) print(feat.GetFieldAsString('comment')) ds.Destroy() os.remove('tmp/testogr2ogr21.gtm') - return 'fail' + pytest.fail(feat.GetFieldAsString('name')) ds.Destroy() os.remove('tmp/testogr2ogr21.gtm') - return 'success' - ############################################################################### # Test ogr2ogr when the output driver delays the destination layer defn creation (#3384) def test_ogr2ogr_22(): if test_cli_utilities.get_ogr2ogr_path() is None: - return 'skip' + pytest.skip() gdaltest.runexternal(test_cli_utilities.get_ogr2ogr_path() + ' -f "MapInfo File" tmp/testogr2ogr22.mif data/dataforogr2ogr21.csv ' + '-sql "SELECT comment, name FROM dataforogr2ogr21" -nlt POINT') ds = ogr.Open('tmp/testogr2ogr22.mif') - if ds is None: - return 'fail' + assert ds is not None ds.GetLayer(0).GetLayerDefn() lyr = ds.GetLayer(0) feat = lyr.GetNextFeature() if feat.GetFieldAsString('name') != 'NAME' or \ feat.GetFieldAsString('comment') != 'COMMENT': - print(feat.GetFieldAsString('name')) print(feat.GetFieldAsString('comment')) ds.Destroy() ogr.GetDriverByName('MapInfo File').DeleteDataSource('tmp/testogr2ogr22.mif') - return 'fail' + pytest.fail(feat.GetFieldAsString('name')) ds.Destroy() ogr.GetDriverByName('MapInfo File').DeleteDataSource('tmp/testogr2ogr22.mif') - return 'success' - ############################################################################### # Same as previous but with -select def test_ogr2ogr_23(): if test_cli_utilities.get_ogr2ogr_path() is None: - return 'skip' + pytest.skip() gdaltest.runexternal(test_cli_utilities.get_ogr2ogr_path() + ' -f "MapInfo File" tmp/testogr2ogr23.mif data/dataforogr2ogr21.csv ' + '-sql "SELECT comment, name FROM dataforogr2ogr21" -select comment,name -nlt POINT') ds = ogr.Open('tmp/testogr2ogr23.mif') - if ds is None: - return 'fail' + assert ds is not None ds.GetLayer(0).GetLayerDefn() lyr = ds.GetLayer(0) feat = lyr.GetNextFeature() if feat.GetFieldAsString('name') != 'NAME' or \ feat.GetFieldAsString('comment') != 'COMMENT': - print(feat.GetFieldAsString('name')) print(feat.GetFieldAsString('comment')) ds.Destroy() ogr.GetDriverByName('MapInfo File').DeleteDataSource('tmp/testogr2ogr23.mif') - return 'fail' + pytest.fail(feat.GetFieldAsString('name')) ds.Destroy() ogr.GetDriverByName('MapInfo File').DeleteDataSource('tmp/testogr2ogr23.mif') - return 'success' - ############################################################################### # Test -clipsrc with WKT geometry (#3530) def test_ogr2ogr_24(): if test_cli_utilities.get_ogr2ogr_path() is None: - return 'skip' + pytest.skip() if not ogrtest.have_geos(): - return 'skip' + pytest.skip() try: os.stat('tmp/poly.shp') @@ -827,30 +742,25 @@ def test_ogr2ogr_24(): gdaltest.runexternal(test_cli_utilities.get_ogr2ogr_path() + ' tmp/poly.shp ../ogr/data/poly.shp -clipsrc "POLYGON((479609 4764629,479609 4764817,479764 4764817,479764 4764629,479609 4764629))"') ds = ogr.Open('tmp/poly.shp') - if ds is None or ds.GetLayer(0).GetFeatureCount() != 4: - return 'fail' + assert ds is not None and ds.GetLayer(0).GetFeatureCount() == 4 - if ds.GetLayer(0).GetExtent() != (479609, 479764, 4764629, 4764817): - print(ds.GetLayer(0).GetExtent()) - gdaltest.post_reason('unexpected extent') - return 'fail' + assert ds.GetLayer(0).GetExtent() == (479609, 479764, 4764629, 4764817), \ + 'unexpected extent' ds.Destroy() ogr.GetDriverByName('ESRI Shapefile').DeleteDataSource('tmp/poly.shp') - return 'success' - ############################################################################### # Test -clipsrc with clip from external datasource def test_ogr2ogr_25(): if test_cli_utilities.get_ogr2ogr_path() is None: - return 'skip' + pytest.skip() if not ogrtest.have_geos(): - return 'skip' + pytest.skip() try: os.stat('tmp/poly.shp') @@ -866,31 +776,26 @@ def test_ogr2ogr_25(): gdaltest.runexternal(test_cli_utilities.get_ogr2ogr_path() + ' tmp/poly.shp ../ogr/data/poly.shp -clipsrc tmp/clip.csv -clipsrcwhere foo=\'foo\'') ds = ogr.Open('tmp/poly.shp') - if ds is None or ds.GetLayer(0).GetFeatureCount() != 4: - return 'fail' + assert ds is not None and ds.GetLayer(0).GetFeatureCount() == 4 - if ds.GetLayer(0).GetExtent() != (479609, 479764, 4764629, 4764817): - print(ds.GetLayer(0).GetExtent()) - gdaltest.post_reason('unexpected extent') - return 'fail' + assert ds.GetLayer(0).GetExtent() == (479609, 479764, 4764629, 4764817), \ + 'unexpected extent' ds.Destroy() ogr.GetDriverByName('ESRI Shapefile').DeleteDataSource('tmp/poly.shp') os.remove('tmp/clip.csv') - return 'success' - ############################################################################### # Test -clipdst with WKT geometry (#3530) def test_ogr2ogr_26(): if test_cli_utilities.get_ogr2ogr_path() is None: - return 'skip' + pytest.skip() if not ogrtest.have_geos(): - return 'skip' + pytest.skip() try: os.stat('tmp/poly.shp') @@ -901,30 +806,25 @@ def test_ogr2ogr_26(): gdaltest.runexternal(test_cli_utilities.get_ogr2ogr_path() + ' tmp/poly.shp ../ogr/data/poly.shp -clipdst "POLYGON((479609 4764629,479609 4764817,479764 4764817,479764 4764629,479609 4764629))"') ds = ogr.Open('tmp/poly.shp') - if ds is None or ds.GetLayer(0).GetFeatureCount() != 4: - return 'fail' + assert ds is not None and ds.GetLayer(0).GetFeatureCount() == 4 - if ds.GetLayer(0).GetExtent() != (479609, 479764, 4764629, 4764817): - print(ds.GetLayer(0).GetExtent()) - gdaltest.post_reason('unexpected extent') - return 'fail' + assert ds.GetLayer(0).GetExtent() == (479609, 479764, 4764629, 4764817), \ + 'unexpected extent' ds.Destroy() ogr.GetDriverByName('ESRI Shapefile').DeleteDataSource('tmp/poly.shp') - return 'success' - ############################################################################### # Test -clipdst with clip from external datasource def test_ogr2ogr_27(): if test_cli_utilities.get_ogr2ogr_path() is None: - return 'skip' + pytest.skip() if not ogrtest.have_geos(): - return 'skip' + pytest.skip() try: os.stat('tmp/poly.shp') @@ -940,21 +840,16 @@ def test_ogr2ogr_27(): gdaltest.runexternal(test_cli_utilities.get_ogr2ogr_path() + ' -nlt MULTIPOLYGON tmp/poly.shp ../ogr/data/poly.shp -clipdst tmp/clip.csv -clipdstsql "SELECT * from clip"') ds = ogr.Open('tmp/poly.shp') - if ds is None or ds.GetLayer(0).GetFeatureCount() != 4: - return 'fail' + assert ds is not None and ds.GetLayer(0).GetFeatureCount() == 4 - if ds.GetLayer(0).GetExtent() != (479609, 479764, 4764629, 4764817): - print(ds.GetLayer(0).GetExtent()) - gdaltest.post_reason('unexpected extent') - return 'fail' + assert ds.GetLayer(0).GetExtent() == (479609, 479764, 4764629, 4764817), \ + 'unexpected extent' ds.Destroy() ogr.GetDriverByName('ESRI Shapefile').DeleteDataSource('tmp/poly.shp') os.remove('tmp/clip.csv') - return 'success' - ############################################################################### # Test -wrapdateline on linestrings @@ -962,7 +857,7 @@ def test_ogr2ogr_27(): def test_ogr2ogr_28(): if test_cli_utilities.get_ogr2ogr_path() is None: - return 'skip' + pytest.skip() try: os.stat('tmp/wrapdateline_src.shp') @@ -1002,7 +897,7 @@ def test_ogr2ogr_28(): ogr.GetDriverByName('ESRI Shapefile').DeleteDataSource('tmp/wrapdateline_src.shp') ogr.GetDriverByName('ESRI Shapefile').DeleteDataSource('tmp/wrapdateline_dst.shp') - return 'success' if ret == 0 else 'fail' + assert ret == 0 ############################################################################### # Test -wrapdateline on polygons @@ -1011,10 +906,10 @@ def test_ogr2ogr_28(): def test_ogr2ogr_29(): if test_cli_utilities.get_ogr2ogr_path() is None: - return 'skip' + pytest.skip() if not ogrtest.have_geos(): - return 'skip' + pytest.skip() for i in range(2): try: @@ -1063,11 +958,9 @@ def test_ogr2ogr_29(): ogr.GetDriverByName('ESRI Shapefile').DeleteDataSource('tmp/wrapdateline_src.shp') ogr.GetDriverByName('ESRI Shapefile').DeleteDataSource('tmp/wrapdateline_dst.shp') - if ret != 0: - return 'fail' - - return 'success' + assert ret == 0 + ############################################################################### # Test -splitlistfields option @@ -1075,19 +968,18 @@ def test_ogr2ogr_29(): def test_ogr2ogr_30(): if test_cli_utilities.get_ogr2ogr_path() is None: - return 'skip' + pytest.skip() ds = ogr.Open('../ogr/data/testlistfields.gml') if ds is None: - return 'skip' + pytest.skip() ds = None gdaltest.runexternal(test_cli_utilities.get_ogr2ogr_path() + ' -splitlistfields tmp/test_ogr2ogr_30.dbf ../ogr/data/testlistfields.gml') gdal.Unlink('../ogr/data//testlistfields.gfs') ds = ogr.Open('tmp/test_ogr2ogr_30.dbf') - if ds is None: - return 'fail' + assert ds is not None lyr = ds.GetLayer(0) feat = lyr.GetNextFeature() @@ -1098,15 +990,12 @@ def test_ogr2ogr_30(): feat.GetField('attrib32') != 5 or \ feat.GetField('attrib41') != 6.1 or \ feat.GetField('attrib42') != 7.1: - gdaltest.post_reason('did not get expected attribs') feat.DumpReadable() - return 'fail' + pytest.fail('did not get expected attribs') ds = None ogr.GetDriverByName('ESRI Shapefile').DeleteDataSource('tmp/test_ogr2ogr_30.dbf') - return 'success' - ############################################################################### # Test that -overwrite work if the output file doesn't yet exist (#3825) @@ -1114,7 +1003,7 @@ def test_ogr2ogr_30(): def test_ogr2ogr_31(): if test_cli_utilities.get_ogr2ogr_path() is None: - return 'skip' + pytest.skip() try: os.stat('tmp/poly.shp') @@ -1125,12 +1014,10 @@ def test_ogr2ogr_31(): gdaltest.runexternal(test_cli_utilities.get_ogr2ogr_path() + ' -overwrite tmp/poly.shp ../ogr/data/poly.shp') ds = ogr.Open('tmp/poly.shp') - if ds is None or ds.GetLayer(0).GetFeatureCount() != 10: - return 'fail' + assert ds is not None and ds.GetLayer(0).GetFeatureCount() == 10 ds.Destroy() ogr.GetDriverByName('ESRI Shapefile').DeleteDataSource('tmp/poly.shp') - return 'success' ############################################################################### # Test that -append/-overwrite to a single-file shapefile work without specifying -nln @@ -1139,7 +1026,7 @@ def test_ogr2ogr_31(): def test_ogr2ogr_32(): if test_cli_utilities.get_ogr2ogr_path() is None: - return 'skip' + pytest.skip() try: os.stat('tmp/test_ogr2ogr_32.shp') @@ -1151,21 +1038,17 @@ def test_ogr2ogr_32(): gdaltest.runexternal(test_cli_utilities.get_ogr2ogr_path() + ' -append tmp/test_ogr2ogr_32.shp ../ogr/data/poly.shp') ds = ogr.Open('tmp/test_ogr2ogr_32.shp') - if ds is None or ds.GetLayer(0).GetFeatureCount() != 20: - gdaltest.post_reason('-append failed') - return 'fail' + assert ds is not None and ds.GetLayer(0).GetFeatureCount() == 20, '-append failed' ds = None gdaltest.runexternal(test_cli_utilities.get_ogr2ogr_path() + ' -overwrite tmp/test_ogr2ogr_32.shp ../ogr/data/poly.shp') ds = ogr.Open('tmp/test_ogr2ogr_32.shp') - if ds is None or ds.GetLayer(0).GetFeatureCount() != 10: - gdaltest.post_reason('-overwrite failed') - return 'fail' + assert ds is not None and ds.GetLayer(0).GetFeatureCount() == 10, \ + '-overwrite failed' ds = None ogr.GetDriverByName('ESRI Shapefile').DeleteDataSource('tmp/test_ogr2ogr_32.shp') - return 'success' ############################################################################### # Test -explodecollections @@ -1174,7 +1057,7 @@ def test_ogr2ogr_32(): def test_ogr2ogr_33(): if test_cli_utilities.get_ogr2ogr_path() is None: - return 'skip' + pytest.skip() try: os.stat('tmp/test_ogr2ogr_33_src.csv') @@ -1198,40 +1081,36 @@ def test_ogr2ogr_33(): ds = ogr.Open('tmp/test_ogr2ogr_33_dst.shp') lyr = ds.GetLayer(0) - if lyr.GetFeatureCount() != 3: - gdaltest.post_reason('-explodecollections failed') - print(lyr.GetFeatureCount()) - return 'fail' + assert lyr.GetFeatureCount() == 3, '-explodecollections failed' feat = lyr.GetFeature(0) if feat.GetField("foo") != 'bar': feat.DumpReadable() - return 'fail' + pytest.fail() if feat.GetGeometryRef().ExportToWkt() != 'POLYGON ((10 10,10 11,11 11,11 10,10 10))': feat.DumpReadable() - return 'fail' + pytest.fail() feat = lyr.GetFeature(1) if feat.GetField("foo") != 'bar': feat.DumpReadable() - return 'fail' + pytest.fail() if feat.GetGeometryRef().ExportToWkt() != 'POLYGON ((100 100,100 200,200 200,200 100,100 100),(125 125,175 125,175 175,125 175,125 125))': feat.DumpReadable() - return 'fail' + pytest.fail() feat = lyr.GetFeature(2) if feat.GetField("foo") != 'baz': feat.DumpReadable() - return 'fail' + pytest.fail() if feat.GetGeometryRef().ExportToWkt() != 'POLYGON ((0 0,0 1,1 1,1 0,0 0))': feat.DumpReadable() - return 'fail' + pytest.fail() ds = None ogr.GetDriverByName('CSV').DeleteDataSource('tmp/test_ogr2ogr_33_src.csv') ogr.GetDriverByName('ESRI Shapefile').DeleteDataSource('tmp/test_ogr2ogr_33_dst.shp') - return 'success' ############################################################################### # Test 'ogr2ogr someDirThatDoesNotExist src.shp -nln someDirThatDoesNotExist' @@ -1242,7 +1121,7 @@ def test_ogr2ogr_33(): def test_ogr2ogr_34(): if test_cli_utilities.get_ogr2ogr_path() is None: - return 'skip' + pytest.skip() try: os.stat('tmp/test_ogr2ogr_34_dir') @@ -1253,29 +1132,24 @@ def test_ogr2ogr_34(): gdaltest.runexternal(test_cli_utilities.get_ogr2ogr_path() + ' tmp/test_ogr2ogr_34_dir ../ogr/data/poly.shp -nln test_ogr2ogr_34_dir') ds = ogr.Open('tmp/test_ogr2ogr_34_dir/test_ogr2ogr_34_dir.shp') - if ds is None or ds.GetLayer(0).GetFeatureCount() != 10: - gdaltest.post_reason('initial shapefile creation failed') - return 'fail' + assert ds is not None and ds.GetLayer(0).GetFeatureCount() == 10, \ + 'initial shapefile creation failed' ds = None gdaltest.runexternal(test_cli_utilities.get_ogr2ogr_path() + ' -append tmp/test_ogr2ogr_34_dir ../ogr/data/poly.shp -nln test_ogr2ogr_34_dir') ds = ogr.Open('tmp/test_ogr2ogr_34_dir/test_ogr2ogr_34_dir.shp') - if ds is None or ds.GetLayer(0).GetFeatureCount() != 20: - gdaltest.post_reason('-append failed') - return 'fail' + assert ds is not None and ds.GetLayer(0).GetFeatureCount() == 20, '-append failed' ds = None gdaltest.runexternal(test_cli_utilities.get_ogr2ogr_path() + ' -overwrite tmp/test_ogr2ogr_34_dir ../ogr/data/poly.shp -nln test_ogr2ogr_34_dir') ds = ogr.Open('tmp/test_ogr2ogr_34_dir/test_ogr2ogr_34_dir.shp') - if ds is None or ds.GetLayer(0).GetFeatureCount() != 10: - gdaltest.post_reason('-overwrite failed') - return 'fail' + assert ds is not None and ds.GetLayer(0).GetFeatureCount() == 10, \ + '-overwrite failed' ds = None ogr.GetDriverByName('ESRI Shapefile').DeleteDataSource('tmp/test_ogr2ogr_34_dir') - return 'success' ############################################################################### # Test 'ogr2ogr someDirThatDoesNotExist src.shp' @@ -1284,7 +1158,7 @@ def test_ogr2ogr_34(): def test_ogr2ogr_35(): if test_cli_utilities.get_ogr2ogr_path() is None: - return 'skip' + pytest.skip() try: os.stat('tmp/test_ogr2ogr_35_dir') @@ -1295,29 +1169,24 @@ def test_ogr2ogr_35(): gdaltest.runexternal(test_cli_utilities.get_ogr2ogr_path() + ' tmp/test_ogr2ogr_35_dir ../ogr/data/poly.shp ') ds = ogr.Open('tmp/test_ogr2ogr_35_dir/poly.shp') - if ds is None or ds.GetLayer(0).GetFeatureCount() != 10: - gdaltest.post_reason('initial shapefile creation failed') - return 'fail' + assert ds is not None and ds.GetLayer(0).GetFeatureCount() == 10, \ + 'initial shapefile creation failed' ds = None gdaltest.runexternal(test_cli_utilities.get_ogr2ogr_path() + ' -append tmp/test_ogr2ogr_35_dir ../ogr/data/poly.shp') ds = ogr.Open('tmp/test_ogr2ogr_35_dir/poly.shp') - if ds is None or ds.GetLayer(0).GetFeatureCount() != 20: - gdaltest.post_reason('-append failed') - return 'fail' + assert ds is not None and ds.GetLayer(0).GetFeatureCount() == 20, '-append failed' ds = None gdaltest.runexternal(test_cli_utilities.get_ogr2ogr_path() + ' -overwrite tmp/test_ogr2ogr_35_dir ../ogr/data/poly.shp') ds = ogr.Open('tmp/test_ogr2ogr_35_dir/poly.shp') - if ds is None or ds.GetLayer(0).GetFeatureCount() != 10: - gdaltest.post_reason('-overwrite failed') - return 'fail' + assert ds is not None and ds.GetLayer(0).GetFeatureCount() == 10, \ + '-overwrite failed' ds = None ogr.GetDriverByName('ESRI Shapefile').DeleteDataSource('tmp/test_ogr2ogr_35_dir') - return 'success' ############################################################################### # Test ogr2ogr -zfield @@ -1326,7 +1195,7 @@ def test_ogr2ogr_35(): def test_ogr2ogr_36(): if test_cli_utilities.get_ogr2ogr_path() is None: - return 'skip' + pytest.skip() try: os.stat('tmp/test_ogr2ogr_36.shp') @@ -1343,10 +1212,7 @@ def test_ogr2ogr_36(): ogr.GetDriverByName('ESRI Shapefile').DeleteDataSource('tmp/test_ogr2ogr_36.shp') - if wkt.find(' 168,') == -1: - return 'fail' - - return 'success' + assert wkt.find(' 168,') != -1 ############################################################################### # Test 'ogr2ogr someDirThatDoesNotExist.shp dataSourceWithMultipleLayer' @@ -1355,7 +1221,7 @@ def test_ogr2ogr_36(): def test_ogr2ogr_37(): if test_cli_utilities.get_ogr2ogr_path() is None: - return 'skip' + pytest.skip() try: os.stat('tmp/test_ogr2ogr_37_dir.shp') @@ -1377,15 +1243,12 @@ def test_ogr2ogr_37(): gdaltest.runexternal(test_cli_utilities.get_ogr2ogr_path() + ' tmp/test_ogr2ogr_37_dir.shp tmp/test_ogr2ogr_37_src') ds = ogr.Open('tmp/test_ogr2ogr_37_dir.shp') - if ds is None or ds.GetLayerCount() != 2: - return 'fail' + assert ds is not None and ds.GetLayerCount() == 2 ds = None ogr.GetDriverByName('ESRI Shapefile').DeleteDataSource('tmp/test_ogr2ogr_37_src') ogr.GetDriverByName('ESRI Shapefile').DeleteDataSource('tmp/test_ogr2ogr_37_dir.shp') - return 'success' - ############################################################################### # Test that we take into account the fields by the where clause when combining # -select and -where (#4015) @@ -1394,7 +1257,7 @@ def test_ogr2ogr_37(): def test_ogr2ogr_38(): if test_cli_utilities.get_ogr2ogr_path() is None: - return 'skip' + pytest.skip() try: os.stat('tmp/test_ogr2ogr_38.shp') @@ -1407,14 +1270,11 @@ def test_ogr2ogr_38(): ds = ogr.Open('tmp/test_ogr2ogr_38.shp') lyr = ds.GetLayer(0) feat = lyr.GetNextFeature() - if feat is None: - return 'fail' + assert feat is not None ds = None ogr.GetDriverByName('ESRI Shapefile').DeleteDataSource('tmp/test_ogr2ogr_38.shp') - return 'success' - ############################################################################### # Test 'ogr2ogr someDirThatDoesNotExist.shp dataSourceWithMultipleLayer -sql "select * from alayer"' (#4268) @@ -1422,7 +1282,7 @@ def test_ogr2ogr_38(): def test_ogr2ogr_39(): if test_cli_utilities.get_ogr2ogr_path() is None: - return 'skip' + pytest.skip() try: os.stat('tmp/test_ogr2ogr_39_dir.shp') @@ -1444,15 +1304,12 @@ def test_ogr2ogr_39(): gdaltest.runexternal(test_cli_utilities.get_ogr2ogr_path() + ' tmp/test_ogr2ogr_39.shp tmp/test_ogr2ogr_39_src -sql "select * from poly"') ds = ogr.Open('tmp/test_ogr2ogr_39.shp') - if ds is None or ds.GetLayerCount() != 1: - return 'fail' + assert ds is not None and ds.GetLayerCount() == 1 ds = None ogr.GetDriverByName('ESRI Shapefile').DeleteDataSource('tmp/test_ogr2ogr_39_src') ogr.GetDriverByName('ESRI Shapefile').DeleteDataSource('tmp/test_ogr2ogr_39.shp') - return 'success' - ############################################################################### # Test 'ogr2ogr -update asqlite.db asqlite.db layersrc -nln layerdst' (#4270) @@ -1460,11 +1317,11 @@ def test_ogr2ogr_39(): def test_ogr2ogr_40(): if test_cli_utilities.get_ogr2ogr_path() is None: - return 'skip' + pytest.skip() drv = ogr.GetDriverByName('SQLite') if drv is None: - return 'skip' + pytest.skip() try: ogr.GetDriverByName('SQLite').DeleteDataSource('tmp/test_ogr2ogr_40.db') @@ -1476,14 +1333,11 @@ def test_ogr2ogr_40(): ds = ogr.Open('tmp/test_ogr2ogr_40.db') lyr = ds.GetLayerByName('poly2') - if lyr.GetFeatureCount() != 10: - return 'fail' + assert lyr.GetFeatureCount() == 10 ds = None ogr.GetDriverByName('SQLite').DeleteDataSource('tmp/test_ogr2ogr_40.db') - return 'success' - ############################################################################### # Test 'ogr2ogr -update PG:xxxx PG:xxxx layersrc -nln layerdst' (#4270) @@ -1492,11 +1346,11 @@ def test_ogr2ogr_41(): import ogr_pg if test_cli_utilities.get_ogr2ogr_path() is None: - return 'skip' + pytest.skip() - ogr_pg.ogr_pg_1() + ogr_pg.test_ogr_pg_1() if gdaltest.pg_ds is None: - return 'skip' + pytest.skip() gdaltest.pg_ds.Destroy() ds = ogr.Open('PG:' + gdaltest.pg_connection_string) @@ -1518,14 +1372,11 @@ def test_ogr2ogr_41(): ds = ogr.Open('PG:' + gdaltest.pg_connection_string) lyr = ds.GetLayerByName('test_ogr2ogr_41_target') - if lyr.GetFeatureCount() != 501: - return 'fail' + assert lyr.GetFeatureCount() == 501 ds.ExecuteSQL('DELLAYER:test_ogr2ogr_41_src') ds.ExecuteSQL('DELLAYER:test_ogr2ogr_41_target') ds = None - return 'success' - ############################################################################### # Test combination of -select and -where FID=xx (#4500) @@ -1533,7 +1384,7 @@ def test_ogr2ogr_41(): def test_ogr2ogr_42(): if test_cli_utilities.get_ogr2ogr_path() is None: - return 'skip' + pytest.skip() try: os.stat('tmp/test_ogr2ogr_42.shp') @@ -1545,14 +1396,11 @@ def test_ogr2ogr_42(): ds = ogr.Open('tmp/test_ogr2ogr_42.shp') lyr = ds.GetLayerByIndex(0) - if lyr.GetFeatureCount() != 1: - return 'fail' + assert lyr.GetFeatureCount() == 1 ds = None ogr.GetDriverByName('ESRI Shapefile').DeleteDataSource('tmp/test_ogr2ogr_42.shp') - return 'success' - ############################################################################### # Test -dim 3 and -dim 2 @@ -1560,7 +1408,7 @@ def test_ogr2ogr_42(): def test_ogr2ogr_43(): if test_cli_utilities.get_ogr2ogr_path() is None: - return 'skip' + pytest.skip() try: os.stat('tmp/test_ogr2ogr_43_3d.shp') @@ -1572,8 +1420,7 @@ def test_ogr2ogr_43(): ds = ogr.Open('tmp/test_ogr2ogr_43_3d.shp') lyr = ds.GetLayerByIndex(0) - if lyr.GetGeomType() != ogr.wkbPolygon25D: - return 'fail' + assert lyr.GetGeomType() == ogr.wkbPolygon25D ds = None try: @@ -1586,15 +1433,12 @@ def test_ogr2ogr_43(): ds = ogr.Open('tmp/test_ogr2ogr_43_2d.shp') lyr = ds.GetLayerByIndex(0) - if lyr.GetGeomType() != ogr.wkbPolygon: - return 'fail' + assert lyr.GetGeomType() == ogr.wkbPolygon ds = None ogr.GetDriverByName('ESRI Shapefile').DeleteDataSource('tmp/test_ogr2ogr_43_2d.shp') ogr.GetDriverByName('ESRI Shapefile').DeleteDataSource('tmp/test_ogr2ogr_43_3d.shp') - return 'success' - ############################################################################### # Test -nlt PROMOTE_TO_MULTI for polygon/multipolygon @@ -1602,7 +1446,7 @@ def test_ogr2ogr_43(): def test_ogr2ogr_44(): if test_cli_utilities.get_ogr2ogr_path() is None: - return 'skip' + pytest.skip() try: os.stat('tmp/test_ogr2ogr_44_src.shp') @@ -1629,26 +1473,18 @@ def test_ogr2ogr_44(): data = f.read() f.close() - if data.find('type="gml:MultiPolygonPropertyType"') == -1: - gdaltest.post_reason('failure') - print(data) - return 'fail' + assert data.find('type="gml:MultiPolygonPropertyType"') != -1 f = open('tmp/test_ogr2ogr_44.gml') data = f.read() f.close() - if data.find('<ogr:geometryProperty><gml:MultiPolygon><gml:polygonMember><gml:Polygon><gml:outerBoundaryIs><gml:LinearRing><gml:coordinates>0,0 0,1 1,1 0,0</gml:coordinates></gml:LinearRing></gml:outerBoundaryIs></gml:Polygon></gml:polygonMember></gml:MultiPolygon></ogr:geometryProperty>') == -1: - gdaltest.post_reason('failure') - print(data) - return 'fail' + assert data.find('<ogr:geometryProperty><gml:MultiPolygon><gml:polygonMember><gml:Polygon><gml:outerBoundaryIs><gml:LinearRing><gml:coordinates>0,0 0,1 1,1 0,0</gml:coordinates></gml:LinearRing></gml:outerBoundaryIs></gml:Polygon></gml:polygonMember></gml:MultiPolygon></ogr:geometryProperty>') != -1 ogr.GetDriverByName('ESRI Shapefile').DeleteDataSource('tmp/test_ogr2ogr_44_src.shp') os.unlink('tmp/test_ogr2ogr_44.gml') os.unlink('tmp/test_ogr2ogr_44.xsd') - return 'success' - ############################################################################### # Test -nlt PROMOTE_TO_MULTI for linestring/multilinestring @@ -1656,7 +1492,7 @@ def test_ogr2ogr_44(): def test_ogr2ogr_45(): if test_cli_utilities.get_ogr2ogr_path() is None: - return 'skip' + pytest.skip() try: os.stat('tmp/test_ogr2ogr_45_src.shp') @@ -1683,26 +1519,18 @@ def test_ogr2ogr_45(): data = f.read() f.close() - if data.find('type="gml:MultiLineStringPropertyType"') == -1: - gdaltest.post_reason('failure') - print(data) - return 'fail' + assert data.find('type="gml:MultiLineStringPropertyType"') != -1 f = open('tmp/test_ogr2ogr_45.gml') data = f.read() f.close() - if data.find('<ogr:geometryProperty><gml:MultiLineString><gml:lineStringMember><gml:LineString><gml:coordinates>0,0 0,1 1,1 0,0</gml:coordinates></gml:LineString></gml:lineStringMember></gml:MultiLineString></ogr:geometryProperty>') == -1: - gdaltest.post_reason('failure') - print(data) - return 'fail' + assert data.find('<ogr:geometryProperty><gml:MultiLineString><gml:lineStringMember><gml:LineString><gml:coordinates>0,0 0,1 1,1 0,0</gml:coordinates></gml:LineString></gml:lineStringMember></gml:MultiLineString></ogr:geometryProperty>') != -1 ogr.GetDriverByName('ESRI Shapefile').DeleteDataSource('tmp/test_ogr2ogr_45_src.shp') os.unlink('tmp/test_ogr2ogr_45.gml') os.unlink('tmp/test_ogr2ogr_45.xsd') - return 'success' - ############################################################################### # Test -gcp (#4604) @@ -1710,7 +1538,7 @@ def test_ogr2ogr_45(): def test_ogr2ogr_46(): if test_cli_utilities.get_ogr2ogr_path() is None: - return 'skip' + pytest.skip() try: os.stat('tmp/test_ogr2ogr_46_src.shp') @@ -1738,25 +1566,17 @@ def test_ogr2ogr_46(): data = f.read() f.close() - if data.find('2,49') == -1 and data.find('2.0,49.0') == -1 and data.find('222638.') == -1: - gdaltest.post_reason('failure') - print(option) - print(data) - return 'fail' + assert not (data.find('2,49') == -1 and data.find('2.0,49.0') == -1 and data.find('222638.') == -1), \ + option - if data.find('3,50') == -1 and data.find('3.0,50.0') == -1 and data.find('333958.') == -1: - gdaltest.post_reason('failure') - print(option) - print(data) - return 'fail' + assert not (data.find('3,50') == -1 and data.find('3.0,50.0') == -1 and data.find('333958.') == -1), \ + option os.unlink('tmp/test_ogr2ogr_46.gml') os.unlink('tmp/test_ogr2ogr_46.xsd') ogr.GetDriverByName('ESRI Shapefile').DeleteDataSource('tmp/test_ogr2ogr_46_src.shp') - return 'success' - ############################################################################### # Test reprojection with features with different SRS @@ -1764,7 +1584,7 @@ def test_ogr2ogr_46(): def test_ogr2ogr_47(): if test_cli_utilities.get_ogr2ogr_path() is None: - return 'skip' + pytest.skip() f = open('tmp/test_ogr2ogr_47_src.gml', 'wt') f.write("""<foo xmlns:gml="http://www.opengis.net/gml"> @@ -1795,7 +1615,7 @@ def test_ogr2ogr_47(): if ds is None: os.unlink('tmp/test_ogr2ogr_47_src.gml') - return 'skip' + pytest.skip() ds = None gdaltest.runexternal(test_cli_utilities.get_ogr2ogr_path() + ' -f GML -t_srs EPSG:4326 tmp/test_ogr2ogr_47_dst.gml tmp/test_ogr2ogr_47_src.gml') @@ -1804,10 +1624,7 @@ def test_ogr2ogr_47(): data = f.read() f.close() - if data.find('>-3.0,40.65') == -1 and data.find('<3.0,40.65') == -1: - gdaltest.post_reason('failure') - print(data) - return 'fail' + assert not (data.find('>-3.0,40.65') == -1 and data.find('<3.0,40.65') == -1) os.unlink('tmp/test_ogr2ogr_47_dst.gml') os.unlink('tmp/test_ogr2ogr_47_dst.xsd') @@ -1815,15 +1632,13 @@ def test_ogr2ogr_47(): os.unlink('tmp/test_ogr2ogr_47_src.gml') os.unlink('tmp/test_ogr2ogr_47_src.gfs') - return 'success' - ############################################################################### # Test fieldmap option def test_ogr2ogr_48(): if test_cli_utilities.get_ogr2ogr_path() is None: - return 'skip' + pytest.skip() gdaltest.runexternal(test_cli_utilities.get_ogr2ogr_path() + ' tmp data/Fields.csv') gdaltest.runexternal(test_cli_utilities.get_ogr2ogr_path() + ' -append -fieldmap identity tmp data/Fields.csv') @@ -1831,14 +1646,12 @@ def test_ogr2ogr_48(): ds = ogr.Open('tmp/Fields.dbf') - if ds is None: - return 'fail' + assert ds is not None layer_defn = ds.GetLayer(0).GetLayerDefn() if layer_defn.GetFieldCount() != 15: - gdaltest.post_reason('Unexpected field count: ' + str(ds.GetLayer(0).GetLayerDefn().GetFieldCount())) ds.Destroy() ogr.GetDriverByName('ESRI Shapefile').DeleteDataSource('tmp/Fields.dbf') - return 'fail' + pytest.fail('Unexpected field count: ' + str(ds.GetLayer(0).GetLayerDefn().GetFieldCount())) error_occurred = False lyr = ds.GetLayer(0) @@ -1857,10 +1670,7 @@ def test_ogr2ogr_48(): ds.Destroy() ogr.GetDriverByName('ESRI Shapefile').DeleteDataSource('tmp/Fields.dbf') - if error_occurred: - return 'fail' - - return 'success' + assert not error_occurred ############################################################################### # Test detection of duplicated field names in source layer and renaming @@ -1869,7 +1679,7 @@ def test_ogr2ogr_48(): def test_ogr2ogr_49(): if test_cli_utilities.get_ogr2ogr_path() is None: - return 'skip' + pytest.skip() gdaltest.runexternal(test_cli_utilities.get_ogr2ogr_path() + ' -f CSV tmp/test_ogr2ogr_49.csv data/duplicatedfields.csv') f = open('tmp/test_ogr2ogr_49.csv') @@ -1878,12 +1688,8 @@ def test_ogr2ogr_49(): os.unlink('tmp/test_ogr2ogr_49.csv') - if lines[0].find('foo,bar,foo3,foo2,baz,foo4') != 0 or \ - lines[1].find('val_foo,val_bar,val_foo3,val_foo2,val_baz,val_foo4') != 0: - print(lines) - return 'fail' - - return 'success' + assert (lines[0].find('foo,bar,foo3,foo2,baz,foo4') == 0 and \ + lines[1].find('val_foo,val_bar,val_foo3,val_foo2,val_baz,val_foo4') == 0) ############################################################################### # Test detection of duplicated field names is case insensitive (#5208) @@ -1891,7 +1697,7 @@ def test_ogr2ogr_49(): def test_ogr2ogr_49_bis(): if test_cli_utilities.get_ogr2ogr_path() is None: - return 'skip' + pytest.skip() gdaltest.runexternal(test_cli_utilities.get_ogr2ogr_path() + ' -f KML tmp/test_ogr2ogr_49_bis.kml data/grid.csv -sql "SELECT field_1 AS name FROM grid WHERE fid = 1"') f = open('tmp/test_ogr2ogr_49_bis.kml') @@ -1911,23 +1717,18 @@ def test_ogr2ogr_49_bis(): """</Folder>""", """</Document></kml>"""] - if len(lines) != len(expected_lines): - print(lines) - return 'fail' + assert len(lines) == len(expected_lines) for i, line in enumerate(lines): - if line.strip() != expected_lines[i].strip(): - print(lines) - return 'fail' - - return 'success' + assert line.strip() == expected_lines[i].strip(), lines + ############################################################################### # Test -addfields def test_ogr2ogr_50(): if test_cli_utilities.get_ogr2ogr_path() is None: - return 'skip' + pytest.skip() f = open('tmp/test_ogr2ogr_50_1.csv', 'wt') f.write('id,field1\n') @@ -1946,30 +1747,26 @@ def test_ogr2ogr_50(): lyr = ds.GetLayer(0) feat = lyr.GetNextFeature() if feat.GetField('field1') != 'foo' or not feat.IsFieldNull('field2'): - gdaltest.post_reason('fail') feat.DumpReadable() - return 'fail' + pytest.fail() feat = lyr.GetNextFeature() if feat.GetField('field1') != 'bar' or feat.GetField('field2') != 'baz': - gdaltest.post_reason('fail') feat.DumpReadable() - return 'fail' + pytest.fail() ds = None os.unlink('tmp/test_ogr2ogr_50.dbf') os.unlink('tmp/test_ogr2ogr_50_1.csv') os.unlink('tmp/test_ogr2ogr_50_2.csv') - return 'success' - ############################################################################### # Test RFC 41 support def test_ogr2ogr_51(): if test_cli_utilities.get_ogr2ogr_path() is None: - return 'skip' + pytest.skip() f = open('tmp/test_ogr2ogr_51_src.csv', 'wt') f.write('id,_WKTgeom1_EPSG_4326,foo,_WKTgeom2_EPSG_32631\n') @@ -1985,10 +1782,7 @@ def test_ogr2ogr_51(): expected_lines = ['"_WKTgeom1_EPSG_4326","_WKTgeom2_EPSG_32631","id","foo"', '"POINT (1 2)","POINT (3 4)","1","bar"'] for i in range(2): - if lines[i].strip() != expected_lines[i]: - gdaltest.post_reason('fail') - print(lines) - return 'fail' + assert lines[i].strip() == expected_lines[i] # Test conversion from a multi-geometry format into a single-geometry format gdaltest.runexternal(test_cli_utilities.get_ogr2ogr_path() + ' tmp/test_ogr2ogr_51_dst.shp tmp/test_ogr2ogr_51_src.csv -nln test_ogr2ogr_51_dst') @@ -1996,14 +1790,9 @@ def test_ogr2ogr_51(): ds = ogr.Open('tmp/test_ogr2ogr_51_dst.shp') lyr = ds.GetLayer(0) sr = lyr.GetSpatialRef() - if sr is None or sr.ExportToWkt().find('GEOGCS["WGS 84"') != 0: - gdaltest.post_reason('fail') - print(sr.ExportToWkt()) - return 'fail' + assert sr is not None and sr.ExportToWkt().find('GEOGCS["WGS 84"') == 0 feat = lyr.GetNextFeature() - if feat.GetGeometryRef().ExportToWkt() != 'POINT (1 2)': - gdaltest.post_reason('fail') - return 'fail' + assert feat.GetGeometryRef().ExportToWkt() == 'POINT (1 2)' ds = None ogr.GetDriverByName('ESRI Shapefile').DeleteDataSource('tmp/test_ogr2ogr_51_dst.shp') @@ -2018,10 +1807,7 @@ def test_ogr2ogr_51(): '"POINT (1 2)","POINT (3 4)","1","bar"', '"POINT (1 2)","POINT (3 4)","1","bar"'] for i in range(3): - if lines[i].strip() != expected_lines[i]: - gdaltest.post_reason('fail') - print(lines) - return 'fail' + assert lines[i].strip() == expected_lines[i] os.unlink('tmp/test_ogr2ogr_51_dst.csv') @@ -2034,10 +1820,7 @@ def test_ogr2ogr_51(): expected_lines = ['"_WKTgeom2_EPSG_32631","_WKTgeom1_EPSG_4326","foo","id"', '"POINT (3 4)","POINT (1 2)","bar","1"'] for i in range(2): - if lines[i].strip() != expected_lines[i]: - gdaltest.post_reason('fail') - print(lines) - return 'fail' + assert lines[i].strip() == expected_lines[i] # Test -geomfield option gdaltest.runexternal(test_cli_utilities.get_ogr2ogr_path() + ' -append tmp/test_ogr2ogr_51_dst.csv tmp/test_ogr2ogr_51_src.csv -nln test_ogr2ogr_51_dst -spat 1 2 1 2 -geomfield geom__WKTgeom1_EPSG_4326') @@ -2050,23 +1833,18 @@ def test_ogr2ogr_51(): '"POINT (3 4)","POINT (1 2)","bar","1"', '"POINT (3 4)","POINT (1 2)","bar","1"'] for i in range(2): - if lines[i].strip() != expected_lines[i]: - gdaltest.post_reason('fail') - print(lines) - return 'fail' + assert lines[i].strip() == expected_lines[i] os.unlink('tmp/test_ogr2ogr_51_src.csv') os.unlink('tmp/test_ogr2ogr_51_dst.csv') - return 'success' - ############################################################################### # Test -nlt CONVERT_TO_LINEAR and -nlt CONVERT_TO_CURVE def test_ogr2ogr_52(): if test_cli_utilities.get_ogr2ogr_path() is None: - return 'skip' + pytest.skip() f = open('tmp/test_ogr2ogr_52_src.csv', 'wt') f.write('id,WKT\n') @@ -2079,10 +1857,7 @@ def test_ogr2ogr_52(): content = f.read() f.close() - if content.find('LINESTRING (0 0,') < 0: - gdaltest.post_reason('fail') - print(content) - return 'fail' + assert content.find('LINESTRING (0 0,') >= 0 gdaltest.runexternal(test_cli_utilities.get_ogr2ogr_path() + ' -f CSV tmp/test_ogr2ogr_52_dst2.csv tmp/test_ogr2ogr_52_dst.csv -select id -nln test_ogr2ogr_52_dst2 -dsco GEOMETRY=AS_WKT -nlt CONVERT_TO_CURVE') @@ -2090,24 +1865,19 @@ def test_ogr2ogr_52(): content = f.read() f.close() - if content.find('COMPOUNDCURVE ((0 0,') < 0: - gdaltest.post_reason('fail') - print(content) - return 'fail' + assert content.find('COMPOUNDCURVE ((0 0,') >= 0 os.unlink('tmp/test_ogr2ogr_52_src.csv') os.unlink('tmp/test_ogr2ogr_52_dst.csv') os.unlink('tmp/test_ogr2ogr_52_dst2.csv') - return 'success' - ############################################################################### # Test -mapFieldType and 64 bit integers def test_ogr2ogr_53(): if test_cli_utilities.get_ogr2ogr_path() is None: - return 'skip' + pytest.skip() f = open('tmp/test_ogr2ogr_53.csv', 'wt') f.write('id,i64,b,WKT\n') @@ -2124,15 +1894,12 @@ def test_ogr2ogr_53(): content = f.read() f.close() - if content.find('<SimpleField name="id" type="int"></SimpleField>') < 0 or \ - content.find('<SimpleData name="id">1</SimpleData>') < 0 or \ - content.find('<SimpleField name="i64" type="float"></SimpleField>') < 0 or \ - content.find('<SimpleData name="i64">123456789012</SimpleData>') < 0 or \ - content.find('<SimpleField name="b" type="string"></SimpleField>') < 0 or \ - content.find('<SimpleData name="b">1</SimpleData>') < 0: - gdaltest.post_reason('fail') - print(content) - return 'fail' + assert (content.find('<SimpleField name="id" type="int"></SimpleField>') >= 0 and \ + content.find('<SimpleData name="id">1</SimpleData>') >= 0 and \ + content.find('<SimpleField name="i64" type="float"></SimpleField>') >= 0 and \ + content.find('<SimpleData name="i64">123456789012</SimpleData>') >= 0 and \ + content.find('<SimpleField name="b" type="string"></SimpleField>') >= 0 and \ + content.find('<SimpleData name="b">1</SimpleData>') >= 0) os.unlink('tmp/test_ogr2ogr_53.kml') @@ -2143,10 +1910,7 @@ def test_ogr2ogr_53(): content = f.read() f.close() - if content.find('"123456789012.0"') < 0: - gdaltest.post_reason('fail') - print(content) - return 'fail' + assert content.find('"123456789012.0"') >= 0 os.unlink('tmp/test_ogr2ogr_53.bna') @@ -2157,26 +1921,21 @@ def test_ogr2ogr_53(): content = f.read() f.close() - if content.find('<SimpleField name="i64" type="string"></SimpleField>') < 0 or \ - content.find('<SimpleData name="i64">123456789012</SimpleData>') < 0: - gdaltest.post_reason('fail') - print(content) - return 'fail' + assert (content.find('<SimpleField name="i64" type="string"></SimpleField>') >= 0 and \ + content.find('<SimpleData name="i64">123456789012</SimpleData>') >= 0) os.unlink('tmp/test_ogr2ogr_53.kml') os.unlink('tmp/test_ogr2ogr_53.csv') os.unlink('tmp/test_ogr2ogr_53.csvt') - return 'success' - ############################################################################### # Test behaviour with nullable fields def test_ogr2ogr_54(): if test_cli_utilities.get_ogr2ogr_path() is None: - return 'skip' + pytest.skip() f = open('tmp/test_ogr2ogr_54.csv', 'wt') f.write('fld1,fld2,WKT\n') @@ -2203,12 +1962,9 @@ def test_ogr2ogr_54(): content = f.read() f.close() - if content.find('<xs:element name="WKT" type="gml:GeometryPropertyType" nillable="true" minOccurs="1" maxOccurs="1"/>') < 0 or \ - content.find('<xs:element name="fld1" nillable="true" minOccurs="1" maxOccurs="1">') < 0 or \ - content.find('<xs:element name="fld2" nillable="true" minOccurs="0" maxOccurs="1">') < 0: - gdaltest.post_reason('fail') - print(content) - return 'fail' + assert (content.find('<xs:element name="WKT" type="gml:GeometryPropertyType" nillable="true" minOccurs="1" maxOccurs="1"/>') >= 0 and \ + content.find('<xs:element name="fld1" nillable="true" minOccurs="1" maxOccurs="1">') >= 0 and \ + content.find('<xs:element name="fld2" nillable="true" minOccurs="0" maxOccurs="1">') >= 0) os.unlink('tmp/test_ogr2ogr_54.gml') os.unlink('tmp/test_ogr2ogr_54.xsd') @@ -2220,12 +1976,9 @@ def test_ogr2ogr_54(): content = f.read() f.close() - if content.find('<xs:element name="WKT" type="gml:GeometryPropertyType" nillable="true" minOccurs="0" maxOccurs="1"/>') < 0 or \ - content.find('<xs:element name="fld1" nillable="true" minOccurs="0" maxOccurs="1">') < 0 or \ - content.find('<xs:element name="fld2" nillable="true" minOccurs="0" maxOccurs="1">') < 0: - gdaltest.post_reason('fail') - print(content) - return 'fail' + assert (content.find('<xs:element name="WKT" type="gml:GeometryPropertyType" nillable="true" minOccurs="0" maxOccurs="1"/>') >= 0 and \ + content.find('<xs:element name="fld1" nillable="true" minOccurs="0" maxOccurs="1">') >= 0 and \ + content.find('<xs:element name="fld2" nillable="true" minOccurs="0" maxOccurs="1">') >= 0) os.unlink('tmp/test_ogr2ogr_54.gml') os.unlink('tmp/test_ogr2ogr_54.xsd') @@ -2233,15 +1986,13 @@ def test_ogr2ogr_54(): os.unlink('tmp/test_ogr2ogr_54.csv') os.unlink('tmp/test_ogr2ogr_54.vrt') - return 'success' - ############################################################################### # Test behaviour with default values def test_ogr2ogr_55(): if test_cli_utilities.get_ogr2ogr_path() is None: - return 'skip' + pytest.skip() f = open('tmp/test_ogr2ogr_55.csv', 'wt') f.write('fld1,fld2,WKT\n') @@ -2272,10 +2023,7 @@ def test_ogr2ogr_55(): content = f.read() f.close() - if content.find('<ogr:fld2>2</ogr:fld2>') < 0: - gdaltest.post_reason('fail') - print(content) - return 'fail' + assert content.find('<ogr:fld2>2</ogr:fld2>') >= 0 os.unlink('tmp/test_ogr2ogr_55.gml') os.unlink('tmp/test_ogr2ogr_55.xsd') @@ -2287,10 +2035,7 @@ def test_ogr2ogr_55(): content = f.read() f.close() - if content.find('<ogr:fld2>') >= 0: - gdaltest.post_reason('fail') - print(content) - return 'fail' + assert content.find('<ogr:fld2>') < 0 os.unlink('tmp/test_ogr2ogr_55.gml') os.unlink('tmp/test_ogr2ogr_55.xsd') @@ -2299,15 +2044,13 @@ def test_ogr2ogr_55(): os.unlink('tmp/test_ogr2ogr_55.csvt') os.unlink('tmp/test_ogr2ogr_55.vrt') - return 'success' - ############################################################################### # Test behaviour when creating a field with same name as FID column. def test_ogr2ogr_56(): if test_cli_utilities.get_ogr2ogr_path() is None: - return 'skip' + pytest.skip() f = open('tmp/test_ogr2ogr_56.csv', 'wt') f.write('str,myid,WKT\n') @@ -2324,25 +2067,20 @@ def test_ogr2ogr_56(): content = f.read() f.close() - if content.find("""ALTER TABLE "public"."test_ogr2ogr_56" ADD COLUMN "myid"" """) >= 0 or \ - content.find("""INSERT INTO "public"."test_ogr2ogr_56" ("wkb_geometry" , "myid" , "str", "wkt") VALUES ('010100000000000000000000000000000000000000', 10, 'aaa', 'POINT(0 0)');""") < 0: - gdaltest.post_reason('fail') - print(content) - return 'fail' + assert (content.find("""ALTER TABLE "public"."test_ogr2ogr_56" ADD COLUMN "myid"" """) < 0 and \ + content.find("""INSERT INTO "public"."test_ogr2ogr_56" ("wkb_geometry" , "myid" , "str", "wkt") VALUES ('010100000000000000000000000000000000000000', 10, 'aaa', 'POINT(0 0)');""") >= 0) os.unlink('tmp/test_ogr2ogr_56.sql') os.unlink('tmp/test_ogr2ogr_56.csv') os.unlink('tmp/test_ogr2ogr_56.csvt') - return 'success' - ############################################################################### # Test default propagation of FID column name and values, and -unsetFid def test_ogr2ogr_57(): if test_cli_utilities.get_ogr2ogr_path() is None: - return 'skip' + pytest.skip() f = open('tmp/test_ogr2ogr_57.csv', 'wt') f.write('id,str,WKT\n') @@ -2373,11 +2111,8 @@ def test_ogr2ogr_57(): content = f.read() f.close() - if content.find("""CREATE TABLE "public"."test_ogr2ogr_57" ( "id" SERIAL, CONSTRAINT "test_ogr2ogr_57_pk" PRIMARY KEY ("id") )""") < 0 or \ - content.find("""INSERT INTO "public"."test_ogr2ogr_57" ("wkt" , "id" , "str") VALUES ('010100000000000000000000000000000000000000', 10, 'a')""") < 0: - gdaltest.post_reason('fail') - print(content) - return 'fail' + assert (content.find("""CREATE TABLE "public"."test_ogr2ogr_57" ( "id" SERIAL, CONSTRAINT "test_ogr2ogr_57_pk" PRIMARY KEY ("id") )""") >= 0 and \ + content.find("""INSERT INTO "public"."test_ogr2ogr_57" ("wkt" , "id" , "str") VALUES ('010100000000000000000000000000000000000000', 10, 'a')""") >= 0) os.unlink('tmp/test_ogr2ogr_57.sql') @@ -2388,11 +2123,8 @@ def test_ogr2ogr_57(): content = f.read() f.close() - if content.find("""CREATE TABLE "public"."test_ogr2ogr_57" ( "ogc_fid" SERIAL, CONSTRAINT "test_ogr2ogr_57_pk" PRIMARY KEY ("ogc_fid") )""") < 0 or \ - content.find("""INSERT INTO "public"."test_ogr2ogr_57" ("wkt" , "str") VALUES ('010100000000000000000000000000000000000000', 'a')""") < 0: - gdaltest.post_reason('fail') - print(content) - return 'fail' + assert (content.find("""CREATE TABLE "public"."test_ogr2ogr_57" ( "ogc_fid" SERIAL, CONSTRAINT "test_ogr2ogr_57_pk" PRIMARY KEY ("ogc_fid") )""") >= 0 and \ + content.find("""INSERT INTO "public"."test_ogr2ogr_57" ("wkt" , "str") VALUES ('010100000000000000000000000000000000000000', 'a')""") >= 0) os.unlink('tmp/test_ogr2ogr_57.sql') @@ -2400,40 +2132,34 @@ def test_ogr2ogr_57(): os.unlink('tmp/test_ogr2ogr_57.csvt') os.unlink('tmp/test_ogr2ogr_57.vrt') - return 'success' - ############################################################################### # Test datasource transactions def test_ogr2ogr_58(): if test_cli_utilities.get_ogr2ogr_path() is None: - return 'skip' + pytest.skip() if ogr.GetDriverByName('SQLite') is None: - return 'skip' + pytest.skip() gdaltest.runexternal(test_cli_utilities.get_ogr2ogr_path() + ' -gt 3 -f SQLite tmp/test_ogr2ogr_58.sqlite ../ogr/data/poly.shp') ds = ogr.Open('tmp/test_ogr2ogr_58.sqlite') lyr = ds.GetLayer(0) - if lyr.GetFeatureCount() != 10: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.GetFeatureCount() == 10 ds = None ogr.GetDriverByName('SQLite').DeleteDataSource('tmp/test_ogr2ogr_58.sqlite') - return 'success' - ############################################################################### # Test metadata support def test_ogr2ogr_59(): if test_cli_utilities.get_ogr2ogr_path() is None: - return 'skip' + pytest.skip() if ogr.GetDriverByName('GPKG') is None: - return 'skip' + pytest.skip() ds = ogr.GetDriverByName('GPKG').CreateDataSource('tmp/test_ogr2ogr_59_src.gpkg') ds.SetMetadataItem('FOO', 'BAR') @@ -2446,76 +2172,52 @@ def test_ogr2ogr_59(): gdaltest.runexternal(test_cli_utilities.get_ogr2ogr_path() + ' -f GPKG tmp/test_ogr2ogr_59_dest.gpkg tmp/test_ogr2ogr_59_src.gpkg -mo BAZ=BAW') ds = ogr.Open('tmp/test_ogr2ogr_59_dest.gpkg') - if ds.GetMetadata() != {'FOO': 'BAR', 'BAZ': 'BAW'}: - gdaltest.post_reason('fail') - print(ds.GetMetadata()) - return 'fail' - if ds.GetMetadata('another_domain') != {'BAR': 'BAZ'}: - gdaltest.post_reason('fail') - print(ds.GetMetadata()) - return 'fail' + assert ds.GetMetadata() == {'FOO': 'BAR', 'BAZ': 'BAW'} + assert ds.GetMetadata('another_domain') == {'BAR': 'BAZ'} lyr = ds.GetLayer(0) - if lyr.GetMetadata() != {'lyr_FOO': 'lyr_BAR'}: - gdaltest.post_reason('fail') - print(lyr.GetMetadata()) - return 'fail' - if lyr.GetMetadata('lyr_another_domain') != {'lyr_BAR': 'lyr_BAZ'}: - gdaltest.post_reason('fail') - print(lyr.GetMetadata()) - return 'fail' + assert lyr.GetMetadata() == {'lyr_FOO': 'lyr_BAR'} + assert lyr.GetMetadata('lyr_another_domain') == {'lyr_BAR': 'lyr_BAZ'} ds = None ogr.GetDriverByName('GPKG').DeleteDataSource('tmp/test_ogr2ogr_59_dest.gpkg') gdaltest.runexternal(test_cli_utilities.get_ogr2ogr_path() + ' -f GPKG tmp/test_ogr2ogr_59_dest.gpkg tmp/test_ogr2ogr_59_src.gpkg -nomd') ds = ogr.Open('tmp/test_ogr2ogr_59_dest.gpkg') - if ds.GetMetadata() != {}: - gdaltest.post_reason('fail') - print(ds.GetMetadata()) - return 'fail' + assert ds.GetMetadata() == {} lyr = ds.GetLayer(0) - if lyr.GetMetadata() != {}: - gdaltest.post_reason('fail') - print(lyr.GetMetadata()) - return 'fail' + assert lyr.GetMetadata() == {} ds = None ogr.GetDriverByName('GPKG').DeleteDataSource('tmp/test_ogr2ogr_59_dest.gpkg') ogr.GetDriverByName('GPKG').DeleteDataSource('tmp/test_ogr2ogr_59_src.gpkg') - return 'success' - ############################################################################### # Test forced datasource transactions def test_ogr2ogr_60(): if test_cli_utilities.get_ogr2ogr_path() is None: - return 'skip' + pytest.skip() if ogr.GetDriverByName('FileGDB') is None: - return 'skip' + pytest.skip() gdaltest.runexternal(test_cli_utilities.get_ogr2ogr_path() + ' -ds_transaction -f FileGDB tmp/test_ogr2ogr_60.gdb ../ogr/data/poly.shp -mapFieldType Integer64=Integer') ds = ogr.Open('tmp/test_ogr2ogr_60.gdb') lyr = ds.GetLayer(0) - if lyr.GetFeatureCount() != 10: - gdaltest.post_reason('fail') - return 'fail' + assert lyr.GetFeatureCount() == 10 ds = None ogr.GetDriverByName('FileGDB').DeleteDataSource('tmp/test_ogr2ogr_60.gdb') - return 'success' - ############################################################################### # Test -spat_srs def test_ogr2ogr_61(): if test_cli_utilities.get_ogr2ogr_path() is None: - return 'skip' + pytest.skip() f = open('tmp/test_ogr2ogr_61.csv', 'wt') f.write('foo,WKT\n') @@ -2525,32 +2227,26 @@ def test_ogr2ogr_61(): gdaltest.runexternal(test_cli_utilities.get_ogr2ogr_path() + ' tmp/test_ogr2ogr_61.shp tmp/test_ogr2ogr_61.csv -spat 426857 5427937 426858 5427938 -spat_srs EPSG:32631 -s_srs EPSG:4326 -a_srs EPSG:4326') ds = ogr.Open('tmp/test_ogr2ogr_61.shp') - if ds is None or ds.GetLayer(0).GetFeatureCount() != 1: - gdaltest.post_reason('fail') - return 'fail' + assert ds is not None and ds.GetLayer(0).GetFeatureCount() == 1 ds.Destroy() gdaltest.runexternal(test_cli_utilities.get_ogr2ogr_path() + ' tmp/test_ogr2ogr_61_2.shp tmp/test_ogr2ogr_61.shp -spat 426857 5427937 426858 5427938 -spat_srs EPSG:32631') ds = ogr.Open('tmp/test_ogr2ogr_61_2.shp') - if ds is None or ds.GetLayer(0).GetFeatureCount() != 1: - gdaltest.post_reason('fail') - return 'fail' + assert ds is not None and ds.GetLayer(0).GetFeatureCount() == 1 ds.Destroy() ogr.GetDriverByName('ESRI Shapefile').DeleteDataSource('tmp/test_ogr2ogr_61.shp') ogr.GetDriverByName('ESRI Shapefile').DeleteDataSource('tmp/test_ogr2ogr_61_2.shp') os.unlink('tmp/test_ogr2ogr_61.csv') - return 'success' - ############################################################################### # Test -noNativeData def test_ogr2ogr_62(): if test_cli_utilities.get_ogr2ogr_path() is None: - return 'skip' + pytest.skip() # Default behaviour @@ -2560,35 +2256,23 @@ def test_ogr2ogr_62(): gdaltest.runexternal(test_cli_utilities.get_ogr2ogr_path() + """ -f GeoJSON tmp/test_ogr2ogr_62.json tmp/test_ogr2ogr_62_in.json""") fp = gdal.VSIFOpenL('tmp/test_ogr2ogr_62.json', 'rb') - if fp is None: - gdaltest.post_reason('fail') - return 'fail' + assert fp is not None data = gdal.VSIFReadL(1, 10000, fp).decode('ascii') gdal.VSIFCloseL(fp) os.unlink('tmp/test_ogr2ogr_62.json') - if data.find('bar') < 0 or data.find('baz') < 0: - gdaltest.post_reason('fail') - print(data) - return 'fail' + assert data.find('bar') >= 0 and data.find('baz') >= 0 # Test -noNativeData gdaltest.runexternal(test_cli_utilities.get_ogr2ogr_path() + """ -f GeoJSON tmp/test_ogr2ogr_62.json tmp/test_ogr2ogr_62_in.json -noNativeData""") fp = gdal.VSIFOpenL('tmp/test_ogr2ogr_62.json', 'rb') - if fp is None: - gdaltest.post_reason('fail') - return 'fail' + assert fp is not None data = gdal.VSIFReadL(1, 10000, fp).decode('ascii') gdal.VSIFCloseL(fp) os.unlink('tmp/test_ogr2ogr_62.json') os.unlink('tmp/test_ogr2ogr_62_in.json') - if data.find('bar') >= 0 or data.find('baz') >= 0: - gdaltest.post_reason('fail') - print(data) - return 'fail' - - return 'success' + assert data.find('bar') < 0 and data.find('baz') < 0 ############################################################################### # Test --formats @@ -2596,7 +2280,7 @@ def test_ogr2ogr_62(): def test_ogr2ogr_63(): if test_cli_utilities.get_ogr2ogr_path() is None: - return 'skip' + pytest.skip() try: os.stat('tmp/poly.shp') @@ -2605,17 +2289,8 @@ def test_ogr2ogr_63(): pass (ret, err) = gdaltest.runexternal_out_and_err(test_cli_utilities.get_ogr2ogr_path() + ' --formats') - if ret.find('Supported Formats') < 0: - gdaltest.post_reason('fail') - print(ret) - print(err) - return 'fail' - if err.find('ERROR') >= 0: - gdaltest.post_reason('fail') - print(ret) - print(err) - return 'fail' - return 'success' + assert ret.find('Supported Formats') >= 0, err + assert err.find('ERROR') < 0, ret ############################################################################### # Test appending multiple layers, whose one already exists (#6345) @@ -2623,7 +2298,7 @@ def test_ogr2ogr_63(): def test_ogr2ogr_64(): if test_cli_utilities.get_ogr2ogr_path() is None: - return 'skip' + pytest.skip() try: shutil.rmtree('tmp/in_csv') @@ -2647,60 +2322,44 @@ def test_ogr2ogr_64(): gdaltest.runexternal(test_cli_utilities.get_ogr2ogr_path() + ' -append tmp/out_csv tmp/in_csv') ds = ogr.Open('tmp/out_csv') - if ds.GetLayerByName(first_layer).GetFeatureCount() != 1: - gdaltest.post_reason('fail') - return 'fail' - if ds.GetLayerByName(second_layer).GetFeatureCount() != 2: - gdaltest.post_reason('fail') - return 'fail' + assert ds.GetLayerByName(first_layer).GetFeatureCount() == 1 + assert ds.GetLayerByName(second_layer).GetFeatureCount() == 2 ds = None shutil.rmtree('tmp/in_csv') shutil.rmtree('tmp/out_csv') - return 'success' - ############################################################################### # Test detection of extension def test_ogr2ogr_65(): if test_cli_utilities.get_ogr2ogr_path() is None: - return 'skip' + pytest.skip() gdaltest.runexternal(test_cli_utilities.get_ogr2ogr_path() + ' tmp/out.csv ../ogr/data/poly.shp') ds = gdal.OpenEx('tmp/out.csv') - if ds.GetDriver().ShortName != 'CSV': - gdaltest.post_reason('fail') - return 'fail' + assert ds.GetDriver().ShortName == 'CSV' ds = None gdal.Unlink('tmp/out.csv') (ret, err) = gdaltest.runexternal_out_and_err(test_cli_utilities.get_ogr2ogr_path() + ' /vsimem/out.xxx ../ogr/data/poly.shp') if err.find("Cannot guess") < 0: - gdaltest.post_reason('expected a warning about probably wrong extension') print(ret) - print(err) - return 'fail' - - return 'success' + pytest.fail('expected a warning about probably wrong extension') + ############################################################################### # Test accidental overriding of dataset when dst and src filenames are the same (#1465) def test_ogr2ogr_66(): if test_cli_utilities.get_ogr2ogr_path() is None: - return 'skip' + pytest.skip() (ret, err) = gdaltest.runexternal_out_and_err(test_cli_utilities.get_ogr2ogr_path() + ' ../ogr/data/poly.shp ../ogr/data/poly.shp') - if err.find("Source and destination datasets must be different in non-update mode") < 0: - gdaltest.post_reason('fail') - print(ret) - print(err) - return 'fail' - - return 'success' + assert err.find("Source and destination datasets must be different in non-update mode") >= 0, \ + ret def hexify_double(val): @@ -2713,7 +2372,7 @@ def check_identity_transformation(x, y, srid): import struct if test_cli_utilities.get_ogr2ogr_path() is None: - return 'skip' + pytest.skip() shape_drv = ogr.GetDriverByName('ESRI Shapefile') for output_shp in ['tmp/output_point.shp', 'tmp/output_point2.shp']: @@ -2759,7 +2418,7 @@ def check_identity_transformation(x, y, srid): shape_drv.DeleteDataSource('tmp/output_point.shp') os.remove('tmp/input_point.csv') - return 'success' if ok else 'fail' + assert ok ############################################################################### # Test coordinates values are preserved for identity transformations @@ -2777,85 +2436,3 @@ def test_ogr2ogr_67(): # both as latitutude/longitude in degrees. ret = check_identity_transformation(x, y, 4326) return ret - - -gdaltest_list = [ - test_ogr2ogr_1, - test_ogr2ogr_2, - test_ogr2ogr_3, - test_ogr2ogr_4, - test_ogr2ogr_5, - test_ogr2ogr_6, - test_ogr2ogr_7, - test_ogr2ogr_8, - test_ogr2ogr_9, - test_ogr2ogr_10, - test_ogr2ogr_11, - test_ogr2ogr_12, - test_ogr2ogr_13, - test_ogr2ogr_14, - test_ogr2ogr_15, - test_ogr2ogr_16, - test_ogr2ogr_17, - test_ogr2ogr_18, - test_ogr2ogr_19, - test_ogr2ogr_20, - test_ogr2ogr_21, - test_ogr2ogr_22, - test_ogr2ogr_23, - test_ogr2ogr_24, - test_ogr2ogr_25, - test_ogr2ogr_26, - test_ogr2ogr_27, - test_ogr2ogr_28, - test_ogr2ogr_29, - test_ogr2ogr_30, - test_ogr2ogr_31, - test_ogr2ogr_32, - test_ogr2ogr_33, - test_ogr2ogr_34, - test_ogr2ogr_35, - test_ogr2ogr_36, - test_ogr2ogr_37, - test_ogr2ogr_38, - test_ogr2ogr_39, - test_ogr2ogr_40, - test_ogr2ogr_41, - test_ogr2ogr_42, - test_ogr2ogr_43, - test_ogr2ogr_44, - test_ogr2ogr_45, - test_ogr2ogr_46, - test_ogr2ogr_47, - test_ogr2ogr_48, - test_ogr2ogr_49, - test_ogr2ogr_49_bis, - test_ogr2ogr_50, - test_ogr2ogr_51, - test_ogr2ogr_52, - test_ogr2ogr_53, - test_ogr2ogr_54, - test_ogr2ogr_55, - test_ogr2ogr_56, - test_ogr2ogr_57, - test_ogr2ogr_58, - test_ogr2ogr_59, - test_ogr2ogr_60, - test_ogr2ogr_61, - test_ogr2ogr_62, - test_ogr2ogr_63, - test_ogr2ogr_64, - test_ogr2ogr_65, - test_ogr2ogr_66, - test_ogr2ogr_67 -] - -# gdaltest_list = [ test_ogr2ogr_51 ] - -if __name__ == '__main__': - - gdaltest.setup_run('test_ogr2ogr') - - gdaltest.run_tests(gdaltest_list) - - sys.exit(gdaltest.summarize()) diff --git a/autotest/utilities/test_ogr2ogr_lib.py b/autotest/utilities/test_ogr2ogr_lib.py index 7b89605a5937..e5c254a83f03 100755 --- a/autotest/utilities/test_ogr2ogr_lib.py +++ b/autotest/utilities/test_ogr2ogr_lib.py @@ -31,11 +31,11 @@ import sys -sys.path.append('../pymod') from osgeo import gdal, gdalconst, ogr import gdaltest import ogrtest +import pytest ############################################################################### # Simple test @@ -45,20 +45,13 @@ def test_ogr2ogr_lib_1(): srcDS = gdal.OpenEx('../ogr/data/poly.shp') ds = gdal.VectorTranslate('', srcDS, format='Memory') - if ds is None or ds.GetLayer(0).GetFeatureCount() != 10: - return 'fail' + assert ds is not None and ds.GetLayer(0).GetFeatureCount() == 10 feat0 = ds.GetLayer(0).GetFeature(0) - if feat0.GetFieldAsDouble('AREA') != 215229.266: - print(feat0.GetFieldAsDouble('AREA')) - gdaltest.post_reason('Did not get expected value for field AREA') - return 'fail' - if feat0.GetFieldAsString('PRFEDEA') != '35043411': - print(feat0.GetFieldAsString('PRFEDEA')) - gdaltest.post_reason('Did not get expected value for field PRFEDEA') - return 'fail' - - return 'success' + assert feat0.GetFieldAsDouble('AREA') == 215229.266, \ + 'Did not get expected value for field AREA' + assert feat0.GetFieldAsString('PRFEDEA') == '35043411', \ + 'Did not get expected value for field PRFEDEA' ############################################################################### # Test SQLStatement @@ -68,16 +61,12 @@ def test_ogr2ogr_lib_2(): srcDS = gdal.OpenEx('../ogr/data/poly.shp') ds = gdal.VectorTranslate('', srcDS, format='Memory', SQLStatement='select * from poly', SQLDialect='OGRSQL') - if ds is None or ds.GetLayer(0).GetFeatureCount() != 10: - gdaltest.post_reason('fail') - return 'fail' + assert ds is not None and ds.GetLayer(0).GetFeatureCount() == 10 # Test @filename syntax gdal.FileFromMemBuffer('/vsimem/sql.txt', '-- initial comment\nselect * from poly\n-- trailing comment') ds = gdal.VectorTranslate('', srcDS, format='Memory', SQLStatement='@/vsimem/sql.txt') - if ds is None or ds.GetLayer(0).GetFeatureCount() != 10: - gdaltest.post_reason('fail') - return 'fail' + assert ds is not None and ds.GetLayer(0).GetFeatureCount() == 10 gdal.Unlink('/vsimem/sql.txt') # Test @filename syntax with a UTF-8 BOM @@ -86,13 +75,9 @@ def test_ogr2ogr_lib_2(): else: gdal.FileFromMemBuffer('/vsimem/sql.txt', '\xEF\xBB\xBFselect * from poly') ds = gdal.VectorTranslate('', srcDS, format='Memory', SQLStatement='@/vsimem/sql.txt') - if ds is None or ds.GetLayer(0).GetFeatureCount() != 10: - gdaltest.post_reason('fail') - return 'fail' + assert ds is not None and ds.GetLayer(0).GetFeatureCount() == 10 gdal.Unlink('/vsimem/sql.txt') - return 'success' - ############################################################################### # Test WHERE @@ -101,20 +86,14 @@ def test_ogr2ogr_lib_3(): srcDS = gdal.OpenEx('../ogr/data/poly.shp') ds = gdal.VectorTranslate('', srcDS, format='Memory', where='EAS_ID=171') - if ds is None or ds.GetLayer(0).GetFeatureCount() != 1: - gdaltest.post_reason('fail') - return 'fail' + assert ds is not None and ds.GetLayer(0).GetFeatureCount() == 1 # Test @filename syntax gdal.FileFromMemBuffer('/vsimem/filter.txt', 'EAS_ID=171') ds = gdal.VectorTranslate('', srcDS, format='Memory', where='@/vsimem/filter.txt') - if ds is None or ds.GetLayer(0).GetFeatureCount() != 1: - gdaltest.post_reason('fail') - return 'fail' + assert ds is not None and ds.GetLayer(0).GetFeatureCount() == 1 gdal.Unlink('/vsimem/filter.txt') - return 'success' - ############################################################################### # Test accessMode @@ -123,45 +102,26 @@ def test_ogr2ogr_lib_4(): srcDS = gdal.OpenEx('../ogr/data/poly.shp') ds = gdal.VectorTranslate('/vsimem/poly.shp', srcDS) - if ds.GetLayer(0).GetFeatureCount() != 10: - gdaltest.post_reason('wrong feature count') - print(ds.GetLayer(0).GetFeatureCount()) - return 'fail' + assert ds.GetLayer(0).GetFeatureCount() == 10, 'wrong feature count' ds = None ds = gdal.VectorTranslate('/vsimem/poly.shp', srcDS, accessMode='append') - if ds is None: - gdaltest.post_reason('ds is None') - return 'fail' - if ds.GetLayer(0).GetFeatureCount() != 20: - gdaltest.post_reason('wrong feature count') - print(ds.GetLayer(0).GetFeatureCount()) - return 'fail' + assert ds is not None, 'ds is None' + assert ds.GetLayer(0).GetFeatureCount() == 20, 'wrong feature count' ret = gdal.VectorTranslate(ds, srcDS, accessMode='append') - if ret != 1: - gdaltest.post_reason('ds is None') - return 'fail' - if ds.GetLayer(0).GetFeatureCount() != 30: - gdaltest.post_reason('wrong feature count') - print(ds.GetLayer(0).GetFeatureCount()) - return 'fail' + assert ret == 1, 'ds is None' + assert ds.GetLayer(0).GetFeatureCount() == 30, 'wrong feature count' feat10 = ds.GetLayer(0).GetFeature(10) - if feat10.GetFieldAsDouble('AREA') != 215229.266: - print(feat10.GetFieldAsDouble('AREA')) - gdaltest.post_reason('Did not get expected value for field AREA') - return 'fail' - if feat10.GetFieldAsString('PRFEDEA') != '35043411': - print(feat10.GetFieldAsString('PRFEDEA')) - gdaltest.post_reason('Did not get expected value for field PRFEDEA') - return 'fail' + assert feat10.GetFieldAsDouble('AREA') == 215229.266, \ + 'Did not get expected value for field AREA' + assert feat10.GetFieldAsString('PRFEDEA') == '35043411', \ + 'Did not get expected value for field PRFEDEA' ds = None ogr.GetDriverByName('ESRI Shapefile').DeleteDataSource('/vsimem/poly.shp') - return 'success' - ############################################################################### # Test dstSRS @@ -170,10 +130,7 @@ def test_ogr2ogr_lib_5(): srcDS = gdal.OpenEx('../ogr/data/poly.shp') ds = gdal.VectorTranslate('', srcDS, format='Memory', dstSRS='EPSG:4326') - if str(ds.GetLayer(0).GetSpatialRef()).find('1984') == -1: - return 'fail' - - return 'success' + assert str(ds.GetLayer(0).GetSpatialRef()).find('1984') != -1 ############################################################################### # Test selFields @@ -185,8 +142,7 @@ def test_ogr2ogr_lib_6(): # Voluntary don't use the exact case of the source field names (#4502) ds = gdal.VectorTranslate('', srcDS, format='Memory', selectFields=['eas_id', 'prfedea']) lyr = ds.GetLayer(0) - if lyr.GetLayerDefn().GetFieldCount() != 2: - return 'fail' + assert lyr.GetLayerDefn().GetFieldCount() == 2 feat = lyr.GetNextFeature() ret = 'success' if feat.GetFieldAsDouble('EAS_ID') != 168: @@ -208,14 +164,11 @@ def test_ogr2ogr_lib_7(): srcDS = gdal.OpenEx('../ogr/data/poly.shp') ds = gdal.VectorTranslate('/vsimem/poly.shp', srcDS, layerCreationOptions=['SHPT=POLYGONZ']) - if ds.GetLayer(0).GetLayerDefn().GetGeomType() != ogr.wkbPolygon25D: - return 'fail' + assert ds.GetLayer(0).GetLayerDefn().GetGeomType() == ogr.wkbPolygon25D ds = None ogr.GetDriverByName('ESRI Shapefile').DeleteDataSource('/vsimem/poly.shp') - return 'success' - ############################################################################### # Add explicit source layer name @@ -224,15 +177,11 @@ def test_ogr2ogr_lib_8(): srcDS = gdal.OpenEx('../ogr/data/poly.shp') ds = gdal.VectorTranslate('', srcDS, format='Memory', layers=['poly']) - if ds is None or ds.GetLayer(0).GetFeatureCount() != 10: - return 'fail' + assert ds is not None and ds.GetLayer(0).GetFeatureCount() == 10 # Test also with just a string and not an array ds = gdal.VectorTranslate('', srcDS, format='Memory', layers='poly') - if ds is None or ds.GetLayer(0).GetFeatureCount() != 10: - return 'fail' - - return 'success' + assert ds is not None and ds.GetLayer(0).GetFeatureCount() == 10 ############################################################################### # Test -segmentize @@ -242,13 +191,9 @@ def test_ogr2ogr_lib_9(): srcDS = gdal.OpenEx('../ogr/data/poly.shp') ds = gdal.VectorTranslate('', srcDS, format='Memory', segmentizeMaxDist=100) - if ds is None or ds.GetLayer(0).GetFeatureCount() != 10: - return 'fail' + assert ds is not None and ds.GetLayer(0).GetFeatureCount() == 10 feat = ds.GetLayer(0).GetNextFeature() - if feat.GetGeometryRef().GetGeometryRef(0).GetPointCount() != 36: - return 'fail' - - return 'success' + assert feat.GetGeometryRef().GetGeometryRef(0).GetPointCount() == 36 ############################################################################### # Test overwrite with a shapefile @@ -258,18 +203,15 @@ def test_ogr2ogr_lib_10(): srcDS = gdal.OpenEx('../ogr/data/poly.shp') ds = gdal.VectorTranslate('/vsimem/tmp/poly.shp', srcDS) - if ds is None or ds.GetLayer(0).GetFeatureCount() != 10: - return 'fail' + assert ds is not None and ds.GetLayer(0).GetFeatureCount() == 10 ds = None # Overwrite ds = gdal.VectorTranslate('/vsimem/tmp', srcDS, accessMode='overwrite') - if ds is None or ds.GetLayer(0).GetFeatureCount() != 10: - return 'fail' + assert ds is not None and ds.GetLayer(0).GetFeatureCount() == 10 ds = None ogr.GetDriverByName('ESRI Shapefile').DeleteDataSource('/vsimem/tmp') - return 'success' ############################################################################### # Test filter @@ -280,14 +222,11 @@ def test_ogr2ogr_lib_11(): srcDS = gdal.OpenEx('../ogr/data/poly.shp') ds = gdal.VectorTranslate('', srcDS, format='Memory', spatFilter=[479609, 4764629, 479764, 4764817]) if ogrtest.have_geos(): - if ds is None or ds.GetLayer(0).GetFeatureCount() != 4: - return 'fail' + assert ds is not None and ds.GetLayer(0).GetFeatureCount() == 4 else: - if ds is None or ds.GetLayer(0).GetFeatureCount() != 5: - return 'fail' - - return 'success' + assert ds is not None and ds.GetLayer(0).GetFeatureCount() == 5 + ############################################################################### # Test callback @@ -302,14 +241,9 @@ def test_ogr2ogr_lib_12(): tab = [0] ds = gdal.VectorTranslate('', '../ogr/data/poly.shp', format='Memory', callback=mycallback, callback_data=tab) - if ds is None or ds.GetLayer(0).GetFeatureCount() != 10: - return 'fail' - - if tab[0] != 1.0: - gdaltest.post_reason('Bad percentage') - return 'fail' + assert ds is not None and ds.GetLayer(0).GetFeatureCount() == 10 - return 'success' + assert tab[0] == 1.0, 'Bad percentage' ############################################################################### # Test callback with failure @@ -326,10 +260,7 @@ def test_ogr2ogr_lib_13(): with gdaltest.error_handler(): ds = gdal.VectorTranslate('', '../ogr/data/poly.shp', format='Memory', callback=mycallback_with_failure) - if ds is not None: - return 'fail' - - return 'success' + assert ds is None ############################################################################### # Test internal wrappers @@ -343,8 +274,7 @@ def test_ogr2ogr_lib_14(): except RuntimeError: pass - return 'success' - + ############################################################################### # Test non existing zfield @@ -355,10 +285,7 @@ def test_ogr2ogr_lib_15(): with gdaltest.error_handler(): ds = gdal.VectorTranslate('', srcDS, format='Memory', zField='foo') lyr = ds.GetLayer(0) - if lyr.GetGeomType() != ogr.wkbPolygon: - return 'fail' - - return 'success' + assert lyr.GetGeomType() == ogr.wkbPolygon ############################################################################### # Test -dim @@ -391,15 +318,10 @@ def test_ogr2ogr_lib_16(): lyr = ds.GetLayer(0) f = lyr.GetNextFeature() if f.GetGeometryRef().ExportToIsoWkt() != wkt_after: - gdaltest.post_reason('failure') print(wkt_before) - print(dim) - print(wkt_after) - print(f.GetGeometryRef().ExportToIsoWkt()) - return 'fail' - - return 'success' + pytest.fail(dim) + ############################################################################### # Test gdal.VectorTranslate(dst_ds, ...) without accessMode specified (#6612) @@ -409,12 +331,9 @@ def test_ogr2ogr_lib_17(): ds = gdal.GetDriverByName('Memory').Create('', 0, 0, 0) gdal.VectorTranslate(ds, gdal.OpenEx('../ogr/data/poly.shp')) lyr = ds.GetLayer(0) - if lyr.GetFeatureCount() != 10: - return 'fail' + assert lyr.GetFeatureCount() == 10 ds = None - return 'success' - ############################################################################### # Test -limit @@ -424,12 +343,9 @@ def test_ogr2ogr_lib_18(): ds = gdal.GetDriverByName('Memory').Create('', 0, 0, 0) gdal.VectorTranslate(ds, gdal.OpenEx('../ogr/data/poly.shp'), limit=1) lyr = ds.GetLayer(0) - if lyr.GetFeatureCount() != 1: - return 'fail' + assert lyr.GetFeatureCount() == 1 ds = None - return 'success' - ############################################################################### # Test -addFields + -select @@ -450,18 +366,14 @@ def test_ogr2ogr_lib_19(): lyr = ds.GetLayer(0) f = lyr.GetNextFeature() if f['foo'] != 'bar' or f.IsFieldSet('bar'): - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' + pytest.fail() f = lyr.GetNextFeature() if f['bar'] != 'foo' or f.IsFieldSet('foo'): - gdaltest.post_reason('fail') f.DumpReadable() - return 'fail' + pytest.fail() ds = None - return 'success' - ############################################################################### # Test preservation of source geometry field name @@ -469,7 +381,7 @@ def test_ogr2ogr_lib_19(): def test_ogr2ogr_lib_20(): if ogr.GetDriverByName('GPKG') is None: - return 'skip' + pytest.skip() src_ds = gdal.GetDriverByName('Memory').Create('', 0, 0, 0) lyr = src_ds.CreateLayer('layer', geom_type=ogr.wkbNone) @@ -477,10 +389,7 @@ def test_ogr2ogr_lib_20(): ds = gdal.VectorTranslate('/vsimem/out.gpkg', src_ds, format='GPKG') lyr = ds.GetLayer(0) - if lyr.GetGeometryColumn() != 'foo': - gdaltest.post_reason('fail') - print(lyr.GetGeometryColumn()) - return 'fail' + assert lyr.GetGeometryColumn() == 'foo' ds = None gdal.Unlink('/vsimem/out.gpkg') @@ -491,15 +400,10 @@ def test_ogr2ogr_lib_20(): ds = gdal.VectorTranslate('/vsimem/out.gpkg', src_ds, format='GPKG', selectFields=['bar']) lyr = ds.GetLayer(0) - if lyr.GetGeometryColumn() != 'bar': - gdaltest.post_reason('fail') - print(lyr.GetGeometryColumn()) - return 'fail' + assert lyr.GetGeometryColumn() == 'bar' ds = None gdal.Unlink('/vsimem/out.gpkg') - return 'success' - ############################################################################### # Verify -append and -select options are an invalid combination @@ -524,12 +428,8 @@ def test_ogr2ogr_lib_21(): f.Destroy() src_ds = None - if gdal.GetLastErrorNo() != gdalconst.CPLE_IllegalArg: - gdaltest.post_reason( - 'expected use of -select and -append together to be invalid') - return 'fail' - - return 'success' + assert gdal.GetLastErrorNo() == gdalconst.CPLE_IllegalArg, \ + 'expected use of -select and -append together to be invalid' ############################################################################### @@ -538,7 +438,7 @@ def test_ogr2ogr_lib_21(): def test_ogr2ogr_clipsrc_no_dst_geom(): if not ogrtest.have_geos(): - return 'skip' + pytest.skip() tmpfilename = '/vsimem/out.csv' wkt = 'POLYGON ((479461 4764494,479461 4764196,480012 4764196,480012 4764494,479461 4764494))' @@ -546,45 +446,9 @@ def test_ogr2ogr_clipsrc_no_dst_geom(): options='-f CSV -clipsrc "%s"' % wkt) lyr = ds.GetLayer(0) fc = lyr.GetFeatureCount() - if fc != 1: - gdaltest.post_reason('fail') - print(fc) - return 'fail' + assert fc == 1 ds = None gdal.Unlink(tmpfilename) - return 'success' - -gdaltest_list = [ - test_ogr2ogr_lib_1, - test_ogr2ogr_lib_2, - test_ogr2ogr_lib_3, - test_ogr2ogr_lib_4, - test_ogr2ogr_lib_5, - test_ogr2ogr_lib_6, - test_ogr2ogr_lib_7, - test_ogr2ogr_lib_8, - test_ogr2ogr_lib_9, - test_ogr2ogr_lib_10, - test_ogr2ogr_lib_11, - test_ogr2ogr_lib_12, - test_ogr2ogr_lib_13, - test_ogr2ogr_lib_14, - test_ogr2ogr_lib_15, - test_ogr2ogr_lib_16, - test_ogr2ogr_lib_17, - test_ogr2ogr_lib_18, - test_ogr2ogr_lib_19, - test_ogr2ogr_lib_20, - test_ogr2ogr_lib_21, - test_ogr2ogr_clipsrc_no_dst_geom, -] - -if __name__ == '__main__': - - gdaltest.setup_run('test_ogr2ogr_lib') - - gdaltest.run_tests(gdaltest_list) - - sys.exit(gdaltest.summarize()) + diff --git a/autotest/utilities/test_ogrinfo.py b/autotest/utilities/test_ogrinfo.py index 201805f5af0d..84bc9a901f23 100755 --- a/autotest/utilities/test_ogrinfo.py +++ b/autotest/utilities/test_ogrinfo.py @@ -29,15 +29,14 @@ # DEALINGS IN THE SOFTWARE. ############################################################################### -import sys import os -sys.path.append('../pymod') from osgeo import gdal import gdaltest import ogrtest import test_cli_utilities +import pytest ############################################################################### # Simple test @@ -45,17 +44,11 @@ def test_ogrinfo_1(): if test_cli_utilities.get_ogrinfo_path() is None: - return 'skip' + pytest.skip() (ret, err) = gdaltest.runexternal_out_and_err(test_cli_utilities.get_ogrinfo_path() + ' ../ogr/data/poly.shp') - if not (err is None or err == ''): - gdaltest.post_reason('got error/warning') - print(err) - return 'fail' - if ret.find('ESRI Shapefile') == -1: - return 'fail' - - return 'success' + assert (err is None or err == ''), 'got error/warning' + assert ret.find('ESRI Shapefile') != -1 ############################################################################### # Test -ro option @@ -63,13 +56,10 @@ def test_ogrinfo_1(): def test_ogrinfo_2(): if test_cli_utilities.get_ogrinfo_path() is None: - return 'skip' + pytest.skip() ret = gdaltest.runexternal(test_cli_utilities.get_ogrinfo_path() + ' -ro ../ogr/data/poly.shp') - if ret.find('ESRI Shapefile') == -1: - return 'fail' - - return 'success' + assert ret.find('ESRI Shapefile') != -1 ############################################################################### # Test -al option @@ -77,29 +67,15 @@ def test_ogrinfo_2(): def test_ogrinfo_3(): if test_cli_utilities.get_ogrinfo_path() is None: - return 'skip' + pytest.skip() ret = gdaltest.runexternal(test_cli_utilities.get_ogrinfo_path() + ' -al ../ogr/data/poly.shp') - if ret.find('Layer name: poly') == -1: - gdaltest.post_reason('fail') - return 'fail' - if ret.find('Geometry: Polygon') == -1: - gdaltest.post_reason('fail') - return 'fail' - if ret.find('Feature Count: 10') == -1: - gdaltest.post_reason('fail') - return 'fail' - if ret.find('Extent: (478315') == -1: - gdaltest.post_reason('fail') - return 'fail' - if ret.find('PROJCS["OSGB') == -1: - gdaltest.post_reason('fail') - return 'fail' - if ret.find('AREA: Real (') == -1: - gdaltest.post_reason('fail') - return 'fail' - - return 'success' + assert ret.find('Layer name: poly') != -1 + assert ret.find('Geometry: Polygon') != -1 + assert ret.find('Feature Count: 10') != -1 + assert ret.find('Extent: (478315') != -1 + assert ret.find('PROJCS["OSGB') != -1 + assert ret.find('AREA: Real (') != -1 ############################################################################### # Test layer name @@ -107,13 +83,10 @@ def test_ogrinfo_3(): def test_ogrinfo_4(): if test_cli_utilities.get_ogrinfo_path() is None: - return 'skip' + pytest.skip() ret = gdaltest.runexternal(test_cli_utilities.get_ogrinfo_path() + ' ../ogr/data/poly.shp poly') - if ret.find('Feature Count: 10') == -1: - return 'fail' - - return 'success' + assert ret.find('Feature Count: 10') != -1 ############################################################################### # Test -sql option @@ -121,13 +94,10 @@ def test_ogrinfo_4(): def test_ogrinfo_5(): if test_cli_utilities.get_ogrinfo_path() is None: - return 'skip' + pytest.skip() ret = gdaltest.runexternal(test_cli_utilities.get_ogrinfo_path() + ' ../ogr/data/poly.shp -sql "select * from poly"') - if ret.find('Feature Count: 10') == -1: - return 'fail' - - return 'success' + assert ret.find('Feature Count: 10') != -1 ############################################################################### # Test -geom=NO option @@ -135,15 +105,11 @@ def test_ogrinfo_5(): def test_ogrinfo_6(): if test_cli_utilities.get_ogrinfo_path() is None: - return 'skip' + pytest.skip() ret = gdaltest.runexternal(test_cli_utilities.get_ogrinfo_path() + ' ../ogr/data/poly.shp poly -geom=no') - if ret.find('Feature Count: 10') == -1: - return 'fail' - if ret.find('POLYGON') != -1: - return 'fail' - - return 'success' + assert ret.find('Feature Count: 10') != -1 + assert ret.find('POLYGON') == -1 ############################################################################### # Test -geom=SUMMARY option @@ -151,17 +117,12 @@ def test_ogrinfo_6(): def test_ogrinfo_7(): if test_cli_utilities.get_ogrinfo_path() is None: - return 'skip' + pytest.skip() ret = gdaltest.runexternal(test_cli_utilities.get_ogrinfo_path() + ' ../ogr/data/poly.shp poly -geom=summary') - if ret.find('Feature Count: 10') == -1: - return 'fail' - if ret.find('POLYGON (') != -1: - return 'fail' - if ret.find('POLYGON :') == -1: - return 'fail' - - return 'success' + assert ret.find('Feature Count: 10') != -1 + assert ret.find('POLYGON (') == -1 + assert ret.find('POLYGON :') != -1 ############################################################################### # Test -spat option @@ -169,17 +130,15 @@ def test_ogrinfo_7(): def test_ogrinfo_8(): if test_cli_utilities.get_ogrinfo_path() is None: - return 'skip' + pytest.skip() ret = gdaltest.runexternal(test_cli_utilities.get_ogrinfo_path() + ' ../ogr/data/poly.shp poly -spat 479609 4764629 479764 4764817') if ogrtest.have_geos(): - if ret.find('Feature Count: 4') == -1: - return 'fail' - return 'success' + assert ret.find('Feature Count: 4') != -1 + return else: - if ret.find('Feature Count: 5') == -1: - return 'fail' - return 'success' + assert ret.find('Feature Count: 5') != -1 + return ############################################################################### # Test -where option @@ -187,15 +146,10 @@ def test_ogrinfo_8(): def test_ogrinfo_9(): if test_cli_utilities.get_ogrinfo_path() is None: - return 'skip' + pytest.skip() ret = gdaltest.runexternal(test_cli_utilities.get_ogrinfo_path() + ' ../ogr/data/poly.shp poly -where "EAS_ID=171"') - if ret.find('Feature Count: 1') == -1: - gdaltest.post_reason('fail') - print(ret) - return 'fail' - - return 'success' + assert ret.find('Feature Count: 1') != -1 ############################################################################### # Test -fid option @@ -203,13 +157,10 @@ def test_ogrinfo_9(): def test_ogrinfo_10(): if test_cli_utilities.get_ogrinfo_path() is None: - return 'skip' + pytest.skip() ret = gdaltest.runexternal(test_cli_utilities.get_ogrinfo_path() + ' ../ogr/data/poly.shp poly -fid 9') - if ret.find('OGRFeature(poly):9') == -1: - return 'fail' - - return 'success' + assert ret.find('OGRFeature(poly):9') != -1 ############################################################################### # Test -fields=no option @@ -217,15 +168,11 @@ def test_ogrinfo_10(): def test_ogrinfo_11(): if test_cli_utilities.get_ogrinfo_path() is None: - return 'skip' + pytest.skip() ret = gdaltest.runexternal(test_cli_utilities.get_ogrinfo_path() + ' ../ogr/data/poly.shp poly -fields=no') - if ret.find('AREA (Real') != -1: - return 'fail' - if ret.find('POLYGON (') == -1: - return 'fail' - - return 'success' + assert ret.find('AREA (Real') == -1 + assert ret.find('POLYGON (') != -1 ############################################################################### # Test ogrinfo --version @@ -233,14 +180,10 @@ def test_ogrinfo_11(): def test_ogrinfo_12(): if test_cli_utilities.get_ogrinfo_path() is None: - return 'skip' + pytest.skip() ret = gdaltest.runexternal(test_cli_utilities.get_ogrinfo_path() + ' --version', check_memleak=False) - if ret.find(gdal.VersionInfo('--version')) != 0: - print(ret) - return 'fail' - - return 'success' + assert ret.find(gdal.VersionInfo('--version')) == 0 ############################################################################### # Test erroneous use of --config @@ -248,14 +191,10 @@ def test_ogrinfo_12(): def test_ogrinfo_13(): if test_cli_utilities.get_ogrinfo_path() is None: - return 'skip' + pytest.skip() (_, err) = gdaltest.runexternal_out_and_err(test_cli_utilities.get_ogrinfo_path() + ' --config', check_memleak=False) - if err.find('--config option given without a key and value argument') < 0: - print(err) - return 'fail' - - return 'success' + assert err.find('--config option given without a key and value argument') >= 0 ############################################################################### # Test erroneous use of --mempreload. @@ -263,14 +202,10 @@ def test_ogrinfo_13(): def test_ogrinfo_14(): if test_cli_utilities.get_ogrinfo_path() is None: - return 'skip' + pytest.skip() (_, err) = gdaltest.runexternal_out_and_err(test_cli_utilities.get_ogrinfo_path() + ' --mempreload', check_memleak=False) - if err.find('--mempreload option given without directory path') < 0: - print(err) - return 'fail' - - return 'success' + assert err.find('--mempreload option given without directory path') >= 0 ############################################################################### # Test --mempreload @@ -278,14 +213,10 @@ def test_ogrinfo_14(): def test_ogrinfo_15(): if test_cli_utilities.get_ogrinfo_path() is None: - return 'skip' + pytest.skip() (ret, _) = gdaltest.runexternal_out_and_err(test_cli_utilities.get_ogrinfo_path() + ' --debug on --mempreload ../ogr/data /vsimem/poly.shp', check_memleak=False) - if ret.find("ESRI Shapefile") < 0: - print(ret) - return 'fail' - - return 'success' + assert ret.find("ESRI Shapefile") >= 0 ############################################################################### # Test erroneous use of --debug. @@ -293,14 +224,10 @@ def test_ogrinfo_15(): def test_ogrinfo_16(): if test_cli_utilities.get_ogrinfo_path() is None: - return 'skip' + pytest.skip() (_, err) = gdaltest.runexternal_out_and_err(test_cli_utilities.get_ogrinfo_path() + ' --debug', check_memleak=False) - if err.find('--debug option given without debug level') < 0: - print(err) - return 'fail' - - return 'success' + assert err.find('--debug option given without debug level') >= 0 ############################################################################### # Test erroneous use of --optfile. @@ -308,31 +235,20 @@ def test_ogrinfo_16(): def test_ogrinfo_17(): if test_cli_utilities.get_ogrinfo_path() is None: - return 'skip' + pytest.skip() (_, err) = gdaltest.runexternal_out_and_err(test_cli_utilities.get_ogrinfo_path() + ' --optfile', check_memleak=False) - if err.find('--optfile option given without filename') < 0: - gdaltest.post_reason('fail') - print(err) - return 'fail' + assert err.find('--optfile option given without filename') >= 0 (_, err) = gdaltest.runexternal_out_and_err(test_cli_utilities.get_ogrinfo_path() + ' --optfile /foo/bar', check_memleak=False) - if err.find('Unable to open optfile') < 0: - gdaltest.post_reason('fail') - print(err) - return 'fail' + assert err.find('Unable to open optfile') >= 0 f = open('tmp/optfile.txt', 'wt') f.write('--config foo\n') f.close() (_, err) = gdaltest.runexternal_out_and_err(test_cli_utilities.get_ogrinfo_path() + ' --optfile tmp/optfile.txt', check_memleak=False) os.unlink('tmp/optfile.txt') - if err.find('--config option given without a key and value argument') < 0: - gdaltest.post_reason('fail') - print(err) - return 'fail' - - return 'success' + assert err.find('--config option given without a key and value argument') >= 0 ############################################################################### # Test --optfile @@ -340,7 +256,7 @@ def test_ogrinfo_17(): def test_ogrinfo_18(): if test_cli_utilities.get_ogrinfo_path() is None: - return 'skip' + pytest.skip() f = open('tmp/optfile.txt', 'wt') f.write('# comment\n') @@ -348,11 +264,7 @@ def test_ogrinfo_18(): f.close() ret = gdaltest.runexternal(test_cli_utilities.get_ogrinfo_path() + ' --optfile tmp/optfile.txt', check_memleak=False) os.unlink('tmp/optfile.txt') - if ret.find("ESRI Shapefile") < 0: - print(ret) - return 'fail' - - return 'success' + assert ret.find("ESRI Shapefile") >= 0 ############################################################################### # Test --formats @@ -360,14 +272,10 @@ def test_ogrinfo_18(): def test_ogrinfo_19(): if test_cli_utilities.get_ogrinfo_path() is None: - return 'skip' + pytest.skip() ret = gdaltest.runexternal(test_cli_utilities.get_ogrinfo_path() + ' --formats', check_memleak=False) - if ret.find('ESRI Shapefile -vector- (rw+v): ESRI Shapefile') < 0: - print(ret) - return 'fail' - - return 'success' + assert ret.find('ESRI Shapefile -vector- (rw+v): ESRI Shapefile') >= 0 ############################################################################### # Test --help-general @@ -375,14 +283,10 @@ def test_ogrinfo_19(): def test_ogrinfo_20(): if test_cli_utilities.get_ogrinfo_path() is None: - return 'skip' + pytest.skip() ret = gdaltest.runexternal(test_cli_utilities.get_ogrinfo_path() + ' --help-general', check_memleak=False) - if ret.find('Generic GDAL utility command options') < 0: - print(ret) - return 'fail' - - return 'success' + assert ret.find('Generic GDAL utility command options') >= 0 ############################################################################### # Test --locale @@ -390,14 +294,10 @@ def test_ogrinfo_20(): def test_ogrinfo_21(): if test_cli_utilities.get_ogrinfo_path() is None: - return 'skip' + pytest.skip() ret = gdaltest.runexternal(test_cli_utilities.get_ogrinfo_path() + ' --locale C ../ogr/data/poly.shp', check_memleak=False) - if ret.find("ESRI Shapefile") < 0: - print(ret) - return 'fail' - - return 'success' + assert ret.find("ESRI Shapefile") >= 0 ############################################################################### # Test RFC 41 support @@ -405,7 +305,7 @@ def test_ogrinfo_21(): def test_ogrinfo_22(): if test_cli_utilities.get_ogrinfo_path() is None: - return 'skip' + pytest.skip() f = open('tmp/test_ogrinfo_22.csv', 'wt') f.write('_WKTgeom1_EPSG_4326,_WKTgeom2_EPSG_32631\n') @@ -413,9 +313,7 @@ def test_ogrinfo_22(): f.close() ret = gdaltest.runexternal(test_cli_utilities.get_ogrinfo_path() + ' tmp/test_ogrinfo_22.csv', check_memleak=False) - if ret.find('1: test_ogrinfo_22 (Unknown (any), Unknown (any))') < 0: - print(ret) - return 'fail' + assert ret.find('1: test_ogrinfo_22 (Unknown (any), Unknown (any))') >= 0 ret = gdaltest.runexternal(test_cli_utilities.get_ogrinfo_path() + ' -al tmp/test_ogrinfo_22.csv', check_memleak=False) expected_ret = """INFO: Open of `tmp/test_ogrinfo_22.csv' @@ -474,21 +372,17 @@ def test_ogrinfo_22(): expected_lines = expected_ret.splitlines() lines = ret.splitlines() for i, exp_line in enumerate(expected_lines): - if exp_line != lines[i]: - print(ret) - return 'fail' + assert exp_line == lines[i], ret os.unlink('tmp/test_ogrinfo_22.csv') - return 'success' - ############################################################################### # Test -geomfield (RFC 41) support def test_ogrinfo_23(): if test_cli_utilities.get_ogrinfo_path() is None: - return 'skip' + pytest.skip() f = open('tmp/test_ogrinfo_23.csv', 'wt') f.write('_WKTgeom1_EPSG_4326,_WKTgeom2_EPSG_32631\n') @@ -553,21 +447,17 @@ def test_ogrinfo_23(): expected_lines = expected_ret.splitlines() lines = ret.splitlines() for i, exp_line in enumerate(expected_lines): - if exp_line != lines[i]: - print(ret) - return 'fail' + assert exp_line == lines[i], ret os.unlink('tmp/test_ogrinfo_23.csv') - return 'success' - ############################################################################### # Test metadata def test_ogrinfo_24(): if test_cli_utilities.get_ogrinfo_path() is None: - return 'skip' + pytest.skip() f = open('tmp/test_ogrinfo_24.vrt', 'wt') f.write("""<OGRVRTDataSource> @@ -628,10 +518,9 @@ def test_ogrinfo_24(): lines = ret.splitlines() for i, exp_line in enumerate(expected_lines): if exp_line != lines[i]: - print(ret) if gdaltest.is_travis_branch('mingw'): return 'expected_fail' - return 'fail' + pytest.fail(ret) ret = gdaltest.runexternal(test_cli_utilities.get_ogrinfo_path() + ' -ro -al tmp/test_ogrinfo_24.vrt -so -mdd all', check_memleak=False) expected_ret = """INFO: Open of `tmp/test_ogrinfo_24.vrt' using driver `OGR_VRT' successful. @@ -678,10 +567,9 @@ def test_ogrinfo_24(): lines = ret.splitlines() for i, exp_line in enumerate(expected_lines): if exp_line != lines[i]: - print(ret) if gdaltest.is_travis_branch('mingw'): return 'expected_fail' - return 'fail' + pytest.fail(ret) ret = gdaltest.runexternal(test_cli_utilities.get_ogrinfo_path() + ' -ro -al tmp/test_ogrinfo_24.vrt -so -nomd', check_memleak=False) expected_ret = """INFO: Open of `tmp/test_ogrinfo_24.vrt' @@ -723,34 +611,24 @@ def test_ogrinfo_24(): lines = ret.splitlines() for i, exp_line in enumerate(expected_lines): if exp_line != lines[i]: - print(ret) if gdaltest.is_travis_branch('mingw'): return 'expected_fail' - return 'fail' + pytest.fail(ret) os.unlink('tmp/test_ogrinfo_24.vrt') - return 'success' - ############################################################################### # Test -rl def test_ogrinfo_25(): if test_cli_utilities.get_ogrinfo_path() is None: - return 'skip' + pytest.skip() (ret, err) = gdaltest.runexternal_out_and_err(test_cli_utilities.get_ogrinfo_path() + ' -rl -q ../ogr/data/poly.shp') - if not (err is None or err == ''): - gdaltest.post_reason('got error/warning') - print(err) - return 'fail' - if ret.find('OGRFeature(poly):0') < 0 or ret.find('OGRFeature(poly):9') < 0: - gdaltest.post_reason('wrong output') - print(ret) - return 'fail' - - return 'success' + assert (err is None or err == ''), 'got error/warning' + assert ret.find('OGRFeature(poly):0') >= 0 and ret.find('OGRFeature(poly):9') >= 0, \ + 'wrong output' ############################################################################### @@ -759,57 +637,15 @@ def test_ogrinfo_25(): def test_ogrinfo_sql_filename(): if test_cli_utilities.get_ogrinfo_path() is None: - return 'skip' + pytest.skip() open('tmp/my.sql', 'wt').write('-- initial comment\nselect * from poly\n-- trailing comment') (ret, err) = gdaltest.runexternal_out_and_err(test_cli_utilities.get_ogrinfo_path() + ' -q ../ogr/data/poly.shp -sql @tmp/my.sql') os.unlink('tmp/my.sql') - if not (err is None or err == ''): - gdaltest.post_reason('got error/warning') - print(err) - return 'fail' - if ret.find('OGRFeature(poly):0') < 0 or ret.find('OGRFeature(poly):9') < 0: - gdaltest.post_reason('wrong output') - print(ret) - return 'fail' - - return 'success' - - -gdaltest_list = [ - test_ogrinfo_1, - test_ogrinfo_2, - test_ogrinfo_3, - test_ogrinfo_4, - test_ogrinfo_5, - test_ogrinfo_6, - test_ogrinfo_7, - test_ogrinfo_8, - test_ogrinfo_9, - test_ogrinfo_10, - test_ogrinfo_11, - test_ogrinfo_12, - test_ogrinfo_13, - test_ogrinfo_14, - test_ogrinfo_15, - test_ogrinfo_16, - test_ogrinfo_17, - test_ogrinfo_18, - test_ogrinfo_19, - test_ogrinfo_20, - test_ogrinfo_21, - test_ogrinfo_22, - test_ogrinfo_23, - test_ogrinfo_24, - test_ogrinfo_25, - test_ogrinfo_sql_filename, -] - - -if __name__ == '__main__': - - gdaltest.setup_run('test_ogrinfo') - - gdaltest.run_tests(gdaltest_list) - - sys.exit(gdaltest.summarize()) + assert (err is None or err == ''), 'got error/warning' + assert ret.find('OGRFeature(poly):0') >= 0 and ret.find('OGRFeature(poly):9') >= 0, \ + 'wrong output' + + + + diff --git a/autotest/utilities/test_ogrlineref.py b/autotest/utilities/test_ogrlineref.py index 0fda9c04ec4b..4f8346d34ab1 100755 --- a/autotest/utilities/test_ogrlineref.py +++ b/autotest/utilities/test_ogrlineref.py @@ -30,8 +30,8 @@ import sys import os +import pytest -sys.path.append('../pymod') sys.path.append('../ogr') from osgeo import ogr @@ -45,21 +45,16 @@ def test_ogrlineref_1(): if not ogrtest.have_geos() or test_cli_utilities.get_ogrlineref_path() is None: - return 'skip' + pytest.skip() if os.path.exists('tmp/parts.shp'): ogr.GetDriverByName('ESRI Shapefile').DeleteDataSource('tmp/parts.shp') _, err = gdaltest.runexternal_out_and_err(test_cli_utilities.get_ogrlineref_path() + ' -create -l data/path.shp -p data/mstones.shp -pm pos -o tmp/parts.shp -s 1000') - if err is not None and err != '': - gdaltest.post_reason('got error/warning: "%s"' % err) - return 'fail' + assert err is None or err == '', ('got error/warning: "%s"' % err) ds = ogr.Open('tmp/parts.shp') - if ds is None or ds.GetLayer(0).GetFeatureCount() != 9: - return 'fail' - - return 'success' + assert ds is not None and ds.GetLayer(0).GetFeatureCount() == 9 ############################################################################### # get_pos test @@ -67,17 +62,12 @@ def test_ogrlineref_1(): def test_ogrlineref_2(): if not ogrtest.have_geos() or test_cli_utilities.get_ogrlineref_path() is None: - return 'skip' + pytest.skip() ret = gdaltest.runexternal(test_cli_utilities.get_ogrlineref_path() + ' -get_pos -r tmp/parts.shp -x -1.4345 -y 51.9497 -quiet').strip() expected = '15977.724709' - if ret != expected: - gdaltest.post_reason('"%s" != %s' % (ret.strip(), expected)) - print(ret) - return 'fail' - - return 'success' + assert ret == expected, ('"%s" != %s' % (ret.strip(), expected)) ############################################################################### # get_coord test @@ -85,16 +75,12 @@ def test_ogrlineref_2(): def test_ogrlineref_3(): if not ogrtest.have_geos() or test_cli_utilities.get_ogrlineref_path() is None: - return 'skip' + pytest.skip() ret = gdaltest.runexternal(test_cli_utilities.get_ogrlineref_path() + ' -get_coord -r tmp/parts.shp -m 15977.724709 -quiet').strip() expected = '-1.435097,51.950080,0.000000' - if ret != expected: - gdaltest.post_reason('%s != %s' % (ret.strip(), expected)) - return 'fail' - - return 'success' + assert ret == expected, ('%s != %s' % (ret.strip(), expected)) ############################################################################### # get_subline test @@ -102,7 +88,7 @@ def test_ogrlineref_3(): def test_ogrlineref_4(): if not ogrtest.have_geos() or test_cli_utilities.get_ogrlineref_path() is None: - return 'skip' + pytest.skip() if os.path.exists('tmp/subline.shp'): ogr.GetDriverByName('ESRI Shapefile').DeleteDataSource('tmp/subline.shp') @@ -110,63 +96,41 @@ def test_ogrlineref_4(): gdaltest.runexternal(test_cli_utilities.get_ogrlineref_path() + ' -get_subline -r tmp/parts.shp -mb 13300 -me 17400 -o tmp/subline.shp') ds = ogr.Open('tmp/subline.shp') - if ds is None: - gdaltest.post_reason('ds is None') - return 'fail' + assert ds is not None, 'ds is None' feature_count = ds.GetLayer(0).GetFeatureCount() - if feature_count != 1: - gdaltest.post_reason('feature count %d != 1' % feature_count) - return 'fail' + assert feature_count == 1, ('feature count %d != 1' % feature_count) ds = None ogr.GetDriverByName('ESRI Shapefile').DeleteDataSource('tmp/subline.shp') - return 'success' - ############################################################################### # test kml def test_ogrlineref_5(): if not ogrtest.have_geos() or test_cli_utilities.get_ogrlineref_path() is None: - return 'skip' + pytest.skip() if os.path.exists('tmp/parts.kml'): ogr.GetDriverByName('KML').DeleteDataSource('tmp/parts.kml') gdaltest.runexternal_out_and_err(test_cli_utilities.get_ogrlineref_path() + ' -create -f "KML" -l data/path.shp -p data/mstones.shp -pm pos -o tmp/parts.kml -s 222') if os.path.exists('tmp/parts.kml'): - return 'success' + return - return 'fail' + pytest.fail() def test_ogrlineref_cleanup(): if not ogrtest.have_geos() or test_cli_utilities.get_ogrlineref_path() is None: - return 'skip' + pytest.skip() if os.path.exists('tmp/parts.shp'): ogr.GetDriverByName('ESRI Shapefile').DeleteDataSource('tmp/parts.shp') if os.path.exists('tmp/parts.kml'): ogr.GetDriverByName('KML').DeleteDataSource('tmp/parts.kml') - return 'success' - - -gdaltest_list = [ - test_ogrlineref_1, - test_ogrlineref_2, - test_ogrlineref_3, - test_ogrlineref_4, - test_ogrlineref_5, - test_ogrlineref_cleanup -] - -if __name__ == '__main__': - - gdaltest.setup_run('test_ogrlineref') + - gdaltest.run_tests(gdaltest_list) - sys.exit(gdaltest.summarize()) diff --git a/autotest/utilities/test_ogrtindex.py b/autotest/utilities/test_ogrtindex.py index 4344aaa3fdab..d8cb0824fe32 100755 --- a/autotest/utilities/test_ogrtindex.py +++ b/autotest/utilities/test_ogrtindex.py @@ -29,16 +29,15 @@ # DEALINGS IN THE SOFTWARE. ############################################################################### -import sys import os -sys.path.append('../pymod') from osgeo import ogr from osgeo import osr import ogrtest import gdaltest import test_cli_utilities +import pytest ############################################################################### # Simple test @@ -46,7 +45,7 @@ def test_ogrtindex_1(srs=None): if test_cli_utilities.get_ogrtindex_path() is None: - return 'skip' + pytest.skip() shape_drv = ogr.GetDriverByName('ESRI Shapefile') @@ -86,24 +85,16 @@ def test_ogrtindex_1(srs=None): shape_ds.Destroy() (_, err) = gdaltest.runexternal_out_and_err(test_cli_utilities.get_ogrtindex_path() + ' -skip_different_projection tmp/tileindex.shp tmp/point1.shp tmp/point2.shp tmp/point3.shp tmp/point4.shp') - if not (err is None or err == ''): - gdaltest.post_reason('got error/warning') - print(err) - return 'fail' + assert (err is None or err == ''), 'got error/warning' ds = ogr.Open('tmp/tileindex.shp') - if ds.GetLayer(0).GetFeatureCount() != 4: - gdaltest.post_reason('did not get expected feature count') - return 'fail' + assert ds.GetLayer(0).GetFeatureCount() == 4, 'did not get expected feature count' if srs is not None: - if ds.GetLayer(0).GetSpatialRef() is None or not ds.GetLayer(0).GetSpatialRef().IsSame(srs): - gdaltest.post_reason('did not get expected spatial ref') - return 'fail' + assert ds.GetLayer(0).GetSpatialRef() is not None and ds.GetLayer(0).GetSpatialRef().IsSame(srs), \ + 'did not get expected spatial ref' else: - if ds.GetLayer(0).GetSpatialRef() is not None: - gdaltest.post_reason('did not get expected spatial ref') - return 'fail' + assert ds.GetLayer(0).GetSpatialRef() is None, 'did not get expected spatial ref' expected_wkts = ['POLYGON ((49 2,49 2,49 2,49 2,49 2))', 'POLYGON ((49 3,49 3,49 3,49 3,49 3))', @@ -112,15 +103,12 @@ def test_ogrtindex_1(srs=None): i = 0 feat = ds.GetLayer(0).GetNextFeature() while feat is not None: - if feat.GetGeometryRef().ExportToWkt() != expected_wkts[i]: - print('i=%d, wkt=%s' % (i, feat.GetGeometryRef().ExportToWkt())) - return 'fail' + assert feat.GetGeometryRef().ExportToWkt() == expected_wkts[i], \ + ('i=%d, wkt=%s' % (i, feat.GetGeometryRef().ExportToWkt())) i = i + 1 feat = ds.GetLayer(0).GetNextFeature() ds.Destroy() - return 'success' - ############################################################################### # Same test but with a SRS set on the different tiles to index @@ -139,7 +127,7 @@ def test_ogrtindex_2(): def test_ogrtindex_3(): if test_cli_utilities.get_ogrtindex_path() is None: - return 'skip' + pytest.skip() shape_drv = ogr.GetDriverByName('ESRI Shapefile') @@ -196,19 +184,15 @@ def test_ogrtindex_3(): test_cli_utilities.get_ogrtindex_path() + ' -src_srs_name src_srs -t_srs EPSG:4326 ' + output_filename + ' tmp/point1.shp tmp/point2.shp ' + src_srs_format + output_format) - if src_srs_format != '-src_srs_format WKT' and not (err is None or err == ''): - gdaltest.post_reason('got error/warning') - print(err) - return 'fail' + assert src_srs_format == '-src_srs_format WKT' or (err is None or err == ''), \ + 'got error/warning' ds = ogr.Open(output_filename) - if ds.GetLayer(0).GetFeatureCount() != 2: - gdaltest.post_reason('did not get expected feature count') - return 'fail' + assert ds.GetLayer(0).GetFeatureCount() == 2, \ + 'did not get expected feature count' - if ds.GetLayer(0).GetSpatialRef().GetAuthorityCode(None) != '4326': - gdaltest.post_reason('did not get expected spatial ref') - return 'fail' + assert ds.GetLayer(0).GetSpatialRef().GetAuthorityCode(None) == '4326', \ + 'did not get expected spatial ref' expected_wkts = ['POLYGON ((2 49,2 49,2 49,2 49,2 49))', 'POLYGON ((3 50,3 50,3 50,3 50,3 50))'] @@ -216,13 +200,10 @@ def test_ogrtindex_3(): feat = ds.GetLayer(0).GetNextFeature() while feat is not None: if feat.GetField('src_srs') != expected_srss[i]: - gdaltest.post_reason('fail') - print(i, src_srs_format) feat.DumpReadable() - return 'fail' - if ogrtest.check_feature_geometry(feat, expected_wkts[i]) != 0: - print('i=%d, wkt=%s' % (i, feat.GetGeometryRef().ExportToWkt())) - return 'fail' + pytest.fail(i, src_srs_format) + assert ogrtest.check_feature_geometry(feat, expected_wkts[i]) == 0, \ + ('i=%d, wkt=%s' % (i, feat.GetGeometryRef().ExportToWkt())) i = i + 1 feat = ds.GetLayer(0).GetNextFeature() ds = None @@ -232,15 +213,14 @@ def test_ogrtindex_3(): if os.path.exists('tmp/tileindex.db'): os.unlink('tmp/tileindex.db') - return 'success' - + ############################################################################### # Cleanup def test_ogrtindex_cleanup(): if test_cli_utilities.get_ogrtindex_path() is None: - return 'skip' + pytest.skip() shape_drv = ogr.GetDriverByName('ESRI Shapefile') shape_drv.DeleteDataSource('tmp/tileindex.shp') @@ -251,21 +231,7 @@ def test_ogrtindex_cleanup(): if os.path.exists('tmp/point4.shp'): shape_drv.DeleteDataSource('tmp/point4.shp') - return 'success' - - -gdaltest_list = [ - test_ogrtindex_1, - test_ogrtindex_2, - test_ogrtindex_3, - test_ogrtindex_cleanup -] - - -if __name__ == '__main__': + - gdaltest.setup_run('test_ogrtindex') - gdaltest.run_tests(gdaltest_list) - sys.exit(gdaltest.summarize()) diff --git a/gdal/ci/travis/gcc52_stdcpp14_sanitize/script.sh b/gdal/ci/travis/gcc52_stdcpp14_sanitize/script.sh index 6261ee566cf4..f4a4e9d2a3cb 100755 --- a/gdal/ci/travis/gcc52_stdcpp14_sanitize/script.sh +++ b/gdal/ci/travis/gcc52_stdcpp14_sanitize/script.sh @@ -1,4 +1,4 @@ -#!/bin/sh +#!/bin/bash set -e @@ -6,7 +6,7 @@ export PATH=$PWD/install-gcc-5.2.0/bin:$PATH export LD_LIBRARY_PATH=$PWD/install-gcc-5.2.0/lib64 export PRELOAD=$PWD/install-gcc-5.2.0/lib64/libasan.so.2.0.0:$PWD/install-gcc-5.2.0/lib64/libubsan.so.0.0.0 #export PRELOAD=$PWD/install-gcc-5.2.0/lib64/libubsan.so.0.0.0 -export ASAN_OPTIONS=allocator_may_return_null=1 +export PYTEST="pytest -vv -p no:sugar --color=no" cd gdal @@ -33,24 +33,51 @@ cd ../autotest #wget http://download.osgeo.org/gdal/data/pgeo/PGeoTest.zip #unzip PGeoTest.zip #cd ../../.. -# Run ogr_fgdb.py in isolation from the rest -(cd ogr - mkdir disabled - mv ogr_fgdb.* disabled -) -# Run ogr_pgeo.py in isolation from the rest -(cd ogr && mv ogr_pgeo.* disabled) +# Don't run these +rm ogr/ogr_fgdb.py ogr/ogr_pgeo.py # Too old spatialite version -(cd ogr && mv ogr_sqlite.* disabled) -(cd gdrivers && mkdir disabled && mv rasterlite.* disabled) +rm ogr/ogr_sqlite.py gdrivers/rasterlite.py + +# install test dependencies +# note: pip 9 is installed on the box, but it hits a strange error after upgrading setuptools. +# so we install a newer pip first. +sudo -H pip install -U pip +sudo -H pip install -U -r ./requirements.txt + + +# Run each module in its own pytest process. +# This makes sure the output from the address sanitizer is relevant +# and it doesn't blow out RAM too much. +# Unfortunately it's also a reasonably large slowdown since we have to wait +# for a python interpreter and all modules to load between each module. +# (and add a grep to get rid of the extra pytest header headers/etc) +# +# NOTE: `find ... -exec` always exits with 0 even when the tests failed. +# That turns out to be what we want here though, since we want +# to not fail when the address sanitizer finds errors. +# So we tee the output to a file and grep it to discover if the tests failed. +export SKIP_MEM_INTENSIVE_TEST=YES SKIP_VIRTUALMEM=YES LD_PRELOAD=$PRELOAD \ + ASAN_OPTIONS=detect_leaks=1,print_suppressions=0,suppressions=$PWD/asan_suppressions.txt +find \ + ogr gcore gdrivers osr alg gnm utilities pyscripts \ + -name '*.py' ! -name netcdf_cfchecks.py ! -name "__init__.py" \ + -print \ + -exec $PYTEST -o console_output_style=classic {} \; \ + | tee ./test-output.txt + +# Check if the tests failed and error out. +if grep -P '===.*\d+ failed' ./test-output.txt > /dev/null ; then + echo 'Tests failed' + exit 1 +else + echo 'Tests passed' +fi -# Run all the Python autotests -SKIP_MEM_INTENSIVE_TEST=YES SKIP_VIRTUALMEM=YES LD_PRELOAD=$PRELOAD ASAN_OPTIONS=detect_leaks=0 GDALTEST_ASAN_OPTIONS=detect_leaks=1,print_suppressions=0,suppressions=$PWD/asan_suppressions.txt python run_all.py -run_as_external # A bit messy, but force testing with libspatialite 4.0dev (that has been patched a bit to remove any hard-coded SRS definition so it is very small) #cd ogr #wget http://s3.amazonaws.com/etc-data.koordinates.com/gdal-travisci/libspatialite4.0dev_ubuntu12.04-64bit_srs_stripped.tar.gz #tar xzf libspatialite4.0dev_ubuntu12.04-64bit_srs_stripped.tar.gz #ln -s install-libspatialite-4.0dev/lib/libspatialite.so.5.0.1 libspatialite.so.3 -#LD_PRELOAD=$PRELOAD LD_LIBRARY_PATH=$LD_LIBRARY_PATH:$PWD python ogr_sqlite.py +#LD_PRELOAD=$PRELOAD LD_LIBRARY_PATH=$LD_LIBRARY_PATH:$PWD $PYTEST ogr_sqlite.py #cd .. diff --git a/gdal/ci/travis/mingw_w64/before_install.sh b/gdal/ci/travis/mingw_w64/before_install.sh index 2deb734238b2..8134a1b1b02f 100755 --- a/gdal/ci/travis/mingw_w64/before_install.sh +++ b/gdal/ci/travis/mingw_w64/before_install.sh @@ -5,10 +5,12 @@ set -e cat /etc/apt/sources.list ls -al /etc/apt/sources.list.d sudo apt-get update -qq -sudo apt-get install ccache -sudo apt-get install binutils-mingw-w64-x86-64 -sudo apt-get install gcc-mingw-w64-x86-64 -sudo apt-get install g++-mingw-w64-x86-64 -sudo apt-get install g++-mingw-w64 -sudo apt-get install mingw-w64-tools -sudo apt-get install -y wine1.4-amd64 +sudo apt-get install -y \ + ccache \ + binutils-mingw-w64-x86-64 \ + gcc-mingw-w64-x86-64 \ + g++-mingw-w64-x86-64 \ + g++-mingw-w64 \ + mingw-w64-tools \ + wine1.4-amd64 \ + curl diff --git a/gdal/ci/travis/mingw_w64/install.sh b/gdal/ci/travis/mingw_w64/install.sh index 47f5a9395828..026c126db2ad 100755 --- a/gdal/ci/travis/mingw_w64/install.sh +++ b/gdal/ci/travis/mingw_w64/install.sh @@ -31,8 +31,8 @@ cd .. ln -sf $PWD/.libs/libgdal-20.dll $HOME/.wine/drive_c/windows ln -sf $PWD/../proj-4.9.2/src/.libs/libproj-9.dll $HOME/.wine/drive_c/windows # Python bindings -wget http://www.python.org/ftp/python/2.7.3/python-2.7.3.amd64.msi -wine64 msiexec /i python-2.7.3.amd64.msi +wget https://www.python.org/ftp/python/2.7.15/python-2.7.15.amd64.msi +wine64 msiexec /i python-2.7.15.amd64.msi cd swig/python gendef $HOME/.wine/drive_c/Python27/python27.dll x86_64-w64-mingw32-dlltool --dllname $HOME/.wine/drive_c/Python27/python27.dll --input-def python27.def --output-lib $HOME/.wine/drive_c/Python27/libs/libpython27.a diff --git a/gdal/ci/travis/mingw_w64/script.sh b/gdal/ci/travis/mingw_w64/script.sh index 9758e3046297..04d4372b16ef 100755 --- a/gdal/ci/travis/mingw_w64/script.sh +++ b/gdal/ci/travis/mingw_w64/script.sh @@ -7,11 +7,27 @@ cd gdal wine64 apps/gdalinfo.exe --version cd ../autotest # Does not work under wine -rm gcore/gdal_api_proxy.py -rm gcore/rfc30.py +rm gcore/gdal_api_proxy.py gcore/rfc30.py +rm gnm/gnm_test.py # For some reason this crashes in the matrix .travis.yml but not in standalone branch rm pyscripts/test_gdal2tiles.py +export PYTHON_DIR="$HOME/.wine/drive_c/Python27" + +# install test dependencies +curl https://bootstrap.pypa.io/get-pip.py -o get-pip.py +wine64 "$PYTHON_DIR/python.exe" get-pip.py +rm get-pip.py +# running pip2.7.exe doesn't seem to work in wine. workaround is use `-m pip` +# https://forum.winehq.org/viewtopic.php?f=2&t=22522 +wine64 "$PYTHON_DIR/python.exe" -m pip install -U -r ./requirements.txt +# same issue with running pytest.exe +export PYTEST="wine64 $PYTHON_DIR/python.exe -m pytest -vv -p no:sugar --color=no" + + # Run all the Python autotests -GDAL_DATA=$PWD/../gdal/data PYTHONPATH=$PWD/../gdal/swig/python/build/lib.win-amd64-2.7 PATH=$PWD/../gdal:$PWD/../gdal/apps/.libs:$PWD:$PATH $HOME/.wine/drive_c/Python27/python.exe run_all.py +GDAL_DATA=$PWD/../gdal/data \ + PYTHONPATH=$PWD/../gdal/swig/python/build/lib.win-amd64-2.7 \ + PATH=$PWD/../gdal:$PWD/../gdal/apps/.libs:$PWD:$PATH \ + $PYTEST diff --git a/gdal/ci/travis/osx/before_install.sh b/gdal/ci/travis/osx/before_install.sh index 7ef1badf6851..bc0656647160 100755 --- a/gdal/ci/travis/osx/before_install.sh +++ b/gdal/ci/travis/osx/before_install.sh @@ -4,5 +4,4 @@ set -e brew update brew uninstall postgis gdal -brew install sqlite3 -brew install ccache +brew install sqlite3 ccache diff --git a/gdal/ci/travis/osx/script.sh b/gdal/ci/travis/osx/script.sh index 9f43d2014ef1..1435d1c73b1c 100755 --- a/gdal/ci/travis/osx/script.sh +++ b/gdal/ci/travis/osx/script.sh @@ -3,12 +3,19 @@ set -e export PYTHONPATH=$PWD/gdal/swig/python/build/lib.macosx-10.12-intel-2.7:$PWD/gdal/swig/python/build/lib.macosx-10.11-x86_64-2.7 +export PYTEST="pytest -vv -p no:sugar --color=no" -# CPP unit tests +echo 'Running CPP unit tests' (cd autotest/cpp && GDAL_SKIP=JP2ECW make quick_test) +echo 'Running Python unit tests' +# install test dependencies +sudo -H pip install -U -r autotest/requirements.txt + # Run all the Python autotests +cd autotest +$PYTEST # For some reason, the tests crash at process exit -(cd autotest; python run_all.py 2>&1 | tee /tmp/log.txt || /bin/true) -tail /tmp/log.txt | grep "Failed: 0 (0 blew exceptions)" >/dev/null +# (cd autotest; $PYTEST 2>&1 | tee /tmp/log.txt || /bin/true) +# tail /tmp/log.txt | grep "Failed: 0 (0 blew exceptionss)" >/dev/null diff --git a/gdal/ci/travis/python3/script.sh b/gdal/ci/travis/python3/script.sh index 96585bb8c3f1..c99defb39fc5 100755 --- a/gdal/ci/travis/python3/script.sh +++ b/gdal/ci/travis/python3/script.sh @@ -31,20 +31,25 @@ cd ogr/tmp/cache/ wget http://download.osgeo.org/gdal/data/pgeo/PGeoTest.zip unzip PGeoTest.zip cd ../../.. + +# install test dependencies +curl -sSL 'https://bootstrap.pypa.io/get-pip.py' | sudo python3 +sudo -H pip3 install -U -r ./requirements.txt + +PYTEST="python3 $(which pytest) -vv -p no:sugar --color=no" + # Run ogr_fgdb.py in isolation from the rest +$PYTEST ogr/ogr_fgdb.py +PYTESTARGS="--ignore ogr/ogr_fgdb.py" -(cd ogr && python3 ogr_fgdb.py) -(cd ogr && mkdir disabled && mv ogr_fgdb.* disabled) # Run ogr_pgeo.py in isolation from the rest # This crashes on Trusty since travis-ci upgraded their Trusty workers #python ogr_pgeo.py -(cd ogr && mv ogr_pgeo.* disabled) +PYTESTARGS="$PYTESTARGS --ignore ogr/ogr_pgeo.py" # Fails on test_validate_jp2_2 (erros not in expected order) -(cd gdrivers && mkdir disabled && mv test_validate_jp2.* disabled) +PYTESTARGS="$PYTESTARGS --ignore gdrivers/test_validate_jp2.py" # Run all the Python autotests -# For some reason, the tests crash at process exit -GDAL_SKIP="JP2ECW ECW" python3 run_all.py 2>&1 | tee /tmp/log.txt || /bin/true -tail /tmp/log.txt | grep "Failed: 0 (0 blew exceptions)" >/dev/null +GDAL_SKIP="JP2ECW ECW" $PYTEST $PYTESTARGS diff --git a/gdal/ci/travis/trusty_32bit/before_install.sh b/gdal/ci/travis/trusty_32bit/before_install.sh index 6768a39ecb2b..0ad4485f9f57 100755 --- a/gdal/ci/travis/trusty_32bit/before_install.sh +++ b/gdal/ci/travis/trusty_32bit/before_install.sh @@ -31,3 +31,4 @@ sudo i386 chroot "$chroot" apt-get install -y --force-yes python-numpy libpng12- sudo i386 chroot "$chroot" apt-get install -y make sudo i386 chroot "$chroot" apt-get install -y python-dev sudo i386 chroot "$chroot" apt-get install -y g++ +sudo i386 chroot "$chroot" apt-get install -y --force-yes curl diff --git a/gdal/ci/travis/trusty_32bit/script.sh b/gdal/ci/travis/trusty_32bit/script.sh index a9014fe5a39c..58fa5a7661c6 100755 --- a/gdal/ci/travis/trusty_32bit/script.sh +++ b/gdal/ci/travis/trusty_32bit/script.sh @@ -4,6 +4,7 @@ set -e export chroot="$PWD"/buildroot.i386 export LC_ALL=en_US.utf8 +export PYTEST="pytest -vv -p no:sugar --color=no" i386 chroot "$chroot" sh -c "cd $PWD/autotest/cpp && make quick_test" # Compile and test vsipreload @@ -17,8 +18,12 @@ i386 chroot "$chroot" sh -c "cd $PWD/autotest/cpp && make vsipreload.so" mv autotest/gcore/vsigs.py autotest/gcore/vsigs.py.disabled +# install pip and use it to install test dependencies +sudo i386 chroot "$chroot" sh -c "curl -sSL 'https://bootstrap.pypa.io/get-pip.py' | python" +sudo i386 chroot "$chroot" pip install -U -r "$PWD/autotest/requirements.txt" + # Run all the Python autotests -i386 chroot "$chroot" sh -c "cd $PWD/autotest && python run_all.py" +i386 chroot "$chroot" sh -c "cd $PWD/autotest && $PYTEST" # Run Shellcheck shellcheck -e SC2086,SC2046 $(find $PWD/gdal -name '*.sh' -a -not -name ltmain.sh) diff --git a/gdal/ci/travis/trusty_clang/before_install.sh b/gdal/ci/travis/trusty_clang/before_install.sh index 13b96b1828bc..3d19a7e07653 100755 --- a/gdal/ci/travis/trusty_clang/before_install.sh +++ b/gdal/ci/travis/trusty_clang/before_install.sh @@ -27,11 +27,13 @@ sudo apt-get install -y libogdi3.2-dev sudo apt-get install -y mono-mcs libmono-system-drawing4.0-cil # Boost for Mongo #sudo apt-get install -y libboost-regex-dev libboost-system-dev libboost-thread-dev -sudo pip install pyflakes +sudo pip install flake8 sudo apt-get install doxygen texlive-latex-base -pyflakes autotest -pyflakes gdal/swig/python/scripts -pyflakes gdal/swig/python/samples +# flake8 codes to just emulate pyflakes (http://flake8.pycqa.org/en/latest/user/error-codes.html) +FLAKE8="flake8 --select=F401,F402,F403,F404,F405,F406,F407,F601,F602,F621,F622,F631,F701,F702,F703,F704,F705,F706,F707,F721,F722,F811,F812,F821,F822,F823,F831,F841,F901" +$FLAKE8 autotest +$FLAKE8 gdal/swig/python/scripts +$FLAKE8 gdal/swig/python/samples psql -c "drop database if exists autotest" -U postgres psql -c "create database autotest" -U postgres psql -c "create extension postgis" -d autotest -U postgres diff --git a/gdal/ci/travis/trusty_clang/script.sh b/gdal/ci/travis/trusty_clang/script.sh index e6378efaca89..2c88405419b7 100755 --- a/gdal/ci/travis/trusty_clang/script.sh +++ b/gdal/ci/travis/trusty_clang/script.sh @@ -6,6 +6,7 @@ set -e # Run it in isolation export JAVA_HOME=/usr/lib/jvm/java-8-openjdk-amd64 export PATH=$JAVA_HOME/jre/bin:$PATH +export PYTEST="pytest -vv -p no:sugar --color=no" cd gdal # Perl unit tests @@ -34,13 +35,20 @@ cd ogr/tmp/cache/ wget http://download.osgeo.org/gdal/data/pgeo/PGeoTest.zip unzip PGeoTest.zip cd ../../.. -# Run ogr_fgdb.py in isolation from the rest + +# install test dependencies +sudo -H pip install -U -r ./requirements.txt + export PYTHONPATH=/usr/lib/python2.7/dist-packages -(cd ogr && python ogr_fgdb.py) -(cd ogr && mkdir disabled && mv ogr_fgdb.* disabled) + +# Run ogr_fgdb.py in isolation from the rest +$PYTEST ogr/ogr_fgdb.py +PYTESTARGS="--ignore ogr/ogr_fgdb.py" + # Run ogr_pgeo.py in isolation from the rest # This crashes on Trusty since travis-ci upgraded their Trusty workers #python ogr_pgeo.py -(cd ogr && mv ogr_pgeo.* disabled) +PYTESTARGS="$PYTESTARGS --ignore ogr/ogr_pgeo.py" + # Run all the Python autotests -GDAL_SKIP="JP2ECW ECW" python run_all.py +GDAL_SKIP="JP2ECW ECW" $PYTEST $PYTESTARGS diff --git a/gdal/ci/travis/ubuntu_1604/before_install.sh b/gdal/ci/travis/ubuntu_1604/before_install.sh index 4be2f75184bc..8673c063c453 100755 --- a/gdal/ci/travis/ubuntu_1604/before_install.sh +++ b/gdal/ci/travis/ubuntu_1604/before_install.sh @@ -55,9 +55,13 @@ tar xzf FileGDB_API_1_5_64gcc51.tar.gz sudo cp FileGDB_API-64gcc51/lib/* "$chroot/usr/lib" sudo chroot "$chroot" ldconfig -sudo chroot "$chroot" apt-get install -y pyflakes3 -chroot "$chroot" sh -c "cd $PWD && pyflakes3 autotest" -chroot "$chroot" sh -c "cd $PWD && pyflakes3 gdal/swig/python/scripts" -chroot "$chroot" sh -c "cd $PWD && pyflakes3 gdal/swig/python/samples" +sudo chroot "$chroot" sh -c "curl -sSL 'https://bootstrap.pypa.io/get-pip.py' | python" +sudo chroot "$chroot" pip install flake8 +# flake8 codes to just emulate pyflakes (http://flake8.pycqa.org/en/latest/user/error-codes.html) +FLAKE8="flake8 --select=F401,F402,F403,F404,F405,F406,F407,F601,F602,F621,F622,F631,F701,F702,F703,F704,F705,F706,F707,F721,F722,F811,F812,F821,F822,F823,F831,F841,F901" + +chroot "$chroot" sh -c "cd $PWD && $FLAKE8 autotest" +chroot "$chroot" sh -c "cd $PWD && $FLAKE8 gdal/swig/python/scripts" +chroot "$chroot" sh -c "cd $PWD && $FLAKE8 gdal/swig/python/samples" sudo chroot "$chroot" apt-get install -y cppcheck bash diff --git a/gdal/ci/travis/ubuntu_1604/script.sh b/gdal/ci/travis/ubuntu_1604/script.sh index 2e34f04cbc17..eea8de532c1d 100755 --- a/gdal/ci/travis/ubuntu_1604/script.sh +++ b/gdal/ci/travis/ubuntu_1604/script.sh @@ -4,17 +4,21 @@ set -e export chroot="$PWD"/xenial export LC_ALL=en_US.utf8 +export PYTEST="pytest -vv -p no:sugar --color=no" chroot "$chroot" sh -c "cd $PWD/autotest/cpp && make quick_test" # Compile and test vsipreload chroot "$chroot" sh -c "cd $PWD/autotest/cpp && make vsipreload.so" + +sudo chroot "$chroot" pip install -U -r "$PWD/autotest/requirements.txt" + # Run all the Python autotests # Run ogr_fgdb test in isolation due to likely conflict with libxml2 -chroot "$chroot" sh -c "cd $PWD/autotest/ogr && python ogr_fgdb.py && cd ../../.." +chroot "$chroot" sh -c "cd $PWD/autotest/ogr && $PYTEST ogr_fgdb.py && cd ../../.." rm autotest/ogr/ogr_fgdb.py # for some reason connection to the DB requires sudo chroot -sudo chroot "$chroot" sh -c "cd $PWD/autotest/ogr && python ogr_mssqlspatial.py && cd ../../.." +sudo chroot "$chroot" sh -c "cd $PWD/autotest/ogr && $PYTEST ogr_mssqlspatial.py && cd ../../.." -chroot "$chroot" sh -c "cd $PWD/autotest && python run_all.py" \ No newline at end of file +chroot "$chroot" sh -c "cd $PWD/autotest && $PYTEST" \ No newline at end of file diff --git a/gdal/ci/travis/ubuntu_1804/script.sh b/gdal/ci/travis/ubuntu_1804/script.sh index aa962a4c283b..54e87fde0af1 100755 --- a/gdal/ci/travis/ubuntu_1804/script.sh +++ b/gdal/ci/travis/ubuntu_1804/script.sh @@ -4,31 +4,37 @@ set -e export chroot="$PWD"/bionic export LC_ALL=en_US.utf8 +export PYTEST="pytest -vv -p no:sugar --color=no" chroot "$chroot" sh -c "cd $PWD/autotest/cpp && make quick_test" # Compile and test vsipreload chroot "$chroot" sh -c "cd $PWD/autotest/cpp && make vsipreload.so" + +# install pip and use it to install test dependencies +sudo chroot "$chroot" sh -c "curl -sSL 'https://bootstrap.pypa.io/get-pip.py' | python" +sudo chroot "$chroot" pip install -U -r "$PWD/autotest/requirements.txt" + # Run all the Python autotests # Run ogr_fgdb test in isolation due to likely conflict with libxml2 -chroot "$chroot" sh -c "cd $PWD/autotest/ogr && python ogr_fgdb.py && cd ../../.." +chroot "$chroot" sh -c "cd $PWD/autotest/ogr && $PYTEST ogr_fgdb.py && cd ../../.." rm autotest/ogr/ogr_fgdb.py # MySQL 8 -chroot "$chroot" sh -c "cd $PWD/autotest/ogr && OGR_MYSQL_CONNECTION_STRING=mysql:test,user=root,password=passwd,port=33060,host=127.0.0.1 python ogr_mysql.py" +chroot "$chroot" sh -c "cd $PWD/autotest/ogr && OGR_MYSQL_CONNECTION_STRING=mysql:test,user=root,password=passwd,port=33060,host=127.0.0.1 $PYTEST ogr_mysql.py" # MariaDB 10.3.9 -chroot "$chroot" sh -c "cd $PWD/autotest/ogr && OGR_MYSQL_CONNECTION_STRING=mysql:test,user=root,password=passwd,port=33061,host=127.0.0.1 python ogr_mysql.py" +chroot "$chroot" sh -c "cd $PWD/autotest/ogr && OGR_MYSQL_CONNECTION_STRING=mysql:test,user=root,password=passwd,port=33061,host=127.0.0.1 $PYTEST ogr_mysql.py" # PostGIS tests -chroot "$chroot" sh -c "cd $PWD/autotest/ogr && OGR_PG_CONNECTION_STRING='host=127.0.0.1 port=25432 dbname=autotest user=docker password=docker' python ogr_pg.py" -chroot "$chroot" sh -c "cd $PWD/autotest/gdrivers && PGHOST=127.0.0.1 PGPORT=25432 PGUSER=docker PGPASSWORD=docker python postgisraster.py" +chroot "$chroot" sh -c "cd $PWD/autotest/ogr && OGR_PG_CONNECTION_STRING='host=127.0.0.1 port=25432 dbname=autotest user=docker password=docker' $PYTEST ogr_pg.py" +chroot "$chroot" sh -c "cd $PWD/autotest/gdrivers && PGHOST=127.0.0.1 PGPORT=25432 PGUSER=docker PGPASSWORD=docker $PYTEST postgisraster.py" # for some reason connection to the DB requires sudo chroot # WARNING: unfortunately this doesn't even work from the ubuntu 18.04 chroot, but it # does from the ubuntu 16.04 one -sudo chroot "$chroot" sh -c "cd $PWD/autotest/ogr && python ogr_mssqlspatial.py && cd ../../.." +sudo chroot "$chroot" sh -c "cd $PWD/autotest/ogr && $PYTEST ogr_mssqlspatial.py && cd ../../.." # Fails with ERROR 1: OGDI DataSource Open Failed: Could not find the dynamic library "vrf" rm autotest/ogr/ogr_ogdi.py -chroot "$chroot" sh -c "cd $PWD/autotest && python run_all.py" \ No newline at end of file +chroot "$chroot" sh -c "cd $PWD/autotest && $PYTEST" \ No newline at end of file diff --git a/gdal/scripts/vagrant/gdal-mingw.sh b/gdal/scripts/vagrant/gdal-mingw.sh index 791bd921b310..0d9c11f1366b 100755 --- a/gdal/scripts/vagrant/gdal-mingw.sh +++ b/gdal/scripts/vagrant/gdal-mingw.sh @@ -37,8 +37,8 @@ ln -sf /usr/x86_64-w64-mingw32/lib/libgeos-3-5-0.dll "$HOME/.wine/drive_c/window ln -sf "$PWD/.libs/libgdal-20.dll" "$HOME/.wine/drive_c/windows" # Python bindings - wget -N -nv -P /var/cache/wget/ http://www.python.org/ftp/python/2.7.3/python-2.7.3.amd64.msi - wine64 msiexec /i /var/cache/wget/python-2.7.3.amd64.msi + sudo wget -N -nv -P /var/cache/wget/ http://www.python.org/ftp/python/2.7.15/python-2.7.15.amd64.msi + wine64 msiexec /i /var/cache/wget/python-2.7.15.amd64.msi cd swig/python gendef "$HOME/.wine/drive_c/Python27/python27.dll" x86_64-w64-mingw32-dlltool --dllname "$HOME/.wine/drive_c/Python27/python27.dll" --input-def python27.def --output-lib "$HOME/.wine/drive_c/Python27/libs/libpython27.a" diff --git a/gdal/scripts/vagrant/gdal.sh b/gdal/scripts/vagrant/gdal.sh index f5f54198bd91..7e508d3269ab 100755 --- a/gdal/scripts/vagrant/gdal.sh +++ b/gdal/scripts/vagrant/gdal.sh @@ -71,3 +71,14 @@ make generate make make vagrant_safe_test cd ../.. + +# Install pytest. +# First install pip 9, which is the last version which can upgrade the system's `six` +# 10+ throws an error :/ +curl -sSL https://bootstrap.pypa.io/get-pip.py -o /tmp/get-pip.py +sudo -H python /tmp/get-pip.py 'pip<10' + +sudo -H pip install -Ur /vagrant/autotest/requirements.txt + +# Add python symbols so gdb is friendlier +sudo apt-get install -y python2.7-dbg diff --git a/gdal/swig/makefile.vc b/gdal/swig/makefile.vc index 4ff4a4a3170d..a989b7892089 100644 --- a/gdal/swig/makefile.vc +++ b/gdal/swig/makefile.vc @@ -88,7 +88,7 @@ java_install: java test: gdalvars cd $(GDAL_HOME)\..\gdalautotest - $(PYDIR)/python.exe run_all.py + $(PYDIR)/python.exe -m pytest -vv clean: -del setup.ini